Weather App

江新
2023-12-01

Weather App

这道题学到非常多的知识感觉收获满满现在回头重新整理一下思路。

白盒的难点在于如何在一套代码中找到存在的利用点,我想全部看完是不现实的❌

而如何在一套代码中寻找呢?我目前还没有想到。大致的思路是看主页面数据库登录界面注册见面等可能存在可利用点的页面,发现可利用点是一个难题,发现可利用点后将可利用点串联起来进行利用则又是一个更加困难的问题。

这题需要下载源码白盒分析

可利用点

首先就来看看index.js

router.post('/register', (req, res) => {

	if (req.socket.remoteAddress.replace(/^.*:/, '') != '127.0.0.1') {
		return res.status(401).end();
	}

	let { username, password } = req.body;

	if (username && password) {
		return db.register(username, password)
			.then(()  => res.send(response('Successfully registered')))
			.catch(() => res.send(response('Something went wrong')));
	}

	return res.send(response('Missing parameters'));
});

/registerPOST请求如果不是127.0.0.1就会返回401

router.post('/login', (req, res) => {
	let { username, password } = req.body;

	if (username && password) {
		return db.isAdmin(username, password)
			.then(admin => {
				if (admin) return res.send(fs.readFileSync('/app/flag').toString());
				return res.send(response('You are not admin'));
			})
			.catch(() => res.send(response('Something went wrong')));
	}
	
	return re.send(response('Missing parameters'));
});

isAdmin(username, password)是一个感兴趣的函数跟进去看一看,全局搜索发现在database.js

async isAdmin(user, pass) {
    return new Promise(async (resolve, reject) => {
        try {
            let smt = await this.db.prepare('SELECT username FROM users WHERE username = ? and password = ?');
            let row = await smt.get(user, pass);
            resolve(row !== undefined ? row.username == 'admin' : false);
        } catch(e) {
            reject(e);
        }
    });
}

发现SQL查询用了?描述符,很可惜不能利用。回index.js继续看

router.post('/api/weather', (req, res) => {
	let { endpoint, city, country } = req.body;

	if (endpoint && city && country) {
		return WeatherHelper.getWeather(res, endpoint, city, country);
	}

	return res.send(response('Missing parameters'));
});	

第一次看好像没有什么令人感兴趣的东西,那么我们去有点关联的database.js看看吧

const sqlite = require('sqlite-async');
const crypto = require('crypto');

class Database {
    constructor(db_file) {
        this.db_file = db_file;
        this.db = undefined;
    }
    
    async connect() {
        this.db = await sqlite.open(this.db_file);
    }

    async migrate() {
        return this.db.exec(`
            DROP TABLE IF EXISTS users;

            CREATE TABLE IF NOT EXISTS users (
                id         INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                username   VARCHAR(255) NOT NULL UNIQUE,
                password   VARCHAR(255) NOT NULL
            );

            INSERT INTO users (username, password) VALUES ('admin', '${ crypto.randomBytes(32).toString('hex') }');
        `);
    }

    async register(user, pass) {
        // TODO: add parameterization and roll public
        return new Promise(async (resolve, reject) => {
            try {
                let query = `INSERT INTO users (username, password) VALUES ('${user}', '${pass}')`;
                resolve((await this.db.run(query)));
            } catch(e) {
                reject(e);
            }
        });
    }

    async isAdmin(user, pass) {...}
    
}

module.exports = Database;

可以看到register(user, pass)里的SQL查询并没有使用?描述符,而是拼接的方式来拼接SQL查询语句,是个可以利用的地方。

全局搜索可以发现在路由的router.post('/register', (req, res) => {}里有调用register(user, pass)函数。

根据migrate()可知usernameunique约束且已经创建了一个密码加密的admin用户,密码爆破的难度++。

const sqlite = require('sqlite-async');

async connect() {
    this.db = await sqlite.open(this.db_file);
}

weather app用了一种我之前没有见过的数据库SQLite这个后面再说。

Difference between MySQL and SQLite

到这里好像没有能继续走下去的了,怎么办呢?这个时候只能回头捡垃圾了。之前有一个不感兴趣的地方被我们略过了,去那里看看吧

router.post('/api/weather', (req, res) => {
	let { endpoint, city, country } = req.body;

	if (endpoint && city && country) {
		return WeatherHelper.getWeather(res, endpoint, city, country);
	}

	return res.send(response('Missing parameters'));
});	

感兴趣的看完了,不感兴趣的WeatherHelper.getWeather(res, endpoint, city, country)也变得有趣了。

const HttpHelper = require('../helpers/HttpHelper');

module.exports = {
    async getWeather(res, endpoint, city, country) {

        // *.openweathermap.org is out of scope
        let apiKey = '10a62430af617a949055a46fa6dec32f';
        let weatherData = await HttpHelper.HttpGet(`http://${endpoint}/data/2.5/weather?q=${city},${country}&units=metric&appid=${apiKey}`); 
        
        ......
    }
}

HttpHelper.HttpGet()就是一个普通的发送GET请求的函数

const http = require('http');

module.exports = {
	HttpGet(url) {
		return new Promise((resolve, reject) => {
			http.get(url, res => {
				let body = '';
				res.on('data', chunk => body += chunk);
				res.on('end', () => {
					try {
						resolve(JSON.parse(body));
					} catch(e) {
						resolve(false);
					}
				});
			}).on('error', reject);
		});
	}
}

接下来就是参考WP了。

利用链

经过上面的分析是这样的一个调用链。

POST /api/weather
url
Hacker
WeatherHelper
HttpHelper

这里用到的是SSRFhttp响应拆分攻击

虽然2wp里都引用了Security Bugs in Practice: SSRF via Request Splitting

但是我觉得其实联系不大,因为这篇文章主要说的是非HTTP控制字符经过JS底层的latin1格式转码后不符合原意的截断从而构成SSRFhttp响应拆分攻击。本题中其实不需要使用到非HTTP控制字符

构造出2个http响应其中一个是向router.post('/register', (req, res) => {}发送POST请求从而调用database.register()

POST /api/weather
url
GET
POST
Hacker
WeatherHelper
HttpHelper
who care
register
database.register()

利用链想好了,接下来就是实现的细节了

实现利用链

首先想到的是创建一个root烙用户,然而是不行的,因为前面已经提过了usernameunique约束。创建一个不行,那就只能修改了。

修改又有2个方向

  1. 创建一个新用户,将其提权为root
  2. 修改root烙密码,登录root

这里选用2

首先是构造恶意SQL

这里需要讲讲ON CONFLICT子句SQLite特有的一个非标准扩展。

The ON CONFLICT clause is a non-standard extension specific to SQLite that can appear in many other SQL commands. It is given its own section in this document because it is not part of standard SQL and therefore might not be familiar.

CREATE TABLE中介绍了该子句的作用,简单来说就是遇到冲突后执行什么操作。

4.1. Response to constraint violations

The response to a constraint violation is determined by the constraint conflict resolution algorithm. Each PRIMARY KEY, UNIQUE, NOT NULL and CHECK constraint has a default conflict resolution algorithm. PRIMARY KEY, UNIQUE and NOT NULL constraints may be explicitly assigned a default conflict resolution algorithm by including a conflict-clause in their definitions. Or, if a constraint definition does not include a conflict-clause or it is a CHECK constraint, the default conflict resolution algorithm is ABORT. Different constraints within the same table may have different default conflict resolution algorithms. See the section titled ON CONFLICT for additional information.

构造的恶意SQL意思是INSERT一组数据('admin', '1337')如果username与数据库中的约束冲突,这里是UNIQUE。则将INSERT操作改为UPDATE SET password = 'admin'操作。

INSERT INTO users (username, password) VALUES ('${user}', '${pass}')

INSERT INTO users (username, password) VALUES ('admin', '1337') ON CONFLICT(username) DO UPDATE SET password = 'admin';--')

恶意SQL构造好了,剩下的问题就是如何http响应拆分攻击

参照wp就好了,这不是本篇花笔墨的地方。

参考


HTB之Weather App

新版HackTheBox做题记录(WP)_ISMidi的博客-程序员ITS401_hackthebox注册教程

 类似资料:

相关阅读

相关文章

相关问答