Showing posts with label http. Show all posts
Showing posts with label http. Show all posts

Dec 11, 2022

Python-HTTPX Vs. Python-Requests

#!/usr/bin/evn python3 

# -*- coding: utf-8 -*-

import httpx

import requests

 

In general, both the module are similar, Here, I just make a simple comparison on what are the differences between Python HTTPX and Requests module.

 


Requests HTTPX
Sessions requests.Session() httpx.Client()
Async support
Not supported
httpx.AsyncClient()
HTTP/2 support
Not supported httpx.Client(http2=True)
httpx.AsyncClient(http2=True)


I have started moving over to HTTPX since Dec 2022.


Links:

Sep 26, 2022

HTTP Security

Here are a few commonly seen HTTP security features.


Content Security Policy (CSP)

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate Cross-Site Scripting (XSS) and data injection attacks.  

To enable CSP, you need to configure your web server to return the Content-Security-Policy HTTP header.  If the site doesn't offer the CSP header, browsers likewise use the standard same-origin policy. 

CSP makes it possible for server administrators to reduce or eliminate the vectors by which XSS can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those allowed domains, ignoring all other scripts (including inline scripts and event-handling HTML attributes).

Examples:

Content-Security-Policy: default-src 'self'

Content-Security-Policy: default-src 'self' example.com *.example.com

Content-Security-Policy: default-src 'self'; img-src *; media-src example.org example.net; script-src userscripts.example.com

Content-Security-Policy: default-src https://onlinebanking.example.com

Content-Security-Policy: default-src 'self' *.example.com; img-src *

Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi


Using HTTP cookies

An HTTP cookie is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests. Typically, an HTTP cookie is used to tell if two requests come from the same browser—keeping a user logged in.

Cookies are mainly used for three purposes: Session management, User preferences, and Tracking.

Instead of using cookies, modern APIs for client storage are the Web Storage API (localStorage and sessionStorage) and IndexedDB. 

Example (set cookies) on sending cookie to client browser.

Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT;

Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly

Set-Cookie: mykey=myvalue; SameSite=Strict

Example () on sending stored cookies to web server.

Cookie: yummy_cookie=choco; tasty_cookie=strawberry

Additional ways to mitigate attacjs involving cookies:

  • Use the HttpOnly attribute to prevent access to cookie values via JavaScript.
  • Use the Secure attribute to prevent MiTM attack and ensure its never sent with unsecured HTTP.
  • Use short lifetime, with SameSite attributes to protect sensitive info.

 

Same-origin policy (web security)

The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors.  

"Same origin" means the protocol, port (if specified), and host are the same for both. It is referenced as the "scheme/host/port tuple".

For example, an URL at http://store.company.com/dir/page.html will give origin comparison as below:

URLReasonOutcome
http://store.company.com/dir2/other.html Only the path differs Same origin
http://store.company.com/dir/inner/another.html Only the path differs Same origin
https://store.company.com/page.html Protocol different Fail
http://store.company.com:81/dir/page.html Port different Fail
http://news.company.com/dir/page.html Host different Fail

Other schemes or URL, such as javascript: and about:blank, are inherited origins from the page. But data: scheme get a new security context. file:/// schema is treated as opaque origins. 

Use CORS to allow cross-origin access. CORS is a part of HTTP that lets servers specify any other hosts from which a browser should permit loading of content.

 

Strict-Transport-Security (HTTP header)

The HSTS or HTTP Strict-Transport-Security response header informs browsers that the site should only be accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be converted to HTTPS.

This is more secure than simply configuring a HTTP to HTTPS (301) redirect on your server, where the initial HTTP connection is still vulnerable to a man-in-the-middle attack.

Example of all the present and future subdomains will be HTTPS for a max-age of 1 year:

Strict-Transport-Security: max-age=31536000; includeSubDomains

Strict-Transport-Security: max-age=31536000; preload

Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

To detect if a HTTPS server is supporting HSTS, check the post at When HTTPS is not Sufficient.

 

X-Content-Type-Options (HTTP header)

This is a web server HTTP header to indicate that the MIME types advertised in the Content-Type headers should be followed and not be changed. The header allows you to avoid MIME type sniffing by saying that the MIME types are deliberately configured. 

For example, it can cause HTML web pages to be downloaded instead of being rendered when they are served with a MIME type other than text/html.

Site security testers usually expect this header to be set, such as:

X-Content-Type-Options: nosniff


X-Frame-Options (HTTP header)

This is a web server response header to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites.

The Content-Security-Policy HTTP header has a frame-ancestors directive which obsoletes this header for supporting browsers.

X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN

If you specify DENY, the page cannot be displayed in a frame, regardless of the site attempting to do so.

If you specify SAMEORIGIN, the page can only be displayed if all ancestor frames are same origin to the page itself.


X-XSS-Protection (HTTP header)

This is a server response header sent to browser that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. These protection is unnecessary when sites implement a strong Content-Security-Policy that disables the use of inline JavaScript ('unsafe-inline').

This feature is not a standard feature for all browsers. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Directives:

X-XSS-Protection: 0
X-XSS-Protection: 1
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=<reporting-uri>

Examples:

X-XSS-Protection: 1; mode=block

Apache (.htaccess):

<IfModule mod_headers.c>
  Header set X-XSS-Protection "1; mode=block"
</IfModule>

Nginx:

add_header "X-XSS-Protection" "1; mode=block";


Links:

  1. Content Security Policy (CSP)
  2. Using HTTP cookies
  3. Same-origin policy (web security)
  4. Strict-Transport-Security (HTTP header)
  5. X-Content-Type-Options (HTTP header)
  6. X-Frame-Options (HTTP header)
  7. X-XSS-Protection (HTTP header)
  8. HTTP Request Methods 

May 30, 2022

HTTP Version

How many HTTP versions have you come across? 

We used to be using HTTP/1.0 for years (199x), and we move to HTTP/1.1 and using it for most of the time. And then HTTP working group has introduced to HTTP/2 (aka SPDY) in 2015 and now HTTP/3 (aka QUIC) in 2022.

 HTTP/2 or SPDY, has some new features (like server pushes) and performance improvements (header compression) over HTTP/1.1.

HTTP/3 or QUIC - is a UDP-based stream-multiplexing, encrypted transport protocol that documented under RFC9000. 

As of today, a few web sites have migrated to HTTP/3, for example, www.facebook.com, blog.cloudflare.com and www.google.com

HTTP/3 Check is a hosted QUIC protocol exploration tool used to test whether a server supports the QUIC transport protocol and the HTTP/3 semantics.

Majority of the browsers are supporting HTTP/2 (enabled by default) but not all are supporting HTTP/3 yet. Below are the curl and httx commands to check HTTP version.

$ curl -sI https://www.dell.com -o/dev/null -w '%{http_version}\n'
1.1

$ curl -sI https://www.google.com -o/dev/null -w '%{http_version}\n'
2

$ echo www.youtube.com | httpx -http2 -title -pipeline -vhost

    __    __  __       _  __
   / /_  / /_/ /_____ | |/ /
  / __ \/ __/ __/ __ \|   /
 / / / / /_/ /_/ /_/ /   |
/_/ /_/\__/\__/ .___/_/|_|
             /_/              v1.2.1

                projectdiscovery.io

Use with caution. You are responsible for your actions.
Developers assume no liability and are not responsible for any misuse or damage.
https://www.youtube.com [YouTube] [vhost] [http2]

 

Links:

Aug 22, 2021

Enable HTTP Basic Authentication in Spring Security

How to enable Spring Security in Java Web application? 

To enable Spring security in Java Web application, you need to configure three things -  (i)  declare a delegating proxy filter in web.xml, (ii) add the ContextLoaderListener in web.xml and (ii) provide actual security constraints on applicationContext-Security.xml file. 

This is also known as Spring's "security chain filter", which relies on web container for initialization of delegating filter proxy.

1) Declare DelegatingFilterProxy filter in web.xml

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>



2) Specify the Spring application context file to ContextLoaderListener

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      /WEB-INF/applicationContext.xml
        /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

 

3) Specify Spring Security intercept URL pattern in the applicationContext-Security.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <security:http auto-config="true">
        <security:intercept-url pattern="/admin"
            access="ROLE_ADMIN" />
    </security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user authorities="ROLE_ADMIN" name="admin"
                    password="admin" />
                <security:user authorities="ROLE_ADMIN" name="root"
                    password="root" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

By doing this simple configuration, all URLs ending with /admin to be only accessible with username and password. The two users who have access to this are now admin and root.


How to enable HTTP Basic Authentication in Spring Security using Java and XML Configuration?

Basic authentication is another common ways to authenticate a user in a web application WITHOUT using a form. This is common in the case of RESTful web services clients are not human but application.

In HTTP basic authentication, user login credentials are passed on the HTTP request header, precisely "Authorization" request header. This header sends username/password into request headers, using Base64 encoding.

Other authentication methods include digest authentication, OAuth 2.0, and form-based authentication.

 

To enable HTTP basic authentication using XML config, we use the  <http-basic /> configuration element in Java web app.

To use form login, just replace the <login-form> element in configuration file  applicationContext-security.xml with <http-basic />.

Here is a sample of Spring security configuration with HTTP basic authentication enabled (applicationContext-security.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
 
<http pattern="/home" security="none"/>
<http use-expressions="true">
  <intercept-url pattern="/**" access="isAuthenticated()" />
  <http-basic />
</http>
 
 
<authentication-manager>
  <authentication-provider>
    <user-service>
      <user name="userId" password="passwd" authorities="ROLE_USER" />
    </user-service>
   </authentication-provider>
</authentication-manager>
 
</beans:beans>

1)The first line says that for /home we don't need any security so anyone can access it.

2)The second line <http> says that we are using Spring expression language and that's why we could have used the isAuthenticated() method for intercepting url.

3) The <intercept-url pattern="/**" access="isAuthenticated()" /> means all URLs need authentication and they will use HTTP basic authentication mechanisms.

4) The authentication manager is not in focus but here we are using in-memory authentication provider with just one user is configured whose username is "userId" and password is "passwd".

To enable HTTP basic autthentication using Java configuration, we configure security aspects of calling the httpBasic()  mehtods on the HttpSecurity object passed into configure() mehtod.

Here is a sample of Spring Security configuration to enable HTTP basic authentication using Java code:

@Configuration
@EnableWebSecurity
public class HttpBasicAuthenticationAdapter extends
    WebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth)
      throws Exception {
    auth
    .inMemoryAuthentication()
    .withUser("userId").password("passwd")
    .authorities("ROLE_USER");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .antMatchers("/securityNone").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic()
    .realmName("Your App");
  }
}

We can combine security constraint using joiner methods like and(). If you want to turn off HTTP basic authentication just remove the call to httpBasic() method and you are done.


Links:

May 19, 2021

Active User != Concurrent Connection

I see a lot of people misunderstand about what is "concurrent connection" for a HTTP/HTTPS server.

They tend to use the "number of active users" is equal to the number of concurrent connections, and this wrong. 

Here, I show you how to estimate the concurrent connection needed for a HTTP/HTTPS server. And I'll introduce the tool that I used too.

Scenario (1):

  • 100 active users
  • (average) 60 requests been made by each user within an hour (1 min 1 click)
  • Each request takes (average of) 2 seconds to complete [slow]

This means there are total of 6000 (100*60) requests been made.

And total of 12000 (6000*2) seconds of active connections needed to be served within 3600 seconds (1 hour).

 Thus, concurrent connection = 12000/3600 = 3.33

Scenario (2):

  • 1000 active users ?
Concurrent connection =  33.3 
 
Scenario (3):
  • Each request is served with 1 second (by a powerful server).
Concurrent connection = 1.7
 
Estimation:
For 100 concurrent connections, your server is able to support around 3000 active users (60 req and 2 sec).

 

Of course, in real life, before you calculate concurrent connection, you need to:

  • Estimate the average number of click or HTTP request is need for a user to complete a transaction (including browsing for items).
  • Estimate the average time (in seconds) needed by your HTTP server to response for each request.
  • Use a tool to make 10 concurrent connections to your HTTP server.
  • And finally you will know how many active users that your application (HTTP server) can support.

Here is a tool, called "autocannon" that I use to perform the 10 concurrent connection to my app server.

# install the tool

$ npm install autocannon -g

# perform 10 concurrent connections to app server.

$ autocannon -c10 http://192.168.1.20


Links:

  • https://github.com/mcollina/autocannon

Jun 28, 2009

DoS in HTTP

This weekend, I've been spending time checking on a couple of posting about denial of service (DoS). Of course, it is all begin with the recently HTTP DoS (not TCP DoS), Slowloris.

This is an effort in performing DoS attack to vulnerable HTTP servers rather than TCP services. A few common web servers have been identified to be vulnerable to this type of attack including Apache 1.x and 2.x. But our favorite IIS is NOT vulnerable.

Ans don't forget to check out the DoS attack to HTTP using Google Analytics. This is interesting as it is targetting those shared sub-domain sites, such as blogspot.com, and browsers that allow top level domain cookies. The idea here is, if you can set a large enough cookie (8190 bytes), you can DoS someone's client from accessing the web page. The limit for a cookie is 4K, but you can use 2 cookies at Google Analytics as a attack vector. This is serious.

The other posts from WebSecurity are interesting too. It classifies HTTP DoS attacks for both the browser and web application. One very interesting post from WebSecurity is the "Recursive File Include DoS Attack". See the links below.

Check them out if you have time:

May 28, 2009

HTTP Parameter Pollution

>>>> New type of attack on web applications: Parameter Pollution

At the recent OWASP conference, the Italian security experts Luca Carettoni and Stefano Di Paola demonstrated a new way of manipulating web applications and tricking security systems: HTTP Parameter Pollution (HPP).

This form of attack essentially involves submitting the parameters in GET and POST requests in unusual form or order, or with unusual delimiters. A request like:

GET /foo?par1=val1&par2=val2 HTTP/1.1

will be processed in the normal way, while

GET /foo?par1=val1&par1=val2 HTTP/1.1

with two occurrences of par1 can result in various different server-side variable interpretations, depending on the web server's or application's parsing routine. According to Carettoni and Di Paola, this can cause the application to behave in an unwanted and highly unpredictable way and result in security issues.

Web application firewalls (WAFs) and server security extensions are also vulnerable to HPP attacks. While Apache's ModSecurity module recognises an SQL-injection attack like:

/index.aspx?page=select 1,2,3 from table where id=1

it fails to detect

/index.aspx?page=select 1&page=2,3 from table where id=1

say the security experts. HPP can reportedly also be exploited for launching Cross-Site-Scripting attacks (XSS) on web browsers. The XSS filter of Internet Explorer 8 is apparently among the components vulnerable to this kind of attack.

Carettoni and Di Paola recommend stricter filtering and URL encoding to counteract HPP. They also recommend using strict regular expressions in URL rewriting.

Feb 25, 2009

Top Ten Web Hacking Techniques of 2008!

Top Ten Web Hacking Techniques of 2008 from Jeremiah Grossman.

1. GIFAR
  • (Billy Rios, Nathan McFeters, Rob Carter, and John Heasman)

2. Breaking Google Gears' Cross-Origin Communication Model
  • (Yair Amit)

3. Safari Carpet Bomb
  • (Nitesh Dhanjani)

4. Clickjacking / Videojacking
  • (Jeremiah Grossman and Robert Hansen)

5. A Different Opera
  • (Stefano Di Paola)

6. Abusing HTML 5 Structured Client-side Storage
  • (Alberto Trivero)

7. Cross-domain leaks of site logins via Authenticated CSS
  • (Chris Evans and Michal Zalewski)

8. Tunneling TCP over HTTP over SQL Injection
  • (Glenn Wilkinson, Marco Slaviero and Haroon Meer)

9. ActiveX Repurposing
  • (Haroon Meer)

10. Flash Parameter Injection
  • (Yuval Baror, Ayal Yogev, and Adi Sharabani)

Nov 7, 2008

SQLmap - Automatic SQL Injection Tool

sqlmap is an automatic SQL injection tool developed in Python. Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications.

Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user’s specific DBMS tables/columns, run his own SQL SELECT statement, read specific files on the file system and much more.

Nov 5, 2008

Grendel

Grendel-Scan is an open-source web application security testing tool. It has automated testing module for detecting common web application vulnerabilities, and features geared at aiding manual penetration tests.

The only system requirement is Java 5.

Nov 3, 2008

WebSlayer

WebSlayer is a tool designed for bruteforcing Web Applications, it can be used for finding not linked resources (directories, servlets, scripts, etc), bruteforce GET and POST parameters, bruteforce Forms parameters (User/Password), Fuzzing, etc. The tools has a payload generator and a easy and powerful results analyzer.

You can perform attacks like:
  • Predictable resource locator, recursion supported
  • Login forms bruteforce
  • Session bruteforce
  • Parameter bruteforce
  • Parameter fuzzing and injection (XSS, SQL)
  • Basic and Ntml authentication bruteforcing

Oct 31, 2008

Web-Harvest

Web-Harvest is Open Source Web Data Extraction tool written in Java. It offers a way to collect desired Web pages and extract useful data from them. It is normally called Web Scraping or Web Data Mining.

It leverages well established techniques and technologies for text/xml manipulation such as XSLT, XQuery and Regular Expressions. Web-Harvest mainly focuses on HTML/XML based web sites.