Skip to content

Instantly share code, notes, and snippets.

@maretekent
Created March 28, 2018 18:38
Show Gist options
  • Save maretekent/be7fe1b99fe024ebf74e47d24b1baa75 to your computer and use it in GitHub Desktop.
Save maretekent/be7fe1b99fe024ebf74e47d24b1baa75 to your computer and use it in GitHub Desktop.
basic django security key elements worthy noting
XXE injection:
To use these parsers safely, you have to explicitly disable referencing of external entities in the
SAX parser implementation you use.
problem:
from django.http import HttpResponse
from lxml import etree
parser = etree.XMLParser(resolve_entities=True)
try:
document = etree.fromstring(content, parser)
except etree.XMLSyntaxError:
return None
solution:
set parser = etree.XMLParser(resolve_entities=False) -- set it to False
disallowing inline DTD is a good defense against this type of attack,
but implementing this is specific to the XML parsing engine being used.
Command Injection:
Should any non alphanumeric characters be encountered, the re.match() method will automatically escape the input,
preventing malicious control shell characters from being passed to the statlab program.
Although the proposed fix is sufficient to remediate our vulnerable example,
the overall logic and security design for os.popen() method can be significantly
improved by not accepting user supplied myUid value through the request.GET['username'] parameter.
import os
from django.http import HttpResponse
import re
def executeCommand(request):
myUid = request.GET['username']
matchResult = re.match(r"[0-9A-Za-z]+$", myUid)
if not matchResult:
return HttpResponse("Inva
out = os.popen("/usr/bin/statlab " + "-" + myUid).read()
return HttpResponse(out)Copy-paste code here to remove the line numbers.
Session Fixation:
1. Ensure that only server generated session values are accepted by the application.
2. Upon a successful login, invalidate the original session value, and re-issue a new session value.
3. Prevent the application from accepting session values via GET or POST requests and
instead store session values within HTTP Cookies only.
def authenticate(request, username, password):
user = verify_uname_password(username, password)
if user and user.is_active:
request.session.flush()
request.session.cycle_key()
@maretekent
Copy link
Author

Cross Site Request Forgery (GET):
It is bad practice to implement Update, Create and Delete operations that
rely on user supplied input via HTTP GET requests, this is an example of misuse of HTTP Verbs.

@maretekent
Copy link
Author

maretekent commented Mar 31, 2018

Click Jacking:
To defend against Click Jacking attacks the web server should be
configured to send X-Frame-Options in the response headers.

Configuring the X-Frame-Options to either DENY, SAMEORIGIN, or
ALLOW-FROM will prevent malicious websites from embedding your application's content.

I.e. it will prevent the browser from loading your application content within or <iframe> tags of other websites.

In Django, this can be configured by specifying the clickjacking.XFrameOptionsMiddleware middleware to the following directive:

X_FRAME_OPTIONS = 'DENY'
However, a more scalable approach would be to deploy HTTP headers globally,
at the web server layer. Let's see how we can configure Apache to set the X-Frame-Options header across all pages.

@maretekent
Copy link
Author

# Prevent Clickjacking using X-Frame-Options header Header set X-Frame-Options "deny" # Prevent Clickjacking using Content Security Policy (Not supported by all major browsers yet) Header set Content-Security-Policy: frame-options 'deny'; # Chrome / Firefox Header set X-Content-Security-Policy: frame-options 'deny'; # Internet Explorer

@maretekent
Copy link
Author

Insecure URL Redirect:
extra validation very important.
if url and url == "https://sso.codebashing.com":

@maretekent
Copy link
Author

Insecure Tls Validation:
As with any user supplied input, it is important to ensure there is a context specific input validation strategy in place. For example, consider the case of a TLS/SSL man-in-the-middle attack, that could abuse the incorrectly defined certificate validation logic.

@maretekent
Copy link
Author

Insecure Object Deserialization:
Most programming languages including Python provide built-in ways for developers to serialize objects to a byte stream and then re-construct those objects using the deserialization process.

Vulnerabilities arise when developers try to construct an object from an untrusted serialization stream, and they assume that this stream can always be trusted.

If the stream was corrupted, tampered with or replaced prior to deserialization, the deserialized objects may have an unexpected or illegal state.

One of the worst consequences of insecure object deserialization is Remote Code Execution.

If an attacker can make a remote server execute an arbitrary command - they could then:

Upload and execute a backdoor.
Pivot, and attack other systems on the same network.
Use the server as a part of a botnet.
Use the server as a cryptocurrency miner.
In this lesson, the deserialization vulnerability in the Python pickle module will be explored. This module implements an algorithm for serializing and deserializing a Python object structure

@maretekent
Copy link
Author

screen shot 2018-03-31 at 23 47 27

@maretekent
Copy link
Author

The json.loads() method then saves the extracted JSON to the exceptionRecordJson variable. And after that its value is passed to the ExceptionRecord constructor class that records the parced error message to the server log.

When the parsed error message is processed, the self.wfile.write() method sends the response in the form of JSON back to the client .

@maretekent
Copy link
Author

content_length = self.headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0

pickledError = self.rfile.read(length)

exceptionRecord = cPickle.loads(base64.b64decode(pickledError))

self._set_headers()
jsonRecordError = self.rfile.read(length)
exceptionRecordJson = json.loads(jsonRecordError)
try:
exceptionRecord = ExceptionRecord(exceptionRecordJson["version"], exceptionRecordJson["log"], exceptionRecordJson["userID"])
saveError(exceptionRecord)
self._set_headers()
self.wfile.write(createJSONSuccess(exceptionRecord));
except (ValueError, TypeError, NameError) as e:
log_error(e, exceptionRecord)
self._set_error_headers()
self.wfile.write(createJSONError(e,exceptionRecord));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment