6.4 示例:使用决策树算法检测FTP暴力破解

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

1.数据搜集和数据清洗

使用ADFA-LD数据集中FTP暴力破解的相关数据,ADFA-LD数据集详细介绍请阅读第3章相关内容。ADFA-LD系统调用可抽象成向量,如图6-4所示。

图6-4 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

从攻击数据集中筛选和FTP暴力破解相关的数据:


def load_adfa_hydra_ftp_files(rootdir):
    x=[]
    y=[]
    allfile=dirlist(rootdir,[])
    for file in allfile:
        if re.match(
r"../data/ADFA-LD/Attack_Data_Master/Hydra_FTP_\d+/UAD-Hydra-FTP*",
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.训练样本

实例化决策树算法:


clf = tree.DecisionTreeClassifier()

4.效果验证

我们使用十折交叉验证:


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

测试结果如下,准确率约为95%:


[ 1.          0.99009901  0.95        0.97979798  0.97979798  0.87878788
  0.98989899  0.97979798  0.94949495  0.95959596]

可视化训练得到的决策树为:


dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("../photo/6/ftp.pdf")

可视化决策树如图6-5所示。

图6-5 FTP暴力破解决策树