Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Django development and attack and defense testing like?

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

The content of this article mainly focuses on Django development and attack and defense testing. The content of the article is clear and clear. It is very suitable for beginners to learn and is worth reading. Interested friends can follow the editor to read together. I hope you can get something through this article!

I. basic development of Django

In the past, I used 1.8.2 to build a blog, and I still installed it on the machine. I brought it over by the way, of course, the new version will fix a lot of bug, and I still have to learn a new version as much as possible.

1. Download, install and launch # download djangopip install django==1.8.2-I https://pypi.mirrors.ustc.edu.cn/simple/# to create a folder and launch the virtual environment virtualenv django_democd django_demosource bin/activate# to create a folder for django files mkdir learn_djangocd learn_django# to create a project python django-admin.py startproject django_web# to create an application python manage.py startapp django_app# to edit the settings.py file in the django_web Add django_app to apps

In this way, the most basic construction is completed.

Run the service and take a look.

2. MVC and MTV in Django framework

MVC is a well-known pattern: model (model), view (view), controller (controller)

The user enters url on the page, transfers it to the url controller, and then matches the corresponding view function according to url. Viwe will go to the models to get the data, and then models will get the data in the database and return it to the view. The view will return the data to be displayed to the template, and then output it to the page.

Django is also a MVC framework, but in Django, the part that the controller accepts user input is handled by the framework itself, so django pays more attention to the model (model), view (view), templates (template), that is, the MTV model.

After requesting a url, matching the corresponding view area, view goes to models (a hierarchy of managed data) to find the data we want, then loads the data into the templates layer, and then presents it to us.

The two are very similar, it can be said that MTV is based on MVC.

3. Static Web development

Create a template layer

Of course, if you just want the simple data to be displayed in the Web page, you don't need to create a template, just go back to it in the views function, but formalize it a little bit.

Create a templates folder in learn_django (if the django project created by IDE is automatically created), this is our template folder to add a visual template index.html

Django Learning Hellow,Django! >

Create a view layer

The view layer is usually a view function that matches with url and returns the corresponding Web page passed in.

From django.shortcuts import render# Create your views here.def index (request): return render (request,'index.html')

Create a url layer

Create the url layer, find our view function based on the url passed in, and return the rendered template

From django.conf.urls import include, urlfrom django.contrib import adminfrom django_app.views import indexurlpatterns = [url (r'^ admin/', include (admin.site.urls)), # match the url with rules, and then match the view function to the corresponding url url (r'^ index/',index)

Run the service, default to port 8000

Python manage.py runserver

At this stage, some students will have some minor problems, that is, they cannot return templates. Windows and linux may be different. Linux needs to put the templates directory under the app directory to find it.

The reason lies in the template path setting problem in settings.py. If the templates directory is placed in the project root directory, just add the templates path in settings.

4. Dynamic web development

The front is about static pages. If you need to be dynamic, then you have to talk about the interaction with database storage. You need to write models to get the data.

Mysql + django

Install the corresponding database interface driver, there are roughly three kinds: mysqldb, pymysql, mysqlclient.

The sqlite3 database under the web root directory is used by default

Modify it to the corresponding mysql information

Create a mysql database and specify the character set as UTF-8

Models layer

The corresponding relationship between the object that creates the model and the database field

Special properties in field definition

From django.db import models# Create your models here.class DjangoTest (models.Model): text = models.CharField (max_length=20) generates the migration file and executes the migration python manage.py makemigrationspython manage.py migrate

View the created information

Set up some test data

Before we create the views layer, let's test the models layer to see if the data has been extracted

There are two ways:

1. Fill in the extracted data directly in models

It can also be written on the view layer. It doesn't matter.

It may appear after running, because running the python file separately in the project requires searching for environment variables, which are not specified, so you need to set them.

Django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS.

Pycharm solution: https://blog.csdn.net/u011013781/article/details/52155761

2. Use django shell

# Open django shellpython manage.py shellimport djangodjango.setup () from django_app.models imoort DjangoTest as dj# to add data. For the result, see the following image a = dj (text= "django shell test") a.save () # query data, get query single data, filter query multiple models, all query dj.objects.all ()

Django admin can help us manage background data quickly.

# create administrator python manage.py create superuser```! [] (http://oxrfjovwk.bkt.clouddn.com/18-6-29/76119583.jpg)

Register our model in admin and open admin.py

Register our model in admin and open admin.py

From django.contrib import admin# Register your models here.from models import DjangoTestadmin.site.register (DjangoTest)

This allows you to manage the model in the administrator interface

View and url layer

When a user requests a page on a django site, django uses the route resolution module to resolve the route, which defaults to urls.py under the app directory.

Django loads the route resolution module and looks for the available urlpatterns, which is a python list, and then the django matches each url pattern in the list in turn, stops when it encounters the first pattern that matches the request, and then calls the corresponding view, which is a python function (or a class-based view).

An example of a simple routing module:

From django.conf.urls import urlfrom. Import viewsurlpatterns = [url (r'^ articles/2003/$', views.special_case_2003), url (r'^ articles/ ([0-9] {4}) / $', views.year_archive), url (r'^ articles/ ([0-9] {4}) / ([0-9] {2}) / $', views.month_archive) Url (r'^ articles/ ([0-9] {4}) / ([0-9] {2}) / ([0-9] +) / $', views.article_detail),]

Examples of corresponding requests:

The request for / articles/2005/03/ will match the third pattern in the list. Django will call the function views.month_archive (request, '2005years,' 03').

/ articles/2005/3/ does not match any URL patterns because the third pattern in the list requires that the month should be two digits.

/ articles/2003/ will match the first pattern in the list, not the second, because the patterns match sequentially, and the first will first test for a match. Please feel free to insert some special cases like this to detect the matching order.

/ articles/2003 does not match any of the patterns, because each pattern requires the URL to end with a slash.

/ articles/2003/03/03/ will match the last pattern. Django will call the function views.article_detail (request, '2003,' 03, '03').

According to the value after url, give the corresponding parameter: id

Urls.py

From django.conf.urls import include, urlfrom django.contrib import adminfrom django_app.views import indexurlpatterns = [url (r'^ admin/', include (admin.site.urls)), url (r'^ index/ (? P [0-9]) / $', index),]

Substitute the id parameter for the query to get the value of the specified index in the data list (ignoring a small detail error)

Views.py

From django.shortcuts import renderfrom django_app.models import DjangoTest# Create your views here.def index (request,id): text = DjangoTest.objects.all () iden = int (id) context = {'text':text [iden]} return render (request,'index.html',context)

Template layer

Template layer syntax reference

Django test ID: {{text.id}} Hello: {{text.text}}

Actual operation effect

II. Web attack and Defense in Django Development (part)

1. Format string vulnerability

Before repair

From django.shortcuts import renderfrom django.contrib.auth import authenticate, loginimport djangodjango.setup () # Create your views here.def index (request): if request.method = = 'GET': return render (request,'index.html') else: username= request.POST [' username'] password = request.POST ['password'] user = authenticate (username=username Password=password) if user is not None: if user.is_active: login (request, user) template = 'Hello {user}!, You can set your email is:' + request.POST.get (' email') return render (request, 'index.html') {"value": template.format (user=request.user)}) else: info = "The password is valid, but the account has been disabled!" Return render (request, 'index.html', {"value": info}) else: info = "The username and password were incorrect." Return render (request, 'index.html', {"value": info})

With a change in the original code, if the authentication option is not added, the returned user will always be an anonymous user.

I have created a super user (admin admin) earlier, so I use this user to authenticate directly.

After authentication, the user name of the logged-in user is returned. We can pass in an email address as a temporary address through the post method. If there is any error in the user name information, the corresponding error message is returned.

Use django authentication system

User object is the core of authentication system. The basic properties of default user are username, password, email.

The mailbox information in the code is directly stitched into a string through format, and then displayed on the page. We can obtain sensitive data through the following payload, and then splice the password attribute in the user variable as variable information to obtain it.

Payload: {user.password}

After repair

Index.html

Store other text information directly in the template

Django test Hello, Django! Hello {{user}}, You can set your email is: {{value}} views.py.email = request.POST.get ('email') return render (request,' index.html', {"value": email}).. .2, XSS

Before testing and repair

Simply accept the post parameter value and display it on the page

Views.pydef index (request): if request.method = 'GET': return render (request,'index.html') else: info = request.POST.get (' info') return render (request,'index.html', {"value": info}) index.html Hello, Django! {{value}}

When typing payload, there is no expected pop-up window, because django automatically provides developers with escape functionality, allowing html code to be escaped before render and then displayed.

In addition to the automatic opening of escape, there are safe, autoescape, make_Safe and so on.

Autoescape test

{% autoescape off%} {{value}} {% endautoescape%}

When the value is off, there is a xss vulnerability

Safe test

Hello, Django! {{value | safe}}

The security mechanism of the template is turned off through safe, resulting in a XSS vulnerability.

There are several other situations where XSS may also exist:

1. Var mystr = "\ {value | escapejs\}\}"

2 、 safe 、 make_safe 、 autoescape

3. Dom XSS

4. HttpResponse returns dynamic content

After repair

Import cgi# Create your views here.def index (request): if request.method = = 'GET': return render (request,'index.html') else: info = request.POST.get (' info') info = cgi.escape (info) return render (request,'index.html', {"value": info})

When using the cgi module, you should pay attention to:

Set to True to escape as many characters as possible that cause the escape.

3. SQL injection

Django QuerySet

View the SQL executed by django queryset

From django_app.models import DjangoTest as djprint dj.objects.all () .query gets SELECT `django_app_ djangotest`.`id`, `django_app_ djangotest`.`text`FROM `django_app_ djangotest` is SELECT id,text FROM django_app_djangotest after simplification

Extra implements aliases, conditions, sorting, etc.

Take select as an example:

Tag = dj.objects.all () .extra (select= {"tag_id": 'id'})

Take where as an example:

The current where parameters in extra can be queried using the soundtrack's sql statement.

If the condition is id=1, the result is to query a piece of data.

Raw method to realize native SQL statement query

A = dj.objects.raw ('SELECT id,text FROM django_app_djangotest')

The raw () method supports index access (a [0])

You can also print what methods are available for the currently assigned variable a.

Directly use API to query data

Django.connection

MySQL API

Such as mysqldb, pymysql, mysqlclient, write the sql statement in the views layer, query it according to the passed parameter values, and return the result to the template.

Before repair

Views.py

From django.shortcuts import renderfrom django_app.models import DjangoTest as dj# Create your views here.def index (request): if request.method = 'GET': return render (request,'index.html') else: id= request.POST.get (' id') tag = dj.objects.extra (where= {'id= {}' .format (id)}) [0] .text return render (request,'index.html', {"value": tag})

Then we can have a pleasant test.

Test piece

A = dj.objects.extra (where= {'id=1'})

SELECT `django_app_ djangotest`.`id`, `django_app_ djangotest`.`text` FROM `django_app_ djangotest` WHERE (id=1asdasdad)

First enter payload to see what the sql statement django passes back to the database is

Changed payload

Several more constructions are tested later, and the SQL statement is correct, but when django is passed into the SQL statement, it will prompt for syntax problems, and even if the syntax is correct, it will not return data. (this is actually a bit of a problem. After I think about it, I didn't take it to the mysql shell to test it. I got it right in the terminal. Bring it back. I'm a little lazy here.)

And because of the value of id, it cannot be displayed on the page, so I think of delay injection at this time.

There will be a delay of 3 seconds when calling a here.

We tested it on the Web page

With regard to the relationship between the number of seconds here is multiple, I have seen a post before, saying that when time satisfies the relationship of multiple times, multiple pieces of data should be queried, and each row executes a delay.

Then it will be easy.

X = dj.objects.extra (where= {"id=1 and if (substr ((select user ()), 1Magne1) = 'ringing dagger sleep (3), 1)"})

The following steps follow the blind injection process to OJBK.

Sometimes instead of executing directly in django shell, go to the mysql command line and type the command correctly, and you can really test it when you run payload to make sure the first step is correct.

What I just said is only the where clause in extra. Other types of data extraction methods have also been mentioned earlier, and a specific case is analyzed.

After repair

Views.py

From django.shortcuts import renderfrom django_app.models import DjangoTest as dj# Create your views here.def index (request): if request.method = 'GET': return render (request,'index.html') else: id= request.POST.get (' id') tag = dj.objects.extra (where= ['id=%s'], params=id) info = tag [0] .text return render (request,'index.html', {"value": info})

When the request sent by the user is matched to the view function for processing, the relevant mechanism of the view function will process the sensitive information, resulting in some malicious statements being filtered.

Now the test won't be done.

Thank you for your reading. I believe you have a certain understanding of "Django development and attack and defense testing". Go ahead and practice it. If you want to know more about it, you can follow the website! The editor will continue to bring you better articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report