85
NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING CS3235 - Semester I, 2014-2015 Computer Security The Projects for CS3235 (Computer Security) Singapore, November 2014.

CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

NATIONAL UNIVERSITY OF SINGAPORE

SCHOOL OF COMPUTING

CS3235 - Semester I,2014-2015

Computer Security

The Projects for CS3235(Computer Security)Singapore, November 2014.

Page 2: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

ii

Page 3: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Table of Contents

CryptoKnocker: A New Approach to Port KnockingWithout Shared Secret. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Jun Hao Tan, Anselm N. Foong,Rongshun Tan and Te Ye Yeo (Gp 1)

Protection and authentication for web applications.. . . . . . . . . . . . . . . . . . . . . . . . . .7Cho Zin Tun, Lin Htet Aung and Yap Fook Lim (Gp 2)

Protection and Authentication for Web Applications: . . . . . . . . . . . . . . . . . . . . . . . 13Quah Zheng Hao, Melvin Lee Zhong Wei,Fam Wei Jian and Tan Jun Wen Jeremy (Gp 3)

System Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ang Sing Yee, Keith Lim Yong Ming and Tan Wei Liang Jeremy (Gp 4)

Door Watcher. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Sherlyn Goh Shi Hui, Yohanes Lim,Teo Jun Hao and Chew Tee Ming (Gp 5)

Testing Mobile Applications for Vulnerabilities.. . . . . . . . . . . . . . . . . . . . . . . . . . . . .31Peh Kim Chai Alex, Prakash S/O A Divakaran,Tan JianWei Leslie and Yu Zhangxin (Gp 6)

Insecurities in Modern Web Browsers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Victoria Chew, Jason Poh, Lim Wei Ke andSudarsan Gopalaswami (Gp 7)

Location Restricted Access Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Iain Meeke, Jin Xiaojie and Zhang Mengdi (Gp 8)

Phortress – A PHP Static Code Analyser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Joel Low Wor On, Naomi Leow Wen Xin andTan Wei Lin (Gp 9)

Comparing OS Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53Clement Chong DeZhi, Lui YuYao,Teo ZhengLe and Tan WeiJie (Gp 10)

iii

Page 4: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Table of Contents

A Study into NFC-Enabled Authentication Methods:Using Smartphones to Enter NUS Facilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Saloni Kaur, Wong Ming Kit,Turker Bulut and Lee Chun Tat (Gp 11)

3D Gesture Recognition Using Leap Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Chen Chi, Pan Long,Sun Hang and Zhao Mengdan (Gp 12)

Security system with 3D gesture recognition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Timothy Lim, Xu XiaNan, Foo Yong Jie and Wang Hanpeng (Gp 13)

Password securities in different operating systems. . . . . . . . . . . . . . . . . . . . . . . . . . .77Eugene Ang Hwai Choon, Muhammad Farhan Bin Ismail,Mai Huong Nguyen Thi and Elias Reda Boutaleb (Gp 14)

iv

Page 5: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

CryptoKnocker: A New Approach to Port Knocking Without Shared Secret

Jun Hao Tan National University of Singapore

[email protected]

Anselm N. Foong National University of Singapore

[email protected]

Te Ye Yeo National University of Singapore

[email protected]

Rongshun Tan National University of Singapore

[email protected]

ABSTRACT Port knocking is a mechanism, which allows clients to open ports from outside a firewall. This is done automatically when someone sends the correct sequence of knocks. Common implementations consist of a sequence of timed packet “knocks” which are considered a shared secret. These secrets are susceptible to eavesdropping and replay attacks due to the open nature of a public channel.

In our project, we propose a new approach to port knocking by integrating modern techniques of authentication such as public key cryptography, nonce and one time password into the port knocking infrastructure to mitigate the above mentioned attacks.

Categories and Subject Descriptors C.2.0 [Computer-Communication Networks]: Security and protections

General Terms Security

Keywords Port knocking, public key cryptography, one time password, Challenge-response authentication

1. INTRODUCTION This paper presents CryptoKnocker, a new approach to port knocking without the need for pre shared secrets. CryptoKnocker is a lightweight application that allows any user to easily implement and manage a port knocking daemon into their existing infrastructure.

Section 2 describes port knocking: an authentication mechanism that could dynamically hide services behind a firewall until access is validated and authorized. It also describes the existing approaches to port knocking. Section 3 describes how various features of CryptoKnocker such as the challenge response authentication, one time password and port control mechanism are implemented. It also explains how CryptoKnocker mitigates the common attacks that are plaguing other port knockers. Section 4 presents experimental results of the security and reliability of our proposed system as well as its performance impact. Section 5 describes the target beneficiaries as well as the extensibility of CryptoKnocker. Section 6 describes related work in port knocking. Lastly, section 7 presents our conclusion of the paper.

2. PORT KNOCKING Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection attempt on a

set of pre-specified closed ports. There are many variants of “knocking” style, which we will describe in this section.

2.1 Purpose of Port Knocking The port knocking’s primary goal is to provide an additional layer of protection through security by obscurity of concealing open ports from the public. Networks initially were deliberately designed to interconnect seamlessly and no prior authentication was required before machines are able to communicate. Therefore, port knocking attempts to fill the gap by providing an added layer of security that authenticates users before access is granted to them. Furthermore, port knocking is also able to keep potentially vulnerable services hidden from the public while, simultaneously, making it accessible to authorized users. This greatly lowers the risk of any adversary being able to target services with zero day attacks or known vulnerabilities.

2.2 Various Schemes of Port Knocking Port knocking generally operates on top of the 2 common transport layer protocols, namely, TCP or UDP, depending on the developers’ implementation [1]. The TCP header is of minimum 20 bytes and contains fields such as the sequence number as well as an acknowledgment number of the packets and therefore is able to hold additional information such as the state of the communication, making them suitable for Multiple Packet Authorization (MPA). The UDP header on the other hand, is only 8 bytes long and is significantly stealthier than TCP and hence more suitable for Single Packet Authorization (SPA) or other undetectable authentication schemes so as to prevent unnecessary divulge of information to potential sniffers. The earliest notion of port knocking would most likely have originated from a 2002 Intel Research publication by Barham, Hand, Isaccs, Jardetzky, Mortier & Roscoe [2]. Barham et al. introduced three techniques, Spread-Spectrum TCP, Tailgate TCP and Option-Keyed TCP, to address IP network vulnerabilities against denial-of-service (DOS) attacks by concealing services from non-authorized users. These techniques featured the idea of clients sending TCP SYN packets with SHA-1 hash sequences encrypted with a key that was shared with the servers, in order to authenticate themselves to the servers. On the server-side firewall lies a Silent Authentication Service, which only opens the concealed service port when the correct packet containing the hash is received while any other packets are silently discarded. Numerous studies [3] have been conducted on port knocking, and many were driven to extend the de-facto authentication mechanism of knock sequences in order to mitigate malicious attacks such as replay attacks, connection hijacking and denial-of-

1

Page 6: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

service attacks. The general approaches include, but is not limited to1:

1) Introduction of One-Time Password (OTP) or nonce. 2) Hash-based Message Authentication Code. 3) Single/Multi Packet(s) Authorization.

2.2.1 One time password approach 1. C S: Knock_seq, OTP 2. S: Verification of OTP and allow Client

The addition of OTP was introduced to prevent replay attacks. In 2004 BlackHat USA, David Worth introduced a Cryptographic One Time Knocking tool in which the client knocker would send an OTP knock via a UDP packet [4]. The server would, thereafter, verify the validity of OTP and authorized the access subsequently. The client, however, is unable to determine and verify the authenticity of the server.

2.2.2 Hash-based message authentication code 1. C S: Payload + E(Ks, MAC1(payload)) 2. S : Computes MAC2(payload) with MAC1

The client and the server should have a secret key prior to communication and the knock packets will be hashed with a function such as SHA-1 and subsequently encrypted with the shared key. At the receiving end, the message authentication code (MAC) is recomputed by the server and compared with the received MAC. deGraaf, Aycock & Jacobson [5] addressed the need for stronger authentication by proposing a challenge response scheme incorporating HMAC. When the server receives a request from the client, it will issue a nonce as a challenge. The client then computes the MAC of the nonce together with the IP addresses of itself and the server's. The MAC is encrypted with the symmetric key and sent back to the server for validation. This ensures the integrity of the clients' messages, but relies on the common knowledge of the keys. A compromise of the key meant that an attacker could masquerade as either party; a single point of failure in the communication protocol.

2.2.3 Single / Multi Packet(s) Authorization The traditional concept of port knocking via knock sequences is further reinforced with the idea of Single and Multi Packet(s) Authorization (SPA/MPA). Under the SPA and MPA, the client knocker specially crafts and sends a message with essential authentication information such as the MD5 sum of the current message, to the knock daemon. The daemon would monitor for incoming connections and control access based on the received packet. In the case of MPA, multiple packets are consolidated before the verification [6]. Instead of relying on the limited size of TCP/UDP headers to store the knock sequences, the SPA/MPA is able to enhance the security of the port knock scheme by encapsulating additional information into the payload. The maximum allowable length of the encapsulated information varies by the Maximum Transmission Unit of the communication interface; for example, 1500 bytes for Ethernet frames. [7]. In 2005, the first publicly published SPA port knocker: Fwknop by Michael Rash, provides clients with the option of either AES-128

1 Other schemes that maybe of interest: TCP steganography, Port-

Knock with IPSec, IPv6 Address Knocking [14] [15].

or GnuPG asymmetric encryption up to 2,048-bit public/private key pair [8].

3. CRYPTOKNOCKER CryptoKnocker is a new approach to port knocking. It eliminates the need of a shared secret by introducing public key cryptography (RSA). It also features two factor authentication (2FA) which is based on time-based one-time password algorithm (TOTP) which is a standard supported by many authenticator including the widely used Google Authenticator and also a challenge response authentication which safeguards against attacks resulting from the loss of the private key and replays attack respectively. CryptoKnocker consists of two key components, the client and the server. The client will handle the knocking of ports; the server is responsible for ensuring only authorized users are granted access to the service behind the port.

3.1 Architecture

Figure 1 Possible Network Architecture

CryptoKnocker supports many different network architectures. One example of such architecture is illustrated in figure 1 which segregates the wired and wireless portion of the network. We use the above network architecture setup in our test environment with the wireless network simulating an external network and the wired network simulating the intranet. CryptoKnocker server can be installed on any server that runs on the Linux operating system, example includes the Raspberry Pi, which can act as a firewall for the Server. By default, all ports will be closed with the exception of the knocking port (UDP 8888). Moreover, the knocking port would not respond to any incoming packet unless it is a knock. For the client to access any internal service, the client would have to first perform a knock on the port using the CryptoKnocker Client application. Upon successful authentication, the user would be granted access automatically into the server on the specified port, which is based on the user’s IP address. The user may also opt to close the port via the same application once he has finished his existing session.

2

Page 7: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.2 Protocol Communication between the client and the server are done over UDP. Payloads are encrypted with public key cryptography. The daemon by default, would listen on UDP port 88882 for incoming knocks. Other than the knocking packets, the daemon would not respond to any traffic. This helps to mask over the presence of a listening port on the server.

3.3 Implementation 3.3.1 CryptoKnocker Client The CryptoKnocker client consists of a knocker, which allows user to

1) Generate a pair of 2048-bit RSA key in PEM3 format

2) Add CryptoKnocker public key to the client

3) Port knock CryptoKnocker.

For keys generation, each key pairs are stored locally within the CryptoKnocker client folder. It also stores CryptoKnocker’s public key within one of its sub folders. The keys’ paths are contained in user.ini (user’s public and private key) and server.ini (daemon’s public key) For port knocking, the user is required to input his user ID, the server’s IP address, desired port to be opened and the OTP from two factor-authenticator. The client application then performs the necessary input validation to ensure input is properly formatted. The user can either choose to open (knock) or close (lock) a port.

3.3.2 CryptoKnocker Server The CryptoKnocker server consists of 2 key components, the CryptoKnocker daemon and the web interface. The CryptoKnocker daemon monitors for any encrypted packets from the client and processes the authentication protocol in order to open or close ports. In addition, CryptoKnocker daemon also logs down every authentications. The web interface provides administrators behind the server with a user-friendly platform to manage clients’ CryptoKnocker public keys, port status and also registration and de-registration of new clients. The web interface is created with Django and jQuery to reduce development time, maximize web security and embellish the administration experience. 2 This port number can be easily change to any other UDP port

depending on the requirement of the users 3 PEM is a standard format for OpenSSL and is described in

detailed in RFC 1424 [16]

3.3.3 Challenge response authentication CryptoKnocker implements a challenge response authentication to authenticate users. The authentication process is as follows:

Legend: C: Client, S: CryptoKnocker Server PU: Public key, PK: Private Key N: Nonce Payload1: <UserID, TypeOfRequest, IP, PortToOpen, OTP, NC> H: Hash function, SHA256 Challenge-Response Authentication C S: E(PUS, Payload1) + Sig(PKC, H(Payload1)) S C: E(PUC < NC, NS>) + Sig(PKS, H(< NC, NS>) )) C S: E(PUC, NS) + Sig(PKS, H(NS))

In the initial round of communication, the CryptoKnocker client sends a payload with the user’s information and the request port to be unlocked on the server. In addition, a nonce value derived from current time stamp is concatenated with the aforementioned details, which will be encrypted with the CryptoKnocker Server’s public key. Once the CryptoKnocker Server receives the client’s request, it performs the following verification:

1. Validity of request, request port and OTP 2. Freshness of nonce 3. IP address matches IP header

The CryptoKnocker Server then responds back with the client’s nonce together with the CryptoKnocker Server’s nonce, which is a random 9-bits integer. A time-based nonce is not used on the CryptoKnocker Server’s response, as the nonce is predictable by any adversary including the user. Usage of time-based nonce will thereby allow any adversary to turn stale message into fresh message. Finally, the client responds back with the CryptoKnocker Server ‘s nonce. At this point in time, if the server nonce sent by the client is fresh, the server will open the desired port to the specific IP address of the client. The CryptoKnocker Server is designed to reveal limited information and cease all communication with the client once the payload authorization process fails.

3.3.4 Overcoming Network Address Translation By embedding IP addresses in the payload, network address translation (NAT) poses a problem in CryptoKnocker as NAT devices would modify the source IP address of a packet causing the source IP address to be different from the one that is stored within the payload. In order to address the concern, CryptoKnocker’s client would first determine if the client is located on the same subnet as CryptoKnocker server. It proceeds as normal if they are in the same subnet. In the event that the client behind a NAT device and the server is located in a separate network, CryptoKnocker could determine the public IP address of the client through the ipgetter module.

Figure 2 CryptoKnocker Client

Figure 3 CryptoKnocker's Admin Web

User Interface

3

Page 8: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.3.5 One time password The private key of the user plays a major role in the authentication process. Therefore, it is crucial that the private key be kept secret and away from others. However, there is still a possibility of the private key being stolen and used. Moreover, the victim may not be immediately aware of it. As a countermeasure, one-time password (OTP), in the form of time-based one-time password algorithm (TOTP), is required when performing port knocking. CryptoKnocker uses TOTP provided by Google authenticator. The use of Google authenticator to get the TOTP is mandatory for all users.

3.3.6 Port control mechanism The CryptoKnocker server has integrated with the python-iptables library to coordinate the chains and input rules of the Linux kernel firewall for granting access from a particular source IP to a destination service port. With the use of iptables, CryptoKnocker server is able to provide a more dynamic packet filtering environment for the network administrator. Moreover, specific checks are in-place to ensure identical client’s IP address will not be able to open the same service port twice. Along with the specific checks, when a port close request is made either by the user or network administrator, the iptables will be filtered to ensure no existing or duplicate rules will coincide with the new DENY rule. These mechanisms aimed to counter a potential overflowing of iptables if users try to invoke multiple open or close requests.

3.3.7 Keys re-generation and revocation Key revocation is an important aspect in any situations which includes stolen keys and compromised client machines. CryptoKnocker provides key revocation on the server. Keys can be easily revoked at the CryptoKnocker administration page.

Figure 5 Keys Revocation administrative page

The user can also re-generate his or her keys using the same key generation function found in CryptoKnocker client. By entering the same user name, CryptoKnocker client will replace any existing key pair with a newly generated pair of public and private keys.

3.4 Attacks and Mitigations 3.4.1 Man in the middle (MITM) attacks A successful MITM attack often depends on an attacker’s ability to impersonate the various endpoints in the protocol and pretend to be that particular endpoint towards the other party. CryptoKnocker is not vulnerable to MITM attacks as it uses PKI to perform mutual authentication as part of the knocking protocol.

3.4.2 Replay attacks Replay attacks are usually done by an attacker by capturing an earlier sequence of packets between a legitimate client and the CryptoKnocker server and thereafter replay the sequence of packets at a later time to impersonate as the client that is trying to communicate to the CryptoKnocker. An example of a replay attack would be an attacker capturing a series of knocks from a client, which informs the CryptoKnocker server to open port 23 to his IP address. When the client leaves, the attacker would just need to request for that client’s IP and thereafter, replay the knocks, thus gaining access to that specific port. CryptoKnocker mitigates replay attack by incorporating nonce as part of the communication protocol. A total of two nonces are used throughout the flow of the communication protocol and we define NS as the CryptoKnocker server’s nonce and NC as the client nonce. The client nonce is always the current timestamp and therefore there will never be an opportunity for collision with an earlier used nonce. The CryptoKnocker’s nonce is a 9 bit random integer, which is always used in concurrence with the client nonce and therefore, also has zero chance of a collision with an earlier packet. Currently, we have assigned the freshness of a client nonce to thirty seconds and this value can be easily tweaked to suit the need of the different environment and requirements.

3.4.3 IP Address manipulation and Insider attacks Insider attacks are defined in this paper as an authorized client, allowing an unauthorized client access into the restricted system via modifying the IP address that is residing in the payload. We assume the insider is not an administrator of CryptoKnocker. Otherwise, the administrator could provide the unauthorized user with a key. One important requirement of CryptoKnocker is that it should only open ports to the correct IP addresses. Besides the IP header, CryptoKnocker also embeds the address within the payload. If the port knocker is relying on the IP header, any attacker could intercept the packet, change the IP address and forward it to the daemon. In such a scenario, the attack could be conducted easily and the attacker is not required to have the knowledge of the payload content regardless of whether the payload is encrypted or not. Another method is to encode the IP address of the client in the payload. The port knocker daemon will then utilized the address within the payload for ensuing communication instead of the one residing in the IP header. In such a case, the attacker who is intercepting the communication will not be able to modify this IP address as he or she does not have the encryption keys. However, this mitigation will not work if the client lied about his IP address. In the implementation of CryptoKnocker, we added an extra layer of security by comparing and verifying both the IP address in the header and payload matches before opening the port to the specific IP address. It is noted that this is not an infallible solution

Figure 4 TOTP from Google

Authenticator

Figure 6 Keys pair generation or re-

generation

4

Page 9: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

as the attacker and client may collude and manipulate both the IP address in the header and payload to circumvent the checks. Another viable collusion scenario is when clients transfer all required information (private key, OTP, etc) to the attacker. In such a scenario, CryptoKnocker will also be unable to detect the attacks. Hence, CryptoKnocker security measure will work well only if there is no collusion between the client and the attacker.

3.4.4 Spoofing attack Traditional port sequence knocking is vulnerable to spoofing attacks, in which the attacker masquerades as the daemon. With the client performing only passive authentication, verification of the daemon’s authenticity is not possible. With CryptoKnocker, the attacker could still masquerade as the daemon. However, once the CryptoKnocker client receives the presumably firewall’s response, the application will come to realize the received digital signature of the hashed nonce cannot be decrypted with the firewall’s public key, and thus, connection is dropped. Similarly, consider the scenario in which the attacker disguise as the client. The attacker could send the encrypted payload concatenated with the digital signature which is encrypted with the attacker’s own private key. Upon receiving the request packet, the daemon is not able to successfully decrypt the signature with the client’s public key and halts communication. Thus, the client and the daemon could verify each communicating party’s authenticity through the challenge response authentication.

3.4.5 Leakage of a client’s private key Given that PKI is used for mutual authentication of endpoints, users may be concerned that if an attacker is able to gain a hold of their client private keys, they could trick the daemon into thinking that they are authorized users and thus, will open the ports for them. CryptoKnocker mitigates this issue through the use of 2FA. The 2FA method that we have chosen to include into CryptoKnocker is one-time password (OTP) based on the time-based one-time password algorithm (TOTP), RFC 6238 [9]. TOTP was chosen as it is a standard OTP algorithm that is used by various industrial corporates for instance, Google Authenticator [10], Microsoft’s One account [11] and Amazon’s Web Services [12], and has authenticator standards built for many platforms. Using TOTP, an attacker would not be able to port knock even if he manages to take control of the client’s private key as he would not have the user’s authenticator.

4. EXPERIMENT 4.1 Hardware In our test environment, we have setup CryptoKnocker server on a Raspberry Pi. The setup is similar to figure 1. The Raspberry Pi is installed with “Debian wheezy” which provides it with networking capabilities similar to that of a home networking router. It uses a wireless dongle to connect to external networks i.e Internet. A machine with SSH service is connected to the Raspberry Pi and the port of SSH (22) is port forwarded on it. We have another laptop connecting to the same router as the Raspberry Pi. From there, the CryptoKnocker client on the laptop is ran to port knock CryptoKnocker server on the Raspberry Pi. In our setup, we did not discover any performance related issue.

4.2 Software 4.2.1 Wireshark A packet captured during the challenge response authentication reveals no useful information on the communication. This is so as all the payloads are encrypted with 2048-bit RSA. Figure 7 shows the UDP dump of the challenge response authentication.

Figure 7 Packet capture of the challenge response

authentication

4.2.2 Nmap By applying the concept of security through obscurity, CryptoKnocker hides services from external networks. A normal port scan using Nmap (figure 8) reveals no opened ports, even though there is an SSH service waiting for connection on port 22.

Figure 8 A normal TCP stealth scan on CryptoKnocker

CryptoKnocker server also hides the presence of an open port knocking port, by refusing to respond to any incoming traffic with the exception of port knocks. Nmap (figure 9) UDP scan shows the UDP port 8888 is closed, as CryptoKnocker do not respond to the scan.

Figure 9 UDP scan on port knocking port

5. DISCUSSION 5.1 POTENTIAL AUDIENCES CryptoKnocker provides a sophisticated security approach to port knocking technique, with minimal configuration required. It can be easily installed and deployed with a low cost credit card sized computer such as the Raspberry Pi. Therefore, CryptoKnocker is

5

Page 10: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

advantageous for Small Office, Home Office (SOHO), as financial and human resources to maintain computer servers and networking infrastructure are often limited. Moreover, CryptoKnocker could also be installed onto most recent off-the-shelf commercial wireless routers that support third party firmware such as dd-wrt or tomato and thus would not need any additional hardware from the end users.

5.2 EXTENSIBILITY CryptoKnocker is developed with open source tools and libraries such as Python, Django and iptables. It is available for anyone to download and modify. Hence, anyone with programming knowledge would be able to extend its functionality. OTP functionality can be also extended to other platforms such as hardware token like YubiKey and SMS token.

6. RELATED WORK There is one development pertinent to improving port knocking that is called Fwknop. Fwknop stands for the “Firewall knock operator”, which uses single packet authorization as authorization scheme and provides both symmetric and asymmetric encryption functionalities such as Elgamal, GnuPG (GPG) and Rijndael [13]. Rather than trying to increase the number of functionalities, CryptoKnocker strives to provide sophisticated port knocking technology to anyone with minimal configuration required. CryptoKnocker is not a conclusion of which approach is better, but rather a system with different trade-offs.

7. CONCLUSION In conclusion, CryptoKnocker aims to change the perspective of port knocking usage in a SOHO environment by providing a robust design to endpoint communications. Through the practice of a public key infrastructure together with a challenge and response authentication, replay attacks and man-in-the-middle attacks can be avoided. The extra verification supported by authenticators such as the Google Authenticator further reduces the likelihood of an adversary gaining unauthorized access via a stolen client key. The compact size of CryptoKnocker allows the system to be easily deployed in credit-card size computers. Technology-savvy personals with programming knowledge can effortlessly adapt CryptoKnocker to suit their network environment and security policies. We believe CryptoKnocker’s small footprint coupled with its security objectives would lead to a wider adoption of port knocking technology within the small office environment.

8. ACKNOWLEDGMENTS We would like to thank Associate Professor Hugh Anderson for providing us guidance and equipment needed for the development and testing of CryptoKnocker.

We would also like to thank ACM SIGCHI for allowing us to modify templates they had developed.

REFERENCES

[1] M. Krzywinski, "Port knocking from the inside out," 2005. [Online]. Available: http://www.portknocking.org/docs/portknocking_an_introduction.pdf.

[2] P. Barham, S. Hand, R. Isaacs, P. Jardetzky, R. Mortier and T. Roscoe, "Techniques for Lightweight Concealment and Authentication in IP Networks," July 2002. [Online]. Available: http://www.intel-

research.net/Publications/Berkeley/012720031106_111.pdf.

[3] M. Krzywinski, "Port Knocking - Resources," Jan 2012. [Online]. Available: http://www.portknocking.org/view/resources.

[4] D. Worth, "COK - Cryptographic One-Time Knocking," Black Hat USA, 2004. [Online]. Available: http://www.blackhat.com/presentations/bh-usa-04/bh-us-04-worth-up.pdf.

[5] R. deGraaf, J. Aycock and M. Jacobson, "Improved port knocking with strong authentication," in Computer Security Applications Conference, 21st Annual, 2005.

[6] V. Srivastava, A. Keshri, A. Roy, V. Chaurasiya and R. Gupta, "Advanced port knocking authentication scheme with QRC using AES," in Emerging Trends in Networks and Computer Communications (ETNCC), 2011 International Conference on, 2011.

[7] M. Rash, "Single Packet Authorization with Fwknop," Cipherdyne.org, December 2005. [Online]. Available: http://www.cipherdyne.org/fwknop/docs/SPA.html.

[8] M. Rash, "Single Packet Authorization – A Comprehensive Guide to Strong Service Concealment with fwknop," Cipherdyne.org, August 2014. [Online]. Available: http://www.cipherdyne.org/fwknop/docs/fwknop-tutorial.html.

[9] D. M'Raihi, V. I. S. Machani, D. C. M. Pei, S. J. Rydell and P. I. , "RFC 6238 - TOTP: Time-Based One-Time Password Algorithm," 28 October 2014. [Online]. Available: https://tools.ietf.org/html/rfc6238.

[10] "google-authenticator: Two-step verification," Google, 2013. [Online]. Available: https://code.google.com/p/google-authenticator/.

[11] M. Jeffrey, "Microsoft Account Gets More Secure," Microsoft, 17 Apr 2013. [Online]. Available: http://blogs.microsoft.com/blog/2013/04/17/microsoft-account-gets-more-secure/.

[12] "Multi-Factor Authentication," Amazon Web Services, 2014. [Online]. Available: https://aws.amazon.com/iam/details/mfa/.

[13] M. Rash, "Single Packet Authorization: The fwknop Approach," 10 September 2012. [Online]. Available: http://www.cipherdyne.org/blog/2012/09/single-packet-authorization-the-fwknop-approach.html.

[14] H. Liu, Z. Wang and Y. Liu, "Address Knocking: An Undetectable Authentication Based on IPv6 Address," 2012 13th International Conference.

[15] V. Y. Eugene, H. Nicholas and T. James, "Eugene, Vasserman Y.; Nicholas, Hopper; James, Tyra;," International Journal of Information Security, vol. 8, no. 2, pp. 121-135, 2009.

[16] B. Kaliski, "Privacy Enhancement for Internet Electronic Mail: Part IV: Key Certification and Related Services," RSA Laboratories, Feb 1993. [Online]. Available: https://www.ietf.org/rfc/rfc1424.txt.

6

Page 11: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Protection and authentication for web applications

Cho Zin TunNational University of

Singapore21 Lower Kent Ridge Road

Singapore [email protected]

Lin Htet AungNational University of

Singapore21 Lower Kent Ridge Road

Singapore [email protected]

Yap Fook LimNational University of

Singapore21 Lower Kent Ridge Road

Singapore [email protected]

ABSTRACTThis paper focuses on the various protection techniques thatare available for the web applications. These protectiontechniques will be explored to determine their propertiesin performing mitigation of attacks. The implementation ofthese protection techniques on the web applications will alsobe discussed.

General TermsSecurity

Keywordsprotection, web, application, server, attacks

1. INTRODUCTIONCyber attack is an increasing risk in the computer world.There are attacks being done everyday to different computersystems around the world and many have succeeded. In or-der to mitigate these attacks, various protection techniqueshave been developed and updated from time to time to pre-vent the ever changing attacks. In the midst of computersystems, the web servers play an important part as sourcesof information. Hence, the protection of the web serversagainst cyber attacks is significant.

2. PROTECTION TECHNIQUESThere exists various protection techniques that are imple-mented on web applications in order to defend against possi-ble attacks. These protection techniques are not all roundedon their own and may only defend against some attacks.Hence, the properties of these protection techniques are in-vestigated to determine the strengths and weaknesses to-wards possible attacks on the web applications.

2.1 Input/Output SanitizationSanitization is the act of removing untrusted malicious codesfrom the original one Improper coding of the application,i.e.,

lack of data sanitization could result in vulnerability. All thecode injection techniques such as SQL injection and Cross-site scripting (XSS) can be succeeded in the absence of In-put/Output Sanitization and they are on the top of the tablein cyber-attack field[1]. Thus, it is necessary to sanitize thedata coming from the user before using it.

2.1.1 Attacks

2.1.1.1 Cross-site scripting.Cross-Site scripting (XSS) is a type of injection attack wheremalicious scripts are injected into the trusted web page;whichare then executed on the client-side rather than on the server-side. Attackers make use of the weakness of the client-sidescripting languages such as HTML and Javascript to ex-ploit the XSS vulnerabilities. The dynamically generatedweb pages display back the user inputs without proper val-idation is the potential threat of XSS. It allows attackers toembed the malicious script in the page and run the script onthe user’s machine whoever views that site. XSS attack oc-curs mostly on the web applications in which user inputs areaccepted, and the typed inputs are echoed back to present tothe user.[2]An attacker could control the victim’s browsersor account on the vulnerable Web application upon a suc-cessful XSS attack.

XSS is often divided into three types: persistent (or Stored)XSS, non-persistent (or reflected) XSS and DOM-based XSS.

Immplementation of data sanitization for XSSEncoding the output If the user input data is returned asa URLparameter of a link query string, then it is necessaryto URL-encode the data. < ahref = http : //site.com?id =USER DATA HERE MUST BE URL ENCODED >

Filtering input parameters for special characters Itis the simplest way of XSS protection. All the externalinput data are passed through a filter to remove all thespecial characters which enable JavaScript commands, the<SCRIPT> tag, CSS styles and other HTML markups,those containing event handlers, to be generated within theHTML stream. Special characters consist of: < > “ % ; ) (& + -It is recommended to use libraries in which all the possi-ble attacks have been considered and tested by the commu-nity at larger rather than writing own library. For example,HTML purifier is one of the libraries for filtering. If the fil-tering rule is strict, not only the dangerous keywords, but

7

Page 12: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

also the actual page’s code will be filtered. As an instance,on a page that writes out <TABLE> elements, the filter theremoves the special characters would discard the < and >characters, which breaks the <TABLE> tag.

Validation Validation could help to solve the problem men-tion above. Validation is a type of user input filtering inwhich malicious codes are removed while keeping other nec-essary codes. In web development, validation allows someHTML elements such as <em> while removing other ma-licious codes such as <script>. Validation can be achievedusing either whitelist or blacklist. Blacklist perform vali-dation by forbidding some recognized malicious codes thatshould not appear in the user input, whereas whitelist doesby allowing only a definite pattern which is safe in its knowl-edge.

Escaping Escaping tells the browser to treat the data asa data but not as a code. So, even though the attackermanages to put a script on the page, it will not affect thevictim since it will not run the script if it is properly escaped.However, not everything can simply be escaped, otherwiseown scripts and HTML markup will not work leaving thepage useless.There are several places on the web that areneeded to use escaping. HTML is escaping when is requiredwhen untrusted data is inserted in between HTML openingand closing tags such as <BODY>, <TABLE>, etc.<DIV> IF THIS DATA IS UNTRUSTED IT MUST BEHTML ESCAPED </DIV>Similarly, Javascript escaping is desired when untrusted datais embedded inside one of the scripts, or in a place whereJavaScript can be presented. This includes attributes suchas STYLE and all event handlers like ONLOAD.<BODY ONLOAD=“IF THIS DATA IS UNTRUSTED ITMUST BE JAVASCRIPT ESCAPED”>CSS escaping is needed, in the same way, when there areuntrusted data in CSS styles. Those styles can be used torun a script into the page.<DIV STYLE= “background-image: IF THIS DATA ISUNTRUSTED IT MUST BE CSS ESCAPED”> [3]There are popular escaping libraries like the ESAPI providedby OWASP and AntiXSS provided for Microsoft.

2.1.1.2 SQL injection.Web application usually allows its legitimate users to sub-mit and fetch the data to/from a database over the internet.SQL injection is one of the code injection technique in whichmalicious SQL commands are passed through the web appli-cation for execution at the backend database. If an attackercan execute any SQL query through the web application,he can attain all the data stored in the database such aspersonal information and secrets. Moreover, he can ruinthe web application by dropping (deleting) tables from thedatabase. He gain full access to the database. Simple Exam-ple of SQL injection: If username = “admin ”and password= “psw123 ”, then the SQL command will beSELECT * FROM users WHERE username = ‘admin ’ANDpassword = ‘psw123 ’If the malicious user types in “admin ’OR 1=1––”for user-name and types in “xxx ”for password, then the SQL com-mand will beSELECT * FROM users WHERE name = ‘admin ’OR 1=1

––AND password = ‘xxx ’The second SQL command will be always true due to (1=1)and –will help the attacker to bypass the login credentialsby commenting out the password checking part. Then, hecan access to the database illegally[4].

Implementation for SQL injectionTaking care of critical characters mysql real escape string()will escape the special characters in a string for use in anSQL statement. It will prepend backslashes to the followingcharacters: \×00,\n, \r, \, ‘,“and \× 1a. [5]. As a con-sequence, admin’OR 1 = 1 will be turned into admin\‘OR\‘1\’= \‘1

FilteringThere are sanitizing filters to ensure that input is eithera number, a float, an email address or a URL. Filter varis a PHP function to take care of it. filter var($var, FIL-TER SANITIZE NUMBER FLOAT, FILTER FLAG ALLOWFRACTION);

The above function will remove all characters except digits,+- and optionally .,eE.[6]

TypingChecking data type is one of the necessary things for inputsanitization.Settype($var, ‘integer ’);

2.1.1.3 Server Side Includes Injection.Server Side Includes(SSI) is a server side scripting languagethat allows dynamic content generation on a web page. Ifthere exists SSI statements, they are executed by the webserver before supplying a webpage to the users. SSI state-ments can be executing a program or a shell command atthe server, or displaying a text file to the web page. SSIinjection is the threat of inserting an SSI command fromthe user input to exploit the web server. Such injected SSIcommand can perform maliciously such as running a badprogram on the server or displaying confidential informationin a retrieved web page. When this injected SSI command isaccepted by the web server to execute, they will be executedat the permission level of the web server user.

2.2 Public Key Infrastructure (PKI)Public key infrastructure is a systematic way of authenticat-ing end users and servers that they are actually who theyclaimed to be. This authentication is done by the help of athird party which is called the Certificate Authority (CA)[9].In a normal asymmetric cryptography, two endpoints usetheir own respective key pairs for encryption and authenti-cation. The key pairs are the private key and public key. Auser ‘s public key is shared with another designated user forencrypted communication. When a message is encryptedwith a user‘s public key, it has to be decrypted using thesame user ‘s private key and vice versa. This is to ensurethat only the user with his own private key can decrypt theencrypted message. However, a problem arises on the au-thentication of the user ‘s public key. When a public keyis received, one cannot confirm that the public key is reallybelonged to the user it claimed. This is because the originalpublic key sent may be changed to an attacker ‘s public key,

8

Page 13: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

causing authentication to be incorrect. The receiving enddoes not have any knowledge in this as there is no mecha-nism for checking. PKI comes into the picture in situationswhere authentication cannot be done successfully. PKI actsas a third party for the communication between two end-points. PKI performs authentication for the communicationby verifying to a user that a public key received is indeed au-thentic. PKI is managed by the Certificate Authority (CA)and Registration Authority (RA). A user who wishes to havehis public key signed by the CA must first verify with theRA its identity and its public key. When verification is done,the CA will sign a hash of the user ‘s public key with theCA ‘s private key. This signed hash is concatenated withthe user ‘s public key to be used as a public key certificate.This public key certificate will be shared to the designateduser. The designated user will decrypt the signed hash byusing the CA ‘s public key which is available in the machine.The decrypted hash will be compared with a hash of the re-ceived public key and will be verified to be authentic if theymatch. The CA takes the role for verifying the authenticityof public keys for all users. PKI is able to mitigate severalattacks such as the man-in-the-middle attack and spoofing.

2.2.1 Attacks

2.2.1.1 Man-in-the-middle attack (MiTM).Man in the middle attack is to intercept a connection be-tween two endpoints and to listen or forge the packets inthe connection. This attack can be done in various ways aslong as the connection between the two endpoints can be in-tercepted. When the connection is intercepted, the attackeracts as a proxy between the two endpoints, spoofing and re-laying packets in the middle[11]. An interception is initiatedby impersonating the web server and receive request packetsfrom a client. The packets received is relayed to the originalweb server through another connection, by impersonating asa client. The attacker acting as a proxy in the middle of theconnection can now read or even modify the packets sentbetween the client and the web server. There exists toolsthat can be used to initiate the man in the middle attacksuch as the mitmproxy tool. This attack can be mitigatedby the PKI since the web server or the users can verify theauthentication of the received packets with the help of theCA. An attacker is not able to change the public keys beingshared as the users will only use public keys that are signedby the CA. A public key that is not digitally signed by theCA is deemed untrustable.Implementation The PKI is implemented in the currentcomputer networks by several certificate authorities thatprovide services to the users. They services the users byproviding identity verification of the other end of the com-munication. Some examples of certificate authorities areVeriSign, GlobalSign and more.

These CA have their own RA to verify with users who intendto sign their public keys. They also have directories to storethe signed certificates together with the public keys of therespective users. They are trustworthy authorities who aretrusted by their users for verification and authentication ofpublic keys.

2.3 Hashing and Salting

Most web applications consist of a login system which re-quires a user to provide a username and the correspondingpassword to access the web application. The password en-tered is compared with the password stored in the databasefor authentication. However, storing plain text passwordsis a dangerous act especially when the database is beingattacked. The passwords will be known easily without anyprotection. A way to protect the passwords is through hash-ing and salting. Hashing is a one way function that convertsa plain text into a fixed length string[12]. The plain text can-not be recovered from the fixed length string as it is a oneway function. This prevents an attacker who successfullyacquired the password hashes to obtain the plain text pass-words. However, there are other attacks developed to cracka password hash, such as the rainbow tables which precom-pute a list of possible password hashes. To further enhancethe password protection, salting comes into place. A salt isa random code generated for each user account in the sys-tem. This salt is concatenated with the password hash to gothrough another hash function to obtain a salted passwordhash. As each user account has a different salt value, usersusing the same password will result in different salted pass-word hashes[13]. This makes rainbow table attacks difficultas salted password hashes cannot be computed beforehandwithout the salt value.

2.3.1 Attacks

2.3.1.1 Hash collision attack.A hash can be cracked to obtain its plain text through hashcollision. It is done using precomputed hash tables such asthe lookup tables and rainbow tables. Possible plain textswill be hashed and stored into a table. Hashes in these tableswill be used to compare with the password hashes acquiredthrough other means from the database. If matching hashesare found, the plain text that corresponds to the hash isthe password. However, if a salt value is added into thepassword hash stored in the database, these precomputedhash tables will become useless as they do not have the saltvalue while when compiling possible hashes.ImplementationHashing can be done using many different hashing functions.Some of the notable hashing functions are MD5 and SHA.These hashing functions generate a fixed length output torepresent each of the plain text being hashed.

The salt values that are required to be random can be gen-erated using the Cryptographically Secure Pseudo-RandomNumber Generator (CSPRNG). CSPRNG is available invarious platforms including PHP, which uses functions likemcrypt create iv.

2.4 Transport Layer Security (TLS)Transport Layer Security, a successor to the Secure SocketsLayer (SSL), is a security protocol used to ensure secrecy andauthentication of a communication between two endpoints.It is used commonly with HTTP for communication betweenweb servers and clients. TLS provides a structure for clientand server to safely authenticate each other and exchangedata using encryption. Before the data exchange can begin,the client and server will talk to each other to decide on theconfigurations and encryption algorithm to be used. After

9

Page 14: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

that, the server sends its public key certificate which is dig-itally signed by a trusted CA, to the client. Through PKI,the client can verify with the trusted CA that the digitallysigned public key is indeed from the server. This public keywill be used to encrypt a pre-master secret key to be sentto the server so that both server and client can compute thesame session key. From there onwards, this session key willbe used for encryption of the data exchange based on theencryption algorithm agreed earlier. If client authenticationfor server is required, it can be initiated in TLS too and thesame authentication process will be performed in the oppo-site direction. The exchange of configuration informationearlier in the process uses asymmetric cryptography whilethe real data transfer uses symmetric cryptography[14, 15].This protocol is compatible to be used with any encryptionalgorithm as long as the server and the client agree on thesame encryption algorithm. The data exchange is secret andis authenticated. This is able to prevent information disclo-sure, man in the middle attack, replay attack and more.

2.4.1 Attacks

2.4.1.1 Replay attack.When a packet is successfully captured from a communica-tion link between the client and the server, an attacker maychoose to resend this packet to either the client or the server.This action, named as replay attack, is done by repeatingthe same packet or the same packet with modified contentto the same endpoint, in order to retrieve some informationwhich may be confidential. However, this can be mitigatedby the TLS protocol as different session keys are used fordifferent sessions to encrypt the data. If a captured packetis to be replayed, it will be on a different session which has adifferent session key, thus the mismatch of session keys willprevent the processing of the replayed packet.ImplementationIn order to have a secured communication link between aweb server and clients, TLS protocol can be implemented.The implementation of this protocol on a web server is donethrough a series of actions. First, a TSL server certificaterequest needs to be created so that a certificate request canbe sent to a trusted CA. The CA will generate a TSL servercertificate based on the request received. This process issimilar to the process in PKI. With the TSL server certifi-cate generated by the CA, this certificate is installed on theweb server so that every time a client initiates a connectionto the web server, this certificate will be sent to the client forauthentication purpose. As long as the clients that connectto the web server trust the CA that we used to generate theweb server certificate, the TLS secured communication canbe established between the web server and the client.

2.5 Brute Force AttackBrute force attack is to try out all possible keys in orderto decrypt a ciphertext or access a secured point. For webapplication in particular, this attack can be targeted at thelogin system of the web application. Brute force attack canbe done using various tools that is able to try out everypossible keys at a considerable speed. It is the simplest formof encryption cracking as it is taking all the possible keys intoaccount. However, this method of attack may take a verylong among of time depending on the protection techniquesused by the target.

2.6 Secure Session ManagementAs HTTP is a stateless protocol, the web sessions are imple-mented to record and manage the useraAZs interactions andstatus are managed in a session. Sessions are also responsi-ble for managing the authentication and access control forthe user. Thus management of sessions are essential part ofa secure web application.

2.6.1 Attack

2.6.1.1 Session Hijacking.For a web application, whether the incoming traffic from auser is identified by its Session Key which is paired with asession on server thus authenticating the user’s account andstatus.In a Session Hijacking attack, the attacker uses var-ious means such as XSS, MiTM or Trojans to obtain theSession Key from the legitimate user. After gaining the Ses-sion Key, the attacker can now masquerade as the user andaccess user data from the application, bypassing the authen-tication processes.ImplementationMost of the web frameworks provide Session Models. Thereare numerous steps that can be used to prevent attacks onthe session. The data traffic between the user and the servershould be encrypted, especially when carrying the SessionKey. The Session Key should be a long random number orstring to reduce the risk of brute force attacks on it. Chang-ing the Session ID after the user logs in successfully willprevent Session Fixation attack in which the attacker pro-vides a link which uses a fixated Session ID. Additionally,checking the other properties of the user (e.g. IP address)along with the Session Key will provide an extra layer ofsecurity.

2.7 Logging & MonitoringLogging and monitoring the server system is vital in protect-ing and keeping a web application secure. Constant moni-toring of log records can give the developers and administra-tors about the normal operating behaviour to be comparedagainst hostile actions. This can help defend against at-tacks while the attacker is identifying vulnerabilities of thesystem. The log records can also provide information aboutexceptions and misuses which can be used to improve the se-curity and robustness of the application. When push comesto shove, these records can help detect security breaches andthe extend of the damage in case other protection techniquesfails. The types of malicious activities that can be counteredby logging and monitoring the system are explained in thefollowing session.

2.7.1 Attack

2.7.1.1 Denial of Service (DoS).A Denials of Service (DoS) attacks is an attempt by an at-tacker using a single machine or connection to disrupt thenormal service of a web application server by flooding it withlarge amount of useless traffic thus depleting the serveraAZsbandwidth and resources. For a Distributed Denial of Ser-vice (DDoS) Attack, there are multiple sources of attacks,usually from a large number of compromised devices, whichis known as a botnet.

10

Page 15: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

DDoS attacks can be typically put under three categories[18].• Volume Based Attacks(e.g. UDP floods, ICMP floods, other spoofed-packet floods)• Protocol Attacks(e.g. SYN floods, fragmented packet attacks, Ping of Death,Smurf DDoS)• Application Layer Attacks(e.g. Slowloris, Zero-day DDoS attacks, DDoS attacks thattarget Apache, Windows or OpenBSD vulnerabilities)

The DDoS attacks are very difficult to prevent and for tar-geted attacks, impossible. Rapid identification and responseis essential in countering DoS attacks. The first step is to ef-ficiently detect malicious incoming traffic before disruptionsoccur. Once the attack is detected, there are a number ofways to mitigate the impact. The first is to use routers andswitches with DoS prevention functionalities. Another wayis to simply put in a temporary firewall rule to drop all in-coming traffic from the detected attack sources. Another isto set up a scalable infrastructure to absorb the attack. Ifthe attack is targeted to consume server processing power,the impact can be minimized by deploying proof-of-work(PoW) system which uses client puzzles to make processingtime between server and client machine asymmetrical. Lim-iting number of attempts or increasing timeout time alongwith the number of attempts also helps.

2.7.1.2 Brute Force Attacks.If someone is deploying a brute force attack on part of theapplication, the attempt will be reflected in the request logsand it can be set up to automatically notify the administra-tor.

2.7.1.3 Security Breach Detection against UnknownAttacks.If attacker has successfully exploited the system using un-known attacks, the breach can be detected by checking thevarious resourcesaAZ access time, frequency and type. Thelogs are also valuable in determining the damage done bychecking the trail of the attack.

2.7.2 ImplementationIn implementing the logging and monitoring system of theapplication, it is important to record 4Ws (When, Where,Who, What) of the events. According to OWASP[17], es-sential events to log includes•web requests•failures in input/output validations•authentications•unsuccessful authorizations attempts•failures in session managements•server system and software errors•restricted file/data access attempts•usage of high privilege functionality•status updates of logging processesIt is also beneficial to use standard formats for the log records.Examples of the standard format include Common Log FileSystem (CLFS), Common Event Format (CEF), and Com-mon Event Expression (CEE). They can easily be integratedwith centralised logging services and automated monitoring

services. There are many useful tools for monitoring such aswireshark (for monitoring network traffic), Xymon (to mon-itor CPU utilization, memory consumption, RAID status,etc), and Splunk (to monitor, gather and analyze data fromdifferent sources on your network).

2.8 Educate UserPrevention on some types of attacks could be further im-proved by user’s awareness. If users have the knowledgeabout specific attack, he could be able to avoid from it. Asan instance, phishing and pretexting can be avoided if theuser knows the nature of those attacks.

2.8.1 Attack

2.8.1.1 Phishing.Phishing is an act of attempting to acquire othersaAZ per-sonal information such as usernames, passwords and bankdetails by pretending as a trustworthy entity. Phishers makeuse of electronic communications, appear to be coming frompopular social web sites, online payment processor, banks orauction sites, to trick unsuspecting public to share their pri-vate information. Phishing is normally carried out by emailspoofing or instant messaging, and it often direct users toenter details at a fake website which looks exactly like a gen-uine one.Implementation If the user has already known the natureof phishing email such as generic greeting, forged link, re-questing personal information and sense of urgency[7], thedanger coming from the phishing could be reduced.

2.9 Software PatchingThe regular update of the software is essential in order tokeep the system safe from the up-to-date attacks. For in-stance, new fixed OpenSSL was released about heartbleedbug[8].

2.9.1 AttacksSoftware Vulnerability attack

2.10 Least PrivilegeIf the attacker succeeds with one of the attacks, he will causea significant damage to the database or system if he has rootaccess. However, his attack would be limited and leading toless damage if non-privileged access is set as default. There-fore, it is necessary to set the default to least privilege thatis, giving minimum access in order to protect the systemas much as possible even though an attack happens to besuccessful.

3. CONCLUSIONSThe protection techniques discussed in this paper have dif-ferent ways of mitigating or preventing attacks on web ap-plications. Hence, it is preferable for web applications toimplement several protection techniques instead of only onetechnique so that the protection coverage is wider. An im-portant process that should always be done for the web ap-plications is to ensure that these protection techniques andprotocols are up-to-date so that newer attacks can also beprevented.

11

Page 16: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

4. REFERENCES[1] OWASP. Top 10 Attacks in 2013. 2013. Internet:

https://www.owasp.org/index.php/Top 10 2013-Top 10

[2] SPI Dynamics. Cross-Site Scripting. 2005. Internet:http://www.rmccurdy.com/scripts/docs/spidynamics/SPIcross-sitescripting.pdf

[3] Acunetix. Preventing XSS Attacks. 2011. Internet:http://www.acunetix.com/blog/articles/preventing-xss-attacks/

[4] Netsparker Limited. What you need to know aboutSQL Injection Web Application Vulnerability. 2014.Internet: https://www.netsparker.com/web-vulnerability-scanner/vulnerability-security-checks-index/sql-injection/

[5] PHP. MySQL Functions. 2009. Internet:http://php.net/manual/en/function.mysql-real-escape-string.php

[6] PHP. Sanitize Filters. 2010. Internet:http://php.net/manual/en/filter.filters.sanitize.php

[7] GlobalSign. The Detection and Prevention of PhishingAttacks. 2012. Internet:https://www.globalsign.eu/resources/white-paper-phishing-attacks.pdf

[8] Codenomicon. The HeartBleed Bug. 2014. Internet:http://heartbleed.com

[9] Windows. Public Key Infrastructure. 2014. Internet:http://msdn.microsoft.com/en-us/library/windows/desktop/bb427432(v=vs.85).aspx

[10] TechTarget. PKI(public key infrastructure). 2006.Internet:http://searchsecurity.techtarget.com/definition/PKI

[11] OWASP. Man-in-the-middle Attack. 2014. Internet:https://www.owasp.org/index.php/Man-in-the-middle attack

[12] CrackStation. Salted Password Hashing. 2014.Internet:https://crackstation.net/hashing-security.htm

[13] ASPHeute. Storing Passwords. 2004. Internet:http://www.aspheute.com/english/20040105.asp

[14] OWASP. Transport Layer Security. 2014. Internet:https://www.owasp.org/index.php/Transport LayerProtection Cheat Sheet

[15] Microsoft. What is TLS/SSL?. 2003. Internet:http://technet.microsoft.com/en-us/library/cc784450(v=ws.10).aspx

[16] OWASP. Session Management. 2014. Internet:https://www.owasp.org/index.php/Session ManagementCheat Sheet

[17] OWASP. Logging. 2014. Internet:https://www.owasp.org/index.php/Logging Cheat Sheet

[18] Incapsula. Denial of Service Attacks. 2014. Internet:http://www.incapsula.com/ddos/ddos-attacks/denial-of-service.html

12

Page 17: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

1

Protection and Authentication for Web Applications Quah Zheng Hao

National University of Singapore School of Computing

13 Computing Drive, Singapore 117417

+65 6516 2727

[email protected]

Fam Wei Jian National University of Singapore

School of Computing 13 Computing Drive, Singapore

117417 +65 6516 2727

[email protected]

Melvin Lee Zhong Wei National University of Singapore

School of Computing 13 Computing Drive, Singapore

117417 +65 6516 2727

[email protected]

Tan Jun Wen Jeremy National University of Singapore

School of Computing 13 Computing Drive, Singapore

117417 +65 6516 2727

[email protected]

ABSTRACT With the exponentially rising number of people becoming connected to the Internet and sharing their personal information online, it is quintessential to protect web applications from malicious attackers who seek to do harm to the application and the information contained within, as the obtaining or alteration of such information can result in substantial harm to the host of the application and the users alike, as well as third parties. In this paper, we explore the strengths and weaknesses of techniques used for protecting web-based applications.

General Term Security, Design, Performance

Keywords Malware, virus, injection, vulnerabilities, attacks, authentication, cross-site scripting, cross-site forgery, configuration, data exposure, access control, validity.

1. Introduction Facebook, a web application for social networking, had around 197 million users in Q1 2009. By Q1 2014, it has reached 1.276 billion users, over 6 times its original number. With nearly 3 billion Internet users worldwide, and the number steadily rising across the years, it is important to explore and find ways to protect web applications, and by extension the people using these applications as well as their important online information from malicious attackers that seek to do harm.

2. Motivation With the advancement of technology, techniques for attacking have also become more complex and efficient. Furthermore, more people are becoming connected to the Internet. In June 2014, a cyber-attack on JP Morgan has affected over 76 million users, compromising much of their personal details, placing many businesses and people at risk. Therefore, there is a need for an analysis of techniques used for protecting web-based applications

to determine which technique is the best, or at least suited for a particular defence strategy.

3. Definitions 3.1 Web Application A web application is define as any software that runs in a web browser environment and is written in a browser-supported programming language (i.e. JavaScript, HTML and CSS) and requires a web browser to render the application.

3.2 Web Server A web server is referred to a hardware (computer) or software (computer application) that delivers web content over the internet. Web applications are hosted on the web server hardware while the web server program responds to request from clients’ web browser by sending the required data back.

4. Background Web application involves both the server and the client, which is presented on the browser of the user. The client, which allows users to interact, makes a round trip to the server to update the page. The Web Application concept was introduced in 1999, using JavaScript and XML. As the client is linked with the web server, it allows hackers to perform malicious attacks onto the servers itself. The level of security in Web Application becomes a major concern, especially Web Application for business use, such as FormMobi. Thus, building a secure web application became a key area that is to be included in the development process.

5. Protective Techniques 5.1 Web Application Firewalls (WAFs) A filter that applies a set of rules to an HTTP conversation. The filter will protect attacks against cross site scripting and SQL injection. By customizing the rules to your application, many attacks can be identified and blocked. However the effort to perform this customization can be significant and needs to be maintained as the application is modified.

13

Page 18: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

2

Figure 1. How WAF works

5.1.1. Strengths of WAF WAF does not depend on the web application itself. Therefore it will not share the same vulnerability, if exist, as the web application. WAF offers basic protection against known attacks or vulnerabilities based on blacklists. WAF is able to whitelist the vulnerability so that it cannot be exploited before the application comes up with a patch which would usually take some time and would be left open to attacks. 5.1.2. Drawbacks of WAF Performance, performance is affected since WAF inspects all incoming and outgoing traffic at the application layer. When the firewall reads and interprets each packet, it will consume CPU cycles. Thus the inspection process takes longer than those traditional packet filtering firewalls and may slow down network performance Another disadvantage of application firewall is that each protocol, such as HTTP, SMTP, etc., requires its own proxy application, and support for new network application and protocols can be limited and slow to emerge.

5.2. Intrusion Detection System (IDS) Intrusion Detection System (IDS) is an application that monitors the network for malicious activities and logs them. Some IDS can also attempt to stop attacks and intrusions, although it is not required of them as they are monitoring systems. There are two kinds of IDS, Network IDS (NIDS) and Host IDS (HIDS). NIDS analyses multiple hosts by scanning the network traffic, while HIDS monitors one host by checking system logs and files. Once the IDS detects the attack, it would alert the system administrator, who can then choose to deflect the attack to a honeypot or honeynet, uncover the origin of the attack and the identity of the attacker to take legal action, or perform other kinds of countermeasures.

Figure 2. A map of how NIDS is used in a network 5.2.1. Strengths of NIDS NIDS can detect and prevent an attack before it even reaches the systems on the internal network. Additionally, NIDS does this in real time, so attacks can be stopped while they are still executing. Since NIDS can protect multiple hosts in a network, regardless of whatever operating system the devices are running on (as long as they are on the same network), this reduces the cost financially and also in terms of maintenance. NIDS protects the network holistically, and thus is capable of identifying attack patterns on a larger network level as opposed to an individual host level. 5.2.2. Drawbacks of NIDS NIDS may detect more false positives due to various user or system bugs and errors that are non-malicious. NIDS cannot detect attack signatures that are sent to the network or host via fragmented packets. Since NIDS relies heavily on pattern-matching to detect attacks, it is possible to evade detection if the attacker changes the data used in the attack even by a small amount. It is also hard for IDS to detect the origin of attacks done via proxies or spoofing. IDS is also unable to monitor encrypted traffic, and can only detect attacks within the network that the IDS is attached to. Most importantly, the computer would be vulnerable if removed from the network, and such a situation is especially common in businesses as employees may have to travel a lot, and thus would not be in the same protected network.

Figure 3. A map of how HIDS is used in a network 5.2.3. Strengths of HIDS HIDS detects less false positives as it runs on the host and can thus analyse log files in context with overall system activity as compared to NIDS. HIDS is also more specific to its operating

14

Page 19: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3

system, and can thus be more specialized in terms of intrusion detection compared to NIDS, which does a more generalized, cross-platform detection. Also, unlike NIDS, it is capable of examining more traffic because the operating system can decrypt the network traffic. Lastly, HIDS can detect attacks outside of the network, specifically suspicious activities or attacks on the physical machine. 5.2.4. Drawbacks of HIDS HIDS uses the local system’s resources, which means that it could impact the system if the system has to perform more resource-demanding services. Also, unlike NIDS, HIDS is more costly in terms of monetary and maintenance, as one HIDS is installed on one host only instead of multiple hosts, which the NIDS does. Thirdly, the log files generated by the HIDS are stored locally on the host system, meaning that they can be easily manipulated. Lastly, unlike the NIDS, the HIDS does not see the bigger picture (the network traffic and hosts that exist in the same network).

5.3. Open-Source Security Testing Methodology Manual (OSSTM) OSSTM is a peer-reviewed manual of security testing and analysis which result in verified facts. OSSTM has created cases that tests five sections:

1. Information and data controls 2. Personnel security awareness levels 3. Fraud and social engineering levels 4. Computer and telecommunications networks, wireless

devices, and mobile devices 5. Physical security access controls, security process, and

physical locations The OSSTM measures the technical details of each of these areas and provides guidance before, during, or after a security assessment. 5.3.1. Strengths of OSSTM Information in OSSTM is all verified and can be specific to one’s needs. Testers would not have to rely on general best practices or mere anecdotal evidence, which is unreliable and untested. It contains formal methodology through thorough analysis. OSSTM is also continuously in development and improving with the times, as testers would add to it with new tested information to assist their peers. OSSTM is also freely available to all users. 5.3.2. Drawbacks of OSSTM OSSTM focuses heavily on operational security, and as such may be lacking in other fields of security. Furthermore, OSSTM compliant tests are not just merely running automated scanners and receiving a report of it. OSSTM relies a lot on the tester’s own knowledge and experience, as results from OSSTM compliant tests need to be interpreted by the tester manually.

5.4. Penetration Testing Execution Standard (PTES) PTES is a new standard which aims at providing a common language for all penetration testers and security assessment professionals to follow. PTES provides clients with a baseline of their own security aspect and using the findings of the entire penetration testing in a manner that makes sense to the clients and provides the most value to it. PTES consists of seven main sections:

1. Pre-engagement Interactions

2. Intelligence Gathering 3. Threat Modelling 4. Vulnerability Analysis 5. Post Exploitation 6. Reporting

PTES technical guidelines help to define certain procedures to follow during a penetration test. 5.4.1. Strengths of PTES PTES provides businesses and service providers with a standard to follow, such that they can at least achieve a reasonable level of security by following the baseline minimum required for a basic pentest, and testers that wish to reach higher security levels can also do so by following it and fitting the standards to their own industries. 5.4.2. Drawbacks of PTES PTES is not as comprehensive in terms of formal technical methodologies (compared to OSSTM), and it merely contains technical guidelines for a tester to follow instead of having detailed steps. Furthermore, the standard is still new, meaning that much of it is still in development and is not as detailed as other existing testing standards. At the time of this paper, PTES is only at version 1.0 of its development, with only the “core elements of the standard are solidified”.

6. Vulnerabilities 6.1. Carriage Return and Line Feed (CRLF) injection CRLF injection is a web attack that exploits an Internet application to enable the attacker to perform other attacks, such as cross-site scripting as listed below. CRLF represents the end of line (EOL) marker for many Internet protocols; therefore it allows a malicious attacker to control web application functions if he can inject his own CRLF sequence into a HTTP stream. 6.1.1. Ways to protect from CRLF injection

1. Sanitize URL (can be very time-consuming). This is the only effective countermeasure against CRLF injection currently.

6.2. Cross-site Scripting (XSS) Cross-Site Scripting attacks are categories under the injection attacks where malicious scripts are injected into trusted web sites. XSS attacks occur when an malicious attacker input, generally in the form of a browser side script, is accepted by the application as part of a request and then is used in the output of the response without proper output encoding in place for validation and sanitization. Malicious attackers can inject malicious script such as JavaScript or VBScript, which is rendering in the victim’s browser. Since the script is part of the response from the application, the victim’s browser trusts it and therefore allows the script to run. XSS allows attackers to execute scripts in the victim’s browser, which can therefore hijack user sessions, act as a keylogger, or redirect the user to malicious site.

15

Page 20: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

4

Figure 4: Typical XSS Attack The two primary types of XSS are Reflected (or Non-persistent) XSS and Stored (or Persistent) XSS. Reflected XSS, on the other hand, is injected script that is off the web server, for example in an error message, search result, or any responses that includes input sent to the server as part of the request. Whenever user clicks on a malicious link or even just browsing a malicious site which contains the malicious script, the victim’s browser will executes the script because it came from a “trusted” server. Reflected XSS is generally a 1:1 hacker to victim ratio because the hacker may send out a malicious URL to a large group of potential victims, but only the one who clicks the link are going to be affected and there is no connection between the compromised users. Stored XSS generally occurs when user input is stored onto the target server (database) in message forum or common field of an application. In this case, the victim then retrieves the malicious script from the server when it requests for the stored information. This is a 1: many hacker to victim ratio, which is more devastating than Reflected XSS. 6.2.1. Ways to protect from XSS:

1. Code auditing. Deny untrusted data into HTML documents in web applications, and execute HTML escape before insertion of untrusted data into HTML element content and common attributes. The same idea goes for JavaScript data, style sheets, and URLs.

2. Ensure that all variable output in the webpage is encoded before returning to the end user. The browser will displays the entities, which are the substitutes HTML mark-up with alternate representations, and does not run them. For example, <script> will be encoded to &lt;script&gt; where character “<” and “>” are encoded to “lt;” and “gt;” respectively. Therefore, when the web browser encounters the entities, they will be converted back to HTML but does not run them.

6.3. Directory Traversal Directory traversal attack allows an attacker to access files in unintended directories that are not supposed to be exposed to the web server or client, giving the attacker freedom to view files or run command. This can compromise the entire system, causing severe harm to the application. For example, an attacker could enter this in an unprotected application called www.example.com:

http://www.example.com\..\..\..\..\windows\cmd.exe (Backs up to the root directory and runs the command prompt) http://www.example.com/../../../../etc/passwd (Accesses password file in UNIX) http://www.example.com/folder/ (lists contents of web server directories - not always a flaw, sometimes intended) 6.3.1. Ways to protect from Directory Traversal Attacks:

1. Ensure that the web server is updated and patched frequently to the latest version.

2. Filter user input to enforce proper inputs only. 6.4. Failure to Restrict URL Access Anyone can send an internet application a request, and applications do not always protect their pages properly. Failure to restrict URL access means that attackers will be able to enter a privileged page which they do not normally or should have access to, such as an administrator page. This can cause harm not just to a single account, but possibly all accounts in the system. An attacker can drop the entire database’s information or retrieve all the sensitive data. 6.4.1. Ways to protect from Unrestricted URL Access:

1. Verify every single page in the application. 2. Ensure that access to pages is role-based. 3. Pages should deny all access by default and only then

allow access to specific roles/users. 4. Ensure conditions in the page are in the correct state to

allow/prevent access 6.5 Insecure Cryptographic Storage Insecure cryptographic storage occurs when important data is not stored properly with sufficient encryption. For example, the hash used to protect passwords is unsalted or too weak (or not encrypted at all), allowing attackers to pre-compute the hash and finding the password via a hash table lookup. It is usually fairly difficult to exploit this vulnerability as it would be hard for an attacker to detect this to use to their advantage. However, if the attacker can gain access to the database and obtain the weakly hashed information, the attacker can then find out what the information is in plaintext and thus cause harm. 6.5.1. Ways to protect from Insecure Cryptographic Storage:

1. Don’t use your own encryption/hashing algorithm. Use the standard well-established cryptographic algorithms.

2. Test the application before releasing it, and patch any vulnerability detected. The most common of which is SQL injections.

3. Avoid storing sensitive data on the server unless absolutely necessary.

4. Avoid transmitting keys over insecure channels 6.6. Buffer Overflow Attack Buffer overflow attacks overflow a buffer with excessive data. An

16

Page 21: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

5

attacker uses this attack to corrupt the execution stack of a web application. The attacker sends a malicious input to a web application forcing the web application to execute arbitrary code that allows the attacker to run remote shell. Upon executing the remote shell, the attacker gains the same system privileges that are granted to the application which allows the attacker to take over the system. Web servers or web applications that manage the static and dynamic aspects of a site, or use graphic libraries to generate images, are vulnerable to buffer overflow attacks. Buffer overflow attacks cause system crashes, might place a system in an infinite loop, or execute code on the system to bypass a security service.

6.6.1. Ways to protect from Buffer overflow attack:

1. Programming languages that manages their own memory will need to review all code that accepts input from users via HTTP request and ensure that it provides appropriate size checking on all such inputs.

2. Array bound checking prevents buffer overflow attacks. If arrays cannot be overflowed, array overflows cannot be used to corrupt adjacent memory. Implementing this requires all read and writes to array be checked to ensure that they are within range.

6.7. SQL Injection

According to OWASP, a SQL injection attacks are categories under injection attacks where attacks consists of inserting or injecting malicious SQL query into entry field from client to the application for execution. Malicious attackers can then read sensitive data, modify the data from the database (Create/Read/Update/Delete), as well as execute administration operations on the database.

One possible way to test for SQL injection is to input a ‘ into the entry field and then compare response of the application to a well formed request. If the web application is vulnerable to SQL injection, a ‘ may return different results when the SQL statement attempts to execute. It may be necessary to use other tests for injection such as “ or ; or ) or ‘+”=’ or %27%20 or %201 = 1 depending on the responses returned from the application. Furthermore, encoding the characters to bypass the filters may be necessary too. If the web application has signs of SQL injection vulnerabilities, then malicious and well-crafted SQL statements may perform devastating executions to the database of the web application. 6.7.1. Ways to protect from SQL injection attacks:

1. Prepared Statements (Parameterized Queries) Parameterized queries enforce the developer to first define all the SQL code, follows by passing in each parameter to the query at a later stage. This coding style allows the database to distinguish between code and data, regardless of the input supplied by the user. For example, if the attacker were to enter the userID of tom’ or ‘1’=‘1, the parameterized query would not be vulnerable because it would look for a username which literally matched the entire string tom’ or ‘1’=‘1. Therefore, prepared statements ensure that a malicious attacker is not able to change the content of the query.

2. Stored Procedures

Stored procedures have the similar effect as the prepared statements where both of them require the developer to define the SQL first, and then pass in the parameters after. The difference between stored procedures and prepared statements is that the SQL code for a stored procedure is defined and stored in the database itself which is then called from the application.

3. Escaping All User Supplied Input

This technique works by escaping user input before inserting into a query. Each DBMS supports one or more character escaping schemes specific to certain kinds of queries. If all the input supplied by the user has been properly escape according the scheme for the database used, then the DBMS will be able to distinguish the input will SQL code written by the developer, thus preventing any possible SQL injection vulnerabilities. However, this methodology is frail compared to using prepared statements and stored procedures.

6.8. Denial of Service (DoS) attack DoS is a common attack used by malicious attackers to prevent access of regular, authorized users (or guests) of the system by a variety of techniques, such as overwhelming the network traffic with requests and consuming all of the resources. This causes an interruption or suspension of the services provided by the system or application.

17

Page 22: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

6

6.8.1. Ways to protect from DoS attacks:

1. There are a myriad of methods that one can use to protect against DoS attacks, such as identifying malicious or unauthenticated traffic and blocking those, blackholing traffic, and sinkholing traffic.

7. CONCLUSION Most of the web application flaws and vulnerabilities discussed above have been categorized as OWASP Top 10. By adopting some of the preventive measures as discussed above, these flaws and vulnerabilities can be minimize to a great extent through secure coding and offensive penetration testing. However, every preventive techniques and measures are accompanied with pros and cons, therefore it is a good practice to analyze the requirement of the web application and tackle the security issues with the correct approach.

8. CITATIONS [1] Number of monthly active Facebook users worldwide from 3rd quarter 2008 to 3rd quarter 2014 (in millions). (n.d.). Retrieved September 20, 2014, from http://www.statista.com/statistics/264810/number-of-monthly-active-facebook-users-worldwide/ [2] Internet Users in the World. (n.d.). Retrieved September 20, 2014, from http://www.internetlivestats.com/internet-users/#trend [3] SILVER-GREENBER, J., GOLDSTEIN, M., & PERLROTH, N. (2014, October 2). JPMorgan Chase Hacking Affects 76 Million Households. Retrieved October 18, 2014, from http://dealbook.nytimes.com/2014/10/02/jpmorgan-discovers-further-cyber-security-issues/?_r=0 [4] Chaffee, A. (2014, May 4). What is a web application (or "webapp")? Retrieved September 20, 2014, from http://www.jguru.com/faq/view.jsp?EID=129328 [5] What is web server - a computer of a program? (n.d.). Retrieved September 22, 2014, from http://www.webdevelopersnotes.com/basics/what_is_web_server.php [6] Glynn, F. (n.d.). Web Application Vulnerabilities. Retrieved September 22, 2014, from http://www.veracode.com/security/web-application-vulnerabilities

[7] Hardin, B. (n.d.). Insecure Cryptographic Storage. Retrieved September 23, 2014, from http://bretthard.in/2009/09/insecure-cryptographic-storage/ [8] Shankdhar, P. (2013, September 16). Protect Data by Preventing Insecure Cryptographic Storage. Retrieved September 23, 2014, from http://resources.infosecinstitute.com/protect-data-by-preventing-insecure-cryptographic-storage/ [9] Top 10 2010-A8-Failure to Restrict URL Access. (n.d.). Retrieved September 26, 2014, from https://www.owasp.org/index.php/Top_10_2010-A8-Failure_to_Restrict_URL_Access [10] Directory Traversal Attacks. (n.d.). Retrieved September 26, 2014, from https://www.acunetix.com/websitesecurity/directory-traversal/ [11] Herzog, P. (n.d.). Open Source Security Testing Methodology Manual (OSSTMM). Retrieved October 4, 2014, from http://www.isecom.org/research/osstmm.html [12] PTES Technical Guidelines. (n.d.). Retrieved October 4, 2014, from http://www.pentest-standard.org/index.php/PTES_Technical_Guidelines [13] Buffer overflow attacks. (n.d.). Retrieved October 10, 2014, from http://www-01.ibm.com/support/knowledgecenter/SSB2MG_4.6.1/com.ibm.ips.doc/concepts/wap_buffer_overflow.htm [14] Dermann, M., Dziadzka, M., Hemkemeier, B., Hoffmann, A., Meisel, A., Rohr, M., & Schreiber, T. (2008, September 1). Best Practices: Use of Web Application Firewalls. Retrieved October 20, 2014, from https://www.owasp.org/index.php/Category:OWASP_Best_Practices:_Use_of_Web_Application_Firewalls [15] What is a WAF. (n.d.). Retrieved October 16, 2014, from http://projects.webappsec.org/w/page/62312086/WAFEC_2_Definition [16] Protection Against Hacking - Technique/Tools. (n.d.). Retrieved October 20, 2014, from http://www.istf.jucc.edu.hk/newsletter/IT_11/IT-11_Hacking.pdf [17] Intrusion Detection Systems. (n.d.). Retrieved October 23, 2014, from http://www.techotopia.com/index.php/Intrusion_Detection_Systems [18] CRLF Injection attacks and HTTP Response Splitting. (n.d.). Retrieved October 26, 2014, from http://www.acunetix.com/websitesecurity/crlf-injection/ [19] SQL Injection Prevention Cheat Sheet. (n.d.). Retrieved October 28, 2014, from https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet [20] Ladkani, U. (2013, July 30). Prevent cross-site scripting attacks by encoding HTML responses. Retrieved November 1, 2014, fromhttp://www.ibm.com/developerworks/library/se-prevent/ [21] Top 10 2013-Top 10. (n.d.). Retrieved November 3, 2014, from https://www.owasp.org/index.php/Top_10_2013-Top_10

18

Page 23: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

[CS3235] PROJECT 13 SYSTEM SECURITY Ang Sing Yee

National University of Singapore 21 Lower Kent Ridge Rd

Singapore 119077 + (65) 6516 6666

[email protected]

Keith Lim Yong Ming National University of Singapore

21 Lower Kent Ridge Rd Singapore 119077 + (65) 6516 6666

[email protected]

Tan Wei Liang Jeremy National University of Singapore

21 Lower Kent Ridge Rd Singapore 119077 + (65) 6516 6666

[email protected]

ABSTRACT This paper describes the CS3235 project done by our group (4) for project code 13 – SYSTEM SECUIRTY. In this paper, we will present a simplified alternative secure channel for authorized personnel (students) to get access into restricted zones of the building.

Categories and Subject Descriptors D.4.6 [Security and Protection]: Access Control, Authentication, Verification

General Terms Security, Verification

Keywords Security, Near Field Communication, Mobile Phone Application, Java, Android, PowerShell, Card Reader, Nonce, Secure Channel, Hash, MD5, Secure Channel Process, Server, User

1. INTRODUCTION This project is done with the goal of providing an alternative route for students to gain access into restricted zones of the building if at any point in time, they do not have their primary means of access into the building (Matriculation card). This alternative route will be implemented with the help of Near Field Communication devices (Card and Card Reader), Mobile Phone Application as well as the Mobile Phone itself, which will act as a host for the Mobile Phone Application and as a Near Field Communication writer. The alternative route will be designed with these security elements:

a) a one-time value (commonly known as nonce)

b) encryption hash

c) user defined PIN

d) 2 factor-authentication

2. MOTIVATION There are two motivations that fuels the creation of this project. The two motivations are convenience and security respectively.

Convenience:

We realized that it is highly inconvenient for students if they are ever faced with a situation whereby they cannot get access into the restricted parts of the school building (such as computing labs in the School of Computing of NUS) when they did not bring their matriculation card along with them. Hence, we decided to create

an alternative secure channel whereby the student can use an application on their phone to achieve the same effect as a matriculation card. This will allow the student to get access into the building as long as they have their phone along with them.

Security:

If the student were to ever lose his/her matriculation card, anyone who have access to the lost/stolen matriculation card would be able to impersonate as the student and gain access into the building in which him/her does not have permission to. Hence, our project seek to address this issue by introducing a user defined PIN which in theory, only known to the student him/herself. Hence, even if the student loses his/her phone, the impersonator will not be able to gain access into the restricted zone as they do not have the user defined PIN of the student. The security aspect of the project will be illustrated and explained in future detail in the coming sections.

3. PROJECT IDEA 3.1 Project Elements The key elements in our project are The Server, The Mobile Phone Application, The User, The Near Field Communication (NFC) card and The NFC Reader.

3.2 Project Simplification Due to time, hard-ware and access constrains, our project will stimulate certain parts of the secure channel using other tools or hardware and present to a simplification of the actual channel if it is to be implemented fully. The simplification is as follows:

a) The Server will be enacted by a computer

b) The opening of the building entry will be represented by a pop-up message.

3.3 Secure Channel Process - Preprocessing We assume that the following preprocessing process had been done before we launched into the Secure Channel Process (SCP).

a) The User had downloaded the application onto his/her mobile phone

b) The User had set his PIN (a personalized password which is of minimum length 4) after logging into the application using his/her NUSNET ID for the first time.

c) The Server stored the User’s matriculation card number and the hash of the User’s PIN in its lookup table, with the matriculation card number as the key and the hash as the value.

19

Page 24: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.4 Secure Channel Process The SCP will start once The User login to the application using his/her NUSNET ID. The User will then press the authenticate button on the application. This activity will notify The Application to generate a nonce. It will then proceed to send the nonce along with the matriculation ID of the student to The Server via an email. From then on, there will be two concurrent processing running, each from The Server and The Application.

3.4.1 The Server The Server will check for any incoming email from the application every 10 seconds (which can be modified to shorter or longer time intervals). Once The Server receive a legitimate email, it will proceed to do the following:

a) Extract the nonce and matriculation number from the email.

b) Obtain the hash of The User’s PIN from its look-up table.

c) Hash the nonce and the hash of the PIN to form a message digest m, whereby m=hash(nonce+hash(PIN))

Figure 1 capture The Server General Process Flow as describe above.

Figure 1. The Server General Process Flow

3.4.2 The Application The application will proceed to do the following:

a) Display a form to obtain the PIN of The User b) Hash the PIN entered by The User to generate

hash(PIN) c) Hash the nonce along with the hash(PIN) to generate m’

whereby m’=hash(nonce,hash(PIN)) Figure 2 capture The Application General Process Flow as describe above.

Figure 2. The Application - General Process Flow The Application will indicate to The User once m’ is generated. The User will proceed to use his/her phone and write onto the blank NFC card which is attached to the NFC reader of the door of the restricted zone. The User then use the written NFC card to tap onto the NFC reader. This process will allow the NFC reader to read m’ and sent m’ to The Server. The Server will compare m’ with m and verify whether m’=m. If m’=m, The Server will proceed to unlock the door and allow The User to gain access into the restricted zone. Otherwise, The Server will refuse m’ and await a new email from The Application. The process then resumes. Figure 3 capture the SCP General Process Flow as described above.

Figure 3. SCP - General Process Flow

3.5 Security Aspect The SCP is similar to the 2-factor authentication system frequently used to secure The User’s data. As the only message that is sent “through-the-air” is the email which consists of only the nonce and The User’ matriculation number, we can be safe from any potential Man-In-The-Middle (MIM) attack. Assume the

20

Page 25: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

MIM intercept the packet which consist of the nonce and the matriculation number of The User. The MIM will be able to extract the nonce and the matriculation number. However, without the PIN which is known only to The User and The Server, the MIM will not be able to generate m’ which will allow him to impose as The User.

If we further assume that the MIM decide to attempt a brute force attack, since the PIN is of minimum length 4, there will be 10^4 possible numbers which can be generated (assuming that The User only chooses numerical digits) and this implies that he will have to try out 10^4 different hash of hash(nonce+hash(PIN)) before he can obtain m’.

However, the brute force attack will be relatively useless due to the following 4 factors:

a) The nonce is randomly generated every time and hence even if The MIM manage to generate m’ a new nonce will cause m’ to be un-usable anymore.

b) We can make the process of brute-force attack arbitrary hard by increasing the length of the PIN

c) The time required to test out 10^4 different hash in a short period between the time taken for The User to walk to the door(provided that The User is not already at the door) and use The Application to write to the NFC Card.

d) Since the PIN is hashed, even if the MIM managed to obtain m’, he would not be able to reverse-engineer and obtain the PIN of the user as a hashed PIN using MD5 would have 128 bits. That would amount to 2^128 possible choices of hash(PIN).

Hence, we can see that the SCP is safe from most MIM attack that will potentially occur if The MIM intercepts the packet containing the nonce and the matriculation number.

3.6 Known Limitations There are two known limitations of SCP and they are categorized under Security Limitations and Scalability Limitations.

3.6.1 Security Limitations 3.6.1.1 Interception Despite the fact that SCP is relatively secure from brute force attack, like most service orientated software and websites, it is still vulnerable to potential interception attacks conducted by the attacker. Figure 4 below illustrate how SCP could be subjected to interception attacks. If the attacker was to intercept the packet that is sent from The Application to The Server, it means that from the point of The Server, it did not receive any email from The Application. Hence, even if The User were to write a legitimate m’ to the NFC card and attempt to use it to gain access into the restricted zone, he/she would be denied entry by The Server. This is due to the fact that m’ is unrecognized by The Server and The Server did not pre-compute any m which can be matched with

m’.

Figure 4. Interception by MIM

3.6.1.2 Denial of Service (DOS) Similarly, SCP is also vulnerable to any potential DOS attacks. The attacker could send multiple emails to The Server and this might result in a temporary shutdown of The Server to legitimate users as The Server is over flooded with emails sent by the attacker.

3.6.2 Scalability Limitation Currently, SCP is implemented such that it models a queue. Assuming that there are 2 users who are using The Application at the same time and UserA sends an email to The Server earlier than UserB. However, UserB reaches the door earlier than UserA. The Server will deny entry to UserB as it is expecting m’ from UserA instead of UserB.

3.7 Known Issues A known issue for the SCP is such that if Powershell is accessing the e-mail client and the card is being scanned at the same time, the Powershell script will be unable to access the email. This issue arises due to a race condition as described below. A Powershell script is constantly running on the foreground and accessing the email client for the latest nonce at the same time. If the user was to scan his card into the NFC scanner, this will cause a separate Powershell script to be executed, which accesses the e-mail client as well. Hence, if the user was to scan his card when the foreground PowerShell script is accessing the e-mail client, an error would occur as both PowerShell scripts are attempting to access the same e-mail client at the same time. This would result in that situation in which the script that attempts to access the mail client first will get to be executed whereas the second one won't. Therefore, we can encounter 2 possible situations: 1. The nonce fails to update 2. The user cannot gain access to the door. In both situations, the issue can be resolved if the user waits for a few seconds before scanning again.

3.8 Future Extensions In the future, extensions will be built upon on the SCP such that it will address the scalability limitation mentioned in 3.6.2

21

Page 26: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

We also aim to remove the need of the NFC card such that The User would be able to gain access to the building simply by tapping the mobile phone (with the application launched) at the NFC Reader. To do that, we will have to make use of the Host Card Emulation (HCE) technology which will allow The Application to transform the mobile phone to a state such that it will emulate the matriculation card of the student. This idea is not implemented during the course of the project as HCE is still a relatively new technology (at the point when this paper is written) such that more time is needed in order for our group to explore this technology.

4. ACKNOWLEDGMENTS Our thanks to ACM SIGCHI for allowing us to modify templates they had developed.

5. REFERENCES [1] Script to read email:

http://gallery.technet.microsoft.com/scriptcenter/af63364d-8b04-473f-9a98-b5ab37e6b024 http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/26/use-powershell-to-data-mine-your-outlook-inbox.aspx

[2] Delete email: http://blogs.technet.com/b/heyscriptingguy/archive/2006/07/25/how-can-i-delete-all-the-email-sent-from-a-specific-person.aspx http://social.technet.microsoft.com/Forums/scriptcenter/en-US/b40dc2a5-c686-4490-948c-569263daec51/powershell-and-outlook-2007-trying-to-delete-messages-in-a-folder-older-than-date?forum=ITCG

[3] Time: http://stackoverflow.com/questions/8747303/converting-time-121-419419-to-readable-minutes-seconds http://ss64.com/ps/syntax-compare.html http://mrpowershell.blogspot.sg/2013/10/how-to-cal-powershell-script-with-c.html http://technet.microsoft.com/en-us/library/ee156791.aspx

[4] Hashing:

http://blogs.msdn.com/b/luc/archive/2011/01/21/powershell-getting-the-hash-value-for-a-string.aspx http://technet.microsoft.com/en-us/library/ee692806.aspx http://stevehardie.com/2012/09/powershell-delete-file-if-exists/ https://gallery.technet.microsoft.com/scriptcenter/Get-Hashes-of-Files-1d85de46

[5] Sending Email in Background:

http://www.kpbird.com/2011/08/send-email-without-user-interaction-in.html

[6] Write to NFC: https://code.google.com/p/phoo-android/wiki/HelloNFC

22

Page 27: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

DoorWatcher Sherlyn Goh Shi Hui

A0100848J

Teo Jun Hao A0097889W

Yohanes Lim A0099768Y

Chew Tee Ming

A0097964H

ABSTRACT In this paper, we will look at the various door access systems that are currently used and analyse their pros and cons. In addition, we will also do a feasibility study on the use of hand phone as an authentication tool for the door access system. An overview of our proposed system as well as the implementation details will also be included. Lastly, we will do a comparison between our proposed systems to the existing systems.

1. INTRODUCTION Door access systems can be seen in many places such as homes, workplaces, schools and even government sectors. They exist to restrict access from unauthorized personnel. In terms of security, door access system acts as a form of mechanism for strengthening confidentiality and protecting unauthorized access to information and hardware behind the door. Current existing door access system utilises smart card, password or biometric data as their authentication tool. Using the information retrieved from the authentication tools, the door access system will verify the user’s identity and his level of access. Different places implement different types of door access system depending on the level of restriction. Each system has their pros and cons which includes user convenience and accuracy in user identification. In this study on door access system, research on current system will be performed and a prototype web based system will be proposed to address on the cons on the existing systems.

2. EXISTING SYSTEMS Current existing door access system revolved around the implementation of Smart Card, Password and Biometric data. Such systems are replacing the traditional key and lock method. These systems can be easily seen in schools, enterprise companies and government sectors. Other notable implementations on the rise include phone application and web based authentication.

2.1 Card Authentication For card authentication door access system[1], user information is configured and stored into a digital card. The user then uses the card to authenticate himself to gain access to the restricted area. This mode of access utilizes the definition of “What User Have”. The benefit of such system is that it is very convenient for the user to authenticate himself. The user only requires flashing the card to the door authentication machine and he will be allowed access. On the other hand, this type of system relies on the smart card as the sole identifier of the user. If an unauthorized user manages to possess this smart card, he will be allowed to access the restricted

zone. As such, this will create a burden for the user as when the card is lost, anybody holding on to the card will be allowed access. User mobility is also dependent on the smart card interfaces and machine. Different places may require different access card. If the user is allowed to different restricted areas using different card authentication door access system, he needs to hold on to multiple numbers of cards. As mentioned earlier, smart card is the sole identifier for the user; the user must always keep track of all of them to ensure no security is compromised. Furthermore, there had been much demonstration on breaching of smart card when a weak encryption is implemented[2]. Such weak encryption includes the use of large 1024 bits prime numbers that only have a small number bits set to 1. This allows the smart card to perform fast computation but opened up to PK Space attacks. Smart cards are also vulnerable towards attacks such as Timing and Glitch.

2.2 Password Authentication For password authentication door access system[3], the user is allowed access to the restricted area after he enters the correct password to the door authentication machine. The pro of this system is the user is not required to possess any authentication item. This mode of access utilizes the definition of “What User Know”. However, the con of this system is the user has to remember the password. Stronger password will more likely be harder to remember. Password strength is normally proportional to the combination of the following factors[4]. Length: Length of password is the easiest mode in strengthening a password. A longer length meant that more guesses of password are needed when performing brute force attack. A minimum length recommended will be 8 characters. These characters are recommended to include a mixture of lowercase and uppercase alphabetic characters, numbers and symbols. Such mixture will determine the character set which is the second factor of password strength. Character Set: A bigger character set implies a bigger number of possible combinations of characters. This results in a larger password space. This increases the difficulty of brute force attack as the search space is now larger.

23

Page 28: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Randomness: For a password to be easily remembered, it is a common practise for human to use dictionary words or information related to himself as a password. In reality, weak password can be seen in various applications and Google had even revealed the top ten common types of passwords[5] in 2013. These passwords include:

1. Pet names 2. A notable date, such as a wedding anniversary 3. A family member’s birthday 4. Your child’s name 5. Another family member’s name 6. Your birthplace 7. A favourite holiday 8. Something related to your favourite sports team 9. The name of a significant other 10. The word “Password”

Such passwords are not random and provide the attacker a platform to guess on the password. If the password used can be found in dictionary, attacker could perform a dictionary attack instead. However, it is also not recommended to use passwords that are difficult to remember. Such password may in fact reduce the security as the user might physically stores the password elsewhere or the rate of the password being reused is high. As such, although password randomness helps in strengthening, it is most recommended to use mnemonic password whereby it is complex but yet easy to remember. To add on, there are other means for password retrieval such as installing cameras to visually capture user password. Social engineering is also common where attackers tries to seek out user related information as user tends to use easily remembered information such as birth date[6] as password.

2.3 Biometric Authentication For biometric authentication door access system, the user provides unique biometric data such as fingerprint to gain access to the restricted area. This mode of access utilizes the definition of “What User Are”. The pro of this system is its convenience. The user does not need to hold on to any authentication item as the biometric data can be easily retrieved from his body. However, the con is the result of verification is never definite. Authentication may fail because of some minor injuries that cause the biometric data provided to be different. In addition, reliability of this method is also a well known problem. Similarity of physical features and inaccuracy of measurement may result in high false acceptance rate. Thus, unauthorized personnel that happen to have a similar biometric data with one of the authorized personnel may be accidentally allowed access to the restricted zone.

3. OVERVIEW OF PROPOSED SYSTEM Our proposed system, DoorWatcher, will make use of the portability of hand phone to ease process of authentication without compromising the security of the system. The prototype of our proposed system consists of a mobile-optimized web application used for user authentication, a Raspberry Pi operated door lock and a centralized server which synchronizes access data with the door locks. The system is implemented based on the

distributed system to eliminate single point of failure. The overall architecture of the system can be seen in Figure 1 of Appendix A.

3.1 How DoorWatcher Works 3.1.1 Registration

Figure 2: Registration Page

Before the user is able to use the door access system, an administrator will first have to register an account for him in the registration page shown in Figure 2. The username and password is then sent to the user.

3.1.2 Use DoorWatcher 1. User connects the mobile phone to the access point of

the Raspberry Pi operated door lock that he/she wants to unlock.

Figure 3: Login Page

2. Once connected to the access point, user opens the

browser application on the phone and immediately be redirected to the DoorWatcher login page shown in Figure 3.

24

Page 29: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3. User enters the username and password to login. 4. Once the username and password matches with the

database, user will be prompted to enter a One-Time Password (OTP).

Figure 4: OTP sent through SMS

5. During this time, an OTP is generated at the backend

component of DoorWatcher and is sent to user’s mobile number as associated with the DoorWatcher account via SMS. The received SMS is shown in Figure 4.

Figure 5: OTP Input Page

6. User receives the OTP through SMS and enters the

same OTP into the DoorWatcher page shown in Figure 5.

7. Once the OTP is verified to be correct, the door will be immediately unlocked for access.

3.2 Security Features 3.2.1 Filtered Inputs CodeIgniter framework[7] comes with default Cross Site Scripting filters that we are able to use to filter all user inputs to prevent malicious data from passing into our application. In addition, the framework escapes all data before inserting into the database to prevent SQL Injection. On top of the security functions provided by CodeIgniter, we also validate user input to ensure that they conform to their type before processing it. 3.2.2 Secure Sockets Layer (SSL) It is important that sensitive information is not sent by plain text, as such, we implemented SSL for our web pages. SSL is a cryptographic protocol designed to ensure secured communication over the Internet. With this implementation, the user will be able to send data from their computer to our server confidentially, without having the need to fear that a person in the middle would

be able to intercept the data that is being transmitted. SSL is implemented with the use of OpenSSL. As previously known, some version of OpenSSL are subjected to Heart-Bleed-vulnerability and thus, various checks have been done to ensure TLS heartbeat is not enabled in our SSL. In Appendix B, we have included 2 Wireshark captures. As seen in Figure 6, the login username and password are captured in clear text. This capture is performed when login process is completed using HTTP protocol. Such behaviour creates a great security threat if our application is implemented using HTTP protocol. A sniffing attack can easily retrieve the username and password, rendering our first level of authentication to be useless. To counter sniffing attack, communication must be secured. As such, HTTPS protocol is implemented with SSL. In Figure 7, we can see that the username and password of the user are encrypted. In our prototype, certificate is self generated. In further development, it may be possible to purchase certificates from Digicert, or set up a personal CA server, properly secured to use in our LAN environment. 3.2.3 Multi-factor Authentication Our prototype uses a two-factor authentication which is similar to e-Banking. The aim of two-factor authentication is to increase the difficulty of providing false credentials. The two-factor authentication consists of both Password and OTP Authentication: 1. Password Authentication

This form of authentication uses the advantage of Password Authentication Door Access System. User performs a first level of authentication by logging in with his username and password. This certified the identity of user with the help of “What User Know”. However, having this first level of authentication may not be sufficient as password can be compromised as mentioned previously under Section 2.2.

2. OTP Authentication To enhance the level of security, we utilized an OTP authentication. This OTP code satisfies the definition of “What User Have”. The OTP code will only be sent via SMS service to user when password authentication is successful. This code is only applicable during the process of login and will expire when timeout or upon successful login. As such, it can be use as a token to authenticate user. Furthermore, if the first level of authentication is being compromised by an unauthorized user, this OTP will be send to the real user which acts as an alert of the intrusion.

3.2.4 OTP Generation Generation of OTP is performed with HMAC hash of timestamp and a secret seed. The OTP generated is implemented using Time-based One-time Password (TOTP) algorithm specified in RFC 6238[8]. Generation of OTP is the most important component in our prototype. A poor generator will display a pattern in OTP generation. Such pattern can be exploited and used by unauthorized user. If an unauthorized user manages to clear the first level of authentication and guess the OTP pin generated during a particular session, the whole system will be compromised and result in a total break.

25

Page 30: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.2.5 Hashed Password By using either hashing or encryption, it provides a safer way to store user password instead of storing in clear text. Hashing is a one-way function and cannot be reversed to obtain the original value. On the other hand, encryption uses an encryption key and is reversible. Our prototype uses hashing to preprocess the password before storing it into the database. The reason is because encryption is reversible, this can lead to vulnerability when hackers happen to possess the key and all passwords in the database will be easily decrypted to its original value. Therefore, hashing was chosen over encryption.

3.2.6 Apache Hardening 1. Hide Apache Version and OS Identity from Errors

By default, the installed Apache will display its version and Operating System installed in the browser. This create a major security threat as attacker can formulate attacks dedicated for the known Apache, especially the older versions, or the known vulnerabilities of the particular Operating System. As such, there is a need to hide such information to act as a form of hardening.

2. Disabled and Restricted Directory Listing

The default Apache lists out all the content of document root directory. This is a form of vulnerability because attacker can search and view information that are meant to be hidden. Therefore, it is a good practice to disable the directory listing. In addition, as some directories should not be access by users, they will be restricted using ALLOW and DENY on httpd.conf file[9].

3. Updating Apache Regularly

Regular update of Apache is recommended as Apache developer community are actively working on security issues. Updating to latest version will ensure that known system flaws are patched and fixed.

4. Disable Unnecessary Modules

To reduce the chance of falling into a web based attack, unused modules should be disabled to eliminate an additional platform for attackers.

5. Using Modules to Secure Apache

Mod_Security[10] act as a firewall for application, providing a platform for traffic monitoring on real time basic. It includes protection against attacks such as Brute Force Attack and SQL Injection. Mod_Evasive is another important module for Apache that provide evasive action in the event of an HTTP DoS attack or brute force attack. It is specially designed to be a detection and network management tool that provides the capability to send abuse report via email or through syslog.

6. Enable Apache Logging

Mod_log_config is enabled to perform logging on Apache, which is independent from logging on Operating System. Logging is an important factor in Security as if an attack occurs, logs can be used for investigation and tracing.

7. Protect DDOS attacks and Hardening Other form of hardening and protection includes applying the following directives. TimeOut, specify the amount of time the server will wait for certain events to complete before it fails. MaxClients, define the maximum number of connections in a certain period. KeepAliveTimeout, define the amount of time the server will wait for the next request before closing the connection. LimitRequestFieldSize, define the size limit on a HTTP request header.

3.2.7 Verifying IP Address IP address checking acts as a form of hardening, in an attempt to detect IP spoofing using proxy. It is noted that we must never trust the IP address arriving at our application as IP packets can be modified. It is hard to prevent IP spoofing. However, it is still possible to reduce the rate of happening by performing checks and hardening[11].

3.2.8 Camera logging Besides having all the software implementation on our DoorWatcher, we have included the use of Camera to record the door entry point. This serves as a picture record log which will be helpful in investigation when a break in is triggered.

4. DESIGN PRINCIPLES 4.1 Economy of Mechanism Keep the design of the system small and simple. We believe the more complicated the system is, the more vulnerabilities it contains. Thus, we minimized the links between the different components of the system. For example, the main server is able to synchronize data down to the local servers, but local servers are not able to transmit data to the main server. The lesser the number of linkage that the system contains, the harder it is for attackers to break it. 4.2 Fail-Safe Default Access decisions are based on permission and not exclusion. Users who want to gain access to the restricted zone through the Door Access System would have to seek permission from their administrator. If access is granted to them, the administrator would then set up an account for each of the user. Users do not have the privilege of creating account for themselves. 4.3 Open Design DoorWatcher’s system design is not kept secret. As shown above, the way of implementation and the framework used for the system are discussed thoroughly in our report The security aspect of our system is not uphold due to attacker’s ignorance.

4.4 Separation of Privilege Protection mechanism does not depend on only one factor. As discussed above, our Door Access System uses two factor authentications, Password and OTP. Failure of any one of the authentication process will result in the door remain locked.

26

Page 31: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

4.5 Psychological Acceptability DoorWatcher is designed to be easy to use. As entering username, password and OTP for authentication is not uncommon in today’s society, it would not be difficult for users to use our door system.

5. COMPARISON BETWEEN PROPOSED SYSTEM AND EXISTING SYSTEMS 5.1 Comparison with Card Authentication Door System Our proposed door system would be more troublesome to use as compared to the card authentication door system. However, the little increase in inconvenience gives us a more secured door system. Card authentication door system uses one factor authentication while our proposed door system uses multi-factor authentication. Thus, it makes it harder for unauthorized people to get into the restricted zone. Another advantage of our proposed door system is it removes the need for the user to carry multiple authentication cards. All these cards are replaced by the user’s smart phone.

5.2 Comparison with Password Authentication Door System Our proposed door system is quite similar to the password authentication door system as both require the user to enter password. The difference is the existing password authentication door system requires the user to input the password onto the door authenticator machine itself while our proposed door system requires the user to input the password into the login web page. The key disadvantage of Password Authentication Door System is that a camera or an overlay on the keyboard could be installed to capture the password while this attack cannot be done on DoorWatcher. 5.3 Comparison with Biometric Authentication Door System DoorWatcher would be more troublesome to use as compared to the Biometric Authentication Door System. In addition, it also requires the user to hold on to an authenticator tool. Despite the increased inconvenience caused, the advantage of our proposed door system is the result of authentication is definite. It is not influenced by other external factor such as injuries, which would influence the result of biometric authentication.

6. ALTERNATIVES The following alternatives are explored as a replacement or add on to our current prototype.

6.1 Single Sign On with Kerberos To provide convenience for user, research on Single Sign On (SSO) implementation[12] is performed and discussion on its advantage against disadvantage are done. In SSO, user is only required to authenticate him once and subsequently gain access to the door without the need to re-authenticate. To enhance security, SSO is normally implemented together with Kerberos. The

advantage of having SSO is user productivity whereby there is no need for users to always enter password and OTP on entry. Overheads on password reset and OTP SMS sending are also reduced as fewer authentications are needed. However, SSO does give rise to problems such as if an attacker managed to gain access to the authenticated device, he may now gain full access to the door without the need to know the password, the first level of authentication. SSO with Kerberos also opens up a new vulnerability, which is a single point of failure. Kerberos requires continuous availability of a central server. As such, if the central server is down, no authentication can be performed. To add on, if the central server is being compromised, authentication would now be pointless.

6.2 Using of IMEI There is always a consideration to add on a third form of authentication. Throughout our brainstorming for prototype, we had considered IMEI number on phone[13], which fits into the definition of “What User Have”. This IMEI number is unique and since it is used as an identifier for user owning the phone, it fits into our criteria for authentication use. However, upon further research, we realise that IMEI number can be easily retrieved. In fact, IMEI number is printed on the back of Iphone and on mobile devices packaging. Also, changing of phone is very common nowadays and thus more overheads are needed to frequently update users IMEI number.

6.3 Mobile Application Mobile Application[14] may become a good alternative for web based application. Since mobile applications requires user to download and install onto the phone, developers can gain more controls to the application. This includes the sending of geo-targeted push notifications in the background processes in the phone. Accessing to DoorWatcher will also be easier since a single tap will open up the application, as compared to web application. However, mobile application is more specific to mobile device. Web based application can be easily accessed through a range of devices, example Iphone, Android, BlackBerry as long as a browser is available. As compared to mobile application, web application is compatible across devices and no updates are required on client side when there are any changes.

7. FURTHER DEVELOPMENT 7.1 QR Code The idea of QR code is to act as a replacement for OTP SMS. OTP may be encoded in QR codes. This implementation increases the convenience level as it removes the need for the user to manually enter the OTP in the application.

7.2 Temporary User Access For a Door Access System, there may be times where temporary access is needed. For example, a user is allowed access to a discussion room from 2pm to 4pm on a particular day. As such, a ticket can be generated to user for such short access.

27

Page 32: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

8. CONCLUSION Our proposed door system, DoorWatcher, provides an alternative way for users to gain access to the restricted zone. As compared with the traditional Door Access System, DoorWatcher does not need to physically interact with the system. Using Raspberry Pi as the backbone for our system, more flexibility and functionality can be added as opposed to the fixed factory made product. With minor adjustment and add on, DoorWatcher may even be capable of authenticating more than one door. Implementing the system with a Raspberry Pi is also considerably cheaper as compared to readymade product. Lastly, DoorWatcher main highlight is our implementation on OTP authentication. This implementation uses SMS which serve as both an authentication and alert platform for user during the authentication process. The idea is generated from the concept for e-Banking which takes great priority on security and authentication.

9. REFERENCES [1] David, C. (1999). Smart Cards Aren’t Always the Smart

Choice. Retrieved from http://www.enhyper.com/content/smart.pdf

[2] Hugh, A. (2014). Retrieved from CS2107 foil 9 page 28 [3] Mark, B. (2002). Ten Windows Password Myths. Retrieved

from http://www.symantec.com/connect/articles/ten-windows-password-myths

[4] Fred B. Schneider. Something You Know, Have, or Are. Retrieved from http://www.cs.cornell.edu/courses/cs513/2005fa/nnlauthpeople.html

[5] Allen, F. V. (2013). Google Reveals the 10 Worst Password Ideas. Retrieved from http://techland.time.com/2013/08/08/google-reveals-the-10-worst-password-ideas/?iid=biz-article-mostpop2

[6] Neil J. Rubenking. (2012). Your Birthday Is a Terrible Password. Retrieved from http://securitywatch.pcmag.com/hacking/300220-your-birthday-is-a-terrible-password

[7] (2014). CodeIgniter User Guide Version 2.2.0. Retrieved from https://ellislab.com/codeigniter/user-guide/general/security.html.

[8] Rob S. (2013). Simple Oath TOTP RFC 6238 in PHP. Retrieved from http://www.opendoorinternet.co.uk/news/2013/05/09/simple-totp-rfc-6238-in-php

[9] Amanda. F. (2011). Rule-based Access Control for Apache. Retrieved from https://www.linode.com/docs/websites/apache-tips-and-tricks/rulebased-access-control-for-apache

[10] (2014). ModSecurity. Retrieved from http://www.modsecurity.org/about.html

[11] Jonathan H. (2006). The Top Five Ways to Prevent IP Spoofing. Retrieved from http://www.computerworld.com/article/2546050/network-security/the-top-five-ways-to-prevent-ip-spoofing.html

[12] (2014). SSO Benefits. Retrieved from https://www.uoguelph.ca/ccs/security/internet/single-sign-sso/benefits

[13] (2014). Find the IMEI Number on a mobile phone. Retrieved from http://www.wikihow.com/Find-the-IMEI-or-MEID-Number-on-a-Mobile-Phone

[14] Sara. A. (2014). Mobile Website vs. Mobile App: What’s the difference? Retrieved from http://www.businessnewsdaily.com/6783-mobile-website-vs-mobile-app.html

10. APPENDIX 10.1 Appendix A

Figure 1: System Architecture

10.2 Appendix B

Figure 6: Implemented with HTTP

28

Page 33: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Figure 7: Implemented with HTTPS

29

Page 34: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

30

Page 35: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Testing Mobile Applications for Vulnerabilities

Peh Kim Chai Alex A0097921W

National University of Singapore [email protected]

Prakash S/O A Divakaran A0098943L

National University of Singapore [email protected]

Tan JianWei Leslie A0097779Y

National University of Singapore [email protected]

Yu Zhangxin A0097868B

National University of Singapore [email protected]

ABSTRACT In this paper we present the usage of various tools for testing mobile applications for vulnerabilities, namely for the iOS and Android platforms.

Keywords Testing, Vulnerabilities, iOS, Android

1. INTRODUCTION The usage of mobile applications is ubiquitous. Companies, banks and large/small corporations are utilizing the mobile platform to leverage their conduct of business. As such, the demand for mobile applications is estimated to be US $50 billion as of 2013 and is expected to rise to US $150 billion [1]. Given the profitability, the number of people swapping over to develop mobile applications is on the increasing trend [2]. Focus is placed heavily on the different operating platforms, but less on the applications developed; even kids are into developing applications. This trend does induce a worry in the security field as the expertise of these developers in terms of security might be low. Like all solutions in technology, as the interest of developers increase, so does the interest of hackers/attackers to exploit the benefits of the market. The motives for them might vary but the opportunities are endless given the enormity of the market and the variety of skillset of the developers. As we have covered motive and opportunity in the MOM framework, we are left to answer the question of method; how will they be able to exploit mobile platforms? To answer this, there is a need to understand the possible vulnerabilities in mobile platforms.

2. Top 10 Mobile Vulnerabilities Mobile applications present a whole new level of challenge as an app can do multiple things, such as network requests and data storage. This makes the behavior prediction a challenge. Open Web Applications Security Project (OWASP) listed the following as the top 10 vulnerabilities for mobile platforms from their research [3]:

2.1.1 Weak Server Side Controls The source of this vulnerability is from a backend web API or web service that implements weak controls in untrustworthy input from a mobile app client.

2.1.2 Insecure Data Storage Sensitive information can be easily extracted when the mobile device gets lost, stolen or some rogue application steals

information and sends it off to an attacker. Appropriate storage practices needs to be practiced by developers.

2.1.3 Insufficient Transport Layer Protection The sufficiency of the TLS applied might be taken for granted which could actually be vulnerable. Some good points to check include if all SSL certificates in date, if SSL certificates are self signed and if the SSL uses good ciphers.

2.1.4 Unintended Data Leakage This could be due to a number of reasons ranging from the OS caching practices to the way development frameworks cache data. This behavior might be totally invisible to the developers and could lead to unintended data leakage.

2.1.5 Poor Authorization and Authentication Porting login applications from a web application to mobile applications should include the same quality of authentication mechanisms and native login applications should apply binary protection. Without such measures, the level of authorization and authentication will be poor.

2.1.6 Broken Cryptography Using broken and deprecated algorithms such as RC2, MD4 and SHA1 could lead to the decipherment/prediction of enciphered/hashed messages in mobile applications.

2.1.7 Client Side Injection When Android applications are downloaded, the program is run as "client side". Attackers can load simple text-based attacks that exploit syntax of targeted interpreter. Source-file and application can be any source of data. SQL Injections are likely to damage or overflow other application component.

2.1.8 Security Decision via Untrusted Inputs Mobile applications accept data input from all sources but the input can be modified by a malicious user in a way that bypasses the protected mechanism such as cookies and environment variables. Security decision such as authentication and authorization with sufficient encryption and integrity checking can prevent an attacker from changing the inputting using customized client or other attacks

2.1.9 Improper Session Handling Session Time Out often occurs during bank transaction. Given infinite amount of time being logged on, allow hackers to retrieve data when users are accessing some sensitive data. Failure to rotate the cookie and insecure token creation allow attacker to exploit vulnerability by gaining physically access to device by network traffic (TCP session hijacking).

31

Page 36: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

2.1.10 Lack of Binary Protection The application is at risk when an attacker can decrypt and reverse engineer the application. It is the risk of not keeping the apps.apk (Android Application Package) file and allow it to be tamper proof. Apk-> .dex->.class->.Java In order to test for these vulnerabilities, there needs to be some level of control, and this control can only be achieved by rooting/jailbreaking the phone.

3. Rooting/Jailbreaking Both in the iOS and Android Platforms, rooting is of great interest. Rooting gives the user much control over his/her phone and this control can be either a joy or a woe.

3.1 The Joy of Rooting / Jailbreaking Rooting an Android or jailbreaking an iPhone enables users to be promoted as superuser or have root permission in the Linux based operating system (OS). It is important to note that Android is built on an underlying Linux kernel. This benefits the user by allowing him or her to take advantage of the root permission and control, allowing the user to do whatever they want, from changing themes, downloading Apps not in the official app store in iOS to replacing the entire operating system in Android.

3.2 The Woe of Rooting/ Jailbreaking Rooting provides unprecedented access to places and locations in the phone with permissions. It also allows applications not from the official iOS store to be downloaded which could itself pose a security risk; the apps are not sandboxed and tested. Malicious applications can exploit the phone without showing any visible signs to the user.

4. Vulnerability Analysis on iOS Apple is well known for its rigorous processing of applications before any application hits the app store. This provides an assurance for users that the content they access on the app store is generally safe. The workflow arguably could address the issue of data leakage; when the app does things that it’s not meant to do, e.g. send away phone contacts to remote location. But this does not address all threats. Reverse engineering (decompiling) a binary on a jail broken phone could expose many vulnerabilities of an application.

4.1 Tools As building requires tools (IDEs, analyzers etc), so does hacking or testing. A jail broken phone, using evasion for iOS 6 and below or Pangu for iOS 7 would be necessary. The other tools would be openSSH, GDB, Clutch, a tool that decrypts apps from the app store and class-dump, to look at the class information. These tools would be necessary for a start to understand the process. Other tools would be mentioned for analysis of a specific vulnerability. The test apps for these experimentations were taken from Prateek Gianchandani [4].

4.2 Poor Authorization and Authentication Apps that require local authentication could be in for a threat that allows an attacker to bypass the login procedure through techniques such as method swizzling and GDB Analysis. Both

this techniques exploit the fact that Objective-C is a runtime-oriented language [5]

4.2.1 Runtime Orientation Runtime orientation or dynamic typing and binding are terms to indicate that decisions are usually deferred to the point of execution time, with the other technique being during compile and link time. As such, during runtime, each object is given a pointer called isa to its class and all the classes it inherits [6]. From there, when a method is invoked possibly through user interaction, the isa pointer is used to find a selector from the dispatcher table which corresponds to that method, and it’ll be executed. Selectors are used to send messages to objects during runtime.

4.2.2 Method Swizzling Method swizzling is done by modifying the method to perform a behavior defined by the attacker during runtime. Using Cycript, a tool which helps to modify behaviors during runtime, we can hook into a running app and modify its behavior. The test app, MethodSwizzilingDemo presents a simple login page that requires the user to key in a user name and password to use the app. This app is first decompiled by dumping its class information using the class dump command. Figure 1 shows the dumped contents with the ViewController specifying some interesting methods.

Figure 1:Class Dump of MethodSwizzilingDemo Binary

The method of interest is the -(BOOL) validateLogin:. This could be easily inferred to be the method that’s handling authentication. Using Cycript, the running process was hooked into, to find the instance of the active ViewController. This instance was used to get access to the validateLogin method and set it to true always. Cycript offers a friendly way of using JavaScript for manipulations as shown in Figure 2.

Figure 2: Cycript Manipulation

4.2.3 GDB Analysis Method swizzling was done using High Level languages such as JavaScript and objective-c. In this example, we will manipulate values at the assembly level.

32

Page 37: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

All iOS devices till to date have been based on the ARM architecture. As objective-c relies on messaging between objects during runtime [7], understanding the register allocations in the ARM architecture would be useful. $r0 is used to hold the pointer to the instance of the class, $r1 contains a selector (method) and $r2 onwards will be the arguments. The general debugger (GDB) is a useful tool to analyze the flow of the application at the assembly level and view the contents of the registers. The compare command, cmp is of particular interest. The cmp is done to make a comparsion before a branch decision is made, which would bring the program execution to a different part of the code. The test app is GDB-Demo, which presents a simple login page. GDB was used to attach to GDB-Demo’s process. The class-dump information showed an interesting method named loginButtonTapped. A break point was set at loginButtonTapped and the disassembly command was used to see the internal assembly commands of that method.

Figure 3: Disassembly of loginButtonTapped

The disassembly showed two points in the program where there were cmp commands. It could be inferred that these compare commands were being used to decide on a branch target as there was a following beq command in the corresponding sections. Checking the branch targets, they were basically triggering the UIAlertView, indicating an error has occurred. So it was decided that the branch should not be taken and the register, $r0 that was compared to #0 was set to 1 in GDB so that the zero flag will not be updated and branch will not be taken. This is shown in Figure 4.

Figure 4: Manipulating register $r0

This thus allowed us to bypass the login authentication and get directly to the home page.

4.2.4 Patching The above two procedures were intensive in the number of steps required to swizzle or bypass the login procedure. This could be avoided if the code of the application can be permanently patched. One way to patch this is to manipulate the ARM instructions. Using the GDB-Demo test app, we first can disassemble the app binary in a graphically presentable environment, IDA Pro. The demo version supports the ARM architecture. Figure 5 shows the flow of subroutines in the loginButtonTapped method.

Figure 5: Before Patching

As seen, the BEQ command decides if the app is presented the admin page or is brought to an error page. The command branches if zero is set to loc_AC84 which is the error page. We would want it to branch if not equal (BNE) instead, i.e implying all wrong usernames and passwords would be accessing the homepage. In order to manipulate the command to BNQ, the offset address of this instruction has to be calculated. The offset address was found by taking the current absolute address shown in IDA Pro, subtracting off the applications start address and adding the application offset. The application start and offset addresses were found using the otool command. This command is used to view the Mach-Object structure of iOS applications, which is basically a file format. Figure 6 shows the results of otool.

Figure 6: otool on GDB-Demo Binary

The text section displays start address and the offset respectively. Using that the offset was calculated to be 0x6C46. The binary was then opened using the Hex Fiend application.

Figure 7: Patched Binary showing BNE

The ARM architectures opcodes were referenced to find the right opcode for the BNE command. This opcode was defined from bit 24 – 31which corresponds to 0xD1. The BEQ command was 0xD0. Using the Hex Fiend application, the opcode was

33

Page 38: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

manipulated to 0xD1. Figure 7 shows the patched binary flow. The command has been changed to BNE.

4.2.5 Mitigations Macros could be used to mitigate the effects of runtime analysis. One example of a macro is shown in below.

#ifndef DEBUG SEC_IS_BEING_DEBUGGED_RETURN_NIL(); #endif This would prevent a debugger from attaching to the running process. It’s advisable to implement this in important parts of the code, like the login page.

5. Vulnerability Analysis on Android required tool: SDK,ADT,Elicpse,Goatdroid,Dronzer,Burp

Burp Suite Free v1.5 – PortSwigger Burp Suite is security testing software which allows the user to examine various aspects of application security and is an excellent tool for security testing.

APKTool – Decompiles the Android app file and is used in conjunction with Dex2Jar

5.1 Insecure Data Storage This risk occurs on the phone as a result of insecure storage of data with-in the phone’s memory stores. Developers may presume that the user has no access to these internal memory stores but an attacker can attach the phone to a computer and use software to retrieve data and/or sensitive personal information including usernames, passwords, authentication tokens, etc. The device also becomes vulnerable to this type of attack if the device has been “rooted”. Rooting gives the Android user privileged access to the device’s subsystems which leaves the device vulnerable to attack. There are also multiple ways in which a developer could choose to save their data in. Shared Preferences allows developer to save primitive data in key value pair in clear text, Internal Storage stores the data in device memory and it only allows the application in which the data is created for to access; data will be gone when application is removed. In contrast with Internal Storage, the External Storage stores data in the SD Card of the device, this data is globally accessible by other application. Lastly, Android supports database storages, SQLite is a lightweight database used in Android. Databases created by application are only accessible by the class in that particular application that creates it and it is not globally accessed by other applications [8]. At times, developer may use the wrong storage mechanism to save the application sensitive data such as username and password. One such example is through the usage of shared preferences to save one's ‘remember me’ credentials.

5.1.1 Scenario One such vulnerable application to this sort of attack is FourGoats, a location based social network [9]. The FourGoats application gives the user the option to remember their credentials by selecting “Remember Me” so that they do not have to enter their details into the “Username” and “Password” fields each time they login. In order to remember the credentials, the application stores them using the SharedPreferences class in the shared_prefs folder of the application.

This test case demonstrates how the xml files can be accessed and how sensitive data can be stolen at the expense of poor choice of data storage option. In order for an attacker to be able to perform this attack they must have physical access to the device.

5.1.2 Methodology Start the emulator and open up goatdroid. You’ll be presented with a login/register screen. Click on register and register a new user, refer to fig. 1 below.

Figure 8: User Registration

Once the user has been registered, go back to the login screen and key in the credentials which have just been created and ensure that ‘Remember Me’ is checked. Click on Login to log into the system.

Figure 9: User Login

Once the user has logged into the system, on the host computer, open command prompt and type “adb shell”. The prompt will change to “root@generic:/ #” if successful. In the adb shell, navigate to “/data/data/org.owasp.goatdroid.fourgoats/shared_prefs”, the directory which stores the credentials where remember me is checked. Inside the folder, you will notice that there is a “credentials.xml” file. Open the files and you will see the username and password stored in the files as shown in Fig. 3.

Figure 10: Username and password stored in plaintext

5.1.3 Mitigations This can be mitigated through proper choice of storage such as using internal storage to store the credentials. Another mitigating factor could use encryption to encrypt the password in the

34

Page 39: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

credentials.xml. Therefore, such tricks will not be easily exposed to the attacker.

5.2 Bypassing Authentication to Access Application Applications can be protected with passwords, or by other means. However, if the developer did not properly code the application, they may allow other applications to access their application. In Android, allowing other applications to access theirs is called exports.

5.2.1 Exportable Activities In Android, activities refer to the screens that are used by the app, that is to say the interface shown to the user. If not properly coded, other applications could access sensitive data within the application maliciously.

5.2.2 Access sensitive data through launching activities We will use Drozer [10] to discover some vulnerability with regards on the Content Provider in the Sieve application.

Figure 11: Drozer startup screen

First we will type “run app.package.list –f sieve” on the command prompt to find the identifier in the device with the name “sieve”, which returns us its package name. Next we try to collect some potential attack vectors we can do.

Figure 12: Searching for attack surface

We look more deeply into the exportable activities with the following command.

Figure 13: Discover exportable activites

By looking at the activities’ name, we can assume that PWList should mean password list. Since this activity is exported and does not require any permission, we can use the following command to launch it, bypassing the authentication.

Figure 14: View of passwords without authorization

5.2.3 Mitigations In order to prevent exportable activities, we need to specify the parameter android:exported = false when creating the activity [11]. For example, <[activity name] android:exported="false"/>. If the activity needs to be used by other applications, we can limit its exposure by giving external applications the least privileges to get things done.

5.3 Client Side Injection Android application are downloaded and installed on the device. Most application requires save application data locally or to remote databases. There are several options to store data [12]. However we will look into databases, in particular SQLite which Android uses. Since Android by default, uses SQLite to store databases, it is subjected to SQL injection on the devices [13].

5.3.1 Content Provider Leakage Within many applications, they use content providers to store and query data within the application or the phone. Without explicitly defining the access permission, any other application could also access its data using the application’s defined content providers. Content provider’s Uniform Resource Identifier (URI) has a standardize convention of “content://” [14].

5.3.2 SQL Injections through Content Provider We will use Drozer to discover some vulnerability with regards on the Content Provider in the Sieve application. We try to collect some basic information about the content providers exported by Sieve.

Figure 15: Collection of basic information

We can make an assumption that the content provider called ‘DBContentProvider’ will contain some form of database in its backend. We began to look for the content URIs that we are accessible.

Figure 16: Discover accessible content URI

Once we discover an accessible content URI, such as “content://com.mwr.example.sieve.DBContentProvider/Passwords/”, we can execute an injection into it. For a SQL query as such: “SELECT [projection] FROM [table] WHERE [selection]”, Drozer is able to modify a query’s projection and selection fields. We will craft SQL injections as shown in the following figure. SQLITE_MASTER is a special table which every SQLite database has [15]. Hence we could easily retrieve the list of tables in the database, and access the data in those tables.

35

Page 40: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Figure 17: SQL injection

5.3.3 Mitigations In order to prevent content provider leakages, we just need to specify the parameter android:exported = false when creating the content provider [14]. For example, <[component name] android:exported="false"/>. As for SQL injections, we can use SQL sanitization techniques, such as using a prepared statement, or use libraries such as DatabaseUtils.sqlEscapeString(String) to escape strings [16].

6. Conclusion In this paper we presented the top 10 mobile vulnerabilities in 2014, we have also discussed the joy and woe of rooting. We then performed vulnerability analysis on test applications written by Prateek Gianchandani using tools such as Pangu, openSSH, GDB and Clutch. Following on, we extended the analysis on Android platform with test applications such as Goatdroid and Drozer. These facilitate the understanding of the vulnerabilities, tools used and methods to conduct tests.

7. Acknowledgements We would like to thank Professor Hugh for taking his precious time in assisting us throughout the project duration. Our thanks to ACM SIGCHI for allowing us to modify templates they had developed.

8. References [1] Management Science, Forthcoming. (January 1, 2014).

Estimating Demand for Mobile Applications in the New Economy. Retrieved from: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2378007

[2] Beth Stackpole. (June 27, 2011). Your next job: Mobile app developer? Retrieved from: http://www.computerworld.com/article/2509463/app-development/your-next-job--mobile-app-developer-.html

[3] OWASP. (September 13, 2014). Projects/OWASP Mobile Security Project - Top Ten Mobile Risks. Retrieved from: https://www.owasp.org/index.php/Projects/OWASP_Mobile_Security_Project_-_Top_Ten_Mobile_Risks

[4] (n.d.). Damn Vulnerable iOS Application (DVIA). Retrieved from: http://damnvulnerableiosapp.com

[5] Apple Inc. (September 17, 2014). Programming with Objective-C. Retrieved from:

https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html

[6] Apple Inc. (October 19, 2009). Objective-C Runtime Programming Guide. Retrieved from: https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtHowMessagingWorks.html

[7] Apple Inc. (October 22, 2013). Objective-C Runtime Reference. Retrieved from: https://developer.apple.com/library/mac/documentation/cocoa/reference/objcruntimeref/index.html#//apple_ref/c/func/objc_msgSend

[8] Srinivas. (2014). Android Hacking and Security, Part 9: Insecure Local Storage: Shared Preferences. InfoSec Institute. Retrieved from: http://resources.infosecinstitute.com/android-hacking-security-part-9-insecure-local-storage-shared-preferences/

[9] Mannino, J. (2014). Projects/OWASP GoatDroid Project. Retrieved from: https://www.owasp.org/index.php/Projects/OWASP_GoatDroid_Project

[10] (n.d.). Download packge for Drozer. Retrieved from: https://www.mwrinfosecurity.com/products/drozer/community-edition/

[11] (n.d.). Android App Manifest Activity. Retrieved from: http://developer.android.com/guide/topics/manifest/activity-element.html

[12] (n.d.). Android App Data Storage. Retrieved from: http://developer.android.com/guide/topics/data/data-storage.html.

[13] Godfrey Nolan. TOP 10 MOBILE SECURITY RISKS. Retrieved from: http://www.decompilingandroid.com/mobile-app-security/top-10-mobile-security-risks/.

[14] Aditya Gupta. 2014. Learning Pentesting for Android Devices. ISBN 978-1-78328-898-4.

[15] (n.d.). SQLite Frequently Asked Questions. Retrieved from: http://www.sqlite.org/faq.html.

[16] (n.d.). Android APLs Database Utils. Retrieved from: http://developer.android.com/reference/android/database/DatabaseUtils.html#sqlEscapeString%28java.lang.String%29

36

Page 41: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Insecurities in Modern Web Browsers Victoria Chew

NUS [email protected]

Lim Wei Ke

NUS [email protected]

Jason Poh NUS

[email protected]

Sudarsan Gopalaswami NUS

[email protected]

ABSTRACT This paper presents some security issues brought about by features offered in modern web browsers and the techniques to mitigate them.

Categories and Subject Descriptors H.4.3 [Information System Applications]: Communication Applications – information browsers.

General Terms Management, Experimentation, Security, Human Factors

Keywords Browser, Chrome, Extensions, Self-XSS, XSS, Cookies

1. INTRODUCTION In the world of Software-as-a-Service (SaaS) and with most people putting ‘everything-on-the-Cloud’, the focus has now shifted to attacks on browsers and web applications instead of the physical machine itself. Browser extensions allow web application developers to bring out more features to existing sites and the browser itself. However, it also contains a big surface area for the attackers to exploit. For this paper, we will explore on how to make use of these exploits in the latest versions of the browsers, by mainly using browser extensions or developer features. We will also recommend changes pertaining to our experiments conducted on how these extensions should be implemented to reduce the attack surface.

2. EVIL FEATURES To an application security analyst concerned, every feature offered by the application in question is a possible attack surface. It has come to our attention that modern browsers are packed with features that enhances the user’s experience as well as for developers to easily extend the browsers features or even do

debugging on the browser itself.

In this section we will dive into some of the interesting features provided by the Google Chrome browser that attackers could exploit.

2.1 JavaScript Console As part of the Google Chrome Developer Tools (DevTools), the JavaScript console provides developers a medium to log diagnostic information as well as a shell prompt where one could inject JavaScript code directly to the page.

Figure 1. Google Chrome JavaScript Console The ability to inject JavaScript codes into a browser page is not new as most browsers allow the execution of JavaScript code directly from the location bar. However, the JavaScript Console allows the attacker to easily enter multiple lines of JavaScript codes to be executed.

Figure 2. Injecting JavaScript via Location Bar Using this potential exploit, an attacker with physical access to a victim’s machine could easily inject malicious JavaScript codes

Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission.

37

Page 42: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

which would otherwise need a Cross Site Scripting (XSS) vulnerability on the target site. The attacker could also use social engineering to get the victim to enter a set of malicious commands which is widely known as a Self-XSS attack. For instance, the JavaScript could make use of ‘document.cookie’ to get the current page cookies and use an ‘XMLHttpRequest’ object to send that cookie back to a malicious web server.

2.2 Google Chrome Extensions The Google Chrome browser extensions allow developers to create small programs that are integrated into the browser, which enhances the functionalities of the Chrome browser. These extensions are essentially mini web pages which consists of HTML, CSS, JavaScript, Images that have exclusive access to APIs exposed by the Google Chrome browser which are not accessible by a normal webpage.

These extensions are also not bounded by the same-origin policy or any other security policy enforced by the web page. The JavaScript that runs in the extensions are also running in another sandboxed environment. In other words, the extensions will not be able to call functions from the web page and vice-versa. Extensions are required to state what APIs they are capable of executing in the form of permissions stated in the extension’s manifest file.

Among the list of APIs that are exposed by Google Chrome browser, we have identified ‘chrome.cookies’ API as one of the most vulnerable API. This API allows developers to create extensions that query and modify the browser’s cookie. Cookies are name-value pairs that the browser uses to store information or state regarding the current web browsing session.

Figure 3. Cookies used in ivle.nus.edu.sg An attacker could then easily publish a legitimate extension to the Google Chrome Web Store and the same legitimate extension could be maliciously taking the victim’s cookies and sending them back to the attacker’s server. This could be done all without the user’s knowledge as the user would have already given the extension permissions to access cookies on the browser.

Figure 4. A vague prompt to give an extension permissions

While it is good that there is actually a prompt to tell the user what the extension is capable of doing, it is not detailed enough for the user to gauge whether the extension is requiring more than enough permissions.

After the user has finished the installation of an extension, it will be stored locally on the user’s machine without any form of protection.

Figure 5. Files of a Chrome Extension All of the files that the extension makes use of are stored in plaintext in a seemingly randomly named folder without any mechanism of integrity checking. As a result, an attacker could easily make use of any extension that is already installed and add malicious JavaScript codes to it, since it does not violate the original permissions.

3. MITIGATIONS In this section, we shall discuss the techniques to mitigate the attacks mentioned in the previous section.

3.1 Content Security Policy Content Security Policy (CSP) is a control mechanism which is sent via HTTP headers by a server response to prevent XSS related attacks. It is currently still in experimental phase and the next iteration is being developed by W3C.

The idea is to let web developers specify a whitelist of sources for which could be loaded on a particular web page. Any attempt to load any resources not in the whitelist will be blocked by the browser.

Figure 6. Content Security Policy in action As seen above, an ‘XMLHttpRequest’ was blocked by the browser because ‘localhost’ is not listed in the whitelist. As it is the same with control mechanisms that relies on the HTTP headers sent by the server, it could be easily modified or stripped by a man-in-the-middle attack. This will then result in a bypass of the feature.

38

Page 43: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

In short, this is definitely great features that will prevent most of XSS related attacks provided that there are other mechanisms in place to ensure the integrity of the HTTP headers. A recommendation of such a mechanism is to hash the HTTP header with a secure hash that could not be easily forged by attackers.

3.2 Invalidation of Cookies In order for an attacker to successfully compromise a victim’s online account without knowing his or her username and password, a valid cookie containing all the login session information must be present. As part of our experiment, we noticed that cookies are still accepted by the web application even after we have logged out of the account. The findings of our experiment can be seen below:

Site/Domain Invalidates session upon logging out

paypal.com Yes

facebook.com Yes

gmail.com, mail.google.com, google.com

Not immediately, 1 min delay

mail.live.com No

ivle.nus.edu.sg No

We have selected the sites above based on how frequent we use them and we are shocked by the results. Hence, we emphasize on the point again that session cookies should be invalidated once the user chooses to log out. This is to ensure that even in the event that an attacker got hold of your cookies, he will not be able to do much once you have chosen to log out of your account.

Besides invalidating your cookies upon logging out, we also think that the session cookie should be tied to the login IP address or the region of the login IP address. While it is not uncommon for a person to want to stay logged in to a website when he or she is on the move in this world of mobile computing, the IP addresses from one destination to another might differ even though the region is the same. The regions mentioned here can be as small as a subnet, or as big as a set of IP addresses which corresponds to a country. The region should be small if the web applications in question have sensitive information or operations (i.e. banking web application) and bigger if it is less sensitive to provide users better usability. We have again conducted an experiment on the same set of sites using a proxy server to mimic the effects of changing regions from Singapore to USA.

Site/Domain Invalidates session upon switching region

paypal.com No

facebook.com Yes

gmail.com, mail.google.com, google.com

Yes

mail.live.com No

ivle.nus.edu.sg No

We observed that only Google and Facebook does a good job enforcing such measures. Despite being one of the leaders in the

payment gateway market, PayPal does not invalidates session cookies or even request the user to re-enter the password upon changing information such as name, email addresses, address, phone number. With a valid session cookie and if the victim does not properly log out of the account, an attacker could easily get sensitive personal information as well as modifying them to get total control over the account (i.e. changing the email address and resetting the password).

Lastly, session cookies should be properly invalidated after a period of time. Similarly, the period can be as short as short as a few minutes for sensitive applications and as long as for months for less sensitive applications. The idea here is that no session cookies should be valid for an indefinite amount of time. This is to ensure that attackers would not be able to use outdated cookies to compromise the victim’s account.

Again, we see that security measures often bring down the usability of an application and vice-versa.

3.3 Hardening Extensions Browser extension modules such as the Google Chrome browser Extensions need to be protected from unauthorized access and modifications. These extensions often have more control over the whole browser compared to normal JavaScript running in the page. We have also seen previously that the Google Chrome browser extensions are only obfuscated or try to be hidden from the user. This is clearly insufficient as a skilled attacker could easily locate the folder and make modifications to it without the victim knowing. This could be done by the attacker if he has physical access to the victim’s machine, or remotely by a virus or Trojan.

We can view extensions like mobile applications in which one could download easily from a web store. These published mobile applications are signed by a developer certificate that maintains the integrity of the whole application. Any modification to the application code would violate the integrity of the application. We thus recommend that web extensions should have a similar approach of code signing or integrity checking based on Public Key Infrastructure.

Lastly, extensions should not be able to read all cookie data easily. Controls, an additional cookie flag similar to ‘HttpOnly’, can be put in place to restrict certain cookies from being read or modified by extensions.

3.4 In-built Public Education Knowledge is king when it comes to security. More often than not, users become victims because they are unaware of the mechanics involved in web applications and browsers, and thus they are not be able gauge what the tools which are available in the browser are capable of doing, or even assess the damaging effects these tools have on them after a misuse.

Figure 7. Facebook anti self-XSS warning

39

Page 44: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

As seen above, as a user tries to open the JavaScript Console while browsing Facebook, an appropriate warning is shown to the user. Information like these should be readily made available to users upon activating ‘dangerous’ tools in the browser.

4. CONCLUSION We have mentioned some suggestions to mitigate the attacks seen in this paper. However, it is important to note that these just cover a small portion in the area of security in web browsers. Web applications therefore should be hardened on the server side instead of relying on the client to enforce the security. Client software such as the web browser should be equipped with features to educate the public on attacks and how to avoid falling prey to them.

5. ACKNOWLEDGMENTS Our thanks to Prof. Hugh Anderson for his guidance and understanding throughout the semester and ACM SIGCHI for allowing us to modify templates they had developed.

6. REFERENCES [1] Chrome: JavaScript APIs, 2013. Retrieved October 21, 2014,

from: https://developer.chrome.com/extensions/api_index.

[2] Content Security Policy 1.0: W3C Candidate Recommendation, 2012. Retrieved October 21, 2014 from: http://www.w3.org/TR/CSP/.

[3] Facebook: What is Self-XSS?, 2014. Retrieved October 21, 2014, from: https://www.facebook.com/help/246962205475854.

40

Page 45: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Location Restricted Access ControlIain Meeke

School of Computing, NUS36 College Avenue East

Singapore+65 9019 7713

[email protected]

JIN XIAOJIESchool of Computing, NUS

21 Prince George’s Park ResidencesSingapore

+65 8109 [email protected]

ZHANG MENGDISchool of Computing, NUS

12 Kent Ridge DriveSingapore

+65 9446 [email protected]

ABSTRACTIn computer security, Network access control (NAC), also callednetwork admission control, is a method of bolstering the securityof a proprietary network by restricting the availability of networkresources to endpoint devices that comply with a defined securitypolicy. A more specific form of this is location based accesscontrol. There are certain security applications in which theadministrator will want to limit access to a network or webpagebased on the users location. This can be solved by collecting realtime information about the known networks a user is connected to,or by using a secret that is only available from a certain location.

General TermsAlgorithms,Experimentation, Security

KeywordsKeywords are your own designated keywords.

1. INTRODUCTIONIn computer security, Network access control (NAC) is methodof restricting network access or usage to users who do not complywith the security policy of the network. A traditional networkaccess server (NAS) is a server that performsauthentication and authorization functions for potential users byverifying log-in information. In addition to these functions, NACrestricts the data that each particular user can access, as well asimplementing anti-threat applications such as firewalls, anti-virussoftware and spyware-detection programs. NAC also regulatesand restricts the things individual subscribers can do once they areconnected. The majority of large companies and universities, suchas NUS, implement some form of NAC to protect their data andtheir users.

In this essay we will be discussing NAC techniques whichrestricts users based on Location. There are currently somesystems in place for limiting access based on location. Oneexample of this is the way video streaming services, such asNetflix, often offer different content based on the location of auses Internet Protocol(IP) address. However these protocols areeasily fooled. We will be examining two techniques for NACwhich include finding the identifier of the access points a user isclose to and also using a quick response (QR) code to provideaccess to a user who can see it.

2. Problem DescriptionNAC is ideal for corporations and agencies where the userenvironment can be rigidly controlled. However, someadministrators have expressed doubt about the practicality ofNAC deployment in networks with large numbers of diverse usersand devices, the nature of which is constantly changing. Anexample of such a network is a large university with multipledepartments, numerous access points and thousands of users who

wish to access certain parts of the network to achieve differentobjectives.

The example we have used to examine this problem is one thatinvolves a class test. Suppose Prof. Bob wants hold a graded popquiz, which is conducted online, for his class and only wantsstudents who are present in the class to participate. See Figure 1

Figure 1. Illustration of the University example

Prof. Bob must implement some form of network access controlto block students who are not physically in the lecture theaterfrom participating in the test.

Figure 1 above shows, Alice, a student who is physicallyattending Bob’s class, and is allowed to participate the quiz.However, Charles, a student who is not physically attendingBob’s class, also wants to participate in the quiz because the quizis graded.

There is an existing solution that can help Prof.Bob solve thisproblem is: by configuring his web server so that only allowsthose IP addresses with same network mask to access the quiz file.For Apache Web Server, use the following command to onlyallows users under NUS network to access the file in the webserver:

Order deny,allowDeny from allAllow from 172.28.188

This solution does work if Alice and Bob are under same localnetwork such as NUS (172.28.188.0) and have the same subnetmask (255.255.252.0) whereas Charles is outside the localnetwork with different subnet mask.

Page 46: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

However, this solution will not work under NUS SoC because Fora large university like NUS, students can access the same network“NUS” even though their physical locations are different. Forinstance, Charles in PGP connects his PC to NUS networkthrough the WiFI SSID “NUS”. He is regarded as under samenetwork as Alice who also connects her PC to NUS network inLT15. By IP filtering solution, Charles will not be filtered outfrom participating the quiz.

Another concern is that IP addresses can be easily spoofed. Forinstance, Student Charles has been to LT15 before and knows thevalid IP address (172.28.189.23) that has been allocated to him.Afterwards he can change the IP address of his PC so it is thesame as the one he was assigned in LT15. See following Figure 2:

Figure 2.The way to manually change the IP address

3. Suggested Solution BSSID of a SSID.3.1 Approach ImplementationIn OpenWebsocket.js there is a function which runs a windowscommand to return the network information which is then parsedto retrieve the BSSIDs of all the networks and APs that can beseen by the user. This same function can be used by the professorto generate his own BSSID list. The professor needs to do this foreach lecture theatre or classroom in which they want to conduct atest. The professor list is stored on his server as a text file.

Now when the professor conducts a test the question is put on theprojector in class and the the URL for the answer page is given tothe students. Anyone with this URL will be able to submit ananswer. However before doing so they must run theOpenWebsocket.js program. When they press the submit buttonon the answer page the BSSID list will be sent along with theiranswer to the professors server. Upon receiving a submission asmall script is run to compare the users BSSID list with the textfile of the professor's BSSID list. If there is a certain percentagematch, for example 30%, then the server accepts the submission.Otherwise it rejects it as it assumes the user is not in the class.

Originally it was thought that a complete match between thestudent BSSID and the Professors BSSID would be needed toprove the student was present in the class. However due to thevarying size of lecture theatres a percentage match is required. Forexample in a lecture theatre that can accommodate 300 people, astudent sitting at the back will be able to see the BSSID for Apsoutside the lecture theatre which the professors computer will notbe able to see that far. However the percentage match should notbe too low as a user sitting outside the lecture theatre could be

able to see a BSSID that is inside the lecture theatre. If such auser tried to submit and the percentage threshold was too low theserver would accept their answer.The reason the websocket is needed is to allow full duplexcommunication between the user and the server. This means thatwhile the websocket is running there is a means for constantcommunication between the user and the server as opposed to theserver sending information and closing the communicationbetween the two.

3.2 Illustration

Figure 3. Illustration of BSSID comparison

System requirement:

1. On Alice’s PC, the operating system is restricted to beWindows. Node.JS must be installed and her browser must beallowed to run JavaScript. To get the WiFi information of aWindows-based device and to further get the BSSID list, thecommandspawn(‘netsh’,[‘wlan’,’show’,’netowrks’,’mode=bssid’]) isneeded and to run this command, we mustrequire(‘child_process’).spawn as a pre-requisite.

Figure 4. Code for acquiring WLAN information in Windows

2. On the web server, the BSSIDlist of Prof.Bob’s PC has alreadybeen created. The BSSID list is ina text file like:

Method:

1. Prof.Bob shows the URL(~/quiz.php) of the quiz to the class.

2. Alice and Charles both open the websocket on their PC by(node OpenWebSocket.js).

Page 47: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Figure 5. Opening WebSocket at student side

3. Alice and Charles both open the browser and enter the URLgiven by Prof.Bob

Figure 6. Browser view from student

4. Alice and Charles both select the answer and click the submitbutton.

5. The JavaScript&PHP in ~/quiz.php file will auto send theanswer and BSSID list of both PCs to the web server.

6. The web server will compute the similarity of received BSSIDlists and existing BSSID list.

7. Since Alice is physically attend the class, so the similarity ofher BSSID list and Prof’s BSSID list should be greater than 30%;yet, Bob is outside the lecture theater, the similarity of his BSSIDlist and Prof’s BSSID list is less than 30%.

On Alice’s browser: On Charles’s browser:

8. The web server will accept Alice’s answer but reject Bob’sanswer.

3.3 ResultsThe problem was solved in that only students who are physicallyattending the class are allowed to participate the quiz; where asfor students outside the lecture theater, even though they can readthe questions, their answers will not be processed by the webserver.

However this implementation only works for Windows-basedoperating system, it does not support other operating system suchas Linux or mobile OS. <Student/Client> must install and runnode.js on their PC before access the quiz. In the future hopefullytheir will be no system-requirements

Another concern is that the OpenWebSocket.js is distributed to allstudents. If the OpenWebSocket.js is not encrypted, they can readthe implementation and modify with their own preferences andspoof the server. As the illustration above, OpenWebSocket.js isused for generating BSSID list for a machine. If Alice sends herBSSID list to Charles, Charles can modify the OpenWebSocket.jsfile to generate same BSSID list as Alice, then Charles sends thisnew list with his quiz answer to the web server which containsquiz.php. The web server will accept the vote this time thoughCharles is not physically attending the class, because the BSSIDlist manually created by Charles is a valid match with the existingBSSID list in the server.

Figure 7. BSSID spoofing

In order to solve this issue, OpenWebSocket.js has to be hiddenaway from user. A new version of implementation for androidplatform is under development, the general idea is to replace thewebsocket.The websocket is used for acquiring BSSID of a deviceby passing a windows shell command “ netsh wlan shownetworks mode=bssid” to Javascript. Android has its own APIfor acquiring BSSID of a mobile device, such as wifi.getWifiInfo()which displays all the WiFi related information.

4. Suggested Solution QR-code4.1 DescriptionAn alternative solution is to use a quick response (QR) code. TheQR code uses standardized encoding method to store data whichcan be converted to binary numbers and validated with the error-correction code.”(wiki) Since now smartphones can be used as aQR code scanner, it has become a popular and convenient way forURL redirection for website. In this project, the QR code is takenadvantage to restrict the access since only those inside the theatrecan scan the image and go to the specific polling website.One problem is that if the URL of the polling website is the sameevery time, then it is not a secret anymore for all the students, thusthe URL should be difficult to guess for each lecture. However,people can still take a picture of the QR code or easily get theURL from the browser and send them to others who are not in thelecture.In order to solve this problem, the idea is to keep changing theURL, so after 5 seconds, the previous image is out of date. (It isassumed that the browser can load the web page in 5 seconds.)The chances of retrieving the URL information from somewhereelse reduces greatly because of the time limit. For the studentswho access that polling website by scanning the QR code in class,the changing of the valid URL will not affect the selection andsubmission of the answers since the browser already loads therequired information.In addition, the access to the image should also be blocked fromelsewhere, therefore in the future we plan to add a login page toonly allow the access from professor or certain computers. ThisQR code approach is designed for the anonymous quiz, but wecan also supplement the student identification feature for gradedquizzes.

Page 48: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

4.2 Implementation

Figure 8 Quiz posed on the projector in LT15Instead of randomly generating URLs and QR codes each 5seconds, a much easier pre-stored method is applied. The QRcodes are pre-computed according to the URLs stored in somearray and these QR codes are stored with indices in the samedirectory. For example, the quiz will take about 2 minutes, and theQR code keeps changing every 5 seconds, so 24 pictures will beshown. In fact, the URLs of QR code are different in that theypass a different variable, which is the “id” appended to the PHPfile, such as “hugh.comp.nus.edu.sg/q2107.php?id=bce53g09”.The “id”s are altered every 5 seconds, received as a variable in thepolling file.The lecturing website and the polling website are synchronizedwith the same question, as the question id is written to a file andread by the polling PHP file in the server. Similarly, we write theURL information of current QR code to some file and read in the“id” variable in the PHP. It will only allow the access if the “id”value is the same in the request, which is of vital importance forvalidation of the QR code.

Figure 9. Html code for Poll QuestAfter students scanning the QR code using their phone, they willbe directed to a URL where they can participate in the questionpolling. The html file will already be loaded to the web browser,containing information needed to transmit the answer as shownabove. Once the students click the “Select your answer, and pressthis button” button, the browser will post the answer value to the“radioButtonAnswer.php” file, which will collect all the data.Therefore, even the URL of the polling website is not valid at themoment, the students can still submit their answers, which allowsthe students to spend adequate time answering the questions.

5. ConclusionAs illustrated above, the BSSID list and QR code method can beused for restricting the access of unauthorized user. At the end thisproject, we realized that the BSSID list can be applied to otherapplications.

For example, case 1-Digital Attendance: by checking the BSSID,signing attendance for a class digitally is an application. Users

access the attendance website and submit their attendance whenthey are physically arrive their working area.

Case 2-confidential meeting: Holding a sensitive project meetingin a common office area is an alternative application. If a webpage containing secret data is supposed to be presented during thatmeeting, by checking the BSSID list, the web page can only beaccessed by those who are in the meeting room.

Case 3-Location tracing: This idea is to give a GPS-likefunctionto a device that is in an area with multiple APs. The database willkeep the BSSID location of the entire building or field. Theapproximate location of a device which has WiFi connection canbe calculated by checking the BSSID list. For example, Figure 10shows the floor plan of NUS COM2-Level 2, assuming there are 4APs which provides the wireless network with SSID “NUS” andeach AP has its own BSSID. If a person can only get the BSSIDof A4, he probably is near the lift. If the building has multiplefloors, the AP allocation will be more complicated which meansthat the location of a person will be calculated more accurately.

Figure 10. Floor plan of NUS COM2-L2

In conclusion, location restricted access control is making use ofBSSID and QR code to perform network access control by eithercomparing the BSSID list of a device to an existing BSSID listthat is stored in a database or scanning the QR code to show thatthe person is physically in the working area. These methods cansolve the security problem of authorizing a user based on hislocation regardless on his previous authentications with the servermaking the systems security more up to date as time goes on.

6. ACKNOWLEDGMENTSOur thanks to Prof.Hugh Anderson for providing us with essentialsuggestions and assistance, making our project progressivelyadvanced .

7. REFERENCES

[1] Margaret R.(n.d.). Network Access Control(NAC). Retrievedfromhttp://searchnetworking.techtarget.com/definition/network-access-control

[2] Denso-Wave. (n.d.). Retrieved fromhttps://archive.today/20120915040047/http://www.qrcode.com/en/qrfeature.html

A1

A2

A3 A4

Page 49: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Phortress – A PHP Static Code Analyser Joel Low Wor On School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

Naomi Leow Wen Xin School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

Tan Wei Lin School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

ABSTRACT Phortress is a static program analyser for PHP. It checks an application for vulnerabilities, such as SQL injections.

CATEGORIES AND SUBJECT DESCRIPTORS F.3.2 [Semantics of Programming Languages]: Program Analysis

GENERAL TERMS Security, Human Factors, Languages, Verification.

KEYWORDS PHP

1. INTRODUCTION PHP is a server-side programming language commonly used to develop web applications. A 2012 survey of 400 web applications found that PHP was used in the development of 63% of them [1], making it the most commonly used language. Among the PHP applications surveyed, critical vulnerabilities such as SQL Injections and OS Command Injections were found in 47% and 28% of applications, respectively [1]. Without a proper testing tool, security flaws in the web application's source code may slip past code reviews and remain undiscovered. As the cost of fixing problems in programs increases with the development of a project, it is important that tools to identify security flaws in program source code are available and integrated into any application testing framework. Therefore, the aim of our project is to develop a sound PHP static code analyser that can determine whether a given application contains vulnerabilities.

2. COMMON VULNERABILITIES 2.1. SQL Injection An SQL injection attack allows an attacker to execute an arbitrary SQL query by embedding his payload within a legitimate query issued by the application. This belongs in the category of the most common vulnerability in web applications [2]. This allows the attacker to gain access to confidential data or tamper with the application's data. SQL injection is possible when user input is concatenated with queries sent to the database without being properly sanitised. An example of code that is vulnerable to SQL injection is shown below: $query = "SELECT grade FROM results WHERE

student_id = '" . $_GET['id'] . "';";

$result = mysql_query($query);

In this example, an attacker could inject an SQL statement with an input like this: ' OR 1 = 1

The resulting query then becomes: SELECT grade FROM results WHERE student_id = ''

OR 1 = 1;

This would allow the attacker to view the grades of all the students stored in the results table, which may not be the intention of the owner of the application. Furthermore, if the user connecting to the database is not configured according to the principle of least privilege, the attacker might be successful in injecting statements that are more malicious. For example, if the application is connecting to the database server with administrative permissions, injections like '; DROP TABLE results

can be successful, allowing an attacker to not only access data he is not privy to, but also successfully launch a denial-of-service.

2.2. Cross-Site Scripting A cross-site scripting (XSS) attack allows an attacker to run a malicious script on a victim's browser when the victim accesses the vulnerable application. Such an attack is possible when the application fails to sanitise data from unreliable sources before displaying it to users. XSS vulnerabilities comprised the third most common source of web application vulnerabilities [2].

2.2.1. Reflected XSS Reflected XSS is possible when the application displays parameters from a HTTP request as part of its response to the request. An attacker could trick an unsuspecting victim into clicking a link, with a malicious script in its parameters, to the vulnerable web application. As the vulnerable application embeds the parameter as part of its response page, the victim's browser executes the malicious script as if it were from the application. The script is therefore able to access the application's cookies, allowing the attacker to obtain the victim's cookies for the application.

2.2.2. Stored XSS Stored XSS is possible when the application stores unsanitised input that is later displayed together with the application's page. Such a vulnerability is typically found in discussion forums, where a user's post may not be sanitised before it is stored in the application's database and displayed. An attacker could make a post containing a malicious script, which will be executed by the browsers of users who view the malicious post.

2.3. OS Command Injection OS Command Injection allows attackers to execute arbitrary commands on the server with the vulnerable application's privileges. This works in a similar manner as an SQL injection. OS

45

Page 50: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

command injection is possible when the application includes unsanitised user inputs in the commands it executes on the system's shell. On servers where web applications are allowed to run with root privileges, this enables the attacker to take complete control of the server.

3. PREVENTIVE MEASURES 3.1. SQL Injection 3.1.1.1. Prepared statements One method used to avoid SQL injection is to make use of prepared statements. In a prepared statement, user input is treated as parameters for the prepared statement, rather than part of the SQL query itself. As such, the values specified in a query never change the semantics of the query, preventing SQL injections if used properly. In PHP, one could use prepared statements properly in the following manner, using named placeholders: $stmt = $dbh->prepare("SELECT grade FROM results

WHERE student_id = :value");

$stmt->bindParam(':value', $_GET['id']);

$stmt->execute();

Using prepared statements has an additional advantage: the query can be executed multiple times using different variables, but the database engine only needs to compile the query once. However, prepared statements alone are not capable of preventing all SQL injections. For example, if the query string in a prepared statement is still constructed by joining strings together instead of binding user input as a parameter, it is still possible for an SQL injection to occur.

3.1.1.2. Placing values in hashes One way to mitigate the risk of SQL injection is to store data affected by user-input queries as hashes. However, this might lead to performance losses as the hashes cannot be indexed and sorted by the database storage engine for quick retrieval. Queries would be modified slightly to become of the following form: $query = "SELECT grade FROM results WHERE

MD5(student_id) = '" . md5($_GET['id']) . "';";

3.1.1.3. SQLMap In addition to taking preventive measures via good coding practices, developers should also perform tests to discover vulnerabilities that may have been unwittingly introduced. There are a number of automatic penetration testing tools that can be used. SQLMap [3] is one such tool that can be run against the web application to allow developers discover holes in the application that are open to SQL Injection attacks. It is able to deduce the SQL server that the application is running on and tailor its attack accordingly. It attempts an attack on the database with six attack methods: Boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries and out-of-band.

3.1.1.4. NoSQL databases A slightly different approach taken by applications built on top of the MongoDB, Express.js, Angular.js, Node.js (MEAN) stack is to dispense with SQL altogether. This does render the application immune to SQL injection attacks. PHP is able to interoperate with MongoDB [4].

3.2. Cross-Site Scripting There are two main approaches to countering cross-site scripting attacks: filtering untrusted inputs based on a blacklist of disallowed HTML tags, and filtering untrusted inputs based on a whitelist of allowed HTML tags.

3.2.1.1. HTML tag blacklisting This involves compiling a list of tags commonly used by attackers to include their payload within the website's Document Object Model (DOM). Commonly blacklisted tags include script and iframe tags. However, attackers can defeat the system by resorting to attack vectors missed by the blacklist or using malformed tags that will resolve to the intended HTML tags after input filtering. For example, the attacker could evade the filter on the <script> tag with a malformed tag like <s<script>cript>. Developers could subsequently add such tags to the blacklist but attackers can easily evade the filter by adding more layers of malformed tags, such as <s<s<script>cript>cript>. The list of tags to be included in the blacklist in order to prevent the inclusion of just the <script> tag alone is infinite. Hence, this approach reduces into an arms race between attackers and website developers and is ultimately ineffective against attacks.

3.2.1.2. HTML tag whitelisting Anything in the input that does not match the whitelist of allowed HTML tags and attributes is filtered away. As far as possible, HTML tags should be excluded from the list unless they are needed for text formatting. This allows developers to restrict allowable input strictly within the boundaries of what is safe. There are libraries available that can be included in a PHP application to aid developers in performing whitelist filtering of inputs. Examples include kses, which uses a user-defined whitelist, and HTML Purifier [5], which has a user-extendable whitelist of its own.

3.3. Analysis Tools 3.3.1. Taint Analysis Taint analysis is a form of information flow analysis [6]. It has been utilised to detect and prevent attacks including SQL Injections, Command Injections and XSS [7]. A variable that has been modified by a user cannot be treated as trustworthy because the user may be a malicious one [8]. Such a variable is said to be tainted, and this taint may be passed to another variable as a result of certain operations, such as assignments. It is possible to sanitise the data so that it is safe by the use of functions that remove potentially malicious content [9]. Static taint analysis follows the information from sources to sinks. Frequently, these are the parts of the program where user input is read and where the user input or something derived from it is used, respectively [10]. This method of analysis is comparatively less accurate and generates more false positives and negatives as compared to dynamic taint analysis. However, its advantages include high code coverage and speed [11]. Dynamic taint analysis is an approach complementary to static taint analysis. It involves changing program inputs and observing the change in outputs from the program at runtime [7] and its advantages and disadvantages are the opposite of those of static taint analysis [11]. As additional runtime information is available in this case, the number of false positives and negatives is reduced. At the same time, a significant number of test cases need to be

46

Page 51: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

generated and run in order to ensure that there is indeed a potential vulnerability [12]. Consequently, work has been done to combine and integrate the two in an attempt to reap the benefits of both techniques. In [12], a direct approach is used: Static taint analysis is used for most of the code, while dynamic analysis is used only in some places to detect vulnerabilities that can only be detected at runtime, such as pointer aliasing, allowing for speed and accuracy where it is needed. Another approach presented in [11] involved the introduction of a Static and Dynamic Combined Framework (SDCF) that integrates static analysis and dynamic taint analysis.

3.3.2. Existing Products

3.3.2.1. RIPS RIPS [13] is a static taint analysis tool for PHP code written in PHP by Johannes Dahse. Its first release was in 2010. The project has been developed further since then, but development on the publicly available version of RIPS has been stopped since Februrary 2013, pending a complete rewrite of the source code. One significant limitation of RIPS, as of version 0.5, is the lack of support for Object-Oriented Programming (OOP) in PHP. This is significant because the majority of web applications written in PHP today are written in the OOP style.

3.3.2.2. Pixy Pixy is a open source static PHP code analysis tool written in Java [14]. Pixy was last updated by its original developers in 2007, hence the latest PHP 5 features are not supported by the original release of Pixy. Unlike many PHP code analysis tools available, Pixy provides good support for analysing code with aliases. However, Pixy is only able to detect SQL injection and XSS vulnerabilities. A fork of Pixy has since been created to support PHP 5 code [15]. However, beyond support for source code in PHP 5, few additional features have been added due to the complexities involved in entending the original code base. Hence, although this fork of Pixy is able to work with PHP 5 code, its analysis of OOP code is incomplete.

3.3.2.3. WebSSARI WebSSARI is a tool that is able to do both static and dynamic analysis of a web application built in PHP [16]. The tool applies intraprocedural type-based flow analysis to identify vulnerabilities. One limitation therefore is a high rate of false positives due to the lack of interprocedural contextual information. WebSSARI has since been adapted as the commercial application CodeSecure. Its source code is hence not available for further development by the academic or open-source communities.

3.3.2.4. WhiteHat Sentinel Source WhiteHat Sentinel Source [17] is a Software-as-a-Service static PHP source code analysis tool. It is able to test code for vulnerabilities listed in the WASC Threat Classification list. Like WebSSARI, it is not easily available for analysis and comparison against other vulnerability analysis tools. It is not clear what methods are used in its code testing.

4. IMPLEMENTATION While all the tools presented in section 3.3.2 perform static code analysis, they tend to lack support for new language features, and are no longer maintained. Phortress attempts to provide an easily extensible framework for implementing program analyses, to allow

programs utilising new language features to be verified. This is important as language features improve programmer productivity and security tools should evolve as quickly as the rest of the language’s ecosystem.

4.1. Major Differences 4.1.1. Metacircularity There are existing products that perform static analysis on PHP code; however, few are implemented in PHP itself. This presents problems: PHP is an evolving language with new language features being implemented in the core language even with a minor release [18]. This means that any such tools will be limited in its ability to audit codebases which use new language features. Other projects that are written in PHP, such as RIPS, have a built-in parser and need to be updated every time a new language feature is implemented. Furthermore, having a built-in parser would most likely result in language features not being properly implemented, with the consequent program differing in semantics when run and when it is analysed. Phortress is written in PHP itself. The PHP source code is parsed using an open-source PHP parser [19]. This is the principle of separation of concerns, as practiced in software engineering. This property allows new language features to be implemented in Phortress rapidly.

4.1.2. Extensibility Phortress has been designed from the onset to be extensible. Static analysis tools tend to be designed for a programming language directly, without regard for potential libraries that can be used on top of the language. This is problematic for modern web applications because applications no longer tend to be written purely relying only on the language runtime: most are built on top of Web application frameworks instead. These frameworks tend to come with libraries that provide functionality for SQL sanitisation and HTML sanitisation as part of the database abstraction layer and template rendering engine. Calls to these functions should be assumed never to cause a security vulnerability, unless one is performing an analysis on the framework itself. This reduces the amount of noise reported to the user, and such vulnerabilities in the application itself are less likely to be missed by the programmer. Existing code analysis tools allow whitelisting, however that is a blunt tool since no other information can be provided by library maintainers that can assist the analyser. In the implementation presented in this paper, Phortress does not come with predefined analyses for any PHP frameworks; however, framework support can be implemented without needing to modify Phortress itself, owing to Phortress’ application architecture.

47

Page 52: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

4.2. Architecture

User Phortress Driver PHP Parser Dephenses

Figure 1: Phortress Architecture Diagram

Phortress can be broken down into three major components: 1. The Phortress Driver. This is the front-end that is visible

to the user. This also contains the logic needed to process syntax trees for identifier resolution.

2. PHP Parser. The Driver will pass files to the Parser to obtain a syntax tree of the given source file. PHP source files can include other source files, and as such, the parse process is recursive. After all includes have been processed, environment information is computed from the parse tree for identifier resolution.

3. Dephenses. This is the heart of the program analysis engine. Dephenses are individual verifications which check for vulnerabilities using a particular analysis method. Dephenses might have provisions for extensibility, such as taking in a list of functions which perform input sanitisation from various application frameworks.

This architecture allows new analyses to be implemented, without concerning itself over language semantics.

4.3. Lexical Analysis Being written in PHP, Lexical Analysis can be done using PHP’s built-in lexer [20]. The PHP Parser used by Phortress uses the built-in lexer by default, with a fall back lexer for use when the PHP version Phortress is run on is older than the target version of the PHP code being analysed. Metacircularity allows this property, giving greater guarantees about the accuracy of the parse tree generated from the program being analysed.

4.4. Syntax Analysis The input program is given to the PHP Parser to convert to a parse tree. At the time of writing, the parser is compatible with PHP 5.6 language features [19].

4.5. Language Semantic Analysis 4.5.1. Dependency Inclusion Because PHP include and require directives accept expressions, it is possible that an include or require directive might include a function call, which would require expression evaluation. Being a static analyser, it is not possible for Phortress to resolve all includes. However, this can be implemented in future releases with relative ease because of metacircularity.

1 Superglobals are variables defined in the global namespace, which

do not need to be qualified with the global keyword, and can be used in any function.

After the included file has been parsed, the node in the syntax tree representing the include/require directive is replaced with the parse tree of the included file. This process is repeated until all includes have been evaluated.

4.5.2. Environment Model PHP has a unique environment model that makes identifier resolution non-trivial [21]:

1. Variables are only available for use after they have been assigned. After assignment, they are visible only within the current scope. Functions cannot access variables from the outer scope, unless using the global keyword or the $_GLOBALS superglobal1.

2. Variables can be unset later in the function, causing the variable to be unbound.

3. In a namespace, constants, classes, variables, and functions can given the same identifier.

4. PHP functions are case insensitive. All other identifiers are case sensitive.

5. Lambdas can be declared in functions, however they can capture values from the function the lambda is declared in.

As such, Phortress includes an implementation of an environment with access links, a design outlined in [22]:

1. Environments are mappings of symbols to its actual values: functions, constants, or variables.

2. Environments can be chained for use in nested environments (namespaces, function scopes or closures); this is similar to the access link mentioned in [22].

3. Phortress implements Environments in an object-oriented manner, with different kinds of environments implemented as subclasses of the base Environment type. Figure 2 (below) illustrates the organisation of the different kinds of environments.

The base Environment class only handles with variables and constants. The NamespaceEnvironment class handles environments with classes and other namespaces, as well as the GlobalEnvironment class that deals with superglobals and global constants. These correspond to the valid locations of class and namespace definitions. Functions and namespaces are accessible anywhere in the parse tree. For this reason, they are not stored in our environment mapping; instead, it is searched whenever we look for one. Constants using define are available only when they have been evaluated and is dependent on 'program order.' Parse-time constants are available at any time. Variables act similarly to constants; however, where constants are accessible from any scope after they have been defined, variables can only be accessed inside the local environment. Globals need to be accessed with global $var or using superglobals. For this reason, what is accessible in an environment can change as the program is executed, even within the same scope. To represent this in a static analyser, one can duplicate environments for every statement. This is a waste of space, as such, in Phortress environments are represented as chains of immutable

48

Page 53: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

environments. This allows us to preserve the behaviour that variables are undeclared until they have been evaluated. Furthermore, when a variable has been unset(), a dummy value is placed in the environment to indicate that the identifier is no longer bound. There is also the concern of superglobals. Because PHP functions cannot access global variables unless using the $_GLOBALS or global keyword, all functions start out with an empty environment. The only variables bound at the start of the function are the superglobals, which are pointing by reference to the global environment's entry, as well as the function’s arguments. The next level of complexity arises from lambdas. Lambdas are able to capture a variable either by value or by reference. A closure is not formed in the normal sense. In this case, a new environment is created, with the variable captured copied by value or by reference, depending on the capture, and included in the initial environment of the closure. Lambda support is incomplete in this version of Phortress.

4.6. Program Analysis Program Analysis is performed by Dephenses. Currently, only one analyser has been implemented. Nevertheless, Phortress can be easily be extended in future with other analysers due to its architecture.

4.6.1. Taint Analysis The abstract syntax tree of the program is traversed and the variables encountered are annotated based on information about their environment made available by the Phortress Driver. The possible taint annotations are:

1. Unassigned: Indicates that the value has yet to be assigned a value.

2 https://github.com/lowjoel/phortress

2. Safe: Indicates that the variable does not hold values based on unsanitised input.

3. Tainted: Indicates that the value assigned to the variable is dependent on unsanitised input.

4. Unknown: It is uncertain whether the value the variable hold is dependent on unsanitised input.

This Dephense maintains a blacklist of functions that send queries to the application database, execute commands on the server's shell or writes to an output source. This blacklist currently only contains functions from within the PHP Standard Library. When a blacklisted function is encountered, the taint values of the arguments to the function are checked. If a tainted variable is found among the function's arguments, the particular invocation will be flagged as vulnerable. The vulnerabilities found are classified by the vulnerability type. The environment of the tainted variables is included in the description of each vulnerability found. The following types of vulnerabilities can be identified via Taint Analysis:

1. SQL Injection 2. Cross Site Scripting 3. OS Command Injection 4. Remote File Inclusion

4.7. Availability Phortress is an open-source project, licensed under the MIT License. The source code can be found on GitHub2.

4.8. Limitations While Phortress beings about a new approach in designing static program analysers, the authors of this paper have not been able to successfully improve on the reliability of the analysis. New

Environment

+ resolveClass

NamespaceEnvironment

# namespaces

ClassEnvironment FunctionEnvironment

GlobalEnvironmentNamespaceContinuation

+ resolveNamespace+ resolveVariable+ resolveFunction

# variables

# classes

<<Trait>>

EnvironmentHasFunctions

- functions

# parent

Figure 2: Environment Class Hierarchy

49

Page 54: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

language features in PHP have made data flow graphs insufficient for determining the values of variables at run-time through the following language constructs:

1. Object-Oriented Programming. OOP introduces late binding to function calls to allow ad-hoc polymorphism. This complicates control flow analysis and thus data flow analysis. One possible solution is to check all possible overrides for a given method; however, a missing class definition would cause the analysis to be incomplete.

2. Exception handling. Exception handling allows an object to be thrown and caught at different places, depending on the function call stack. The contents of the exception can be tainted in different ways.

5. FUTURE WORK Phortress was inspired by the Rails Security Analyser tool Brakeman [23]. In addition to static code analysis, Brakeman also checks the dependencies of web applications for vulnerabilities. PHP now has Composer [24], which serves the same function as Bundler for Ruby applications. Phortress should emulate Brakeman, and check that the dependencies that applications use are secure. This would help prevent one of the top ten most common sources of application vulnerabilities [2]. There has also been work to standardise the file system structure of PHP Applications and frameworks [25]. Composer uses this structure, but PHP does not natively support this structure yet. This relies on applications to implement an autoloader function [26]. Since file includes are resolved at runtime, static code analysers would need to implement the same standard, or fall back to directly interpreting such autoloader functions. The current implementation of Phortress only supports static analysis; however, as pointed out in section 3.3.1, dynamic analysis complements static program analysis. Phortress can be extended to implement such functionality. Finally, in addition to running data flow analysis on the input program, Phortress should support control flow analysis, including exceptions and late binding of functions. This would allow Phortress to support the new language features introduced in PHP 5.

6. ACKNOWLEDGEMENTS The authors of this paper would like to thank A/Prof Hugh Anderson for his guidance and support during this project, as well as to A/Prof Khoo Siau Cheng who has provided his experience in program analysis.

7. REFERENCES 1 POSITIVE TECHNOLOGIES. Web Application

Vulnerability Statistics for 2010-2011. 2012.

2 OWASP FOUNDATION. Top 10 2013-Top 10. 2014. Retrieved November 6, 2014 from https://www.owasp.org/index.php/Top_10_2013-Top_10

3 Damele, Bernardo A. G. and Stampar, Miroslav. sqlmap: Automatic Database Injection and Takeover Tool. Retrieved November 7, 2014 from http://sqlmap.org/

4 THE PHP GROUP. PHP: MongoDB. Retrieved November 7, 2014 from http://php.net/manual/en/class.mongodb.php

5 Yang, Justin E. HTML Purifier. Retrieved November 6, 2014 from http://htmlpurifier.org/

6 Jones, Neil D. and Muchnick, Steven S. Program Flow Analysis: Theory and Application. Prentice Hall Professional Technical Reference, 1981.

7 Clause, James, Li, Wanchun, and Orso, Alessandro. Dytan: A Generic Dynamic Taint Analysis Framework. Georgia Institute of Technology, 2007.

8 Caera, Dumitru. Detecting Software Vulnerabilities Static Taint Analysis. 2009.

9 Schwartz, Edward J., Avgerinos, Thanassis, and Brumley, David. All You Ever Wanted to Know About Dynamic Taint Analysis and Forward Symbolic Execution (but might have been afraid to ask). In Proceedings of the 2010 IEEE Symposium on Security and Privacy (Oakland 2010).

10 Haldar, V., Chandra, D., and Franz, M. Dynamic Taint Propagation for Java. In Computer Security Applications Conference (Tucson 2005).

11 Zhang, Ruoyu, Huang, Shiqiu, Qi, Zhengwei, and Haibing, Guan. Static Program Analysis Assisted Dynamic Taint Tracking for Software Vulnerability Discovery. Journal of Computers & Mathematics with Applications, 63, 2 (January 2012), 469-480.

12 Aggarwal, A. and Jalote, P. Integrating Static and Dynamic Analysis for Detecting Vulnerabilities. In International Computer Software and Applications Conference (Chicago 2006), 343-350.

13 Dahse, Johannes. RIPS - A static source code analyser for vulnerabilities in PHP scripts. 2011. Retrieved November 6, 2014 from http://rips-scanner.sourceforge.net

14 Jovanovic, Nenad, Kruegel, Christopher, and Kirda, Engin. Pixy: A Static Analysis Tool for Detecting Web Application Vulnerabilities. In IEEE Symposium on Security and Privacy (Oakland 2006), 258-263.

15 Klee, Oliver. Pixy: Tainted Object Propagation Analysis for PHP 5. Retrieved November 7, 2014 from https://github.com/oliverklee/pixy

16 Huang, Yao-Wen and al, et. Security Web Application Code by Static Analysis and Runtime Protection. In International Conference on World Wide Web (New York 2004).

17 WHITE HAT SECURITY. Find Vulnerabilities in Source Code: Sentinel Source. Retrieved November 6, 2014 from https://www.whitehatsec.com/sentinel_services/sentinelSource-development.html

18 THE PHP GROUP. Migrating from PHP 5.5.x to PHP 5.6.x. Retrieved November 6, 2014 from http://php.net/manual/en/migration56.php

19 Popov, Nikita. PHP Parser. Retrieved November 6, 2014 from https://github.com/nikic/PHP-Parser

20 THE PHP GROUP. token_get_all. Retrieved November 6, 2014 from http://php.net/manual/en/function.token-get-all.php

21 THE PHP GROUP. PHP: Language Reference. Retrieved November 7, 2014 from http://php.net/manual/en/langref.php

50

Page 55: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

22 Aho, Alfred V., Lam, Monica S., Sethi, Ravi, and Ullman, Jeffrey D. Compilers: Principles, Techniques & Tools. Addison Wesley, 2006.

23 Collins, Justin. Brakeman - Rails Security Scanner. Retrieved November 6, 2014 from http://brakemanscanner.org/

24 Adermann, Nils and Boggiano, Jordi. Composer: Dependency Manager for PHP. Retrieved November 7, 2014 from https://getcomposer.org/

25 PHP FRAMEWORK INTEROP GROUP. PSR-4: Autoloader. Retrieved November 7, 2014 from http://www.php-fig.org/psr/psr-4/

26 PHP FRAMEWORK INTEROP GROUP. Example Implementations of PSR-4. Retrieved from https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md

51

Page 56: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

52

Page 57: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Comparing OS Security Clement Chong DeZhi, Lui YuYao, Teo ZhengLe, Tan WeiJie

School of Computing, National University of Singapore 21 Lower Kent Ridge Road, Singapore 119077

ABSTRACT In this paper, we explore and compare security techniques used in different operating systems - Windows, Linux and Mac OS X

Categories and Subject Descriptors D.4.6 [Security and protection]

General Terms Security, Theory

Keywords Operating Systems, security, Windows, Linux, Mac OS X, access control, memory protection, buffer overflow, ASLR, DEP

INTRODUCTION Security is not perceived as a benefit and regarded as an impediment to the system until something goes wrong. In this paper, we aim to probe the security techniques used between three operating systems (OS) - Windows, Linux and Mac OS. This paper comprises of 3 main sections - Memory Protection, File Protection and Password Security. In each section, it contains several techniques that will be explained, analyzed and compared between the three operating systems.

2. MEMORY PROTECTION

2.1 Address Space Layout Randomization ASLR is a operating system security technique involved in making the memory address less predictable from buffer overflow attacks. It renders exploits which depend on pre-allocated memory addresses which is useless by randomizing the layout of the virtual memory address space. This includes the base addresses of stack, heap, code segment and libraries in the process’s address space.

2.1.1 Windows ASLR was first introduced in Windows Vista and was also included in all the later versions. Upon system startup, core processes are loaded into the predictable or known memory locations in all the versions before Windows Vista. Most attacks work by attacking memory locations which are bind with particular processes. With ASLR, it randomizes the memory locations, making it much difficult and tedious for an attacker to correctly predict the location of a given process. In the implementation, programs or executable files must be compiled using the ASLR flag provided by Visual C++ linker, only then will the randomization take place during program runtime, and address of shell code will be randomly allocated during startup. If an executable image has not been complied with the flag, the Windows kernel will attempt to load the image at its preferred base address. This can cause the image to be

loaded at a predictable memory location and it leads to real world exploits for software vulnerabilities. To resolve this issue, an application running on Windows can choose to enable a feature known as Force ASLR [1]. When this feature is enabled, it forces all executable images to be randomized in the application when loaded, including those disabled images. This was to prevent executable images at a predictable location from loading in the memory.

2.1.2 Linux ASLR can help to prevent the common types of buffer overflow attacks. Linux implement ASLR with the help of the PaX patches. ASLR can locate the heap, base, libraries and stack at randomized address space of the process’s, which makes it difficult for an attacker to predict the memory address of the next instruction. ASLR is built and embedded into the Linux kernel and is controlled by the parameter /proc/sys/kernel/randomize_va_space. The randomize_va_space parameter can take the following values “Seccomp” - abbreviation for secure computing mode, is a sandboxing mechanism in the Linux kernel used for minimizing the exposed kernel surface [11]. When seccomp is being enabled, the process is reduced into “secure mode” where only a minimal type of systems calls such as exit(), read() or write() are available. These system calls are only made applicable to files that had been initialized during bootup by the process. By limiting the type of system calls available for a process, it isolate the system’s resources from it. Should an attacker uses these process and attempt to make any other system calls, the kernel will terminate the process immediately via “SIGKILL”. Seccomp-BPF which is an extension to Seccomp, can be used to allow or deny a system calls that are not originally being granted for a given process. Instead of simply terminating the process, Seccomp-BPF will notify the user, thus allowing the user to make the necessary changes. 0 : Disable ASLR. This setting is applied if the kernel is booted with the norandmaps boot parameter. 1 : Randomize the positions of the stack, virtual dynamic shared object (VDSO) page, and shared memory regions. The base address of the data segment is located immediately after the end of the executable code segment. 2 : This is the default setting. Randomize the positions of the stack, VDSO page, shared memory regions, and the data segment.

2.1.3 MAC OS ASLR is designed for memory addresses to be less predictable from attackers. In Mac OS X, ASLR uses the large 64-bit memory space to place executable code, related programming constructs and

53

Page 58: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

system libraries in randomized locations for Position Independent Execution (PIE) [3]. This is likely to reduce the risk of the exploits of memory attacks, such as “return to libc” and “shellcode”. In addition, to mitigate that risk, Mac OS X randomly relocates the system frameworks, kernel and kexts at system boot. This memory protection is compatible to both 32-bit and 64-bit processes.

2.1.4 Comparison Analysis Based on the analysis, ASLR is commonly used in most OS to prevent potential attacker to predict the memory address space of each instruction set.ASLR in Linux is dynamically randomized for each process. While Windows processes are randomized at system boot and Mac OS X libraries are randomized when system or applications are updated and compiled with ASLR support. In addition, the address of shared libraries from Linux are randomly allocated. However, the address of program image is not as it will add runtime overhead and reduce the OS performance [4]. Conversely, Windows is able to randomize both program images and libraries without reducing the OS performance, but only apply modules marked as ASLR-safe when compiled. In addition, ASLR is not enabled by default in Windows unlike Linux and Mac OS. In Windows, applications either have to be set to use the features by their developers or the user has to set the system to use them. Some programs opt-in, some don't.

2.2 NX NX classifies different sections of memory as either "executable" or "non-executable", and thus disallows execution of code in non-executable sections such as stack and heap. This technique is implemented via both hardware and software level. An attempt to execute code in non-executable memory locations will result in an exception or fault being raised. Although by marking the stack as ‘non-executable’, operating system can effectively prevent malicious code running in the stack, this however does not prevent stack from modification should buffer overflow happens. Furthermore, with the absence of ASLR, a return-to-libc attack is capable to turn off the NX feature [5]. Hence, ASLR are often used in conjunction with NX for maximum protection in modern operating systems.

2.2.1 Windows Microsoft’s implementation of NX is called Data Execution Prevention (DEP). Windows XP Service Pack 2 was the first version of Windows that came with DEP implemented on x86 architecture. In Windows 8 and above, to further enlarge the address space thus ensure the security in Windows, the NX feature, along with Physical Address Extension (PAE), has become a hardware requirement for the OS installation [6].

2.2.2 Linux Currently, almost all Linux distributions such as Fedora and Ubuntu have their kernel support NX bit on x86 and x86-64 processors. It is the ExecShield patch in Fedora and Ubuntu that allows Linux to emulate NX. Debian however does not include ExecShield patch and thus does not by default provide NX in its kernel [7].

2.2.3 MAC OS Historically, (Berkeley Software Distribution) BSD systems always X) is the implementation of NX in OpenBSD in which a memory page is either writable or executable, but not both at the same time. Mac OS X, with certain parts of it built upon BSD, naturally supports NX protection. Mac OS X 10.4 and earlier versions only support NX stack protection. In Mac OS X 10.5 and above, stack and heap are both protected as non-executable.

2.2.4 Comparison Analysis Nowadays, all modern operating systems have included NX protection as their basic counter measure to memory attacks such as shellcode injection attack. Nonetheless, NX does come with cost because it may break incompatible applications or introduce overheads in performance [8]. Windows 7 unfortunately only enforces NX for its libraries and binaries which are NX compatible. Third-party softwares like Oracle’s Java JRE and Adobe Reader need to explicitly opt-in to NX [9]. In Contrast, Mac OS X and ExecShield patched Linux have their NX turned on by default.

3. FILE PROTECTION

3.1 Sandbox Sandbox is a security mechanism for isolating executable programs. It creates a boundary which limit the the number of resources that the programs can access to. Programs that are not being sandboxed gain equal permissions of the user, thus gaining access to all user-accessible system resources. If the attacker able to take control of the program, he gains the ability to do anything that the user can do. Sandboxing technology is also used to test suspected malicious programs with wide-ranging potential to inflict harm, without putting the host device at risk of being attacked. It is often used to execute untested code, or untrusted programs from unverified third parties, suppliers, untrusted users and untrusted websites.

3.1.1 Windows Sandboxes that are enforced by the latest Operating System - Windows 8, are referred as “AppContainer”, which is an improvised feature of “Integrity levels” which was introduced in Windows Vista.

AppContainer is considered as an untrusted integrity, that's even lower than low integrity level. By default, it blocks both reads and write as well. When each program is installed, the system analyze the resources (library access, network access...etc) that the program need and devise a newly created unique AppContainer security identifier. When the program is being executed, the AppContainer integrity level and security identifier is being applied [10]. Based on the security identifier, Windows will then determine whether the various operations should be executed. For example, if the security identifier indicates that the program has full privileges to a particular folder, the system will allow the program to access files in that folder.

54

Page 59: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

As such, “AppContainer” only allows the program to access limited number of files in the system, thus restricting the damage being done by the attacker should a malicious attack is made.

3.1.2 Linux “Seccomp” - abbreviation for secure computing mode, is a sandboxing mechanism in the Linux kernel used for minimizing the exposed kernel surface [11]. When Seccomp is being enabled, the process is reduced into “secure mode” where only a minimal type of systems calls such as exit(), read() or write() are available. These system calls are only made applicable to files that had been initialized during boot up by the process. By limiting the type of system calls available for a process, it isolate the system’s resources from it. Should an attacker uses these process and attempt to make any other system calls, the kernel will terminate the process immediately via “SIGKILL”. Seccomp-BPF which is an extension to seccomp, can be used to allow or deny a system calls that are not originally being granted for a given process. Instead of simply terminating the process, Seccomp-BPF will notify the user, thus allowing the user to make the necessary changes.

3.1.3 MAC OS

Figure 1 [12] Mac OS introduced “App Sandbox” which is enforced at the kernel level to enable any application to be sandboxed. It does the following: 1. App Sandbox allows the user to define the functionality of the application, thus enabling the system to allocate minimal set of privileges that it requires 2. App Sandbox allows the user the capability to grant the application additional access. Once the application is being sandboxed, the system create a directory called “container” which stores the files that the application uses only - databases, caches, and other app-specific data. The directory is kept hidden, therefore, user are not able to access it. The application has full access to read/write of any files that is stored in the directory. “Powerbox” is used to enable the application to gain access to files that are not within the container. The advantage of using “Powerbox” is that it is not programmatically structured. As such, the attacker is unable to gain control of the “Powerbox” to access the file system. When a user wishes to allow the application to access to a particular file outside the container, he/she uses the Open and Save dialogs via “Powerbox”. The system then includes the absolute path of the file to the application sandbox, thus enabling the application to gain full access of the file.

The negative aspect of the above is that once the application is exploited by malicious code, the security of the file is being compromised.

3.1.4 Comparison Analysis While these operating systems aim to isolate the system’s resources from their running process/application, different form of sandbox mechanisms are being used. Linux utilize system calls filtering to limit the type of system calls made available for a given process. Windows, on the other hand, utilize integrity level and security identifier as an indication for the system to determine whether the requested resources by a program should be granted while Mac OS create a limitation boundary around the application that allows the application to have full rights to files that are within its boundary only.

In a nutshell, though comprehensive enough, windows adopt a weaker approach instead. For example, the Internet Explorer are not sandboxed with “AppContainer” as most plugins and extensions are unable to function properly in such a restricted environment. Unlike Linux and Mac OS, which able to dynamically loosen the restrictions of a sandboxed process, windows had to raise its integrity level so as to allow the process to function properly.

3.2 Access Control Mechanism Access control mechanisms (ACM) play a critical role in protecting operating systems from malicious attacks. It is an integral part of system security which include authorization, authentication and accountability of an entity who tries to gain access to certain resources or files. It is used to preserve 3 aspects of Information Security: Confidentiality, Integrity and Availability. Most operating systems uses a common mechanism call Access Control List (ACL). In this paper, we will describe the respective mechanisms which are only found in each specific operating system.

3.2.1 Windows

3.2.1.1 Mandatory Integrity Control (MIC) Windows uses 4 integrity levels - low, medium, high and system, to evaluate access. Each user and objects will be tagged with an integrity SID - a label which determines the level of access. Windows ensures that all an entity with a low integrity level is unable to access to an object which has a higher integrity level even if that object allows write access to the entity. In other words, to be able to modify the object, the integrity level of the subject must be either equal or greater than the object’s level. When a user attempts to launch an executable file, the integrity level of the process is taken to be the minimum of the user integrity level and the file integrity level. As such, when an administrator with high integrity level executes a low integrity program, the process adopted an integrity SID at low integrity level. If the attacker gain control of the program, the low integrity level of the program restricted his ability to inflict damage to the system.

55

Page 60: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.2.1.2 User Account Control (UAC) UAC aims to notify the user when program that are being executed perform a change that requires administrator-level permission. This help to prevent malicious program from compromising the operating system when the administrator or user that receive administrative privileges unknowingly execute it. UAC works by constantly adjusting the permission level of the user account. If the user is doing typical tasks such as browsing the web or creating documents, then the system allocate the user permissions that are of a standard user even though he is being logged on as an administrator. If the user wishes to grant permission to a program, the system temporarily restore the user administrator rights to complete the task. After which, the permissions are being reverted back as a standard user. This is because even though the user is being logged on as an administrator, malicious process are unable to run without the user’s consent.

3.2.2 Linux

3.2.2.1 Security-Enhanced Linux (SELinux) SELinux is a mandatory access control (MAC) security mechanism implemented in the kernel. Unlike Windows, SELinux does not have the concept of a root user. SELinux defines the access rights of users, files and applications on the system. All security-relevant interactions between entities on the system are hooked by LSM before passing to the SELinux module and consulting its security policy to permit the particular operation. SELinux controls the interactions of these entities using a security policy configured by the system administrator. When an entity attempt to access a particular file, the system kernel will check the access vector cache (AVC), where all the subject and object permissions are being cached. If to no avail, the request will proceed to the security server, which look up the security context of the application, which was applied from the kernel’s installed policy.

Figure 2 [13]

3.2.2.2 Application Armor (AppArmor) AppArmor was designed as an alternative to SELinux and serve as a substitute as the traditional Unix DAC model. It allows the administrator to hook each program with a security profile that restricts the capabilities of that program. AppArmor and is

implemented using the Linux Security Modules (LSM) interface as described below.

3.2.2.3 Linux Security Modules (LSM) Linux Security Modules (LSM) aim at separating the kernel from security features. It does not provide any form of security but instead adds security fields to the kernel. Similar to interception system calls, LSM hooks, provided by LSM Module, are placed just ahead of the access (shown below) to control operations on kernel objects and security fields in kernel data structures. The module will then examine and decide whether should the access occur or deny.

3.2.3 MAC OS

3.2.3.1 Mandatory Access Control (MAC) MAC enforce restrictions on access to system resources (such as networking, file systems, and process execution) so that resources are only made available to processes that are explicitly granted access. Mandatory access controls are integrated with the exec system service to prevent the unauthorized applications from being executed. In addition, Mandatory access controls restrict sandboxed application to access system resources, even though the process are running as root.

3.2.4 Comparison Analysis Different operating system adopted different form of access control mechanism. Unlike Linux, Windows and MAC OS do not modified its kernel to implement their respective access control mechanism. As mention, SELinux automatically defines the access and transition rights of every user, files, application and processes on the system. However, mechanisms being implemented by Windows and MAC do allow user interaction with the system,

56

Page 61: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

which in turn place a significant risk of being attacked as well. Access control mechanism are not able to authenticate the “real” user. As such, an attacker who gain administrative privileges are still able to conduct malicious activity. Linux, on the other hand, do not require the permission of the user to access its resources. They are done automatically in the kernel.

4. PASSWORD SECURITY While access control lists limits and determines accessibility of objects by users, passwords ensure the security and confidentiality of data. Most modern OS ensure that the user meets certain password requirements such as including a combination of numbers, symbols and lower and upper case letters [14]. While this helps reduce the likelihood of a hacker to decipher your password, choosing a secure password and keeping it secret is the limit of what a user can do to protect themselves. It is then up to the OS to store the passwords securely and to ensure that in the case of a security breach, the attacker will not be able to decipher the passwords. This is where hashing and salting can be particularly effective.

4.1 Windows Windows stores its passwords in the Security Accounts Manager (SAM) database which can be found in C:\WINDOWS\System32\Config. The file is strictly accessible only to administrators that can run processes as NT AUTHORITY\SYSTEM. The hashing algorithm used are LM or NTLM. The LM hash is a relatively weak cryptographic one-way function which uses password to compute the LM hash. As such, it is easily exploitable by attackers. In an effort to improve security against offline attacks, Microsoft also introduced SYSKEY which allows encryption of the database so that the password hash values stores in SAM are encrypted with a key [15].

4.2 Linux Account information are stored in the /etc/password folder in which information such as Username, Password (encrypted or an x if shadow passwords are used), User ID (UID) ,Group ID(GID) , GECOS field for additional information, path of Home directory and the shell used. For Linux systems that uses shadow password format, the password are encrypted and stored in the /etc/shadow which can be read only by privileged users. The form of encryption used varies depending on the id specified in the crypt() function. The key used for encryption is the password keyed by the user. If the id starts with:

$1$: it uses MD5. $5$: it uses SHA-256. $6$: it uses SHA-512. Otherwise it uses DES

4.3 Mac OS Although the underlying infrastructure of Mac OS X is UNIX BSD, there are several differences between Mac OS X and traditional UNIX-based systems in terms of password security. While most UNIX variants store their password hashes in /etc/shadow, Mac OS X stores its password hashes in /var/db/shadow/hash/. In Mac OS X, every user has their own

individual shadow file stored in a .plist file located in /var/db/dslocal/nodes/Default/users/username.plist

From the file, we derived that the hash algorithm used is SALTED-SHA512-PBKDF2 which is a considerably strong hash. (We discovered this on a fully patched Mac OS X Yosemite on 31/10/2014)

4.4 Comparison Analysis When comparing techniques used in Windows and Linux. One difference is in the use of salt in its hashing mechanism. Unlike Windows, Linux and Mac OS password hashing algorithms uses salt which adds an additional layer of security and making it difficult for an attacker to decipher the password. As mentioned earlier, LM hashes are relatively weak and can be cracked easily without the use of a computer as compared to the hashing algorithms used in Linux excluding DES. However, due to the advancement in technology, these hashing algorithms can be decrypted easily using online cracker databases.

5. CONCLUSION AND FUTURE WORK We have looked at the various security techniques used in the three different OS especially in the areas of Memory Protection, File Protection and Password Security. In the area of memory protection, all three operating system are similar in the way it uses NX bit for marking non-executable areas such as stack. While there were differences in implementation among the different operating systems, all three OS implements ASLR and DEP to protect against memory attacks. In terms of sandboxing, Windows has adopted a weaker approach compared to Linux and Mac OS. While Windows has to raise its integrity level to allow certain processes to function properly, Linux and Mac OS are able to dynamically loosen the restrictions of sandboxed processes. Furthermore, as compared to Linux and Mac OS, Windows password hashing algorithm does not utilise salt. As such the hashes generated are relatively weaker. In comparing access control, while the techniques used to maintain access control among different users varies in the different OS, it achieves the same purpose in limiting the access of users on the system. No matter how it is implemented, it ultimately boils down to how complex it is to set them correctly. If ACL is not set correctly, there will always be security holes. It is evident from our comparison analysis that Windows OS is slightly weaker in terms of security techniques used to protect the system when comparing with Linux and Mac OS. Moreover, due to the open source nature of Linux OS, this allows security patches, fixes as well as new techniques to be implemented quickly as compared to Windows and Mac OS.

In this project, we are focusing on three areas namely memory protection, file protection and password security. For future work, we will be looking into going in depth in the areas of maintaining system integrity, authentication and authorisation techniques.

1. REFERENCES [1] Matt Miller. 2013. Software defense: mitigating common

exploitation techniques. Retrieved from http://blogs.technet.com/b/srd/archive/2013/12/11/software-defense-mitigating-common-exploitation-techniques.aspx

57

Page 62: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

[2] Oracle. August 2014. Oracle® Linux Security Guide for Release 6. Retrieved from http://docs.oracle.com/cd/E37670_01/E36387/E36387.pdf

[3] Apple Inc. June 2012. OS X Mountain Lion Core Technologies Overview. Retrieved from http://movies.apple.com/media/us/osx/2012/docs/OSX_MountainLion_Core_Technologies_Overview.pdf

[4] Edward J. Schwartz. The Danger of Unrandomized Code. Retrieved from https://www.usenix.org/system/files/login/articles/105516-Schwartz.pdf

[5] contex. Bypassing non-executable-stack during exploitation using return-to-libc. Retreived from http://www.infosecwriters.com/text_resources/pdf/return-to-libc.pdf

[6] Microsoft. October 2013. PAE/NX/SSE2 Support Requirement Guide for Windows 8. Retrieved from http://technet.microsoft.com/en-us/library/dn482072.aspx

[7] Edward J. Schwartz, Thanassis Avgerinos and David Brumley. 2011. Q: Exploit Hardening Made Easy. Retrieved from http://users.ece.cmu.edu/~ejschwar/papers/usenix11.pdf

[8] NSA Systems and Network Analysis Center Information Assurance Directorate. 2007. Data Execution Prevention (DEP). Retrieved from

https://www.nsa.gov/ia/_files/factsheets/i733-tr-043r-2007.pdf

[9] Alin Rad Pop. June 2010. DEP/ASLR Implementation Progress in Popular Third-party Windows Applications. Retrieved from http://secunia.com/gfx/pdf/DEP_ASLR_2010_paper.pdf

[10] Peter Bright. October 2012. Better on the inside: under the hood of Windows 8. Retrieved from http://arstechnica.com/information-technology/2012/10/better-on-the-inside-under-the-hood-of-windows-8/

[11] Mozilla Wiki. Security/Sandbox/Seccomp. Retrieved from https://wiki.mozilla.org/Security/Sandbox/Seccomp

[12] Apple Inc. App Sandbox Design Guide. Retrieved from https://developer.apple.com/library/mac/documentation/Security/Conceptual/AppSandboxDesignGuide/AboutAppSandbox/AboutAppSandbox.html

[13] Centos. Deployment Guide: SELinux. Retrieved from https://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-selinux.html

[14] Jesper M. Johansson. November 2008. Technet. Security watch revisiting the 10 immutable laws of security. Retrieved from http://technet.microsoft.com/en-us/magazine/2008.11.securitywatch.aspx

58

Page 63: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

A STUDY INTO NFC—ENABLED AUTHENTICATION METHODS: USING SMARTPHONES TO ENTER NUS FACILITIES

Saloni Kaur A0084053L

[email protected]

Wong Ming Kit A0128454A

[email protected]

Turker Bulut A0128093E

[email protected]

Lee Chun Tat A0128680B

[email protected]

ABSTRACT: An individual currently needs to tap an NUS Matric Card on detection devices to obtain entry access to NUS Facilities. However, the use of a single card could cause many security issues in case the individual loses the Matric Card or gets it stolen. With no authentication procedure in place while using the card, a stranger who obtains one’s Matric Card can pretend to be the owner of the Matric Card and thus gain full-access to all the facilities on campus, including the owner’s the dorm room. In order to provide a solution to such security issues, our team developed a secure mobile system to replace NUS Matric Cards with NFC-enabled smartphones. Given the ever-increasing use of smartphones, our team developed a system that is not only more secure but also more convenient for individuals with NUS Matric Cards. Keywords: Near Field Communication (“NFC”), Blowfish, RSA, Radio-frequency Identification (“RFID”), International Mobile Station Equipment Identity (“IMEI”), Big Data, The Internet of Things (“IoT”) 1. INTRODUCTION: Near Field Communication is currently one of the fastest growing technologies in the world and it looks promising to enter individuals’ daily lives by allowing simple and secure transfer of data. In fact, many use this technology without even knowing about it. When one taps her EZ-link card to pay for public transport or taps her NUS Matric Card

to enter facilities, she uses NFC technology. Especially with the rising industrial and commercial interest in the concepts of Big Data and The Internet of Things, NFC devices could dominate the data collection and transfer markets. Many smartphone producers include NFC tags in their new models and bring this technology literally into their hands for daily use. This paper proposes a particular use of the NFC technology to replace NUS Matric Cards with smartphones. NUS Matric Cards allows individuals to enter NUS facilities by tapping the cards to detection devices at the entrance of each facility. This situation implies a potential risk that if someone loses his NUS Matric Card, one is no longer able to access NUS Facilities, and in a worse scenario, if someone gets his card stolen, the thief is then able to enter NUS buildings as if he is the owner of the Matric Card. Our system solves many of these security issues by taking advantage of several cryptography concepts as well as utilizing the security advantages of the NFC wireless communication. 2. METHODOLOGY: Our team developed a system that utilizes NFC to enable smartphones to emulate NUS Matric Cards. Despite its extensive use in newly developed systems in many industries, NFC is still a fairly new technology and many of its security issues remain yet to be addressed. However, our team tried to

59

Page 64: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

eliminate the majority of these security concerns by incorporating multiple layers of encryption and authentication into the system. 2.1 Near Field Communication: 2.1.1 Technology Overview Near Field Communication is a form of short-range wireless communication between electronic devices. NFC-enabled devices allow users to communicate easily and safely with other NFC-enabled devices and/or environments. A simple touch of two devices or holding them close to each other is usually sufficient for the communication. Due to its simplicity and security in comparison to its alternatives (i.e. Bluetooth, RFID, etc.), NFC has wide-range applications across several platforms, including payment and ticketing, electronic keys, identification, receiving and sharing information, and set-up services2. NFC technology supports three modes of operation3, all of which our system utilizes:

a. Reader/Write Mode: NFC-device read and/or write passive NFC tags and stickers

b. Peer-to-Peer Mode: NFC-devices communicate and exchange information

c. Card Emulation Mode: NFC-devices behave as existing contactless cards

2.1.2 Security Aspects a. Eavesdropping Threat: An attacker may use an antenna to listen to the communication between two NFC-enabled devices. This attack becomes significantly more difficult to conduct in case of passive mode of communication (i.e. only one device generates a radio frequency field while the others ‘listen’) than in active mode of communication (i.e. both devices generate

their own radio frequency fields to transfer data). Solution(s): To establish a secure channel. b. Data Corruption/Destruction/Modification Threat: An attacker may try to disturb or modify the communication to prevent the receiver from understanding the data sent by the other device. The attacker can achieve data corruption by sending valid frequencies of data to the receiving device. Solution(s): (1) To establish a secure channel (2) To check for the radio frequency field while two NFC devices transfer data and stop transmission when an attack is detected c. Data Insertion Threat: An attacker may try to insert data while two devices are exchanging information. Solution(s): (1) No delay from the answering device; (2) The answering device listens to the channel; (3) To establish a secure channel d. Man-in-the-Middle Attack Threat: In a real NFC communication scenario, this attack is practically not possible. Solution(s): Since the attack is not possible, a solution is not needed. 2.1.2.6 Security Overview and Our System: To address many of the possible security issues and avoid attacks, establishing a secure channel seems to be a sufficient option. Our team used RSA and blowfish encryption in the system to ensure a secure channel for the communication, in addition to other security measures that are discussed later in this paper.

60

Page 65: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

2.2 RSA Encryption and Blowfish: To ensure the security of our system, our team has integrated a double-layer of encryption: RSA encryption and Blowfish. RSA algorithm ensures that the information will be converted to “a form not understandable by the intruder therefore protecting unauthorized users from having access to the information even if they are able to break into the system.”1 However, due to the restriction of RSA with regard to its ability to only be able to encrypt a 1024 bytes data, our team also used Blowfish to encrypt longer data.4 Blowfish is a form of symmetric encryption and in our case it is not secure to transfer the shared key to the server application from the client application by using only RSA, a form of asymmetric encryption. Thus, we first use RSA only to transfer shared Blowfish keys. 3. IMPLEMENTATION: Let us now discuss the overview of our system and its security aspects. 3.1 Overview of the Process: 3.1.1 Setup of the System (One-time only):

a. The client downloads the application on her phone and opens the application.

b. The client enters Matriculation number to register her application with the server.

Our team has set up a PHP backend server to send an email to the user’s NUS account (i.e. the one with the user’s matriculation number) with a 6-digit verification code.

c. The client verifies her identity by entering the 6-digit code from our

server’s email and runs the application to set a 4-digit password for every-time use.

3.1.2 Everyday Use after the Setup

a. The client runs the application and gets prompted for her 4-digit password.

b. Client enters the password and enables the NFC-tag to emulate the clients Matriculation Card.

c. Client taps phone on the detection device and the detection device (i.e. server application) reads NFC tag of the client device and retrieves encrypted identification number of the cardholder.

d. The detection device (i.e. server application) verifies the user’s identification with the system database.

e. If approved by the server, the detection device unlocks the door.

See Figure 1. 3.2 Security of the Process: 3.2.1 Throughout Setup Step (b) in Section 3.1.1: By sending an email to the user’s NUS account (i.e. a#######@nus.edu.sg), our system ensures that the client needs to have access to her password-protected email first. Therefore, an attacker is not able to setup the application to pretend to be someone else if he only knows the client’s Matriculation Number. The attacker would presumably not have access to the client’s password-protected email and thus could not enter the 6-digit verification code sent by the backend server.

61

Page 66: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Step (c) in Section 3.1.1: The client sets up a 4-digit password that only she knows to use every time she enables her device to emulate her Matric Card. If an attacker has the client’s phone and application, he still cannot gain entry access without knowing the 4-digit password. 3.2.2 Throughout Daily Use of the Application Step (b) in Section 3.1.2: When the client correctly enters her 4-digit password, the application generates a random Blowfish key (symmetric) and then encrypts the Blowfish key with RSA by 1024-bit public key.

In addition, the application uses Blowfish method to encrypt a dataset, containing the unique IMEI number of the clients phone, her Matriculation number, and her 4-digit password. This encryption guarantees the following: (1) The client’s phone is the one that is registered with her Matriculation Number by checking the unique IMEI and Matriculation numbers. Therefore, even though an attacker may have access to the client’s email address and tries to verify his own phone, he will not be able to do so because of the IMEI mismatch. (2) Besides the client, no one can activate the application without knowing the 4-digit password. Thus, an attacker who does not know the 4-digit password cannot pretend to be the client and gain entry access to facilities. The client application then converts bytes of information into arrays and calculates the MD5 hash of the encrypted dataset and key to ensure the authenticity of the data. Later, the application combines the following items for verification by the system: (1) Blowfish-encrypted dataset (i.e. IMEI, Matriculation number, and 4-digit PIN), (2) RSA-encrypted blowfish symmetric key, and (3) MD5 hash of the encrypted dataset. Steps (c) (d) (e) in Section 3.1.2: When the client taps her NFC-enabled device to transfer all of the combined information, the NFC-enabled receiver device sends all of that information to the server. The server has access to the RSA keys to decrypt the blowfish symmetric key, which then allows the system to decrypt the blowfish-encrypted dataset because the blowfish encryption is symmetric. After this two-fold decryption process, the server is then able to verify the client’s identity and send a signal to unlock the door and grant access to enter the facility. 3.2.3 Security with respect to previously discussed possible attacks

Figure 1 – Process Flow

62

Page 67: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

To address possible eavesdropping, data corruption/destruction, data modification and data insertion attacks*, first and foremost, our team focused on establishing a secure channel by integrating a double layer of encryption because such a channel emerged as the primary means of preventing malicious attacks. Even though an attacker may somehow achieve to access the transferred data, he would not be able to perform any attack because all of the information would be encrypted. In addition, presumably the receiving device would perform almost immediate verification with its signaling speed so that there is no delay in communication between the NFC-enabled devices. As such delays constitute potential threats, this promptness of communication would therefore leave no room for data insertion attacks. Likewise, the answering device (i.e. receiving device) would be permanently listening in our case and therefore would be able to detect any malicious attempts to insert data. In case of such a data insertion attack, the system would shut itself down to prevent the attack. *Reminder: Man-in-the-middle attacks were not practically possible in NFC-enabled communications. 4. CONCLUSION: This paper illustrates our current solution to remove the potential risks associated with losing one’s Matric Card or getting it stolen by using NFC-enabled devices and RSA and Blowfish cryptography techniques. The applicability of our solution to the NUS environment implies that our solution could be scaled up to bring more secure and convenient means of entry-access to many more organizations with facilities that use smartcard entry systems. 5. ACKNOWLEDGEMENTS:

Our team would like to thank Prof. Norman Hugh Anderson for his encouragement for and support in this project. 6. REFERENCES:

1. Goshwe, NentaweY. “Data Encryption and Decryption Using RSA Algorithm in a Network Environment” IJCSNS International Journal of Computer Science and Network Security, 13(7).

2. Jan Kramer Consulting Services.

“Near Field Communication White Paper”. Web. Retrived October 1, 2014. <http://jkremer.com/White%20Papers/Near%20Field%20Communication%20White%20Paper%20JKCS.pdf>

3. Kumar, Anurag. “Near Field

Communication” A seminar report submitted to the School of Engineering Cochin University Of Science & Technology. October 2010.

4. Schneier, Bruce. "Description of a

New Variable-Length Key, 64-Bit Block Cipher(Blowfish)." Blowfish Paper. 1993. Web. Retrieved October 1, 2014. <http://www.schneier.com/paper-blowfish-fse.html>.

63

Page 68: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

64

Page 69: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3D Gesture Recognition Using Leap Motion Chen Chi

School of Computing, National University of Singapore

13 Computing Drive Singapore 117417

[email protected]

Pan Long School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

Sun Hang School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

Zhao Mengdan School of Computing,

National University of Singapore 13 Computing Drive Singapore 117417

[email protected]

ABSTRACT

Living in Information Age, people use their digital devices with the rapidly increasing demands for both convenience and security. In this paper, we will discuss some efficient algorithms of 3-dimensional gesture recognition in Leap Motion. The application Recognito, based on Leap Motion controller, has been implemented for a demo purpose for these algorithms. We will also discuss some implementation details in this report.

Categories and Subject Descriptors I.4.8 [Image Processing And Computer Vision]: Scene Analysis – object recognition; I.5.4 [Pattern Recognition]: Applications – computer vision.

General Terms Algorithms, Design, Reliability, Security, Verification.

Keywords gesture recognition, security, identification, verification

1. INTRODUCTION The Leap Motion controller is a small USB peripheral device which is designed for gesture recognition. The device uses infrared stereo cameras as tracking sensors and infrared light for gesture detection and is able to observe in a roughly hemispherical area, to a range from approximately 25 to 600 millimeters above the device [1]. Together with the Leap Motion controller, there is a Leap Motion Service System to recognizes and track hands, fingers and finger-like tools. The Leap Motion Service System reads data inputs as x, y, z-axis coordinates from Leap Motion controller and can also use these data to recognise users’ hands, fingers and their motion [2].

Figure 1: Leap Motion controller. As the Leap Motion is easily accessible and comes with acceptable accuracy and reasonable price, there is a possibility that it can be used for identification purposes. Therefore in this project, we used the Leap Motion controller as the main device and developed several possible authentication mechanisms using gesture recognition. And all the mechanisms will be included in our self-developed application - Recognito. With Recognito, we can easily evaluate and compare these approaches for real life use purpose.

2. 3D GESTURE RECOGNITION AND BIOMETRIC VERIFICATION 2.1 3D Gesture Recognition Gesture recognition is the mathematical interpretation of a human motion by a computing device [4]. Recognizing gestures as input allows computers to be more accessible for the physically-impaired and makes interaction between machine and human become more natural, especially in a gaming or 3-D virtual world environment. Hand and body gestures can be amplified by a controller that contains accelerometers and gyroscopes to sense tilting, rotation and acceleration of movement - or the computing device can be outfitted with a camera so that software in the device can recognize and interpret specific gestures. In our project, we use the Leap Motion Controller as a main computing device to capture user’s hand gestures for analysing. All the normally used gestures such as circle, swipe and tap can be recognized.

65

Page 70: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

2.2 Biometric Verification Biometric verification refers to a method by which a person can be uniquely identified by evaluating one or more distinguishing biological traits. Some well-used identifiers include fingerprints, hand geometry, earlobe geometry, retina and iris patterns, voice waves, DNA, and signatures [5]. The oldest form of biometric verification is fingerprinting. Historians have found examples of thumbprints on clay seals being used as a means of important identification for theft in ancient China. Although so many ways of implementing biometric verification schemes are possible, there still exists a common identification verification process: A record of a person's unique characteristic is captured and kept in a database and will be used for identification. When identification verification is required, by comparing the new captured-record with the previous record in the database, the person’s identity can be confirmed if there is a match. In our project, we use the hand gestures captured by the Leap Motion controller as a means of biometric verification. A record of user’s unique gesture is captured and kept in the database in order to be compared with the future input gestures for verification purpose, which just coincide with the common process of biometric verification mentioned above.

3. SYSTEM APPROACHES

3.1 Gesture Based Verification Approach Leap Motion Service System is able to feed Recognito up to approximately 100 frames per second. Frame contains the data of several lists of primary objects defined in Leap Motion such as fingers, hands and gestures [3]. The data structure of primary objects in Leap Motion is shown in Figure 2. In this approach, we only demonstrated the recognition and tracking of fingertips. For

each finger captured by the sensors of Leap Motion controller, its tip coordinate in three dimensions is stored as a vector.

3.1.1 Algorithm We suppose that there are two collections of frames, namely Bn and Vn. Bn references the benchmarking gesture, which was set by users, while Vn references the gesture to be verified. For each frame F fed by Leap Motion Service System in Bn or Vn, denoted by Bi or Vi, we have ten vectors of tip coordinates for each finger, Bi,j or Vi,j (j = 0, 1, … , 9). For each tip coordinate Bi,j or Vi,j, there are three attributes x, y, and z, representing the distance away from the origin in the respective direction. For absent fingers, the tip coordinate will be set to the origin.

We define Δ to be the difference of these two collections. The formula of Δ is as below.

In the formula, |F| is the cardinality of F. Vi,j.k - Vi-1,j.k is the displacement in the direction of k (k = x, y, z) between two consecutive frames for the gesture to be verified. Bi,j.k - Bi-1,j.k is the displacement in the direction of k (k = x, y, z) between two consecutive frames for the benchmarking gesture.

The minimum value of Δ is 0 since it is the sum of squares of real numbers. If Δ = 0, the gesture V is identical to the benchmarking gesture B. Relatively small values of Δ indicate that the probability of the gesture V matching the benchmarking gesture B is relatively high. In this circumstance, we may accept that V matches B and V passes the verification. If Δ is relatively large, it

Figure 2: The data structure of primary objects in Leap Motion [3].

66

Page 71: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

is less likely for the gesture V to match the benchmarking gesture B, which implies that V does not pass the verification.

To determine whether Δ is small enough or not, the threshold δ is defined as below.

In the formula, k is the preset constant. Higher k will increase the reliability, but decrease the confidentiality. Lower k will increase the confidentiality, but decrease the reliability. We have tested a large set of possible values of k and in assessment of this approach, the results are all based on a k from our tests that secures the highest confidentiality while it also provides acceptable reliability.

3.1.2 Application For the first use of Recognito, user will be required to set his preferred gesture twice. The first gesture will be served as the benchmarking gesture while the second gesture will be served as the gesture to be verified. Recognito will select key frames to be added in F at the rate of 20 frames per second. If these two gestures match, the first gesture will be stored and set as the benchmarking gesture. From then on, user can gesture over Leap Motion controller to verify his identity and unlock Recognito.

3.1.3 Performance The gesture based verification approach gives a high complexity of password, which guarantees the confidentiality. However, a problem exists that users may need to try several times to unlock Recognito because they may not be able to make the gesture close enough to the benchmark gesture every time.

3.2 Image-Gesture Authentication Approach Although pure gesture based verification using Leap Motion is applicable for gesture authentication, we can still combine the traditional way of authentication and gesture recognition to increase the integrity of the system. Therefore, we designed another approach that uses key points on customized image as the unlock password.

3.2.1 Algorithm Instead of verifying the gestures directly, we combined leap motion with some traditional authentication methods, like text password, picture password etc. In this approach, leap motion only served as the input device. As Leap Motion supports various gestures and can recognise various objects, there are many ways to use Leap Motion as an input device. For example, using a sequence of left/right hand recognised by Leap Motion controller, or a sequence of paper/scissor/stone as the password are possible ways for authentication purpose. Starting from Windows 8, Microsoft provides picture password for uses to log in their operating system. In this approach, we also use picture password, as Microsoft does, but with Leap Motion as input device instead of mouse or touch screen. Also, due to the accuracy of Leap Motion, we only support “linking objects” gestures to serve as passwords.

In order to use Leap Motion controller as the input device, we have to emulate move and touch (click) action with gestures. In Leap Motion Service System, a mapping from 3D coordinates of

fingers and hands to 2D coordinates of applications in computer screen is provided. Thus, move is easy to emulate with Leap Motion. Also, an adaptive virtual surface is defined for users to interact with 2D elements in the computer applications. That virtual surface is approximately parallel to the x-y plane in Leap Motion Service System coordinates, but it is also adaptable regarding the position and orientation of users’ hands and fingers. The touch action will be activated when users move finger towards the virtual surface and within the hovering and touching space, a normalised distance ranged from -1 to 1 is calculated for that finger, as shown in Figure 3. We can then activate the “selecting” action when the finger goes across the virtual surface.

With move and touch emulation, users can perform “linking objects” in pictures, but with their gestures instead of mouse.

Figure 3: The virtual touch surface.

3.2.2 Application In this approach, users are required to select an image as the base of password authentication. The image can be either selected from the default images provided in Recognito or imported from the local path. And then, users need to define 7 points with order on the image as the password. Thereafter, every time user wants to unlock, he must point the correct 7 points in order, or he would be unable to unlock Recognito. The following image shows an example of the password.

Figure 3: Sample password for Doge.

67

Page 72: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

3.2.3 Performance The combination of traditional password unlock technique and the gesture recognition technique gives a surprising reliability and confidentiality in the authentication performance. As users can choose their own images and define their own special points with order in the image, it is hard for others to guess. And the unlock procedure is much more accurate and fast.

4. ASSESSMENT In our assessment for the two approaches, we mainly focus on two criteria that have the most impact on the gesture-password authentication scheme: confidentiality and reliability. Confidentiality: The confidentiality of a gesture-password refers to whether malicious person can easily guess or remember user’s password and unlock the program. Reliability: The reliability of a gesture-password means whether users can easily unlock their own password without trying too many times.

4.1 Gesture Based Verification Approach 4.1.1 Confidentiality This approach provides a high confidentiality, and there are several reasons. Firstly, there are so many possible gestures in the world, and malicious person can hardly guess the password. Secondly, as everyone has his own way of drawing, it will be very hard to copy one’s gesture even if the malicious person stand by his side and remember his gesture. Therefore, the gesture based verification approach gives a high confidentiality for the password authentication scheme.

4.1.2 Reliability As stated in 4.1.1, everyone has his own way of drawing and it is hard for others to copy. However, we cannot ignore that even for the same person, he might not be able to draw his gesture-password exactly the same. And if the password has relative high complexity, the unlock procedure will be more difficult. Thus, it might take many times for one to unlock his own password, which leads to low reliability of the password. Nevertheless, we can put some limitations on the gestures to decrease the complexity of the gesture-password so that the reliability can increase. For example, defining a password that uses the order of left or right hands is a possible approach. Therefore, the reliability will be increased greatly, although the confidentiality will decrease a bit because it will be reactively easy to remember.

4.2 Image-Gesture Authentication Approach 4.2.1 Confidentiality Since the images and points are all chosen by the user, this approach also holds a relative high confidentiality. There are so many possible points in one image, so it is extremely hard for others to guess. A malicious attacker trying to unlock the Recognito under this approach would need to guess what parts of the image were used for the special points (which is difficult but not impossible using modern techniques), as well as the exact order. However, comparing to the first approach, the chance of the password be remembered by malicious person is a little higher. Therefore the overall confidentiality of this approach will be slightly lower than the first one.

4.2.2 Reliability Unlike the first approach, this approach provides a high reliability of password, because the only type of gesture to be recognized by Leap Motion controller is pointing. As long as users can point to the right positions in correct order, Recognito will be unlocked. This is easy to use and more user-friendly. The following table demonstrates the rating of the two criteria for different approaches.

Gesture Recognition Approach

Image-Gesture Authentication Approach

Confidentiality Very high Moderate

Reliability Low Very high

Total Moderate High

Table 1: Comparison between the two approaches.

5. RELATED WORK The gesture recognition algorithm illustrated in 3.1.1 can be extended with concepts in machine learning. The benchmarking gesture can be refined every time user makes his gesture. The gesture recognition is expected to achieve higher confidentiality and reliability.

6. CONCLUSION After implementing the two approaches in Recognito, we can find that although pure gesture recognition gives a high confidentiality in authentication, the accuracy is not promised, which is an obvious shortage in password authentication. However, with simplifying the gestures such as using the order of left and right hands as password, we can still implement a secure-enough password authentication scheme. Besides this, the combination of traditional password techniques and the gesture recognition, a more secured password authentication scheme can be implemented. Therefore, we can conclude that using Leap Motion to develop gesture authentication schemes is possible and reliable.

Moreover, as Leap Motion controller is easily accessible and comes with bunch of interesting games, there might be a trend that people starts using Leap Motion just as normal as using mouse. For this reason, we believe that the gesture-password authentication scheme using Leap Motion will have the chance to come into use in the near future.

7. ACKNOWLEDGMENTS Our thanks to Prof Hugh Anderson for providing us with Leap Motion controller.

8. REFERENCES [1] Cho, O. Development of Serious Game for Kids using Leap

Motion based on Honey Bee Dance, Advanced Science and Technology Letters Vol.46 (Games and Graphics 2014), pp.260-264, 2014. Retrieved October 21, 2014: http://dx.doi.org/10.14257/astl.2014.46.55

[2] Leap Motion, Inc.: Camera Images - Leap Motion Python SDK v2.1 documentation. Retrieved October 25, 2014:

68

Page 73: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

https://developer.leapmotion.com/documentation/python/devguide/Leap_Images.html

[3] Leap Motion, Inc.: Tracking Model - Leap Motion Python SDK v2.1 documentation. Retrieved October 25, 2014: https://developer.leapmotion.com/documentation/skeletal/python/devguide/Leap_Tracking.html

[4] TechTarget: Definition of Gesture Recognition. Retrieved October 28, 2014: http://whatis.techtarget.com/definition/gesture-recognition

[5] TechTarget: Definition of Biometric Verification. Retrieved October 28, 2014: http://searchsecurity.techtarget.com/definition/biometric-verification

69

Page 74: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

70

Page 75: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Security system with 3D gesture recognition

Timothy Lim National University of Singapore School of Computing National

University of Singapore 15 Computing Drive (+65) 6516-4368

[email protected]

Xu XiaNan National University of Singapore School of Computing National

University of Singapore 15 Computing Drive (+65) 6516-4368

[email protected]

Foo Yong Jie National University of Singapore School of Computing National

University of Singapore 15 Computing Drive (+65) 6516-4368

[email protected]

Wang Hanpeng National University of Singapore School of Computing National

University of Singapore 15 Computing Drive (+65) 6516-4368

[email protected]

ABSTRACT

The project will present a novel approach on the design of security systems by using Kinect, a motion sensing input device, through a multi-factor approach using facial and gesture recognition to authenticate users.

Categories and Subject Descriptors D.3.2 Java

General Terms Security

Keywords Security System, Kinect, Gesture Recognition, Facial Recognition

1. INTRODUCTION Security is important, especially more so today, from environments ranging from physical access restriction in home or office to authentication in digital systems. The proposed technique utilizes a multi-factor authentication approach using facial and gesture recognition to authenticate users. A prototype will demonstrate the capabilities of the proposed security approach.

2. System Our security system has the following logical components: Gesture Recognizer, Face Recognizer, Login Mode State Machine and New User State Machine.

2.1 Registration Flow The registration flow for new users is modelled in the registration state machine (Fig 2.1).

Fig 2.1 Registration State Machine

2.2 Login Flow The login flow for existing users is modelled in the login state machine (Fig 2.2).

Fig 2.2 Login State Machine

3. Gesture Algorithms

3.1 Finger Tracking The system allows for hand and finger tracking via fast marching squares to find the contour of the hand and then estimates finger endpoints by looking for inflections in the curvature of the contour through an open source Processing library, Finger Tracker [1]. This allows usage of gestures such as extending a number of fingers to trigger the start of gesture recognition.

3.2 Gesture Recognition The system recognizes gestures based on the movement of the centroid of the bounding box of the user’s hand to output a set of points. Outliers occur when hand moves slightly when it is still or when there is recognition of “noise” that is far from the user’s previous hand position (Fig 3.2.1).

Fig 3.2.1 Outliers

71

Page 76: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

To improve accuracy of recorded gesture, the points are processed through the removal of outliers and scaling the points within the bounding box of the window to improve accuracy (Fig 3.2.2).

Fig 3.2.2 Removal of outliers and Scaling of points within

bounding box

3.3 Curve Smoothing To improve accuracy for gesture matching, we generate curves from the set of recorded gesture points to interpolate intermediate points by using Bezier curve as proposed by Shin et al [2].

We perform a cubic Bezier function on the points to generate a detailed Bezier curve for the purpose of eliminating noise. Since the points stored in the file are widely spread, we have to generate the smooth curve using these control points. Higher degree Bezier curves are more computationally expensive, as we balance the performance and expense; we choose the cubic Bezier curve function to generate the curve.

The cubic Bezier function uses 4 control points to generate a smooth sub curve. Given the 4 control points to be P0, P1, P2, P3 and the curve starts at P0 going towards P1 and finally reached P3, the computed interval point P(t) along this curve is defined by formula:

P(t) = (1-t)3P0 + 3(1-t)2*t*P1 + 3(1-t)*t2P2 + t3*P3, t∈[0,1]

In real instances, because the user might do the motion in different speed, result in different intervals width between the control points. We practice few times and eventually find a suitable t value equals 0.03124, which means that for every 4 control points, we will generate 16 points to represent the sub-curve.

Although the sub-curves are smooth, the entire curve is not since the ending tangent vector of the first Bezier curve is not the same as the starting tangent vector of the second Bezier curve. In order to generate a complete long smooth Bezier curve, we modify the first point of each sub-curve starting from the second sub-curve onwards to achieve C1 continuity (the two tangent vectors are to be the same).

3.4 Curve Matching Algorithm A graph is broken down into multiple sub graphs before it is compared with its sub graph from the original graph in the database. We make use of two comparing methods, the Tangent Gradient Difference and the Average Distance.

The Tangent Gradient Difference is calculated by subtracting the gradients of the tangents of the sub graph and of the original and

dividing it with the original graph. A sub graph with a percentage difference greater than the gradient difference threshold is deemed to have failed.

The Average Distance is calculated by comparing the average distance between the first, middle and last points of the sub graph and original graph respectively. A sub graph with an average distance greater than the distance threshold is deemed to have failed.

If the sub graph passes any form of comparing method, it is deemed to have passed. If the percentage of failure is below a certain threshold, the graphs are deemed to be similar and the user is deemed to know the password.

3.5 Curve Matching Rules To allow for flexibility in curve matching, the curves are split into segment and matched based on their derivative and distance using fuzzy logic. The fuzzy sets are described in Table 3.3.1.

Tangent Vector Match (TVM) low, high

Distance Match (DM) low, high

Fuzzy Sets Table 3.5.1 The fuzzy rules to determine whether curve segment matches are described in Table 3.5.2.

OUTPUT RULE

Curve Segment Match

IF TVM_high AND DM_high then Match

IF TVM_high AND DM_low then Match

IF TVM_low AND DM_high then Match

IF TVM_low AND DM_low then NOT Match

Fuzzy Rules Table 3.5.2

3.4 Curve Matching Verification The red dots represents the user input gesture points while the green curve is the transformation of the user input gesture points after scaling and the removal of outliers. A smooth curve is generated for the processed user input points it is compared to the smooth curve generated by the blue points, which is retrieved from from the database. If the smooth curves generated by the green and blue points are similar enough, the user is authenticated. Generic gestures, namely, semi-circle, triangle and lightning shapes, are generated to test and verify that curve matching works.

3.4.1 Semi-Circle The semi-circle shape (Fig 3.4.1.1) passes the tangent gradient test (Fig 3.4.1.2), with failed tangent vectors less than the set threshold.

72

Page 77: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Fig 3.4.1.1 Circle Passed

Fig 3.4.1.2 Passed Tangent Gradient Graph of a match of circles.

3.4.2 Triangle

The triangle gesture (Fig 3.4.2.1) fails both tangent gradient (Fig 3.4.2.2) and distance test (Fig 3.4.2.3) as seen from the large number of points with difference crossing the set threshold.

Fig 3.4.2.1 Triangle Failed

Fig 3.4.2.2 Failed Tangent Gradient Graph of failed triangles

Fig 3.4.2.3 Failed Average Distance of failed triangles

The triangle gesture (Fig 3.4.6) passes the tangent gradient test (Fig 3.4.7) and distance (Fig 3.4.8) since it has a closer match.

Fig 3.4.2.4 Triangle Passed

Fig 3.4.2.5 Passed Tangent Gradient of passed triangles

Fig 3.4.2.6 Passed Distance of passed triangles

3.4.3 Lighting The lightning gesture (Fig 3.4.3.1) passes the tangent gradient test (Fig 3.4.3.2) and distance test (Fig 3.4.3.2).

73

Page 78: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Fig 3.4.3.1 Passed Lighting

Fig 3.4.3.2 Passed Tangent Gradient of a passed lightning

Fig 3.4.3.3 Passed Average Distance of passed lightning

The lightning gesture (Fig 3.4.3.4) fails the tangent gradient test (Fig 3.4.3.5) as seen from the larger number of points with difference crossing the set threshold.

Fig 3.4.3.4 Lighting Failed

Fig 3.4.3.5 Failed Tangent Gradient of failed lightning

Fig 3.4.3.6 Failed Average Distance of failed lightning

4. Face Algorithms

4.1 Face Detection Our facial detector implements Haar feature-based cascade classifiers to detect faces [3]. Initially, the algorithm needs a lot of positive images (images of faces) and negative images (images without faces) to train the classifier. We extract features from it and apply each and every feature on all training images. For each feature, it finds the best threshold which classifies the faces from positive and negative. However, there will be errors or misclassifications. Therefore, we select the features with minimum error rate, which means they are features which best classifies the “face” and “non-face” images. After training is done, there are around 6000 features stored in the classifiers. These features will be used to match a query image and check if a face presents in it. It is very slow to apply all features at once to do the face detection. For this here comes the concept of Cascade of Classifiers. Instead of applying all the 6000 features on a window, the features are grouped into different stages of classifiers and applied one-by-one. As a result, the final classifier is a weighted sum of these weak classifiers. It is called weak because it cannot classify the image alone, however, together with other classifiers forms an overall strong classifier. We import OpenCV library as supports of our face detector. OpenCV already contains many pre-trained classifiers for face, eyes, smile etc. In our application, we use the OpenCV implementation 'haarcascade_frontalface_default.xml' as our face detector kernel.

4.2 Face Recognition Our approach to facial recognition is using the Eigen face method [4].

4.2.1 Recognizer training

The general idea of this algorithm is to first transform images set for training into vectors. We then obtain the mean image and

74

Page 79: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

covariance of these images which is used to generate Eigen vectors. The Eigen vectors can be represented as images (Fig 4.1) as Eigen faces. Facial recognition is done using these Eigen faces.

Fig 4.1 Sample Eigen Faces

4.2.2 Recognizer Process

The face recognizer first will convert a new query face into its Eigen face components. The input image is compared with our mean image and multiplied with the difference of each eigenvector. Each value would represent a weight and would be saved on a vector Ω. We now determine which face class provides the best description for the input image. This is done by minimizing the Euclidean distance. The query face is considered to belong to a class if Euclidean distance is below an established threshold ε, which in turn means that it is to be a known face. If the difference is above the given threshold, but below a second threshold, the image can be determined as an unknown face. However, if the input image is above these two thresholds, the image is determined not to be a face. In our application, if the query image does not pass the first threshold, the user will not be recognized and has to input the user identification manually.

5. Storage

5.1 Gesture Data The points are serialized from a hash map and stored as a flat JSON file as key-value pairs, with “user_id” as key and the gesture points as the value.

5.2 Face Data Face recognition data is stored as flat JPG files with width of 180 pixels and height of 200 pixels.

6. Authentication

6.1 Multi Factor Authentication Multi-factor authentication requires at least two out of three factors, namely, the knowledge factor, possession factor and inherence factor. Our implementation of a security system is a two factor authentication system which utilizes the inherence factor, through the user’s face, and knowledge factor, the gesture password which the user knows.

7. Implementation Our system is implemented on the Processing framework, utilizing open source frameworks such as OpenNI, SimpleOpenNI

and Processing libraries, FingerTracker, OpenCV and Eigenfaces. The current setup allows for hand and finger tracking via fast marching squares to find the contour of the hand and then estimates finger endpoints by looking for inflections in the curvature of the contour.

8. Limitations 8.1.1 Gesture Data Storage Gesture data is stored plainly in the database as the algorithm requires the coordinate data to authenticate the user. There is difficulty in hashing this data and as such, the password is known once the database is compromised.

8.1.2 Face Recognition The face recognition system can be compromised if an attacker uses a photo of the user.

9. Future Works 9.1.1 Face Recording The face recognition implementation records the user’s face on the user’s control. It detects the user’s face when it is front facing but does not have automated checks to ensure that the angle is optimal for future recognition.

10. Conclusion The prototype developed is able to perform the proposed novel method of multi-factor authentication through gesture and face recognition using Kinect.

11. Acknowledgements Our implementation of the project uses the following open source libraries:

1. Processing

2. OpenNI

3. Simple OpenNI

4. FingerTracker

5. OpenCV Processing

6. Processing-Eigenfaces

12. REFERENCES [1] Finger Tracker. http://makematics.com/code/FingerTracker/ [2] Paul Viola and Michael Jones.2001. “Rapid Object

Detection using a Boosted Cascade of Simple Features”. [3] M. Kirby and L. Sirovich (1990). "Application of the

Karhunen-Loeve procedure for the characterization of human faces". IEEE Transactions on Pattern analysis and Machine Intelligence 12 (1): 103–108. doi:10.1109/34.41390. Shin, M.C., Tsap, L.V., Goldgof, D.B.: Gesture recognition using bezier curves for visualization navigation from registered 3-d data. Pattern Recognition 37 (2004)

75

Page 80: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

76

Page 81: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Password securities in different operating systems Eugene Ang Hwai Choon, Muhammad Farhan Bin Ismail, Mai Huong Nguyen Thi, Elias Reda

Boutaleb NUS

[email protected], [email protected], [email protected], [email protected]

ABSTRACT In this paper, our group discusses some attacks to recover the plain-text passwords from hashed passwords in different operating systems (OS) such as Windows and Linux. We hope it could serve as a guide for future computer security students in their studies.

Categories and Subject Descriptors D.4.6 Security and Protection – access controls.

General Terms Experimentation, Security

Keywords Operating systems, Log-in mechanisms, Windows, Linux, SAM, NTLM, SHA-512, passwords

1. INTRODUCTION The strength of the login password to a user’s account determines how secure a user’s account is. With security of operating systems (OS) being increasingly emphasized by system administrators (to ensure no secrets leak out), we come to today’s topic on password security. What determines whether a password is secure enough? Is it the complexity of the password? Is it the hash system used by the OS? Is it the combination of random strings generated which make the password hash more complex?

In the modern operating systems, passwords are no longer stored in plaintext. The reason is that if an attacker could access to the local database, he could see many passwords of the same user guess a pattern over time. People often use the same passwords for multiple other services such as Amazon, PayPal. Thus, one account being compromised may put other accounts at risk. Thus passwords were hashed by cryptographic hash functions before putting into databases.

Hashes are essentially one way functions which are computationally difficult to reverse. Different OS uses a combination of different hash algorithms. Certain OS like Linux and Mac OS X also makes use of a salt value that makes the password harder to brute force.

We will thus discuss the strength of each OS’ password security

implementation in the coming sections, and suggests ways in which will slow down a potential attacker.

2. EXPERIMENTS In this section, we will discuss how to get the local database containing hashed passwords in Windows and Linux, and how to break them.

Before that, we want to introduce the set of usernames and passwords we used in this experiment. Some of the passwords are from [1].

Table 1. Set of usernames and passwords

ID Usernames Passwords

1 tester1 “tester1”

2 tester2 “*IVANA_*123”

3 tester3 “h3L 0!”

4 tester4 “Msbi12/Dec,4”

5 tester5 “ILuv2PlayB@dm1nt()n”

6 tester6 “Hello2U!“

7 tester7 “$&f1T#“

The above table contains weak password, moderate passwords using upper, lower cases mixed with digits and special characters, and strong passwords in which we have all characteristics of moderate passwords and the characters don’t form a meaningful English word or sentence.

2.1. Windows In Windows, the hashed passwords of users are stored inside Security Account Manager (SAM). We could find SAM under Windows\system32\config or HKEY_LOCAL_MACHINE. As Windows uses SAM while it is running and HKEY_LOCAL_MACHINE\SAM is protected, we could not get it directly in Windows. There are common ways to get SAM. One is to use pwdump [2]. Below is the sample execution:

Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Conference’10, Month 1–2, 2010, City, State, Country. Copyright 2010 ACM 1-58113-000-0/00/0010 …$15.00.

77

Page 82: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

Figure 1. Using pwdump7 to extract hashed passwords in a Windows machine.

Another way is to boot the machine into another OS such as Linux and mount Windows partition with write permission, and copy SAM to an external media. Apart from getting SAM, this method also could modify SAM, and will be discussed in later part (2.4).

A format of a line in SAM is: username : userID : LM hash : NT hash. NT hash uses MD4 without salt, see more in [3]. MD4 is a weak hash function and the first collision attack was found by Dobbertin in 1998.

We have used online tools to conduct the pre-image attacks on the hashed passwords we obtained. Below is the sample execution using Hashkiller [4]:

Figure 2. Using Hashkiller to perform pre-image attack in case 6.

The result was summarized in the below table.

Table 2. Summary of pre-image attacks.

ID 1 2 3 4 5 6 7

Hashkiller Y Y N N N Y N

From the table, it is easily seen that Hashkiller could break the hashes of weak and moderate passwords, and fails in all the cases of strong passwords. We have attempted to break the hashes of strong passwords by building a Rainbow table using an online tool RainbowCrack [5]. The rainbow table we built has the key length up to 6 characters; and the range of characters is from 32 to 95 in ASCII. Below is the execution using RCrack to break hashes:

Figure 3. Using RCrack to perform pre-image attacks in case 3 and 7.

2.2. Linux The Linux version used in this section is Ubuntu 14.04.

In Ubuntu, hashed passwords are stored in /etc/passwd or /etc/shadow if the password field in /etc/passwd was marked with “x”, and only users with sudo privileges could see the content of the file. One typical password is below: tester1:$6$EDlXnK7b$KvJYNN18y8tcDOd4I0ojFXXrDuJgnJowDWRMfzusumeAC1bMo/oHbeJpV8jIV2Y/UFpOlXnImQyvhRwfTB6Ms0:16366:0:99999:7::: with $6$ indicates that the cryptographic hash function is SHA-512, salt value = EDlXnK7b. We use hashcat (see more from [6]) to conduct the pre-image attacks on the hashed passwords. Below is a sample execution of using Hashcat to break hashed passwords:

Figure 4. Using Hashcat to perform pre-image attack in case 1.

2.3. Mac OSX Passwords in Mac OS X are stored in the folder /var/db/dslocal/nodes/Default/users/ in .plist files. They have to be first converted into proper xml files to reveal the entropy, iterations and salt values.

Figure 5. Converted image for the <user>.plist file

Hashcat is also used here in brute forcing the combination of salt, entropy and iterations. Again, the success of such attacks depend on the complexity of the password, with a dictionary-based password will yield a faster runtime.

78

Page 83: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

The format of the password hash to be cracked is $ml$<iterations>$<salt>$<entropy>. An example of the password hash would be: $ml$13315$LhJfbeYtbMQV1l2seHtHZvFxWjc/WSaMGgZbXfyhJwc=$FcOUmE8V5g1DWMTW8y1Lo8axhsD35wE59j8ED+bZa8c+2g3MobWFhKD7f8lm9afBjljikkY50FKcjfl/DWsdF4RQ2lDKKgAg7p6Q3BlGzRJjinM69QFlzPsLSt7st4BGDx20mPVzTGEJtCBmSaBf7/Qj8JyRbTdb18WAzynwRvE=

This seems like a more secure implementation than that of the Windows security hashing.

2.4. Exploit on SAM through cnntpw (Ubuntu)

Figure 6. How a module in Ubuntu is able to configure the SAM file on the same computer.

The module chntpw is able to show the current Windows users on the computer as well as if they are encrypted by passwords. The Administrator account is encrypted by a password as shown by “dis/lock” under the ‘Lock?’ column.

Figure 7. Modified SAM file

Also, the module allows the user to modify the password for each user, or remove the passwords, or make a non-administrator account an administrator. As seen above, the account Administrator now has *BLANK* password. Upon restarting the computer, the Administrator account no longer requires a password.

3. PAM Given shortcomings of using only single, weak passwords, in the end, it is up to the system administrator, systems programmer or application developer to roll its own authentication processes and policies, according to what is being asked of him. However, it may tedious to do everything from scratch. This is where PAM comes in. 3.1. Introduction to PAM A pluggable authentication module (PAM) allows the programmer to decouple authentication logic from the application's logic. He can thus tune the security policies of any application without altering or recompiling it. It designates two things: the PAM library that provides an interface for authentication support in applications and daemons/services, and the modules defining and containing the authentication logic. It is especially present and used in UNIX-based operating systems such as Linux, Mac OS X and BSDs. Most distributions support PAM today. 3.2. How to use PAM and how PAM works For an application to become PAM-aware, one needs to link the PAM library against it. New authentication schemes can be implemented by writing and installing PAM modules, whereas authentication policies can be set or modified using configuration files. PAM modules are located in the /lib/security/ directory. Policies are defined in configuration files located in the /etc/pam.d directory. Each one is named after the application or service that is using PAM. We can look at one of them for the chsh utility:

79

Page 84: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

auth sufficient pam_rootok.so auth required pam_unix.so account required pam_unix.so session required pam_unix.so password required pam_permit.so When an PAM-aware application is run, it will first call on the PAM's services, who will then read the configuration file corresponding to the application, and run the module stack for each authentication facility. A module stack is the list of modules that are run for a particular module type, in the order in which they are defined in the file. In the configuration file example above, the stack for the auth type would be pam_rootok.so, pam_unix.so. Each line contains a module type (first column), a module that contains the tasks to be performed (third column), and a control flag that determines what happens when the stack returns a certain result (second column). Module types designates PAM authentication facilities: - authentication management: asking an user for a password or another security token, - account management: manages access restrictions and checks, ie has the user account/password expired? - session management: specify actions to be performed when an user is authenticated and when said user leaves ie resource allocation and freeing, - password management: deals with updating authentication passwords and tokens. For each module run in a given stack, a success/failure value is returned. Control flags determines how those values propagates through the stack: - required: if a module fails, the other modules are run anyway, but the failure is still returned. - requisite: if a module fails, no other module is run. A failure is returned. - sufficient: as long as one module succeeds, it results in success, even if another module failed before. No other module is run. 3.3. A two-step authentication module As part of the topic, we tried to harden user authentication when running a simple program by adding two-factor authentication to it via a PAM module. It consists of 3 files : the test application pam_ls, the pam_2step_auth.so module and the configuration file associated with pam_ls. The test program takes an username as an argument and performs a directory listing (ls -la). But before doing so, it asks for the UNIX password of said user. If if succeeds, then it proceeds to generate a random PIN and send it via SMS. The random PIN is hashed, and is compared to the hash of the sent PIN inputted by the user. If it succeeds once more, then the user is authenticated.

There are quite a lot of shortcomings and limitations with the implementation: - The phone number to which the SMS is sent is hardcoded in the sendsms script. Instead, the phone number bound to the authenticating user should be fetched from a database and used. - There is no login failure logging and reporting, no account lock out when a certain amount of login attempts reached makes it easy to bruteforce either. It would probably need to run as a service/daemon to keep track of that information. - There is no database for storing user information such as phone numbers, hashes, PINs and PIN expiration times. But since the program just performs a directory listing and ends right after, it is not of much use. - It is easy to bruteforce the application, as the PIN range is between 1000 and 999999. One could set an expiration time for OTP (one-time password) PINs, hash the generated PIN, and keep the hash in the database. After the user inputted his PIN, it will be hashed and compared to the hash in the database. - Since SMSes are sent via the Internet, the requests can be intercepted. It is quite easy since it is all in plaintext in the URL request. - If the mobile phone is stolen, no further authentication is possible.

4. REFERENCES [1] Tips for creating a strong password,

http://windows.microsoft.com/en-sg/windows-vista/tips-for-creating-a-strong-password

[2] Password Dumper pwdump7, http://www.tarasco.org/security/pwdump_7/

[3] Password Technical Overview, http://technet.microsoft.com/en-us/library/hh994558(v=ws.10).aspx

[4] MD5/ SHA1/ NTLM Online Database, http://www.hashkiller.co.uk/

[5] RainbowCrack Project, http://project-rainbowcrack.com/ [6] Hashcat Advanced Password Recovery,

http://hashcat.net/hashcat/ [7] Ubuntu manuals,

http://manpages.ubuntu.com/manpages/hardy/man5/passwd.5.html

[8] Fairley, M. 2014. How to Extract OS X Mavericks Password Hash for Cracking With Hashcat. https://web.archive.org/web/20140703020831/http://www.michaelfairley.co/blog/2014/05/18/how-to-extract-os-x-mavericks-password-hash-for-cracking-with-hashcat/

[9] CookieMaster, 2014. Cracking OS X Mountain Lion, OS X Mavericks, and OS X Yosemite account password In Hackmac Forums http://www.hackmac.org/forum/topic/2678-cracking-os-x-mountain-lion-os-x-mavericks-and-os-x-yosemite-account-password/

[10] Exploiting Windows Weak Password Security Storage Methods, http://www3.nd.edu/~dpettifo/tutorials/chntpw.html

80

Page 85: CS3235 - Semester I, 2014-2015 Computer Securityhugh/CS3235/PREVIOUS...Port knocking is a computer networking technique of externally opening ports on a firewall by creating a connection

[11] User Authentication HOWTO, http://tldp.org/HOWTO/User-Authentication-HOWTO/x115.html

[12] Pluggable Authentication Modules, https://www.freebsd.org/doc/en/articles/pam/article.html

[13] How PAM works, http://www.tuxradar.com/content/how-pam-works

[14] PAM Tutorial, http://wpollock.com/AUnix2/PAM-Help.htm

[15] Making the Most of Pluggable Authentication Modules, http://www.informit.com/articles/article.aspx?p=20968

[16] Writing Your First PAM Module, http://www.rkeene.org/projects/info/wiki/222

[17] The Linux-PAM Module Writers' Guide, http://www.linux-pam.org/Linux-PAM-html/Linux-PAM_MWG.html

81