The ANDROID_ID is unique in each application in Android.
To get the ANDROID_ID with Java inside Android I amd using this code:
import android.content.Context;
import android.content.ContentResolver;
import android.provider.Settings;
protected void onCreate(...) {
context = (Context)this;
String androidId = Settings.Secure.getString((ContentResolver)context.getContentResolver(), (String)"android_id");
}
But I want to run it inside some other application on my andoird phone.
I wanted to use Frida for this.
I am loading my injected script with Python:
import frida
device = frida.get_usb_device()
pid = device.spawn(["com.target.app"])
device.resume(pid)
time.sleep(1) #Without it Java.perform silently fails
session = device.attach(pid)
script = session.create_script(open("jsfrida.js").read())
script.load()
#prevent the python script from terminating
raw_input()
But inside my script I don't understand how to call it, this is what I tried:
Java.perform(function (){
console.log("Inside java perform function");
var ActivityThread = Java.use('android.app.ActivityThread');
var Context = Java.use('android.content.Context');
var settings = Java.use('android.provider.Settings.Secure');
var ctx = Java.cast(ActivityThread.currentApplication().getApplicationContext(), Context);
//console.log(ctx.getPackageName());
//console.log(ctx.getContentResolver());
var androidId = settings.Secure.getString(ctx.getContentResolver(), "android_id");
console.log(androidId);
console.log("END");
});
But it doesn't print the androidId, it only prints:
Script loaded successfully
Inside java perform function
Secure is inner class so you need to use $
inner classes will be compiled to ClassName$InnerClassName
To get CotentResolver you can invoke getContentResolver without casting.
$ frida -Uf com.app.example --no-pause
____
/ _ | Frida 12.1.2 - A world-class dynamic instrumentation toolkit
| (_| |
> _ | Commands:
/_/ |_| help -> Displays the help system
. . . . object? -> Display information about 'object'
. . . . exit/quit -> Exit
. . . .
. . . . More info at http://www.frida.re/docs/home/
Spawned `com.app.example`. Resuming main thread!
[Android::com.app.example]->
function getContext() {
return Java.use('android.app.ActivityThread').currentApplication().getApplicationContext().getContentResolver();
}
function logAndroidId() {
console.log('[?]', Java.use('android.provider.Settings$Secure').getString(getContext(), 'android_id'));
}
undefined
[Android::com.app.example]-> Java.perform(logAndroidId)
[?] 52d1497b52bf8a11
undefined
[Android::com.app.example]->
Related
I have a python module, consisting of import_ical.py and __init__.py in my directory . Calling this module from console works, when using:
python -m .import_ical .import_ical.py
When I call the same module using Jython, I get:
TypeError: 'module' object is not callable
at org.python.core.Py.TypeError(Py.java:263)
at org.python.core.PyObject.__call__(PyObject.java:390)
at org.python.core.PyObject.__call__(PyObject.java:496)
at services.imports.CalendarImporter.importFromUrl(CalendarImporter.java:53)
at services.imports.CalendarImporterTest.testMultipleEventsImport(CalendarImporterTest.java:21)
[...]
CalendarImporter.importFromUrl() does the following:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec("sys.path.append('<dir>')");
interpreter.exec("sys.path.append('/home/<user>/.local/lib/python2.7/site-packages')");
interpreter.exec("import import_ical");
PyObject importIcalPy = interpreter.get("import_ical");
PyObject pythonResult = importIcalPy.__call__(<parameters go here>);
When I execute my JUnit test (CalendarImporterTest) that executes this Jython code, a class file is generated in my module directory, named import_ical$py.class. It contains the following lines (amongst others):
#Filename("<dir>/import_ical.py")
public class import_ical$py extends PyFunctionTable implements PyRunnable {
[....]
static final PyCode __call__$20;
[....]
public PyObject __call__$20(PyFrame var1, ThreadState var2) {
var1.setline(243);
PyObject var3 = var1.getglobal("import_ical").__call__(var2, var1.getlocal(0), var1.getlocal(1), var1.getlocal(2));
var1.f_lasti = -1;
return var3;
}
}
Debugging to the last line of my CalendarImporter Java code shown above gives me the following variables states:
interpreter = {PythonInterpreter}
[...]
globals = {PyStringMap}
table
[...]
1 = {ConcurrentHashMap$MapEntry} "import_ical" -> "<module 'import_ical' from '<dir>/import_ical$py.class'>"
[...]
[...]
[...]
importIcalPy = {PyModule}
[...]
__dict__ = {PyStringMap}
table
[...]
19 = {ConcurrentHashMap$MapEntry} "import_ical" -> "<function import_ical at 0xc>"
[...]
32 = {ConcurrentHashMap$MapEntry} "__call__" -> "<function __call__ at 0x13>"
[...]
[...]
[...]
As a python newbie, I cannot detect anything that would arouse my scepticism with regards to the generated class file of the module and even the variables' state shown above seems to tell me that there is a proper function __call__ within in my python module importIcalPy.
Note: I had already added the function __call__ to my python module to make the module by "callable" from Jython and catch this error - obviously without success.
So can anyone please tell me: why do I get that "not callable" error? And what can I do to prevent it? Any help is greatly appreciated - thank you!
[Comment: I have intensely searched for a solution both, in Stackoverflow and using a big search engine, but all search results lead me to another problem where a python module could not call another python module.]
Finally, and thanks to the hints of user2357112, I've found a fix. Replace the content of CalendarImporter.importFromUrl() shown above with the following code:
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec("sys.path.append('<dir>')");
interpreter.exec("sys.path.append('/home/<user>/.local/lib/python2.7/site-packages')");
interpreter.exec("import import_ical");
// set variables if necessary in script:
// interpreter.set("__file__", <myFile>);
// set system argument variables (one append per variable):
interpreter.exec("sys.argv.append('".concat("<myVar>").concat("')"));
interpreter.execfile("<fileWithQualifiedPath>");
PyObject importIcalPy = interpreter.get("import_ical");
PyObject pythonResult = importIcalPy.__call__(new PyString("<myScriptArgument>"));
Hope, it will help someone.
I want to fetch the app category from play store through its unique identifier i.e. package name, I am using the following code but does not return any data. I also tried to use this AppsRequest.newBuilder().setAppId(query) still no help.
Thanks.
String AndroidId = "dead000beef";
MarketSession session = new MarketSession();
session.login("email", "passwd");
session.getContext().setAndroidId(AndroidId);
String query = "package:com.king.candycrushsaga";
AppsRequest appsRequest = AppsRequest.newBuilder().setQuery(query).setStartIndex(0)
.setEntriesCount(10).setWithExtendedInfo(true).build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
String response1 = response.toString();
Log.e("reponse", response1);
}
});
session.flush();
Use this script:
######## Fetch App names and genre of apps from playstore url, using pakage names #############
"""
Reuirements for running this script:
1. requests library
Note: Run this command to avoid insecureplatform warning pip install --upgrade ndg-httpsclient
2. bs4
pip install requests
pip install bs4
"""
import requests
import csv
from bs4 import BeautifulSoup
# url to be used for package
APP_LINK = "https://play.google.com/store/apps/details?id="
output_list = []; input_list = []
# get input file path
print "Need input CSV file (absolute) path \nEnsure csv is of format: <package_name>, <id>\n\nEnter Path:"
input_file_path = str(raw_input())
# store package names and ids in list of tuples
with open(input_file_path, 'rb') as csvfile:
for line in csvfile.readlines():
(p, i) = line.strip().split(',')
input_list.append((p, i))
print "\n\nSit back and relax, this might take a while!\n\n"
for package in input_list:
# generate url, get html
url = APP_LINK + package[0]
r = requests.get(url)
if not (r.status_code==404):
data = r.text
soup = BeautifulSoup(data, 'html.parser')
# parse result
x = ""; y = "";
try:
x = soup.find('div', {'class': 'id-app-title'})
x = x.text
except:
print "Package name not found for: %s" %package[0]
try:
y = soup.find('span', {'itemprop': 'genre'})
y = y.text
except:
print "ID not found for: %s" %package[0]
output_list.append([x,y])
else:
print "App not found: %s" %package[0]
# write to csv file
with open('results.csv', 'w') as fp:
a = csv.writer(fp, delimiter=",")
a.writerows(output_list)
This is what i did, best and easy solution
https://androidquery.appspot.com/api/market?app=your.unique.package.name
Or otherwise you can get source html and get the string out of it ...
https://play.google.com/store/apps/details?id=your.unique.package.name
Get this string out of it - use split or substring methods
<span itemprop="genre">Sports</span>
In this case sports is your category
use android-market-api it will gives all information of application
I'm attempting to update a password via a portlet in Quercus using java libraries. Here is some of the code that I'm using:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.SearchControls;
import javax.sql.DataSource;
import java.util.Hashtable;
$uname = isset($_POST['uname'])?$_POST['uname']:'';
$pass1 = isset($_POST['pass1'])?$_POST['pass1']:'';
//connecto to LDAP
$ldapADURL = "ldaps://poplar.example.edu:636";
$ldapEnv = new HashTable();
$ldapEnv->put("java.naming.factory.initial","com.sun.jndi.ldap.LdapCtxFactory");
$ldapEnv->put("java.naming.provider.url", $ldapADURL);
$ldapEnv->put("java.naming.security.protocal", "ssl");
$ldapEnv->put("java.naming.referral", "follow");
$ldapEnv->put("java.naming.security.authentication", "simple");
$ldapEnv->put("java.naming.security.principal", "ADUser");
$ldapEnv->put("java.naming.security.credentials", "P#ssw0rd");
$ADCtx = new InitialDirContext($ldapEnv);
//query the vault for our user
$ctlsAD = new SearchControls();
$attribsAD = array("sAMAccountName","DN","title","extensionAttribute14","extensionAttribute8","cn");
$ctlsAD->setReturningAttributes($attribsAD);
$ctlsAD->setSearchScope(2);
$filter="(sAMAccountName=" . $uname . ")";
$resultAD=$ADCtx->search("DC=conncoll,DC=edu",$filter,$ctlsAD);
if ($resultAD->hasMore()) {
$item = $resultAD->next();
$resultADAttribs = $item->getAttributes();
$rsTitle = str_replace("title: ","",$resultADAttribs->get("title"));
$rsAttrib14 = str_replace("extensionAttribute14: ","",$resultADAttribs->get("extensionAttribute14"));
$rsAttrib8 = str_replace("extensionAttribute8: ","",$resultADAttribs->get("extensionAttribute8"));
$rsUname = str_replace("sAMAccountName: ","",$resultADAttribs->get("sAMAccountName"));
$rsDN = str_replace("dn: ","",$resultADAttribs->get("DN"));
}
echo ( '<br />' . $rsTitle . '<br />' . $rsAttrib14 . '<br />' . $rsAttrib8 . '<br />' . $rsUname . '<br />' . $rsDN . '<br />');
if (isset($rsUname)/*ccLDAPCheckUser($uname)*/){
$ADCtx->addToEnvironment("java.naming.security.principal","OtherADUser");
$ADCtx->addToEnvironment("java.naming.security.credentials","0therP#ssw0rd");
//$resultAD2 = $ADCtx->search("DC=conncoll,DC=edu",$filter,$ctlsAD);
$pass2 = "\"" . $pass1 . "\"";
$newPass = mb_convert_encoding($pass2, "UTF-16LE");
$ADNewPass = new BasicAttribute("userpassword",$newPass);
$ADNewAttrib8 = new BasicAttribute("extensionAttribute8",$rsAttrib8);
$ADAttributes = new BasicAttributes();
$ADAttributes->put($ADNewPass);
$ADAttributes->put($ADNewAttrib8);
$ADCtx->modifyAttributes("sAMAccountName=" . $rsUname,2,$ADAttributes);
}
After running this code I get the following error from the LDAP server:
javax.naming.directory.InitialDirContext.modifyAttributes: [LDAP: error code 1 - 000020D6: SvcErr: DSID-031007DB, problem 5012 (DIR_ERROR), data 0 ]
So I'm wondering several things. The first is if I have the syntax of the modifyAttributes function call correct. I've tried it with dc=example,dc=edu tacked on to the query string to no success. The first query returns results correctly so I'm sure that I'm getting connected to the AD server and I've had someone verify that the JVM executing the code has a valid up-to-date certificate in its store.
The error makes me believe that I need the exact location specified for the object I'm attempting to update, which I don't have.
Thanks for your thoughts on the issue!
So I found part of my answer with getting the DN and using that instead of the sAMAccountName to issue a password reset.
I set $rsDN as follows:
$rsDN = $item->getNameInNamespace();
and issue the call to change the password as such:
$ADCtx->modifyAttributes($rsDN,2,$ADAttributes);
Now of course I'm getting SSL errors but I'm at least hitting the correct object with the update.
I have this on my app/scripts folder (I created this folder inside app/). I'm not sure how I can properly set the classpath here, thus I didn't even run this to know if it will actually connect to the database. How can I run this in a clean way from the command line?
package scripts
import scala.collection.TraversableOnce
import scala.collection.generic.SeqForwarder
import scala.io.Source
import scala.slick.jdbc.{StaticQuery => Q}
import scala.slick.session.Session
import scala.slick.session.Database
import play.api.db.DB
import tables.Campeonatos
import tables.Jogos
import org.postgresql.Driver
import play.api.test._
import play.api.test.Helpers._
// ...
class InsertJogosCSV extends App {
val dao = new DAO()
val application = FakeApplication()
def insertJogos(csv: CSV)(implicit s: Session) = {
val times = dao.getTimeIdByNameMap
var count = 0
csv foreach { case cols =>
count += 1
dao.insertJogo(cols, times)
}
count
}
val csvFilePath: String = args(0)
val csv = new CSV(csvFilePath)
csv.printLines
running(application) {
val realDatabase = Database.forDataSource(DB.getDataSource()(application))
implicit val s = realDatabase.createSession
insertJogos(csv)
}
}
I've made a blog post explaining my final solution. Should work as an answer to the question.
http://blog.felipe.rs/2014/05/15/run-maintenance-scripts-in-the-context-of-a-running-play-framework-application/
You could achieve this by using the play test:console command at the root of your app. First you could probably move the code into a main method rather than extending App:
class InsertJogosCSV {
def main(args: Array[String]) {
val dao = new DAO()
val application = FakeApplication()
def insertJogos(csv: CSV)(implicit s: Session) = {....}
....
}
}
then run the play test:console command and do the following
scala> import scripts.InsertJogosCSV
import scripts.InsertJogosCSV
scala> val insert = new InsertJogosCSV()
insert: scripts.InsertJogosCSV = scripts.InsertJogosCSV#7d5f9d2b
scala> insert.main
res0: .....
The play test:console by default adds everything from the app folder to your class path as well as the FakeApplication context that you need for your script. Hope that helps.
Similar question: https://stackoverflow.com/a/11297578/2556428
I am using another approach , for similar task.
Create empty subproject in main playframework project.
In build.sbt it looks like
// Main project
lazy val root = (project in file(".")).enablePlugins(play.PlayScala).enablePlugins(com.typesafe.sbt.web.SbtWeb)
// Utils sbt project with scripts
lazy val sjutil = project.aggregate(root).dependsOn(root)
and sjutil/build.sbt like normal sbt project with extra deps if needed, for me it was akka-remote
name := "sjutil"
version := "1.0-SNAPSHOT"
scalaVersion := "2.11.1"
libraryDependencies += "com.typesafe.akka" %% "akka-remote" % "2.3.4"
You can place some App direct in sjutil/ folder
sjutil/actorsstarter.scala:
object actorsstarter {
lazy val logger = play.api.Logger("actorsstarter")
def main(args: Array[String]) {
// read config from conf/application.conf of main project
val remoteConfig = ConfigFactory.load.getConfig("botstarter")
val system = ActorSystem("application",remoteConfig)
val path = "akka.tcp://application#127.0.0.1:2553/user"
....
logger.info("Started")
}
}
after that you can run this script with:
./activator sjutil/run
and make everything you can do with normal project: stage, dist and etc.
I'm trying to call a bash script within a oracle database through a java script. To test it I just tried a basic script :
#!/bin/bash
echo "It works !"
And the java script that I use is :
import java.lang.*;
import java.io.*;
public class UAM_TOOLS{
public static String Toto () throws IOException {
String[] unixCommand = {"/home/oz380/toto.sh"};
String pwd;
Process p = Runtime.getRuntime().exec(unixCommand);
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
pwd = input.readLine();
input.close();
return pwd;
}
};
I granted all the permissions that had to be granted and I created the function in my database :
SQL> CREATE OR REPLACE FUNCTION TOPI RETURN VARCHAR2
2 as language java
3 name 'UAM_TOOLS.Toto() return java.lang.String';
4 /
But then when I call the function :
select TOPI from dual;
or :
SQL> set serveroutput on;
SQL> DECLARE
2 G VARCHAR2(50);
3 BEGIN
4 G := UAM.TOPI;
5 DBMS_OUTPUT.PUT_LINE(G);
6 END;
7 /
It doesn't work and prints the error :
ORA-29541: class UAM.UAM_TOOLS could not be resolved
I don't really understand what the problem can be. If anyone does I would be really thankful.
Before the
CREATE FUNCTION
step you need to compile your class at command line
$>javac UAM_TOOLS.java
or using an IDE sth like Eclipse
that will generate compiled class with .class extension. For your case it will be UAM_TOOLS.class
And you still need to upload it to database on command line where the host which db runs on it
$>loadjava -user yourUserName/youPass#Yourdb UAM_TOOLS.class
after that 2 step you can resume with create function step.