picoCTF-Web Exploitation-Java Code Analysis!?!

2024-05-14 12:28

本文主要是介绍picoCTF-Web Exploitation-Java Code Analysis!?!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Description

BookShelf Pico, my premium online book-reading service.I believe that
my website is super secure. I challenge you to prove me wrong by
reading the ‘Flag’ book!Here are the credentials to get you started:

  • Username: “user”
  • Password: “user”

Source code can be downloaded

here

.Website can be accessed

here!

Hints

Maybe try to find the JWT Signing Key (“secret key”) in the source
code? Maybe it’s hardcoded somewhere? Or maybe try to crack it?

The ‘role’ and ‘userId’ fields in the JWT can be of interest to you!

The ‘controllers’, ‘services’ and ‘security’ java packages in the
given source code might need your attention. We’ve provided a
README.md file that contains some documentation.

Upgrade your ‘role’ with the new (cracked) JWT. And re-login for the
new role to get reflected in browser’s localStorage.

通过介绍我们可以得到以下信息:

  • 尝试破解JWT 签名密钥
  • JWT中的role和userId字段可能会对我们有帮助
  • 重点关注源码中的controllers, services, security包。
  • README.md文件可能对我们有所帮助
  • 在JWT中提升role并刷新cookie存储?

1. 分析代码

首先,我们下载源码,使用是gradle管理包,先看README.md,里面说明了项目的架构以及各个包的功能。访问here!网站,使用username:user, password:user用户登录,发现图片有Flag,点击提示有锁,需要用户拥有role为Admin的权限(user用户的role是Free

Flag
You need to have Admin role to access this special book!
This book is locked.

我们给用户user修改role为Admin试试,查看UserController找到修改role的代码

@PatchMapping("/users/role")
public Response<String> updateRole(@Valid @RequestBody UpdateUserRoleRequest userRoleRequest) throws ResourceNotFoundException, ValidationException {userService.updateRole(userRoleRequest);return new Response<String>().setPayload("Role successfully updated.").setType(ResponseType.SUCCESS);
}
@Getter
@Setter
@NoArgsConstructor
public class UpdateUserRoleRequest {private Integer id;@NotNull(message = "Role cannot be Null")@NotEmpty(message = "Role cannot be empty")private String role;
}

我们需要构建RequestBody参数包含idrole ,role已知为Admin ,接下来需要找到user用户的id ,在UserController 中有一个users接口,查询所有用户信息

@GetMapping("/users")
public Response<List<UserDto>> getAll() {List<UserDto> userList = userService.getAllUsers();Response<List<UserDto>> response = new Response<>();response.setPayload(userList);response.setType(ResponseType.SUCCESS);return response;
}

我们进去Service看一下,发现有权限认证hasAuthority('Admin'),需要Admin权限,前面修改role的也需要这个权限认证,不过又多了一步#userRoleRequest.id != authentication.principal.grantedAuthorities[0].userId ,意思好像是userId不能是本用户,也就是自己不能修改自己的role

@PreAuthorize("hasAuthority('Admin')")
public List<UserDto> getAllUsers() {return UserDto.getUserDtoListFromUsers(userRepository.findAll());
}@PreAuthorize("hasAuthority('Admin') and #userRoleRequest.id != authentication.principal.grantedAuthorities[0].userId")
public void updateRole(UpdateUserRoleRequest userRoleRequest) throws ResourceNotFoundException {Optional<User> userOptional = userRepository.findById(userRoleRequest.getId());if(!userOptional.isPresent()){throw new ResourceNotFoundException("user with ID: "+userRoleRequest.getId()+" not found");}User user = userOptional.get();Optional<Role> roleOptional = roleRepository.findById(userRoleRequest.getRole());if(!roleOptional.isPresent()){throw new ResourceNotFoundException("user with role: "+userRoleRequest.getRole()+" not found");}Role role = roleOptional.get();user.setRole(role);userRepository.save(user);
}

2. 修改JWT

所有操作需要给user用户一个Admin权限,我们知道JWT在登录后生成一个token,每次请求会在Request Header中带上这个token,以便后端程序对权限进行验证。

User登录网站,使用DevTools查看请求头,得到token

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiRnJlZSIsImlzcyI6ImJvb2tzaGVsZiIsImV4cCI6MTcxNjE5MDE1MywiaWF0IjoxNzE1NTg1MzUzLCJ1c2VySWQiOjEsImVtYWlsIjoidXNlciJ9.27h2BykhrD30xizlmoid0Wkj3OLuNPgR-XGo30UBv_0

拿到JWT官网解析,得到payload

{"role": "Free","iss": "bookshelf","exp": 1716190153,"iat": 1715585353,"userId": 1,"email": "user"
}

修改role为Admin重新加密,前提需要找到签名密钥(第一条提示)。继续查看权限验证JWT相关代码,发现密钥为1234

@Service
class SecretGenerator {private Logger logger = LoggerFactory.getLogger(SecretGenerator.class);private static final String SERVER_SECRET_FILENAME = "server_secret.txt";@Autowiredprivate UserDataPaths userDataPaths;private String generateRandomString(int len) {// not so randomreturn "1234";}String getServerSecret() {try {String secret = new String(FileOperation.readFile(userDataPaths.getCurrentJarPath(), SERVER_SECRET_FILENAME), Charset.defaultCharset());logger.info("Server secret successfully read from the filesystem. Using the same for this runtime.");return secret;}catch (IOException e){logger.info(SERVER_SECRET_FILENAME+" file doesn't exists or something went wrong in reading that file. Generating a new secret for the server.");String newSecret = generateRandomString(32);try {FileOperation.writeFile(userDataPaths.getCurrentJarPath(), SERVER_SECRET_FILENAME, newSecret.getBytes());} catch (IOException ex) {ex.printStackTrace();}logger.info("Newly generated secret is now written to the filesystem for persistence.");return newSecret;}}
}

修改role及密钥信息得到新得token

在这里插入图片描述

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiQWRtaW4iLCJpc3MiOiJib29rc2hlbGYiLCJleHAiOjE3MTYxOTMxNTcsImlhdCI6MTcxNTU4ODM1NywidXNlcklkIjoxLCJlbWFpbCI6InVzZXIifQ.zMJVsnlSGl2OKzBSQ_h2qIU5mB7OL7bgF6khdI31eMw

3. 修改新建用户的role为Admin

  • 网页上直接创建一个用户

    在这里插入图片描述

  • 使用postman请求用户查询接口得到hucker的userId为6

    (Header中增加Authorization,填入上面得到的新token

    在这里插入图片描述

  • 构建ResponseBody,给hucker用户修改权限为Admin

    在这里插入图片描述

  • 重新登录,发现role已经修改为Admin ,点击Flag拿到结果

    在这里插入图片描述

这篇关于picoCTF-Web Exploitation-Java Code Analysis!?!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/988748

相关文章

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B