8.3 示例:使用逻辑回归算法检测Java溢出攻击

完整演示代码请见本书GitHub上的8-2.py。

1.数据搜集和数据清洗

使用ADFA-LD数据集中Java溢出攻击的相关数据(见图8-3),ADFA-LD数据集详细介绍请阅读第3章相关内容。

图8-3 ADFA-LD系统调用抽象成向量

加载ADFA-LD中的正常样本数据:


def load_adfa_training_files(rootdir):
    x=[]
    y=[]
    list = os.listdir(rootdir)
    for i in range(0, len(list)):
        path = os.path.join(rootdir, list[i])
        if os.path.isfile(path):
            x.append(load_one_flle(path))
            y.append(0)
    return x,y

定义遍历目录下文件的函数:


def dirlist(path, allfile):
    filelist = os.listdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            dirlist(filepath, allfile)
        else:
            allfile.append(filepath)
    return allfile

从攻击数据集中筛选和Java溢出攻击相关的数据:


def load_adfa_java_files(rootdir):
    x=[]
    y=[]
    allfile=dirlist(rootdir,[])
    for file in allfile:
        if re.match(
r" ../data/ADFA-LD/Attack_Data_Master/Java_Meterpreter_\d+/UAD-Java-Meterpreter*",
file):
            x.append(load_one_flle(file))
            y.append(1)
    return x,y

2.特征化

由于ADFA-LD数据集都记录了函数调用序列,每个文件包含的函数调用序列的个数都不一致,可以参考第3章中的词集模型进行特征化:


x1,y1=load_adfa_training_files("../data/ADFA-LD/Training_Data_Master/")
x2,y2=load_adfa_hydra_ftp_files("../data/ADFA-LD/Attack_Data_Master/"
x=x1+x2
y=y1+y2
vectorizer = CountVectorizer(min_df=1)
x=vectorizer.fit_transform(x)
x=x.toarray()

3.训练样本

实例化逻辑回归算法,正则系数为1e5:


logreg = linear_model.LogisticRegression(C=1e5)

4.效果验证

我们使用十折交叉验证:


print  cross_validation.cross_val_score(logreg, x, y, n_jobs=-1,cv=10)

测试结果如下,准确率93%左右:


0.930928852415