Notes – Open Web Application Security Project’s Top 10 Attacks

ATTACK #1: SQL Injection

Solution:
– Use prepared Statement with parameter markers (i.e. ?)
– Don’t use just prepared statement alone and avoid concatentating strings to form a query

Command Injection

– Exploit: Define linux commands into a string where that string is ultimately used inside an exec() function

Normal use:

exec(“cat log_” + $filebase + “.txt”);

Abuse case:

exec(“cat log_hits; rm -rf /; : .txt”); // This recursively deletes all files from the top

In windows,
– the Pipe command (|) can be used to append command-line functions
– dir command lists directories

In UNIX,
– the Semicolon (;) can be used to append command-line functions
– the ls command lists directories

Solution #1: Input validation – Ignore illegal characters;
Solution #2: Processes should be limited with the least amount of permissions

XML Injection

Attackers can add and modified nodes on XML to manipulate application logic
Attackers can cause Denial of Service if they construct the fragments to be deeply nested

Solution: Use XML parsers

Document Type Definition Attack

– XML External Entities can be used to store strings of information that can be referenced like a variable during the parsing of XML
– They can also be used as a macrocommand to load files from a file system

– If attckers are able to construct or manipulate the XML, they can take advantage of the macro to load sensitive files from the local file system or other machines on the same network

Billion Laughs Attack

– Happens when attackers construct XML External Entities that reference other XML External Entities in an exponential manner. The result is that the process eats up too much memory causing the system to slow down when parsed (CPU 90%+)

– Solution: Strict validation before it gets parsed; Validate against DTD or XSD; Configure parser to limit entity resolution depth to as shallow as possible to prevent Billion Laughs

Overall General Mitigation Strategy Against Injection Attacks

1) Output Encoding – Do it right before displaying content to the user so that runnable code will be exposed and not executed
2) Input Validation – Ensure what public interfaces clients have access to are cross refrerenced against a white list and/or blacklist; use parameterized variables with prepared statements instead of concatentation
3) Logging and Auditing – The first two may not catch everything but at least there is a means of tracking attackers and assess damages when it does happen

ATTACK #2: Broken Authentication and Session Management

Sessions ID’s should be
– random
– non-colliding; unique so that a new session ID does not match an existing one and large enough so that it can be recreated through bruteforce
– Live as short as possible; server-side must expired the cookie, not the client

Exploit: Use browser plugins to view your local cookie; inspect the session ID; a bad session ID would be the concatentation of your IP and timestamp; Attackers could experiment by manipulating these values until it matches an active session ID of some other logged in user in the system.

How to test:

Have two users set up; Log in with the first and obtain the cookie; Have the second user login with the first person’s cookie appended

http://site.com/login.jsp?sessionID=123456

Check to see if the second user still maintains the first sessionID or has been issued a completely new one.

If it is the case it is the old one, then this is evidence of a session fixation issue; Log in as the first user and you will appear as the second one afterwards

Solution #1: Reduce time cookie is valid; client-side timeout; server-side timeout
solution #2: On the server-side, do not process session ID’s on GET/POST requests
Solution #3: When users authenticate successfully, issue new session ID’s
Solution #4: Only accept session ID’s that were created on the server-side
Solution #5: SSL/TLS to encypt data between client and server to prevent man in the middle
Solution #6: Map IP addresses to Session ID’s when possible
solution #7: Force re-authentication for highly critical operations (i.e. change password by supplying old, tranfering money, etc)
Solution #8: Use HTTPOnly flag to prevent XSS
Solution #9: Use random and long session IDs so that it cannot be easily guessed.

Other auth related problems

1) Username Enumeration – Attackers can construct dictionary to hammer out a valid username if the system responds whether the username exists or doest not
2) Weak password policies – Lack of these policies makes it easier to guess
3) Account Lockouts – Lack of lockouts allows attackers to continously attack
4) Password Reset Functionality – If the recovery questions are too easy, attackers can guess the responses.
5) Lack of auth – Some content on the website is able to be accessed without auth.

ATTACK #3: XSS (Cross-site Scripting)

Malcious code from another domain gets copied into a vulnerable domain which then gets executed by that web app or by the victims

Reflected Attack: User clicks on a malicious link which then the victim’s browser goes to that website, Javascript is run; Note the malcious code is not stored on the vulnerable website

http://mybank.com/page?message=

The original intent was:

But the userNameParameter can be manipulated to do more:

Where request.getParamter("userName") would have been the following string:

mark' alert(document.cookie); var blah='

Solution #1: Don't reflect input created by users; it happens when state is stored in hidden fields; instead have state maintained on the server-side
Solution #2: Use both output encoding and input validation
Solution #3: Client-side and server-side validation
Solution #4: Logging and auditing for active and passive controls

ATTACK #4: Insecure Direct Object References

Happens when developesr expost a URL mapping to a resource in the web application; alternatively a name-value pair is explicit in the URL and attackers modified it to their advantage

http://site.com/foo.php/accountID=42

http://site.com/bar.jsp?fileName=../../../etc/passwd%00

%00 is a null byte; this causes execution to ignore anything else aftwards effectively making it the same as a semi colon

Network traffic can be sniffed to modifiy parameters on the request before it gets sent do the server; Attackers will put in garbage to see what will happen:

ERROR: /var/www/loan_docs/garbage_loan.docx file not found

This is open door for path manipulation attack

Use ../../../etc/shadow%00 to obtain a list of password hashes

How to Test:
- Look at all request parameters
- Don't rely on automated tools
- Code review
- Tamper with request parameters to see what happens and if it responds properly

Solution #1: Ensure server-sode process acting on user's behalf has the least amount of permissions to do it's job

Solution #2: chroot jail

Solution #3: Server-side generated resource mapping list; If clients misbehave and attempt to submit a mapping that does not exist, it could indicate there is an attack.

ATTACK #5: Security misconfiguration

When new securities advisories are release, it's just a matter of hours or days before an exploit is released. If an attacker is able to identify a vulnerable server, they will use tools like Metasploit Framwork, UI based exploits packages

Ensure after deployment that the server is properly configured to have it's Security settings configured to not have the default values

How to test: Use tools like Nessus to scan for network and system misconfiguration

Solution #1: Stay up to date with patches; attackers will reverse engineer patches to figure out what was fixed and then re-issue new exploits.

solution #2: Use system hardening tools like Bastille (*nix) and MS Baseline Security Analyzer (Windows)

ATTACK #6: Sensitive Data Exposure

C.I.A. of Information Security

Confidentiality - Verbose messages give too much insight about system
Integrity - Data that can be manipulated by attackers
Availability - Attackers can DOS to cause the applications to unusable

How to test for Insecure Crytographic Storage:
- Check code base for instance where cyptographic algorithms, libraries, and crypto APIs are used
- Ensure you are using the right algorithms for the right purposes
- Ensure data signatures are being used to validate the integrity of the data and the origin of the data
- Use http://www.keylength.com for guidance on how long a crypto key needs to be
- If there are house-made algorithms, consider them weak and replace them with industry standard ones

Solution #1: Passwords need to be salt and hashed with the highest available cypto method available; Encypt other sensitive data

Solution #2: Use role-based access instead of user-based access to prevent hard coding against specific users

Solution #3: Use HTTPS using a cert from a trusted source

ATTACK #7: Missing Function Level Access Control

3 types of missing function level access control:

1) Forceful browsing: Attackers can guess resources on the web app and access them successfully if there is no authorization check

http://site.com/userAdmin.jsp

2) Vertical access: The lower privledged user is able to access the same resources a higher privledged user is allowed

3) Horizontal access: The attacker can access data/resources of other users with the same role

AuthN = Authentication; Validating if a user is in the system
AuthZ = Authorization; Validate if a user is allowed to access a resource

How to test against Forceful Browsing:
- With a site map attempt to navigate through the site as unauthenticated user

How to test against vertical access control:
- Look for operations that are only available to certain roles
- Log in as a different role and attenpt to access those operations

How to test against horizontal access control:
- Look for operations that specify id as a paremter and augment it to be another record belonging to another user

Solution #1: Any time a resource is requested by a client, it should automatically be routed to an authorization module to test if the logged in user is permitted to access the resource.

Solution #2: Admins should be able to manage entitlements based on roles

Solution #3: Default to no access

Solution #4: Don't depend on the client to block access to a control

ATTACK #8: CSRF (Cross Site Request Forgery)

- Attackers use

<IMG>

, JavaScript and hidden

<iframe>

are used to embed the trigger of an HTTP Request. The victim who is logged into the vulnerable website will unknowingly execute the request on a valid session with the server.

How to test: Use an HTTP Proxy to observe HTTP requests. If you can derrive a pattern to change the parameters to make the operation perform different than expected, you have an issue.

If you have no security ID or CSRF token on the request, then the web app is prone to CSRF. If there is a security ID or CSRF token on the request, modify it to something else and ensure that the server does not proccess the request.

This is a difficut issue to completely address if there exists at least one CSRF opening. Attackers will take advantage of this and use it to gain a valid security token to issue a CSRF attack

Solution #1: Prompt the user to re-enter their password for high-risk operations i.e. password change, transfering money, buying things

Solution #2: Use "out-of-band" verification process i.e. USB key with a hardware token, or a 1-time disposble password, or 2-step verification process via text message.

Solution #3: Use CAPTCHA challenges; downside on UX

ATTACK #9: Using Component with Known Vulnerabilities

Libraries/Components that you use don't necessarily publish their vulnerabilities. This is especially the case if it is open source.

Components often run with the same level of access as the application.

How to test:
- Perform inventory of all open source libraries used
- Static analysis tools can be used to automate this search

Solution:
- Most components/libraries don't release patches; instead they fix it in the next release
- Update your dependencies to latest version

ATTACK #10: Unvalidated Redirects and Forwards

When we redirect or forward users without validating the destination, it provides attackers a door to trick users into visiting malicious websites

Exploit:
1) Present users with a login link in email or IM that has a redirect URL

http://site.com/login.php?redirectUrl=http://evil.com/

2) The user will then be prompted to enter their credentials on legitimate site. Upon successful AuthN, they will be then redirected to whatever was defined on the redirect url

3) The user will be then shown on evil.com the exact same web that prompts them their username and password was incorrect. The user will then re-enter their credentials on the impersonating form. Upon succesfully submitting their credentials which are sent to the attacker, they will be then redirected to the original website.

4) The original website will not display username and password because they had already established a valid session on step 2)

How to test:
- Look for areas in the code that ask the user to input information
- Enter dummy urls that your application would never send a user i.e. google.com
- If it succeeds, there is no url white list cross referencing or validationing happening

Solution:
- Check destination prior to redirect or forward
- Implement proper access controls

Share

Notes – Android Network Service Discovery API

STEP ONE: Register Your Service on the Network

1) Define your service as a NsdServiceInfo object
2) Init socket server if using one
3) Create a NsdManager.RegistrationListener object
4) Call NsdManager.serviceInfo:NsdServiceInfo, protocolType:int, listener:NsdManager.RegistrationListener

STEP TWO: Discover Services on the Network

1) Create a NsdManager.DiscoveryListener object
2) Call NsdManager.discoverServices (serviceType:String, protocolType:int, listner:NsdManager.DiscoveryListener)

When defining this listener, it needs to handle:

– Verification the type of service
– If it has found it’s own service by picking up it’s own broadcast
– Verification the name of service

STEP THREE: Connect to Services on The Network

Resolve Phase – Obtain connection information prior to connection

) Create a NsdManager.ResolveListener object
) Provided that the discover found the correct service, call NsdManager.resolveService(serviceInfo:NsdServiceInfo, listener:NsdManager.ResolveListener)

When defining this listener, it needs to handle:
– If the service names match, then it’s on the same IP
– If it finds the correct service is found, then keep a reference to that service’s NsdServiceInfo object, port number and IP address represented as an java.net.InetAddress object

STEP FOUR: Unregister Your Service on Application Close

– Availability of NSD should be tied to app lifecycle
– Unregister when app is closed so that other apps stop trying to connect to it
– NSD is expensive so invoke it only when the user needs it

Source – http://developer.android.com/training/connect-devices-wirelessly/nsd.html

Share

Notes – Android Native Development Kit

Process

– NDK Only works on > API 3
– script: ndk-build – generates binaries and adds those binaries to the project path
– Even if your Android app has no Java src code, .dex will still be created.

– ‘native’ keyword: Compiler hint to look for implementation in native library than in Java code.

– .so files: Native shared libraries

– .a files: Link to other native library

– JNI: Java Native Interface; Bridge between native and Java

– ABI: Application Binary Interface; describes how your application’s machine code will interact with ARM, MIPs and x86 hardware.

– NativeActivity: Declare this in the Android Manifest if your app has no Java Activities

– Android.mk (REQUIRED): Module Config file for ndk-build script; references src files, build flags and libs.

– Application.mk (OPTIONAL): Manifest of modules the app needs like ABI, tool chains and standard libs.

Workflow

Step 1):
Design your app, deciding which parts to implement in Java, and which parts to implement as native code.

Step 2):
Create an Android app Project in Eclipse as you would for any other Android project. If you are writing a native-only app, declare the NativeActivity class in AndroidManifest.xml. You can do so from the Eclipse/ADT Android Manifest Editor, or by hand-editing the file. For more information, see the Native Activity section.

Step 3):
Create an Android.mk file describing the native library, including name, flags, linked libraries and source files to be compiled in the ‘JNI’ directory.

Step 3b) OPTIONAL: Create an Application.mk file configuring the target ABIs, toolchain, release/debug mode, and STL. For any of these that you do not specify, the following default values are used, respectively:
ABI: armeabi
Toolchain: GCC 4.6
Mode: Release
STL: system

Step 4):
Place your native source under the project’s jni directory.

Step 5)
Use ndk-build to compile the native (.so, .a) libraries.

Step 6)
Build the Java component, producing the executable .dex file.

Step 7)
Package everything into an APK file, containing .so, .dex, and other files needed for your app to run.
Note that Eclipse can perform steps 5. through 7. in a single operation.

Native Activities and Applications

– Declare NativeActivity in the manifest if you have no Java in your Android app
– Limitations: Sensors, input events, and assets need native interfaces to access this data instead of JNI
– native_activity.h: Native activity class that contains callback and other data structs; Callbacks must be non-blocking otherwise ANR pops up; Src can be found at /platforms/android-9/arch-arm/usr/include/android/native_a ctivity.h
– android_native_app_glue.h: Util for callbacks, iputs events, etc; These types of events need to be in a seperate thread to prevent blocking main thread; Src is at /sources/android/native_app_glue/android_native_app_glue.c

[Using the native-activity.h interface]

To create a Java-less Native app:

1) Create project in eclipse
2) Delete pre-generated Activity
3) Select Project -> Right Click -> Android Tools -> Add Native Support
4) AndroidManifest.xml needs to configured to -not- have code

5) Name of the activity must be android.app.NativeActivity

6) Add meta-data that references the shared library that is the entry point to the native app

   <meta-data android:name="android.app.lib_name" android:value="native-activity" />
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>

   </activity>
   </application>
</manifest>

7) Define the native activity in native code. The equivalent of main() function is ANativeActivity_onCreate()
8) Set the ANativeActivity->;instance field to the address of any instance of specific data that you want to use
9) Implement anything else that you want your activity to do upon starting
10) Implement the rest of the callbacks that you set in ANativeActivity->;callbacks

11) Develop the rest of your application.

12) Create an Android.mk file in the jni/ directory of your project to describe your native module to the build system; (See section on Android.mk)
13) Commandline to root of project, Compile using ‘ndk-build’ command
14) Deploy /bin/*.apk

Share

Notes On How To Hack A Web Application

hacker

Overall
– Understand Software Security (sec = short form)
– Understand security features in web browsers
– List common attacks
– For each attack, understand the attack, it’s technique and how to mitigate

[Part 1 Intro to Soft Sec.]

– More code increases chance of bugs
– Threats can come from inside or outside the company

Problems
– Security and privacy expectations are implicit
– Software Security is a relatively young field
– Software failure is a real and pervasive problem
– We need to build software that is secure and can be secured
– The problem with penetration testing is that it does not provide a solution to the problems it discovers

Two Broad Classes of Security Defects

– Bugs happen in Implementation
– Flaws happen at Architecture Design
– Bugs/Flaws in software is 50/50

– Bugs fixed in code
– Flaws fixed in Architecture Risk Analysis
– Defect is both implementation and design vulnerability

Trinity of Trouble
– Connectivity: Everything is connected to the internet
– Complexity: Simple UX ironically leads to more complicated code
– Extensibility: Software must be flexible enough to work with code that hasn’t been made yet. Client-server model is the simplest attack pattern to exploit. As a server-side developer, you must ensure the system can defend itself against misbehaving clients.

Impacts of Software Failure
– Financial loss
– Data loss
– Performance loss
– Brand rep loss
– Customer trust loss
– Compliance failure

[Part 2 – The browser sec model]

Same origin policy: Prevent different domains from interacting with each other

Web Browsers and Web Applications
– Same origin policy: Permits scripts running on pages originated from the same site or origin; Client-side is responsible for enforcing strict separation
– Exclusions: HTML Img, Scripts, and Style sheets
– The browser security model prevents access of content from different origins
– DOM: Document Object Model: Used to represent HTML and XML
– Web browsers use DOM optionally but for JavaScript to execute, it is required
– Mashups: Getting data from multiple origins and having them interact with each other violates the Same Origin

[Part 3 – Attack & Defense Vulnerability Discovery, Prevention]

ATTACK #1: XSS – Cross Site Scripting

Bypass the Same Origin Policy. There are two types:

1) Persistent: Stored on the server-side, downloaded when client downloads compramised web page
2) Reflected: User input has the malicious script sent to the application, it’s executed on the server, the results are sent back to the browser

Examples of reflected:
– Cookie session hijack
– Re-writing HTML
– Impersonating requests as a legit user
– Faking a login/password screen
– Performing port scan on LAN

– Because the script comes from a trusted web server, it does not violate the Same Origin Policy
– Same origin policy limits HTML content but does not limit script blocks, images and CSS. It can load from another source but it limits what gets executed. This mean malicious scripts get downloaded at the same time the DOM is created.
– Man in the middle attack: Relay I/O the user sends and receives from a compromised site.

Protecting Against XSS
– Encode outputs: Select an encoding method that does not produce control sequences; HTML encoding for HTML output;
< is a “<" symbol; URL encoding for log files; This forces content to be treated like plain text instead of runnable code - Constrain inputs: perform regEx and parsers to check syntax on the server side - Safely store and process data using safe methods Mitigation & Remediation
– Client-side validation can be easily by passed by an attacker
– Server-side must reject bad input rather than process it
– Java: Use jTidy as an encoding library

How to Test for XSS
– Check if input validation is being done on the server
– Check if output encoding is being done on the server
– Check if malicious XSS code is between HTML tags, inside HTML attributes, or in

<script/>

blocks
– XSS in HTML tag check: Embed JavaScript alerts (i.e. displaying your session ID) in your server-side code to check for vulnerabilities; if the alert is displayed properly, then you are not doing any output encoding. If it is done properly, the JS alert script will appear as plain text
– XSS in HTML attribute check: Check for presence of malicious code store in attributes/callbacks like onLoad,

onError, onMouseOver
– Rostering: Use a white list of acceptable location to reference remote resources i.e.

http://myWebsite.com/balloon.jpg vs http://atacker.com/ballon.jpg
– XSS in script tags: Ensure the content you have in the

<script/>

tags is the one you wrote

ATTACK #2: SQL Injection

1) SQL Concatenation: Ability to assemble to a dynamic SQL query with OR, SELECT, JOIN, UPDATE
2) Stored procedure w/ runtime variable: Inject un-intended parameters
3) Prepared Query object (name-value pairs) where the value references run-time server-variable i.e. currentDate()

– SQL Injections cause apps to return different data to the attacker than what should normally be returned
– Static Analysis tools: Scan code for SQL Queries that combine both user and hard coded defined input;
– General approach to discovering vulnerabilities is to add tautological parameter values and examine the results
– One example for a username and password would be ” and ‘1=1–‘
– Submit inputs via POST and GET, Cookie Values and Header Values

Check for input-based vulnerabilities:

– Integer:

http://foo.com/bar.jsp=?value=123*1

If this executes as 123, it is being interpreted as code instead of as an integer

– String:

http://foo.com/bar.jsp?value=A’+’BC

If this executes as ABC, it is being interpreted as code instead of as a string

– Errors:

http://foo.com/bar.jsp?value=123/0

If this throws an error, it’s because it’s being interpreted as code

Information leaking through back doors: Egress Connections; Timing Attacks

ATTACK #3: Header Manipulation

– Attackers modify the HTTP response coming from a trusted web app
– Attackers send HTTP request that forces server to send two HTTP responses; attackers control the 2nd response
– The headers in the response separate the original header using %0d%0a which is the URL-encoded equivalent of Carriage Return Line Feed characters

\r\n

and allow attackers to define a new http response containing a malicious payload. The client will make only one request but it will be sent two. The first one ends abruptly while the second one is malicious.
– Header manipulation is a great way to launch XSS.
– Solution #1: URL encode strings before they become a part of HTTP response headers
– Solution #2: Validate user input for

CRLF, \r\n, %0d%0a

, any other funny encoding

ATTACK #4: System Information Leak

– Attackers can learn about a system when it provides too much information or information that was unintended.
– Examples: Verbose error messages tip off what an attacker can and cannot do; Never display a stack trace to a user, although useless to a typical user, it would provide insight to an attacker (reverse engineering)

How to Test for information leaks:
– SQL/XPath injection; testing for valid username using the forgot password feature
– Data-type confusion: Pass an invalid date to get access to a stack trace
– XSS on the common error page

Solutions:
– try/catch blocks – handle the exceptions instead of display them
– redirect users to a relevant error page, i.e. NoSuchPage.html when a 404 happens

ATTACK #5: Path Manipulation/Directory Traversal

– Exposed File I/O operations allow for unauthorized CRUD calls on the system’s resources
– Example: http://foo.com/../../../../etc/passwd

String downloadFileName = request.getParameter(“filename”);
File file = new File(“c:\\tomcat\\webapps\\myapp\\imguploads\\” + downloadFileName;

On the user-interface, if we can specify the value of what would be downloadFileName variable, this would be allowed

“../../../../../../../../../../../boot.ini”

– Testing: Look for areas in the code that take in a string representing a file path; use “../../foo.txt” and add

“../” to go beyond the application directory

– Solution #1: RegEx only acceptable characters
– Solution #2: chroot directory permissions to define where can read and who can write

ATTACK #6: Cross-Site Request Forgery (CSRF)

Piggyback on victim’s sessionID so that an attacker can make legit requests on their behalf unbeknownst to them

– Exploit: Attackers create an

<img>, hidden <form>, <IFRAME>

or Javascript that calls actions in the background
– Example:

<img src="http://bank.com/transfer?to=attacker&amt=200"/>

Note how this is not a valid bitmap to display so nothing will show and it will work because it is being done on a valid user session.
– How to test: Use HTTP proxy software like Fiddler; inspect the request and response
– Prevention: Pair session ID’s with a security token; the unique random security token is store on the server and it’s store as a hidden parameter in the HTML form sent to the user

ATTACK #7: Hidden Field Manipulation

– Attackers change hidden or disabled form fields on a form
– Example #1: A disabled button is sent to the client; attackers enable the button locally and are able to click on the button thus executing the action
– Example #2: Instead of manipulating the HTML, they can just modify the request parameters to do what the button click would have done using tools like BurpProxy
– If attackers can manipulate the requests, they can control the application logic
– How to test #1: Use the same software proxy tools to intercept and change hidden field parameters on requests and observe the responses. If an exception is thrown
– How to test #1: Use browser tools like Firefox’s Web Developer plugin to enable form fields to see all hidden fields

– Solution #1: Input validation on the client side
– Solution #2: Resource permission check on the server-side to validate the current logged in user is allowed to access said resource

ATTACK #8: Cookie Security

Cookies are name-value stores to track userid, sessionid, and preferences; Attackers can then use this information to impersonate the user
– Attackers can transfer and view cookies using insecure protocols
– Attackers can access cookies if it is shared among multiple applications and the attacker is in control of one of those applications
– The longer a cookie persists, the longer an attacker has time to access it
– Allowing cookies to be accessed by JavaScript can be harmful if the JavaScript did not originate from the original application (i.e. XSS)
– Solution: Some browsers support HTTPOnly flag which prevent client-side JavaScript from reading it’s cookies
– How to test #1: 1) Go to the website you want to test 2) type

javascript:alert(document.cookie)

3) if you see an alert popup with name-value pairs, it means the HTTPOnly flag is not set
– How to test #2: Use HTTP proxy to see if the HTTP header cookie config like secure flag, domain, path and expiration
– How to test #3: Static analysis tools to search the code base for any areas where there is a Cookie object instantiated; there you can view what flags have been set
– Solution #1: Setting the secure flag on cookie so that it can only be sent over HTTPS
– Solution #2: Expire cookies to shortest time possible
– Solution #3: Set domain and path to be only used on your application; this prevents it from being shared with other apps thus reducing the attack surface
– Solution #4: Don’t use cross application cookies; less secure applications may have access to sensitive information stored on the shared cookie
– Solution #5: Set the HTTPOnly flag to true

ATTACK #9: Session and State Management

HTTP is stateless. Every request is discrete. The only way it knows any two requests are related is via a common sessionID. Application server software automates the creation of sessionID’s to be un-guessable, non-colliding, and exclusive for only session management (meaning don’t use this string for any other purpose).

Exploit #1: SessionID Theft can be done through XSS

– Malicious cross-site JavaScript can access the cookie i.e. alert(document.cookie); instead of displaying in a browser, the cookie information is relayed to a website under the control of the attacker. The attacker then sets their own browser’s request to the same sessionID and beings to impersonate the victim’s requests

Exploit #2: Man in the middle attack

– Attackers look at the un-encrypted network traffic and look for session Id’s in the HTTP requests

Exploit #3; Brute force prediction

– If the application is creating session Id’s based off a pattern (i.e. sequentially), it is easy for attackers to predict and create their own sessionID
– If the range of possible session Id’s is small, it can be predicted using basic math and script

Exploit #4: Session fixation; attackers define the SessionID and the server treats it as legit

– Attacker request from the application server an arbitrary sessionID
– Attacker then presents the victim with a web link to the application’s login page with the known sessionID
– Victim enters username and password with the known sessionID
– Application authenticates the user but does not overwrite the known sessionID with a new sessionID
– Attacker is now in possession of a sessionID that has been authenticated

Solution #1: Expire cookies which store session Id’s
Solution #2: On logout or on time out, application server must invalidate sessionID
Solution #3: Application server should ignore session Id’s stored in variables on GET and POST requests
Solution #4: Cookies should have random changing token
Solution #5: Encrypt network traffic using SSL/TLS to prevent man in the middle
Solution #6: Application logic should only associate users with session ID’s after authentication, not before
Solution #7: Session Id’s before authentication should be considered invalid by the application
Solution #8: When a session ID is created, it should be mapped to an IP address. May not work in environment with load balancers where IP addresses may not
Solution #9: For extra sensitive transactions (i.e $), have the user re-authenticate
Solution #10: Application server should only accept sessionID’s created by that application server
Solution #11: Regenerate a sesionID after login
Solution #12: On cookies that contain the sessionID, set the secure attribute making the SSL/TLS mandatory for transmission
Solution #13: Use large random IDs to make them less predictable
Solution #13: Reduce dependence on persistent cookies

ATTACK #10 Weak Access Controls

Attackers are able to perform operations outside of what a typical user is expected to perform.
– Horizontal access is when an attacker can see the data of others in the same role
– Vertical access is when an attacker is able to access behaviors and data outside of their role i.e. Employee role accessing administrator functions

How to test #1: Changing the query string (Horizontal access)

http://site.com/confirmation.jsp?refNo=123 is your own

http://site.com/confirmation.jsp?refNo=456 is someone else’s data

How to test #2: Changing the URL

http://site.com/adminConsole.jsp

How to test #3: Parameter Tampering – In REST operations, delete and update operations can put in a arbitrary record ID to artifacts they should not have access (Horizontal access)

Hot to test #4: Parameter Tampering – When they access an application as an admin (or monitor the transactions of admin), the request and response is recorded and studied. Then the attacker will attempt to perform the same actions as a lower privileged user.

Solution: Weak access controls are architectural flaws; Implement a white list of users (Entitlements) to dictate what data and behaviors a user can possess; Make the access permissions as close to the object as possible i.e. don’t make global entitlements.

Share

The Dilemna of Mobile Apps Development

Source – http://www.commitstrip.com/en/2014/08/18/the-dilemna-of-mobile-apps-development/

Share

Review – Google Cloud Platform Roadshow: Toronto Edition

[Update – Aug 15/14]: I may have misinterpret some parts of the presentation. Paul Newson took the time to help me make the corrections. Thanks man!

The Google Cloud Platform Roadshow landed in Toronto today at the head offices of Google Canada. It was a 4-hour high-level sales pitch of what is available in their current Cloud services offerings. It wasn’t a revisit to their DataStore or App Engine but their utility was mentioned quite often throughout the presentations. No one in the audience could doubt how impressive the technologies they have to offer at scale. However interesting questions from the audience did not hide the doubt could Google be trusted?

IMAG0095

The afternoon started off with Jeromy Carriere (@sjcarriere) telling a familiar tale where a large company (Google) has invested in so much infrastructure to the extent they can commercialize the technologies they’ve been using internally to support their own business. As prices for hardware go down over the years, Google has priced their services to transfer the savings to their Cloud customers.

IMAG0098

Mandy Waite (@tekgrrl) followed up with the first of her two presentations. In Blurring The IaaS/PasS Divide, she described the traditional model of how we’ve had to choose between one or the other and how it’s possible to have the best of both. AppEngine is a PaaS that saves web application developers a lot of headaches so that they may focus on the coding tasks. Compute Engine is an IaaS that allows you to manage many Virtual Machines that can come in a variety of Operating System flavors configured with whatever services running on them. She then did a pretty cool demo of a web app (App Engine) that asynchronously solved Sudoku puzzles when shown on a webcam. App Engine received the snapshot bitmap from the client, send it to the TaskQueue which then sends it to next available Computer Engine Managed VM. That VM is configured to run the OpenCV library which cannot be run within App Engine. OpenCV parses the displayed numbers and the empty cells. The result is then piped into an algorithm that will solve any Sudoku puzzle. The original image is then modified to have the empty cells populated with the computer generated solution. When that Task completes, the final solution image is sent back to the client via App Engine. A very cool demo of how App Engine can leverage libraries itself cannot run. Rather than have one VM process all requests, Compute Engine can be configured to scale up to as many services as needed by the demand. When the demand is gone, inactive instances can be shutdown.

sudoku

Next up was Paul Newson (https://plus.google.com/+PaulNewson) “From Data to Meaning”. He talked about how they’ve gone from MapReduce to Hadoop for processing large datasets in clusters. A common problem with large datasets we accumulate is that 1) The data is not where you want and 2) the data is not in the format you need it to be. He then provided a demonstration of how Hadoop can be the solution using the following “HDFS connectors”:

These connectors provide a way for Hadoop to talk to Google Cloud Storage, BigQuery, and Datastore as if it were talking to it’s native HDFS storage system.

A typical workflow would start off with your data in Cloud storage. Then the connectors would then transfer your data into Hadoop which will be distributed to many VM’s. Each VM would apply whatever operations on them. The results from each node get piped back to somewhere else in Cloud storage. Paul’s analogy was “Why use a wheelbarrow when you can use a big truck?” We’ve been doing ETL for years but what could take hours to process could be reduced to seconds through Hadoop instances. His second demo was equally as impressive as he took trillions 3 billion genomic records normalized by Hadoop and loaded all of into BigQuery. Then he was able to write SQL queries to derive insights in tens of seconds what could possibly take hours on a single machine.

Recommended video on the Evolution of MapReduce at Google and “Google Cloud Dataflow”

After a short break, the show continued with Paul Newson’s second presentation on “Containerizing the Cloud”. He described how Google has been able to perform reliable deployments to production with minimal disruption to end users. When you think about Search, Gmail, and Youtube, Google is multi-tenant and each of these services are made of different components that they themselves have been containerized. Each week, 2 billion containers are started to support these and many other services. This is not humanly possible to manage. A cluster scheduler is responsible for identifying the next available container to be initialized.

IMAG0100

Paul then talked about “Kubernetes” open source initiative which they use for cluster management written in Go. It’s a middleware that tracks which containers are communicating with other containers (i.e. Front Ends and Back Ends). Google uses Kubernates for staged rollouts some containers with old code can be brought offline while the containers with new code take its place. It’s not a good idea to bring down all instances all at once because once users start using the service when it’s back online, it will be difficult to rollback. Staged rollouts allows for production issues to make their appearance in an instance where their risk can be mitigated.

Related Video On Docker: Google I/O 2014 – Containerizing the Cloud with Docker on Google Cloud Platform

The final session of the day was done again by Mandy Waite in “How to Design, Build, and run a Cloud app”. She talked about a Google I/O app called WalkShare which collects GPS coordinates on your device, uploads them to an App Engine app which then will mashup with Google StreetView visualization of that GPS data. By sharing a walk with a user, they will see StreetView images of direction you were facing with each step you have previously taken. I dunno. Something makes me feel uneasy sharing my GPS position with strangers. Not only that but you can share the walk with complete strangers too so that they may be able to anonymously comment.

Mandy explained the architecture in high level detail. Google Cloud Datastore was used to store the GPS data. Google Cloud Endpoints where used to sync device GPS records to the data store. To allow for unauthenticated users to post comments on the walk, Capcha was implemented on Computer Engine Managed VM’s. The Captcha library cannot be run on App Engine because App Engine does not have the java.awt.* package that involves image processing (Great example of IaaS|PaaS hybrid). To demonstrate memcache on data that was not persisted, Compute Engine was used again to have managed VM’s run Redis. The key are the walks of users and the value was a set of GPS coordinates. It was a cool example that demonstrate most of the features of a typical web app but with the addition of a native mobile front end and showcased once again how Compute Engine can leverage 3rd party libraries that don’t run in App Engine.

Related Video On Walkshare: Google I/O 2014 – Zero to hero with Google Cloud Platform

The day concluded with “Networking reception with drinks and hors d’oeuvres”. Good thing they had food, beer and wine, I was starving. “Tall” Tom (The Roadshow’s MC), Jeromy, Mandy and Paul made up the Fireside chat panel. As the food was being laid out, all the deferred Q&A was unleashed towards the end. Some of the more controversial questions came up such as can we trust Google to store the private data of its users? It’s well known Google takes the data generated from it’s own users, analyzes it for patterns and takes action on those patterns to drive their main bread & butter which is advertising. Who is to say they will not take the data provided by their Cloud customers so that they may be able to take advantage of it? Tom and Paul re-iterated Google’s strict policies on the privacy of data and the extremes they go to protect it. There are number of protocols in place that range from the physical security of their secret data centers to the ethical governance on who can access and what kind of data can be accessed. Even though I am aware of these protocols, I still share the same fears as those in the audience.

IMAG0097

This didn’t come up but it reminded me of the story of the pedophile who was caught for having child porn in their Gmail. It’s a double-edge sword as probably the lives of one or more children were saved but then it demonstrates a means how privacy can be compromised. I digress. Paul did close out the privacy question by reminding us that the foundation of Google’s business is based on trust. Without it, they wouldn’t be there to sell Cloud services to us. He also reminded us there was a time where we were scared to buy things online. It took a while but eventually we started whipping out our credit cards to place online orders. The point was made that it’s a matter of time before companies can create a value proposition that alleviates and surpasses any fears consumers would have in using a public cloud service.

Some might argue that this time has been here for a while if you look at smaller younger companies. However if you look at larger companies that have a lot more to lose, many still have not made the transition into cloud because the risk of swapping technological pillars is so great. Jeromy’s keynote highlighted how competitive the Cloud business has become over the years. As prices for hardware continue to drop year after year, the price for cloud services drop but not as much. As a result, there is strong growth for large companies themselves to invest into their own private cloud infrastructure where they themselves can host multi-tenant their own services. While Google and other large tech companies continue to sway other large enterprises into using their services, some of the companies they target strive to keep their data and the insights it may yield in-house. At the end of the day, it will come down to money no matter how we developers code it. Cloud is a very exciting business to be in whether you are in the public or private.

Overall, I did enjoy spending my time at Google Canada HQ. The domain of problems that concerns me in the present and in the immediate future are of the native mobile sort. You cannot buy into a technology unless you know what it is capable of doing. The team did a great job in showing the audience how to leverage some of the technologies that have been a part of Google’s success. When the day comes I need to make decisions about making data available anywhere, anytime and to anybody, I’m glad I went to the session to become informed what choices are there available in scaling and distributed computing.

Minor improvements I may offer to future Roadshow event is to break the lull between 1-2pm with a Youtube playlist. I managed to kill the time with the free wi-fi which was great. The other improvement is to actually have a fireplace video running in loop during the “Fireside chat”. All in all, the team had the essentials covered. Great show guys and gal!

IMAG0104

One cannot go to Google Canada HQ and not take notice of the awesome amenities they have other than the prime downtown location. First of all the have a patio. Second the patio has mini golf course on it! Third is an on-site cafeteria where you never have to worry about food. Looks like a nice place to work at!

IMAG0101

IMAG0102

IMAG0103

Share

Navigation Drawer Checklist

When the Navigation Drawer is open,
1) the action bar changes it’s title with the App name
2) Remove any actions contextual to the screen behind it
3) Overflow menu will remain visible

Don’t place actions in the navigation drawer itself

If the user is in an Contextual Action Bar (i.e. Search, Copy & Paste, etc), replace the CAB with a standard action bar and the above rules apply

Upon first time installing the app, display the Navigation Drawer automatically. This will make the user aware of its existence

Disable automatically showing the Navigation Drawer, the first time the user opens it explicitly. This demonstrates the user understands how to open the drawer. Subsequent app launches will have the Navigation Drawer closed.

Navigation Drawer Styling – should be between 240-320dp in width, each row should be at least 48dp or more in height.

Create Navigation Drawer Icon – http://romannurik.github.io/AndroidAssetStudio/icons-nav-drawer-indicator.html

Source – “Navigation Drawer” @ https://developer.android.com/design/patterns/navigation-drawer.html

Share

Want to be a panelist @ #DevTO’s NCFOP?

splash-500

Who
Moderator
2-4 Senior Developers
Live audience of developers with varying experiences

When
Call for Panelists Deadline: Friday, July 18
Actual event: #DevTO Monday, September 29, 2014 @ 6:30pm

Where
Exact venue TBA in August 2014
Will be in Downtown Toronto or just outside it accessible via TTC

Panelists
2-4 senior programmers who continue to code/innovate in a relevant programming language today
Must have proven track record of re-inventing themselves as languages come and go
Currently in a position writing new code for an innovative role product and/or services in the past 12 months
Not in a support developer role performing routine maintenance and bug fixes
Each panelist will represent an industry sector they have experience in i.e. Medical, Finance, Marketing, Science, Enterprise, etc

What
Panelists will be interviewed in front of an audience asking questions like:
What goes through their mind when tackling a new language?
What are their reasons not to leave programming?
Why did they not leave for management or startup their own company?

They also be asked to answer tough questions:
Thoughts on job outsourcing to India, China, etc.
Losing their job, getting back on their feet
Does the industry make it hard for women or they getting a fair deal like anyone else?

Friday July 18th Friday July 25th is the Call For Panelists deadline. A shortlist will be created. Final panelist selection will be based on the balance between many years of experience and the relevance of the technology they are currently practicing (Sorry Microsoft Access Dev).

Why
Overall Goal/Takeaway: Inspire the younger generation of coders with knowledge from experienced folk so that they may have longevity and prosperity in the industry.

Share

Values for declare-styleable attr tags

Running through a tutorial for creating a custom views at http://developer.android.com/training/custom-views/create-view.htm, I was blocked by the lack of information what are the possible values for

<declare-styleable/>

Turns out as I learned from this helpful blog post at http://chaosinmotion.com/blog/?p=179, the possible follows are as follows:

  • reference
  • string
  • color
  • dimension
  • boolean
  • integer
  • float
  • fraction
  • enum
  • flag
Share

Eclipse SVN: Subclipse vs. Subversive

Where I work, we use both SVN and Git. I’ve dumped SourceTree for Eclipse Kepler’s integrated Git client which is actually pretty nice. For an integrated Subversive client, over the years I’ve jumped between Subclipse and Subversive. This here looks to be the Definitive Thread on which one to choose. For me, I’ve gone ahead with Subclipse with my current Eclipse Kepler install.

http://stackoverflow.com/questions/61320/svn-plugins-for-eclipse-subclipse-vs-subversive

Share

Older posts «