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

How to use keras to determine SQL injection attacks

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

Editor to share with you how to use keras to do SQL injection attack judgment, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Through the deep learning framework keras to do SQL injection feature recognition, but although the use of keras, but most are still ordinary neural networks, only added some regularization, dropout layer (the layer that appears with deep learning).

The basic idea is to feed a pile of data (int type), calculate the probability of each class through neural network calculation (forward and reverse) and SOFTMAX multi-classification probability. Note: there are only two categories: 0-normal text; 1-contains SQL injected text.

In terms of file segmentation, four python files are made:

The util class, which is used to convert char to int (NN needs to be numeric, and any other type has to be converted to int/float before it can be fed, also known as feed).

Data class, which is used to obtain training data and verify data. Since the training here is supervised, what needs to be returned at this time is a tuple (x, y).

Trainer class, the network model of keras is modeled here, including loss function, training epoch times, etc.

Predict class, get several test data and see the prediction class of the effect.

First put the trainer class code, the network is defined here, the most important one, as important as the data format (hehe, the data format is very important, in this kind of program)

Import SQL injection Dataimport numpy as npimport kerasfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activationfrom keras.layers.normalization import BatchNormalizationfrom keras.optimizers import SGD x, y=SQL injection Data.loadSQLInjectData () availableVectorSize=15x=keras.preprocessing.sequence.pad_sequences (x, padding='post', maxlen=availableVectorSize) y=keras.utils.to_categorical (y, num_classes=2) model = Sequential () model.add (Dense (64, activation='relu', input_dim=availableVectorSize) model.add (BatchNormalization () model.add (Dropout)) model.add (Dense (64) Activation='relu') model.add (Dropout (0. 3)) model.add (Dense (2, activation='softmax')) sgd = SGD (lr=0.001, momentum=0.9) model.compile (loss='mse', optimizer=sgd, metrics= ['accuracy']) history=model.fit (x, yepochsquarry 500 pint 5) model.save (' E:\\ sql_checker\\ models\\ trained_models.h6') print ("DONE Model saved in path-- > E:\\ sql_checker\\ models\\ trained_models.h6 ") import matplotlib.pyplot as pltplt.plot (history.history ['loss']) plt.title (' model loss') plt.ylabel ('loss') plt.xlabel (' epoch') plt.legend (['train',' test'], loc='upper left') plt.show ()

Let's first explain the plt code above, because it is easiest to explain that this code is used to represent the loss value loss of each epoch training in a line chart:

What is training? What is loss of loss value?

The purpose of the training is to make the final classification data calculated by the network consistent with the y given by us. What about the inconsistency? Inconsistency means loss, that is to say, the purpose of training is to be consistent, that is, to minimize the loss.

How to minimize the loss? Gradient descent, the SGD optimization algorithm is used here:

From keras.optimizers import SGD sgd = SGD (lr=0.001, momentum=0.9) model.compile (loss='mse', optimizer=sgd, metrics= ['accuracy'])

The loss='mse' of the above code defines the use of that kind of loss function, and there are several loss functions for your own reference.

Optimizer=sgd is which optimization algorithm is used. Different optimizer have different parameters.

Since the fully connected NN is used here, a fixed input size is required, which is used to fix (not enough to complement 0) the eigenvector size:

X=keras.preprocessing.sequence.pad_sequences (x, padding='post', maxlen=availableVectorSize)

Let's take a look at the final classification output, which is one hot. This one hot is easily defined as a waste of space, and there is no correlation between categories, but it is very convenient to use here.

Y=keras.utils.to_categorical (y, num_classes=2)

Then let's talk about the prediction part of the code:

Import SQL injection into Dataimport Converter import numpy as npimport kerasfrom keras.models import load_model print ("predict....") X=SQL injects Data.loadTestSQLInjectData () x=keras.preprocessing.sequence.pad_sequences (x, padding='post', maxlen=15) model=load_model ('E:\\ sql_checker\\ models\\ trained_models.h6') result=model.predict_classes (x, batch_size=len (x)) result=Converter.convert2label (result) print (result) print ("DONE")

This part of the code is easy to understand and doesn't even have y.

Well, it seems to be a little interesting.

Let's put out several other utility classes and data class codes:

Def toints (sentence): base=ord ('0') ary= [] for c in sentence: ary.append (ord (c)-base) return ary def convert2label (vector): string_array= [] for v in vector: if vicious injection 1: string_array.append ('SQL injection') else: string_array.append ('normal text') return string_arrayimport Converterimport numpy as np def loadSQLInjectData (): X = [] x.append (Converter.toints ("100")) x.append (Converter.toints X.append (Converter.toints ("1")) x.append (Converter.toints ("3")) x.append (Converter.toints ("19")) x.append (Converter.toints ("37")) x.append (Converter.toints ("1'or -")) x.append ("1'or 1") -- ") x.append (Converter.toints (" updatable ")) x.append (Converter.toints (" update tbl ")) x.append (Converter.toints (" update someb ")) x.append (Converter.toints (" update ")) x.append (Converter.toints (" updat ")) x.append (Converter.toints (" update a ") x.append (Converter.toints ("'- ")) x.append (Converter.toints ("'or 1x1 ") -- ") x.append (Converter.toints (" aupdatable ")) x.append (Converter.toints (" hello world ")) y = [[0], [0], [0], [0], [0], [1], [1], [0], [1], [0], [0], [1], [1], [0], [0] x=np.asarray (x) y=np.asarray (y) return x Y def loadTestSQLInjectData (): X = [] x.append (Converter.toints ("some value")) x.append (Converter.toints ("- 1")) x.append (Converter.toints ("'or 1") -- ") x.append (Converter.toints (" noupdate ")) x.append (Converter.toints (" update ")) x.append (Converter.toints (" update ")) x.append (Converter.toints (" update z ")) x=np.asarray (x) return x is all the content of the article" how to use keras to determine SQL injection attacks ". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Wechat

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

12
Report