SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
PORTING TO ANDROID
PORTING YOUR FAVOURITE CMDLINE TOOL
TO ANDROID
Vlatko Kosturjak (@k0st), Droidcon Zagreb, 30th of April
AGENDA
Introduction
Native code
Toolchains
Things I wish I knew in advance
Calling native executables
Issues and implications
Summary
Questions and answers
45 minutes
ABOUT ME
Security Consultant in Diverto
Linux and FLOSS enthusiast
Open source developer
Have code in OpenVAS, Nmap, Metasploit, ...
Android "developer" since 2010
started counting from first Market app
mostly focused on NDK and ADK
https://github.com/kost
ABOUT ME IN PICTURES
ABOUT ME IN PICTURES
INTRODUCE ELEPHANT
Talk will cover
producing standalone binaries
executing standalone binaries
Talk is mostly about Nmap experience
Most Nmap frontends on playstore are using this port
in source or binary form
Talk will NOT cover
producing libraries or JNI
integrating with Android Studio
https://github.com/kost/nmap-android
https://github.com/kost/NetworkMapper
NATIVE CODE
NOT your Java code :)
It's mostly about
C/C++
Assembler
Not portable across platforms
For each platform, you need different binary
x86
arm
mips
WHY BOTHER WITH NATIVE CODE?
performance
legacy code
code reuse
you just need that tool
WHAT'S THE PROCESS?
compiling
compiling on same machine
cross-compiling
compiling on (host) machine for other (target) machine
TOOLCHAINS
Android NDK
Commercial
Open Source
Custom
CUSTOM TOOLCHAIN
Your own version of compiler
Your own version of build scripts
Custom
COMMERCIAL
Embarcadero
Good old Borland...
Xamarin
Native apps in C#
...
OPEN SOURCE / FREE
Crystax
drop-in replacement for Google's NDK
WCHAR, locales, full C+11 standard library...
Buildroot
Standard embedded cross compilation toolchain
ARM, x86, MIPS
Scratchbox
ARM, x86, MIPS (experimental)
Anyone remembers Maemo? :)
...
ANDROID NDK
Android official toolchain
Available for free from developer.android.com
Bionic
No full ANSI C support
locale
different threads
Patch as you grow
standalone binary support/bugs
stdout symbol bug
WCHAR support
standard library support
WHAT'S THE FUZZ?
Download NDK
Download tool you want to port
./configure --host=arm-linux-androideabi
make
make install
It works - go home!
IN CASE IT IS HELLO WORLD...
/* Hello World program */
#include <stdio.h>
void main()
{
printf("Hello World");
}
It works pretty well indeed.
IN REAL WORLD
Code isn't perfect
Not portable
Endianess
Path Separators
Dependencies
Extensions
3rd party libraries
TWO WAYS TO INVOKE COMPILER
Calling with sysroot
export CC="$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/a
export CFLAGS="--sysroot=$SYSROOT"
$CC $CFLAGS -o hello hello.c
Producing directory for target
$NDK/build/tools/make-standalone-toolchain.sh --platform=android-3 --install-
/opt/ndk3/bin/arm-linux-androideabi-gcc -o hello hello.c
NDK PLATFORMS
NDK platform Platforms 32/64 bit
3 ARM 32
9 ARM/MIPS/Intel 32
21 ARM/MIPS/Intel 64
PROCESS OF CROSS COMPILING
Compile and fix as you go :)
sorry, no single recipe
Standard problems
stdout bug
old autoconf/automake support files
arm-linux-androideabi missing
In short
nothing that google/stackoverflow can't help :)
STATIC VS DYNAMIC LINKING
Dynamic
small size
run-time dependency
Static
large size
no dependencies
LIFE IS PERFECT
Static binaries working like a charm
“until resolv.conf disappeared :) ”
DNS PROBLEMS
int main(int argc,char *argv[]) {
int i;
struct hostent *hp;
for ( i=1; i<argc; ++i ) {
hp = gethostbyname(argv[i]);
if ( !hp ) {
fprintf(stderr, "%s: host '%s'n", hstrerror(h_errno),
argv[i]);
continue;
}
printf("Host:t%sn" ,argv[i]);
printf("tResolves to:t%sn", hp->h_name);
}
}
Original at gist
DNS AND RESOLV.CONF
#ifdef ANDROID_CHANGES /* READ FROM SYSTEM PROPERTIES */
dns_last_change_counter = _get_dns_change_count();
[..]
#else /* !ANDROID_CHANGES - IGNORE resolv.conf in Android */
#define MATCH(line, name) 
[..]
Original at https://code.google.com/p/android-source-
browsing
DYNAMIC VS STATIC
Type Size Dependency DNS OOTB
Dynamic smaller yes yes
Static bigger no no
Mixed medium yes (basic) yes
HERE COMES LOLIPOP
error: only position independent executables (PIE) are supported.
Position Independent Executable (PIE)
PIE support appeared in API level 16
Finally they implemented it :)
Too bad binaries does not work
WHAT'S PIE?
Position Independent Executable (PIE)
Security protection
better Address Space Layout Randomization (ASLR)
Exploitation mitigation technique
Harder return-to-libc exploitation
Requirements
PIE required for dynamic executables
PIE not required for static executables
PIE EXAMPLE
#include <stdio.h>
int global;
int checkadr (int *bla)
{
int local;
printf("bla adr = %pn", &bla);
printf("global adr = %pn", &global);
printf("local adr = %pn", &global);
}
int main (void) {
int c;
printf("c adr = %pn", &c);
printf("checkadr adr = %pn", &checkadr);
PIE SUPPORT
Android version Supported Required
1,2,3 no no
4 yes no
5 yes yes
PIE WORKAROUND
Way to run PIE executables on non supported systems
if system suppports PIE
just run executable
if system does not suppport PIE
use run_pie.c
run_pie your_proggy args
CFLAGS +=-fvisibility=default -fPIE
LDFLAGS += -rdynamic -pie
https://gist.github.com/kost/5fd4628f45a4995bec28
CALLING NATIVE EXECUTABLES
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputSt
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("n");
}
BETTER WAY - USING
PROCESSBUILDER
ProcessBuilder processBuilder = new ProcessBuilder(shellToRun);
processBuilder.redirectErrorStream(true);
scanProcess = processBuilder.start();
outputStream = new DataOutputStream(scanProcess.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(scanProcess.getInputSt
while (((pstdout = inputStream.readLine()) != null)) {
output.append(pstdout).append("n");
}
RUNNING BINARIES AS ROOT
Not needed to set any new android permission
Historic references to SUPERUSER permissions
Not much different than executing as normal user
Have to Runtime.getRuntime().exec("su")
Write commands to stdin of process
Loop the output
ROOT IMPLICATIONS
Killing run away root processes
Hard as it can be due to blocking nature
UI does not have root access
Killing spawned root processes
parse ps output
spawn su shell
kill process
SECURITY IMPLICATIONS
Native binary problems
Memory corruption attacks (Buffer overflows, ...)
Format string problems...
...
Permissions
Command injections
SECURITY IMPLICATIONS -
PERMISSIONS
Setting insecure permissions to executables/libraries
Very common when something does not work
Dangerous and heroic
Other apps can write to your bin or library
Exploitation
Find insecure .so library, inject your code
Find insecure binary, replace it with your version!
echo "#!/bin/sh" > /data/data/com.heroic.app/bin/mybinary
echo "echo '0wned!'" >> /data/data/com.heroic.app/bin/mybinary
SECURITY IMPLICATIONS -
UNTRUSTED INPUT
Passing untrusted/unvalidated input to shell
Running native executables can lead to command
injections
Extremely dangerous if running as user
Extremely heroic and dangerous if running as root
Pay special attention to exported activities
other apps can call that intent
which means they can execute commands as your
app!!
UNTRUSTED INPUT EXAMPLE
Bundle b = getIntent().getExtras();
configFilePath = b.getString("path");
[..]
ShellExecuter exe = new ShellExecuter();
return exe.Executer("cat " + configFilePath);
<activity
android:name=".MyHeroicActivity"
....
android:exported="true" />
UNTRUSTED INPUT EXPLOITATION
public void onBtnClick(View view) {
Intent intent = new Intent();
intent.setClassName("com.heroic.app", "com.heroic.app.MyHeroicActivit
intent.putExtra("path", "/system/etc/hosts; echo 'Owned' > /data/data
startActivity(intent);
}
ON THE END..
You get bad comments :)
Don't use ratings for bug reports ;)
Please submit VERBOSE bug reports to author directly
FORTUNATELY
Fortunately, there are good comments ;)
Thanks on these
SUMMARY
Porting is quite possible
Not as easy as marketing says
You can't configure; make; make install in most cases
Expect you'll have to patch if project is bigger
Not that hard
If you know requirements upfront
Have listened to this lecture carefully
Be aware of security implications!
THANKS ON LISTENING
?
ANY QUESTIONS?

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Does Cowgirl Dream of Red Swirl?
Does Cowgirl Dream of Red Swirl?Does Cowgirl Dream of Red Swirl?
Does Cowgirl Dream of Red Swirl?
 
CloudOpen North America 2013: Vagrant & CFEngine
CloudOpen North America 2013: Vagrant & CFEngineCloudOpen North America 2013: Vagrant & CFEngine
CloudOpen North America 2013: Vagrant & CFEngine
 
find & improve some bottleneck in Debian project (DebConf14 LT)
find & improve some bottleneck in Debian project (DebConf14 LT)find & improve some bottleneck in Debian project (DebConf14 LT)
find & improve some bottleneck in Debian project (DebConf14 LT)
 
Drupal Development : Tools, Tips, and Tricks
Drupal Development : Tools, Tips, and TricksDrupal Development : Tools, Tips, and Tricks
Drupal Development : Tools, Tips, and Tricks
 
WAF protections and bypass resources
WAF protections and bypass resourcesWAF protections and bypass resources
WAF protections and bypass resources
 
8-9-10=Jessie,Stretch,Buster
8-9-10=Jessie,Stretch,Buster8-9-10=Jessie,Stretch,Buster
8-9-10=Jessie,Stretch,Buster
 
Chromium OS Introduction
Chromium OS IntroductionChromium OS Introduction
Chromium OS Introduction
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwares
 
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
 
Null Xposed Framework internals and writing modules
Null Xposed Framework internals and writing modulesNull Xposed Framework internals and writing modules
Null Xposed Framework internals and writing modules
 
Understand study
Understand studyUnderstand study
Understand study
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3
 
Docker italia fatti un container tutto tuo
Docker italia fatti un container tutto tuoDocker italia fatti un container tutto tuo
Docker italia fatti un container tutto tuo
 
Rust 101 (2017 edition)
Rust 101 (2017 edition)Rust 101 (2017 edition)
Rust 101 (2017 edition)
 
0d1n
0d1n0d1n
0d1n
 
Phpstormを使いこなす
Phpstormを使いこなすPhpstormを使いこなす
Phpstormを使いこなす
 
Django dev-env-my-way
Django dev-env-my-wayDjango dev-env-my-way
Django dev-env-my-way
 
We codeil save kermit
We codeil   save kermitWe codeil   save kermit
We codeil save kermit
 
scaling compiled applications - highload 2013
scaling compiled applications - highload 2013scaling compiled applications - highload 2013
scaling compiled applications - highload 2013
 
Drupal 101 V-0.1
Drupal 101 V-0.1Drupal 101 V-0.1
Drupal 101 V-0.1
 

Similar a Porting your favourite cmdline tool to Android

Hacking with Reverse Engineering and Defense against it
Hacking with Reverse Engineering and Defense against it Hacking with Reverse Engineering and Defense against it
Hacking with Reverse Engineering and Defense against it
Prakashchand Suthar
 
Development workflow
Development workflowDevelopment workflow
Development workflow
Sigsiu.NET
 

Similar a Porting your favourite cmdline tool to Android (20)

.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
 
.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques
 
Hacking with Reverse Engineering and Defense against it
Hacking with Reverse Engineering and Defense against it Hacking with Reverse Engineering and Defense against it
Hacking with Reverse Engineering and Defense against it
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
Development workflow
Development workflowDevelopment workflow
Development workflow
 
UnDeveloper Studio
UnDeveloper StudioUnDeveloper Studio
UnDeveloper Studio
 
Lab Handson: Power your Creations with Intel Edison!
Lab Handson: Power your Creations with Intel Edison!Lab Handson: Power your Creations with Intel Edison!
Lab Handson: Power your Creations with Intel Edison!
 
Java Device I/O at Raspberry PI to Build a Candy Vending Machine
Java Device I/O at Raspberry PI to Build a Candy Vending MachineJava Device I/O at Raspberry PI to Build a Candy Vending Machine
Java Device I/O at Raspberry PI to Build a Candy Vending Machine
 
Dependent things dependency management for apple sw - slideshare
Dependent things   dependency management for apple sw - slideshareDependent things   dependency management for apple sw - slideshare
Dependent things dependency management for apple sw - slideshare
 
Reverse code engineering
Reverse code engineeringReverse code engineering
Reverse code engineering
 
Fight with linux reverse
Fight with linux reverseFight with linux reverse
Fight with linux reverse
 
Intro to Reverse Engineering
Intro to Reverse EngineeringIntro to Reverse Engineering
Intro to Reverse Engineering
 
From printed circuit boards to exploits
From printed circuit boards to exploitsFrom printed circuit boards to exploits
From printed circuit boards to exploits
 
C# Production Debugging Made Easy
 C# Production Debugging Made Easy C# Production Debugging Made Easy
C# Production Debugging Made Easy
 
NYU Hacknight: iOS and OSX ABI
NYU Hacknight: iOS and OSX ABINYU Hacknight: iOS and OSX ABI
NYU Hacknight: iOS and OSX ABI
 
Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?
 
Iz Pack
Iz PackIz Pack
Iz Pack
 
DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...
DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...
DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...
 
Betabeers Android as a Digital Signage platform
Betabeers   Android as a Digital Signage platformBetabeers   Android as a Digital Signage platform
Betabeers Android as a Digital Signage platform
 
Os Selbak
Os SelbakOs Selbak
Os Selbak
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

Porting your favourite cmdline tool to Android

  • 1. PORTING TO ANDROID PORTING YOUR FAVOURITE CMDLINE TOOL TO ANDROID Vlatko Kosturjak (@k0st), Droidcon Zagreb, 30th of April
  • 2. AGENDA Introduction Native code Toolchains Things I wish I knew in advance Calling native executables Issues and implications Summary Questions and answers 45 minutes
  • 3. ABOUT ME Security Consultant in Diverto Linux and FLOSS enthusiast Open source developer Have code in OpenVAS, Nmap, Metasploit, ... Android "developer" since 2010 started counting from first Market app mostly focused on NDK and ADK https://github.com/kost
  • 4. ABOUT ME IN PICTURES
  • 5. ABOUT ME IN PICTURES
  • 6. INTRODUCE ELEPHANT Talk will cover producing standalone binaries executing standalone binaries Talk is mostly about Nmap experience Most Nmap frontends on playstore are using this port in source or binary form Talk will NOT cover producing libraries or JNI integrating with Android Studio https://github.com/kost/nmap-android https://github.com/kost/NetworkMapper
  • 7. NATIVE CODE NOT your Java code :) It's mostly about C/C++ Assembler Not portable across platforms For each platform, you need different binary x86 arm mips
  • 8. WHY BOTHER WITH NATIVE CODE? performance legacy code code reuse you just need that tool
  • 9. WHAT'S THE PROCESS? compiling compiling on same machine cross-compiling compiling on (host) machine for other (target) machine
  • 11. CUSTOM TOOLCHAIN Your own version of compiler Your own version of build scripts Custom
  • 13. OPEN SOURCE / FREE Crystax drop-in replacement for Google's NDK WCHAR, locales, full C+11 standard library... Buildroot Standard embedded cross compilation toolchain ARM, x86, MIPS Scratchbox ARM, x86, MIPS (experimental) Anyone remembers Maemo? :) ...
  • 14. ANDROID NDK Android official toolchain Available for free from developer.android.com Bionic No full ANSI C support locale different threads Patch as you grow standalone binary support/bugs stdout symbol bug WCHAR support standard library support
  • 15. WHAT'S THE FUZZ? Download NDK Download tool you want to port ./configure --host=arm-linux-androideabi make make install It works - go home!
  • 16. IN CASE IT IS HELLO WORLD... /* Hello World program */ #include <stdio.h> void main() { printf("Hello World"); } It works pretty well indeed.
  • 17. IN REAL WORLD Code isn't perfect Not portable Endianess Path Separators Dependencies Extensions 3rd party libraries
  • 18. TWO WAYS TO INVOKE COMPILER Calling with sysroot export CC="$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/a export CFLAGS="--sysroot=$SYSROOT" $CC $CFLAGS -o hello hello.c Producing directory for target $NDK/build/tools/make-standalone-toolchain.sh --platform=android-3 --install- /opt/ndk3/bin/arm-linux-androideabi-gcc -o hello hello.c
  • 19. NDK PLATFORMS NDK platform Platforms 32/64 bit 3 ARM 32 9 ARM/MIPS/Intel 32 21 ARM/MIPS/Intel 64
  • 20. PROCESS OF CROSS COMPILING Compile and fix as you go :) sorry, no single recipe Standard problems stdout bug old autoconf/automake support files arm-linux-androideabi missing In short nothing that google/stackoverflow can't help :)
  • 21. STATIC VS DYNAMIC LINKING Dynamic small size run-time dependency Static large size no dependencies
  • 22. LIFE IS PERFECT Static binaries working like a charm “until resolv.conf disappeared :) ”
  • 23. DNS PROBLEMS int main(int argc,char *argv[]) { int i; struct hostent *hp; for ( i=1; i<argc; ++i ) { hp = gethostbyname(argv[i]); if ( !hp ) { fprintf(stderr, "%s: host '%s'n", hstrerror(h_errno), argv[i]); continue; } printf("Host:t%sn" ,argv[i]); printf("tResolves to:t%sn", hp->h_name); } } Original at gist
  • 24. DNS AND RESOLV.CONF #ifdef ANDROID_CHANGES /* READ FROM SYSTEM PROPERTIES */ dns_last_change_counter = _get_dns_change_count(); [..] #else /* !ANDROID_CHANGES - IGNORE resolv.conf in Android */ #define MATCH(line, name) [..] Original at https://code.google.com/p/android-source- browsing
  • 25. DYNAMIC VS STATIC Type Size Dependency DNS OOTB Dynamic smaller yes yes Static bigger no no Mixed medium yes (basic) yes
  • 26. HERE COMES LOLIPOP error: only position independent executables (PIE) are supported. Position Independent Executable (PIE) PIE support appeared in API level 16 Finally they implemented it :) Too bad binaries does not work
  • 27. WHAT'S PIE? Position Independent Executable (PIE) Security protection better Address Space Layout Randomization (ASLR) Exploitation mitigation technique Harder return-to-libc exploitation Requirements PIE required for dynamic executables PIE not required for static executables
  • 28. PIE EXAMPLE #include <stdio.h> int global; int checkadr (int *bla) { int local; printf("bla adr = %pn", &bla); printf("global adr = %pn", &global); printf("local adr = %pn", &global); } int main (void) { int c; printf("c adr = %pn", &c); printf("checkadr adr = %pn", &checkadr);
  • 29. PIE SUPPORT Android version Supported Required 1,2,3 no no 4 yes no 5 yes yes
  • 30. PIE WORKAROUND Way to run PIE executables on non supported systems if system suppports PIE just run executable if system does not suppport PIE use run_pie.c run_pie your_proggy args CFLAGS +=-fvisibility=default -fPIE LDFLAGS += -rdynamic -pie https://gist.github.com/kost/5fd4628f45a4995bec28
  • 31. CALLING NATIVE EXECUTABLES p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputSt String line; while ((line = reader.readLine()) != null) { output.append(line).append("n"); }
  • 32. BETTER WAY - USING PROCESSBUILDER ProcessBuilder processBuilder = new ProcessBuilder(shellToRun); processBuilder.redirectErrorStream(true); scanProcess = processBuilder.start(); outputStream = new DataOutputStream(scanProcess.getOutputStream()); inputStream = new BufferedReader(new InputStreamReader(scanProcess.getInputSt while (((pstdout = inputStream.readLine()) != null)) { output.append(pstdout).append("n"); }
  • 33. RUNNING BINARIES AS ROOT Not needed to set any new android permission Historic references to SUPERUSER permissions Not much different than executing as normal user Have to Runtime.getRuntime().exec("su") Write commands to stdin of process Loop the output
  • 34. ROOT IMPLICATIONS Killing run away root processes Hard as it can be due to blocking nature UI does not have root access Killing spawned root processes parse ps output spawn su shell kill process
  • 35. SECURITY IMPLICATIONS Native binary problems Memory corruption attacks (Buffer overflows, ...) Format string problems... ... Permissions Command injections
  • 36. SECURITY IMPLICATIONS - PERMISSIONS Setting insecure permissions to executables/libraries Very common when something does not work Dangerous and heroic Other apps can write to your bin or library Exploitation Find insecure .so library, inject your code Find insecure binary, replace it with your version! echo "#!/bin/sh" > /data/data/com.heroic.app/bin/mybinary echo "echo '0wned!'" >> /data/data/com.heroic.app/bin/mybinary
  • 37. SECURITY IMPLICATIONS - UNTRUSTED INPUT Passing untrusted/unvalidated input to shell Running native executables can lead to command injections Extremely dangerous if running as user Extremely heroic and dangerous if running as root Pay special attention to exported activities other apps can call that intent which means they can execute commands as your app!!
  • 38. UNTRUSTED INPUT EXAMPLE Bundle b = getIntent().getExtras(); configFilePath = b.getString("path"); [..] ShellExecuter exe = new ShellExecuter(); return exe.Executer("cat " + configFilePath); <activity android:name=".MyHeroicActivity" .... android:exported="true" />
  • 39. UNTRUSTED INPUT EXPLOITATION public void onBtnClick(View view) { Intent intent = new Intent(); intent.setClassName("com.heroic.app", "com.heroic.app.MyHeroicActivit intent.putExtra("path", "/system/etc/hosts; echo 'Owned' > /data/data startActivity(intent); }
  • 40. ON THE END.. You get bad comments :) Don't use ratings for bug reports ;) Please submit VERBOSE bug reports to author directly
  • 41. FORTUNATELY Fortunately, there are good comments ;) Thanks on these
  • 42. SUMMARY Porting is quite possible Not as easy as marketing says You can't configure; make; make install in most cases Expect you'll have to patch if project is bigger Not that hard If you know requirements upfront Have listened to this lecture carefully Be aware of security implications!