持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情
前言
之前的文章中,利用阿里云漏洞库进行了漏洞情报抓取,详情请见,抓取后的数据根据阿里漏洞库系统所打的标签,即:
数据准备
先前抓取的数据存放于百度网盘,有需要的可以下载,数据仅为学习使用,请勿用于其他用途,数据格式如下:
{
'content': "a race condition was found in the way the linux kernel's memory subsystem handled the copy-on-write (cow) breakage of private read-only shared memory mappings. this flaw allows an unprivileged, local user to gain write access to read-only memory mappings, increasing their privileges on the system.",
'company': [
'ubuntu_18.04'
],
'product': [
'linux'
],
'version': [
'*'
],
'influence': [
'4.13.0',
'16.19'
],
'type': '系统',
'cve_number': 'CVE-2022-2590',
'title': '空标题',
'href': 'https://avd.aliyun.com/detail?id=AVD-2022-2590'
}
其中type字段则为漏洞类型,用于生成分类标签。
数据处理
import codecs
import jieba
from tqdm import tqdm
writer = codecs.open("train.txt",'w','UTF-8')
lines = codecs.open("aliyunSpider.txt","r",'UTF-8').readlines()
lines = list(set(lines))
print(len(lines))
count0 = 0
count1 = 0
for line in tqdm(lines):
try:
content = eval(line.strip())["content"].strip()
if len(content) > 20 and count0 <= 50000:
if eval(line.strip())["type"] == "系统":
count0 += 1
print(count0)
writer.write("{}<split>1".format(' '.join(list(jieba.cut(content)))))
writer.write("\n")
elif eval(line.strip())["type"] == "应用" and count1 <= 50000:
count1 += 1
print(count1)
writer.write("{}<split>0".format(' '.join(list(jieba.cut(content)))))
writer.write("\n")
except Exception as e:
pass
二分类数据处理较为简单,仅仅加载数据后,根据type字段将系统和应用两部分数据区分写文档,并且选取字符长度大于20的进行保留,使用jieba分词工具进行分词,并使用空格进行连接,生成正负样本。
处理后的数据如下:
系统:
a race condition was found in the way the linux kernel ' s memory subsystem handled the copy - on - write ( cow ) breakage of private read - only shared memory mappings . this flaw allows an unprivileged , local user to gain write access to read - only memory mappings , increasing their privileges on the system .
应用:
bitbucket server 与 data center 是 一款 代码 协作 软件 。 近期 atlassian 官方 发布 安全更新 , 披露 了 cve - 2022 - 36804 bitbucket server and data center 远程 命令 执行 漏洞 。 攻击者 在 可以 接触 到 公开 项目 , 或者 对 私有 项目 拥有 read 权限 的 情况 下 , 可 利用 相关 api 执行 任意 命令 , 控制 服务器 。
train.txt
apple os x 是 一款 苹果 分发 的 基于 bsd 的 操作系统 。<split>0
cpanel 是 美国 cpanel 公司 的 一套 基于 web 的 自动化 主机 托管 平台 。 该 平台 主要 用于 自动化 管理 网站 和 服务器 。<split>0
mozilla firefox 是 美国 mozilla 基金会 的 一款 开源 web 浏览器 。<split>1
iscripts autohoster 是 一款 基于 php 的 web 应用程序 。<split>0
dataease v1.11 . 1 was discovered to contain a sql injection vulnerability via the parameter datasourceid .<split>0
d - bus 是 一款 进程 间通信 ( ipc ) 实现 。 用于 在 应用程序 间 发送 消息 。<split>1
chromium - browser 是 一个 开放源码 的 web 浏览器 项目 , 由谷歌 启动 , 为 专有 的 谷歌 浏览器 浏览器 提供 源代码 。<split>1
在 固件 版本 为 1012 的 insteon hub 2245 - 222 设备 上 , 从 pubnub 服务 收到 的 特别 精心制作 的 回复 可能 会 在 覆盖 任意 数据 的 全局 区域 上 导致 缓冲区 溢出 。 攻击者 应该 模拟 pubnub 并 响应 https get 请求 来 触发 此 漏洞 。 strcpy 溢出 了 insteon _ pubnub 缓冲区 。 channel _ ad _ r , 它 的 大小 为 16 字节 。 攻击者 可以 发送 任意 长 的 “ ad _ r ” 参数 来 利用 这个 漏洞 。<split>1
mattermost server 是 美国 mattermost 公司 的 一套 开源 的 消息传递 平台 。<split>0
malwarebytes premium 是 美国 malwarebytes 公司 的 一套 反 恶意 间谍 软件 。 该软件 支持 删除 蠕虫 、 拨号 程序 、 木马 、 rootkit 、 间谍 软件 、 漏洞 、 僵尸 和 其他 恶意软件 等 。<split>0
模型结构
接下来使用TextCNN作为文本二分类的baseline,模型结构如下:
模型
模型方面代码如下:
import tensorflow as tf
import numpy as np
class TextCNN(object):
"""
A CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
def __init__(
self, sequence_length, num_classes, vocab_size,
embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):
# Placeholders for input, output and dropout
self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")
# Keeping track of l2 regularization loss (optional)
l2_loss = tf.constant(0.0)
# Embedding layer
with tf.device('/cpu:0'), tf.name_scope("embedding"):
self.W = tf.Variable(
tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
name="W")
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
filter_shape = [filter_size, embedding_size, 1, num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
conv = tf.nn.conv2d(
self.embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
# Apply nonlinearity
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
# Maxpooling over the outputs
pooled = tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features
num_filters_total = num_filters * len(filter_sizes)
self.h_pool = tf.concat(pooled_outputs, 3)
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])
# Add dropout
with tf.name_scope("dropout"):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
# Final (unnormalized) scores and predictions
with tf.name_scope("output"):
W = tf.get_variable(
"W",
shape=[num_filters_total, num_classes],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
self.predictions = tf.argmax(self.scores, 1, name="predictions")
# Calculate mean cross-entropy loss
with tf.name_scope("loss"):
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss
# Accuracy
with tf.name_scope("accuracy"):
correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
后续文章会对模型进行详细记录,Thanks♪(・ω・)ノ。