repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
bitcoinj
|
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/wallet/WalletLoadTest.java
|
/*
* Copyright by the original author or authors.
*
* 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 org.bitcoinj.wallet;
import org.bitcoinj.core.Context;
import org.bitcoinj.crypto.HDPath;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Basic test of loading a wallet from a known test file
*/
public class WalletLoadTest {
private static final File walletFile = new File("src/test/resources/org/bitcoinj/wallet/panda-test-wallet.wallet");
private static final String testWalletMnemonic = "panda diary marriage suffer basic glare surge auto scissors describe sell unique";
private static final Instant testWalletCreation = Instant.ofEpochSecond(1554102000);
@Test
void basicWalletLoadTest() throws UnreadableWalletException {
Context.propagate(new Context());
Wallet wallet = Wallet.loadFromFile(walletFile);
Instant creation = wallet.getKeyChainSeed().creationTime().get();
assertEquals(testWalletCreation, creation, "unexpected creation timestamp");
String mnemonic = wallet.getKeyChainSeed().getMnemonicString();
assertEquals(testWalletMnemonic, mnemonic, "unexpected mnemonic");
HDPath accountPath = wallet.getActiveKeyChain().getAccountPath();
assertEquals(HDPath.parsePath("M/0H"), accountPath);
}
}
| 1,927
| 36.803922
| 136
|
java
|
bitcoinj
|
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/wallet/WalletAccountPathTest.java
|
/*
* Copyright by the original author or authors.
*
* 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 org.bitcoinj.wallet;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.crypto.HDPath;
import org.bitcoinj.base.BitcoinNetwork;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.stream.Stream;
import static org.bitcoinj.base.ScriptType.P2PKH;
import static org.bitcoinj.base.ScriptType.P2WPKH;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
import static org.bitcoinj.wallet.KeyChainGroupStructure.BIP43;
import static org.bitcoinj.wallet.KeyChainGroupStructure.BIP32;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Create new Wallets in a temp directory and make sure their account paths are correct.
*/
public class WalletAccountPathTest {
private static final String testWalletMnemonic = "panda diary marriage suffer basic glare surge auto scissors describe sell unique";
@TempDir File tempDir;
File walletFile;
@BeforeEach
void setupTest() {
walletFile = new File(tempDir, "test.wallet");
}
@MethodSource("walletStructureParams")
@ParameterizedTest(name = "path {1} generated for {2}, {3}")
void walletStructurePathTest2(KeyChainGroupStructure structure, HDPath expectedPath, ScriptType scriptType,
BitcoinNetwork network) throws IOException, UnreadableWalletException {
// When we create a wallet with parameterized structure, network, and scriptType
Wallet wallet = createWallet(walletFile, network, structure, scriptType);
// Then the account path is as expected
assertEquals(expectedPath, wallet.getActiveKeyChain().getAccountPath());
}
private static Stream<Arguments> walletStructureParams() {
return Stream.of(
// Note: For BIP32 wallets the Network does not affect the path
Arguments.of(BIP32, "M/0H", P2PKH, MAINNET),
Arguments.of(BIP32, "M/0H", P2PKH, TESTNET),
Arguments.of(BIP32, "M/1H", P2WPKH, MAINNET),
Arguments.of(BIP32, "M/1H", P2WPKH, TESTNET),
Arguments.of(BIP43, "M/44H/0H/0H", P2PKH, MAINNET),
Arguments.of(BIP43, "M/44H/1H/0H", P2PKH, TESTNET),
Arguments.of(BIP43, "M/84H/0H/0H", P2WPKH, MAINNET),
Arguments.of(BIP43, "M/84H/1H/0H", P2WPKH, TESTNET)
);
}
// Create a wallet, save it to a file, then reload from a file
private static Wallet createWallet(File walletFile, Network network, KeyChainGroupStructure structure, ScriptType outputScriptType) throws IOException, UnreadableWalletException {
Context.propagate(new Context());
DeterministicSeed seed = new DeterministicSeed(testWalletMnemonic, null, "", Instant.now());
Wallet wallet = Wallet.fromSeed(network, seed, outputScriptType, structure);
wallet.saveToFile(walletFile);
return Wallet.loadFromFile(walletFile);
}
}
| 3,920
| 41.619565
| 183
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/Among.java
|
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package opennlp.tools.stemmer.snowball;
import java.lang.reflect.Method;
class Among {
public Among (String s, int substring_i, int result,
String methodname, SnowballProgram methodobject) {
this.s_size = s.length();
this.s = s.toCharArray();
this.substring_i = substring_i;
this.result = result;
this.methodobject = methodobject;
if (methodname.length() == 0) {
this.method = null;
} else {
try {
this.method = methodobject.getClass().
getDeclaredMethod(methodname, new Class[0]);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
public final int s_size; /* search string */
public final char[] s; /* search string */
public final int substring_i; /* index to longest matching substring */
public final int result; /* result of the lookup */
public final Method method; /* method to use if substring matches */
public final SnowballProgram methodobject; /* object to invoke method on */
};
| 2,697
| 42.516129
| 81
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/SpanishStemmer.java
|
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This file was generated automatically by the Snowball to Java compiler
package opennlp.tools.stemmer.snowball;
/**
* This class was automatically generated by a Snowball to Java compiler
* It implements the stemming algorithm defined by a snowball script.
*/
public class SpanishStemmer extends opennlp.tools.stemmer.snowball.AbstractSnowballStemmer {
private static final long serialVersionUID = 1L;
private final static SpanishStemmer methodObject = new SpanishStemmer ();
private final static Among a_0[] = {
new Among ( "", -1, 6, "", methodObject ),
new Among ( "\u00E1", 0, 1, "", methodObject ),
new Among ( "\u00E9", 0, 2, "", methodObject ),
new Among ( "\u00ED", 0, 3, "", methodObject ),
new Among ( "\u00F3", 0, 4, "", methodObject ),
new Among ( "\u00FA", 0, 5, "", methodObject )
};
private final static Among a_1[] = {
new Among ( "la", -1, -1, "", methodObject ),
new Among ( "sela", 0, -1, "", methodObject ),
new Among ( "le", -1, -1, "", methodObject ),
new Among ( "me", -1, -1, "", methodObject ),
new Among ( "se", -1, -1, "", methodObject ),
new Among ( "lo", -1, -1, "", methodObject ),
new Among ( "selo", 5, -1, "", methodObject ),
new Among ( "las", -1, -1, "", methodObject ),
new Among ( "selas", 7, -1, "", methodObject ),
new Among ( "les", -1, -1, "", methodObject ),
new Among ( "los", -1, -1, "", methodObject ),
new Among ( "selos", 10, -1, "", methodObject ),
new Among ( "nos", -1, -1, "", methodObject )
};
private final static Among a_2[] = {
new Among ( "ando", -1, 6, "", methodObject ),
new Among ( "iendo", -1, 6, "", methodObject ),
new Among ( "yendo", -1, 7, "", methodObject ),
new Among ( "\u00E1ndo", -1, 2, "", methodObject ),
new Among ( "i\u00E9ndo", -1, 1, "", methodObject ),
new Among ( "ar", -1, 6, "", methodObject ),
new Among ( "er", -1, 6, "", methodObject ),
new Among ( "ir", -1, 6, "", methodObject ),
new Among ( "\u00E1r", -1, 3, "", methodObject ),
new Among ( "\u00E9r", -1, 4, "", methodObject ),
new Among ( "\u00EDr", -1, 5, "", methodObject )
};
private final static Among a_3[] = {
new Among ( "ic", -1, -1, "", methodObject ),
new Among ( "ad", -1, -1, "", methodObject ),
new Among ( "os", -1, -1, "", methodObject ),
new Among ( "iv", -1, 1, "", methodObject )
};
private final static Among a_4[] = {
new Among ( "able", -1, 1, "", methodObject ),
new Among ( "ible", -1, 1, "", methodObject ),
new Among ( "ante", -1, 1, "", methodObject )
};
private final static Among a_5[] = {
new Among ( "ic", -1, 1, "", methodObject ),
new Among ( "abil", -1, 1, "", methodObject ),
new Among ( "iv", -1, 1, "", methodObject )
};
private final static Among a_6[] = {
new Among ( "ica", -1, 1, "", methodObject ),
new Among ( "ancia", -1, 2, "", methodObject ),
new Among ( "encia", -1, 5, "", methodObject ),
new Among ( "adora", -1, 2, "", methodObject ),
new Among ( "osa", -1, 1, "", methodObject ),
new Among ( "ista", -1, 1, "", methodObject ),
new Among ( "iva", -1, 9, "", methodObject ),
new Among ( "anza", -1, 1, "", methodObject ),
new Among ( "log\u00EDa", -1, 3, "", methodObject ),
new Among ( "idad", -1, 8, "", methodObject ),
new Among ( "able", -1, 1, "", methodObject ),
new Among ( "ible", -1, 1, "", methodObject ),
new Among ( "ante", -1, 2, "", methodObject ),
new Among ( "mente", -1, 7, "", methodObject ),
new Among ( "amente", 13, 6, "", methodObject ),
new Among ( "aci\u00F3n", -1, 2, "", methodObject ),
new Among ( "uci\u00F3n", -1, 4, "", methodObject ),
new Among ( "ico", -1, 1, "", methodObject ),
new Among ( "ismo", -1, 1, "", methodObject ),
new Among ( "oso", -1, 1, "", methodObject ),
new Among ( "amiento", -1, 1, "", methodObject ),
new Among ( "imiento", -1, 1, "", methodObject ),
new Among ( "ivo", -1, 9, "", methodObject ),
new Among ( "ador", -1, 2, "", methodObject ),
new Among ( "icas", -1, 1, "", methodObject ),
new Among ( "ancias", -1, 2, "", methodObject ),
new Among ( "encias", -1, 5, "", methodObject ),
new Among ( "adoras", -1, 2, "", methodObject ),
new Among ( "osas", -1, 1, "", methodObject ),
new Among ( "istas", -1, 1, "", methodObject ),
new Among ( "ivas", -1, 9, "", methodObject ),
new Among ( "anzas", -1, 1, "", methodObject ),
new Among ( "log\u00EDas", -1, 3, "", methodObject ),
new Among ( "idades", -1, 8, "", methodObject ),
new Among ( "ables", -1, 1, "", methodObject ),
new Among ( "ibles", -1, 1, "", methodObject ),
new Among ( "aciones", -1, 2, "", methodObject ),
new Among ( "uciones", -1, 4, "", methodObject ),
new Among ( "adores", -1, 2, "", methodObject ),
new Among ( "antes", -1, 2, "", methodObject ),
new Among ( "icos", -1, 1, "", methodObject ),
new Among ( "ismos", -1, 1, "", methodObject ),
new Among ( "osos", -1, 1, "", methodObject ),
new Among ( "amientos", -1, 1, "", methodObject ),
new Among ( "imientos", -1, 1, "", methodObject ),
new Among ( "ivos", -1, 9, "", methodObject )
};
private final static Among a_7[] = {
new Among ( "ya", -1, 1, "", methodObject ),
new Among ( "ye", -1, 1, "", methodObject ),
new Among ( "yan", -1, 1, "", methodObject ),
new Among ( "yen", -1, 1, "", methodObject ),
new Among ( "yeron", -1, 1, "", methodObject ),
new Among ( "yendo", -1, 1, "", methodObject ),
new Among ( "yo", -1, 1, "", methodObject ),
new Among ( "yas", -1, 1, "", methodObject ),
new Among ( "yes", -1, 1, "", methodObject ),
new Among ( "yais", -1, 1, "", methodObject ),
new Among ( "yamos", -1, 1, "", methodObject ),
new Among ( "y\u00F3", -1, 1, "", methodObject )
};
private final static Among a_8[] = {
new Among ( "aba", -1, 2, "", methodObject ),
new Among ( "ada", -1, 2, "", methodObject ),
new Among ( "ida", -1, 2, "", methodObject ),
new Among ( "ara", -1, 2, "", methodObject ),
new Among ( "iera", -1, 2, "", methodObject ),
new Among ( "\u00EDa", -1, 2, "", methodObject ),
new Among ( "ar\u00EDa", 5, 2, "", methodObject ),
new Among ( "er\u00EDa", 5, 2, "", methodObject ),
new Among ( "ir\u00EDa", 5, 2, "", methodObject ),
new Among ( "ad", -1, 2, "", methodObject ),
new Among ( "ed", -1, 2, "", methodObject ),
new Among ( "id", -1, 2, "", methodObject ),
new Among ( "ase", -1, 2, "", methodObject ),
new Among ( "iese", -1, 2, "", methodObject ),
new Among ( "aste", -1, 2, "", methodObject ),
new Among ( "iste", -1, 2, "", methodObject ),
new Among ( "an", -1, 2, "", methodObject ),
new Among ( "aban", 16, 2, "", methodObject ),
new Among ( "aran", 16, 2, "", methodObject ),
new Among ( "ieran", 16, 2, "", methodObject ),
new Among ( "\u00EDan", 16, 2, "", methodObject ),
new Among ( "ar\u00EDan", 20, 2, "", methodObject ),
new Among ( "er\u00EDan", 20, 2, "", methodObject ),
new Among ( "ir\u00EDan", 20, 2, "", methodObject ),
new Among ( "en", -1, 1, "", methodObject ),
new Among ( "asen", 24, 2, "", methodObject ),
new Among ( "iesen", 24, 2, "", methodObject ),
new Among ( "aron", -1, 2, "", methodObject ),
new Among ( "ieron", -1, 2, "", methodObject ),
new Among ( "ar\u00E1n", -1, 2, "", methodObject ),
new Among ( "er\u00E1n", -1, 2, "", methodObject ),
new Among ( "ir\u00E1n", -1, 2, "", methodObject ),
new Among ( "ado", -1, 2, "", methodObject ),
new Among ( "ido", -1, 2, "", methodObject ),
new Among ( "ando", -1, 2, "", methodObject ),
new Among ( "iendo", -1, 2, "", methodObject ),
new Among ( "ar", -1, 2, "", methodObject ),
new Among ( "er", -1, 2, "", methodObject ),
new Among ( "ir", -1, 2, "", methodObject ),
new Among ( "as", -1, 2, "", methodObject ),
new Among ( "abas", 39, 2, "", methodObject ),
new Among ( "adas", 39, 2, "", methodObject ),
new Among ( "idas", 39, 2, "", methodObject ),
new Among ( "aras", 39, 2, "", methodObject ),
new Among ( "ieras", 39, 2, "", methodObject ),
new Among ( "\u00EDas", 39, 2, "", methodObject ),
new Among ( "ar\u00EDas", 45, 2, "", methodObject ),
new Among ( "er\u00EDas", 45, 2, "", methodObject ),
new Among ( "ir\u00EDas", 45, 2, "", methodObject ),
new Among ( "es", -1, 1, "", methodObject ),
new Among ( "ases", 49, 2, "", methodObject ),
new Among ( "ieses", 49, 2, "", methodObject ),
new Among ( "abais", -1, 2, "", methodObject ),
new Among ( "arais", -1, 2, "", methodObject ),
new Among ( "ierais", -1, 2, "", methodObject ),
new Among ( "\u00EDais", -1, 2, "", methodObject ),
new Among ( "ar\u00EDais", 55, 2, "", methodObject ),
new Among ( "er\u00EDais", 55, 2, "", methodObject ),
new Among ( "ir\u00EDais", 55, 2, "", methodObject ),
new Among ( "aseis", -1, 2, "", methodObject ),
new Among ( "ieseis", -1, 2, "", methodObject ),
new Among ( "asteis", -1, 2, "", methodObject ),
new Among ( "isteis", -1, 2, "", methodObject ),
new Among ( "\u00E1is", -1, 2, "", methodObject ),
new Among ( "\u00E9is", -1, 1, "", methodObject ),
new Among ( "ar\u00E9is", 64, 2, "", methodObject ),
new Among ( "er\u00E9is", 64, 2, "", methodObject ),
new Among ( "ir\u00E9is", 64, 2, "", methodObject ),
new Among ( "ados", -1, 2, "", methodObject ),
new Among ( "idos", -1, 2, "", methodObject ),
new Among ( "amos", -1, 2, "", methodObject ),
new Among ( "\u00E1bamos", 70, 2, "", methodObject ),
new Among ( "\u00E1ramos", 70, 2, "", methodObject ),
new Among ( "i\u00E9ramos", 70, 2, "", methodObject ),
new Among ( "\u00EDamos", 70, 2, "", methodObject ),
new Among ( "ar\u00EDamos", 74, 2, "", methodObject ),
new Among ( "er\u00EDamos", 74, 2, "", methodObject ),
new Among ( "ir\u00EDamos", 74, 2, "", methodObject ),
new Among ( "emos", -1, 1, "", methodObject ),
new Among ( "aremos", 78, 2, "", methodObject ),
new Among ( "eremos", 78, 2, "", methodObject ),
new Among ( "iremos", 78, 2, "", methodObject ),
new Among ( "\u00E1semos", 78, 2, "", methodObject ),
new Among ( "i\u00E9semos", 78, 2, "", methodObject ),
new Among ( "imos", -1, 2, "", methodObject ),
new Among ( "ar\u00E1s", -1, 2, "", methodObject ),
new Among ( "er\u00E1s", -1, 2, "", methodObject ),
new Among ( "ir\u00E1s", -1, 2, "", methodObject ),
new Among ( "\u00EDs", -1, 2, "", methodObject ),
new Among ( "ar\u00E1", -1, 2, "", methodObject ),
new Among ( "er\u00E1", -1, 2, "", methodObject ),
new Among ( "ir\u00E1", -1, 2, "", methodObject ),
new Among ( "ar\u00E9", -1, 2, "", methodObject ),
new Among ( "er\u00E9", -1, 2, "", methodObject ),
new Among ( "ir\u00E9", -1, 2, "", methodObject ),
new Among ( "i\u00F3", -1, 2, "", methodObject )
};
private final static Among a_9[] = {
new Among ( "a", -1, 1, "", methodObject ),
new Among ( "e", -1, 2, "", methodObject ),
new Among ( "o", -1, 1, "", methodObject ),
new Among ( "os", -1, 1, "", methodObject ),
new Among ( "\u00E1", -1, 1, "", methodObject ),
new Among ( "\u00E9", -1, 2, "", methodObject ),
new Among ( "\u00ED", -1, 1, "", methodObject ),
new Among ( "\u00F3", -1, 1, "", methodObject )
};
private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 4, 10 };
private int I_p2;
private int I_p1;
private int I_pV;
private void copy_from(SpanishStemmer other) {
I_p2 = other.I_p2;
I_p1 = other.I_p1;
I_pV = other.I_pV;
super.copy_from(other);
}
private boolean r_mark_regions() {
int v_1;
int v_2;
int v_3;
int v_6;
int v_8;
// (, line 31
I_pV = limit;
I_p1 = limit;
I_p2 = limit;
// do, line 37
v_1 = cursor;
lab0: do {
// (, line 37
// or, line 39
lab1: do {
v_2 = cursor;
lab2: do {
// (, line 38
if (!(in_grouping(g_v, 97, 252)))
{
break lab2;
}
// or, line 38
lab3: do {
v_3 = cursor;
lab4: do {
// (, line 38
if (!(out_grouping(g_v, 97, 252)))
{
break lab4;
}
// gopast, line 38
golab5: while(true)
{
lab6: do {
if (!(in_grouping(g_v, 97, 252)))
{
break lab6;
}
break golab5;
} while (false);
if (cursor >= limit)
{
break lab4;
}
cursor++;
}
break lab3;
} while (false);
cursor = v_3;
// (, line 38
if (!(in_grouping(g_v, 97, 252)))
{
break lab2;
}
// gopast, line 38
golab7: while(true)
{
lab8: do {
if (!(out_grouping(g_v, 97, 252)))
{
break lab8;
}
break golab7;
} while (false);
if (cursor >= limit)
{
break lab2;
}
cursor++;
}
} while (false);
break lab1;
} while (false);
cursor = v_2;
// (, line 40
if (!(out_grouping(g_v, 97, 252)))
{
break lab0;
}
// or, line 40
lab9: do {
v_6 = cursor;
lab10: do {
// (, line 40
if (!(out_grouping(g_v, 97, 252)))
{
break lab10;
}
// gopast, line 40
golab11: while(true)
{
lab12: do {
if (!(in_grouping(g_v, 97, 252)))
{
break lab12;
}
break golab11;
} while (false);
if (cursor >= limit)
{
break lab10;
}
cursor++;
}
break lab9;
} while (false);
cursor = v_6;
// (, line 40
if (!(in_grouping(g_v, 97, 252)))
{
break lab0;
}
// next, line 40
if (cursor >= limit)
{
break lab0;
}
cursor++;
} while (false);
} while (false);
// setmark pV, line 41
I_pV = cursor;
} while (false);
cursor = v_1;
// do, line 43
v_8 = cursor;
lab13: do {
// (, line 43
// gopast, line 44
golab14: while(true)
{
lab15: do {
if (!(in_grouping(g_v, 97, 252)))
{
break lab15;
}
break golab14;
} while (false);
if (cursor >= limit)
{
break lab13;
}
cursor++;
}
// gopast, line 44
golab16: while(true)
{
lab17: do {
if (!(out_grouping(g_v, 97, 252)))
{
break lab17;
}
break golab16;
} while (false);
if (cursor >= limit)
{
break lab13;
}
cursor++;
}
// setmark p1, line 44
I_p1 = cursor;
// gopast, line 45
golab18: while(true)
{
lab19: do {
if (!(in_grouping(g_v, 97, 252)))
{
break lab19;
}
break golab18;
} while (false);
if (cursor >= limit)
{
break lab13;
}
cursor++;
}
// gopast, line 45
golab20: while(true)
{
lab21: do {
if (!(out_grouping(g_v, 97, 252)))
{
break lab21;
}
break golab20;
} while (false);
if (cursor >= limit)
{
break lab13;
}
cursor++;
}
// setmark p2, line 45
I_p2 = cursor;
} while (false);
cursor = v_8;
return true;
}
private boolean r_postlude() {
int among_var;
int v_1;
// repeat, line 49
replab0: while(true)
{
v_1 = cursor;
lab1: do {
// (, line 49
// [, line 50
bra = cursor;
// substring, line 50
among_var = find_among(a_0, 6);
if (among_var == 0)
{
break lab1;
}
// ], line 50
ket = cursor;
switch(among_var) {
case 0:
break lab1;
case 1:
// (, line 51
// <-, line 51
slice_from("a");
break;
case 2:
// (, line 52
// <-, line 52
slice_from("e");
break;
case 3:
// (, line 53
// <-, line 53
slice_from("i");
break;
case 4:
// (, line 54
// <-, line 54
slice_from("o");
break;
case 5:
// (, line 55
// <-, line 55
slice_from("u");
break;
case 6:
// (, line 57
// next, line 57
if (cursor >= limit)
{
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
}
private boolean r_RV() {
if (!(I_pV <= cursor))
{
return false;
}
return true;
}
private boolean r_R1() {
if (!(I_p1 <= cursor))
{
return false;
}
return true;
}
private boolean r_R2() {
if (!(I_p2 <= cursor))
{
return false;
}
return true;
}
private boolean r_attached_pronoun() {
int among_var;
// (, line 67
// [, line 68
ket = cursor;
// substring, line 68
if (find_among_b(a_1, 13) == 0)
{
return false;
}
// ], line 68
bra = cursor;
// substring, line 72
among_var = find_among_b(a_2, 11);
if (among_var == 0)
{
return false;
}
// call RV, line 72
if (!r_RV())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 73
// ], line 73
bra = cursor;
// <-, line 73
slice_from("iendo");
break;
case 2:
// (, line 74
// ], line 74
bra = cursor;
// <-, line 74
slice_from("ando");
break;
case 3:
// (, line 75
// ], line 75
bra = cursor;
// <-, line 75
slice_from("ar");
break;
case 4:
// (, line 76
// ], line 76
bra = cursor;
// <-, line 76
slice_from("er");
break;
case 5:
// (, line 77
// ], line 77
bra = cursor;
// <-, line 77
slice_from("ir");
break;
case 6:
// (, line 81
// delete, line 81
slice_del();
break;
case 7:
// (, line 82
// literal, line 82
if (!(eq_s_b(1, "u")))
{
return false;
}
// delete, line 82
slice_del();
break;
}
return true;
}
private boolean r_standard_suffix() {
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
// (, line 86
// [, line 87
ket = cursor;
// substring, line 87
among_var = find_among_b(a_6, 46);
if (among_var == 0)
{
return false;
}
// ], line 87
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 98
// call R2, line 99
if (!r_R2())
{
return false;
}
// delete, line 99
slice_del();
break;
case 2:
// (, line 104
// call R2, line 105
if (!r_R2())
{
return false;
}
// delete, line 105
slice_del();
// try, line 106
v_1 = limit - cursor;
lab0: do {
// (, line 106
// [, line 106
ket = cursor;
// literal, line 106
if (!(eq_s_b(2, "ic")))
{
cursor = limit - v_1;
break lab0;
}
// ], line 106
bra = cursor;
// call R2, line 106
if (!r_R2())
{
cursor = limit - v_1;
break lab0;
}
// delete, line 106
slice_del();
} while (false);
break;
case 3:
// (, line 110
// call R2, line 111
if (!r_R2())
{
return false;
}
// <-, line 111
slice_from("log");
break;
case 4:
// (, line 114
// call R2, line 115
if (!r_R2())
{
return false;
}
// <-, line 115
slice_from("u");
break;
case 5:
// (, line 118
// call R2, line 119
if (!r_R2())
{
return false;
}
// <-, line 119
slice_from("ente");
break;
case 6:
// (, line 122
// call R1, line 123
if (!r_R1())
{
return false;
}
// delete, line 123
slice_del();
// try, line 124
v_2 = limit - cursor;
lab1: do {
// (, line 124
// [, line 125
ket = cursor;
// substring, line 125
among_var = find_among_b(a_3, 4);
if (among_var == 0)
{
cursor = limit - v_2;
break lab1;
}
// ], line 125
bra = cursor;
// call R2, line 125
if (!r_R2())
{
cursor = limit - v_2;
break lab1;
}
// delete, line 125
slice_del();
switch(among_var) {
case 0:
cursor = limit - v_2;
break lab1;
case 1:
// (, line 126
// [, line 126
ket = cursor;
// literal, line 126
if (!(eq_s_b(2, "at")))
{
cursor = limit - v_2;
break lab1;
}
// ], line 126
bra = cursor;
// call R2, line 126
if (!r_R2())
{
cursor = limit - v_2;
break lab1;
}
// delete, line 126
slice_del();
break;
}
} while (false);
break;
case 7:
// (, line 134
// call R2, line 135
if (!r_R2())
{
return false;
}
// delete, line 135
slice_del();
// try, line 136
v_3 = limit - cursor;
lab2: do {
// (, line 136
// [, line 137
ket = cursor;
// substring, line 137
among_var = find_among_b(a_4, 3);
if (among_var == 0)
{
cursor = limit - v_3;
break lab2;
}
// ], line 137
bra = cursor;
switch(among_var) {
case 0:
cursor = limit - v_3;
break lab2;
case 1:
// (, line 140
// call R2, line 140
if (!r_R2())
{
cursor = limit - v_3;
break lab2;
}
// delete, line 140
slice_del();
break;
}
} while (false);
break;
case 8:
// (, line 146
// call R2, line 147
if (!r_R2())
{
return false;
}
// delete, line 147
slice_del();
// try, line 148
v_4 = limit - cursor;
lab3: do {
// (, line 148
// [, line 149
ket = cursor;
// substring, line 149
among_var = find_among_b(a_5, 3);
if (among_var == 0)
{
cursor = limit - v_4;
break lab3;
}
// ], line 149
bra = cursor;
switch(among_var) {
case 0:
cursor = limit - v_4;
break lab3;
case 1:
// (, line 152
// call R2, line 152
if (!r_R2())
{
cursor = limit - v_4;
break lab3;
}
// delete, line 152
slice_del();
break;
}
} while (false);
break;
case 9:
// (, line 158
// call R2, line 159
if (!r_R2())
{
return false;
}
// delete, line 159
slice_del();
// try, line 160
v_5 = limit - cursor;
lab4: do {
// (, line 160
// [, line 161
ket = cursor;
// literal, line 161
if (!(eq_s_b(2, "at")))
{
cursor = limit - v_5;
break lab4;
}
// ], line 161
bra = cursor;
// call R2, line 161
if (!r_R2())
{
cursor = limit - v_5;
break lab4;
}
// delete, line 161
slice_del();
} while (false);
break;
}
return true;
}
private boolean r_y_verb_suffix() {
int among_var;
int v_1;
int v_2;
// (, line 167
// setlimit, line 168
v_1 = limit - cursor;
// tomark, line 168
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 168
// [, line 168
ket = cursor;
// substring, line 168
among_var = find_among_b(a_7, 12);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 168
bra = cursor;
limit_backward = v_2;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 171
// literal, line 171
if (!(eq_s_b(1, "u")))
{
return false;
}
// delete, line 171
slice_del();
break;
}
return true;
}
private boolean r_verb_suffix() {
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
// (, line 175
// setlimit, line 176
v_1 = limit - cursor;
// tomark, line 176
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 176
// [, line 176
ket = cursor;
// substring, line 176
among_var = find_among_b(a_8, 96);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 176
bra = cursor;
limit_backward = v_2;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 179
// try, line 179
v_3 = limit - cursor;
lab0: do {
// (, line 179
// literal, line 179
if (!(eq_s_b(1, "u")))
{
cursor = limit - v_3;
break lab0;
}
// test, line 179
v_4 = limit - cursor;
// literal, line 179
if (!(eq_s_b(1, "g")))
{
cursor = limit - v_3;
break lab0;
}
cursor = limit - v_4;
} while (false);
// ], line 179
bra = cursor;
// delete, line 179
slice_del();
break;
case 2:
// (, line 200
// delete, line 200
slice_del();
break;
}
return true;
}
private boolean r_residual_suffix() {
int among_var;
int v_1;
int v_2;
// (, line 204
// [, line 205
ket = cursor;
// substring, line 205
among_var = find_among_b(a_9, 8);
if (among_var == 0)
{
return false;
}
// ], line 205
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 208
// call RV, line 208
if (!r_RV())
{
return false;
}
// delete, line 208
slice_del();
break;
case 2:
// (, line 210
// call RV, line 210
if (!r_RV())
{
return false;
}
// delete, line 210
slice_del();
// try, line 210
v_1 = limit - cursor;
lab0: do {
// (, line 210
// [, line 210
ket = cursor;
// literal, line 210
if (!(eq_s_b(1, "u")))
{
cursor = limit - v_1;
break lab0;
}
// ], line 210
bra = cursor;
// test, line 210
v_2 = limit - cursor;
// literal, line 210
if (!(eq_s_b(1, "g")))
{
cursor = limit - v_1;
break lab0;
}
cursor = limit - v_2;
// call RV, line 210
if (!r_RV())
{
cursor = limit - v_1;
break lab0;
}
// delete, line 210
slice_del();
} while (false);
break;
}
return true;
}
public boolean stem() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
// (, line 215
// do, line 216
v_1 = cursor;
lab0: do {
// call mark_regions, line 216
if (!r_mark_regions())
{
break lab0;
}
} while (false);
cursor = v_1;
// backwards, line 217
limit_backward = cursor; cursor = limit;
// (, line 217
// do, line 218
v_2 = limit - cursor;
lab1: do {
// call attached_pronoun, line 218
if (!r_attached_pronoun())
{
break lab1;
}
} while (false);
cursor = limit - v_2;
// do, line 219
v_3 = limit - cursor;
lab2: do {
// (, line 219
// or, line 219
lab3: do {
v_4 = limit - cursor;
lab4: do {
// call standard_suffix, line 219
if (!r_standard_suffix())
{
break lab4;
}
break lab3;
} while (false);
cursor = limit - v_4;
lab5: do {
// call y_verb_suffix, line 220
if (!r_y_verb_suffix())
{
break lab5;
}
break lab3;
} while (false);
cursor = limit - v_4;
// call verb_suffix, line 221
if (!r_verb_suffix())
{
break lab2;
}
} while (false);
} while (false);
cursor = limit - v_3;
// do, line 223
v_5 = limit - cursor;
lab6: do {
// call residual_suffix, line 223
if (!r_residual_suffix())
{
break lab6;
}
} while (false);
cursor = limit - v_5;
cursor = limit_backward; // do, line 225
v_6 = cursor;
lab7: do {
// call postlude, line 225
if (!r_postlude())
{
break lab7;
}
} while (false);
cursor = v_6;
return true;
}
public boolean equals( Object o ) {
return o instanceof SpanishStemmer;
}
public int hashCode() {
return SpanishStemmer.class.getName().hashCode();
}
}
| 47,086
| 37.532733
| 109
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/SnowballStemmer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 opennlp.tools.stemmer.snowball;
import opennlp.tools.stemmer.Stemmer;
public class SnowballStemmer implements Stemmer {
public enum ALGORITHM {
DANISH,
DUTCH,
ENGLISH,
FINNISH,
FRENCH,
GERMAN,
HUNGARIAN,
ITALIAN,
NORWEGIAN,
PORTER,
PORTUGUESE,
ROMANIAN,
RUSSIAN,
SPANISH,
SWEDISH,
TURKISH
}
private final AbstractSnowballStemmer stemmer;
private final int repeat;
public SnowballStemmer(ALGORITHM algorithm, int repeat) {
this.repeat = repeat;
if (ALGORITHM.RUSSIAN.equals(algorithm))
stemmer = new RussianStemmer();
else if (ALGORITHM.ENGLISH.equals(algorithm))
stemmer = new EnglishStemmer();
else if (ALGORITHM.SPANISH.equals(algorithm))
stemmer = new SpanishStemmer();
else
throw new IllegalStateException("Unexpected stemmer algorithm: " + algorithm.toString());
}
public SnowballStemmer(ALGORITHM algorithm) {
this(algorithm, 1);
}
public CharSequence stem(CharSequence word) {
stemmer.setCurrent(word.toString());
for (int i = 0; i < repeat; i++)
stemmer.stem();
return stemmer.getCurrent();
}
}
| 2,121
| 29.314286
| 101
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/AbstractSnowballStemmer.java
|
/*
2
3 Copyright (c) 2001, Dr Martin Porter
4 Copyright (c) 2002, Richard Boulton
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 * Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
12 * Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * Neither the name of the copyright holders nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
23 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 */
package opennlp.tools.stemmer.snowball;
abstract class AbstractSnowballStemmer extends SnowballProgram {
public abstract boolean stem();
};
| 1,793
| 48.833333
| 84
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/EnglishStemmer.java
|
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This file was generated automatically by the Snowball to Java compiler
package opennlp.tools.stemmer.snowball;
/**
* This class was automatically generated by a Snowball to Java compiler
* It implements the stemming algorithm defined by a snowball script.
*/
class EnglishStemmer extends opennlp.tools.stemmer.snowball.AbstractSnowballStemmer {
private static final long serialVersionUID = 1L;
private final static EnglishStemmer methodObject = new EnglishStemmer();
private final static Among a_0[] = {
new Among ( "arsen", -1, -1, "", methodObject ),
new Among ( "commun", -1, -1, "", methodObject ),
new Among ( "gener", -1, -1, "", methodObject )
};
private final static Among a_1[] = {
new Among ( "'", -1, 1, "", methodObject ),
new Among ( "'s'", 0, 1, "", methodObject ),
new Among ( "'s", -1, 1, "", methodObject )
};
private final static Among a_2[] = {
new Among ( "ied", -1, 2, "", methodObject ),
new Among ( "s", -1, 3, "", methodObject ),
new Among ( "ies", 1, 2, "", methodObject ),
new Among ( "sses", 1, 1, "", methodObject ),
new Among ( "ss", 1, -1, "", methodObject ),
new Among ( "us", 1, -1, "", methodObject )
};
private final static Among a_3[] = {
new Among ( "", -1, 3, "", methodObject ),
new Among ( "bb", 0, 2, "", methodObject ),
new Among ( "dd", 0, 2, "", methodObject ),
new Among ( "ff", 0, 2, "", methodObject ),
new Among ( "gg", 0, 2, "", methodObject ),
new Among ( "bl", 0, 1, "", methodObject ),
new Among ( "mm", 0, 2, "", methodObject ),
new Among ( "nn", 0, 2, "", methodObject ),
new Among ( "pp", 0, 2, "", methodObject ),
new Among ( "rr", 0, 2, "", methodObject ),
new Among ( "at", 0, 1, "", methodObject ),
new Among ( "tt", 0, 2, "", methodObject ),
new Among ( "iz", 0, 1, "", methodObject )
};
private final static Among a_4[] = {
new Among ( "ed", -1, 2, "", methodObject ),
new Among ( "eed", 0, 1, "", methodObject ),
new Among ( "ing", -1, 2, "", methodObject ),
new Among ( "edly", -1, 2, "", methodObject ),
new Among ( "eedly", 3, 1, "", methodObject ),
new Among ( "ingly", -1, 2, "", methodObject )
};
private final static Among a_5[] = {
new Among ( "anci", -1, 3, "", methodObject ),
new Among ( "enci", -1, 2, "", methodObject ),
new Among ( "ogi", -1, 13, "", methodObject ),
new Among ( "li", -1, 16, "", methodObject ),
new Among ( "bli", 3, 12, "", methodObject ),
new Among ( "abli", 4, 4, "", methodObject ),
new Among ( "alli", 3, 8, "", methodObject ),
new Among ( "fulli", 3, 14, "", methodObject ),
new Among ( "lessli", 3, 15, "", methodObject ),
new Among ( "ousli", 3, 10, "", methodObject ),
new Among ( "entli", 3, 5, "", methodObject ),
new Among ( "aliti", -1, 8, "", methodObject ),
new Among ( "biliti", -1, 12, "", methodObject ),
new Among ( "iviti", -1, 11, "", methodObject ),
new Among ( "tional", -1, 1, "", methodObject ),
new Among ( "ational", 14, 7, "", methodObject ),
new Among ( "alism", -1, 8, "", methodObject ),
new Among ( "ation", -1, 7, "", methodObject ),
new Among ( "ization", 17, 6, "", methodObject ),
new Among ( "izer", -1, 6, "", methodObject ),
new Among ( "ator", -1, 7, "", methodObject ),
new Among ( "iveness", -1, 11, "", methodObject ),
new Among ( "fulness", -1, 9, "", methodObject ),
new Among ( "ousness", -1, 10, "", methodObject )
};
private final static Among a_6[] = {
new Among ( "icate", -1, 4, "", methodObject ),
new Among ( "ative", -1, 6, "", methodObject ),
new Among ( "alize", -1, 3, "", methodObject ),
new Among ( "iciti", -1, 4, "", methodObject ),
new Among ( "ical", -1, 4, "", methodObject ),
new Among ( "tional", -1, 1, "", methodObject ),
new Among ( "ational", 5, 2, "", methodObject ),
new Among ( "ful", -1, 5, "", methodObject ),
new Among ( "ness", -1, 5, "", methodObject )
};
private final static Among a_7[] = {
new Among ( "ic", -1, 1, "", methodObject ),
new Among ( "ance", -1, 1, "", methodObject ),
new Among ( "ence", -1, 1, "", methodObject ),
new Among ( "able", -1, 1, "", methodObject ),
new Among ( "ible", -1, 1, "", methodObject ),
new Among ( "ate", -1, 1, "", methodObject ),
new Among ( "ive", -1, 1, "", methodObject ),
new Among ( "ize", -1, 1, "", methodObject ),
new Among ( "iti", -1, 1, "", methodObject ),
new Among ( "al", -1, 1, "", methodObject ),
new Among ( "ism", -1, 1, "", methodObject ),
new Among ( "ion", -1, 2, "", methodObject ),
new Among ( "er", -1, 1, "", methodObject ),
new Among ( "ous", -1, 1, "", methodObject ),
new Among ( "ant", -1, 1, "", methodObject ),
new Among ( "ent", -1, 1, "", methodObject ),
new Among ( "ment", 15, 1, "", methodObject ),
new Among ( "ement", 16, 1, "", methodObject )
};
private final static Among a_8[] = {
new Among ( "e", -1, 1, "", methodObject ),
new Among ( "l", -1, 2, "", methodObject )
};
private final static Among a_9[] = {
new Among ( "succeed", -1, -1, "", methodObject ),
new Among ( "proceed", -1, -1, "", methodObject ),
new Among ( "exceed", -1, -1, "", methodObject ),
new Among ( "canning", -1, -1, "", methodObject ),
new Among ( "inning", -1, -1, "", methodObject ),
new Among ( "earring", -1, -1, "", methodObject ),
new Among ( "herring", -1, -1, "", methodObject ),
new Among ( "outing", -1, -1, "", methodObject )
};
private final static Among a_10[] = {
new Among ( "andes", -1, -1, "", methodObject ),
new Among ( "atlas", -1, -1, "", methodObject ),
new Among ( "bias", -1, -1, "", methodObject ),
new Among ( "cosmos", -1, -1, "", methodObject ),
new Among ( "dying", -1, 3, "", methodObject ),
new Among ( "early", -1, 9, "", methodObject ),
new Among ( "gently", -1, 7, "", methodObject ),
new Among ( "howe", -1, -1, "", methodObject ),
new Among ( "idly", -1, 6, "", methodObject ),
new Among ( "lying", -1, 4, "", methodObject ),
new Among ( "news", -1, -1, "", methodObject ),
new Among ( "only", -1, 10, "", methodObject ),
new Among ( "singly", -1, 11, "", methodObject ),
new Among ( "skies", -1, 2, "", methodObject ),
new Among ( "skis", -1, 1, "", methodObject ),
new Among ( "sky", -1, -1, "", methodObject ),
new Among ( "tying", -1, 5, "", methodObject ),
new Among ( "ugly", -1, 8, "", methodObject )
};
private static final char g_v[] = {17, 65, 16, 1 };
private static final char g_v_WXY[] = {1, 17, 65, 208, 1 };
private static final char g_valid_LI[] = {55, 141, 2 };
private boolean B_Y_found;
private int I_p2;
private int I_p1;
private void copy_from(EnglishStemmer other) {
B_Y_found = other.B_Y_found;
I_p2 = other.I_p2;
I_p1 = other.I_p1;
super.copy_from(other);
}
private boolean r_prelude() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
// (, line 25
// unset Y_found, line 26
B_Y_found = false;
// do, line 27
v_1 = cursor;
lab0: do {
// (, line 27
// [, line 27
bra = cursor;
// literal, line 27
if (!(eq_s(1, "'")))
{
break lab0;
}
// ], line 27
ket = cursor;
// delete, line 27
slice_del();
} while (false);
cursor = v_1;
// do, line 28
v_2 = cursor;
lab1: do {
// (, line 28
// [, line 28
bra = cursor;
// literal, line 28
if (!(eq_s(1, "y")))
{
break lab1;
}
// ], line 28
ket = cursor;
// <-, line 28
slice_from("Y");
// set Y_found, line 28
B_Y_found = true;
} while (false);
cursor = v_2;
// do, line 29
v_3 = cursor;
lab2: do {
// repeat, line 29
replab3: while(true)
{
v_4 = cursor;
lab4: do {
// (, line 29
// goto, line 29
golab5: while(true)
{
v_5 = cursor;
lab6: do {
// (, line 29
if (!(in_grouping(g_v, 97, 121)))
{
break lab6;
}
// [, line 29
bra = cursor;
// literal, line 29
if (!(eq_s(1, "y")))
{
break lab6;
}
// ], line 29
ket = cursor;
cursor = v_5;
break golab5;
} while (false);
cursor = v_5;
if (cursor >= limit)
{
break lab4;
}
cursor++;
}
// <-, line 29
slice_from("Y");
// set Y_found, line 29
B_Y_found = true;
continue replab3;
} while (false);
cursor = v_4;
break replab3;
}
} while (false);
cursor = v_3;
return true;
}
private boolean r_mark_regions() {
int v_1;
int v_2;
// (, line 32
I_p1 = limit;
I_p2 = limit;
// do, line 35
v_1 = cursor;
lab0: do {
// (, line 35
// or, line 41
lab1: do {
v_2 = cursor;
lab2: do {
// among, line 36
if (find_among(a_0, 3) == 0)
{
break lab2;
}
break lab1;
} while (false);
cursor = v_2;
// (, line 41
// gopast, line 41
golab3: while(true)
{
lab4: do {
if (!(in_grouping(g_v, 97, 121)))
{
break lab4;
}
break golab3;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// gopast, line 41
golab5: while(true)
{
lab6: do {
if (!(out_grouping(g_v, 97, 121)))
{
break lab6;
}
break golab5;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
} while (false);
// setmark p1, line 42
I_p1 = cursor;
// gopast, line 43
golab7: while(true)
{
lab8: do {
if (!(in_grouping(g_v, 97, 121)))
{
break lab8;
}
break golab7;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// gopast, line 43
golab9: while(true)
{
lab10: do {
if (!(out_grouping(g_v, 97, 121)))
{
break lab10;
}
break golab9;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// setmark p2, line 43
I_p2 = cursor;
} while (false);
cursor = v_1;
return true;
}
private boolean r_shortv() {
int v_1;
// (, line 49
// or, line 51
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 50
if (!(out_grouping_b(g_v_WXY, 89, 121)))
{
break lab1;
}
if (!(in_grouping_b(g_v, 97, 121)))
{
break lab1;
}
if (!(out_grouping_b(g_v, 97, 121)))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 52
if (!(out_grouping_b(g_v, 97, 121)))
{
return false;
}
if (!(in_grouping_b(g_v, 97, 121)))
{
return false;
}
// atlimit, line 52
if (cursor > limit_backward)
{
return false;
}
} while (false);
return true;
}
private boolean r_R1() {
if (!(I_p1 <= cursor))
{
return false;
}
return true;
}
private boolean r_R2() {
if (!(I_p2 <= cursor))
{
return false;
}
return true;
}
private boolean r_Step_1a() {
int among_var;
int v_1;
int v_2;
// (, line 58
// try, line 59
v_1 = limit - cursor;
lab0: do {
// (, line 59
// [, line 60
ket = cursor;
// substring, line 60
among_var = find_among_b(a_1, 3);
if (among_var == 0)
{
cursor = limit - v_1;
break lab0;
}
// ], line 60
bra = cursor;
switch(among_var) {
case 0:
cursor = limit - v_1;
break lab0;
case 1:
// (, line 62
// delete, line 62
slice_del();
break;
}
} while (false);
// [, line 65
ket = cursor;
// substring, line 65
among_var = find_among_b(a_2, 6);
if (among_var == 0)
{
return false;
}
// ], line 65
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 66
// <-, line 66
slice_from("ss");
break;
case 2:
// (, line 68
// or, line 68
lab1: do {
v_2 = limit - cursor;
lab2: do {
// (, line 68
// hop, line 68
{
int c = cursor - 2;
if (limit_backward > c || c > limit)
{
break lab2;
}
cursor = c;
}
// <-, line 68
slice_from("i");
break lab1;
} while (false);
cursor = limit - v_2;
// <-, line 68
slice_from("ie");
} while (false);
break;
case 3:
// (, line 69
// next, line 69
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// gopast, line 69
golab3: while(true)
{
lab4: do {
if (!(in_grouping_b(g_v, 97, 121)))
{
break lab4;
}
break golab3;
} while (false);
if (cursor <= limit_backward)
{
return false;
}
cursor--;
}
// delete, line 69
slice_del();
break;
}
return true;
}
private boolean r_Step_1b() {
int among_var;
int v_1;
int v_3;
int v_4;
// (, line 74
// [, line 75
ket = cursor;
// substring, line 75
among_var = find_among_b(a_4, 6);
if (among_var == 0)
{
return false;
}
// ], line 75
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 77
// call R1, line 77
if (!r_R1())
{
return false;
}
// <-, line 77
slice_from("ee");
break;
case 2:
// (, line 79
// test, line 80
v_1 = limit - cursor;
// gopast, line 80
golab0: while(true)
{
lab1: do {
if (!(in_grouping_b(g_v, 97, 121)))
{
break lab1;
}
break golab0;
} while (false);
if (cursor <= limit_backward)
{
return false;
}
cursor--;
}
cursor = limit - v_1;
// delete, line 80
slice_del();
// test, line 81
v_3 = limit - cursor;
// substring, line 81
among_var = find_among_b(a_3, 13);
if (among_var == 0)
{
return false;
}
cursor = limit - v_3;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 83
// <+, line 83
{
int c = cursor;
insert(cursor, cursor, "e");
cursor = c;
}
break;
case 2:
// (, line 86
// [, line 86
ket = cursor;
// next, line 86
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// ], line 86
bra = cursor;
// delete, line 86
slice_del();
break;
case 3:
// (, line 87
// atmark, line 87
if (cursor != I_p1)
{
return false;
}
// test, line 87
v_4 = limit - cursor;
// call shortv, line 87
if (!r_shortv())
{
return false;
}
cursor = limit - v_4;
// <+, line 87
{
int c = cursor;
insert(cursor, cursor, "e");
cursor = c;
}
break;
}
break;
}
return true;
}
private boolean r_Step_1c() {
int v_1;
int v_2;
// (, line 93
// [, line 94
ket = cursor;
// or, line 94
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 94
if (!(eq_s_b(1, "y")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 94
if (!(eq_s_b(1, "Y")))
{
return false;
}
} while (false);
// ], line 94
bra = cursor;
if (!(out_grouping_b(g_v, 97, 121)))
{
return false;
}
// not, line 95
{
v_2 = limit - cursor;
lab2: do {
// atlimit, line 95
if (cursor > limit_backward)
{
break lab2;
}
return false;
} while (false);
cursor = limit - v_2;
}
// <-, line 96
slice_from("i");
return true;
}
private boolean r_Step_2() {
int among_var;
// (, line 99
// [, line 100
ket = cursor;
// substring, line 100
among_var = find_among_b(a_5, 24);
if (among_var == 0)
{
return false;
}
// ], line 100
bra = cursor;
// call R1, line 100
if (!r_R1())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 101
// <-, line 101
slice_from("tion");
break;
case 2:
// (, line 102
// <-, line 102
slice_from("ence");
break;
case 3:
// (, line 103
// <-, line 103
slice_from("ance");
break;
case 4:
// (, line 104
// <-, line 104
slice_from("able");
break;
case 5:
// (, line 105
// <-, line 105
slice_from("ent");
break;
case 6:
// (, line 107
// <-, line 107
slice_from("ize");
break;
case 7:
// (, line 109
// <-, line 109
slice_from("ate");
break;
case 8:
// (, line 111
// <-, line 111
slice_from("al");
break;
case 9:
// (, line 112
// <-, line 112
slice_from("ful");
break;
case 10:
// (, line 114
// <-, line 114
slice_from("ous");
break;
case 11:
// (, line 116
// <-, line 116
slice_from("ive");
break;
case 12:
// (, line 118
// <-, line 118
slice_from("ble");
break;
case 13:
// (, line 119
// literal, line 119
if (!(eq_s_b(1, "l")))
{
return false;
}
// <-, line 119
slice_from("og");
break;
case 14:
// (, line 120
// <-, line 120
slice_from("ful");
break;
case 15:
// (, line 121
// <-, line 121
slice_from("less");
break;
case 16:
// (, line 122
if (!(in_grouping_b(g_valid_LI, 99, 116)))
{
return false;
}
// delete, line 122
slice_del();
break;
}
return true;
}
private boolean r_Step_3() {
int among_var;
// (, line 126
// [, line 127
ket = cursor;
// substring, line 127
among_var = find_among_b(a_6, 9);
if (among_var == 0)
{
return false;
}
// ], line 127
bra = cursor;
// call R1, line 127
if (!r_R1())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 128
// <-, line 128
slice_from("tion");
break;
case 2:
// (, line 129
// <-, line 129
slice_from("ate");
break;
case 3:
// (, line 130
// <-, line 130
slice_from("al");
break;
case 4:
// (, line 132
// <-, line 132
slice_from("ic");
break;
case 5:
// (, line 134
// delete, line 134
slice_del();
break;
case 6:
// (, line 136
// call R2, line 136
if (!r_R2())
{
return false;
}
// delete, line 136
slice_del();
break;
}
return true;
}
private boolean r_Step_4() {
int among_var;
int v_1;
// (, line 140
// [, line 141
ket = cursor;
// substring, line 141
among_var = find_among_b(a_7, 18);
if (among_var == 0)
{
return false;
}
// ], line 141
bra = cursor;
// call R2, line 141
if (!r_R2())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 144
// delete, line 144
slice_del();
break;
case 2:
// (, line 145
// or, line 145
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 145
if (!(eq_s_b(1, "s")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 145
if (!(eq_s_b(1, "t")))
{
return false;
}
} while (false);
// delete, line 145
slice_del();
break;
}
return true;
}
private boolean r_Step_5() {
int among_var;
int v_1;
int v_2;
// (, line 149
// [, line 150
ket = cursor;
// substring, line 150
among_var = find_among_b(a_8, 2);
if (among_var == 0)
{
return false;
}
// ], line 150
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 151
// or, line 151
lab0: do {
v_1 = limit - cursor;
lab1: do {
// call R2, line 151
if (!r_R2())
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 151
// call R1, line 151
if (!r_R1())
{
return false;
}
// not, line 151
{
v_2 = limit - cursor;
lab2: do {
// call shortv, line 151
if (!r_shortv())
{
break lab2;
}
return false;
} while (false);
cursor = limit - v_2;
}
} while (false);
// delete, line 151
slice_del();
break;
case 2:
// (, line 152
// call R2, line 152
if (!r_R2())
{
return false;
}
// literal, line 152
if (!(eq_s_b(1, "l")))
{
return false;
}
// delete, line 152
slice_del();
break;
}
return true;
}
private boolean r_exception2() {
// (, line 156
// [, line 158
ket = cursor;
// substring, line 158
if (find_among_b(a_9, 8) == 0)
{
return false;
}
// ], line 158
bra = cursor;
// atlimit, line 158
if (cursor > limit_backward)
{
return false;
}
return true;
}
private boolean r_exception1() {
int among_var;
// (, line 168
// [, line 170
bra = cursor;
// substring, line 170
among_var = find_among(a_10, 18);
if (among_var == 0)
{
return false;
}
// ], line 170
ket = cursor;
// atlimit, line 170
if (cursor < limit)
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 174
// <-, line 174
slice_from("ski");
break;
case 2:
// (, line 175
// <-, line 175
slice_from("sky");
break;
case 3:
// (, line 176
// <-, line 176
slice_from("die");
break;
case 4:
// (, line 177
// <-, line 177
slice_from("lie");
break;
case 5:
// (, line 178
// <-, line 178
slice_from("tie");
break;
case 6:
// (, line 182
// <-, line 182
slice_from("idl");
break;
case 7:
// (, line 183
// <-, line 183
slice_from("gentl");
break;
case 8:
// (, line 184
// <-, line 184
slice_from("ugli");
break;
case 9:
// (, line 185
// <-, line 185
slice_from("earli");
break;
case 10:
// (, line 186
// <-, line 186
slice_from("onli");
break;
case 11:
// (, line 187
// <-, line 187
slice_from("singl");
break;
}
return true;
}
private boolean r_postlude() {
int v_1;
int v_2;
// (, line 203
// Boolean test Y_found, line 203
if (!(B_Y_found))
{
return false;
}
// repeat, line 203
replab0: while(true)
{
v_1 = cursor;
lab1: do {
// (, line 203
// goto, line 203
golab2: while(true)
{
v_2 = cursor;
lab3: do {
// (, line 203
// [, line 203
bra = cursor;
// literal, line 203
if (!(eq_s(1, "Y")))
{
break lab3;
}
// ], line 203
ket = cursor;
cursor = v_2;
break golab2;
} while (false);
cursor = v_2;
if (cursor >= limit)
{
break lab1;
}
cursor++;
}
// <-, line 203
slice_from("y");
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
}
public boolean stem() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
int v_8;
int v_9;
int v_10;
int v_11;
int v_12;
int v_13;
// (, line 205
// or, line 207
lab0: do {
v_1 = cursor;
lab1: do {
// call exception1, line 207
if (!r_exception1())
{
break lab1;
}
break lab0;
} while (false);
cursor = v_1;
lab2: do {
// not, line 208
{
v_2 = cursor;
lab3: do {
// hop, line 208
{
int c = cursor + 3;
if (0 > c || c > limit)
{
break lab3;
}
cursor = c;
}
break lab2;
} while (false);
cursor = v_2;
}
break lab0;
} while (false);
cursor = v_1;
// (, line 208
// do, line 209
v_3 = cursor;
lab4: do {
// call prelude, line 209
if (!r_prelude())
{
break lab4;
}
} while (false);
cursor = v_3;
// do, line 210
v_4 = cursor;
lab5: do {
// call mark_regions, line 210
if (!r_mark_regions())
{
break lab5;
}
} while (false);
cursor = v_4;
// backwards, line 211
limit_backward = cursor; cursor = limit;
// (, line 211
// do, line 213
v_5 = limit - cursor;
lab6: do {
// call Step_1a, line 213
if (!r_Step_1a())
{
break lab6;
}
} while (false);
cursor = limit - v_5;
// or, line 215
lab7: do {
v_6 = limit - cursor;
lab8: do {
// call exception2, line 215
if (!r_exception2())
{
break lab8;
}
break lab7;
} while (false);
cursor = limit - v_6;
// (, line 215
// do, line 217
v_7 = limit - cursor;
lab9: do {
// call Step_1b, line 217
if (!r_Step_1b())
{
break lab9;
}
} while (false);
cursor = limit - v_7;
// do, line 218
v_8 = limit - cursor;
lab10: do {
// call Step_1c, line 218
if (!r_Step_1c())
{
break lab10;
}
} while (false);
cursor = limit - v_8;
// do, line 220
v_9 = limit - cursor;
lab11: do {
// call Step_2, line 220
if (!r_Step_2())
{
break lab11;
}
} while (false);
cursor = limit - v_9;
// do, line 221
v_10 = limit - cursor;
lab12: do {
// call Step_3, line 221
if (!r_Step_3())
{
break lab12;
}
} while (false);
cursor = limit - v_10;
// do, line 222
v_11 = limit - cursor;
lab13: do {
// call Step_4, line 222
if (!r_Step_4())
{
break lab13;
}
} while (false);
cursor = limit - v_11;
// do, line 224
v_12 = limit - cursor;
lab14: do {
// call Step_5, line 224
if (!r_Step_5())
{
break lab14;
}
} while (false);
cursor = limit - v_12;
} while (false);
cursor = limit_backward; // do, line 227
v_13 = cursor;
lab15: do {
// call postlude, line 227
if (!r_postlude())
{
break lab15;
}
} while (false);
cursor = v_13;
} while (false);
return true;
}
public boolean equals( Object o ) {
return o instanceof EnglishStemmer;
}
public int hashCode() {
return EnglishStemmer.class.getName().hashCode();
}
}
| 56,259
| 40.398087
| 87
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/RussianStemmer.java
|
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This file was generated automatically by the Snowball to Java compiler
package opennlp.tools.stemmer.snowball;
/**
* This class was automatically generated by a Snowball to Java compiler
* It implements the stemming algorithm defined by a snowball script.
*/
class RussianStemmer extends AbstractSnowballStemmer {
private static final long serialVersionUID = 1L;
private final static RussianStemmer methodObject = new RussianStemmer ();
private final static Among a_0[] = {
new Among ( "\u0432", -1, 1, "", methodObject ),
new Among ( "\u0438\u0432", 0, 2, "", methodObject ),
new Among ( "\u044B\u0432", 0, 2, "", methodObject ),
new Among ( "\u0432\u0448\u0438", -1, 1, "", methodObject ),
new Among ( "\u0438\u0432\u0448\u0438", 3, 2, "", methodObject ),
new Among ( "\u044B\u0432\u0448\u0438", 3, 2, "", methodObject ),
new Among ( "\u0432\u0448\u0438\u0441\u044C", -1, 1, "", methodObject ),
new Among ( "\u0438\u0432\u0448\u0438\u0441\u044C", 6, 2, "", methodObject ),
new Among ( "\u044B\u0432\u0448\u0438\u0441\u044C", 6, 2, "", methodObject )
};
private final static Among a_1[] = {
new Among ( "\u0435\u0435", -1, 1, "", methodObject ),
new Among ( "\u0438\u0435", -1, 1, "", methodObject ),
new Among ( "\u043E\u0435", -1, 1, "", methodObject ),
new Among ( "\u044B\u0435", -1, 1, "", methodObject ),
new Among ( "\u0438\u043C\u0438", -1, 1, "", methodObject ),
new Among ( "\u044B\u043C\u0438", -1, 1, "", methodObject ),
new Among ( "\u0435\u0439", -1, 1, "", methodObject ),
new Among ( "\u0438\u0439", -1, 1, "", methodObject ),
new Among ( "\u043E\u0439", -1, 1, "", methodObject ),
new Among ( "\u044B\u0439", -1, 1, "", methodObject ),
new Among ( "\u0435\u043C", -1, 1, "", methodObject ),
new Among ( "\u0438\u043C", -1, 1, "", methodObject ),
new Among ( "\u043E\u043C", -1, 1, "", methodObject ),
new Among ( "\u044B\u043C", -1, 1, "", methodObject ),
new Among ( "\u0435\u0433\u043E", -1, 1, "", methodObject ),
new Among ( "\u043E\u0433\u043E", -1, 1, "", methodObject ),
new Among ( "\u0435\u043C\u0443", -1, 1, "", methodObject ),
new Among ( "\u043E\u043C\u0443", -1, 1, "", methodObject ),
new Among ( "\u0438\u0445", -1, 1, "", methodObject ),
new Among ( "\u044B\u0445", -1, 1, "", methodObject ),
new Among ( "\u0435\u044E", -1, 1, "", methodObject ),
new Among ( "\u043E\u044E", -1, 1, "", methodObject ),
new Among ( "\u0443\u044E", -1, 1, "", methodObject ),
new Among ( "\u044E\u044E", -1, 1, "", methodObject ),
new Among ( "\u0430\u044F", -1, 1, "", methodObject ),
new Among ( "\u044F\u044F", -1, 1, "", methodObject )
};
private final static Among a_2[] = {
new Among ( "\u0435\u043C", -1, 1, "", methodObject ),
new Among ( "\u043D\u043D", -1, 1, "", methodObject ),
new Among ( "\u0432\u0448", -1, 1, "", methodObject ),
new Among ( "\u0438\u0432\u0448", 2, 2, "", methodObject ),
new Among ( "\u044B\u0432\u0448", 2, 2, "", methodObject ),
new Among ( "\u0449", -1, 1, "", methodObject ),
new Among ( "\u044E\u0449", 5, 1, "", methodObject ),
new Among ( "\u0443\u044E\u0449", 6, 2, "", methodObject )
};
private final static Among a_3[] = {
new Among ( "\u0441\u044C", -1, 1, "", methodObject ),
new Among ( "\u0441\u044F", -1, 1, "", methodObject )
};
private final static Among a_4[] = {
new Among ( "\u043B\u0430", -1, 1, "", methodObject ),
new Among ( "\u0438\u043B\u0430", 0, 2, "", methodObject ),
new Among ( "\u044B\u043B\u0430", 0, 2, "", methodObject ),
new Among ( "\u043D\u0430", -1, 1, "", methodObject ),
new Among ( "\u0435\u043D\u0430", 3, 2, "", methodObject ),
new Among ( "\u0435\u0442\u0435", -1, 1, "", methodObject ),
new Among ( "\u0438\u0442\u0435", -1, 2, "", methodObject ),
new Among ( "\u0439\u0442\u0435", -1, 1, "", methodObject ),
new Among ( "\u0435\u0439\u0442\u0435", 7, 2, "", methodObject ),
new Among ( "\u0443\u0439\u0442\u0435", 7, 2, "", methodObject ),
new Among ( "\u043B\u0438", -1, 1, "", methodObject ),
new Among ( "\u0438\u043B\u0438", 10, 2, "", methodObject ),
new Among ( "\u044B\u043B\u0438", 10, 2, "", methodObject ),
new Among ( "\u0439", -1, 1, "", methodObject ),
new Among ( "\u0435\u0439", 13, 2, "", methodObject ),
new Among ( "\u0443\u0439", 13, 2, "", methodObject ),
new Among ( "\u043B", -1, 1, "", methodObject ),
new Among ( "\u0438\u043B", 16, 2, "", methodObject ),
new Among ( "\u044B\u043B", 16, 2, "", methodObject ),
new Among ( "\u0435\u043C", -1, 1, "", methodObject ),
new Among ( "\u0438\u043C", -1, 2, "", methodObject ),
new Among ( "\u044B\u043C", -1, 2, "", methodObject ),
new Among ( "\u043D", -1, 1, "", methodObject ),
new Among ( "\u0435\u043D", 22, 2, "", methodObject ),
new Among ( "\u043B\u043E", -1, 1, "", methodObject ),
new Among ( "\u0438\u043B\u043E", 24, 2, "", methodObject ),
new Among ( "\u044B\u043B\u043E", 24, 2, "", methodObject ),
new Among ( "\u043D\u043E", -1, 1, "", methodObject ),
new Among ( "\u0435\u043D\u043E", 27, 2, "", methodObject ),
new Among ( "\u043D\u043D\u043E", 27, 1, "", methodObject ),
new Among ( "\u0435\u0442", -1, 1, "", methodObject ),
new Among ( "\u0443\u0435\u0442", 30, 2, "", methodObject ),
new Among ( "\u0438\u0442", -1, 2, "", methodObject ),
new Among ( "\u044B\u0442", -1, 2, "", methodObject ),
new Among ( "\u044E\u0442", -1, 1, "", methodObject ),
new Among ( "\u0443\u044E\u0442", 34, 2, "", methodObject ),
new Among ( "\u044F\u0442", -1, 2, "", methodObject ),
new Among ( "\u043D\u044B", -1, 1, "", methodObject ),
new Among ( "\u0435\u043D\u044B", 37, 2, "", methodObject ),
new Among ( "\u0442\u044C", -1, 1, "", methodObject ),
new Among ( "\u0438\u0442\u044C", 39, 2, "", methodObject ),
new Among ( "\u044B\u0442\u044C", 39, 2, "", methodObject ),
new Among ( "\u0435\u0448\u044C", -1, 1, "", methodObject ),
new Among ( "\u0438\u0448\u044C", -1, 2, "", methodObject ),
new Among ( "\u044E", -1, 2, "", methodObject ),
new Among ( "\u0443\u044E", 44, 2, "", methodObject )
};
private final static Among a_5[] = {
new Among ( "\u0430", -1, 1, "", methodObject ),
new Among ( "\u0435\u0432", -1, 1, "", methodObject ),
new Among ( "\u043E\u0432", -1, 1, "", methodObject ),
new Among ( "\u0435", -1, 1, "", methodObject ),
new Among ( "\u0438\u0435", 3, 1, "", methodObject ),
new Among ( "\u044C\u0435", 3, 1, "", methodObject ),
new Among ( "\u0438", -1, 1, "", methodObject ),
new Among ( "\u0435\u0438", 6, 1, "", methodObject ),
new Among ( "\u0438\u0438", 6, 1, "", methodObject ),
new Among ( "\u0430\u043C\u0438", 6, 1, "", methodObject ),
new Among ( "\u044F\u043C\u0438", 6, 1, "", methodObject ),
new Among ( "\u0438\u044F\u043C\u0438", 10, 1, "", methodObject ),
new Among ( "\u0439", -1, 1, "", methodObject ),
new Among ( "\u0435\u0439", 12, 1, "", methodObject ),
new Among ( "\u0438\u0435\u0439", 13, 1, "", methodObject ),
new Among ( "\u0438\u0439", 12, 1, "", methodObject ),
new Among ( "\u043E\u0439", 12, 1, "", methodObject ),
new Among ( "\u0430\u043C", -1, 1, "", methodObject ),
new Among ( "\u0435\u043C", -1, 1, "", methodObject ),
new Among ( "\u0438\u0435\u043C", 18, 1, "", methodObject ),
new Among ( "\u043E\u043C", -1, 1, "", methodObject ),
new Among ( "\u044F\u043C", -1, 1, "", methodObject ),
new Among ( "\u0438\u044F\u043C", 21, 1, "", methodObject ),
new Among ( "\u043E", -1, 1, "", methodObject ),
new Among ( "\u0443", -1, 1, "", methodObject ),
new Among ( "\u0430\u0445", -1, 1, "", methodObject ),
new Among ( "\u044F\u0445", -1, 1, "", methodObject ),
new Among ( "\u0438\u044F\u0445", 26, 1, "", methodObject ),
new Among ( "\u044B", -1, 1, "", methodObject ),
new Among ( "\u044C", -1, 1, "", methodObject ),
new Among ( "\u044E", -1, 1, "", methodObject ),
new Among ( "\u0438\u044E", 30, 1, "", methodObject ),
new Among ( "\u044C\u044E", 30, 1, "", methodObject ),
new Among ( "\u044F", -1, 1, "", methodObject ),
new Among ( "\u0438\u044F", 33, 1, "", methodObject ),
new Among ( "\u044C\u044F", 33, 1, "", methodObject )
};
private final static Among a_6[] = {
new Among ( "\u043E\u0441\u0442", -1, 1, "", methodObject ),
new Among ( "\u043E\u0441\u0442\u044C", -1, 1, "", methodObject )
};
private final static Among a_7[] = {
new Among ( "\u0435\u0439\u0448\u0435", -1, 1, "", methodObject ),
new Among ( "\u043D", -1, 2, "", methodObject ),
new Among ( "\u0435\u0439\u0448", -1, 1, "", methodObject ),
new Among ( "\u044C", -1, 3, "", methodObject )
};
private static final char g_v[] = {33, 65, 8, 232 };
private int I_p2;
private int I_pV;
private void copy_from(RussianStemmer other) {
I_p2 = other.I_p2;
I_pV = other.I_pV;
super.copy_from(other);
}
private boolean r_mark_regions() {
int v_1;
// (, line 57
I_pV = limit;
I_p2 = limit;
// do, line 61
v_1 = cursor;
lab0: do {
// (, line 61
// gopast, line 62
golab1: while(true)
{
lab2: do {
if (!(in_grouping(g_v, 1072, 1103)))
{
break lab2;
}
break golab1;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// setmark pV, line 62
I_pV = cursor;
// gopast, line 62
golab3: while(true)
{
lab4: do {
if (!(out_grouping(g_v, 1072, 1103)))
{
break lab4;
}
break golab3;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// gopast, line 63
golab5: while(true)
{
lab6: do {
if (!(in_grouping(g_v, 1072, 1103)))
{
break lab6;
}
break golab5;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// gopast, line 63
golab7: while(true)
{
lab8: do {
if (!(out_grouping(g_v, 1072, 1103)))
{
break lab8;
}
break golab7;
} while (false);
if (cursor >= limit)
{
break lab0;
}
cursor++;
}
// setmark p2, line 63
I_p2 = cursor;
} while (false);
cursor = v_1;
return true;
}
private boolean r_R2() {
if (!(I_p2 <= cursor))
{
return false;
}
return true;
}
private boolean r_perfective_gerund() {
int among_var;
int v_1;
// (, line 71
// [, line 72
ket = cursor;
// substring, line 72
among_var = find_among_b(a_0, 9);
if (among_var == 0)
{
return false;
}
// ], line 72
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 76
// or, line 76
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 76
if (!(eq_s_b(1, "\u0430")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 76
if (!(eq_s_b(1, "\u044F")))
{
return false;
}
} while (false);
// delete, line 76
slice_del();
break;
case 2:
// (, line 83
// delete, line 83
slice_del();
break;
}
return true;
}
private boolean r_adjective() {
int among_var;
// (, line 87
// [, line 88
ket = cursor;
// substring, line 88
among_var = find_among_b(a_1, 26);
if (among_var == 0)
{
return false;
}
// ], line 88
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 97
// delete, line 97
slice_del();
break;
}
return true;
}
private boolean r_adjectival() {
int among_var;
int v_1;
int v_2;
// (, line 101
// call adjective, line 102
if (!r_adjective())
{
return false;
}
// try, line 109
v_1 = limit - cursor;
lab0: do {
// (, line 109
// [, line 110
ket = cursor;
// substring, line 110
among_var = find_among_b(a_2, 8);
if (among_var == 0)
{
cursor = limit - v_1;
break lab0;
}
// ], line 110
bra = cursor;
switch(among_var) {
case 0:
cursor = limit - v_1;
break lab0;
case 1:
// (, line 115
// or, line 115
lab1: do {
v_2 = limit - cursor;
lab2: do {
// literal, line 115
if (!(eq_s_b(1, "\u0430")))
{
break lab2;
}
break lab1;
} while (false);
cursor = limit - v_2;
// literal, line 115
if (!(eq_s_b(1, "\u044F")))
{
cursor = limit - v_1;
break lab0;
}
} while (false);
// delete, line 115
slice_del();
break;
case 2:
// (, line 122
// delete, line 122
slice_del();
break;
}
} while (false);
return true;
}
private boolean r_reflexive() {
int among_var;
// (, line 128
// [, line 129
ket = cursor;
// substring, line 129
among_var = find_among_b(a_3, 2);
if (among_var == 0)
{
return false;
}
// ], line 129
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 132
// delete, line 132
slice_del();
break;
}
return true;
}
private boolean r_verb() {
int among_var;
int v_1;
// (, line 136
// [, line 137
ket = cursor;
// substring, line 137
among_var = find_among_b(a_4, 46);
if (among_var == 0)
{
return false;
}
// ], line 137
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 143
// or, line 143
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 143
if (!(eq_s_b(1, "\u0430")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 143
if (!(eq_s_b(1, "\u044F")))
{
return false;
}
} while (false);
// delete, line 143
slice_del();
break;
case 2:
// (, line 151
// delete, line 151
slice_del();
break;
}
return true;
}
private boolean r_noun() {
int among_var;
// (, line 159
// [, line 160
ket = cursor;
// substring, line 160
among_var = find_among_b(a_5, 36);
if (among_var == 0)
{
return false;
}
// ], line 160
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 167
// delete, line 167
slice_del();
break;
}
return true;
}
private boolean r_derivational() {
int among_var;
// (, line 175
// [, line 176
ket = cursor;
// substring, line 176
among_var = find_among_b(a_6, 2);
if (among_var == 0)
{
return false;
}
// ], line 176
bra = cursor;
// call R2, line 176
if (!r_R2())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 179
// delete, line 179
slice_del();
break;
}
return true;
}
private boolean r_tidy_up() {
int among_var;
// (, line 183
// [, line 184
ket = cursor;
// substring, line 184
among_var = find_among_b(a_7, 4);
if (among_var == 0)
{
return false;
}
// ], line 184
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 188
// delete, line 188
slice_del();
// [, line 189
ket = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// ], line 189
bra = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 189
slice_del();
break;
case 2:
// (, line 192
// literal, line 192
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 192
slice_del();
break;
case 3:
// (, line 194
// delete, line 194
slice_del();
break;
}
return true;
}
public boolean stem() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
int v_8;
int v_9;
int v_10;
// (, line 199
// do, line 201
v_1 = cursor;
lab0: do {
// call mark_regions, line 201
if (!r_mark_regions())
{
break lab0;
}
} while (false);
cursor = v_1;
// backwards, line 202
limit_backward = cursor; cursor = limit;
// setlimit, line 202
v_2 = limit - cursor;
// tomark, line 202
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_3 = limit_backward;
limit_backward = cursor;
cursor = limit - v_2;
// (, line 202
// do, line 203
v_4 = limit - cursor;
lab1: do {
// (, line 203
// or, line 204
lab2: do {
v_5 = limit - cursor;
lab3: do {
// call perfective_gerund, line 204
if (!r_perfective_gerund())
{
break lab3;
}
break lab2;
} while (false);
cursor = limit - v_5;
// (, line 205
// try, line 205
v_6 = limit - cursor;
lab4: do {
// call reflexive, line 205
if (!r_reflexive())
{
cursor = limit - v_6;
break lab4;
}
} while (false);
// or, line 206
lab5: do {
v_7 = limit - cursor;
lab6: do {
// call adjectival, line 206
if (!r_adjectival())
{
break lab6;
}
break lab5;
} while (false);
cursor = limit - v_7;
lab7: do {
// call verb, line 206
if (!r_verb())
{
break lab7;
}
break lab5;
} while (false);
cursor = limit - v_7;
// call noun, line 206
if (!r_noun())
{
break lab1;
}
} while (false);
} while (false);
} while (false);
cursor = limit - v_4;
// try, line 209
v_8 = limit - cursor;
lab8: do {
// (, line 209
// [, line 209
ket = cursor;
// literal, line 209
if (!(eq_s_b(1, "\u0438")))
{
cursor = limit - v_8;
break lab8;
}
// ], line 209
bra = cursor;
// delete, line 209
slice_del();
} while (false);
// do, line 212
v_9 = limit - cursor;
lab9: do {
// call derivational, line 212
if (!r_derivational())
{
break lab9;
}
} while (false);
cursor = limit - v_9;
// do, line 213
v_10 = limit - cursor;
lab10: do {
// call tidy_up, line 213
if (!r_tidy_up())
{
break lab10;
}
} while (false);
cursor = limit - v_10;
limit_backward = v_3;
cursor = limit_backward; return true;
}
public boolean equals( Object o ) {
return o instanceof RussianStemmer;
}
public int hashCode() {
return RussianStemmer.class.getName().hashCode();
}
}
| 34,323
| 43.46114
| 97
|
java
|
heldroid
|
heldroid-master/src/java/opennlp/tools/stemmer/snowball/SnowballProgram.java
|
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package opennlp.tools.stemmer.snowball;
import java.lang.reflect.InvocationTargetException;
class SnowballProgram {
protected SnowballProgram()
{
current = new StringBuffer();
setCurrent("");
}
/**
* Set the current string.
*/
public void setCurrent(String value)
{
current.replace(0, current.length(), value);
cursor = 0;
limit = current.length();
limit_backward = 0;
bra = cursor;
ket = limit;
}
/**
* Get the current string.
*/
public String getCurrent()
{
String result = current.toString();
// Make a new StringBuffer. If we reuse the old one, and a user of
// the library keeps a reference to the buffer returned (for example,
// by converting it to a String in a way which doesn't force a copy),
// the buffer size will not decrease, and we will risk wasting a large
// amount of memory.
// Thanks to Wolfram Esser for spotting this problem.
current = new StringBuffer();
return result;
}
// current string
protected StringBuffer current;
protected int cursor;
protected int limit;
protected int limit_backward;
protected int bra;
protected int ket;
protected void copy_from(SnowballProgram other)
{
current = other.current;
cursor = other.cursor;
limit = other.limit;
limit_backward = other.limit_backward;
bra = other.bra;
ket = other.ket;
}
protected boolean in_grouping(char [] s, int min, int max)
{
if (cursor >= limit) return false;
char ch = current.charAt(cursor);
if (ch > max || ch < min) return false;
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false;
cursor++;
return true;
}
protected boolean in_grouping_b(char [] s, int min, int max)
{
if (cursor <= limit_backward) return false;
char ch = current.charAt(cursor - 1);
if (ch > max || ch < min) return false;
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false;
cursor--;
return true;
}
protected boolean out_grouping(char [] s, int min, int max)
{
if (cursor >= limit) return false;
char ch = current.charAt(cursor);
if (ch > max || ch < min) {
cursor++;
return true;
}
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) {
cursor ++;
return true;
}
return false;
}
protected boolean out_grouping_b(char [] s, int min, int max)
{
if (cursor <= limit_backward) return false;
char ch = current.charAt(cursor - 1);
if (ch > max || ch < min) {
cursor--;
return true;
}
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) {
cursor--;
return true;
}
return false;
}
protected boolean in_range(int min, int max)
{
if (cursor >= limit) return false;
char ch = current.charAt(cursor);
if (ch > max || ch < min) return false;
cursor++;
return true;
}
protected boolean in_range_b(int min, int max)
{
if (cursor <= limit_backward) return false;
char ch = current.charAt(cursor - 1);
if (ch > max || ch < min) return false;
cursor--;
return true;
}
protected boolean out_range(int min, int max)
{
if (cursor >= limit) return false;
char ch = current.charAt(cursor);
if (!(ch > max || ch < min)) return false;
cursor++;
return true;
}
protected boolean out_range_b(int min, int max)
{
if (cursor <= limit_backward) return false;
char ch = current.charAt(cursor - 1);
if(!(ch > max || ch < min)) return false;
cursor--;
return true;
}
protected boolean eq_s(int s_size, String s)
{
if (limit - cursor < s_size) return false;
int i;
for (i = 0; i != s_size; i++) {
if (current.charAt(cursor + i) != s.charAt(i)) return false;
}
cursor += s_size;
return true;
}
protected boolean eq_s_b(int s_size, String s)
{
if (cursor - limit_backward < s_size) return false;
int i;
for (i = 0; i != s_size; i++) {
if (current.charAt(cursor - s_size + i) != s.charAt(i)) return false;
}
cursor -= s_size;
return true;
}
protected boolean eq_v(CharSequence s)
{
return eq_s(s.length(), s.toString());
}
protected boolean eq_v_b(CharSequence s)
{ return eq_s_b(s.length(), s.toString());
}
protected int find_among(Among v[], int v_size)
{
int i = 0;
int j = v_size;
int c = cursor;
int l = limit;
int common_i = 0;
int common_j = 0;
boolean first_key_inspected = false;
while(true) {
int k = i + ((j - i) >> 1);
int diff = 0;
int common = common_i < common_j ? common_i : common_j; // smaller
Among w = v[k];
int i2;
for (i2 = common; i2 < w.s_size; i2++) {
if (c + common == l) {
diff = -1;
break;
}
diff = current.charAt(c + common) - w.s[i2];
if (diff != 0) break;
common++;
}
if (diff < 0) {
j = k;
common_j = common;
} else {
i = k;
common_i = common;
}
if (j - i <= 1) {
if (i > 0) break; // v->s has been inspected
if (j == i) break; // only one item in v
// - but now we need to go round once more to get
// v->s inspected. This looks messy, but is actually
// the optimal approach.
if (first_key_inspected) break;
first_key_inspected = true;
}
}
while(true) {
Among w = v[i];
if (common_i >= w.s_size) {
cursor = c + w.s_size;
if (w.method == null) return w.result;
boolean res;
try {
Object resobj = w.method.invoke(w.methodobject,
new Object[0]);
res = resobj.toString().equals("true");
} catch (InvocationTargetException e) {
res = false;
// FIXME - debug message
} catch (IllegalAccessException e) {
res = false;
// FIXME - debug message
}
cursor = c + w.s_size;
if (res) return w.result;
}
i = w.substring_i;
if (i < 0) return 0;
}
}
// find_among_b is for backwards processing. Same comments apply
protected int find_among_b(Among v[], int v_size)
{
int i = 0;
int j = v_size;
int c = cursor;
int lb = limit_backward;
int common_i = 0;
int common_j = 0;
boolean first_key_inspected = false;
while(true) {
int k = i + ((j - i) >> 1);
int diff = 0;
int common = common_i < common_j ? common_i : common_j;
Among w = v[k];
int i2;
for (i2 = w.s_size - 1 - common; i2 >= 0; i2--) {
if (c - common == lb) {
diff = -1;
break;
}
diff = current.charAt(c - 1 - common) - w.s[i2];
if (diff != 0) break;
common++;
}
if (diff < 0) {
j = k;
common_j = common;
} else {
i = k;
common_i = common;
}
if (j - i <= 1) {
if (i > 0) break;
if (j == i) break;
if (first_key_inspected) break;
first_key_inspected = true;
}
}
while(true) {
Among w = v[i];
if (common_i >= w.s_size) {
cursor = c - w.s_size;
if (w.method == null) return w.result;
boolean res;
try {
Object resobj = w.method.invoke(w.methodobject,
new Object[0]);
res = resobj.toString().equals("true");
} catch (InvocationTargetException e) {
res = false;
// FIXME - debug message
} catch (IllegalAccessException e) {
res = false;
// FIXME - debug message
}
cursor = c - w.s_size;
if (res) return w.result;
}
i = w.substring_i;
if (i < 0) return 0;
}
}
/* to replace chars between c_bra and c_ket in current by the
* chars in s.
*/
protected int replace_s(int c_bra, int c_ket, String s)
{
int adjustment = s.length() - (c_ket - c_bra);
current.replace(c_bra, c_ket, s);
limit += adjustment;
if (cursor >= c_ket) cursor += adjustment;
else if (cursor > c_bra) cursor = c_bra;
return adjustment;
}
protected void slice_check()
{
if (bra < 0 ||
bra > ket ||
ket > limit ||
limit > current.length()) // this line could be removed
{
System.err.println("faulty slice operation");
// FIXME: report error somehow.
/*
fprintf(stderr, "faulty slice operation:\n");
debug(z, -1, 0);
exit(1);
*/
}
}
protected void slice_from(String s)
{
slice_check();
replace_s(bra, ket, s);
}
protected void slice_from(CharSequence s)
{
slice_from(s.toString());
}
protected void slice_del()
{
slice_from("");
}
protected void insert(int c_bra, int c_ket, String s)
{
int adjustment = replace_s(c_bra, c_ket, s);
if (c_bra <= bra) bra += adjustment;
if (c_bra <= ket) ket += adjustment;
}
protected void insert(int c_bra, int c_ket, CharSequence s)
{
insert(c_bra, c_ket, s.toString());
}
/* Copy the slice into the supplied StringBuffer */
protected StringBuffer slice_to(StringBuffer s)
{
slice_check();
int len = ket - bra;
s.replace(0, s.length(), current.substring(bra, ket));
return s;
}
/* Copy the slice into the supplied StringBuilder */
protected StringBuilder slice_to(StringBuilder s)
{
slice_check();
int len = ket - bra;
s.replace(0, s.length(), current.substring(bra, ket));
return s;
}
protected StringBuffer assign_to(StringBuffer s)
{
s.replace(0, s.length(), current.substring(0, limit));
return s;
}
protected StringBuilder assign_to(StringBuilder s)
{
s.replace(0, s.length(), current.substring(0, limit));
return s;
}
/*
extern void debug(struct SN_env * z, int number, int line_count)
{ int i;
int limit = SIZE(z->p);
//if (number >= 0) printf("%3d (line %4d): '", number, line_count);
if (number >= 0) printf("%3d (line %4d): [%d]'", number, line_count,limit);
for (i = 0; i <= limit; i++)
{ if (z->lb == i) printf("{");
if (z->bra == i) printf("[");
if (z->c == i) printf("|");
if (z->ket == i) printf("]");
if (z->l == i) printf("}");
if (i < limit)
{ int ch = z->p[i];
if (ch == 0) ch = '#';
printf("%c", ch);
}
}
printf("'\n");
}
*/
}
| 13,815
| 28.904762
| 81
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/Main.java
|
package it.polimi.elet.necst.heldroid;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
if (args.length < 1) {
printUsage();
return;
}
String[] newArgs = Arrays.copyOfRange(args, 1, args.length);
String mode = args[0];
try {
if (mode.equals("filter"))
it.polimi.elet.necst.heldroid.goodware.Main.main(newArgs);
else if (mode.equals("detector"))
it.polimi.elet.necst.heldroid.ransomware.Main.main(newArgs);
else
printUsage();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printUsage() {
System.out.println("bin/heldroid (filter|detector) [options]");
System.out.println("options depend on the command invoked");
}
}
| 888
| 26.78125
| 76
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/pipeline/ApplicationData.java
|
package it.polimi.elet.necst.heldroid.pipeline;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import it.polimi.elet.necst.heldroid.apk.DecodingException;
import it.polimi.elet.necst.heldroid.apk.PackageDecoder;
import it.polimi.elet.necst.heldroid.apk.PackageDecoders;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import it.polimi.elet.necst.heldroid.xml.manifest.ManifestAnalysisReport;
import it.polimi.elet.necst.heldroid.xml.manifest.ManifestAnalyzer;
import it.polimi.elet.necst.heldroid.xml.manifest.ManifestAnalyzers;
import it.polimi.elet.necst.heldroid.xml.resources.StringResource;
import it.polimi.elet.necst.heldroid.xml.resources.StringResourceMetaParser;
import it.polimi.elet.necst.heldroid.xml.resources.StringResourceParsers;
import java.io.File;
public class ApplicationData {
private static PackageDecoder decoder;
private static StringResourceMetaParser parser;
private static ManifestAnalyzer analyzer;
private DecodedPackage decodedPackage;
private ManifestAnalysisReport manifestReport;
private StringResource stringResource;
private FileTree decodedFileTree;
private SmaliLoader smaliLoader;
public DecodedPackage getDecodedPackage() {
return decodedPackage;
}
public ManifestAnalysisReport getManifestReport() {
return manifestReport;
}
public StringResource getStringResource() {
return stringResource;
}
public synchronized FileTree getDecodedFileTree() {
if (decodedFileTree != null)
return decodedFileTree;
return (decodedFileTree = new FileTree(decodedPackage.getDecodedDirectory()));
}
public synchronized SmaliLoader getSmaliLoader() {
if (smaliLoader != null)
return smaliLoader;
return (smaliLoader = SmaliLoader.onSources(this.getDecodedFileTree().getAllFilesIn(decodedPackage.getSmaliDirectory())));
}
private ApplicationData() { }
public static ApplicationData open(File file) throws ParsingException, DecodingException {
ApplicationData result = null;
if (isApkFile(file))
result = extract(file);
else if (isUnpackedApkDirectory(file)) {
result = read(file);
}
if (result != null)
{
try {
result.getSmaliLoader();
} catch (Exception ex) {
throw new DecodingException("Invalid smali files.");
}
return result;
}
throw new DecodingException(file.getAbsolutePath() + " is not a valid android package.");
}
private static boolean isUnpackedApkDirectory(File directory) {
File manifest = new File(directory, "AndroidManifest.xml");
return manifest.exists();
}
private static boolean isApkFile(File file) {
return file.getName().toLowerCase().endsWith(".apk");
}
private static ApplicationData extract(File apk) throws DecodingException, ParsingException {
DecodedPackage decodedPackage;
if (decoder == null)
decoder = PackageDecoders.apkTool();
decodedPackage = decoder.decode(apk);
return process(decodedPackage);
}
private static ApplicationData read(File unpackedApkDirectory) throws ParsingException {
final File mainDirectory = unpackedApkDirectory;
DecodedPackage decodedPackage = new DecodedPackage() {
@Override
public File getClassesDex() {
return new File(mainDirectory, "classes.dex");
}
@Override
public File getResourcesDirectory() {
throw new UnsupportedOperationException("This method is not implemented yet");
}
@Override
public File getAndroidManifest() {
return new File(mainDirectory, "AndroidManifest.xml");
}
@Override
public File getDecodedDirectory() {
return mainDirectory;
}
@Override
public File getSmaliDirectory() {
return new File(mainDirectory, "it/polimi/elet/necst/heldroid/smali");
}
@Override
public File getOriginalApk() {
return mainDirectory;
}
@Override
public void dispose() { /* Do nothing, since directory is not created by the application */ }
};
return process(decodedPackage);
}
private static ApplicationData process(DecodedPackage decodedPackage) throws ParsingException {
ApplicationData result = new ApplicationData();
result.decodedPackage = decodedPackage;
if (parser == null)
parser = new StringResourceMetaParser(StringResourceParsers.domBased());
result.stringResource = parser.parseDirectory(decodedPackage.getDecodedDirectory());
if (analyzer == null)
analyzer = ManifestAnalyzers.domBased(result.stringResource);
result.manifestReport = analyzer.analyze(decodedPackage.getAndroidManifest());
return result;
}
public void dispose() {
decodedPackage.dispose();
}
}
| 5,287
| 31.243902
| 130
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/pipeline/ThreadedCollectionExecutor.java
|
package it.polimi.elet.necst.heldroid.pipeline;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadedCollectionExecutor<T> {
public interface ParameterizedRunnable<T> {
void run(T parameter);
}
private ExecutorService executor;
private int maxThreadCount;
private int itemsPerThread;
private TimeUnit timeoutUnit;
private int timeout;
public void setTimeout(int delay, TimeUnit unit) {
if (delay < 0)
delay = 0;
this.timeout = delay;
this.timeoutUnit = unit;
}
public ThreadedCollectionExecutor(int maxThreadCount, int itemsPerThread) {
this.maxThreadCount = maxThreadCount;
this.itemsPerThread = itemsPerThread;
this.executor = Executors.newFixedThreadPool(maxThreadCount);
timeout = 5;
timeoutUnit = TimeUnit.SECONDS;
}
/**
* Executs the given task on each item of the given collection. Up to itemsPerThread tasks are executed in the same
* thread. If more than itemsPerThread items are present, each chunk is executed in a new thread, up to a maximum
* of maxThreadCount. The method returns when all items have been executed a task on.
* @param collection Generic collection of items.
* @param task Generic task, represented by a Runnable-like interface (accepting 1 parameter for run).
*/
public void execute(Collection<T> collection, final ParameterizedRunnable<T> task) {
List<T> tempList = new ArrayList<T>(itemsPerThread);
int i = 0;
for (T item : collection) {
if (i++ < itemsPerThread)
tempList.add(item);
else {
final List<T> listReference = tempList;
executor.execute(new Runnable() {
@Override
public void run() {
for (T itemReference : listReference) {
if (Thread.currentThread().isInterrupted())
return;
task.run(itemReference);
}
}
});
tempList = new ArrayList<T>(itemsPerThread);
tempList.add(item);
i = 1;
}
}
if (tempList.size() > 0) {
final List<T> listReference = tempList;
executor.execute(new Runnable() {
@Override
public void run() {
for (T itemReference : listReference) {
if (Thread.currentThread().isInterrupted())
return;
task.run(itemReference);
}
}
});
}
try {
executor.shutdown();
// enforces termination strictly before actual timeout
// usually aborting threads take around 0.001 seconds more than the timeout
long millis = (long)(timeoutUnit.toMillis(timeout) * 0.95);
if (executor.awaitTermination(millis, TimeUnit.MILLISECONDS) == false)
executor.shutdownNow(); // forces shutdown
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 3,443
| 32.115385
| 119
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/pipeline/FileTree.java
|
package it.polimi.elet.necst.heldroid.pipeline;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class FileTree {
private class DirectoryNode {
private File directory;
private String name;
private List<File> files;
private Collection<DirectoryNode> childNodes;
private int startIndexInAllFiles, endIndexInAllFiles;
public DirectoryNode(File directory) {
if (!directory.isDirectory())
throw new IllegalArgumentException("Expected a directory.");
Collection<File> subfolders = new ArrayList<File>();
this.directory = directory;
this.name = directory.getName();
this.files = new ArrayList<File>();
for (File file : directory.listFiles()) {
if (file.isFile())
this.files.add(file);
else
subfolders.add(file);
}
startIndexInAllFiles = FileTree.this.allFiles.size();
FileTree.this.allFiles.addAll(this.files);
this.childNodes = new ArrayList<DirectoryNode>(subfolders.size());
for (File folder : subfolders)
this.childNodes.add(new DirectoryNode(folder));
endIndexInAllFiles = FileTree.this.allFiles.size() - 1;
}
public File getDirectory() {
return directory;
}
public String getName() {
return name;
}
public Collection<File> getFiles() {
return files;
}
public Collection<File> getAllFiles() {
return FileTree.this.allFiles.subList(startIndexInAllFiles, endIndexInAllFiles);
}
public Collection<DirectoryNode> getChildNodes() {
return childNodes;
}
}
private DirectoryNode root;
private List<File> allFiles;
public FileTree(File rootDirectory) {
this.allFiles = new ArrayList<File>();
this.root = new DirectoryNode(rootDirectory);
}
public Collection<File> getAllFiles() {
return allFiles;
}
public Collection<File> getFilesIn(File directory) {
return this.selectNode(directory).getFiles();
}
public Collection<File> getAllFilesIn(File directory) {
return this.selectNode(directory).getAllFiles();
}
private DirectoryNode selectNode(File directory) {
String relativePath = directory.getAbsolutePath().substring(root.getDirectory().getAbsolutePath().length());
String[] chunks = relativePath.split(File.separator.replace("\\", "\\\\"));
DirectoryNode currentNode = root;
for (int i = 0; i < chunks.length; i++) {
if (chunks[i].isEmpty())
continue;
for (DirectoryNode subNode : currentNode.getChildNodes())
if (subNode.getName().equals(chunks[i])) {
currentNode = subNode;
break;
}
}
return currentNode;
}
}
| 3,086
| 28.682692
| 116
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/DecodingException.java
|
package it.polimi.elet.necst.heldroid.apk;
/**
* Created by Nicolo on 04/02/14.
*/
public class DecodingException extends Exception {
public DecodingException(Throwable cause) {
super(cause);
}
public DecodingException(String message) {
super(message);
}
}
| 293
| 18.6
| 50
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/ApkToolDecoder.java
|
package it.polimi.elet.necst.heldroid.apk;
import java.io.*;
class ApkToolDecoder implements PackageDecoder {
private static final File APK_TOOL_JAR = new File("apktool.jar");
private static final String APK_EXTENSION = ".apk";
private File outputDirectory;
public ApkToolDecoder(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
@Override
public DecodedPackage decode(File apkFile) throws DecodingException {
if (!apkFile.getName().toLowerCase().endsWith(APK_EXTENSION))
throw new DecodingException("Invalid file type.");
String apkName = apkFile.getName();
File workingDirectory = new File(outputDirectory, apkName);
try {
if (workingDirectory.exists())
return new ApkToolOutput(apkFile, workingDirectory);
/* Windows
Process p =
Runtime.getRuntime().exec(
String.format("java -jar %s decode -f -o \"%s\" \"%s\"",
APK_TOOL_JAR.getAbsolutePath(),
workingDirectory.getAbsolutePath(),
apkFile.getAbsolutePath())); */
Process p =
Runtime.getRuntime().exec(new String[] {
"java", "-jar", APK_TOOL_JAR.getAbsolutePath(),
"decode", "-o", workingDirectory.getAbsolutePath(),
apkFile.getAbsolutePath()
});
exhaustStreamAsync(p.getInputStream());
exhaustStreamAsync(p.getErrorStream());
p.waitFor();
DecodedPackage result = new ApkToolOutput(apkFile, workingDirectory);
if (result.getAndroidManifest().exists() && result.getSmaliDirectory().exists())
return result;
throw new DecodingException("No manifest or smali directory produced!");
} catch (Exception e) {
throw new DecodingException(e);
}
}
private static void exhaustStream(InputStream inputStream) {
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
try {
while (bufferedReader.readLine() != null)
;
inputStream.close();
} catch (IOException e) { }
}
private static void exhaustStreamAsync(final InputStream inputStream) {
new Thread(new Runnable() {
@Override
public void run() {
exhaustStream(inputStream);
}
}).start();
}
}
| 2,606
| 32
| 92
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/PackageDecoder.java
|
package it.polimi.elet.necst.heldroid.apk;
import java.io.File;
public interface PackageDecoder {
DecodedPackage decode(File apkFile) throws DecodingException;
}
| 168
| 20.125
| 65
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/PackageDecoders.java
|
package it.polimi.elet.necst.heldroid.apk;
import java.io.File;
public class PackageDecoders {
private static ApkToolDecoder apkToolDecoder;
public static PackageDecoder apkTool() {
if (apkToolDecoder != null)
return apkToolDecoder;
String currentDirectory = System.getProperty("user.dir");
File tempDirectory = new File(currentDirectory, "apktool-tmp");
if (!tempDirectory.exists())
tempDirectory.mkdir();
apkToolDecoder = new ApkToolDecoder(tempDirectory);
return apkToolDecoder;
//TODO: make sure to cleanup once done.
}
}
| 625
| 25.083333
| 71
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/DecodedPackage.java
|
package it.polimi.elet.necst.heldroid.apk;
import java.io.File;
public interface DecodedPackage {
static final String CLASSES_DEX_FILE_NAME = "classes.dex";
static final String ANDROID_MANIFEST_FILE_NAME = "AndroidManifest.xml";
static final String SMALI_DIRECTORY_NAME = "smali";
static final String RESOURCES_DIRECTORY_NAME = "res";
File getClassesDex();
File getAndroidManifest();
File getDecodedDirectory();
File getSmaliDirectory();
File getResourcesDirectory();
File getOriginalApk();
void dispose();
}
| 557
| 26.9
| 75
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/apk/ApkToolOutput.java
|
package it.polimi.elet.necst.heldroid.apk;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import java.io.File;
import java.io.FileNotFoundException;
class ApkToolOutput implements DecodedPackage {
private File classesDex, androidManifest, decodedDirectory, originalApk, smaliDirectory, resourcesDirectory;
@Override
public File getClassesDex() {
return classesDex;
}
@Override
public File getAndroidManifest() {
return androidManifest;
}
@Override
public File getDecodedDirectory() {
return decodedDirectory;
}
@Override
public File getOriginalApk() {
return originalApk;
}
@Override
public File getResourcesDirectory() {
return resourcesDirectory;
}
@Override
public File getSmaliDirectory() { return smaliDirectory; }
@Override
public void dispose() {
FileSystem.deleteDirectory(decodedDirectory);
}
public ApkToolOutput(File originalApk, File mainDirectory) throws FileNotFoundException {
this.decodedDirectory = mainDirectory;
this.originalApk = originalApk;
File dex = new File(mainDirectory, CLASSES_DEX_FILE_NAME);
File xml = new File(mainDirectory, ANDROID_MANIFEST_FILE_NAME);
File res = new File(mainDirectory, RESOURCES_DIRECTORY_NAME);
if (!xml.exists())
throw new FileNotFoundException(ANDROID_MANIFEST_FILE_NAME + " is missing!");
this.classesDex = dex;
this.androidManifest = xml;
this.smaliDirectory = new File(mainDirectory, SMALI_DIRECTORY_NAME);
this.resourcesDirectory = res;
}
}
| 1,656
| 26.163934
| 112
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/ParsingException.java
|
package it.polimi.elet.necst.heldroid.xml;
/**
* Created by Nicolo on 04/02/14.
*/
public class ParsingException extends Exception {
public ParsingException(Throwable cause) {
super(cause);
}
public ParsingException(String message) {
super(message);
}
}
| 290
| 18.4
| 49
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/ManifestAnalysisReport.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
import java.util.Collection;
public interface ManifestAnalysisReport {
String getPackageName();
String getApplicationName();
String getApplicationDescription();
Collection<String> getPermissions();
Collection<String> getIntentFilters();
Collection<String> getUsedFeatures();
}
| 355
| 26.384615
| 51
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/StringAttribute.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
public class StringAttribute {
private static final String PREFIX = "@string/";
public static boolean isResourceReference(String attributeValue) {
return attributeValue.startsWith(PREFIX);
}
public static String getReferenceName(String resourceReference) {
if (resourceReference.length() < PREFIX.length())
return "";
return resourceReference.substring(PREFIX.length());
}
}
| 487
| 27.705882
| 70
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/ManifestStrings.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
class ManifestStrings {
public static final String PERMISSION_TAG = "uses-permission";
public static final String APPLICATION_TAG = "application";
public static final String INTENT_FILTER_TAG = "intent-filter";
public static final String ACTION_TAG = "action";
public static final String USES_FEATURE_TAG = "uses-feature";
public static final String LABEL_ATTRIBUTE = "android:label";
public static final String DESCRIPTION_ATTRIBUTE = "android:description";
public static final String NAME_ATTRIBUTE = "android:name";
public static final String PACKAGE_ATTRIBUTE = "package";
public static final String RECEIVE_SMS = "android.permission.RECEIVE_SMS";
public static final String SEND_SMS = "android.permission.SEND_SMS";
public static final String INTERNET = "android.permission.INTERNET";
public static final String BLUETOOTH = "android.permission.BLUETOOTH";
public static final String NFC = "android.permission.NFC";
public static final String TRANSMIT_IR = "android.permission.TRANSMIT_IR";
public static final String USE_SIP = "android.permission.USE_SIP";
public static final String WRITE_SMS = "android.permission.WRITE_SMS";
public static final String WRITE_SOCIAL_STREAM = "android.permission.WRITE_SOCIAL_STREAM";
public static final String WRITE_APN_SETTINGS = "android.permission.WRITE_APN_SETTINGS";
}
| 1,447
| 52.62963
| 94
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/ManifestAnalyzers.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
import it.polimi.elet.necst.heldroid.xml.resources.StringResource;
/**
* Created by Nicolo on 04/02/14.
*/
public class ManifestAnalyzers {
private static DomManifestAnalyzer domBasedAnalyzer;
public static ManifestAnalyzer domBased(StringResource stringResource) {
if (domBasedAnalyzer != null)
return domBasedAnalyzer;
domBasedAnalyzer = new DomManifestAnalyzer(stringResource);
return domBasedAnalyzer;
}
}
| 516
| 26.210526
| 76
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/DomManifestAnalyzer.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
import it.polimi.elet.necst.heldroid.utils.Xml;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import it.polimi.elet.necst.heldroid.xml.resources.StringResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
class DomManifestAnalyzer implements ManifestAnalyzer {
private DocumentBuilderFactory dbFactory;
private List<String> permissions, intentFilters, usedFeatures;
private String packageName, applicationName, applicationDescription;
private StringResource stringResource;
public DomManifestAnalyzer(StringResource stringResource) {
this.dbFactory = DocumentBuilderFactory.newInstance();
this.stringResource = stringResource;
this.permissions = new ArrayList<String>();
this.intentFilters = new ArrayList<String>();
this.usedFeatures = new ArrayList<String>();
}
@Override
public ManifestAnalysisReport analyze(File manifestFile) throws ParsingException {
try {
DocumentBuilder db = dbFactory.newDocumentBuilder();
Document document = db.parse(manifestFile);
document.getDocumentElement().normalize();
this.clearStoredData();
this.analyzeManifest(document);
this.analyzePermissions(document);
this.analyzeIntentFilters(document);
this.analyzeUsedFeatures(document);
return new ManifestAnalysisReport() {
@Override
public String getPackageName() {
return packageName;
}
@Override
public String getApplicationName() {
return applicationName;
}
@Override
public String getApplicationDescription() { return applicationDescription; }
@Override
public Collection<String> getPermissions() {
return permissions;
}
@Override
public Collection<String> getIntentFilters() { return intentFilters; }
@Override
public Collection<String> getUsedFeatures() { return usedFeatures; }
};
} catch (Exception e) {
throw new ParsingException(e);
}
}
private void clearStoredData() {
this.packageName = "";
this.applicationName = "";
this.applicationDescription = "";
this.permissions.clear();
this.intentFilters.clear();
this.usedFeatures.clear();
}
private void analyzeManifest(Document document) {
// Gets the <manifest> node of the xml, which is the document main element
Element manifestElement = document.getDocumentElement();
// Checks if the package attribute exists: in that case, it contains the package name associated with
// the analyzed application
if (manifestElement.hasAttribute(ManifestStrings.PACKAGE_ATTRIBUTE))
packageName = manifestElement.getAttribute(ManifestStrings.PACKAGE_ATTRIBUTE);
// Gets the <application> tag, child of <manifest>. It is a mandatory node for every manifest but
// the method of course returns a list which we have to check for consistency
NodeList applicationTags = manifestElement.getElementsByTagName(ManifestStrings.APPLICATION_TAG);
if (applicationTags.getLength() > 0) {
Element applicationElement = (Element) applicationTags.item(0);
String label = this.getStringAttribute(applicationElement, ManifestStrings.LABEL_ATTRIBUTE);
String description = this.getStringAttribute(applicationElement, ManifestStrings.DESCRIPTION_ATTRIBUTE);
if (label != null)
this.applicationName = label;
if (description != null)
this.applicationDescription = description;
}
}
private String getStringAttribute(Element currentElement, String attributeName) {
// Looks at the attribute only if it exists
if (currentElement.hasAttribute(attributeName)) {
String value = currentElement.getAttribute(attributeName);
// If the value refers to a string resource (@string/name), we have to look for it among the string
// resources declared in xml files in the res folder, that here we supposed to have in stringResource
if (StringAttribute.isResourceReference(value)) {
String reference = StringAttribute.getReferenceName(value);
return this.stringResource.getValue(reference);
}
// Otherwise, the plain value is returned
return value;
}
// No attribute exists
return null;
}
private void analyzePermissions(Document document) {
Collection<Element> permissionElements = Xml.getElementsByTagName(document.getDocumentElement(), ManifestStrings.PERMISSION_TAG);
for (Element permissionElement : permissionElements) {
if (!permissionElement.hasAttribute(ManifestStrings.NAME_ATTRIBUTE))
continue;
String name = permissionElement.getAttribute(ManifestStrings.NAME_ATTRIBUTE);
permissions.add(name);
}
}
private void analyzeIntentFilters(Document document) {
Collection<Element> intentFilterElements = Xml.getElementsByTagName(document.getDocumentElement(), ManifestStrings.INTENT_FILTER_TAG);
for (Element intentFilterElement : intentFilterElements) {
Collection<Element> actionElements = Xml.getElementsByTagName(intentFilterElement, ManifestStrings.ACTION_TAG);
for (Element actionElement : actionElements) {
if (!actionElement.hasAttribute(ManifestStrings.NAME_ATTRIBUTE))
continue;
intentFilters.add(actionElement.getAttribute(ManifestStrings.NAME_ATTRIBUTE));
}
}
}
private void analyzeUsedFeatures(Document document) {
Collection<Element> usedFeatureElements = Xml.getElementsByTagName(document.getDocumentElement(), ManifestStrings.USES_FEATURE_TAG);
for (Element usedFeatureElement : usedFeatureElements) {
if (!usedFeatureElement.hasAttribute(ManifestStrings.NAME_ATTRIBUTE))
continue;
String name = usedFeatureElement.getAttribute(ManifestStrings.NAME_ATTRIBUTE);
usedFeatures.add(name);
}
}
}
| 6,770
| 38.138728
| 142
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/manifest/ManifestAnalyzer.java
|
package it.polimi.elet.necst.heldroid.xml.manifest;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import java.io.File;
public interface ManifestAnalyzer {
ManifestAnalysisReport analyze(File manifestFile) throws ParsingException;
}
| 252
| 24.3
| 78
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/StringResourceMetaParser.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import java.io.File;
public class StringResourceMetaParser {
private StringResourceParser basicParser;
public StringResourceMetaParser(StringResourceParser basicParser) {
this.basicParser = basicParser;
}
public StringResource parseDirectory(File directory) {
StringResource finalResult = new StringDictionary();
for (File file : directory.listFiles()) {
if (file.isDirectory())
finalResult = finalResult.merge(this.parseDirectory(file));
if (!file.getName().endsWith(".xml"))
continue;
try {
StringResource res = basicParser.parse(file);
finalResult = finalResult.merge(res);
} catch (ParsingException pe) {
continue;
}
}
return finalResult;
}
}
| 968
| 26.685714
| 75
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/DomStringResourceParser.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class DomStringResourceParser implements StringResourceParser {
protected static final String RESOURCES_TAG = "resources";
protected static final String STRING_TAG = "string";
protected static final String NAME_ATTRIBUTE = "name";
private DocumentBuilderFactory dbFactory;
public DomStringResourceParser() {
this.dbFactory = DocumentBuilderFactory.newInstance();
}
@Override
public StringResource parse(File resourceFile) throws ParsingException {
StringDictionary dictionary = new StringDictionary();
try {
DocumentBuilder db = dbFactory.newDocumentBuilder();
Document document = db.parse(resourceFile);
Element resourceElement = document.getDocumentElement();
resourceElement.normalize();
// The top-level node of a valid resource file must be <resources>
if (!resourceElement.getTagName().equals(RESOURCES_TAG))
throw new ParsingException("This is not a valid resource xml file.");
// Then we look for all the <string> tags below
NodeList stringNodes = resourceElement.getElementsByTagName(STRING_TAG);
for (int i = 0; i < stringNodes.getLength(); i++) {
Node stringNode = stringNodes.item(i);
if (stringNode.getNodeType() != Node.ELEMENT_NODE)
continue;
Element stringElement = (Element) stringNode;
// Strings with no name cannot be referenced and hence are useless
if (!stringElement.hasAttribute(NAME_ATTRIBUTE))
continue;
dictionary.add(stringElement.getAttribute(NAME_ATTRIBUTE), stringElement.getTextContent());
}
return dictionary;
} catch (Exception e) {
throw new ParsingException(e);
}
}
}
| 2,234
| 34.47619
| 107
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/StringResource.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
import java.util.Collection;
public interface StringResource {
Collection<String> getAllNames();
String getValue(String name);
StringResource merge(StringResource resource);
Boolean isEmpty();
}
| 266
| 23.272727
| 52
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/StringDictionary.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
class StringDictionary implements StringResource {
private Map<String, String> map;
public StringDictionary() {
this.map = new HashMap<String, String>();
}
public void add(String name, String value) {
this.map.put(name, value);
}
@Override
public Collection<String> getAllNames() {
return this.map.keySet();
}
@Override
public String getValue(String name) {
return this.map.get(name);
}
@Override
public StringResource merge(StringResource resource) {
StringDictionary result = new StringDictionary();
result.map.putAll(this.map);
for (String name : resource.getAllNames())
result.map.put(name, resource.getValue(name));
return result;
}
@Override
public Boolean isEmpty() {
return (this.map.size() == 0);
}
}
| 1,003
| 21.311111
| 58
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/StringResourceParser.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
import it.polimi.elet.necst.heldroid.xml.ParsingException;
import java.io.File;
public interface StringResourceParser {
StringResource parse(File resourceFile) throws ParsingException;
}
| 247
| 23.8
| 68
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/xml/resources/StringResourceParsers.java
|
package it.polimi.elet.necst.heldroid.xml.resources;
public class StringResourceParsers {
private static DomStringResourceParser domParser;
public static StringResourceParser domBased() {
if (domParser != null)
return domParser;
domParser = new DomStringResourceParser();
return domParser;
}
}
| 345
| 23.714286
| 53
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/csv/CsvWriter.java
|
package it.polimi.elet.necst.heldroid.csv;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CsvWriter {
private boolean lineStarted;
private String separator;
private BufferedWriter writer;
public CsvWriter(File file) throws IOException {
this(file, false);
}
public CsvWriter(File file, boolean append) throws IOException {
this.writer = new BufferedWriter(new FileWriter(file, append));
this.lineStarted = false;
this.separator = ", ";
}
public synchronized void writeField(String value) {
try {
if (lineStarted)
writer.write(separator);
writer.write(value);
lineStarted = true;
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
public synchronized void writeField(Object value) {
this.writeField(value.toString());
}
public synchronized void close() {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void newRecord() {
try {
lineStarted = false;
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
if (separator != null)
this.separator = separator;
}
}
| 1,573
| 22.848485
| 71
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/csv/PerformancesWriter.java
|
package it.polimi.elet.necst.heldroid.csv;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.io.File;
import java.io.IOException;
public class PerformancesWriter extends CsvWriter {
public PerformancesWriter(File file) throws IOException {
super(file, true);
if (file.length() == 0)
this.writeHeaders();
}
protected synchronized void writeHeaders() {
super.writeField("Apk name");
super.writeField("Apk size (B)");
super.writeField("Files count");
super.writeField("Smali classes count");
super.writeField("Total smali classes size (B)");
super.writeField("Unpacking time (s)");
super.writeField("Analysis time (s)");
super.writeField("Classification time (ms)");
super.newRecord();
}
public synchronized void writeAll(ApplicationData applicationData, double unpackingTime, double analysisTime, double classificationTime) {
String apkName = applicationData.getDecodedPackage().getOriginalApk().getAbsolutePath();
long apkSize = applicationData.getDecodedPackage().getOriginalApk().length();
long totalClassesSize = applicationData.getSmaliLoader().getTotalClassesSize();
int filesCount = applicationData.getDecodedFileTree().getAllFiles().size();
int classesCount = applicationData.getSmaliLoader().getClassesCount();
super.writeField(apkName);
super.writeField(apkSize);
super.writeField(filesCount);
super.writeField(classesCount);
super.writeField(totalClassesSize);
super.writeField(unpackingTime);
super.writeField(analysisTime);
super.writeField(classificationTime);
super.newRecord();
}
}
| 1,764
| 37.369565
| 142
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/csv/FeaturesWriter.java
|
package it.polimi.elet.necst.heldroid.csv;
import it.polimi.elet.necst.heldroid.goodware.features.core.Feature;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
public class FeaturesWriter extends CsvWriter {
private Collection<Feature> features;
private boolean includeClassPrediction;
public FeaturesWriter(File file, Collection<Feature> features, boolean includeClassPrediction) throws IOException {
super(file, true);
this.features = features;
this.includeClassPrediction = includeClassPrediction;
if (file.length() == 0)
this.writeHeaders();
}
protected synchronized void writeHeaders() {
super.writeField("Apk Name");
for (Feature feature : features)
super.writeField(feature.getName());
super.writeField("Detection Ratio");
if (includeClassPrediction)
super.writeField("Class Prediction");
super.newRecord();
}
public synchronized void writeAll(String apkName, Collection<Feature> gatheredFeatures, Double detectionRatio, String predictedClass) {
if (gatheredFeatures.size() != features.size())
throw new IllegalArgumentException("Features number doesn't match with header.");
super.writeField(apkName);
for (Feature feature : gatheredFeatures)
super.writeField(feature.getValue());
if (detectionRatio != null)
super.writeField(detectionRatio);
else
super.writeField(Feature.UNKNOWN_VALUE);
if (includeClassPrediction)
super.writeField(predictedClass);
super.newRecord();
}
}
| 1,684
| 29.089286
| 139
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/Main.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import it.polimi.elet.necst.heldroid.apk.DecodingException;
import it.polimi.elet.necst.heldroid.ransomware.emulation.TrafficScanner;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.HtmlScanner;
import it.polimi.elet.necst.heldroid.utils.Options;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.sentdetect.SentenceSample;
import opennlp.tools.sentdetect.SentenceSampleStream;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.TrainingParameters;
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String args[]) throws IOException, ParserConfigurationException, DecodingException,
LangDetectException, InterruptedException {
logger.info("Starting off!");
if (args.length < 1) {
printUsage();
return;
}
String op = args[0];
Options options = new Options(args);
DetectorFactory.loadProfile(Globals.LANGUAGE_PROFILES_DIRECTORY);
if (op.equals("scan")) {
logger.info("Scanning mode");
if (options.contains("-sequential"))
MainScannerSequential.main(args);
else
MainScanner.main(args);
} else if (op.equals("server"))
MainServer.main(args);
else if (op.equals("pcap"))
pcapAnalysis(args);
else if (op.equals("learn"))
learnSentenceDetector(args);
else
printUsage();
}
private static void printUsage() {
String jarName = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
System.out.println("java -jar " + jarName + " (server|scan|pcap|learn) [[args]]\n" + "\n"
+ " server <conf_dir> <watch_folder>:\n"
+ " Scan any new APK file popping up in the <watch_folder> and spin up a webserver\n"
+ " The <conf_dir> must contain:\n" + " - AndroidCallbacks.txt\n"
+ " - Conditions.txt\n" + " - EasyTaintWrapperSource.txt\n"
+ " - SourcesAndSinks.txt\n" + "\n"
+ " scan <conf_dir> <directory> <output.csv> <json_result_directory>:\n"
+ " Scan all *.apk in directory (recursively). Save JSON data in <json_result_directory>.\n"
+ " The <conf_dir> must contain:\n" + " - AndroidCallbacks.txt\n"
+ " - Conditions.txt\n" + " - EasyTaintWrapperSource.txt\n"
+ " - SourcesAndSinks.txt\n" + "\n" + " pcap <directory>:\n"
+ " Analyzes network-dump.pcap in the second-level subdirectories of the specified directory\n"
+ "\n" + " learn <lang> <textfile>:\n"
+ " learns a sentence detector model for language lang analyzing sentences\n"
+ " from the given text file, one per line");
}
private static void pcapAnalysis(String[] args) throws IOException {
File dir = new File(args[1]);
TextClassifierCollection textClassifierCollection = Factory.createClassifierCollection();
HtmlScanner htmlScanner = new HtmlScanner(textClassifierCollection);
TrafficScanner trafficScanner = new TrafficScanner(htmlScanner);
htmlScanner.setAcceptanceStrategy(Factory.createAcceptanceStrategy());
for (File resultDir : dir.listFiles()) {
if (!resultDir.isDirectory() || !resultDir.getName().endsWith(".apk"))
continue;
File innerResultDir = resultDir.listFiles()[0];
try {
trafficScanner.setPcap(new File(innerResultDir, "network-dump.pcap"));
AcceptanceStrategy.Result result = trafficScanner.analyze();
System.out.println(String.format("%s - Detected: %b ; Score: %f", resultDir.getName(),
result.isAccepted(), result.getScore()));
} catch (Exception e) {
}
}
}
private static void learnSentenceDetector(String[] args) throws IOException {
File trainingFile = new File(args[2]);
String language = args[1];
Charset charset = Charset.forName("UTF-8");
ObjectStream<String> lineStream = new PlainTextByLineStream(new FileInputStream(trainingFile), charset);
ObjectStream<SentenceSample> sampleStream = new SentenceSampleStream(lineStream);
SentenceModel model;
try {
model = SentenceDetectorME.train(language, sampleStream, true, null, TrainingParameters.defaultParams());
} finally {
sampleStream.close();
}
File modelFile = new File(Globals.MODELS_DIRECTORY, language + "-sent.bin");
OutputStream modelStream = null;
try {
modelStream = new BufferedOutputStream(new FileOutputStream(modelFile));
model.serialize(modelStream);
} finally {
if (modelStream != null)
modelStream.close();
}
}
private static String sanitize(String str) {
return str.trim().replace("\"", "");
}
}
| 5,561
| 36.581081
| 114
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/Globals.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import soot.dava.toolkits.base.AST.analysis.Analysis;
public class Globals {
public static final File MODELS_DIRECTORY = new File("models");
public static final File STOP_WORDS_DIRECTORY = new File("stop-words");
public static final File LANGUAGE_PROFILES_DIRECTORY = new File("language-profiles");
public static final File ANDROID_PLATFORMS_DIRECTORY = new File("android-platforms");
public static final File TRAINING_DATA_DIRECTORY = new File("training");
public static final File EXAMINED_FILES_LIST_FILE = new File("examined.txt");
public static final File PERFORMANCE_FILE = new File("diagnostics.csv");
public static final double MIN_LIKELIHOOD_THRESHOLD = 0.35;
public static final double MAX_LIKELIHOOD_THRESHOLD = 0.63;
public static final int MIN_PRODUCED_STEMS = 3;
public static final int MAX_PRODUCED_STEMS = 6;
public static final File getLatestAndroidVersion() {
final String regex = "android-(\\d{1,2})";
final Pattern pattern = Pattern.compile(regex);
File[] androidPlatformFiles = ANDROID_PLATFORMS_DIRECTORY.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches(regex);
}
});
int maxVersion = 0;
for (File androidPlaftormFile : androidPlatformFiles) {
Matcher matcher = pattern.matcher(androidPlaftormFile.getName());
if (matcher.matches()) {
try {
int version = Integer.parseInt(matcher.group(1));
if (version > maxVersion)
maxVersion = version;
} catch (NumberFormatException e) {
// Should never happen, thanks to the regex
e.printStackTrace();
}
}
}
if (maxVersion == 0) {
throw new IllegalStateException("Cannot find any android version");
}
File androidDir = new File(ANDROID_PLATFORMS_DIRECTORY, "android-"+maxVersion);
return new File(androidDir, "android.jar");
}
}
| 2,158
| 34.393443
| 95
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/Factory.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminDetector;
import it.polimi.elet.necst.heldroid.ransomware.emulation.TrafficScanner;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionFlowDetector;
import it.polimi.elet.necst.heldroid.ransomware.images.ImageScanner;
import it.polimi.elet.necst.heldroid.ransomware.locking.AdminLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.locking.DialogLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.locking.DrawOverLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.locking.MultiLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.photo.PhotoDetector;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.GenericTextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.Segmenter;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.SentenceClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.StopWordList;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.HtmlScanner;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.MultiResourceScanner;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.XmlLayoutScanner;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.XmlValuesScanner;
import opennlp.tools.sentdetect.SentenceDetector;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.stemmer.Stemmer;
import opennlp.tools.stemmer.snowball.SnowballStemmer;
public class Factory {
private final static Logger logger = LoggerFactory.getLogger(Factory.class);
public static EncryptionFlowDetector createEncryptionFlowDetector()
throws ParserConfigurationException {
EncryptionFlowDetector encryptionFlowDetector = new EncryptionFlowDetector();
encryptionFlowDetector.setAndroidPlatformsDir(Globals.ANDROID_PLATFORMS_DIRECTORY);
return encryptionFlowDetector;
}
public static DeviceAdminDetector createDeviceAdminDetector() throws ParserConfigurationException {
DeviceAdminDetector deviceAdminDetector = new DeviceAdminDetector();
return deviceAdminDetector;
}
public static PhotoDetector createPhotoAdminDetector() {
return new PhotoDetector();
}
public static TrafficScanner createTrafficScanner() {
HtmlScanner htmlScanner = new HtmlScanner(createClassifierCollection());
htmlScanner.setAcceptanceStrategy(createAcceptanceStrategy());
return new TrafficScanner(htmlScanner);
}
public static MultiLockingStrategy createLockingStrategy() throws ParserConfigurationException {
MultiLockingStrategy allLockingStratgies = new MultiLockingStrategy();
allLockingStratgies.add(new AdminLockingStrategy());
allLockingStratgies.add(new DrawOverLockingStrategy());
allLockingStratgies.add(new DialogLockingStrategy());
return allLockingStratgies;
}
public static ImageScanner createImageScanner() {
logger.info("Creating ImageScanner");
TextClassifierCollection textClassifierCollection = createClassifierCollection();
logger.info("Instantiating ImageScanner class");
ImageScanner imageScanner = new ImageScanner(textClassifierCollection);
logger.info("Setting acceptance strategy");
imageScanner.setAcceptanceStrategy(createAcceptanceStrategy());
return imageScanner;
}
public static MultiResourceScanner createResourceScanner() throws ParserConfigurationException {
logger.info("Creating resource scanner...");
TextClassifierCollection textClassifierCollection = createClassifierCollection();
MultiResourceScanner multiResourceScanner = new MultiResourceScanner(textClassifierCollection);
multiResourceScanner.add(new XmlLayoutScanner(textClassifierCollection));
multiResourceScanner.add(new XmlValuesScanner(textClassifierCollection));
multiResourceScanner.add(new HtmlScanner(textClassifierCollection));
multiResourceScanner.setAcceptanceStrategy(createAcceptanceStrategy());
return multiResourceScanner;
}
public static AcceptanceStrategy createAcceptanceStrategy() {
return new AcceptanceStrategy() {
@Override
public Result accepts(TextClassification textClassification) {
List<SentenceClassification> accuses = textClassification
.findAllSentences(Globals.MIN_LIKELIHOOD_THRESHOLD, "threat", "porn", "law", "copyright");
List<SentenceClassification> moneypaks = textClassification
.findAllSentences(Globals.MIN_LIKELIHOOD_THRESHOLD, "moneypak");
double accuseScore = weightNumerosity(accuses);
double moneypakScore = weightNumerosity(moneypaks);
Result result = new Result();
result.setAccepted((moneypakScore >= Globals.MIN_LIKELIHOOD_THRESHOLD)
&& (accuseScore >= Globals.MIN_LIKELIHOOD_THRESHOLD));
result.setScore(accuseScore);
result.setComment(String.format("Threat: %f, Porn: %f, Law: %f, Copyright: %f, Moneypak: %f",
textClassification.maxLikelihood("threat"), textClassification.maxLikelihood("porn"),
textClassification.maxLikelihood("law"), textClassification.maxLikelihood("copyright"),
textClassification.maxLikelihood("moneypak")));
result.setFileClassification(textClassification.getFileClassification());
return result;
}
};
}
private static double weightNumerosity(List<SentenceClassification> sentences) {
double max = 0;
double sum = 0;
for (SentenceClassification s : sentences) {
double t = computeThreshold(s);
if (s.getLikelihood() >= t) {
sum += (s.getLikelihood() - t);
if (s.getLikelihood() > max)
max = s.getLikelihood();
}
}
if (max < Globals.MIN_LIKELIHOOD_THRESHOLD)
return 0;
return max + (1 - max) * (1 - Math.exp(-sum));
}
private static double computeThreshold(SentenceClassification s) {
double stemCoefficient = (s.getProducedStemsCount() - Globals.MIN_PRODUCED_STEMS)
/ (Globals.MAX_PRODUCED_STEMS - Globals.MIN_PRODUCED_STEMS);
stemCoefficient = Math.max(0, Math.min(1, stemCoefficient));
return Globals.MAX_LIKELIHOOD_THRESHOLD
- stemCoefficient * (Globals.MAX_LIKELIHOOD_THRESHOLD - Globals.MIN_LIKELIHOOD_THRESHOLD);
}
public static TextClassifierCollection createClassifierCollection() {
logger.info("Creating classifier collection...");
TextClassifier englishClassifier = createClassifier(SupportedLanguage.ENGLISH);
TextClassifier russianClassifier = createClassifier(SupportedLanguage.RUSSIAN);
TextClassifier spanishClassifier = createClassifier(SupportedLanguage.SPANISH);
TextClassifierCollection textClassifierCollection = new TextClassifierCollection();
textClassifierCollection.add(SupportedLanguage.ENGLISH, englishClassifier);
textClassifierCollection.add(SupportedLanguage.RUSSIAN, russianClassifier);
textClassifierCollection.add(SupportedLanguage.SPANISH, spanishClassifier);
return textClassifierCollection;
}
private static TextClassifier createClassifier(SupportedLanguage language) {
logger.info("Creating classifier for " + language);
StopWordList swc = StopWordList.fromFile(new File(Globals.STOP_WORDS_DIRECTORY, language.getName() + ".txt"));
Stemmer stm = new SnowballStemmer(language.getStemmerAlgorithm());
try {
InputStream modelStream = new FileInputStream(
new File(Globals.MODELS_DIRECTORY, language.getCode() + "-sent.bin"));
SentenceModel model = new SentenceModel(modelStream);
SentenceDetector sd = new SentenceDetectorME(model);
Segmenter segmenter = new Segmenter(swc, stm, sd);
GenericTextClassifier classifier = new GenericTextClassifier(segmenter);
File trainingData = new File(Globals.TRAINING_DATA_DIRECTORY, language.getCode() + "-ransom.csv");
BufferedReader reader = new BufferedReader(new FileReader(trainingData));
String line;
while ((line = reader.readLine()) != null) {
if (line.equals(""))
continue;
int commaIndex = line.indexOf(',');
String category = sanitize(line.substring(0, commaIndex - 1));
String text = sanitize(line.substring(commaIndex + 1));
classifier.teach(category, text);
}
reader.close();
logger.info("Classifier for " + language + " is ready!");
return classifier;
} catch (Exception e) {
logger.error("Cannot create classifier for " + language + " because: " + e);
e.printStackTrace();
return null;
}
}
private static String sanitize(String str) {
return str.trim().replace("\"", "");
}
}
| 9,514
| 40.190476
| 114
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/MainServer.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminDetector;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult.Policy;
import it.polimi.elet.necst.heldroid.ransomware.emulation.TrafficScanner;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionFlowDetector;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionResult;
import it.polimi.elet.necst.heldroid.ransomware.images.ImageScanner;
import it.polimi.elet.necst.heldroid.ransomware.locking.MultiLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.MultiResourceScanner;
import it.polimi.elet.necst.heldroid.utils.CollectionToJsonConverter;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.MixedInputStream;
import soot.jimple.infoflow.results.InfoflowResults;
public class MainServer implements Runnable {
private static final int MAX_THREADS_COUNT = 20;
private Object workersLock = new Object();
private MultiLockingStrategy multiLockingStrategy;
private MultiResourceScanner multiResourceScanner;
private ImageScanner imageScanner;
private EncryptionFlowDetector encryptionFlowDetector;
private DeviceAdminDetector deviceAdminDetector;
private TrafficScanner trafficScanner;
private File uploadDirectory;
private File hashDirectory;
public static void main(String[] args)
throws ParserConfigurationException {
File target = new File(args[1]);
MainServer server = new MainServer(target);
server.run();
}
public MainServer(File uploadDirectory)
throws ParserConfigurationException {
this.uploadDirectory = uploadDirectory;
if (!uploadDirectory.exists())
if (!uploadDirectory.mkdir())
throw new RuntimeException("Cannot create upload directory!");
this.hashDirectory = new File(uploadDirectory, "hash");
if (!hashDirectory.exists())
if (!hashDirectory.mkdir())
throw new RuntimeException("Cannot create hash directory!");
File samplesCliScript = new File(uploadDirectory, "samples_cli.py");
if (!samplesCliScript.exists())
throw new RuntimeException("samples_cli.py not found in "
+ uploadDirectory.getAbsolutePath());
this.multiLockingStrategy = Factory.createLockingStrategy();
this.multiResourceScanner = Factory.createResourceScanner();
this.imageScanner = Factory.createImageScanner();
this.encryptionFlowDetector = Factory.createEncryptionFlowDetector();
this.deviceAdminDetector = Factory.createDeviceAdminDetector();
this.trafficScanner = Factory.createTrafficScanner();
}
private String fetchResponseByHash(String hash) throws IOException {
File savedResponse = new File(this.hashDirectory, hash + ".json");
if (savedResponse.exists())
return FileSystem.readFileAsString(savedResponse);
return null;
}
private void saveResponseByHash(String hash, String response)
throws IOException {
File savedResponse = new File(this.hashDirectory, hash + ".json");
OutputStream stream = new FileOutputStream(savedResponse);
stream.write(response.getBytes());
stream.close();
}
@Override
public void run() {
HttpServer server = null;
try {
server = HttpServer.create(new InetSocketAddress(8001), 0);
} catch (IOException e) {
e.printStackTrace();
}
server.createContext("/scan", new ScanHandler());
server.createContext("/pcap-scan", new PcapScanHandler());
HttpContext context = server.createContext("/fetch-scan",
new HashHandler());
context .getFilters()
.add(new ParameterFilter());
context = server.createContext("/fetch-apk", new ApkHandler());
context .getFilters()
.add(new ParameterFilter());
// Handle APK downloads
server.setExecutor(Executors.newFixedThreadPool(MAX_THREADS_COUNT)); // creates
// a
// default
// executor
server.start();
}
private String buildResponseFromScan(File file) {
ApplicationData applicationData;
try {
applicationData = ApplicationData.open(file);
} catch (Exception e) {
return "Error unpacking: " + e.getMessage();
}
boolean lockDetected, encryptionDetected, deviceAdminUsed;
List<Policy> policies;
Set<String> languages;
AcceptanceStrategy.Result textResult;
EncryptionResult encryptionResult;
synchronized (workersLock) {
multiLockingStrategy.setTarget(applicationData.getDecodedPackage());
multiResourceScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
encryptionFlowDetector.setTarget(
applicationData.getDecodedPackage());
lockDetected = multiLockingStrategy.detect();
// encryptionDetected = encryptionFlowDetector.detect();
encryptionResult = encryptionFlowDetector.detect().value;
InfoflowResults infoFlowResults = encryptionResult.getInfoFlowResults();
encryptionDetected = (infoFlowResults != null
&& infoFlowResults .getResults()
.size() > 0);
DeviceAdminResult deviceAdminResult = deviceAdminDetector.detect(true).value;
deviceAdminUsed = deviceAdminResult.isDeviceAdminUsed();
policies = deviceAdminResult.getPolicies();
AcceptanceStrategy.Result textScannerResult = multiResourceScanner.evaluate();
AcceptanceStrategy.Result imageScannerResult = null;
boolean resultFromImages = false;
/*
* Analyze images only if no text is found yet
*/
if (!textScannerResult.isAccepted()) {
if (imageScanner == null) {
imageScanner = Factory.createImageScanner();
}
imageScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
imageScanner.setTesseractLanguage(
multiResourceScanner.getEncounteredLanguagesRaw());
imageScannerResult = imageScanner.evaluate();
}
if (imageScannerResult != null) {
resultFromImages = imageScannerResult.getScore() > textScannerResult.getScore();
}
if (resultFromImages) {
textResult = imageScannerResult;
languages = imageScanner.getEncounteredLanguages();
} else {
textResult = textScannerResult;
languages = multiResourceScanner.getEncounteredLanguages();
}
}
applicationData.dispose();
return MainServer.buildResponseFromResults(lockDetected,
encryptionResult.isWritable(),
encryptionDetected,
deviceAdminUsed,
policies,
textResult,
languages);
}
private static String buildResponseFromResults(boolean lockDetected,
boolean hasRWPermission, boolean encryptionDetected,
boolean deviceAdminUsed, List<Policy> policies,
AcceptanceStrategy.Result textResult, Set<String> languages) {
StringBuilder builder = new StringBuilder();
/*
* By default the decimal separator is a comma. This is wrong in JSON,
* since it expects a dot, so we need to use a DecimalFormat object.
*/
DecimalFormatSymbols symbols = new DecimalFormatSymbols(
Locale.getDefault());
symbols.setDecimalSeparator('.');
DecimalFormat formatter = new DecimalFormat();
formatter.setDecimalFormatSymbols(symbols);
builder.append("{\n");
builder.append(
String.format(" \"lockDetected\": %b,\n", lockDetected));
builder.append(String.format(" \"textDetected\": %b,\n",
textResult.isAccepted()));
builder.append(String.format(" \"textScore\": %s,\n",
formatter.format(textResult.getScore())));
builder.append(String.format(" \"languages\": %s,\n", CollectionToJsonConverter.convert(languages)));
builder.append(String.format(" \"hasRWPermission\": %b,\n",
hasRWPermission));
builder.append(String.format(" \"encryptionDetected\": %b,\n",
encryptionDetected));
builder.append(String.format(" \"deviceAdminUsed\": %b,\n",
deviceAdminUsed));
builder.append(String.format(" \"deviceAdminPolicies\": \"%s\",\n",
policies));
builder.append(String.format(" \"textComment\": \"%s\",\n",
textResult.getComment()));
builder.append(String.format(" \"suspiciousFiles\": \"%s\"\n",
textResult.getFileClassification()));
builder.append("}");
return builder.toString();
}
private String buildResponseFromPcapScan(File file) {
AcceptanceStrategy.Result textResult;
synchronized (trafficScanner) {
trafficScanner.setPcap(file);
textResult = trafficScanner.analyze();
}
StringBuilder builder = new StringBuilder();
builder.append("{\n");
builder.append(String.format(" textDetected: %b,\n",
textResult.isAccepted()));
builder.append(
String.format(" textScore: %f,\n", textResult.getScore()));
builder.append(String.format(" textComment: \"%s\"\n",
textResult.getComment()));
builder.append("}");
return builder.toString();
}
private abstract class BaseHandler implements HttpHandler {
protected void respond(HttpExchange exchange, int statusCode,
String message) throws IOException {
byte[] bytes = message.getBytes();
exchange.sendResponseHeaders(501, bytes.length);
OutputStream stream = exchange.getResponseBody();
stream.write(bytes);
stream.close();
}
}
private class ScanHandler extends BaseHandler implements HttpHandler {
private static final String MULTIPLART_MIME_TYPE = "multipart/form-data";
private static final String OCTET_STREAM_MIME_TYPE = "application/octet-stream";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String BOUNDARY_FIELD = "boundary";
private static final String BOUNDARY_PREFIX = "--";
private static final String BOUNDARY_SUFFIX = "--";
/**
* Scans an apk sent as application/octect-stream and returns the scan
* results. Notice that a connection-reset socket exception is thrown is
* this method returns without reading the whole request stream.
* Therefore, to mitigate useless reads, if an error arises before
* starting the read phase, the client cannot know which error it was.
*
* @param t
* @throws IOException
*/
public void handle(HttpExchange t) throws IOException {
File requestFile = File.createTempFile("upload-",
".apk",
MainServer.this.uploadDirectory);
this.saveRequestFile(t, requestFile);
String hash = FileSystem.hashOf(requestFile);
String response = MainServer.this.fetchResponseByHash(hash);
if (response == null) {
response = MainServer.this.buildResponseFromScan(requestFile);
MainServer.this.saveResponseByHash(hash, response);
}
this.respond(t, 200, response);
}
protected File saveRequestFile(HttpExchange exchange, File resultFile)
throws IOException {
String method = exchange.getRequestMethod();
if (!method.equals("POST"))
throw new RuntimeException("Invalid method: POST required!");
String boundary = this.getBoundary(exchange);
if (boundary == null)
throw new RuntimeException("No boundary specification!");
int contentLength = Integer.valueOf(exchange.getRequestHeaders()
.getFirst(
"Content-Length"));
String startBoundary = BOUNDARY_PREFIX + boundary;
String endBoundary = "\r\n" + BOUNDARY_PREFIX + boundary
+ BOUNDARY_SUFFIX;
MixedInputStream requestStream = new MixedInputStream(
exchange.getRequestBody());
String line;
// Reads until a start boundary is found
while (!requestStream .readLine()
.equals(startBoundary))
;
// Then keeps reading until a Content-Type header is found. Usually
// there are two headers at the start
// of a boundary (Content-Disposition and Content-Type). We assume
// that only one file is included within
// the request and thus it is useless to parse Content-Disposition
while (!(line = requestStream.readLine()).startsWith(
CONTENT_TYPE_HEADER))
;
// Gets the mime type of this part
String mimeType = line.split(":")[1].trim();
// If it is not an octect stream, fails
if (!mimeType.equals(OCTET_STREAM_MIME_TYPE)) {
requestStream.close();
throw new RuntimeException(
"Invalid MIME type: expected application/octet-stream!");
}
OutputStream outputStream = new FileOutputStream(resultFile);
byte[] buffer = new byte[4096];
// Index of one of the last blocks of data (not important that is
// exactly the last)
int endingBlockIndex = Math.max(0,
(contentLength / buffer.length) - 1);
int readBlocks = 0;
int brc = 0;
// There are some empty lines after Content-Type
requestStream.skipEmptyLines();
// If more parts are included, only the first is considered (until a
// startBoundary). If this is the only
// part, anyway the endBoundary has startBoundary as prefix
while ((brc = requestStream.read(buffer)) > 0) {
readBlocks++;
// Looks for the endBoundary string, but only if we are
// approaching the end of the octet stream
// While normally it wouldn't be needed, ApkDecoder complains
// about unaligned zip files
if (readBlocks >= endingBlockIndex) {
int boundaryIndex = this.findBinaryString(buffer,
endBoundary);
if (boundaryIndex >= 0) {
byte[] tempBuffer = new byte[boundaryIndex];
System.arraycopy(buffer,
0,
tempBuffer,
0,
boundaryIndex);
buffer = tempBuffer;
brc = buffer.length;
}
}
outputStream.write(buffer, 0, brc);
}
requestStream.close();
outputStream.close();
return resultFile;
}
private int findBinaryString(byte[] buffer, String target) {
byte[] targetBytes = target.getBytes();
if (buffer.length < targetBytes.length)
return -1;
for (int i = 0; i < buffer.length - targetBytes.length; i++) {
boolean found = true;
for (int j = 0; j < targetBytes.length; j++)
if (buffer[j + i] != targetBytes[j]) {
found = false;
break;
}
if (found)
return i;
}
return -1;
}
private String getBoundary(HttpExchange exchange) {
Headers headers = exchange.getRequestHeaders();
String contentType = headers.getFirst(CONTENT_TYPE_HEADER);
String[] parts = contentType.split(";");
String mimeType = parts[0] .trim()
.toLowerCase();
if (!mimeType.equals(MULTIPLART_MIME_TYPE))
return null;
for (int i = 1; i < parts.length; i++) {
String part = parts[i].trim();
if (part.startsWith(BOUNDARY_FIELD)) {
String[] boundarySpecs = part.split("=");
return boundarySpecs[1].trim();
}
}
return null;
}
}
private class PcapScanHandler extends ScanHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
File requestFile = File.createTempFile("upload-",
".pcap",
MainServer.this.uploadDirectory);
this.saveRequestFile(t, requestFile);
String hash = FileSystem.hashOf(requestFile) + ".pcap";
String response = MainServer.this.fetchResponseByHash(hash);
if (response == null) {
response = MainServer.this.buildResponseFromPcapScan(
requestFile);
MainServer.this.saveResponseByHash(hash, response);
}
this.respond(t, 200, response);
}
}
private class ApkHandler extends BaseHandler implements HttpHandler {
private final File baseFolder;
public ApkHandler() {
baseFolder = new File("/home/andronio/experiments/Automator");
}
@Override
public void handle(HttpExchange exchange) throws IOException {
Map<?, ?> params = (Map<?, ?>) exchange.getAttribute("parameters");
String family = (String) params.get("family");
String hash = (String) params.get("hash");
if (family == null || hash == null) {
respond(exchange, 400, "No hash or family provided");
return;
}
File familyFolder = new File(baseFolder, family).getCanonicalFile();
if (!familyFolder.exists()) {
respond(exchange, 404, "Family not found");
}
if (!familyFolder .getParentFile()
.equals(baseFolder.getCanonicalFile())) {
respond(exchange, 400, "Bad family");
return;
}
File apk = new File(familyFolder, hash + ".apk").getCanonicalFile();
if (!apk.getParentFile()
.equals(familyFolder.getCanonicalFile())) {
respond(exchange, 400, "Bad file");
return;
}
if (!apk.exists()) {
respond(exchange, 404, "Apk not found");
return;
}
// Set output file name
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.add("Content-Disposition",
"attachment; filename=\"" + hash + ".apk\"");
// Start sending file
exchange.sendResponseHeaders(200, apk.length());
OutputStream os = exchange.getResponseBody();
FileInputStream fis = new FileInputStream(apk);
byte[] buffer = new byte[8 * 1024]; // 8KB buffer
int read = 0;
while ((read = fis.read(buffer)) > -1) {
os.write(buffer, 0, read);
}
fis.close();
os.close();
}
}
private class HashHandler extends BaseHandler implements HttpHandler {
private static final String SAMPLES_API_KEY = "11d75ea7912546ea97d9fea1d0317b38";
@Override
public void handle(HttpExchange exchange) throws IOException {
Map<?, ?> params = (Map<?, ?>) exchange.getAttribute("parameters");
String hash = (String) params.get("hash");
String response = MainServer.this.fetchResponseByHash(hash);
if (response == null) {
File sample = this.fetchSample(hash);
if (!sample.exists()) {
this.respond(exchange, 404, "Not found");
return;
}
response = MainServer.this.buildResponseFromScan(sample);
MainServer.this.saveResponseByHash(hash, response);
}
this.respond(exchange, 200, response);
}
private File fetchSample(String hash) throws IOException {
String command = String.format(
"python %s/samples_cli.py -log-level DEBUG get -at-key %s %s",
MainServer.this.uploadDirectory.getAbsolutePath(),
SAMPLES_API_KEY,
hash);
Process downloader = Runtime.getRuntime()
.exec(command);
System.out.println("Executed: " + command);
try {
downloader.waitFor();
} catch (InterruptedException e) {
}
File resultFile = new File(MainServer.this.uploadDirectory,
hash + ".apk");
File misplacedFile = new File(hash + ".apk");
if (misplacedFile.exists())
misplacedFile.renameTo(resultFile);
return resultFile;
}
}
public class ParameterFilter extends Filter {
@Override
public String description() {
return "Parses the requested URI for parameters";
}
@Override
public void doFilter(HttpExchange exchange, Chain chain)
throws IOException {
parseGetParameters(exchange);
chain.doFilter(exchange);
}
private void parseGetParameters(HttpExchange exchange)
throws UnsupportedEncodingException {
Map<String, String> parameters = new HashMap<String, String>();
URI requestedUri = exchange.getRequestURI();
String query = requestedUri.getRawQuery();
parseQuery(query, parameters);
exchange.setAttribute("parameters", parameters);
}
private void parseQuery(String query, Map<String, String> parameters)
throws UnsupportedEncodingException {
if (query == null)
return;
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0)
key = URLDecoder.decode(param[0],
System.getProperty("file.encoding"));
if (param.length > 1)
value = URLDecoder.decode(param[1],
System.getProperty("file.encoding"));
parameters.put(key, value);
}
}
}
}
| 20,520
| 29.858647
| 105
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/MainScannerSequential.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminDetector;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult.Policy;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionFlowDetector;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionResult;
import it.polimi.elet.necst.heldroid.ransomware.images.ImageScanner;
import it.polimi.elet.necst.heldroid.ransomware.locking.MultiLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.MultiResourceScanner;
import it.polimi.elet.necst.heldroid.utils.CollectionToJsonConverter;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Options;
import it.polimi.elet.necst.heldroid.utils.PersistentFileList;
import it.polimi.elet.necst.heldroid.utils.Stopwatch;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import soot.jimple.infoflow.results.InfoflowResults;
public class MainScannerSequential {
/**
* Contains the directory in which the JSON report should be saved
*/
private static File jsonDirectory;
public static void main(String[] args) throws ParserConfigurationException,
IOException, InterruptedException {
final File target = new File(args[1]);
final File result = new File(args[2]);
MainScannerSequential.jsonDirectory = new File(args[3]);
final Options options = new Options(args);
silentMode = options.contains("-s");
noLock = options.contains("-nl");
noTextDetection = options.contains("-nt");
noEncryption = options.contains("-ne");
noDeviceAdminDetection = options.contains("-na");
multiLockingStrategy = Factory.createLockingStrategy();
multiResourceScanner = Factory.createResourceScanner();
imageScanner = Factory.createImageScanner();
encryptionFlowDetector = Factory.createEncryptionFlowDetector();
deviceAdminDetector = Factory.createDeviceAdminDetector();
examinedFiles = new PersistentFileList(
Globals.EXAMINED_FILES_LIST_FILE);
if (result.exists())
resultsWriter = new BufferedWriter(new FileWriter(result, true));
else {
resultsWriter = new BufferedWriter(new FileWriter(result));
resultsWriter.write(
"Sample; LockDetected; TextDetected; TextScore; Language; RW Permission; EncryptionDetected; DeviceAdminUsed; DeviceAdminPolicies; Comment; TimedOut; Classified Files");
resultsWriter.newLine();
}
if (Globals.PERFORMANCE_FILE.exists())
performancesWriter = new BufferedWriter(
new FileWriter(Globals.PERFORMANCE_FILE, true));
else {
performancesWriter = new BufferedWriter(
new FileWriter(Globals.PERFORMANCE_FILE));
performancesWriter.write(
"Sample; LockDetectionTime; TextDetectionTime; EncryptionDetectionTime; DeviceAdminDetectionTime; UnpackingTime; SmaliClassCount; SmaliSize; ApkSize");
performancesWriter.newLine();
}
Thread .currentThread()
.setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t,
Throwable e) {
if ((t != null) && (t.getName() != null))
System.out.println(
"In thread : " + t.getName());
if ((e != null) && (e.getMessage() != null)) {
System.out.println(e.getClass()
.getName()
+ ": " + e.getMessage());
if (e.getStackTrace() != null)
for (StackTraceElement ste : e.getStackTrace())
if (ste != null)
System.out.println(ste
.getFileName()
+ " at line "
+ ste.getLineNumber());
}
}
});
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName()
.toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
closeWriters();
}
private static void println(String message) {
if (!silentMode)
System.out.println(message);
}
private static void print(String message) {
if (!silentMode)
System.out.print(message);
}
private static void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private static void readFileList(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkFile(File file) {
if (examinedFiles.contains(file)) {
println("Skipped: " + file.getName());
return;
}
if (!file .getName()
.toLowerCase()
.endsWith(".apk")) {
return;
}
final Wrapper<Double> unpackingTime = new Wrapper<Double>(0.0);
final ApplicationData data = unpack(file, unpackingTime);
if (data == null) {
return;
}
scanData(data, unpackingTime.value);
}
private static ApplicationData unpack(final File file,
final Wrapper<Double> unpackingTime) {
final Wrapper<ApplicationData> resultWrapper = new Wrapper<ApplicationData>(
null);
final Wrapper<Exception> exceptionWrapper = new Wrapper<Exception>(
null);
println("Unpacking: " + file.getName());
unpackingTime.value = Stopwatch.time(new Runnable() {
@Override
public void run() {
try {
resultWrapper.value = ApplicationData.open(file);
} catch (Exception e) {
exceptionWrapper.value = e;
}
}
});
if (resultWrapper.value != null)
println("Unpacked: " + file.getName());
else if (exceptionWrapper.value != null)
println("Dropped: " + file.getName() + " : "
+ exceptionWrapper.value.getMessage());
return resultWrapper.value;
}
private static void scanData(final ApplicationData applicationData,
Double unpackingTime) {
String apkName = applicationData.getDecodedPackage()
.getOriginalApk()
.getAbsolutePath();
println("Submitted: " + apkName);
examinedFiles.add(applicationData .getDecodedPackage()
.getOriginalApk());
final Wrapper<Boolean> lockDetected = new Wrapper<Boolean>(false);
final Wrapper<AcceptanceStrategy.Result> textDetected = new Wrapper<AcceptanceStrategy.Result>(
AcceptanceStrategy.fail());
final Wrapper<Boolean> encryptionDetected = new Wrapper<Boolean>(false);
final Wrapper<Boolean> hasRWPermission = new Wrapper<>(false);
final Wrapper<Boolean> deviceAdminUsed = new Wrapper<>(false);
final Wrapper<List<Policy>> deviceAdminPolicies = new Wrapper<>(null);
final Wrapper<Set<String>> languages = new Wrapper<>(null);
final Wrapper<Double> lockDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> textDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> encryptionDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> deviceAdminDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
ExecutorService executor = Executors.newFixedThreadPool(3);
if (!noTextDetection) {
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
multiResourceScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
AcceptanceStrategy.Result textResult = multiResourceScanner.evaluate();
AcceptanceStrategy.Result imageResult = null;
boolean resultFromImages = false;
/*
* Analyze images only if no text is found yet
*/
if (!textResult.isAccepted()) {
if (imageScanner == null) {
imageScanner = Factory.createImageScanner();
}
imageScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
imageScanner.setTesseractLanguage(
multiResourceScanner.getEncounteredLanguagesRaw());
imageResult = imageScanner.evaluate();
}
if (imageResult != null) {
resultFromImages = imageResult.getScore() > textResult.getScore();
}
if (languages != null) {
if (languages.value == null) {
languages.value = new HashSet<>();
}
// Add languages depending on who did the
// analysis
if (resultFromImages) {
languages.value.addAll(
imageScanner.getEncounteredLanguages());
} else {
languages.value.addAll(
multiResourceScanner.getEncounteredLanguages());
}
}
if (textDetected != null)
textDetected.value = resultFromImages
? imageResult : textResult;
}
});
if (textDetectionTime != null)
textDetectionTime.value = time;
}
});
}
if (!noLock)
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
multiLockingStrategy.setTarget(
applicationData.getDecodedPackage());
Boolean result = lockDetected.value = multiLockingStrategy.detect();
if (lockDetected != null)
lockDetected.value = result;
}
});
if (lockDetectionTime != null)
lockDetectionTime.value = time;
}
});
if (!noEncryption)
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
encryptionFlowDetector.setTarget(
applicationData.getDecodedPackage());
Wrapper<EncryptionResult> encryptionResult = encryptionFlowDetector.detect();
InfoflowResults infoFlow = encryptionResult.value.getInfoFlowResults();
Boolean result = (infoFlow != null
&& infoFlow .getResults()
.size() > 0);
if (encryptionDetected != null)
encryptionDetected.value = result;
if (hasRWPermission != null)
hasRWPermission.value = encryptionResult.value.isWritable();
}
});
if (encryptionDetectionTime != null)
encryptionDetectionTime.value = time;
}
});
if (!noDeviceAdminDetection)
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
deviceAdminDetector.setTarget(
applicationData.getDecodedPackage());
boolean reuseCfg = !noEncryption;
Wrapper<DeviceAdminResult> deviceAdminResult = deviceAdminDetector.detect(reuseCfg);
if (deviceAdminResult != null) {
if (deviceAdminResult.value != null) {
DeviceAdminResult res = deviceAdminResult.value;
if (deviceAdminPolicies != null)
deviceAdminPolicies.value = res.getPolicies();
if (deviceAdminUsed != null)
deviceAdminUsed.value = true;
// No longer needed
deviceAdminResult = null;
}
}
}
});
if (deviceAdminDetectionTime != null) {
deviceAdminDetectionTime.value = time;
}
}
});
boolean timedOut = false;
executor.shutdown();
try {
if (!executor.awaitTermination(ANALYSIS_TIMEOUT,
TimeUnit.SECONDS)) {
executor.shutdownNow();
timedOut = true;
}
} catch (InterruptedException e) {
}
// Create JSON
try {
String hash = FileSystem.hashOf(applicationData .getDecodedPackage()
.getOriginalApk());
File hashDirectory = new File(MainScannerSequential.jsonDirectory,
hash + ".json");
OutputStream jsonWriter = new FileOutputStream(hashDirectory);
String json = MainScannerSequential.buildResponseFromResults(
lockDetected.value,
hasRWPermission.value,
encryptionDetected.value,
deviceAdminUsed.value,
deviceAdminPolicies.value,
textDetected.value,
languages.value);
jsonWriter.write(json.getBytes());
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
resultsWriter.write(String.format(
"%s; %b; %b; %f; %s; %b; %b; %b; %s; \"%s\"; %b; %s\n",
apkName,
lockDetected.value,
textDetected.value.isAccepted(),
textDetected.value.getScore(),
languages.value,
hasRWPermission.value,
encryptionDetected.value,
deviceAdminUsed.value,
deviceAdminPolicies.value,
textDetected.value.getComment(),
timedOut,
textDetected.value.getFileClassification()));
performancesWriter.write(
String.format("%s; %f; %f; %f; %f; %f; %d; %d; %d\n",
apkName,
lockDetectionTime.value,
textDetectionTime.value,
encryptionDetectionTime.value,
deviceAdminDetectionTime.value,
unpackingTime,
applicationData .getSmaliLoader()
.getClassesCount(),
applicationData .getSmaliLoader()
.getTotalClassesSize(),
applicationData .getDecodedPackage()
.getOriginalApk()
.length()));
resultsWriter.flush();
performancesWriter.flush();
} catch (IOException e) {
}
// No longer deleting temp files
if (!timedOut)
println("Completed: " + apkName);
else {
print("Timeout");
if (textDetectionTime.value == ANALYSIS_TIMEOUT)
print(" TextDetection");
if (!noLock && (lockDetectionTime.value == ANALYSIS_TIMEOUT))
print(" LockDetection");
if (!noEncryption
&& (encryptionDetectionTime.value == ANALYSIS_TIMEOUT))
print(" EncryptionDetection");
println(": " + apkName);
}
}
private static String buildResponseFromResults(boolean lockDetected,
boolean hasRWPermission, boolean encryptionDetected,
boolean deviceAdminUsed, List<Policy> policies,
AcceptanceStrategy.Result textResult, Set<String> languages) {
StringBuilder builder = new StringBuilder();
/*
* By default the decimal separator is a comma. This is wrong in JSON,
* since it expects a dot, so we need to use a DecimalFormat object.
*/
DecimalFormatSymbols symbols = new DecimalFormatSymbols(
Locale.getDefault());
symbols.setDecimalSeparator('.');
DecimalFormat formatter = new DecimalFormat();
formatter.setDecimalFormatSymbols(symbols);
builder.append("{\n");
builder.append(
String.format(" \"lockDetected\": %b,\n", lockDetected));
builder.append(String.format(" \"textDetected\": %b,\n",
textResult.isAccepted()));
builder.append(String.format(" \"textScore\": %s,\n",
formatter.format(textResult.getScore())));
builder.append(String.format(" \"languages\": %s,\n", CollectionToJsonConverter.convert(languages)));
builder.append(String.format(" \"hasRWPermission\": %b,\n",
hasRWPermission));
builder.append(String.format(" \"encryptionDetected\": %b,\n",
encryptionDetected));
builder.append(String.format(" \"deviceAdminUsed\": %b,\n",
deviceAdminUsed));
builder.append(String.format(" \"deviceAdminPolicies\": \"%s\",\n",
policies));
builder.append(String.format(" \"textComment\": \"%s\",\n",
textResult.getComment()));
builder.append(String.format(" \"suspiciousFiles\": \"%s\"\n",
textResult.getFileClassification()));
builder.append("}");
return builder.toString();
}
private static void closeWriters() throws IOException {
resultsWriter.close();
performancesWriter.close();
examinedFiles.dispose();
}
private static final int ANALYSIS_TIMEOUT = 40; // seconds
private static Boolean silentMode = false;
private static Boolean noLock = false;
private static Boolean noEncryption = false;
private static Boolean noDeviceAdminDetection = false;
private static Boolean noTextDetection = false;
private static PersistentFileList examinedFiles;
private static BufferedWriter resultsWriter;
private static BufferedWriter performancesWriter;
private static MultiLockingStrategy multiLockingStrategy;
private static MultiResourceScanner multiResourceScanner;
private static ImageScanner imageScanner;
private static EncryptionFlowDetector encryptionFlowDetector;
private static DeviceAdminDetector deviceAdminDetector;
}
| 17,194
| 30.435101
| 174
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/MainScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminDetector;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult.Policy;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionFlowDetector;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionResult;
import it.polimi.elet.necst.heldroid.ransomware.images.ImageScanner;
import it.polimi.elet.necst.heldroid.ransomware.locking.MultiLockingStrategy;
import it.polimi.elet.necst.heldroid.ransomware.photo.PhotoAdminResult;
import it.polimi.elet.necst.heldroid.ransomware.photo.PhotoDetector;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.MultiResourceScanner;
import it.polimi.elet.necst.heldroid.utils.CFGUtils;
import it.polimi.elet.necst.heldroid.utils.CollectionToJsonConverter;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Options;
import it.polimi.elet.necst.heldroid.utils.PersistentFileList;
import it.polimi.elet.necst.heldroid.utils.Stopwatch;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import soot.jimple.infoflow.cfg.SharedCfg;
import soot.jimple.infoflow.results.InfoflowResults;
public class MainScanner {
/**
* Contains the directory in which the JSON report should be saved
*/
private static File jsonDirectory;
private final static Logger logger = LoggerFactory.getLogger(MainScanner.class);
public static void main(String[] args) throws ParserConfigurationException,
IOException, InterruptedException {
mainArgs = args;
logger.info("Starting off!");
final File target = new File(args[1]);
final File result = new File(args[2]);
jsonDirectory = new File(args[3]);
final Options options = new Options(args);
silentMode = options.contains("-s");
noLock = options.contains("-nl");
noEncryption = options.contains("-ne");
noTextDetection = options.contains("-nt");
noDeviceAdminDetection = options.contains("-na");
logger.info("Instantiating components...");
logger.info("Creating lock-strategy detector");
multiLockingStrategy = Factory.createLockingStrategy();
logger.info("Creaating resource scanner");
multiResourceScanner = Factory.createResourceScanner();
logger.info("Creating image scanner");
imageScanner = Factory.createImageScanner();
logger.info("Creating encryption-strategy detector");
encryptionFlowDetector = Factory.createEncryptionFlowDetector();
logger.info("Creating device-admin detector");
deviceAdminDetector = Factory.createDeviceAdminDetector();
logger.info("Creating photo-admin detector");
photoAdminDetector = Factory.createPhotoAdminDetector();
logger.info("Components ready to analyze!");
examinedFiles = new PersistentFileList(
Globals.EXAMINED_FILES_LIST_FILE);
if (result.exists())
resultsWriter = new BufferedWriter(new FileWriter(result, true));
else {
resultsWriter = new BufferedWriter(new FileWriter(result));
resultsWriter.write(
"Sample; LockDetected; LockStrategy; TextDetected; TextScore; Languages; RW Permission; EncryptionDetected; PhotoCaptureDetected; DeviceAdminUsed; DeviceAdminPolicies; DevAdminFromReflection; Comment; TimedOut; Classified files");
resultsWriter.newLine();
}
if (Globals.PERFORMANCE_FILE.exists())
performancesWriter = new BufferedWriter(
new FileWriter(Globals.PERFORMANCE_FILE, true));
else {
performancesWriter = new BufferedWriter(
new FileWriter(Globals.PERFORMANCE_FILE));
performancesWriter.write(
"Sample; LockDetectionTime; TextDetectionTime; EncryptionDetectionTime; DeviceAdminDetectionTime; UnpackingTime; SmaliClassCount; SmaliSize; ApkSize");
performancesWriter.newLine();
}
availableFiles = new ArrayList<File>();
availableUnpackedData = new ArrayList<ApplicationData>();
unpackingTimes = new ArrayList<Double>();
logger.info("Preparing workers threads");
fileEnumeratingThread = new Thread(new Runnable() {
@Override
public void run() {
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName()
.toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
synchronized (fileEnumerationFinishedLock) {
fileEnumerationFinished = true;
}
}
});
fileEnumeratingThread.setName("FileEnumerationThread");
unpackingThread = new Thread(new Runnable() {
@Override
public void run() {
unpackingRoutine();
}
});
unpackingThread.setName("UnpackingThread");
analysisThread = new Thread(new Runnable() {
@Override
public void run() {
analysisRoutine();
}
});
analysisThread.setName("AnalysisThread");
fileEnumeratingThread.start();
unpackingThread.start();
analysisThread.start();
fileEnumeratingThread.join();
unpackingThread.join();
analysisThread.join();
closeWriters();
}
private static void print(String message) {
if (!silentMode)
System.out.print(message);
}
private static void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
if (aborted)
return;
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private static void readFileList(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkFile(File file) {
if (examinedFiles.contains(file)) {
logger.info("Skipped: " + file.getName());
return;
}
if (file.isFile() && file .getName()
.toLowerCase()
.endsWith(".apk")) {
synchronized (availableFiles) {
availableFiles.add(file);
}
}
}
private static void unpackingRoutine() {
while (true) {
if (aborted)
return;
int unpackedApksCount;
synchronized (availableUnpackedData) {
unpackedApksCount = availableUnpackedData.size();
}
if (unpackedApksCount >= MAX_ALLOWED_UNPACKED_APKS_IN_MEMORY) {
analysisStalls++;
if (analysisStalls >= MAX_ANALYSIS_STALLS) {
logger.warn("Stalled " + analysisStalls
+ " times. Maybe analysis thread crahsed? Restarting.");
restartApplication();
return;
}
try {
logger.warn("Analysis too slow: unpacking routine stalled for "
+ UNPACKING_WAIT_TIME + " seconds");
Thread.sleep(UNPACKING_WAIT_TIME * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
continue;
}
} else {
analysisStalls = 0;
}
File file;
synchronized (availableFiles) {
synchronized (fileEnumerationFinishedLock) {
if (fileEnumerationFinished && (availableFiles.size() == 0))
break;
}
if (availableFiles.size() == 0)
continue;
file = availableFiles.get(0);
}
logger.info("Unpacking: " + file.getName());
try {
Long startTime = System.currentTimeMillis();
ApplicationData applicationData = ApplicationData.open(file);
Long endTime = System.currentTimeMillis();
synchronized (availableUnpackedData) {
availableUnpackedData.add(applicationData);
unpackingTimes.add((double) (endTime - startTime) / 1000.0);
}
logger.info("Unpacked: " + file.getName());
} catch (Exception e) {
logger.warn("Dropped: " + file.getName() + "; " + e.getMessage());
}
synchronized (availableFiles) {
availableFiles.remove(0);
}
}
}
private static void analysisRoutine() {
while (true) {
if (aborted)
return;
ApplicationData applicationData;
Double unpackingTime;
Integer availableUnpackedDataSize;
synchronized (availableUnpackedData) {
availableUnpackedDataSize = availableUnpackedData.size();
}
if (availableUnpackedDataSize == 0) {
synchronized (availableFiles) {
synchronized (fileEnumerationFinishedLock) {
if (fileEnumerationFinished
&& (availableFiles.size() == 0))
break;
}
}
unpackingStalls++;
if (unpackingStalls >= MAX_UNPACKING_STALLS) {
logger.warn("Stalled " + analysisStalls
+ " times. Maybe unpacking thread crahsed? Restarting.");
restartApplication();
return;
}
try {
logger.warn("Unpacking too slow: analysis routine stalled for "
+ ANALYSIS_WAIT_TIME + " seconds");
Thread.sleep(ANALYSIS_WAIT_TIME * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
continue;
}
} else {
unpackingStalls = 0;
}
applicationData = availableUnpackedData.get(0);
unpackingTime = unpackingTimes.get(0);
scanData(applicationData, unpackingTime);
synchronized (availableUnpackedData) {
availableUnpackedData.remove(0);
unpackingTimes.remove(0);
}
}
}
private static void scanData(final ApplicationData applicationData,
Double unpackingTime) {
String apkName = applicationData.getDecodedPackage()
.getOriginalApk()
.getAbsolutePath();
logger.info("Submitted: " + apkName);
examinedFiles.add(applicationData .getDecodedPackage()
.getOriginalApk());
final Wrapper<Boolean> lockDetected = new Wrapper<Boolean>(false);
final Wrapper<String> lockStrategy = new Wrapper<>(null);
final Wrapper<AcceptanceStrategy.Result> textDetected = new Wrapper<AcceptanceStrategy.Result>(
AcceptanceStrategy.fail());
final Wrapper<Boolean> encryptionDetected = new Wrapper<Boolean>(false);
final Wrapper<Boolean> photoCaptureDetected = new Wrapper<>(false);
final Wrapper<Boolean> hasRWPermission = new Wrapper<>(false);
final Wrapper<Boolean> deviceAdminUsed = new Wrapper<Boolean>(false);
final Wrapper<Boolean> encryptionDetectorTimedOut = new Wrapper<>(
false);
final Wrapper<Set<String>> languages = new Wrapper<Set<String>>(null);
final Wrapper<Boolean> isFromReflection = new Wrapper<>(false);
final Wrapper<PhotoAdminResult> photoCaptureResult = new Wrapper<>(null);
final Wrapper<List<Policy>> deviceAdminPolicies = new Wrapper<List<Policy>>(
null);
final Wrapper<Double> lockDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> textDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> encryptionDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
final Wrapper<Double> deviceAdminDetectionTime = new Wrapper<Double>(
(double) ANALYSIS_TIMEOUT);
ExecutorService executor = Executors.newFixedThreadPool(4);
if (!noTextDetection) {
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
multiResourceScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
AcceptanceStrategy.Result textResult = multiResourceScanner.evaluate();
AcceptanceStrategy.Result imageResult = null;
boolean resultFromImages = false;
/*
* Analyze images only if no text is found yet
*/
if (!textResult.isAccepted()) {
if (imageScanner == null) {
imageScanner = Factory.createImageScanner();
}
imageScanner.setUnpackedApkDirectory(
applicationData .getDecodedPackage()
.getDecodedDirectory());
imageScanner.setTesseractLanguage(
multiResourceScanner.getEncounteredLanguagesRaw());
imageResult = imageScanner.evaluate();
}
/*
* If both results are available then take the one
* with higher score
*/
if (imageResult != null) {
resultFromImages = imageResult.getScore() > textResult.getScore();
}
if (languages != null) {
if (languages.value == null) {
languages.value = new HashSet<>();
}
// Add languages depending on who did the
// analysis
if (resultFromImages) {
languages.value.addAll(
imageScanner.getEncounteredLanguages());
} else {
languages.value.addAll(
multiResourceScanner.getEncounteredLanguages());
}
}
if (textDetected != null)
textDetected.value = resultFromImages
? imageResult : textResult;
}
});
if (textDetectionTime != null)
textDetectionTime.value = time;
}
});
}
if (!noLock)
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
multiLockingStrategy.setTarget(
applicationData.getDecodedPackage());
Boolean result = lockDetected.value = multiLockingStrategy.detect();
if (lockDetected != null)
lockDetected.value = result;
if (result) {
lockStrategy.value = multiLockingStrategy.getSuccessfulStrategy();
}
}
});
if (lockDetectionTime != null)
lockDetectionTime.value = time;
}
});
if (!noEncryption) {
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
encryptionFlowDetector.setTarget(
applicationData.getDecodedPackage());
Wrapper<EncryptionResult> encryptionResult = encryptionFlowDetector.detect();
if (encryptionResult.value != null) {
if (encryptionResult.value.isTimedout()) {
encryptionDetectorTimedOut.value = true;
} else {
InfoflowResults infoFlow = encryptionResult.value.getInfoFlowResults();
boolean result = (infoFlow != null
&& infoFlow.getResults() != null
&& infoFlow .getResults()
.size() > 0);
if (encryptionDetected != null)
encryptionDetected.value = result;
}
} else {
encryptionDetected.value = null;
}
if (hasRWPermission != null) {
hasRWPermission.value = encryptionResult.value.isWritable();
if (!hasRWPermission.value) {
SharedCfg.setCfg(CFGUtils.createCfg(applicationData.getDecodedPackage()));
}
}
}
});
if (encryptionDetectionTime != null)
encryptionDetectionTime.value = time;
}
});
}
if (!noDeviceAdminDetection) {
executor.submit(new Runnable() {
@Override
public void run() {
Double time = Stopwatch.time(new Runnable() {
@Override
public void run() {
deviceAdminDetector.setTarget(
applicationData.getDecodedPackage());
photoAdminDetector.setTarget(
applicationData.getDecodedPackage());
/*
* If the EncryptionFlowDetector is enabled, we will
* reuse the CFG that it generates, otherwise we
* will generate a new one
*/
boolean reuseCfg = !noEncryption;
Wrapper<DeviceAdminResult> deviceAdminResult = null;
try {
deviceAdminResult = deviceAdminDetector.detect(
reuseCfg);
photoCaptureResult.value = photoAdminDetector.detect(
reuseCfg).value;
photoCaptureDetected.value = photoCaptureResult.value.isPhotoDetected();
} catch (Throwable e) {
e.printStackTrace();
}
if (deviceAdminResult != null) {
if (deviceAdminResult.value != null) {
DeviceAdminResult res = deviceAdminResult.value;
if (deviceAdminPolicies != null)
deviceAdminPolicies.value = res.getPolicies();
if (deviceAdminUsed != null)
deviceAdminUsed.value = true;
isFromReflection.value = deviceAdminResult.value.isFromReflection() || photoCaptureResult.value.isFromReflection();
// No longer needed
deviceAdminResult = null;
}
}
}
});
if (deviceAdminDetectionTime != null)
deviceAdminDetectionTime.value = time;
}
});
}
boolean timedOut = false;
executor.shutdown();
try {
if (!executor.awaitTermination(ANALYSIS_TIMEOUT,
TimeUnit.SECONDS)) {
logger.warn("Analysis timed out");
executor.shutdownNow();
timedOut = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Check if encryption analysis timedout
timedOut = timedOut || encryptionDetectorTimedOut.value;
// Create JSON
try {
String fn = FilenameUtils.getBaseName(apkName);
File hashDirectory = new File(MainScanner.jsonDirectory,
fn + ".json");
OutputStream jsonWriter = new FileOutputStream(hashDirectory);
String json = MainScanner.buildResponseFromResults(
lockDetected.value,
lockStrategy.value,
hasRWPermission.value,
encryptionDetected.value,
photoCaptureDetected.value,
deviceAdminUsed.value,
deviceAdminPolicies.value,
isFromReflection.value,
textDetected.value,
languages.value);
jsonWriter.write(json.getBytes());
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
resultsWriter.write(String.format(
"%s; %b; %s; %b; %f; %s; %b; %b; %b; %b; %s; %s; \"%s\"; %b; %s\n",
apkName,
lockDetected.value,
lockStrategy.value,
textDetected.value.isAccepted(),
textDetected.value.getScore(),
languages.value,
hasRWPermission.value,
encryptionDetected.value,
photoCaptureDetected.value,
deviceAdminUsed.value,
deviceAdminPolicies.value,
isFromReflection.value,
textDetected.value.getComment(),
timedOut,
textDetected.value.getFileClassification()));
performancesWriter.write(
String.format("%s; %f; %f; %f; %f; %f; %d; %d; %d\n",
apkName,
lockDetectionTime.value,
textDetectionTime.value,
encryptionDetectionTime.value,
deviceAdminDetectionTime.value,
unpackingTime,
applicationData .getSmaliLoader()
.getClassesCount(),
applicationData .getSmaliLoader()
.getTotalClassesSize(),
applicationData .getDecodedPackage()
.getOriginalApk()
.length()));
resultsWriter.flush();
performancesWriter.flush();
} catch (IOException e) {
}
// No longer deleting temp files
if (!timedOut)
logger.info("Completed: " + apkName);
else {
print("Timeout");
if (textDetectionTime.value == ANALYSIS_TIMEOUT)
print(" TextDetection");
if (!noLock && (lockDetectionTime.value == ANALYSIS_TIMEOUT))
print(" LockDetection");
if (!noEncryption
&& (encryptionDetectionTime.value == ANALYSIS_TIMEOUT))
print(" EncryptionDetection");
print(": " + apkName);
}
}
private static String buildResponseFromResults(boolean lockDetected,
String lockStrategy,
boolean hasRWPermission, boolean encryptionDetected,
boolean photoCaptureDetected, boolean deviceAdminUsed,
List<Policy> policies, boolean isFromReflection, AcceptanceStrategy.Result textResult,
Set<String> languages) {
StringBuilder builder = new StringBuilder();
/*
* By default the decimal separator is a comma. This is wrong in JSON,
* since it expects a dot, so we need to use a DecimalFormat object.
*/
DecimalFormatSymbols symbols = new DecimalFormatSymbols(
Locale.getDefault());
symbols.setDecimalSeparator('.');
DecimalFormat formatter = new DecimalFormat();
formatter.setDecimalFormatSymbols(symbols);
builder.append("{\n");
builder.append(
String.format(" \"lockDetected\": %b,\n", lockDetected));
builder.append(
String.format(" \"lockStrategy\": \"%s\",\n", lockStrategy));
builder.append(String.format(" \"textDetected\": %b,\n",
textResult.isAccepted()));
builder.append(String.format(" \"textScore\": %s,\n",
formatter.format(textResult.getScore())));
builder.append(String.format(" \"languages\": %s,\n",
CollectionToJsonConverter.convert(languages)));
builder.append(String.format(" \"hasRWPermission\": %b,\n",
hasRWPermission));
builder.append(String.format(" \"encryptionDetected\": %b,\n",
encryptionDetected));
builder.append(String.format(" \"photoCaptureDetected\": %b,\n",
photoCaptureDetected));
builder.append(String.format(" \"deviceAdminUsed\": %b,\n",
deviceAdminUsed));
builder.append(String.format(" \"deviceAdminPolicies\": \"%s\",\n",
policies));
builder.append(String.format(" \"fromReflection\": %b,\n",
isFromReflection));
builder.append(String.format(" \"textComment\": \"%s\",\n",
textResult.getComment()));
builder.append(String.format(" \"suspiciousFiles\": \"%s\"\n",
textResult.getFileClassification()));
builder.append("}");
return builder.toString();
}
private static void closeWriters() throws IOException {
resultsWriter.close();
performancesWriter.close();
examinedFiles.dispose();
}
public static void restartApplication() {
synchronized (fileEnumerationFinishedLock) {
fileEnumerationFinished = true;
}
synchronized (availableFiles) {
availableFiles.clear();
}
synchronized (availableUnpackedData) {
availableUnpackedData.clear();
}
aborted = true; // not important to synchronize it
try {
closeWriters();
} catch (IOException e) {
e.printStackTrace();
}
try {
String javaBin = System.getProperty("java.home") + File.separator
+ "bin" + File.separator + "java";
// File currentJar = new File(Main.class .getProtectionDomain()
// .getCodeSource()
// .getLocation()
// .toURI());
File currentJar = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getFile());
List<String> commands = new ArrayList<String>();
commands.add(javaBin);
commands.add("-jar");
commands.add(currentJar.getPath());
for (int i = 0; i < mainArgs.length; i++)
commands.add(mainArgs[i]);
final ProcessBuilder builder = new ProcessBuilder(commands);
builder.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(-1);
}
}
// Maximum allowed number of unpacked applications that can reside as an
// ApplicationData class in memory
// When this number is reached, the unpacking thread waits for
// UNPACKING_WAIT_TIME before continuing
private static final int MAX_ALLOWED_UNPACKED_APKS_IN_MEMORY = 15;
private static final int UNPACKING_WAIT_TIME = 20; // seconds
private static final int ANALYSIS_WAIT_TIME = 20;
private static final int ANALYSIS_TIMEOUT = 210; // seconds
// Maximum number of times analysis can stall: beyond this, the program
// assumes the analysis thread has
// crashed and restarts
private static final int MAX_ANALYSIS_STALLS = 50;
private static final int MAX_UNPACKING_STALLS = 30;
private static int analysisStalls = 0;
private static int unpackingStalls = 0;
private static Object fileEnumerationFinishedLock = new Object();
private static Boolean fileEnumerationFinished = false;
private static Boolean aborted = false;
private static Boolean silentMode = false;
private static Boolean noLock = false;
private static Boolean noEncryption = false;
private static Boolean noTextDetection = false;
private static Boolean noDeviceAdminDetection = false;
private static PersistentFileList examinedFiles;
private static BufferedWriter resultsWriter;
private static BufferedWriter performancesWriter;
private static MultiLockingStrategy multiLockingStrategy;
private static MultiResourceScanner multiResourceScanner;
private static ImageScanner imageScanner;
private static EncryptionFlowDetector encryptionFlowDetector;
private static DeviceAdminDetector deviceAdminDetector;
private static PhotoDetector photoAdminDetector;
private static List<File> availableFiles;
private static List<ApplicationData> availableUnpackedData;
private static List<Double> unpackingTimes; // list of times required to
// unpack an apk
private static Thread fileEnumeratingThread, unpackingThread,
analysisThread;
private static String[] mainArgs;
}
| 25,324
| 29.329341
| 235
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/device_admin/Constants.java
|
package it.polimi.elet.necst.heldroid.ransomware.device_admin;
public interface Constants {
/* Files */
static final String ANDROID_MANIFEST_FILE = "AndroidManifest.xml";
/* Tags */
static final String RECEIVER_TAG = "receiver";
static final String META_DATA_TAG = "meta-data";
static final String DEVICE_ADMIN_TAG = "device-admin";
static final String USES_POLICIES_TAG = "uses-policies";
static final String USES_PERMISSION_TAG = "uses-permission";
static final String USES_PERMISSION_SDK_23_TAG = "uses-permission-sdk-23";
static final String APPLICATION_TAG = "application";
/* Attributes */
static final String PERMISSION_ATTRIBUTE = "android:permission";
static final String NAME_ATTRIBUTE = "android:name";
static final String RESOURCE_ATTRIBUTE = "android:resource";
/* Values */
static final String BIND_DEVICE_ADMIN_VALUE = "android.permission.BIND_DEVICE_ADMIN";
static final String DEVICE_ADMIN_VALUE = "android.app.device_admin";
/* Regex */
/**
* A regex for identifying Android xml file references, such as:
* {@code @[<package-name>:]<resource-type>/<resource-name>})
* This regex has 3 named groups:
* <ol>
* <li>{@code package}, that contains the optional package name</li>
* <li>{@code type}, that contains the resource type</li>
* <li>{@code name}, that contains the resource name</li>
* </ol>
*/
static final String RESOURCE_REGEX = "^\\@(?:(?<package>\\w+(?:\\.\\w+)*)(?::))?(?<type>\\w+)\\/(?<name>\\w+)$";
}
| 1,479
| 36.948718
| 113
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/device_admin/DeviceAdminDetector.java
|
package it.polimi.elet.necst.heldroid.ransomware.device_admin;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.APPLICATION_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.BIND_DEVICE_ADMIN_VALUE;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.DEVICE_ADMIN_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.DEVICE_ADMIN_VALUE;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.META_DATA_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.NAME_ATTRIBUTE;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.PERMISSION_ATTRIBUTE;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.RECEIVER_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.RESOURCE_ATTRIBUTE;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.RESOURCE_REGEX;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.USES_PERMISSION_SDK_23_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.USES_PERMISSION_TAG;
import static it.polimi.elet.necst.heldroid.ransomware.device_admin.Constants.USES_POLICIES_TAG;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.DeviceAdminResult.Policy;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.InstructionSimulator.Node;
import it.polimi.elet.necst.heldroid.ransomware.encryption.EncryptionFlowDetector;
import it.polimi.elet.necst.heldroid.utils.CFGUtils;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import it.polimi.elet.necst.heldroid.utils.Xml;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.infoflow.cfg.SharedCfg;
import soot.jimple.infoflow.problems.conditions.BreadthFirstSearch;
import soot.jimple.infoflow.problems.conditions.ConstantDeclarationFinder;
import soot.jimple.infoflow.problems.conditions.DeclarationFinder;
import soot.jimple.infoflow.problems.conditions.SootClassUtil;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
/**
* This class analyzes an APK file in order to discover if the app uses Android
* Device Administrator API.
*
* @author Nicola Dellarocca
*
*/
public class DeviceAdminDetector {
/*
***********************************************
* Please note the static import for constants *
***********************************************
*/
// Resource files are like: @type/file_name
private static final Pattern POLICIES_FILE_REGEX = Pattern.compile(
RESOURCE_REGEX);
private DecodedPackage mTarget;
private DocumentBuilderFactory mDbFactory;
private DocumentBuilder mDb;
private IInfoflowCFG mCfg;
/**
* Creates a {@code DeviceAdminDetector} instance
*
* @throws ParserConfigurationException
* if it is not possible to create an XML parser for the
* AndroidManifest.xml file.
*/
public DeviceAdminDetector() throws ParserConfigurationException {
this.mDbFactory = DocumentBuilderFactory.newInstance();
this.mDb = mDbFactory.newDocumentBuilder();
}
/**
* Scans the AndroidManifest.xml file to discover if the app uses the
* {@link Constants#BIND_DEVICE_ADMIN_VALUE} permission.
*
* @param manifest
* The manifest in which the permission will be searched.
* @return <code>true</code> if the manifest contains such permission,
* <code>false</code> otherwise.
*/
private boolean findDeviceAdminPermission(Document manifest) {
Element root = manifest.getDocumentElement();
// First search inside <uses-permission> tags
Collection<Element> usesPermissionTags = Xml.getElementsByTagName(root,
USES_PERMISSION_TAG);
for (Element usesPermissionTag : usesPermissionTags) {
if (usesPermissionTag.hasAttribute(NAME_ATTRIBUTE)
&& usesPermissionTag.getAttribute(NAME_ATTRIBUTE)
.equals(BIND_DEVICE_ADMIN_VALUE)) {
return true;
}
}
// GC
usesPermissionTags = null;
// Now look inside <uses-permission-sdk-23> tags
Collection<Element> usesPermission23Tags = Xml.getElementsByTagName(
root, USES_PERMISSION_SDK_23_TAG);
for (Element usesPermission23Tag : usesPermission23Tags) {
if (usesPermission23Tag.hasAttribute(NAME_ATTRIBUTE)
&& usesPermission23Tag .getAttribute(NAME_ATTRIBUTE)
.equals(BIND_DEVICE_ADMIN_VALUE)) {
return true;
}
}
usesPermission23Tags = null;
// Now look inside the <application> tag
Element application = Xml.getChildElement(root, APPLICATION_TAG);
if (application.hasAttribute(PERMISSION_ATTRIBUTE)
&& application .getAttribute(PERMISSION_ATTRIBUTE)
.equals(BIND_DEVICE_ADMIN_VALUE)) {
return true;
}
application = null;
// Then look inside <receiver> tag
Collection<Element> receivers = Xml.getElementsByTagName(root,
RECEIVER_TAG);
for (Element receiver : receivers) {
if (receiver.hasAttribute(PERMISSION_ATTRIBUTE)
&& receiver .getAttribute(PERMISSION_ATTRIBUTE)
.equals(BIND_DEVICE_ADMIN_VALUE)) {
return true;
}
// Also look inside <meta-data> for such permission
Element metadata = Xml.getChildElement(receiver, META_DATA_TAG);
if (metadata != null) {
if (metadata.hasAttribute(PERMISSION_ATTRIBUTE)
&& metadata .getAttribute(PERMISSION_ATTRIBUTE)
.equals(BIND_DEVICE_ADMIN_VALUE)) {
return true;
}
}
}
return false;
}
/**
* Scans the Android Manifest to (possibly) find the resource containing
* Device Administrator policies.
*
* @return The string identifying an Android resource (in the form
* {@code @<type>/<file_name>} or {@code null}, if the Manifest does
* not contain such reference.
*/
private String findDeviceAdminPoliciesFile() {
try {
Document document = mDb.parse(mTarget.getAndroidManifest());
Element root = document.getDocumentElement();
Collection<Element> receivers = Xml.getElementsByTagName(root,
RECEIVER_TAG);
boolean hasDeviceAdminPermission = findDeviceAdminPermission(
document);
if (!hasDeviceAdminPermission) {
return null;
}
/*
* At this point the manifest contains such permission. We need to
* find the receiver that contains the appropriate <meta-data> child
* (i.e. that contains the device admin policies file reference)
*/
for (Element receiver : receivers) {
// Get <meta-data> child
Element metadata = Xml.getChildElement(receiver, META_DATA_TAG);
if (metadata != null) {
if (metadata.hasAttribute(NAME_ATTRIBUTE)
&& metadata .getAttribute(NAME_ATTRIBUTE)
.equals(DEVICE_ADMIN_VALUE)) {
if (metadata.hasAttribute(RESOURCE_ATTRIBUTE)) {
return metadata.getAttribute(RESOURCE_ATTRIBUTE);
}
}
}
}
} catch (Exception e) {
System.err.println("Exception: " + e);
}
return null;
}
/**
* Parses {@code policiesFile} trying to extract all (known) policies.
*
* See {@link DeviceAdminResult.Policy} for the list of currently supported
* policies.
*
* @param policiesFile
* @return A wrapper for {@link DeviceAdminResult} object. The wrapper will
* never be {@code null}.
*/
private Wrapper<DeviceAdminResult> parseDeviceAdminPoliciesFile(
File policiesFile) {
// Holds the result
DeviceAdminResult result = null;
// Perform checks only if policies file exists
if (policiesFile.exists()) {
try {
Document document = mDb.parse(policiesFile);
Element root = document.getDocumentElement();
// It must start wit <device-admin> tag
if (root.getTagName()
.equals(DEVICE_ADMIN_TAG)) {
// This app makes use of <device-admin>
result = new DeviceAdminResult();
result.setDeviceAdminUsed(true);
// This tag's child are the policies
Element usesPolicies = Xml.getChildElement(root,
USES_POLICIES_TAG);
if (usesPolicies != null) {
// Will contain a list of policies
List<Element> policies = Xml.getChildElements(
usesPolicies);
if (policies.size() > 0) {
// Add all policies to result
for (Element policy : policies) {
// Try to parse policies, otherwise skip them
try {
Policy p = Policy.parseString(
policy.getTagName());
result.addPolicy(p);
} catch (Exception e) {
System.err.println(
"Skipping unknown policy: "
+ policy);
}
}
}
}
}
} catch (Exception e) {
System.err.println("Exception: " + e);
return new Wrapper<DeviceAdminResult>(null);
}
}
return new Wrapper<DeviceAdminResult>(result);
}
/**
* Creates the CFG. If reuseCfg is set to <code>true</code>, it will reuse
* the CFG created by someone else, otherwise it will create a brand new
* one.
*
* Please note that this class will wait until someone else creates the CFG,
* so <b>it might wait forever if no one creates the CFG</b>.
*
* @param reuseCfg
* If <code>true</code> it will wait until someone else creates
* the CFG, otherwise it will create a new CFG by itself.
*/
private void createCfg(boolean reuseCfg) {
if (reuseCfg) {
mCfg = SharedCfg.waitForCfg();
} else {
mCfg = CFGUtils.createCfg(mTarget);
// /*
// * We will generate the CFG using the latest android version
// * available on the platform.
// */
// File libPath = Globals.getLatestAndroidVersion();
// if (libPath == null)
// libPath = Globals.ANDROID_PLATFORMS_DIRECTORY;
//
// // A new setup application is required to create the CFG
// SetupApplication app = new SetupApplication(
// libPath.getAbsolutePath(), mTarget .getOriginalApk()
// .getAbsolutePath());
//
// app.getConfig().setIgnoreFlowsInSystemPackages(false);
// try {
// app.calculateSourcesSinksEntrypoints("SourcesAndSinks.txt");
//
// // Configure Soot
// soot.G.reset();
//
// Options .v()
// .set_src_prec(Options.src_prec_apk);
// Options .v()
// .set_process_dir(Collections.singletonList(
// mTarget .getOriginalApk()
// .getAbsolutePath()));
// Options .v()
// .set_force_android_jar(libPath.getAbsolutePath());
// Options .v()
// .set_whole_program(true);
// Options .v()
// .set_allow_phantom_refs(true);
// Options .v()
// .set_output_format(Options.output_format_jimple);
// Options .v()
// .setPhaseOption("cg.spark", "on");
//
// Scene .v()
// .loadNecessaryClasses();
//
// SootMethod dummyMain = app .getEntryPointCreator()
// .createDummyMain();
// // The dummy main is the starting point
// Options .v()
// .set_main_class(dummyMain.getSignature());
//
// // Share the dummy main
// Scene .v()
// .setEntryPoints(Collections.singletonList(dummyMain));
//
// System.out.println(dummyMain.getActiveBody());
//
// PackManager .v()
// .runPacks();
//
// DefaultBiDiICFGFactory factory = new DefaultBiDiICFGFactory();
// mCfg = factory.buildBiDirICFG(CallgraphAlgorithm.OnDemand,
// false);
//
// System.out.println(dummyMain.getActiveBody());
// // List<SootMethod> entryPoints = Scene.v().getEntryPoints();
//// printCfg(entryPoints.get(0));
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
/**
* Prints all CFG nodes in stdout in a breadth-first way.
*
* @param startPoint
* The node from which to start the CFG exploration.
*/
private void printCfg(SootMethod startPoint) {
Deque<Unit> stack = new LinkedList<>();
HashSet<Unit> visited = new HashSet<>();
stack.addAll(mCfg.getStartPointsOf(startPoint));
while (!stack.isEmpty()) {
Unit node = stack.pop();
if (visited.contains(node))
continue;
visited.add(node);
System.out.println(node);
System.out.println("*** " + mCfg.getSuccsOf(node));
stack.addAll(mCfg.getSuccsOf(node));
if (mCfg.isCallStmt(node)) {
Collection<SootMethod> callees = mCfg.getCalleesOfCallAt(node);
for (SootMethod callee : callees) {
stack.addAll(mCfg.getStartPointsOf(callee));
}
}
}
}
/**
* Scans the APK trying to discover if the app makes use of Android Device
* Administrator API.
*
* @param reuseCfg
* Whether the detector should reuse the CFG that has been
* generated by someone else (e.g. the
* {@link EncryptionFlowDetector}).
*
* @return a wrapper containing a {@link DeviceAdminResult} object. The
* wrapper will never be {@code null}. If the app does not use the
* Device Administrator API, the result will be a wrapper for a
* {@code null} object (i.e. {@code wrapper.value} will be
* {@code null}.
* @throws IllegalStateException
* if a {@link #setTarget(DecodedPackage) target} is not set or
* the CFG cannot be built
*/
public Wrapper<DeviceAdminResult> detect(boolean reuseCfg)
throws IllegalStateException {
if (mTarget == null) {
throw new IllegalStateException("Target is not set");
}
// First of all create the CFG. It will be used later
createCfg(reuseCfg);
if (this.mCfg == null)
throw new IllegalStateException("Cannot create the CFG");
String deviceAdminPoliciesFile = findDeviceAdminPoliciesFile();
/*
* If no device admin policies file is found, we have nothing to do
*/
if (deviceAdminPoliciesFile != null) {
Matcher matcher = POLICIES_FILE_REGEX.matcher(
deviceAdminPoliciesFile);
if (matcher.matches()) {
// This file should always be in XML folder
File targetDirectory = new File(mTarget.getResourcesDirectory(),
"xml");
if (targetDirectory.exists() && targetDirectory.isDirectory()) {
// Get the name of the policies file, if it exists
final String fileName = matcher.group("name");
if (fileName != null && fileName.length() > 0) {
/*
* If such file exists, let's search it in /res
* subfolders
*/
FilenameFilter filter = new FilenameFilter() {
/*
* Some files have no extension, so let's check both
* with and without .xml extension
*/
@Override
public boolean accept(File dir, String name) {
// Some APKs do not add the .xml extension
String regex = "^" + fileName + "(\\.\\w+)?$";
return name.matches(regex);
}
};
// Search it
List<File> matchingFiles = FileSystem.listFilesRecursively(
mTarget.getResourcesDirectory(), filter);
/*
* Should never happen, since a device admin policies
* file is specified in the AndroidManifest
*/
if (matchingFiles.size() == 0) {
System.err.println(
"Error: policies file not found in res subfolders");
return new Wrapper<DeviceAdminResult>(null);
}
// File policiesFile = new File(xmlDirectory, fileName);
File policiesFile = matchingFiles.get(0);
Wrapper<DeviceAdminResult> result = parseDeviceAdminPoliciesFile(
policiesFile);
// It should never be null, since we've just created it!
if (result != null && result.value != null
&& result.value.getPolicies() != null) {
// Loop over supported policies only
for (Policy policy : Policy.getSupportedPolicies()) {
/*
* If policy is not present in policies file,
* don't waste time
*/
if (!result.value .getPolicies()
.contains(policy)) {
continue;
}
/*
* Check if the policy is actually used in the
* code
*/
PolicyUsage usage = isPolicyUsed(policy);
/*
* If it is not used, remove it from the list of
* used policies
*/
if (usage == PolicyUsage.NONE) {
System.out.printf(
"Policy %S is not used. Removing it...\n",
policy.name());
result.value.getPolicies()
.remove(policy);
} else {
System.out.printf("Policy %S is used!!\n",
policy.name());
// Update result accordingly to usage type
if (usage == PolicyUsage.REFLECTION) {
result.value.setFromReflection(true);
}
}
}
}
return result;
}
}
}
}
// If we reach this point it means that no policy is found
return new Wrapper<DeviceAdminResult>(null);
}
// /**
// * Checks if the {@code policy} is actually used inside the smali code.
// This
// * check is performed by looking for dangerous method calls inside any of
// * the smali files of the app referenced by the {@code target} instance
// * variable.
// *
// * Please note that the currently supported policies are only
// * {@link Policy#USES_POLICY_WIPE_DATA} and
// * {@link Policy#USES_POLICY_RESET_PASSWORD}.
// *
// * @param policy
// * The policy to test
// * @return {@code true} if the code contains such method calls,
// * {@code false} otherwise.
// */
// private boolean isPolicyUsed(Policy policy) {
// if (policy == null) {
// throw new IllegalArgumentException(
// "You must provide a valid policy");
// }
//
// String regex = null;
//
// switch (policy) {
// case USES_POLICY_WIPE_DATA:
// // Look for methods: DevicePolicyManager.wipeData(int)
// regex =
// "^.*Landroid/app/admin/DevicePolicyManager;->wipeData\\(I\\)V.*$";
// break;
//
// case USES_POLICY_RESET_PASSWORD:
// // Look for methods: DevicePolicyManager.resetPassword(String, int)
// regex =
// "^.*Landroid/app/admin/DevicePolicyManager;->resetPassword\\(Ljava/lang/String;I\\)Z.*$";
// break;
//
// default:
// throw new IllegalArgumentException(
// "This policy is not supported yet.");
// }
//
// File smaliDirectory = mTarget.getSmaliDirectory();
//
// return FileSystem.searchRecursively(smaliDirectory, regex);
// }
private enum PolicyUsage {
NONE,
METHOD_CALL,
REFLECTION
}
/**
* Searches if the policy is used (directly or through reflection).
*
* @param policy
* The policy to check.
* @return <code>true</code> if the policy is used, <code>false</code>
* otherwise.
*
*/
private PolicyUsage isPolicyUsed(final Policy policy) {
if (policy == null) {
throw new IllegalArgumentException(
"You must provide a valid policy");
}
if (!policy.isSupported()) {
throw new IllegalArgumentException(
"This policy is not supported yet");
}
if (this.mCfg == null) {
throw new IllegalStateException("CFG is null");
}
/*
* Search if one of the methods related to the policy is call either
* directly or through reflection.
*/
if (searchRelatedMethod(policy)) {
return PolicyUsage.METHOD_CALL;
}
/*
* Otherwise search for reflection usage
*/
if (searchReflection(policy.getRelatedMethods(),
RefType.v("android.app.admin.DevicePolicyManager"))) {
return PolicyUsage.REFLECTION;
}
return PolicyUsage.NONE;
}
/**
* Searches for methods invocation through reflection and return a boolean
* indicating if they have been found.
*
* @param relatedMethods
* The collection of methods we are interested in (i.e. of which
* we want to discover invocations). It must contain at least 1
* element.
* @param enforceTargetType
* The type of the target object (i.e. the type of object on
* which the method will be invoked). It can be <code>null</code>
* if you don't care about its type.
* @return <code>true</code> if any reflection method invocations is found,
* otherwise <code>false</code>.
*/
private boolean searchReflection(ArrayList<String> relatedMethods,
final RefType enforceTargetType) {
if (relatedMethods == null || relatedMethods.isEmpty()) {
throw new IllegalArgumentException(
"You must provide at least one related method");
}
BreadthFirstSearch<Unit> searcher = new BreadthFirstSearch<Unit>(mCfg) {
@Override
protected Collection<Unit> nextNodes(Unit current) {
Collection<Unit> result = new HashSet<>(0);
// Add successors
result.addAll(cfg.getSuccsOf(current));
// If this is a method call, add callee's start points
if (cfg.isCallStmt(current)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
current);
for (SootMethod callee : callees) {
result.addAll(cfg.getStartPointsOf(callee));
}
}
return result;
}
@Override
protected boolean isResult(Unit node) {
/*
* If it's not a method call then it is not a valid result.
*/
if (cfg.isCallStmt(node)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
node);
/*
* Obtain the InvokeExpression to get details of method
* invocation.
*/
InvokeExpr ie = ((Stmt) node).getInvokeExpr();
/*
* This method must have exactly 2 args, otherwise it is the
* wrong method. The args are: 1: Target object 2: Array of
* arguments
*/
if (ie.getArgCount() != 2) {
return false;
}
/*
* Usually there's only 1 callee, but IInfoflowCFG returns a
* collection...
*/
for (SootMethod callee : callees) {
// Get the invoked method's class
SootClass declClass = callee.getDeclaringClass();
// Check the target's type
if (enforceTargetType != null
&& !enforceTargetType.equals(ie .getArg(0)
.getType())) {
return false;
}
/*
* Check that the invoked method is
* java.lang.reflect.Method->invoke
*/
if (callee .getName()
.equals("invoke")
&& SootClassUtil.isOrExtendsClass(declClass,
Method.class)) {
return true;
}
}
}
// If we reach this point it means that no method is found.
return false;
}
};
// Get dummy main entry points
List<SootMethod> entryPoints = Scene.v()
.getEntryPoints();
List<Unit> startPoints = new ArrayList<>();
for (SootMethod entryPoint : entryPoints) {
startPoints.addAll(mCfg.getStartPointsOf(entryPoint));
}
// For each entry point let's perform a search
Set<Unit> results = new HashSet<>(0);
for (Unit start : startPoints) {
results.addAll(searcher.search(start, false));
}
/*
* If there is at least 1 result search for relatedMethods, otherwise
* return null;
*/
if (results.isEmpty()) {
return false;
}
/*
* Find the declaration (i.e. variable assignment) for the method that
* is invoked through reflection. In other words we want to find an
* instruction like:
*
* java.lang.Method object = <whatever>
*/
Set<Unit> methodSearched = null;
for (Unit methodInvocation : results) {
Value reflectionMethodLocal = ((InstanceInvokeExpr) ((Stmt) methodInvocation).getInvokeExpr()).getBase();
DeclarationFinder finder = new DeclarationFinder(mCfg,
reflectionMethodLocal);
methodSearched = finder.search(methodInvocation, true);
}
/*
* The assignment must exist somewhere in the code. Check if we were
* able to find it
*/
if (methodSearched == null || methodSearched.isEmpty()) {
return false;
}
/*
* Here we want to check if the method invoked through reflection is one
* of the relatedMethods.
*/
try {
/*
* The set of names of those methods that are invoked through
* reflection
*/
Set<String> names = findHardcodedMethodName(methodSearched,
relatedMethods);
System.out.println("*** Related methods = " + relatedMethods);
System.out.println("*** HarcodedMethodNames = " + names);
// Check if at least one related method is contained inside the set
// for (String relatedMethod : relatedMethods) {
// if (names.contains(relatedMethod))
// return true;
// }
for (String name : names) {
if (relatedMethods.contains(
enforceTargetType.getClassName() + "->" + name)) {
return true;
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Navigates the CFG backwards looking for hardcoded strings related to
* methods invoked through reflection.
*
* @param reflectionMethodInvokes
* @param methodsToFind
* The array of methods to find. It must contain at least one
* element. The format of the string should be the following:
*
* <pre>
* {@code <declaring_class>-><method_name>(<params_type>)}
* </pre>
*
* for instance:
*
* <pre>
* {@code java.lang.String->substring(int,int)}
* </pre>
*
* @return
*/
private Set<String> findHardcodedMethodName(
Set<Unit> reflectionMethodInvokes,
ArrayList<String> methodsToFind) {
for (Unit reflectionMethodInvoke : reflectionMethodInvokes) {
if (reflectionMethodInvoke instanceof AssignStmt
&& mCfg.isCallStmt(reflectionMethodInvoke)) {
AssignStmt assignStmt = (AssignStmt) reflectionMethodInvoke;
InvokeExpr ie = assignStmt.getInvokeExpr();
System.out.println(
"****** " + assignStmt + " -> " + ie.getArg(0)
.getType());
// Ensure that the first parameter is of type String
if (!ie .getArg(0)
.getType()
.equals(RefType.v("java.lang.String"))) {
return null;
}
// Find method name
// findMethodNameReflection(iie.getBase(), callStmt);
ConstantDeclarationFinder finder = new ConstantDeclarationFinder(
mCfg, ie.getArg(0));
Set<Unit> constantDeclarations = finder.search(assignStmt,
true);
System.out.println(
"*** Constant decL = " + constantDeclarations);
Set<String> extractedHardcodedNames = new HashSet<>(0);
for (Unit constantDeclaration : constantDeclarations) {
if (constantDeclaration instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) constantDeclaration;
Value methodName = assign.getRightOp();
String extractedString = extractString(methodName,
constantDeclaration);
InstructionSimulator simulator = new InstructionSimulator(
mCfg, constantDeclaration,
reflectionMethodInvoke);
Set<InstructionSimulator.Node> nodes = simulator.search(
new InstructionSimulator.Node(extractedString,
constantDeclaration),
true);
for (Node n : nodes) {
extractedHardcodedNames.add(n.getValue());
}
return extractedHardcodedNames;
} else if (constantDeclaration instanceof InvokeStmt) {
InvokeExpr ie2 = ((InvokeStmt) constantDeclaration).getInvokeExpr();
for (int i = 0; i < ie2.getArgCount(); i++) {
Value argument = ie2.getArg(i);
if (argument instanceof StringConstant) {
InstructionSimulator simulator = new InstructionSimulator(
mCfg, constantDeclaration,
reflectionMethodInvoke);
Set<Node> nodes = simulator.search(
new InstructionSimulator.Node(
((StringConstant) argument).value,
constantDeclaration),
true);
for (Node n : nodes)
extractedHardcodedNames.add(n.getValue());
return extractedHardcodedNames;
}
}
} else {
throw new Error("Cannot retrieve hardcoded value");
}
return extractedHardcodedNames;
}
}
}
return null;
}
/**
* Extracts the string from a value (a {@link StringConstant} or a variable
* that can be resolved to a String), if possible.
*
* @param value
* The value from which the string should be extracted.
* @param usageNode
* The node in which the provided value is used (i.e. the
* starting point for a backwards analysis).
* @return The extracted string, if possible, otherwise <code>null</code>.
*/
private String extractString(Value value, Unit usageNode) {
if (value instanceof StringConstant) {
return ((StringConstant) value).value;
}
if (value .getType()
.equals(RefType.v("java.lang.String"))) {
/*
* Here we should look for the string definition and, if there is
* any transformation to the string (e.g. "replace" or
* "replaceAll"), apply it to get the final String.
*
* Finally we should return it, if we can find it, otherwise return
* null.
*/
ConstantDeclarationFinder finder = new ConstantDeclarationFinder(
mCfg, value);
Set<Unit> declarations = finder.search(usageNode, true);
if (declarations.isEmpty()) {
/*
* We didn't succeed in finding the declaration. Return null.
*/
return null;
}
for (Unit declaration : declarations) {
/*
* It is safe, since ConstantDeclarationFinder returns only
* AssignStmts
*/
AssignStmt assign = (AssignStmt) declaration;
/*
* It is safe, since ConstantDeclarationFinder returns only
* assignment of constants
*/
Constant rightOp = (Constant) assign.getRightOp();
/*
* If the constant is a string, simulate its possible
* transformations
*/
if (rightOp instanceof StringConstant) {
String raw = ((StringConstant) rightOp).value;
// simulateTransformations(raw, declaration, usageNode);
}
// Otherwise return null
return null;
}
}
System.out.println("Cannot extract type: " + value.getType());
return null;
}
private boolean searchRelatedMethod(final Policy policy) {
// We will perform a BFS looking for methods related to the policy.
BreadthFirstSearch<Unit> searcher = new BreadthFirstSearch<Unit>(mCfg) {
@Override
protected Collection<Unit> nextNodes(Unit current) {
Collection<Unit> result = new ArrayList<>();
// Skip system classes
// if
// (SystemClassHandler.isClassInSystemPackage(cfg.getMethodOf(current).getDeclaringClass().getName()))
// return new ArrayList<>(0);
// Add successors
result.addAll(this.cfg.getSuccsOf(current));
// Add all called methods, if they exists
if (this.cfg.isCallStmt(current)) {
Collection<SootMethod> callees = this.cfg.getCalleesOfCallAt(
current);
for (SootMethod callee : callees) {
result.addAll(this.cfg.getStartPointsOf(callee));
}
}
return result;
}
@Override
protected boolean isResult(Unit node) {
boolean result = false;
if (node instanceof Stmt && ((Stmt) node).containsInvokeExpr())
result = isRelatedUnit(node, policy);
return result;
}
};
// Get dummy main entry points
List<SootMethod> entryPoints = Scene.v()
.getEntryPoints();
List<Unit> startPoints = new ArrayList<>();
for (SootMethod entryPoint : entryPoints) {
startPoints.addAll(mCfg.getStartPointsOf(entryPoint));
}
Set<Unit> results = new HashSet<>(0);
for (Unit start : startPoints) {
results.addAll(searcher.search(start, false));
}
return results.size() > 0;
}
/**
* Sets the APK file to scan.
*
* @param target
* The target for the APK to scan.
*/
public void setTarget(DecodedPackage target) {
this.mTarget = target;
}
/**
* Checks whether an {@link InvokeExpr} contains a call to a method that is
* related to the specified {@link Policy}.
*
* @param node
* The node containing a method call.
* @param policy
* The policy to check.
* @return <code>true</code> if the method call is related to the policy,
* <code>false</code> otherwise.
*/
protected boolean isRelatedUnit(Unit node, final Policy policy) {
if (mCfg.isCallStmt(node)) {
Collection<SootMethod> calledMethods = mCfg.getCalleesOfCallAt(
node);
for (SootMethod calledMethod : calledMethods) {
if (policy.isMethodRelated(calledMethod))
return true;
}
}
return false;
}
}
| 32,916
| 29.506951
| 108
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/device_admin/InstructionSimulator.java
|
/**
*
*/
package it.polimi.elet.necst.heldroid.ransomware.device_admin;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import soot.PrimType;
import soot.RefType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.LongConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.infoflow.problems.conditions.BreadthFirstSearch;
import soot.jimple.infoflow.problems.conditions.ValueUtil;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
/**
* This abstract class simulates the execution of instructions on a variable
* thanks to reflection.
*
* @author Nicola Dellarocca
*
* @param <Type>
* The type of the {@link Value}.
*/
public class InstructionSimulator
extends BreadthFirstSearch<InstructionSimulator.Node> {
protected Unit startNode;
protected Unit endNode;
/**
* @param cfg
*/
public InstructionSimulator(IInfoflowCFG cfg, Unit startNode,
Unit endNode) {
super(cfg);
this.startNode = startNode;
this.endNode = endNode;
}
public static class Node {
private String value;
private Unit unit;
/**
* Convenience constructor
*/
public Node(String value, Unit node) {
this.value = value;
this.unit = node;
}
/**
* @return the node
*/
public Unit getNode() {
return unit;
}
/**
* @param node
* the node to set
*/
public void setNode(Unit node) {
this.unit = node;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value
* the value to set
*/
public void setValue(String value) {
this.value = value;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return unit+"->"+value;
}
}
/**
* {@inheritDoc}
*/
@Override
protected Collection<InstructionSimulator.Node> nextNodes(
InstructionSimulator.Node current) {
Set<Node> result = new HashSet<>();
/*
* If this is a method call we need to check the callee. If it is a
* String transformation method we will apply it, otherwise we will
* inspect successors
*/
if (cfg.isCallStmt(current.unit)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
current.unit);
for (SootMethod callee : callees) {
/*
* If it calls a String transformation method, then apply it
*/
if (callee .getDeclaringClass()
.getName()
.equals(current.value .getClass()
.getName())) {
InvokeExpr ie = ((Stmt) current.unit).getInvokeExpr();
// Extract params
Object[] invokeArgs = new Object[ie.getArgCount()];
for (int i=0; i<invokeArgs.length; i++) {
Value arg = ie.getArg(i);
invokeArgs[i] = ValueUtil.extractValue(arg);
}
// Assign to the node the new value
current.value = applyTransformation(current.value, callee, invokeArgs);
} else {
for (Unit startPoint : cfg.getStartPointsOf(callee)) {
result.add(new Node(current.value, startPoint));
}
}
}
}
// Add all successors
for (Unit succ : cfg.getSuccsOf(current.unit)) {
result.add(new Node(current.value, succ));
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean isResult(InstructionSimulator.Node node) {
return node.unit.equals(endNode);
}
/**
* Applies the transformation to the current value and returns the
* transformed value.
*
* @param currentValue
* @param transformation
* @return
*/
protected String applyTransformation(String currentValue,
SootMethod transformation, Object[] values) {
// Ignore constructor
if (transformation.getName().equals("<init>")) {
return currentValue;
}
Class<?> clazz = String.class;
Class<?>[] paramValues = new Class<?>[transformation.getParameterCount()];
try {
for (int i = 0; i < paramValues.length; i++) {
Type t = transformation.getParameterType(i);
String className = null;
if (t instanceof PrimType) {
className = ((PrimType) t) .boxedType()
.getClassName();
} else if (t instanceof RefType) {
className = ((RefType) t).getClassName();
}
if (className == null) {
throw new IllegalArgumentException(
"Cannot detect parameter types for: "
+ transformation);
}
if (className.equals("java.lang.Integer")) {
paramValues[i] = int.class;
} else {
paramValues[i] = Class.forName(className);
}
}
System.out.println("*** Invoking "+transformation.getName()+" with params: "+Arrays.toString(paramValues)+" on value: "+currentValue);
Method method = clazz.getDeclaredMethod(transformation.getName(), paramValues);
Object result = method.invoke(currentValue, values);
System.out.println("*** -> RESULT = "+result);
if (result instanceof String) {
return (String) result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 5,182
| 22.138393
| 137
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/device_admin/DeviceAdminResult.java
|
package it.polimi.elet.necst.heldroid.ransomware.device_admin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import soot.BooleanType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.RefType;
import soot.ShortType;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
/**
* This class is a container for all the currently available Android Device
* Administrator policies.
*
* @author Nicola Dellarocca
*
*/
public class DeviceAdminResult {
/**
* All policies currently implemented in Android.
*
* @author Nicola Dellarocca
*
*/
public enum Policy {
USES_ENCRYPTED_STORAGE(null),
USES_POLICY_DISABLE_CAMERA(null),
USES_POLICY_DISABLE_KEYGUARD_FEATURES(null),
USES_POLICY_EXPIRE_PASSWORD(null),
USES_POLICY_FORCE_LOCK(null),
USES_POLICY_LIMIT_PASSWORD(null),
USES_POLICY_RESET_PASSWORD(new String[] {
"android.app.admin.DevicePolicyManager->resetPassword" }),
USES_POLICY_WATCH_LOGIN(null),
USES_POLICY_WIPE_DATA(new String[] {
"android.app.admin.DevicePolicyManager->wipeData" });
/**
* The regex that related methods <b>must</b> satisfy.
*/
public static final String REGEX = "(.+?)->(.+?)";
private String[] relatedMethods;
private Policy(String[] relatedMethodNames) {
this.relatedMethods = relatedMethodNames;
}
/**
* Whether the current policy is supported (i.e. if it has at least one
* related method).
*
* @return <code>true</code> if it is supported, <code>false</code>
* otherwise.
*/
public boolean isSupported() {
return this.relatedMethods != null
&& this.relatedMethods.length > 0;
}
/**
* Returns an array containing all the supported policies. If no policy
* is supported, the array will be empty. It is guaranteed that the
* result will never be <code>null</code>.
*
* @return The supported policies, or an empty array if no policy is
* supported.
*/
public static Policy[] getSupportedPolicies() {
List<Policy> supportedPolicies = new ArrayList<>();
for (Policy policy : Policy.values()) {
if (policy.isSupported())
supportedPolicies.add(policy);
}
return supportedPolicies.toArray(
new Policy[supportedPolicies.size()]);
}
/**
* Checks whether the provided method is related to this policy. Please
* note that the method <b>must</b> respect the format:
*
* <pre>
* {@code <declaring_class>-><method_name>}
* </pre>
*
* for instance:
*
* <pre>
* {@code java.lang.String->substring}
* </pre>
*
* @param method
* The method to check.
* @return <code>true</code> if the method is related to this policy,
* <code>false</code> otherwise.
*/
public boolean isMethodRelated(SootMethod method) {
if (method == null) {
throw new IllegalArgumentException("Method must be non null");
}
if (this.relatedMethods == null)
throw new IllegalStateException("Policy not supported yet");
SootClass declClass = method.getDeclaringClass();
StringBuilder builder = new StringBuilder(declClass.getName());
builder.append("->");
builder.append(method.getName());
// builder.append('(');
//
// int nParams = method.getParameterCount();
//
// // Add params type
// for (int i=0; i<nParams; i++) {
// Type type = method.getParameterType(i);
//
// if (type instanceof RefType) {
// builder.append(((RefType) type).getClassName());
// } else if (type instanceof IntType) {
// builder.append("int");
// } else if (type instanceof LongType) {
// builder.append("long");
// } else if (type instanceof BooleanType) {
// builder.append("boolean");
// } else if (type instanceof FloatType) {
// builder.append("float");
// } else if (type instanceof DoubleType) {
// builder.append("double");
// } else if (type instanceof ShortType) {
// builder.append("short");
// } else {
// throw new IllegalArgumentException("Cannot determine the type of params");
// }
//
// builder.append(',');
// }
//
// if (nParams > 0) {
// // Remove trailing comma
// builder.setLength(builder.length()-1);
// }
//
// builder.append(')');
String methodString = builder.toString();
for (String relatedMethod : relatedMethods) {
if (relatedMethod.equals(methodString)) {
return true;
}
}
return false;
}
/**
* Returns the methods related to this policy. Please note that it could
* be <code>null</code> if the policy is not supported.
*
* @see Policy#isSupported();
*
* @return The array of related methods (with length ≥ 1) or
* <code>null</code> if the policy is not supported.
*/
public ArrayList<String> getRelatedMethods() {
return new ArrayList<String>(Arrays.asList(relatedMethods));
}
/**
* Returns the AndroidManifest entry equivalent to this policy.
*
* @return The Android Manifest entry equivalent to this policy (e.g.
* {@link #USES_ENCRYPTED_STORAGE} inside the manifest is
* represented by the string "encrypted-storage").
*/
public String getManifestEntry() {
String result = this.name()
.toLowerCase();
result = result .replace("USES_", "")
.replace("POLICY_", "")
.replaceAll("_", "-");
return result;
}
/**
* Tries to parse a string and convert it to one of the possible values
* of {@link Policy}.
*
* @param policy
* The string to parse.
* @return The corresponding {@link Policy}.
* @throws IllegalStateException
* if the specified enum type has no constant with the
* specified name.
* @throws NullPointerException
* if {@code policy} is {@code null}.
*/
public static Policy parseString(String policy)
throws IllegalStateException, NullPointerException {
policy = policy .toUpperCase()
.replaceAll("-", "_");
if (policy.equals("ENCRYPTED_STORAGE")) {
policy = "USES_" + policy;
} else {
policy = "USES_POLICY_" + policy;
}
return Policy.valueOf(policy);
}
}
private List<Policy> policies;
private boolean deviceAdminUsed;
private boolean isFromReflection;
/**
* Creates an empty instance.
*/
public DeviceAdminResult() {
this.policies = new LinkedList<>();
}
/**
* Creates an instance containing the provided policies.
*
* @param policies
* The policies to include.
*/
public DeviceAdminResult(List<Policy> policies, boolean isFromReflection) {
this();
policies.addAll(policies);
}
public void addAll(Collection<Policy> policies) {
policies.addAll(policies);
}
/**
* @param isFromReflection the isFromReflection to set
*/
public void setFromReflection(boolean isFromReflection) {
this.isFromReflection = isFromReflection;
}
/**
* @return the isFromReflection
*/
public boolean isFromReflection() {
return isFromReflection;
}
public List<Policy> getPolicies() {
return policies;
}
/**
* Replaces all the previously inserted policies with the ones provided.
*
* @param policies
* The new policies to be included.
*/
public void setPolicies(List<Policy> policies) {
this.policies = policies;
}
public void addPolicy(Policy policy) {
if (policies == null) {
policies = new LinkedList<Policy>();
}
policies.add(policy);
}
/**
* Removes all previously included policies.
*/
public void clearPolicies() {
if (policies != null) {
policies.clear();
}
}
public boolean isDeviceAdminUsed() {
return deviceAdminUsed;
}
public void setDeviceAdminUsed(boolean deviceAdminUsed) {
this.deviceAdminUsed = deviceAdminUsed;
}
}
| 7,890
| 24.537217
| 81
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/encryption/GlobalEncryptionDetector.java
|
package it.polimi.elet.necst.heldroid.ransomware.encryption;
import it.polimi.elet.necst.heldroid.pipeline.FileTree;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.SmaliSimulator;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.core.SmaliMethod;
import it.polimi.elet.necst.heldroid.smali.names.SmaliClassName;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.smali.statements.*;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GlobalEncryptionDetector {
private static final SmaliMemberName GET_EXTERNAL_STORAGE = new SmaliMemberName("Landroid/os/Environment;->getExternalStorageDirectory");
private static final SmaliMemberName NEW_CIPHER_OUTPUT_STREAM = new SmaliMemberName("Ljavax/crypto/CipherOutputStream;-><init>");
private DecodedPackage target;
private SmaliLoader loader;
private final Wrapper<Boolean> encryptionFlowFound = new Wrapper<Boolean>();
private int maxAnalysisNesting = 7;
public void setTarget(DecodedPackage target) {
this.target = target;
}
public void setMaxAnalysisNesting(int maxAnalysisNesting) {
this.maxAnalysisNesting = maxAnalysisNesting;
}
public boolean detect() {
if (target == null)
throw new NullPointerException("target not set!");
FileTree smaliTree = new FileTree(target.getSmaliDirectory());
this.encryptionFlowFound.value = false;
this.loader = SmaliLoader.onSources(smaliTree.getAllFiles());
List<SmaliMethod> entryPoints = this.findDetectionEntryPoints();
if (entryPoints.size() == 0)
return false;
for (SmaliMethod entryPoint : entryPoints)
if (reachesEncryption(entryPoint))
return true;
return false;
}
private List<SmaliMethod> findDetectionEntryPoints() {
List<SmaliMethod> result = new ArrayList<SmaliMethod>();
for (SmaliClass klass : loader.getClasses())
for (SmaliMethod method : klass.getMethods())
for (SmaliStatement statement : method.getInterestingStatements())
if (statement.is(SmaliInvocationStatement.class)) {
SmaliInvocationStatement invocation = (SmaliInvocationStatement)statement;
if (invocation.getMethodName().equals(GET_EXTERNAL_STORAGE))
result.add(method);
}
return result;
}
private boolean reachesEncryption(SmaliMethod method) {
final SmaliSimulator simulator = SmaliSimulator.on(method);
final Set<String> taintedLocations = new HashSet<String>();
// Looks among invocations to find a call to getExternalStorageDirectory
simulator.addHandler(SmaliInvocationStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliInvocationStatement invocation = (SmaliInvocationStatement)statement;
if (invocation.getMethodName().equals(GET_EXTERNAL_STORAGE)) {
// When getExternalStorageDirectory is invoked, its result must be tainted
// and it constitutes the source of tainting for this analysis
simulator.addHandler(SmaliMoveResultStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliMoveResultStatement moveResult = (SmaliMoveResultStatement)statement;
taintedLocations.add(moveResult.getDestination());
simulator.removeHandler(SmaliMoveResultStatement.class);
return encryptionFlowFound.value;
}
});
// Removes this handler to avoid conflicts with other handlers
simulator.removeHandler(SmaliInvocationStatement.class);
// Adds a series of instrumentation handlers to keep track of the taint
instrument(simulator, taintedLocations, 1);
}
return encryptionFlowFound.value;
}
});
simulator.simulate();
return encryptionFlowFound.value;
}
private void instrument(final SmaliSimulator simulator, final Set<String> taintedLocations, final int level) {
if (level > maxAnalysisNesting)
return;
this.instrumentMove(simulator, taintedLocations);
this.instrumentFieldAccess(simulator, taintedLocations);
this.instrumentArrayAccess(simulator, taintedLocations);
this.instrumentInvocation(simulator, taintedLocations, level);
}
private void instrumentMove(final SmaliSimulator simulator, final Set<String> taintedLocations) {
simulator.addHandler(SmaliMoveStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliMoveStatement move = (SmaliMoveStatement)statement;
propagateTaint(taintedLocations, move.getSource(), move.getDestination());
return encryptionFlowFound.value;
}
});
}
private void instrumentFieldAccess(final SmaliSimulator simulator, final Set<String> taintedLocations) {
// PUT
simulator.addHandler(SmaliPutStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliPutStatement put = (SmaliPutStatement)statement;
propagateTaint(taintedLocations, put.getRegister(), put.getFieldName().getCompleteName());
return encryptionFlowFound.value;
}
});
// GET
simulator.addHandler(SmaliGetStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliGetStatement get = (SmaliGetStatement)statement;
propagateTaint(taintedLocations, get.getFieldName().getCompleteName(), get.getRegister());
return encryptionFlowFound.value;
}
});
}
private void instrumentArrayAccess(final SmaliSimulator simulator, final Set<String> taintedLocations) {
// ARRAY PUT
simulator.addHandler(SmaliArrayPutStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliArrayPutStatement put = (SmaliArrayPutStatement)statement;
propagateTaint(taintedLocations, put.getTargetRegister(), put.getArrayRegister());
return encryptionFlowFound.value;
}
});
// ARRAY GET
simulator.addHandler(SmaliArrayGetStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliArrayGetStatement get = (SmaliArrayGetStatement)statement;
propagateTaint(taintedLocations, get.getArrayRegister(), get.getTargetRegister());
return encryptionFlowFound.value;
}
});
}
private void instrumentInvocation(final SmaliSimulator simulator, final Set<String> taintedLocations, final int level) {
simulator.addHandler(SmaliInvocationStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliInvocationStatement invocation = (SmaliInvocationStatement)statement;
SmaliClassName className = invocation.getMethodName().getClassName();
SmaliClass klass = loader.getClassByName(className);
List<String> parameters = invocation.getParameters();
simulator.removeHandler(SmaliMoveResultStatement.class);
// Invocation to an external method
if (klass == null) {
boolean taintResult = false;
for (String param : parameters)
if (taintedLocations.contains(param)) {
taintResult = true;
break;
}
if (taintResult) {
// A flow has been found that leas from getExternalStorage to encryption: return with success
if (invocation.getMethodName().equals(NEW_CIPHER_OUTPUT_STREAM))
return (encryptionFlowFound.value = true);
// If any parameter is tainted, the invocation result is tainted too, so add an handler
// for the next move-result. Notice that move-result handlers are reset at the beginning of this handler
instrumentNextMoveResult(simulator, taintedLocations);
// Also the object on which the method is invoked becomes tainted
if (!invocation.getQualifier().contains("static"))
taintedLocations.add(parameters.get(0));
}
} else {
final SmaliMethod target = klass.getMethodBySignature(invocation.getMethodName(), invocation.getParameterTypes());
if (target == null)
return encryptionFlowFound.value;
final SmaliSimulator innerSimulator = SmaliSimulator.on(target);
final Set<String> innerTaintedLocations = new HashSet<String>();
for (int i = 0; i < parameters.size(); i++)
if (taintedLocations.contains(parameters.get(i)))
innerTaintedLocations.add(String.format("p%d", i));
instrument(innerSimulator, innerTaintedLocations, level + 1);
// If target method returns something tainted, the next move-result will propagate the taint
innerSimulator.addHandler(SmaliReturnStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
if (innerTaintedLocations.contains(((SmaliReturnStatement)statement).getRegister()))
instrumentNextMoveResult(simulator, taintedLocations);
return encryptionFlowFound.value;
}
});
innerSimulator.simulate();
for (String taint : innerTaintedLocations)
if (taint.startsWith("L"))
taintedLocations.add(taint);
}
return encryptionFlowFound.value;
}
});
}
private void instrumentNextMoveResult(final SmaliSimulator simulator, final Set<String> taintedLocations) {
simulator.addHandler(SmaliMoveResultStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
taintedLocations.add(((SmaliMoveResultStatement)statement).getDestination());
simulator.removeHandler(SmaliMoveResultStatement.class);
return encryptionFlowFound.value;
}
});
}
private static void propagateTaint(final Set<String> taintedLocation, String source, String destination) {
if (taintedLocation.contains(source))
taintedLocation.add(destination);
else
taintedLocation.remove(destination);
}
}
| 12,261
| 44.753731
| 141
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/encryption/EncryptionFlowDetector.java
|
package it.polimi.elet.necst.heldroid.ransomware.encryption;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import it.polimi.elet.necst.heldroid.utils.Xml;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.android.InfoflowAndroidConfiguration;
import soot.jimple.infoflow.android.SetupApplication;
import soot.jimple.infoflow.android.source.AndroidSourceSinkManager.LayoutMatchingMode;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AccessPath.ArrayTaintType;
import soot.jimple.infoflow.data.AccessPathFactory;
import soot.jimple.infoflow.data.pathBuilders.DefaultPathBuilderFactory;
import soot.jimple.infoflow.problems.conditions.ConditionParser;
import soot.jimple.infoflow.problems.conditions.ConditionSet;
import soot.jimple.infoflow.taintWrappers.EasyTaintWrapper;
import soot.jimple.infoflow.taintWrappers.ITaintPropagationWrapper;
import soot.jimple.infoflow.taintWrappers.TaintWrapperSet;
public class EncryptionFlowDetector {
private static final String PERMISSION_TAG = "uses-permission";
private static final String NAME_ATTRIBUTE = "android:name";
private static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
private static final String SOURCE_SINKS_FILE_NAME = "SourcesAndSinks.txt";
private static final String TAINT_WRAPPER_FILE_NAME = "EasyTaintWrapperSource.txt";
private static final String CONDITIONS_FILE = "Conditions.txt";
private static final int FLOW_TIMEOUT = 220; // seconds
private DocumentBuilderFactory dbFactory;
private DocumentBuilder db;
private DecodedPackage target;
private File androidPlatformsDir;
private ConditionSet conditions;
private File sourceSinksFilePath;
private File taintWrapperFilePath;
private File conditionsFilePath;
public void setTarget(DecodedPackage target) {
this.target = target;
}
public void setAndroidPlatformsDir(File androidPlatformsDir) {
this.androidPlatformsDir = androidPlatformsDir;
}
public EncryptionFlowDetector()
throws ParserConfigurationException {
this.sourceSinksFilePath = new File(SOURCE_SINKS_FILE_NAME);
this.taintWrapperFilePath = new File(TAINT_WRAPPER_FILE_NAME);
this.conditionsFilePath = new File(CONDITIONS_FILE);
this.dbFactory = DocumentBuilderFactory.newInstance();
this.db = dbFactory.newDocumentBuilder();
try {
ConditionParser parser = ConditionParser.fromFile(this.conditionsFilePath.getPath());
this.conditions = parser.getConditionSet();
} catch (IOException e) {
System.err.println("Cannot parse file: Conditions.txt");
this.conditions = null;
}
}
private boolean hasRwPermission() {
try {
Document document = db.parse(target.getAndroidManifest());
Element root = document.getDocumentElement();
Collection<Element> permissions = Xml.getElementsByTagName(root,
PERMISSION_TAG);
boolean canWrite = false;
for (Element permission : permissions) {
if (!permission.hasAttribute(NAME_ATTRIBUTE))
continue;
String name = permission.getAttribute(NAME_ATTRIBUTE);
if (name.equals(WRITE_EXTERNAL_STORAGE))
canWrite = true;
/*
* Any app that declares the WRITE_EXTERNAL_STORAGE permission
* is implicitly granted READ_EXTERNAL_STORAGE permission. So
* there's no need to check READ_EXTERNAL_STORAGE permission.
*/
// if (canRead && canWrite)
if (canWrite) {
return true;
}
}
return false;
} catch (Exception e) {
// If we cannot parse the manifest, we assume that the sample has RW
// permission
return true;
}
}
public Wrapper<EncryptionResult> detect() {
if (target == null)
throw new NullPointerException("Target not set!");
if (androidPlatformsDir == null)
throw new NullPointerException("Android platforms dir not set!");
final Wrapper<EncryptionResult> result = new Wrapper<>(
new EncryptionResult());
result.value.setWritable(this.hasRwPermission());
if (!this.hasRwPermission()) {
System.out.println("APK has no RW permission");
// return false;
return result;
}
// final Wrapper<InfoflowResults> res = new
// Wrapper<InfoflowResults>(null);
// Logging.suppressAll();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Runnable() {
@Override
public void run() {
SetupApplication app;
try {
app = initAnalysis();
// if (res != null)
// res.value = app.runInfoflow();
if (result != null && result.value != null) {
result.value.setInfoFlowResults(app.runInfoflow());
}
} catch (Throwable e) {
e.printStackTrace();
result.value.setTimedout(true);
}
}
});
executor.shutdown();
try {
if (!executor.awaitTermination(FLOW_TIMEOUT, TimeUnit.SECONDS)) {
executor.shutdownNow();
result.value.setTimedout(true);
}
} catch (InterruptedException e) {
e.printStackTrace();
result.value.setTimedout(true);
}
// Logging.restoreAll();
// boolean result = (res.value != null) &&
// (res.value.getResults().size() > 0);
return result;
}
private SetupApplication initAnalysis() {
// SetupApplication app = new SetupApplication(
// androidPlatformsDir.getAbsolutePath(), target .getOriginalApk()
// .getAbsolutePath());
String androidJar = new File(androidPlatformsDir,
"android-23/android.jar").getAbsolutePath();
SetupApplication app = new SetupApplication(androidJar,
target.getOriginalApk().getAbsolutePath());
InfoflowAndroidConfiguration config = app.getConfig();
InfoflowAndroidConfiguration.setMergeNeighbors(false);
InfoflowAndroidConfiguration.setPathAgnosticResults(false);
InfoflowAndroidConfiguration.setOneResultPerAccessPath(true);
config.setStopAfterFirstFlow(true);
config.setEnableImplicitFlows(false);
config.setEnableStaticFieldTracking(true);
config.setEnableCallbacks(true);
// Callbacks are not sources
config.setEnableCallbackSources(false);
config.setEnableExceptionTracking(false);
config.setLayoutMatchingMode(LayoutMatchingMode.NoMatch);
config.setFlowSensitiveAliasing(true);
config.setPathBuilder(
DefaultPathBuilderFactory.PathBuilder.ContextSensitive);
config.setComputeResultPaths(true);
config.setMaxThreadNum(-1);
// ForwardCFGNavigator navigator = new ForwardCFGNavigator();
// navigator.setLoggingEnabled(false);
// navigator.setIgnoreExceptions(false);
// navigator.setIgnoreFlowsInSystemPackages(true);
// config.setCFGNavigator(navigator);
config.setConditions(conditions);
// config.setConditionFilename("Conditions.txt");
EasyTaintWrapper easyTaintWrapper = null;
TaintWrapperSet taintSet = new TaintWrapperSet();
try {
easyTaintWrapper = new EasyTaintWrapper(this.taintWrapperFilePath.getPath());
taintSet.addWrapper(easyTaintWrapper);
} catch (IOException e) {
}
taintSet.addWrapper(new ITaintPropagationWrapper() {
@Override
public boolean supportsCallee(Stmt callSite) {
if (callSite.containsFieldRef()) {
InvokeExpr ie = callSite.getInvokeExpr();
return this.supportsCallee(ie.getMethod());
}
return false;
}
@Override
public boolean supportsCallee(SootMethod method) {
SootClass sootClass = method.getDeclaringClass();
boolean isInputStream = sootClass.getName().equals(InputStream.class.getName());
while (!isInputStream && sootClass.hasSuperclass()) {
sootClass = sootClass.getSuperclass();
sootClass.getName().equals(InputStream.class.getName());
}
return (isInputStream && method .getName()
.equals("read"));
}
@Override
public boolean isExclusive(Stmt stmt, Abstraction taintedPath) {
return false;
}
@Override
public void initialize(InfoflowManager manager) {
// TODO Auto-generated method stub
}
@Override
public int getWrapperMisses() {
return 0;
}
@Override
public int getWrapperHits() {
return 0;
}
@Override
public Set<Abstraction> getTaintsForMethod(Stmt stmt,
Abstraction d1, Abstraction taintedPath) {
if (!stmt.containsInvokeExpr()) {
return null;
}
Set<Abstraction> result = new HashSet<>();
final SootMethod method = stmt.getInvokeExpr().getMethod();
final InvokeExpr ie = stmt.getInvokeExpr();
if (!taintedPath.getAccessPath().isEmpty()) {
if (method.getName().equals("read") && ie.getArgCount() >= 1) {
result.add(d1.deriveNewAbstraction(ie.getArg(0), false, stmt, ie.getArg(0).getType(), ArrayTaintType.ContentsAndLength));
} else if (ie instanceof InstanceInvokeExpr && method.getName().equals("update")) {
result.add(d1.deriveNewAbstraction(AccessPathFactory.v().createAccessPath(((InstanceInvokeExpr) ie).getBase(), true), stmt));
}
}
if (result.isEmpty()) {
return null;
}
return result;
}
@Override
public Set<Abstraction> getAliasesForMethod(Stmt stmt,
Abstraction d1, Abstraction taintedPath) {
return null;
}
});
easyTaintWrapper.setAggressiveMode(false);
// app.setTaintWrapper(easyTaintWrapper);
app.setTaintWrapper(taintSet);
try {
app.calculateSourcesSinksEntrypoints(this.sourceSinksFilePath.getPath());
} catch (Exception e) {
}
return app;
}
public interface FlowResultHandler {
void onResult(boolean found);
}
}
| 10,043
| 29.621951
| 131
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/encryption/EncryptionResult.java
|
package it.polimi.elet.necst.heldroid.ransomware.encryption;
import soot.jimple.infoflow.results.InfoflowResults;
public class EncryptionResult {
private InfoflowResults infoFlowResults;
private boolean writable;
private boolean timedout;
public InfoflowResults getInfoFlowResults() {
return infoFlowResults;
}
public boolean isWritable() {
return writable;
}
public void setWritable(boolean writable) {
this.writable = writable;
}
public void setInfoFlowResults(InfoflowResults infoFlowResults) {
this.infoFlowResults = infoFlowResults;
}
public void setTimedout(boolean timedout) {
this.timedout = timedout;
}
public boolean isTimedout() {
return timedout;
}
}
| 708
| 18.694444
| 66
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/photo/PhotoAdminResult.java
|
/**
*
*/
package it.polimi.elet.necst.heldroid.ransomware.photo;
/**
* 14 giu 2016
* @author Nicola Dellarocca
*
*/
public class PhotoAdminResult {
private boolean fromReflection;
private boolean photoDetected;
/**
* @return the fromReflection
*/
public boolean isFromReflection() {
return fromReflection;
}
/**
* @return the photoDetected
*/
public boolean isPhotoDetected() {
return photoDetected;
}
/**
* @param fromReflection the fromReflection to set
*/
public void setFromReflection(boolean fromReflection) {
this.fromReflection = fromReflection;
}
/**
* @param photoDetected the photoDetected to set
*/
public void setPhotoDetected(boolean photoDetected) {
this.photoDetected = photoDetected;
}
}
| 761
| 15.933333
| 56
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/photo/PhotoDetector.java
|
/**
*
*/
package it.polimi.elet.necst.heldroid.ransomware.photo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import it.polimi.elet.necst.heldroid.ransomware.emulation.ReflectionSimulator;
import it.polimi.elet.necst.heldroid.utils.CFGUtils;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.InvokeExpr;
import soot.jimple.Ref;
import soot.jimple.Stmt;
import soot.jimple.infoflow.cfg.SharedCfg;
import soot.jimple.infoflow.problems.conditions.BreadthFirstSearch;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
import soot.jimple.infoflow.util.SystemClassHandler;
/**
* @author Nicola Dellarocca
*
*/
public class PhotoDetector {
protected IInfoflowCFG mCfg;
protected DecodedPackage mTarget;
protected String[] relatedMethods = {
"android.hardware.Camera->takePicture",
"android.hardware.camera2.CameraManager->openCamera",
"getNumberOfCameras",
"getCameraInfo"};
/**
* @param target
* the target to set
*/
public void setTarget(DecodedPackage target) {
this.mTarget = target;
}
/**
*
* @param reuseCfg
* @return
* @throws IllegalStateException
*/
public Wrapper<PhotoAdminResult> detect(boolean reuseCfg)
throws IllegalStateException {
if (mTarget == null)
throw new IllegalStateException("Target not set");
createCfg(reuseCfg);
PhotoAdminResult result = findCameraMethods();
System.out.println("Overall result: "+result);
return new Wrapper<>(result);
}
protected PhotoAdminResult findCameraMethods() {
PhotoAdminResult result = new PhotoAdminResult();
BreadthFirstSearch<Unit> searcher = new BreadthFirstSearch<Unit>(mCfg) {
@Override
protected Collection<Unit> nextNodes(Unit current) {
Collection<Unit> result = new HashSet<>(0);
result.addAll(cfg.getSuccsOf(current));
// If this is a method call, add callee's start points
if (cfg.isCallStmt(current)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
current);
for (SootMethod callee : callees) {
result.addAll(cfg.getStartPointsOf(callee));
}
}
return result;
}
@Override
protected boolean isResult(Unit node) {
if (cfg.isCallStmt(node)) {
InvokeExpr ie = ((Stmt) node).getInvokeExpr();
SootMethod sm = ie.getMethod();
SootClass sc = sm.getDeclaringClass();
String composed = sc.getName() + "->" + sm.getName();
for (String s : relatedMethods) {
if (composed.equals(s)) {
return false;
// return true;
}
}
}
return false;
}
};
// Get dummy main entry points
List<SootMethod> entryPoints = Scene.v()
.getEntryPoints();
List<Unit> startPoints = new ArrayList<>();
for (SootMethod entryPoint : entryPoints) {
startPoints.addAll(mCfg.getStartPointsOf(entryPoint));
}
for (Unit start : startPoints) {
if (!searcher.search(start, false).isEmpty()) {
result.setPhotoDetected(true);
return result;
}
}
System.out.println("****** HERE");
// If we reach this point, we found no method
ArrayList<String> relatedMethods = new ArrayList<>();
relatedMethods.add("takePicture");
relatedMethods.add("getNumberOfCameras");
relatedMethods.add("getCameraInfo");
RefType enforceTargetType = null;// RefType.v("android.hardware.Camera");
boolean fromReflection = ReflectionSimulator.searchReflection(mCfg, relatedMethods, enforceTargetType);
result.setPhotoDetected(fromReflection);
result.setFromReflection(fromReflection);
return result;
}
protected void createCfg(boolean reuseCfg) {
if (reuseCfg) {
this.mCfg = SharedCfg.waitForCfg();
} else {
this.mCfg = CFGUtils.createCfg(mTarget);
}
}
}
| 3,973
| 24.63871
| 105
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/SmaliLockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.pipeline.FileTree;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliInspector;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
public abstract class SmaliLockingStrategy extends LockingStrategy {
protected SmaliLoader loader;
protected SmaliInspector inspector;
protected SmaliConstantFinder constantFinder;
@Override
public void setTarget(DecodedPackage target) {
if (!target.getSmaliDirectory().exists())
throw new RuntimeException("Smali directory doesn't exist!");
FileTree smaliTree = new FileTree(target.getSmaliDirectory());
this.loader = SmaliLoader.onSources(smaliTree.getAllFiles());
this.inspector = loader.generateInspector();
this.constantFinder = loader.generateConstantFinder();
this.target = target;
}
public void setTarget(DecodedPackage target, SmaliLoader loader, SmaliInspector inspector, SmaliConstantFinder constantFinder) {
this.target = target;
this.loader = loader;
this.inspector = inspector;
this.constantFinder = constantFinder;
}
}
| 1,316
| 36.628571
| 132
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/MultiLockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.pipeline.FileTree;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliInspector;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import java.util.ArrayList;
import java.util.List;
public class MultiLockingStrategy extends LockingStrategy {
private List<LockingStrategy> lockingStrategies;
private boolean needsSmali;
private SmaliLoader loader;
private SmaliInspector inspector;
private SmaliConstantFinder constantFinder;
private String successfulStrategy;
public MultiLockingStrategy() {
this.lockingStrategies = new ArrayList<LockingStrategy>();
this.needsSmali = false;
}
public void add(LockingStrategy strategy) {
this.lockingStrategies.add(strategy);
if (strategy instanceof SmaliLockingStrategy)
this.needsSmali = true;
}
@Override
public void setTarget(DecodedPackage target) {
super.setTarget(target);
if (needsSmali) {
if (!target.getSmaliDirectory().exists())
throw new RuntimeException("Smali directory doesn't exist!");
FileTree smaliTree = new FileTree(target.getSmaliDirectory());
this.loader = SmaliLoader.onSources(smaliTree.getAllFiles());
this.inspector = loader.generateInspector();
this.constantFinder = loader.generateConstantFinder();
}
for (LockingStrategy strategy : lockingStrategies)
if (strategy instanceof SmaliLockingStrategy)
((SmaliLockingStrategy)strategy).setTarget(target, loader, inspector, constantFinder);
else
strategy.setTarget(target);
}
@Override
protected boolean detectStrategy() {
for (LockingStrategy strategy : lockingStrategies)
if (strategy.detect()) {
this.successfulStrategy = strategy.strategyName();
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected String strategyName() {
return "MultiLockingStrategy";
}
public String getSuccessfulStrategy() {
return this.successfulStrategy;
}
}
| 2,388
| 29.628205
| 102
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/LockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
public abstract class LockingStrategy {
protected DecodedPackage target;
private String detectionReport;
public void setTarget(DecodedPackage target) {
this.target = target;
}
public String getDetectionReport() {
return detectionReport;
}
protected void setDetectionReport(String detectionReport) {
this.detectionReport = detectionReport;
}
public boolean detect() {
if (target == null)
throw new NullPointerException("target not set!");
this.setDetectionReport("");
return this.detectStrategy();
}
protected abstract boolean detectStrategy();
protected abstract String strategyName();
}
| 827
| 22
| 63
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/DialogLockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.names.SmaliClassName;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import java.util.ArrayList;
import java.util.Collection;
public class DialogLockingStrategy extends SmaliLockingStrategy {
private static final SmaliClassName ALERT_DIALOG = new SmaliClassName("Landroid/app/AlertDialog;");
private static final SmaliMemberName SET_FLAGS = new SmaliMemberName("Landroid/view/Window;->setFlags");
private static final int FLAG_SHOW_WHEN_LOCKED = 0x00080000;
private static Collection<String> zeroCodes;
static {
zeroCodes = new ArrayList<String>();
zeroCodes.add("0x00");
zeroCodes.add("0x0");
zeroCodes.add("0");
}
@Override
protected boolean detectStrategy() {
Collection<SmaliClass> alertDialogs = this.getAlertDialogs();
if (alertDialogs.size() == 0)
return false;
for (SmaliClass dialog : alertDialogs)
if (this.isDialogImmortal(dialog))
return true;
return false;
}
private Collection<SmaliClass> getAlertDialogs() {
return this.loader.getSubclassesOf(ALERT_DIALOG);
}
private boolean isDialogImmortal(SmaliClass dialog) {
SmaliConstantFinder finder = this.loader.generateConstantFinder(dialog);
SmaliMemberName setCancelable = new SmaliMemberName(dialog.getName(), "setCancelable");
final Wrapper<Boolean> isUncancelable = new Wrapper<Boolean>(false);
final Wrapper<Boolean> showWhenLocked = new Wrapper<Boolean>(false);
finder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
return (isUncancelable.value = zeroCodes.contains(value));
}
});
finder.searchParameters(setCancelable, 0);
finder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
String literal = value;
int radix = 10;
if (value.contains("0x")) {
literal = value.replace("0x", "");
radix = 16;
}
try {
int number = Integer.parseInt(literal, radix);
if ((number & FLAG_SHOW_WHEN_LOCKED) != 0)
return (showWhenLocked.value = true);
} catch (NumberFormatException nfex) { }
return false;
}
});
finder.searchParameters(SET_FLAGS, 0);
return isUncancelable.value && showWhenLocked.value;
}
/**
* {@inheritDoc}
*/
@Override
protected String strategyName() {
return "Dialog";
}
}
| 3,072
| 31.691489
| 108
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/DrawOverLockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.smali.SmaliSimulator;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.core.SmaliMethod;
import it.polimi.elet.necst.heldroid.smali.names.SmaliClassName;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.smali.statements.SmaliIfStatement;
import it.polimi.elet.necst.heldroid.smali.statements.SmaliReturnStatement;
import it.polimi.elet.necst.heldroid.smali.statements.SmaliStatement;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import it.polimi.elet.necst.heldroid.utils.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.util.Collection;
public class DrawOverLockingStrategy extends SmaliLockingStrategy {
private static final String PERMISSION_TAG = "uses-permission";
private static final String NAME_ATTRIBUTE = "android:name";
private static final String SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW";
private static final String KEY_CODE_PARAMETER = "p1";
private static final String EQUAL = "eq";
private static final String NOT_EQUAL = "ne";
private static final SmaliMemberName ON_KEY_DOWN = new SmaliMemberName("Lcom/example/testlock/MainActivity$mainActivity;->onKeyDown");
private static final SmaliMemberName ON_KEY_UP = new SmaliMemberName("Lcom/example/testlock/MainActivity$mainActivity;->onKeyUp");
private static final SmaliClassName ACTIVITY = new SmaliClassName("Landroid/app/Activity;");
private static Collection<String> backButtonCodes, homeButtonCodes, zeroCodes;
static {
backButtonCodes = new ArrayList<String>();
backButtonCodes.add("0x04");
backButtonCodes.add("0x4");
backButtonCodes.add("4");
homeButtonCodes = new ArrayList<String>();
homeButtonCodes.add("0x03");
homeButtonCodes.add("0x3");
homeButtonCodes.add("3");
zeroCodes = new ArrayList<String>();
zeroCodes.add("0x00");
zeroCodes.add("0x0");
zeroCodes.add("0");
}
private DocumentBuilderFactory dbFactory;
private DocumentBuilder db;
public DrawOverLockingStrategy() throws ParserConfigurationException {
super();
this.dbFactory = DocumentBuilderFactory.newInstance();
this.db = dbFactory.newDocumentBuilder();
}
@Override
protected boolean detectStrategy() {
boolean drawOver = hasDrawOverPermission();
boolean suppress = suppressesNavigation();
this.setDetectionReport(String.format("Suppresses navigation: %b, Has draw-over permission: %b", suppress, drawOver));
return drawOver;
}
private boolean hasDrawOverPermission() {
try {
Document document = db.parse(target.getAndroidManifest());
Element root = document.getDocumentElement();
Collection<Element> permissions = Xml.getElementsByTagName(root, PERMISSION_TAG);
for (Element permission : permissions) {
if (!permission.hasAttribute(NAME_ATTRIBUTE))
continue;
String name = permission.getAttribute(NAME_ATTRIBUTE);
if (name.equals(SYSTEM_ALERT_WINDOW))
return true;
}
return false;
} catch (Exception e) {
return true;
}
}
private boolean suppressesNavigation() {
Collection<SmaliClass> activities = loader.getSubclassesOf(ACTIVITY);
for (SmaliClass activity : activities)
if (suppressesNavigation(activity))
return true;
return false;
}
private boolean suppressesNavigation(SmaliClass activityClass) {
SmaliMethod onKeyDown = activityClass.getMethodByName(ON_KEY_DOWN);
SmaliMethod onKeyUp = activityClass.getMethodByName(ON_KEY_UP);
if ((onKeyDown != null) && suppressesNavigation(onKeyDown))
return true;
if (onKeyUp != null)
return suppressesNavigation(onKeyUp);
return false;
}
private boolean suppressesNavigation(SmaliMethod target) {
final SmaliSimulator simulator = SmaliSimulator.on(target);
final Wrapper<Boolean> comparisonFound = new Wrapper<Boolean>(false);
final Wrapper<Boolean> navigationSuppressed = new Wrapper<Boolean>(false);
simulator.addHandler(SmaliIfStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliIfStatement ifStatement = (SmaliIfStatement)statement;
String qualifier = ifStatement.getQualifier();
if (!qualifier.equals(EQUAL) && !qualifier.equals(NOT_EQUAL))
return (comparisonFound.value = false);
String otherRegister = null;
if (ifStatement.getRegister1().equals(KEY_CODE_PARAMETER))
otherRegister = ifStatement.getRegister2();
else if (ifStatement.getRegister2().equals(KEY_CODE_PARAMETER))
otherRegister = ifStatement.getRegister1();
else
return (comparisonFound.value = false);
Collection<String> values = simulator.getPossibleValues(otherRegister);
for (String value : values)
if (homeButtonCodes.contains(value) || backButtonCodes.contains(value)) {
comparisonFound.value = true;
if (qualifier.equals(EQUAL))
return true;
else
return false;
}
return (comparisonFound.value = false);
}
});
simulator.addHandler(SmaliReturnStatement.class, new SmaliSimulator.StatementHandler() {
@Override
public boolean statementReached(SmaliStatement statement) {
SmaliReturnStatement returnStatement = (SmaliReturnStatement)statement;
if (returnStatement.getRegister() == null)
return false;
String register = returnStatement.getRegister();
Collection<String> values = simulator.getPossibleValues(register);
for (String value : values)
if (!zeroCodes.contains(value)) // Everything different from zero is true
return (navigationSuppressed.value = true);
return false;
}
});
simulator.simulate();
return navigationSuppressed.value;
}
/**
* {@inheritDoc}
*/
@Override
protected String strategyName() {
return "DrawOver";
}
}
| 7,064
| 35.796875
| 138
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/locking/AdminLockingStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.locking;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import it.polimi.elet.necst.heldroid.utils.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class AdminLockingStrategy extends SmaliLockingStrategy {
private static final String PERMISSION_ATTRIBUTE = "android:permission";
private static final String BIND_DEVICE_ADMIN = "android.permission.BIND_DEVICE_ADMIN";
private static final String RESOURCE_ATTRIBUTE = "android:resource";
private static final String FORCE_LOCK_TAG = "force-lock";
private static final String ACTION_ADD_DEVICE_ADMIN = "android.app.action.ADD_DEVICE_ADMIN";
private static final SmaliMemberName INTENT_CONSTRUCTOR = new SmaliMemberName("Landroid/content/Intent;-><init>");
private static final int INTENT_CONSTRUCTOR_NAME_PARAMETER_INDEX = 0;
private static final SmaliMemberName LOCK_NOW = new SmaliMemberName("Landroid/app/admin/DevicePolicyManager;->lockNow");
private DocumentBuilderFactory dbFactory;
private DocumentBuilder db;
public AdminLockingStrategy() throws ParserConfigurationException {
super();
this.dbFactory = DocumentBuilderFactory.newInstance();
this.db = dbFactory.newDocumentBuilder();
}
@Override
protected boolean detectStrategy() {
boolean lockingPrivilege = true;
try {
lockingPrivilege = hasLockingPrivilege();
} catch (Exception e) { }
boolean askAdmin = asksForAdmin();
boolean locks = callsLock();
this.setDetectionReport(String.format("Has locking privilege: %b, Asks for admin: %b, Calls lock(): %b", lockingPrivilege, askAdmin, locks));
return lockingPrivilege && asksForAdmin() && callsLock();
}
private boolean asksForAdmin() {
final Wrapper<Boolean> found = new Wrapper<Boolean>(false);
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
if (value.contains(ACTION_ADD_DEVICE_ADMIN))
return (found.value = true);
return false;
}
});
constantFinder.searchParameters(INTENT_CONSTRUCTOR, INTENT_CONSTRUCTOR_NAME_PARAMETER_INDEX);
return found.value;
}
private boolean hasLockingPrivilege() throws IOException, SAXException {
Document document = db.parse(target.getAndroidManifest());
Element root = document.getDocumentElement();
Collection<Element> receivers = Xml.getElementsByTagName(root, "receiver");
for (Element receiver : receivers) {
if (!receiver.hasAttribute(PERMISSION_ATTRIBUTE))
continue;
String permission = receiver.getAttribute(PERMISSION_ATTRIBUTE);
if (!permission.contains(BIND_DEVICE_ADMIN))
continue;
Element metadata = Xml.getChildElement(receiver, "meta-data");
if ((metadata == null) || !metadata.hasAttribute(RESOURCE_ATTRIBUTE))
continue;
String resource = metadata.getAttribute(RESOURCE_ATTRIBUTE);
File resourceDirectory = new File(target.getDecodedDirectory(), "res");
if (!resource.startsWith("@"))
continue;
int slashIndex = resource.indexOf('/');
String folderName = resource.substring(1, slashIndex - 1);
String fileName = resource.substring(slashIndex + 1);
File metadataXml = new File(new File(resourceDirectory, folderName), fileName);
if (!metadataXml.exists())
continue;
if (this.hasLockingPrivilege(metadataXml))
return true;
}
return false;
}
private boolean hasLockingPrivilege(File metadataXml) {
try {
Document document = db.parse(metadataXml);
Collection<Element> forceLock = Xml.getElementsByTagName(document.getDocumentElement(), FORCE_LOCK_TAG);
return forceLock.size() > 0;
} catch (Exception e) {
return false;
}
}
private boolean callsLock() {
List<SmaliMemberName> singleton = new ArrayList<SmaliMemberName>();
singleton.add(LOCK_NOW);
boolean[] result = inspector.invocationsExist(singleton);
return result[0];
}
/**
* {@inheritDoc}
*/
@Override
protected String strategyName() {
return "DeviceAdmin";
}
}
| 5,005
| 34.006993
| 149
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/SupportedLanguage.java
|
package it.polimi.elet.necst.heldroid.ransomware.text;
import opennlp.tools.stemmer.snowball.SnowballStemmer;
public enum SupportedLanguage {
ENGLISH("english", "en", "eng", SnowballStemmer.ALGORITHM.ENGLISH),
RUSSIAN("russian", "ru", "rus", SnowballStemmer.ALGORITHM.RUSSIAN),
SPANISH("spanish", "es", "spa", SnowballStemmer.ALGORITHM.SPANISH);
private String name, code, iso3code;
private SnowballStemmer.ALGORITHM stemmerAlgorithm;
public String getName() {
return name;
}
public String getCode() {
return code;
}
public String getIso3code() {
return iso3code;
}
public SnowballStemmer.ALGORITHM getStemmerAlgorithm() {
return stemmerAlgorithm;
}
SupportedLanguage(String name, String code, String iso3code, SnowballStemmer.ALGORITHM stemmerAlgorithm) {
this.name = name;
this.code = code;
this.iso3code = iso3code;
this.stemmerAlgorithm = stemmerAlgorithm;
}
public static SupportedLanguage fromCode(String languageCode) {
languageCode = languageCode.toLowerCase();
for (SupportedLanguage language : SupportedLanguage.values())
if (language.getCode().equals(languageCode))
return language;
return null;
}
}
| 1,301
| 27.304348
| 110
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/FileClassification.java
|
package it.polimi.elet.necst.heldroid.ransomware.text;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* This class lets you track all files containing strings belonging to one of the categories listed in {@link FileClassification#CATEGORIES}
* @author Nicola
*
*/
public class FileClassification {
public static final String[] CATEGORIES = new String[] { "threat", "porn",
"law", "copyright", "moneypak" };
private Map<String, List<String>> classifiedFiles;
public FileClassification() {
classifiedFiles = new HashMap<>();
// initialize empty categories
for (String cat : CATEGORIES) {
classifiedFiles.put(cat, new LinkedList<String>());
}
}
/**
* Adds a file to a category
* @param category The category to which the file belongs
* @param file The file thats belong to a category
*/
public void addFile(String category, File file) {
this.addFile(category, file.getAbsolutePath());
}
/**
* Clears all previously added files
*/
public void clear() {
for (String cat : CATEGORIES) {
// If the list does not exist, this method creates it
if (classifiedFiles.get(cat) != null)
classifiedFiles.get(cat).clear();
else
classifiedFiles.put(cat, new LinkedList<String>());
}
}
/**
* This method lets you merge two {@link FileClassification} instances: <code>this</code> and <code>other</code>
* @param other The instance with which this instance should be merged
*/
public void merge(FileClassification other) {
for (String category : CATEGORIES) {
List<String> thisList = classifiedFiles.get(category);
// The list should already exists, but let's check it anyway
if (thisList == null) {
thisList = new LinkedList<>();
classifiedFiles.put(category, thisList);
}
List<String> otherList = other.getClassifiedFiles().get(category);
if (otherList == null) {
return;
}
// Avoid adding duplicates
for (String s : otherList) {
if (!thisList.contains(s)) {
thisList.add(s);
}
}
}
}
public void addFile(String category, String fileName) {
List<String> list = classifiedFiles.get(category);
if (list == null) {
list = new LinkedList<>();
classifiedFiles.put(category, list);
}
// add file only if it's not already included in the list
if (!list.contains(fileName)) {
list.add(fileName);
}
}
public Map<String, List<String>> getClassifiedFiles() {
return classifiedFiles;
}
@Override
public String toString() {
// StringBuilder builder = new StringBuilder("[");
//
// for (String cat : CATEGORIES) {
// builder.append(cat);
// builder.append(": ");
// builder.append(getClassifiedFiles().get(cat));
//
// if (!cat.equals(CATEGORIES[CATEGORIES.length-1]))
// builder.append(", ");
// }
//
// builder.append("]");
// return builder.toString();
return classifiedFiles.toString();
}
}
| 2,984
| 23.467213
| 141
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/TextClassification.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import it.polimi.elet.necst.heldroid.ransomware.text.FileClassification;
public class TextClassification {
private List<SentenceClassification> sentenceClassifications;
private FileClassification fileClassification;
public FileClassification getFileClassification() {
return fileClassification;
}
public void setFileClassification(FileClassification fileClassification) {
this.fileClassification = fileClassification;
}
public List<SentenceClassification> getSentenceClassifications() {
return sentenceClassifications;
}
TextClassification(List<SentenceClassification> sentenceClassifications) {
this.sentenceClassifications = sentenceClassifications;
this.fileClassification = new FileClassification();
}
public double maxLikelihood(String category) {
double max = 0;
for (SentenceClassification c : sentenceClassifications)
if (c.getCategory().equals(category) && c.getLikelihood() > max)
max = c.getLikelihood();
return max;
}
public SentenceClassification containsAnySentence(double minLikelihood,
String... categories) {
List<String> categoryList = Arrays.asList(categories);
for (SentenceClassification c : sentenceClassifications)
if (categoryList.contains(c.getCategory())
&& c.getLikelihood() >= minLikelihood)
return c;
return null;
}
public List<SentenceClassification> containsAllSentences(
double minLikelihood, String... categories) {
List<SentenceClassification> list = new ArrayList<SentenceClassification>(
categories.length);
Map<String, Boolean> found = new HashMap<String, Boolean>();
int foundCount = 0;
for (SentenceClassification c : sentenceClassifications)
if ((!found.containsKey(c.getCategory())
|| !found.get(c.getCategory()))
&& c.getLikelihood() >= minLikelihood) {
found.put(c.getCategory(), true);
list.add(c);
foundCount++;
if (foundCount == categories.length)
return list;
}
return new ArrayList<SentenceClassification>();
}
public List<SentenceClassification> findAllSentences(double minLikelihood,
String... categories) {
List<SentenceClassification> list = new ArrayList<SentenceClassification>();
List<String> categoryList = Arrays.asList(categories);
for (SentenceClassification c : sentenceClassifications)
if (categoryList.contains(c.getCategory())
&& c.getLikelihood() >= minLikelihood)
list.add(c);
return list;
}
public void append(TextClassification other) {
sentenceClassifications.addAll(other.sentenceClassifications);
// Merge also FileClassification data
this.fileClassification.merge(other.getFileClassification());
}
public static TextClassification empty() {
return new TextClassification(new ArrayList<SentenceClassification>());
}
}
| 2,959
| 28.306931
| 78
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/Segmenter.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
import opennlp.tools.sentdetect.SentenceDetector;
import opennlp.tools.stemmer.Stemmer;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.tokenize.Tokenizer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Segmenter {
private static final Pattern whitespaces = Pattern.compile("\\s+");
private StopWordCollection stopWordCollection;
private Stemmer stemmer;
private SentenceDetector sentenceDetector;
private Tokenizer tokenizer;
public Segmenter(StopWordCollection stopWordCollection, Stemmer stemmer, SentenceDetector sentenceDetector) {
this.stopWordCollection = stopWordCollection;
this.stemmer = stemmer;
this.sentenceDetector = sentenceDetector;
this.tokenizer = SimpleTokenizer.INSTANCE;
}
public List<StemmedSentence> segment(String text) {
text = text.toLowerCase();
List<StemmedSentence> stemmedSentences = new ArrayList<StemmedSentence>();
String[] sentences = sentenceDetector.sentDetect(text);
for (String sentence : sentences) {
String[] chunks = sentence.split("\\n");
for (String chunk : chunks) {
Matcher matcher = whitespaces.matcher(chunk);
if (matcher.matches())
continue;
Set<String> stems = applyStemming(chunk);
stemmedSentences.add(new StemmedSentence(chunk, stems));
}
}
return stemmedSentences;
}
private Set<String> applyStemming(String sentence) {
Set<String> stems = new HashSet<String>();
String[] tokens = tokenizer.tokenize(sentence);
for (String token : tokens) {
if (!isWord(token))
continue;
if (stopWordCollection.contains(token))
continue;
CharSequence stem = stemmer.stem(token);
stems.add(stem.toString());
}
return stems;
}
private static boolean isNumber(String token) {
for (Character c : token.toCharArray())
if (!Character.isDigit(c))
return false;
return true;
}
private static boolean isWord(String token) {
for (int i = 0; i < token.length(); i++)
if (!Character.isLetter(token.codePointAt(i))) // works with unicode
return false;
return true;
}
public static class StemmedSentence {
private Set<String> stems;
private String originalText;
public Set<String> getStems() {
return stems;
}
public String getOriginalText() {
return originalText;
}
private StemmedSentence(String originalText, Set<String> stems) {
this.stems = stems;
this.originalText = originalText;
}
}
}
| 3,045
| 28.572816
| 113
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/TextClassifierCollection.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TextClassifierCollection {
private Map<SupportedLanguage, TextClassifier> classifiers;
public Set<SupportedLanguage> getSupposedLanguages() {
return classifiers.keySet();
}
public TextClassifierCollection() {
this.classifiers = new HashMap<SupportedLanguage, TextClassifier>();
}
public void add(SupportedLanguage language, TextClassifier classifier) {
this.classifiers.put(language, classifier);
}
public TextClassifier get(SupportedLanguage language) {
return this.classifiers.get(language);
}
}
| 798
| 27.535714
| 76
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/SentenceClassification.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
public class SentenceClassification {
private String category, text;
private double likelihood;
private int producedStemsCount;
public String getCategory() {
return category;
}
void setCategory(String category) {
this.category = category;
}
public double getLikelihood() {
return likelihood;
}
void setLikelihood(double likelihood) {
this.likelihood = likelihood;
}
public String getText() {
return text;
}
void setText(String text) {
this.text = text;
}
public boolean isValid() {
return (this.likelihood > 0);
}
public int getProducedStemsCount() {
return producedStemsCount;
}
void setProducedStemsCount(int producedStemsCount) {
this.producedStemsCount = producedStemsCount;
}
@Override
public String toString() {
return String.format("[%s: %2f] %s", this.category, this.likelihood, this.text);
}
}
| 1,060
| 20.653061
| 88
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/GenericTextClassifier.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class GenericTextClassifier implements TextClassifier {
private Segmenter segmenter;
private Map<String, List<StemVector>> basis;
public GenericTextClassifier(Segmenter segmenter) {
this.segmenter = segmenter;
this.basis = new HashMap<String, List<StemVector>>();
}
public void teach(String category, String text) {
List<Segmenter.StemmedSentence> stemmedSentences = segmenter.segment(text);
List<StemVector> categoryVectors = this.basis.get(category);
if (categoryVectors == null)
this.basis.put(category, (categoryVectors = new ArrayList<StemVector>()));
for (Segmenter.StemmedSentence stemmedSentence : stemmedSentences)
categoryVectors.add(new StemVector(stemmedSentence.getStems()));
}
public TextClassification classify(String text) {
List<SentenceClassification> sentenceClassifications = new ArrayList<SentenceClassification>();
List<Segmenter.StemmedSentence> stemmedSentences = segmenter.segment(text);
for (Segmenter.StemmedSentence stemmedSentence : stemmedSentences) {
StemVector sentenceVector = new StemVector(stemmedSentence.getStems());
String bestCategory = "<UNDEFINED>";
double bestSimilarity = 0;
for (Map.Entry<String, List<StemVector>> entry : this.basis.entrySet()) {
String category = entry.getKey();
List<StemVector> categoryVectors = entry.getValue();
for (StemVector categoryVector : categoryVectors) {
double similarity = categoryVector.cosineSimilarity(sentenceVector);
if (similarity >= bestSimilarity) {
bestCategory = category;
bestSimilarity = similarity;
}
}
}
SentenceClassification sentenceClassification = new SentenceClassification();
sentenceClassification.setCategory(bestCategory);
sentenceClassification.setLikelihood(bestSimilarity);
sentenceClassification.setText(stemmedSentence.getOriginalText());
sentenceClassification.setProducedStemsCount(sentenceVector.stems.size());
sentenceClassifications.add(sentenceClassification);
}
return new TextClassification(sentenceClassifications);
}
private static class StemVector {
private Set<String> stems;
public StemVector(Set<String> stems) {
this.stems = stems;
}
public double cosineSimilarity(StemVector other) {
Set<String> smaller, bigger;
if (this.stems.size() < other.stems.size()) {
smaller = this.stems;
bigger = other.stems;
} else {
smaller = other.stems;
bigger = this.stems;
}
int intersectionSize = 0;
for (String stem : smaller)
if (bigger.contains(stem))
intersectionSize++;
return (double)intersectionSize / (Math.sqrt(smaller.size()) * Math.sqrt(bigger.size()));
}
}
public static class Match {
private String category;
private double similarity;
public String getCategory() {
return category;
}
private void setCategory(String category) {
this.category = category;
}
public double getSimilarity() {
return similarity;
}
private void setSimilarity(double similarity) {
this.similarity = similarity;
}
}
}
| 3,885
| 33.389381
| 103
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/StopWordList.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StopWordList implements StopWordCollection {
private String[] stopwords;
private StopWordList(List<String> list) {
this.stopwords = new String[list.size()];
for (int i = 0; i < list.size(); i++)
this.stopwords[i] = list.get(i);
}
public boolean contains(String word) {
return (word.length() <= 1) || (Arrays.binarySearch(this.stopwords, word) >= 0);
}
public static StopWordList fromFile(File source) {
try {
BufferedReader reader = new BufferedReader(new FileReader(source));
List<String> stopwordList = new ArrayList<String>();
String word = null;
while ((word = reader.readLine()) != null)
stopwordList.add(word);
reader.close();
Collections.sort(stopwordList);
return new StopWordList(stopwordList);
} catch (IOException e) {
return null;
}
}
}
| 1,165
| 27.439024
| 88
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/TextClassifier.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
public interface TextClassifier {
TextClassification classify(String text);
}
| 153
| 24.666667
| 69
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/classification/StopWordCollection.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.classification;
public interface StopWordCollection {
boolean contains(String word);
}
| 146
| 23.5
| 69
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/XmlLayoutScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.util.List;
public class XmlLayoutScanner extends ResourceScanner {
private static final int MIN_STRING_LENGTH = 30;
private static final String TEXT_ATTRIBUTE = "android:text";
private DocumentBuilderFactory dbFactory;
private DocumentBuilder db;
public XmlLayoutScanner(TextClassifierCollection classifierCollection) throws ParserConfigurationException {
super(classifierCollection);
this.dbFactory = DocumentBuilderFactory.newInstance();
this.db = dbFactory.newDocumentBuilder();
}
@Override
protected TextClassification findRansomwareText() {
List<File> layoutDirectories = this.getApkResourceDirectories("layout");
TextClassification finalClassification = TextClassification.empty();
for (File layoutDirectory : layoutDirectories)
for (File layout : FileSystem.listFiles(layoutDirectory, ".xml")) {
TextClassification layoutTextClassification = this.findRansomwareText(layout);
finalClassification.append(layoutTextClassification);
}
return finalClassification;
}
protected TextClassification findRansomwareText(File xmlLayout) {
try {
Document document = db.parse(xmlLayout);
Element root = document.getDocumentElement();
TextClassification result = this.classifyElementText(root, TextClassification.empty());
extractLikelihood(xmlLayout, result);
result.setFileClassification(getFileClassification());
return result;
} catch (Exception e) {
return TextClassification.empty();
}
}
protected TextClassification classifyElementText(Element element, TextClassification totalClassification) {
String text = element.getAttribute(TEXT_ATTRIBUTE);
if (isSuitableForClassification(text)) {
TextClassifier textClassifier = this.getTextClassifierFor(text);
if (textClassifier != null) {
TextClassification textClassification = textClassifier.classify(text);
totalClassification.append(textClassification);
}
}
for (Element child : Xml.getChildElements(element))
this.classifyElementText(child, totalClassification);
return totalClassification;
}
}
| 3,033
| 37.897436
| 112
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/ResourceScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cybozu.labs.langdetect.Detector;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import it.polimi.elet.necst.heldroid.ransomware.text.FileClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
public abstract class ResourceScanner {
private static final Logger logger = LoggerFactory.getLogger(ResourceScanner.class);
private static final Pattern RES_VALUE_PATTERN = Pattern.compile(
"\\@\\w+\\/[\\w_]+");
private static final int MIN_STRING_LENGTH = 30;
protected TextClassifierCollection textClassifierCollection;
protected File unpackedApkDirectory;
protected AcceptanceStrategy acceptanceStrategy;
protected TextClassification textClassification;
protected FileClassification fileClassification = new FileClassification();
private Set<SupportedLanguage> encounteredLanguages;
private int totalSentences;
protected File getApkResourceDirectory() {
return new File(unpackedApkDirectory, "res");
}
protected List<File> getApkResourceDirectories(final String prefix) {
File res = this.getApkResourceDirectory();
List<File> result = new ArrayList<File>();
File[] matchedFiles = res.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name .toLowerCase()
.startsWith(prefix.toLowerCase());
}
});
if (matchedFiles != null) {
for (File file : matchedFiles)
if (file.isDirectory())
result.add(file);
}
return result;
}
public void setUnpackedApkDirectory(File unpackedApkDirectory) {
this.unpackedApkDirectory = unpackedApkDirectory;
}
public void setAcceptanceStrategy(AcceptanceStrategy acceptanceStrategy) {
this.acceptanceStrategy = acceptanceStrategy;
}
public FileClassification getFileClassification() {
return fileClassification;
}
public void extractLikelihood(String fileName,
TextClassification classification) {
if (fileName == null) {
throw new IllegalArgumentException("File shouldn't be null");
}
if (classification == null) {
throw new IllegalArgumentException(
"Classification shouldn't be null");
}
for (String category : FileClassification.CATEGORIES) {
double score = classification.maxLikelihood(category);
if (score > 0d) {
fileClassification.addFile(category, fileName);
}
}
}
public void extractLikelihood(File file,
TextClassification classification) {
if (file == null) {
throw new IllegalArgumentException("File shouldn't be null");
}
String fullPath = file.getAbsolutePath();
// use relative path, if possible
Matcher matcher = Pattern .compile(".*\\.apk\\/(.+)")
.matcher(fullPath);
this.extractLikelihood(matcher.matches() ? matcher.group(1) : fullPath,
classification);
}
public ResourceScanner(TextClassifierCollection textClassifierCollection) {
logger.info("Instantiating ResourceScanner");
this.textClassifierCollection = textClassifierCollection;
this.resetStatistics();
}
public AcceptanceStrategy.Result evaluate() {
if (unpackedApkDirectory == null || !unpackedApkDirectory.exists())
throw new NullPointerException("UnpackedApkDirectory not set!");
if (acceptanceStrategy == null)
throw new NullPointerException("AcceptanceStrategy not set!");
this.resetStatistics();
this.textClassification = this.findRansomwareText();
return acceptanceStrategy.accepts(this.textClassification);
}
protected abstract TextClassification findRansomwareText();
private void resetStatistics() {
this.encounteredLanguages = new HashSet<>();
this.totalSentences = 0;
}
protected SupportedLanguage languageOf(String text) {
try {
Detector detector = DetectorFactory.create();
detector.append(text);
String languageCode = detector.detect();
return SupportedLanguage.fromCode(languageCode);
} catch (LangDetectException e) {
e.printStackTrace();
return null;
}
}
protected boolean isSuitableForClassification(String text) {
if ((text == null) || (text.length() < MIN_STRING_LENGTH))
return false;
Matcher matcher = RES_VALUE_PATTERN.matcher(text);
return !matcher.matches();
}
protected TextClassifier getTextClassifierFor(String text) {
SupportedLanguage language = languageOf(text);
if (language == null)
return null;
this.totalSentences++;
this.encounteredLanguages.add(language);
return textClassifierCollection.get(language);
}
/**
* Returns all the languages encountered by this scanner. Note that this
* result is built from {@link ResourceScanner#getEncounteredLanguagesRaw()}
* , so if you modify the set returned by this method, the modifications
* will not be applied to the scanner.
*
* @return
*/
public Set<String> getEncounteredLanguages() {
Set<String> result = new HashSet<>();
for (SupportedLanguage lang : encounteredLanguages) {
result.add(lang.getName());
}
return result;
}
public Set<SupportedLanguage> getEncounteredLanguagesRaw() {
return this.encounteredLanguages;
}
public String getScanReport() {
StringBuilder builder = new StringBuilder();
Set<String> encounteredLanguages = this.getEncounteredLanguages();
if (encounteredLanguages.size() > 0) {
builder.append("Languages: ");
for (String lang : encounteredLanguages)
builder.append(lang.toUpperCase() + ", ");
}
builder.append("Analyzed sentences: ");
builder.append(String.format("%d", this.totalSentences));
return builder.toString();
}
}
| 6,125
| 28.171429
| 93
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/HtmlScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
public class HtmlScanner extends ResourceScanner {
private static final long MAX_HTML_FILE_SIZE = 100000;
public HtmlScanner(TextClassifierCollection textClassifierCollection1) {
super(textClassifierCollection1);
}
public AcceptanceStrategy.Result evaluate(File htmlFile) {
try {
TextClassification classification = this.findRandomwareText(htmlFile);
return acceptanceStrategy.accepts(classification);
} catch (Exception e) {
e.printStackTrace();
return AcceptanceStrategy.fail();
}
}
@Override
protected TextClassification findRansomwareText() {
TextClassification finalClassification = TextClassification.empty();
for (File htmlFile : FileSystem.listFilesRecursively(this.unpackedApkDirectory, ".html")) {
TextClassification htmlTextClassification = this.findRandomwareText(htmlFile);
finalClassification.append(htmlTextClassification);
}
return finalClassification;
}
protected TextClassification findRandomwareText(File htmlFile) {
if (htmlFile.length() > MAX_HTML_FILE_SIZE)
return TextClassification.empty();
try {
Document document = Jsoup.parse(htmlFile, "UTF-8");
Element body = document.body();
TextClassification result = this.classifyElementText(body, TextClassification.empty());
extractLikelihood(htmlFile, result);
result.setFileClassification(getFileClassification());
return result;
} catch (Exception e) {
return TextClassification.empty();
}
}
protected TextClassification classifyElementText(Element element, TextClassification totalClassification) {
String text = element.ownText();
if (isSuitableForClassification(text)) {
TextClassifier textClassifier = this.getTextClassifierFor(text);
if (textClassifier != null) {
TextClassification textClassification = textClassifier.classify(text);
totalClassification.append(textClassification);
}
}
for (Element child : element.children())
this.classifyElementText(child, totalClassification);
return totalClassification;
}
}
| 2,847
| 35.512821
| 111
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/AcceptanceStrategy.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import it.polimi.elet.necst.heldroid.ransomware.text.FileClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
public abstract class AcceptanceStrategy {
public abstract Result accepts(TextClassification textClassification);
public static Result fail() {
Result result = new Result();
result.setAccepted(false);
result.setScore(0);
return result;
}
public static Result fail(double score) {
Result result = fail();
result.setScore(score);
return result;
}
public static Result fail(String comment) {
Result result = fail();
result.setComment(comment);
return result;
}
public static class Result {
private boolean accepted;
private double score;
public String comment;
public FileClassification fileClassification;
public boolean isAccepted() {
return accepted;
}
public void setAccepted(boolean accepted) {
this.accepted = accepted;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public FileClassification getFileClassification() {
return fileClassification;
}
public void setFileClassification(
FileClassification fileClassification) {
this.fileClassification = fileClassification;
}
}
}
| 1,488
| 20.897059
| 87
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/MultiResourceScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import it.polimi.elet.necst.heldroid.ransomware.text.FileClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
public class MultiResourceScanner extends ResourceScanner {
private List<ResourceScanner> internalScanners;
public MultiResourceScanner(TextClassifierCollection classifierCollection) {
super(classifierCollection);
this.internalScanners = new ArrayList<ResourceScanner>();
}
@Override
protected TextClassification findRansomwareText() {
TextClassification finalClassification = TextClassification.empty();
FileClassification finalFileClassification = new FileClassification();
for (ResourceScanner scanner : internalScanners) {
scanner.getFileClassification().clear();
AcceptanceStrategy.Result result = scanner.evaluate();
finalClassification.append(scanner.textClassification);
// Merge results
finalFileClassification.merge(result.getFileClassification());
// Add to this scanner all languages encountered by the internal scanner
this.getEncounteredLanguagesRaw().addAll(scanner.getEncounteredLanguagesRaw());
}
finalClassification.setFileClassification(finalFileClassification);
return finalClassification;
}
@Override
public void setUnpackedApkDirectory(File unpackedApkDirectory) {
super.setUnpackedApkDirectory(unpackedApkDirectory);
for (ResourceScanner scanner : internalScanners)
scanner.setUnpackedApkDirectory(unpackedApkDirectory);
}
@Override
public void setAcceptanceStrategy(AcceptanceStrategy acceptanceStrategy) {
super.setAcceptanceStrategy(acceptanceStrategy);
for (ResourceScanner scanner : internalScanners)
scanner.setAcceptanceStrategy(acceptanceStrategy);
}
public List<ResourceScanner> getScanners() {
return internalScanners;
}
public void add(ResourceScanner scanner) {
this.internalScanners.add(scanner);
}
}
| 2,479
| 36.575758
| 93
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/text/scanning/XmlValuesScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.text.scanning;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class XmlValuesScanner extends ResourceScanner {
private static final int MIN_STRING_LENGTH = 30;
private static final String RESOURCES_TAG = "resources";
private static final String STRING_TAG = "string";
private static final String STRING_ARRAY_TAG = "string-array";
private static final String ITEM_TAG = "item";
private DocumentBuilderFactory dbFactory;
private DocumentBuilder db;
public XmlValuesScanner(TextClassifierCollection classifierCollection) throws ParserConfigurationException {
super(classifierCollection);
this.dbFactory = DocumentBuilderFactory.newInstance();
this.db = dbFactory.newDocumentBuilder();
}
@Override
protected TextClassification findRansomwareText() {
TextClassification finalClassification = TextClassification.empty();
File res = this.getApkResourceDirectory();
File valuesDir = new File(res, "values");
if (valuesDir.exists()) {
for (File stringValuesFile : FileSystem.listFiles(valuesDir, ".xml")) {
TextClassification valuesTextClassification = this.findRansomwareText(stringValuesFile, null);
finalClassification.append(valuesTextClassification);
}
}
for (SupportedLanguage supportedLanguage : textClassifierCollection.getSupposedLanguages()) {
File valuesLangDir = new File(res, "values-" + supportedLanguage.getCode());
if (!valuesDir.exists())
continue;
TextClassifier langTextClassifier = textClassifierCollection.get(supportedLanguage);
for (File stringValuesFile : FileSystem.listFiles(valuesDir, ".xml")) {
TextClassification valuesTextClassification = this.findRansomwareText(stringValuesFile, langTextClassifier);
finalClassification.append(valuesTextClassification);
}
}
return finalClassification;
}
protected TextClassification findRansomwareText(File stringValuesFile, TextClassifier knownClassifier) {
try {
Document document = db.parse(stringValuesFile);
Element root = document.getDocumentElement();
TextClassification result = this.classifyElementText(root, knownClassifier);
extractLikelihood(stringValuesFile, result);
result.setFileClassification(getFileClassification());
return result;
} catch (Exception e) {
return TextClassification.empty();
}
}
protected TextClassification classifyElementText(Element root, TextClassifier knownClassifier) {
if (!root.getTagName().equals(RESOURCES_TAG))
return null;
TextClassification totalClassification = TextClassification.empty();
List<Element> children = Xml.getChildElements(root);
for (Element child : children) {
List<String> contents = new ArrayList<String>();
if (child.getTagName().equals(STRING_TAG)) {
String content = child.getTextContent();
if (isSuitableForClassification(content))
contents.add(content);
} else if (child.getTagName().equals(STRING_ARRAY_TAG)) {
for (Element item : Xml.getChildElements(child)) {
if (!item.getTagName().equals(ITEM_TAG))
continue;
String content = item.getTextContent();
if (isSuitableForClassification(content))
contents.add(content);
}
}
for (String content : contents) {
TextClassifier textClassifier = (knownClassifier != null) ? knownClassifier : this.getTextClassifierFor(content);
if (textClassifier != null) {
TextClassification textClassification = textClassifier.classify(content);
totalClassification.append(textClassification);
}
}
}
return totalClassification;
}
}
| 4,888
| 39.741667
| 129
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/emulation/ReflectionSimulator.java
|
/**
*
*/
package it.polimi.elet.necst.heldroid.ransomware.emulation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.InstructionSimulator;
import it.polimi.elet.necst.heldroid.ransomware.device_admin.InstructionSimulator.Node;
import soot.Immediate;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.infoflow.problems.conditions.BreadthFirstSearch;
import soot.jimple.infoflow.problems.conditions.ConstantDeclarationFinder;
import soot.jimple.infoflow.problems.conditions.DeclarationFinder;
import soot.jimple.infoflow.problems.conditions.SootClassUtil;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
/**
* @author Nicola Dellarocca
*
*/
public class ReflectionSimulator {
public static boolean searchReflection(IInfoflowCFG cfg, ArrayList<String> relatedMethods,
final RefType enforceTargetType) {
if (relatedMethods == null || relatedMethods.isEmpty()) {
throw new IllegalArgumentException(
"You must provide at least one related method");
}
BreadthFirstSearch<Unit> searcher = new BreadthFirstSearch<Unit>(cfg) {
@Override
protected Collection<Unit> nextNodes(Unit current) {
Collection<Unit> result = new HashSet<>(0);
// Add successors
result.addAll(cfg.getSuccsOf(current));
// If this is a method call, add callee's start points
if (cfg.isCallStmt(current)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
current);
for (SootMethod callee : callees) {
result.addAll(cfg.getStartPointsOf(callee));
}
}
return result;
}
@Override
protected boolean isResult(Unit node) {
/*
* If it's not a method call then it is not a valid result.
*/
if (cfg.isCallStmt(node)) {
Collection<SootMethod> callees = cfg.getCalleesOfCallAt(
node);
/*
* Obtain the InvokeExpression to get details of method
* invocation.
*/
InvokeExpr ie = ((Stmt) node).getInvokeExpr();
/*
* This method must have exactly 2 args, otherwise it is the
* wrong method. The args are: 1: Target object 2: Array of
* arguments
*/
if (ie.getArgCount() != 2) {
return false;
}
/*
* Usually there's only 1 callee, but IInfoflowCFG returns a
* collection...
*/
for (SootMethod callee : callees) {
// Get the invoked method's class
SootClass declClass = callee.getDeclaringClass();
// Check the target's type
if (enforceTargetType != null
&& !enforceTargetType.equals(ie .getArg(0)
.getType())) {
return false;
}
/*
* Check that the invoked method is
* java.lang.reflect.Method->invoke
*/
System.out.println("********** CALLEEE: "+callee);
if (callee .getName()
.equals("invoke")
&& SootClassUtil.isOrExtendsClass(declClass,
Method.class)) {
return true;
}
}
}
// If we reach this point it means that no method is found.
return false;
}
};
// Get dummy main entry points
List<SootMethod> entryPoints = Scene.v()
.getEntryPoints();
List<Unit> startPoints = new ArrayList<>();
for (SootMethod entryPoint : entryPoints) {
startPoints.addAll(cfg.getStartPointsOf(entryPoint));
}
// For each entry point let's perform a search
Set<Unit> results = new HashSet<>(0);
for (Unit start : startPoints) {
results.addAll(searcher.search(start, false));
}
System.out.println("****** Start points: "+results.size());
/*
* If there is at least 1 result search for relatedMethods, otherwise
* return null;
*/
if (results.isEmpty()) {
return false;
}
/*
* Find the declaration (i.e. variable assignment) for the method that
* is invoked through reflection. In other words we want to find an
* instruction like:
*
* java.lang.Method object = <whatever>
*/
Set<Unit> methodSearched = null;
for (Unit methodInvocation : results) {
Value reflectionMethodLocal = ((InstanceInvokeExpr) ((Stmt) methodInvocation).getInvokeExpr()).getBase();
DeclarationFinder finder = new DeclarationFinder(cfg,
reflectionMethodLocal);
methodSearched = finder.search(methodInvocation, true);
}
/*
* The assignment must exist somewhere in the code. Check if we were
* able to find it
*/
if (methodSearched == null || methodSearched.isEmpty()) {
return false;
}
/*
* Here we want to check if the method invoked through reflection is one
* of the relatedMethods.
*/
try {
/*
* The set of names of those methods that are invoked through
* reflection
*/
Set<String> names = findHardcodedMethodName(cfg, methodSearched,
relatedMethods);
System.out.println("*** Related methods = " + relatedMethods);
System.out.println("*** HarcodedMethodNames = " + names);
// Check if at least one related method is contained inside the set
// for (String relatedMethod : relatedMethods) {
// if (names.contains(relatedMethod))
// return true;
// }
for (String name : names) {
if (relatedMethods.contains(
(enforceTargetType != null ? (enforceTargetType.getClassName() + "->") : "") + name)) {
System.out.println("*** YAY");
return true;
}
}
System.out.println("NAY");
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static Set<String> findHardcodedMethodName(IInfoflowCFG cfg,
Set<Unit> reflectionMethodInvokes,
ArrayList<String> methodsToFind) {
for (Unit reflectionMethodInvoke : reflectionMethodInvokes) {
if (reflectionMethodInvoke instanceof AssignStmt
&& cfg.isCallStmt(reflectionMethodInvoke)) {
AssignStmt assignStmt = (AssignStmt) reflectionMethodInvoke;
InvokeExpr ie = assignStmt.getInvokeExpr();
System.out.println(
"****** " + assignStmt + " -> " + ie.getArg(0)
.getType());
// Ensure that the first parameter is of type String
if (!ie .getArg(0)
.getType()
.equals(RefType.v("java.lang.String"))) {
return null;
}
System.out.println("Is string constant??? "+ ie +" -> "+(ie.getArg(0) instanceof StringConstant));
if (ie.getArg(0) instanceof StringConstant) {
Set<String> result = new HashSet<>();
result.add(((StringConstant) (ie.getArg(0))).value);
return result;
}
// Find method name
// findMethodNameReflection(iie.getBase(), callStmt);
ConstantDeclarationFinder finder = new ConstantDeclarationFinder(
cfg, ie.getArg(0));
Set<Unit> constantDeclarations = finder.search(assignStmt,
true);
System.out.println(
"*** Constant decL = " + constantDeclarations);
Set<String> extractedHardcodedNames = new HashSet<>(0);
for (Unit constantDeclaration : constantDeclarations) {
if (constantDeclaration instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) constantDeclaration;
Value methodName = assign.getRightOp();
String extractedString = extractString(cfg, methodName,
constantDeclaration);
InstructionSimulator simulator = new InstructionSimulator(
cfg, constantDeclaration,
reflectionMethodInvoke);
Set<InstructionSimulator.Node> nodes = simulator.search(
new InstructionSimulator.Node(extractedString,
constantDeclaration),
true);
for (Node n : nodes) {
extractedHardcodedNames.add(n.getValue());
}
return extractedHardcodedNames;
} else if (constantDeclaration instanceof InvokeStmt) {
InvokeExpr ie2 = ((InvokeStmt) constantDeclaration).getInvokeExpr();
for (int i = 0; i < ie2.getArgCount(); i++) {
Value argument = ie2.getArg(i);
if (argument instanceof StringConstant) {
InstructionSimulator simulator = new InstructionSimulator(
cfg, constantDeclaration,
reflectionMethodInvoke);
Set<Node> nodes = simulator.search(
new InstructionSimulator.Node(
((StringConstant) argument).value,
constantDeclaration),
true);
for (Node n : nodes)
extractedHardcodedNames.add(n.getValue());
return extractedHardcodedNames;
}
}
} else {
throw new Error("Cannot retrieve hardcoded value");
}
return extractedHardcodedNames;
}
}
}
return null;
}
private static String extractString(IInfoflowCFG cfg, Value value, Unit usageNode) {
if (value instanceof StringConstant) {
return ((StringConstant) value).value;
}
if (value .getType()
.equals(RefType.v("java.lang.String"))) {
/*
* Here we should look for the string definition and, if there is
* any transformation to the string (e.g. "replace" or
* "replaceAll"), apply it to get the final String.
*
* Finally we should return it, if we can find it, otherwise return
* null.
*/
ConstantDeclarationFinder finder = new ConstantDeclarationFinder(
cfg, value);
Set<Unit> declarations = finder.search(usageNode, true);
if (declarations.isEmpty()) {
/*
* We didn't succeed in finding the declaration. Return null.
*/
return null;
}
for (Unit declaration : declarations) {
/*
* It is safe, since ConstantDeclarationFinder returns only
* AssignStmts
*/
AssignStmt assign = (AssignStmt) declaration;
/*
* It is safe, since ConstantDeclarationFinder returns only
* assignment of constants
*/
Constant rightOp = (Constant) assign.getRightOp();
/*
* If the constant is a string, simulate its possible
* transformations
*/
if (rightOp instanceof StringConstant) {
String raw = ((StringConstant) rightOp).value;
// simulateTransformations(raw, declaration, usageNode);
}
// Otherwise return null
return null;
}
}
System.out.println("Cannot extract type: " + value.getType());
return null;
}
}
| 10,465
| 28.153203
| 108
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/emulation/TrafficScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.emulation;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import org.jnetpcap.Pcap;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.protocol.tcpip.Http;
import org.jnetpcap.protocol.tcpip.Tcp;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.AcceptanceStrategy;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.HtmlScanner;
public class TrafficScanner {
private static final String HTML_MIME_TYPE = "text/html";
private static final String TRACEDROID_USERAGENT = "Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; generic Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
private static final File TEMP_HTML_STORAGE = new File("pcap-html");
private Set<String> unreachableHosts;
private HtmlScanner htmlScanner;
private Pcap pcap;
private StringBuilder errorBuffer;
private PcapPacketHandler<String> packetHandler;
private AcceptanceStrategy.Result finalResult;
private boolean analysisFinished = false;
public TrafficScanner(final HtmlScanner htmlScanner) {
if (!TEMP_HTML_STORAGE.exists())
TEMP_HTML_STORAGE.mkdir();
this.htmlScanner = htmlScanner;
this.unreachableHosts = new HashSet<String>();
this.packetHandler = new PcapPacketHandler<String>() {
@Override
public void nextPacket(PcapPacket packet, String user) {
if (analysisFinished)
return;
Tcp tcp = new Tcp();
Http http = new Http();
if (!packet.hasHeader(tcp) || !packet.hasHeader(http))
return;
if (!http.hasField(Http.Request.Accept) || !http.fieldValue(Http.Request.Accept).contains(HTML_MIME_TYPE))
return;
File htmlFile = resendRequest(http);
if (htmlFile == null)
return;
AcceptanceStrategy.Result result = htmlScanner.evaluate(htmlFile);
if (result.isAccepted()) {
analysisFinished = true;
finalResult = result;
}
}
};
}
public void setPcap(File pcapFile) {
if (!pcapFile.getAbsolutePath().endsWith(".pcap"))
throw new IllegalArgumentException("Not a pcap file!");
this.errorBuffer = new StringBuilder();
this.pcap = Pcap.openOffline(pcapFile.getAbsolutePath(), errorBuffer);
}
public AcceptanceStrategy.Result analyze() {
if (pcap == null)
throw new NullPointerException("No pcap file set!");
finalResult = AcceptanceStrategy.fail();
analysisFinished = false;
try {
pcap.loop(Pcap.LOOP_INFINITE, packetHandler, "");
} finally {
pcap.close();
}
return finalResult;
}
private File resendRequest(Http http) {
String host = http.fieldValue(Http.Request.Host);
String requestUrl = "http://" + host + http.fieldValue(Http.Request.RequestUrl);
if (unreachableHosts.contains(host) || requestUrl.endsWith(".jpg") || requestUrl.endsWith(".png"))
return null;
String referer = http.fieldValue(Http.Request.Referer);
String language = http.fieldValue(Http.Request.Accept_Language);
String acceptEncoding = http.fieldValue(Http.Request.Accept_Encoding);
String accept = http.fieldValue(Http.Request.Accept);
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", host);
connection.setRequestProperty("User-Agent", TRACEDROID_USERAGENT);
if (isNotEmpty(referer))
connection.setRequestProperty("Referer", referer);
if (isNotEmpty(language))
connection.setRequestProperty("Accept-Language", language);
if (isNotEmpty(acceptEncoding))
connection.setRequestProperty("Accept-Encoding", acceptEncoding);
if (isNotEmpty(accept))
connection.setRequestProperty("Accept", accept);
connection.setUseCaches(false);
InputStream is = connection.getInputStream();
String type = connection.getContentType();
String encoding = connection.getContentEncoding();
File htmlFile = new File(TEMP_HTML_STORAGE, String.format("%x.html", http.hashCode()));
if ((type == null) || (!type.contains("html")))
return null;
if (encoding == null)
encoding = "text/html";
if (encoding.contains("gzip"))
decompressGzip(is, htmlFile);
else
writeAll(is, htmlFile);
return htmlFile;
} catch (Exception e) {
if (e.getMessage().contains("timed out"))
unreachableHosts.add(host);
return null;
}
}
private static boolean decompressGzip(InputStream in, File output) {
byte[] buffer = new byte[4096];
try {
GZIPInputStream gzip = new GZIPInputStream(in);
FileOutputStream out = new FileOutputStream(output);
int len;
while ((len = gzip.read(buffer)) > 0)
out.write(buffer, 0, len);
gzip.close();
out.close();
return true;
} catch (IOException ex) {
return false;
}
}
private static void writeAll(final InputStream in, final File output) throws FileNotFoundException {
ExecutorService executor = Executors.newSingleThreadExecutor();
final FileOutputStream out = new FileOutputStream(output);
executor.submit(new Runnable() {
@Override
public void run() {
byte[] buffer = new byte[4096];
try {
int len;
while ((len = in.read(buffer)) > 0) {
synchronized (out) {
out.write(buffer, 0, len);
}
}
in.close();
synchronized (out) {
out.close();
}
} catch (IOException ex) { }
}
});
executor.shutdownNow();
try {
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
synchronized (out) {
out.flush();
out.close();
}
}
} catch (Exception e) { }
}
private static boolean isNotEmpty(String str) {
return (str != null) && !str.equals("");
}
}
| 7,342
| 31.78125
| 193
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/ransomware/images/ImageScanner.java
|
package it.polimi.elet.necst.heldroid.ransomware.images;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import org.languagetool.Language;
import org.languagetool.Languages;
import org.languagetool.MultiThreadedJLanguageTool;
import org.languagetool.language.AmericanEnglish;
import org.languagetool.rules.Rule;
import org.languagetool.rules.spelling.SpellingCheckRule;
import org.languagetool.tools.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.polimi.elet.necst.heldroid.ransomware.text.SupportedLanguage;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassification;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifier;
import it.polimi.elet.necst.heldroid.ransomware.text.classification.TextClassifierCollection;
import it.polimi.elet.necst.heldroid.ransomware.text.scanning.ResourceScanner;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
public class ImageScanner extends ResourceScanner {
private static final Logger logger = LoggerFactory.getLogger(ImageScanner.class);
// Min number of characters that text must contain to be analysed
private static final int MIN_TEXT_LENGTH = 15;
private static final String TESSERACT_DEFAULT_LANG = "eng+rus";
/*
* The biggest Android icon usually measures 200x200 px.
*/
private static final int MIN_IMAGE_HEIGHT = 201; // Pixels
private static final int MIN_IMAGE_WIDTH = 201; // Pixels
private String tesseractLanguage = TESSERACT_DEFAULT_LANG;
public ImageScanner(TextClassifierCollection textClassifierCollection) {
super(textClassifierCollection);
logger.info("Creating ImageScanner");
}
@Override
protected TextClassification findRansomwareText() {
TextClassification finalClassification = TextClassification.empty();
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// Android drawable resources can be jpg, png or gif files
final String[] extensions = new String[] { ".jpg", ".png",
".gif" };
for (String ext : extensions) {
/*
* Icons starting with "abc_" belongs to android appcompat
* v7
*/
if (!name.startsWith("abc_") && name.endsWith(ext))
return true;
}
return false;
}
};
// Search all images inside res and assets folders
File resFolder = new File(this.unpackedApkDirectory, "res");
File assetsFolder = new File(this.unpackedApkDirectory, "assets");
List<File> filesToScan = new LinkedList<>();
if (resFolder.exists()) {
filesToScan.addAll(
FileSystem.listFilesRecursively(resFolder, filter));
}
if (assetsFolder.exists()) {
filesToScan.addAll(
FileSystem.listFilesRecursively(assetsFolder, filter));
}
// Analyze files
for (File file : filesToScan) {
TextClassification partial = this.findRansomwareText(file);
finalClassification.append(partial);
}
return finalClassification;
}
private TextClassification findRansomwareText(File image) {
try {
/*
* We will discard small images, since they can be icons and we
* don't want to waste time
*/
if (!shouldAnalyze(image)) {
System.out.println("Skipping small image: " + image.getName());
return TextClassification.empty();
}
File imageBW = convertToGrayscale(image);
String extracted = extractText(imageBW);
// Remove unnecessary file
imageBW.delete();
if (extracted != null) {
TextClassification result = this.classifyElementText(extracted,
TextClassification.empty());
extractLikelihood(image, result);
result.setFileClassification(getFileClassification());
return result;
}
} catch (IOException e) {
System.err.println(
"Cannot convert image to grayscale: " + e.getMessage());
}
return TextClassification.empty();
}
private boolean shouldAnalyze(File image) {
try {
BufferedImage bi = ImageIO.read(image);
return bi != null &&
bi.getWidth() >= MIN_IMAGE_WIDTH &&
bi.getHeight() >= MIN_IMAGE_HEIGHT;
} catch (IOException e) {
// If we cannot open the image we cannot analyze it
System.err.println("Cannot open image: " + image.getName());
return false;
}
}
protected TextClassification classifyElementText(String text,
TextClassification totalClassification) {
if (isSuitableForClassification(text)) {
TextClassifier textClassifier = this.getTextClassifierFor(text);
if (textClassifier != null) {
TextClassification textClassification = textClassifier.classify(
text);
totalClassification.append(textClassification);
}
}
return totalClassification;
}
private String extractText(File image) {
// Use tesseract
String extracted = tesseract(image);
if (extracted .trim()
.length() >= MIN_TEXT_LENGTH) {
// Detect language
SupportedLanguage lang = languageOf(extracted);
if (lang != null) {
// Apply text corrector
return correct(extracted, lang);
}
}
return null;
}
/**
* Tries to correct the text by applying the rules related to the supplied
* language.
*
* @param text
* The text to correct
* @param lang
* The language of {@code text}
* @return The corrected text
* @throws IllegalArgumentException
* If the language is not supported or unrecognized
*/
private String correct(String extracted, SupportedLanguage lang)
throws IllegalArgumentException {
Language language = null;
/*
* Create the language automatically from language code. The only
* exception is english language, since we need to know the country
* variant of the language (e.g. en-US).
*/
if (lang == SupportedLanguage.ENGLISH) {
// By default we'll use american english for english lang
language = new AmericanEnglish();
} else {
language = Languages.getLanguageForShortName(lang.getCode());
}
// Main class of the corrector. Uses as much threads as CPU cores
// available
MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(language,
Runtime .getRuntime()
.availableProcessors());
// Disable useless rules
lt.disableRule("WHITESPACE_RULE");
// Words whitelist
List<String> wordsToIgnore = Arrays.asList("moneypak", "greendot");
for (Rule rule : lt.getAllActiveRules()) {
if (rule instanceof SpellingCheckRule) {
((SpellingCheckRule) rule).addIgnoreTokens(wordsToIgnore);
}
}
// JLanguageTool expects the Unicode text to be in NFKC form
extracted = Normalizer.normalize(extracted, Normalizer.Form.NFKC);
try {
String corrected = Tools.correctText(extracted, lt);
return corrected;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Instructs Tesseract to recognize character based on the specified
* language(s). If {@code hint} is {@code null}, a default language of
* "eng+rus" will be used.
*
* @param hint
* The languages Tesseract should use.
*/
public void setTesseractLanguage(Set<SupportedLanguage> hint) {
if (hint == null || hint.size() == 0) {
// This will set the default value for tesseract
this.tesseractLanguage = TESSERACT_DEFAULT_LANG;
return;
}
Iterator<SupportedLanguage> iterator = hint.iterator();
// Join all hints with a "plus" sign
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
builder.append(iterator .next()
.getIso3code());
builder.append('+');
}
// Remove trailing "plus"
builder.setLength(builder.length() - 1);
this.tesseractLanguage = builder.toString();
}
private String tesseract(File image) {
if (tesseractLanguage == null) {
tesseractLanguage = TESSERACT_DEFAULT_LANG;
}
BufferedReader reader = null;
File extractedTextFile = null;
try {
extractedTextFile = File.createTempFile("extracted", ".txt");
String extractedTextWithoutExtension = extractedTextFile.getAbsolutePath()
.substring(
0,
extractedTextFile .getAbsolutePath()
.lastIndexOf(
'.'));
Process tesseract = Runtime .getRuntime()
.exec(new String[] { "tesseract",
image.getAbsolutePath(),
extractedTextWithoutExtension,
"-l", tesseractLanguage, "-c",
"tessedit_char_blacklist=|\\" });
tesseract.waitFor();
reader = new BufferedReader(new FileReader(extractedTextFile));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (extractedTextFile != null) {
extractedTextFile.delete();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// instance.setDatapath("/usr/local/share/tessdata/");
// instance.setLanguage(tesseractLanguage);
// Ignore the following chars: | (pipe), \ (backslash)
// instance.setTessVariable("tessedit_char_blacklist", "|\\");
// try {
// String result = instance.doOCR(image);
// return result;
// } catch (TesseractException e) {
// e.printStackTrace();
// }
return null;
}
private File convertToGrayscale(File image) throws IOException {
// Open the original image
BufferedImage bi = ImageIO.read(image);
int width, height;
width = bi.getWidth();
height = bi.getHeight();
// Transform each pixel's color
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color c = new Color(bi.getRGB(j, i));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
int sum = red + green + blue;
int threshold = 256 / 2;
/*
* If it is a dark color, transform it to black, otherwise leave
* it as it is
*/
if (sum < threshold) {
sum = 0;
}
Color newColor = new Color(sum, sum, sum);
// Change image color
bi.setRGB(j, i, newColor.getRGB());
}
}
// Create temp "black/white" image, it will be deleted after analysis
File output = File.createTempFile("gray", ".png");
ImageIO.write(bi, "png", output);
return output;
}
}
| 10,693
| 27.902703
| 93
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/Main.java
|
package it.polimi.elet.necst.heldroid.goodware;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.json.JSONObject;
import it.polimi.elet.necst.heldroid.csv.FeaturesWriter;
import it.polimi.elet.necst.heldroid.csv.PerformancesWriter;
import it.polimi.elet.necst.heldroid.goodware.features.AdwareFilter;
import it.polimi.elet.necst.heldroid.goodware.features.DangerousApiFilter;
import it.polimi.elet.necst.heldroid.goodware.features.DangerousPermissionsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.FileMetricsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.HarmlessPermissionsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.HiddenApkFilter;
import it.polimi.elet.necst.heldroid.goodware.features.PackageFilter;
import it.polimi.elet.necst.heldroid.goodware.features.PotentialLeakageFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SmsNumbersFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousFlowFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousIntentFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousUrlsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SystemCallsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.ValidDomainFilter;
import it.polimi.elet.necst.heldroid.goodware.features.core.Feature;
import it.polimi.elet.necst.heldroid.goodware.features.core.MetaFeatureGatherer;
import it.polimi.elet.necst.heldroid.goodware.weka.ApkClassifier;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.utils.FileSystem;
import it.polimi.elet.necst.heldroid.utils.Options;
import it.polimi.elet.necst.heldroid.utils.PersistentFileList;
public class Main {
public static void printUsage() {
System.out.println("GoodwareFilter.jar source features-file [-s] [-g] [-c model attributes]");
System.out.println("source:");
System.out.println(" an apk file, a directory containing an unpacked apk file, ");
System.out.println(" a .apklist text file containing a line-by-line list of absolute apk paths");
System.out.println(" or a directory (which will be recursively searched for any of the above)");
System.out.println("features-file:");
System.out.println(" a csv file containing extracted features, and possibly a prediction");
System.out.println(" if -c is enabled");
System.out.println("-s: silent mode");
System.out.println(" Only classifications and critical exceptions are written in output");
System.out.println("-g: google play mode");
System.out.println(" Also downloads meta-data from google play store as features");
System.out.println("-c: classification mode");
System.out.println(" model is a valid weka model file and attributes an data-empty arff file that");
System.out.println(" specifies attributes used by the model. Only features whose name is included in");
System.out.println(" the attribute list are mined");
System.out.println("-server: server mode");
System.out.println(" starts a classification http server that receives an apk file as an octet-stream");
System.out.println(" in a multipart/form-data POST request and returns a json response containing features");
System.out.println(" and class probabilities. Route to use is /scan. To pass an hash, perform a GET request");
System.out.println(" to route /hash passing 'hash' as query parameter");
}
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length < 2) {
printUsage();
return;
}
mainArgs = args;
final File target = new File(args[0]);
Options options = new Options(args);
classificationEnabled = false;
if (options.contains("-c")) {
String[] classifierParams = options.getParameters("-c", 2);
File model = new File(classifierParams[0]);
File attributes = new File(classifierParams[1]);
apkClassifier = new ApkClassifier(model, attributes);
classificationEnabled = true;
}
if (options.contains("-server")) {
MainServer server = new MainServer(apkClassifier, target);
server.run();
return;
}
silentMode = options.contains("-s");
metaFeatureGatherer = new MetaFeatureGatherer();
metaFeatureGatherer.add(new DangerousPermissionsFilter());
metaFeatureGatherer.add(new DangerousApiFilter());
metaFeatureGatherer.add(new PotentialLeakageFilter());
metaFeatureGatherer.add(new AdwareFilter());
metaFeatureGatherer.add(new SuspiciousUrlsFilter());
metaFeatureGatherer.add(new PackageFilter());
metaFeatureGatherer.add(new FileMetricsFilter());
metaFeatureGatherer.add(new SystemCallsFilter());
metaFeatureGatherer.add(new HarmlessPermissionsFilter());
metaFeatureGatherer.add(new SuspiciousIntentFilter());
metaFeatureGatherer.add(new HiddenApkFilter()); // TODO: remove
metaFeatureGatherer.add(new SmsNumbersFilter()); // TODO: remove
metaFeatureGatherer.add(new ValidDomainFilter());
metaFeatureGatherer.add(new SuspiciousFlowFilter());
if (classificationEnabled) {
// Only enables used attributes as features to be extracted
metaFeatureGatherer.disableAllFeatures();
metaFeatureGatherer.enableFeatures(apkClassifier.getAttributesNames());
}
boolean includeGoogle = options.contains("-g");
if (includeGoogle) {
System.err.println("WARNING: support for Google Play metadata retrieval has been removed");
//metaFeatureGatherer.add(new PlayStorePermissionsFilter());
//metaFeatureGatherer.add(new PlayStorePopularityFilter());
}
examinedFiles = new PersistentFileList(new File(EXAMINED_FILES_LIST_NAME));
featuresWriter = new FeaturesWriter(new File(args[1]), metaFeatureGatherer.getAllFiltersFeatures(), classificationEnabled);
performancesWriter = new PerformancesWriter(new File(PERFORMANCE_FILENAME));
availableFiles = new ArrayList<File>();
availableUnpackedData = new ArrayList<ApplicationData>();
unpackingTimes = new ArrayList<Double>();
fileEnumeratingThread = new Thread(new Runnable() {
@Override
public void run() {
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName().toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
synchronized (fileEnumerationFinishedLock) {
fileEnumerationFinished = true;
}
}
});
unpackingThread = new Thread(new Runnable() {
@Override
public void run() {
unpackingRoutine();
}
});
analysisThread = new Thread(new Runnable() {
@Override
public void run() {
analysisRoutine();
}
});
fileEnumeratingThread.start();
unpackingThread.start();
analysisThread.start();
fileEnumeratingThread.join();
unpackingThread.join();
analysisThread.join();
closeWriters();
}
private static void println(String message) {
if (!silentMode)
System.out.println(message);
}
private static void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
if (aborted)
return;
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private static void readFileList(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkFile(File file) {
if (examinedFiles.contains(file)) {
println("Skipped: " + file.getName());
return;
}
if (file.isFile()) {
synchronized (availableFiles) {
availableFiles.add(file);
}
}
}
private static void unpackingRoutine() {
while (true) {
if (aborted)
return;
int unpackedApksCount;
synchronized (availableUnpackedData) {
unpackedApksCount = availableUnpackedData.size();
}
if (unpackedApksCount >= MAX_ALLOWED_UNPACKED_APKS_IN_MEMORY) {
analysisStalls++;
if (analysisStalls >= MAX_ANALYSIS_STALLS) {
println("Stalled " + analysisStalls + " times. Maybe analysis thread crahsed? Restarting.");
restartApplication();
return;
}
try {
println("Analysis too slow: unpacking routine stalled for " + UNPACKING_WAIT_TIME + " seconds");
Thread.sleep(UNPACKING_WAIT_TIME * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
continue;
}
} else {
analysisStalls = 0;
}
File file;
synchronized (availableFiles) {
synchronized (fileEnumerationFinishedLock) {
if (fileEnumerationFinished && (availableFiles.size() == 0))
break;
}
if (availableFiles.size() == 0)
continue;
file = availableFiles.get(0);
}
println("Unpacking: " + file.getName());
try {
Long startTime = System.currentTimeMillis();
ApplicationData applicationData = ApplicationData.open(file);
Long endTime = System.currentTimeMillis();
synchronized (availableUnpackedData) {
availableUnpackedData.add(applicationData);
unpackingTimes.add((double)(endTime - startTime) / 1000.0);
}
println("Unpacked: " + file.getName());
} catch (Exception e) {
println("Dropped: " + file.getName() + "; " + e.getMessage());
}
synchronized (availableFiles) {
availableFiles.remove(0);
}
}
}
private static void analysisRoutine() {
while (true) {
if (aborted)
return;
ApplicationData applicationData;
Double unpackingTime;
synchronized (availableUnpackedData) {
if (availableUnpackedData.size() == 0) {
synchronized (availableFiles) {
synchronized (fileEnumerationFinishedLock) {
if (fileEnumerationFinished && (availableFiles.size() == 0))
break;
else
continue;
}
}
}
applicationData = availableUnpackedData.get(0);
unpackingTime = unpackingTimes.get(0);
}
scanData(applicationData, unpackingTime);
synchronized (availableUnpackedData) {
availableUnpackedData.remove(0);
unpackingTimes.remove(0);
}
}
}
private static void scanData(final ApplicationData applicationData, Double unpackingTime) {
String apkName = applicationData.getDecodedPackage().getOriginalApk().getAbsolutePath();
println("Submitted: " + apkName);
Long startTime = System.currentTimeMillis();
metaFeatureGatherer.matchAllFilters(applicationData);
Long endTime = System.currentTimeMillis();
Collection<Feature> features = metaFeatureGatherer.getAllFiltersFeatures();
Double detectionRatio = checkAnalysisDetectionRatio(applicationData.getDecodedPackage().getOriginalApk());
Double analysisTime = (double)(endTime - startTime) / 1000.0;
Double classificationTime = 0.0;
String predictedClass = "";
if (classificationEnabled) {
startTime = System.nanoTime();
predictedClass = apkClassifier.classify(features);
endTime = System.nanoTime();
classificationTime = (double)(endTime - startTime) / 1e+6;
System.out.println(apkName + " classified as " + predictedClass); // not affected by silent mode
}
featuresWriter.writeAll(apkName, features, detectionRatio, predictedClass);
performancesWriter.writeAll(applicationData, unpackingTime, analysisTime, classificationTime);
examinedFiles.add(applicationData.getDecodedPackage().getOriginalApk());
// This process often takes time but is unimportant to the computation's end
Thread disposeThread = new Thread(new Runnable() {
@Override
public void run() {
applicationData.dispose();
}
});
disposeThread.run();
println("Completed: " + apkName);
}
private static Double checkAnalysisDetectionRatio(File apkFile) {
File directory = apkFile.getParentFile();
File vtResult = new File(directory, VT_RESULT_FILENAME);
if (!vtResult.exists())
return null;
try {
String jsonContent = FileSystem.readFileAsString(vtResult);
JSONObject vtAnalysis = new JSONObject(jsonContent);
JSONObject scans = vtAnalysis.getJSONObject("scans");
int detectionCount = 0;
int totalScans = 0;
Iterator<?> iterator = scans.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
Object field = scans.get(key);
if (field instanceof JSONObject) {
JSONObject scan = (JSONObject)field;
Boolean detected = scan.getBoolean("detected");
totalScans++;
if (detected)
detectionCount++;
}
}
return ((double)detectionCount / totalScans);
} catch (Exception e) {
return null;
}
}
private static void closeWriters() throws IOException {
featuresWriter.close();
performancesWriter.close();
examinedFiles.dispose();
}
public static void restartApplication()
{
synchronized (fileEnumerationFinishedLock) {
fileEnumerationFinished = true;
}
synchronized (availableFiles) {
availableFiles.clear();
}
synchronized (availableUnpackedData) {
availableUnpackedData.clear();
}
aborted = true; // not important to synchronize it
try {
closeWriters();
} catch (IOException e) {
e.printStackTrace();
}
try {
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
File currentJar = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
List<String> commands = new ArrayList<String>();
commands.add(javaBin);
commands.add("-jar");
commands.add(currentJar.getPath());
for (int i = 0; i < mainArgs.length; i++)
commands.add(mainArgs[i]);
final ProcessBuilder builder = new ProcessBuilder(commands);
builder.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(-1);
}
}
private static final String EXAMINED_FILES_LIST_NAME = "examined.txt";
private static final String VT_RESULT_FILENAME = "vt_result.json";
private static final String PERFORMANCE_FILENAME = "diagnostics.csv";
// Maximum allowed number of unpacked applications that can reside as an ApplicationData class in memory
// When this number is reached, the unpacking thread waits for UNPACKING_WAIT_TIME before continuing
private static final int MAX_ALLOWED_UNPACKED_APKS_IN_MEMORY = 15;
private static final int UNPACKING_WAIT_TIME = 5; // seconds
// Maximum number of times analysis can stall: beyond this, the program assumes the analysis thread has
// crashed and restarts
private static final int MAX_ANALYSIS_STALLS = 36; // 36 = 3 minutes
private static int analysisStalls = 0;
private static Object fileEnumerationFinishedLock = new Object();
private static Boolean fileEnumerationFinished = false;
private static Boolean aborted = false;
private static Boolean silentMode = false;
private static boolean classificationEnabled;
private static ApkClassifier apkClassifier;
private static MetaFeatureGatherer metaFeatureGatherer;
private static FeaturesWriter featuresWriter;
private static PerformancesWriter performancesWriter;
private static PersistentFileList examinedFiles;
private static List<File> availableFiles;
private static List<ApplicationData> availableUnpackedData;
private static List<Double> unpackingTimes; // list of times required to unpack an apk
private static Thread fileEnumeratingThread, unpackingThread, analysisThread;
private static String[] mainArgs;
}
| 18,516
| 37.179381
| 131
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/MainServer.java
|
package it.polimi.elet.necst.heldroid.goodware;
import com.sun.net.httpserver.*;
import it.polimi.elet.necst.heldroid.goodware.features.*;
import it.polimi.elet.necst.heldroid.goodware.features.core.Feature;
import it.polimi.elet.necst.heldroid.goodware.features.core.MetaFeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.utils.*;
import it.polimi.elet.necst.heldroid.goodware.weka.ApkClassifier;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.Executors;
public class MainServer implements Runnable {
private static final int MAX_THREADS_COUNT = 20;
private ApkClassifier sharedClassifier;
private File uploadDirectory;
private File hashDirectory;
private String[] classLabels;
public MainServer(ApkClassifier sharedClassifier, File uploadDirectory) {
this.sharedClassifier = sharedClassifier;
this.uploadDirectory = uploadDirectory;
if (!uploadDirectory.exists())
if (!uploadDirectory.mkdir())
throw new RuntimeException("Cannot create upload directory!");
this.hashDirectory = new File(uploadDirectory, "hash");
if (!hashDirectory.exists())
if (!hashDirectory.mkdir())
throw new RuntimeException("Cannot create hash directory!");
this.classLabels = sharedClassifier.getClassLabels();
}
private String fetchResponseByHash(String hash) throws IOException {
File savedResponse = new File(this.hashDirectory, hash + ".json");
if (savedResponse.exists())
return FileSystem.readFileAsString(savedResponse);
return null;
}
private void saveResponseByHash(String hash, String response) throws IOException {
File savedResponse = new File(this.hashDirectory, hash + ".json");
OutputStream stream = new FileOutputStream(savedResponse);
stream.write(response.getBytes());
stream.close();
}
@Override
public void run() {
HttpServer server = null;
try {
server = HttpServer.create(new InetSocketAddress(8000), 0);
} catch (IOException e) {
e.printStackTrace();
}
server.createContext("/scan", new ScanHandler());
HttpContext context = server.createContext("/fetch-scan", new HashHandler());
context.getFilters().add(new ParameterFilter());
server.setExecutor(Executors.newFixedThreadPool(MAX_THREADS_COUNT)); // creates a default executor
server.start();
}
private String buildResponseFromScan(File file) {
MetaFeatureGatherer gatherer = this.createGatherer();
ApplicationData applicationData;
try {
applicationData = ApplicationData.open(file);
} catch (Exception e) {
return "Error unpacking: " + e.getMessage();
}
gatherer.matchAllFilters(applicationData);
applicationData.dispose();
Collection<Feature> features = gatherer.getAllFiltersFeatures();
double[] classDistribution;
synchronized (MainServer.this.sharedClassifier) {
classDistribution = MainServer.this.sharedClassifier.computeDistribution(features);
}
return this.buildResponseFromResults(features, classDistribution);
}
private String buildResponseFromResults(Collection<Feature> features, double[] classDistribution) {
StringBuilder builder = new StringBuilder();
boolean firstLine;
builder.append("{\n");
builder.append(" features: [\n ");
firstLine = true;
for (Feature f : features) {
if (!firstLine) builder.append(",\n ");
builder.append(String.format("{ name: \"%s\", value: \"%s\" }", f.getName(), f.getValue()));
firstLine = false;
}
builder.append("\n ],\n ");
firstLine = true;
for (int i = 0; i < classDistribution.length; i++) {
if (!firstLine) builder.append(",\n ");
builder.append(String.format("%s: %s", MainServer.this.classLabels[i], String.valueOf(classDistribution[i])));
firstLine = false;
}
builder.append("\n}");
return builder.toString();
}
private MetaFeatureGatherer createGatherer() {
MetaFeatureGatherer metaFeatureGatherer = new MetaFeatureGatherer();
metaFeatureGatherer.add(new DangerousPermissionsFilter());
metaFeatureGatherer.add(new DangerousApiFilter());
metaFeatureGatherer.add(new PotentialLeakageFilter());
metaFeatureGatherer.add(new AdwareFilter());
metaFeatureGatherer.add(new SuspiciousUrlsFilter());
metaFeatureGatherer.add(new PackageFilter());
metaFeatureGatherer.add(new FileMetricsFilter());
metaFeatureGatherer.add(new SystemCallsFilter());
metaFeatureGatherer.add(new HarmlessPermissionsFilter());
metaFeatureGatherer.add(new SuspiciousIntentFilter());
metaFeatureGatherer.add(new HiddenApkFilter());
metaFeatureGatherer.add(new SmsNumbersFilter());
metaFeatureGatherer.add(new ValidDomainFilter());
metaFeatureGatherer.add(new SuspiciousFlowFilter());
metaFeatureGatherer.disableAllFeatures();
metaFeatureGatherer.enableFeatures(MainServer.this.sharedClassifier.getAttributesNames());
return metaFeatureGatherer;
}
private abstract class BaseHandler implements HttpHandler {
protected void respond(HttpExchange exchange, int statusCode, String message) throws IOException {
byte[] bytes = message.getBytes();
exchange.sendResponseHeaders(501, bytes.length);
OutputStream stream = exchange.getResponseBody();
stream.write(bytes);
stream.close();
}
}
private class ScanHandler extends BaseHandler implements HttpHandler {
private static final String MULTIPLART_MIME_TYPE = "multipart/form-data";
private static final String OCTET_STREAM_MIME_TYPE = "application/octet-stream";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String BOUNDARY_FIELD = "boundary";
private static final String BOUNDARY_PREFIX = "--";
private static final String BOUNDARY_SUFFIX = "--";
/**
* Scans an apk sent as application/octect-stream and returns the scan results.
* Notice that a connection-reset socket exception is thrown is this method returns without reading the
* whole request stream. Therefore, to mitigate useless reads, if an error arises before starting the read
* phase, the client cannot know which error it was.
* @param t
* @throws IOException
*/
public void handle(HttpExchange t) throws IOException {
File requestFile = this.saveRequestFile(t);
String hash = FileSystem.hashOf(requestFile);
String response = MainServer.this.fetchResponseByHash(hash);
if (response == null) {
response = MainServer.this.buildResponseFromScan(requestFile);
MainServer.this.saveResponseByHash(hash, response);
}
this.respond(t, 200, response);
}
private File saveRequestFile(HttpExchange exchange) throws IOException {
String method = exchange.getRequestMethod();
if (!method.equals("POST"))
throw new RuntimeException("Invalid method: POST required!");
String boundary = this.getBoundary(exchange);
if (boundary == null)
throw new RuntimeException("No boundary specification!");
int contentLength = Integer.valueOf(exchange.getRequestHeaders().getFirst("Content-Length"));
String startBoundary = BOUNDARY_PREFIX + boundary;
String endBoundary = "\r\n" + BOUNDARY_PREFIX + boundary + BOUNDARY_SUFFIX;
MixedInputStream requestStream = new MixedInputStream(exchange.getRequestBody());
String line;
// Reads until a start boundary is found
while (!requestStream.readLine().equals(startBoundary))
;
// Then keeps reading until a Content-Type header is found. Usually there are two headers at the start
// of a boundary (Content-Disposition and Content-Type). We assume that only one file is included within
// the request and thus it is useless to parse Content-Disposition
while (!(line = requestStream.readLine()).startsWith(CONTENT_TYPE_HEADER))
;
// Gets the mime type of this part
String mimeType = line.split(":")[1].trim();
// If it is not an octect stream, fails
if (!mimeType.equals(OCTET_STREAM_MIME_TYPE))
throw new RuntimeException("Invalid MIME type: expected application/octet-stream!");
// Creates a temporary file with prefix upload-, random name, apk suffix, in the given directory
File resultFile = File.createTempFile("upload-", ".apk", MainServer.this.uploadDirectory);
OutputStream outputStream = new FileOutputStream(resultFile);
byte[] buffer = new byte[4096];
// Index of one of the last blocks of data (not important that is exactly the last)
int endingBlockIndex = Math.max(0, (contentLength / buffer.length) - 1);
int readBlocks = 0;
int brc = 0;
// There are some empty lines after Content-Type
requestStream.skipEmptyLines();
// If more parts are included, only the first is considered (until a startBoundary). If this is the only
// part, anyway the endBoundary has startBoundary as prefix
while ((brc = requestStream.read(buffer)) > 0) {
readBlocks++;
// Looks for the endBoundary string, but only if we are approaching the end of the octet stream
// While normally it wouldn't be needed, ApkDecoder complains about unaligned zip files
if (readBlocks >= endingBlockIndex) {
int boundaryIndex = this.findBinaryString(buffer, endBoundary);
if (boundaryIndex >= 0) {
byte[] tempBuffer = new byte[boundaryIndex];
System.arraycopy(buffer, 0, tempBuffer, 0, boundaryIndex);
buffer = tempBuffer;
brc = buffer.length;
}
}
outputStream.write(buffer, 0, brc);
}
requestStream.close();
outputStream.close();
return resultFile;
}
private int findBinaryString(byte[] buffer, String target) {
byte[] targetBytes = target.getBytes();
if (buffer.length < targetBytes.length)
return -1;
for (int i = 0; i < buffer.length - targetBytes.length; i++) {
boolean found = true;
for (int j = 0; j < targetBytes.length; j++)
if (buffer[j + i] != targetBytes[j]) {
found = false;
break;
}
if (found)
return i;
}
return -1;
}
private String getBoundary(HttpExchange exchange) {
Headers headers = exchange.getRequestHeaders();
String contentType = headers.getFirst(CONTENT_TYPE_HEADER);
String[] parts = contentType.split(";");
String mimeType = parts[0].trim().toLowerCase();
if (!mimeType.equals(MULTIPLART_MIME_TYPE))
return null;
for (int i = 1; i < parts.length; i++) {
String part = parts[i].trim();
if (part.startsWith(BOUNDARY_FIELD)) {
String[] boundarySpecs = part.split("=");
return boundarySpecs[1].trim();
}
}
return null;
}
}
private class HashHandler extends BaseHandler implements HttpHandler {
private static final String SAMPLES_API_KEY = "11d75ea7912546ea97d9fea1d0317b38";
@Override
public void handle(HttpExchange exchange) throws IOException {
Map<?, ?> params = (Map<?, ?>)exchange.getAttribute("parameters");
String hash = (String) params.get("hash");
String response = MainServer.this.fetchResponseByHash(hash);
if (response == null) {
File sample = this.fetchSample(hash);
if (!sample.exists()) {
this.respond(exchange, 404, "Not found");
return;
}
response = MainServer.this.buildResponseFromScan(sample);
MainServer.this.saveResponseByHash(hash, response);
}
this.respond(exchange, 200, response);
}
private File fetchSample(String hash) throws IOException {
String command = String.format("python %s/samples_cli.py -log-level DEBUG get -at-key %s %s", MainServer.this.uploadDirectory.getAbsolutePath(), SAMPLES_API_KEY, hash);
Process downloader = Runtime.getRuntime().exec(command);
System.out.println("Executed: " + command);
try {
downloader.waitFor();
} catch (InterruptedException e) { }
File resultFile = new File(MainServer.this.uploadDirectory, hash + ".apk");
File misplacedFile = new File(hash + ".apk");
if (misplacedFile.exists())
misplacedFile.renameTo(resultFile);
return resultFile;
}
}
public class ParameterFilter extends Filter {
@Override
public String description() {
return "Parses the requested URI for parameters";
}
@Override
public void doFilter(HttpExchange exchange, Chain chain) throws IOException {
parseGetParameters(exchange);
chain.doFilter(exchange);
}
private void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException {
Map<String, String> parameters = new HashMap<String, String>();
URI requestedUri = exchange.getRequestURI();
String query = requestedUri.getRawQuery();
parseQuery(query, parameters);
exchange.setAttribute("parameters", parameters);
}
@SuppressWarnings("unchecked")
private void parseQuery(String query, Map<String, String> parameters) throws UnsupportedEncodingException {
if (query == null)
return;
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0)
key = URLDecoder.decode(param[0], System.getProperty("file.encoding"));
if (param.length > 1)
value = URLDecoder.decode(param[1], System.getProperty("file.encoding"));
parameters.put(key, value);
}
}
}
}
| 15,541
| 37.093137
| 180
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/MainBatch.java
|
/**
*
*/
package it.polimi.elet.necst.heldroid.goodware;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import it.polimi.elet.necst.heldroid.goodware.features.AdwareFilter;
import it.polimi.elet.necst.heldroid.goodware.features.DangerousApiFilter;
import it.polimi.elet.necst.heldroid.goodware.features.DangerousPermissionsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.FileMetricsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.HarmlessPermissionsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.HiddenApkFilter;
import it.polimi.elet.necst.heldroid.goodware.features.PackageFilter;
import it.polimi.elet.necst.heldroid.goodware.features.PotentialLeakageFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SmsNumbersFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousFlowFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousIntentFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SuspiciousUrlsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.SystemCallsFilter;
import it.polimi.elet.necst.heldroid.goodware.features.ValidDomainFilter;
import it.polimi.elet.necst.heldroid.goodware.features.core.Feature;
import it.polimi.elet.necst.heldroid.goodware.features.core.MetaFeatureGatherer;
import it.polimi.elet.necst.heldroid.goodware.weka.ApkClassifier;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
public class MainBatch {
private static ApkClassifier apkClassifier;
public static void main(String[] args) throws IOException {
if (args.length < 2) {
printUsage();
return;
}
final File target = new File(args[0]);
File destination = new File(args[1]);
File model = new File("hel-models/j48-sensitive-h.model");
File attributes = new File("hel-models/attributes.arff");
apkClassifier = new ApkClassifier(model, attributes);
new Thread(new Worker(apkClassifier, target, destination)).start();
}
public static void printUsage() {
System.out.println("GoodwareFilter.jar source destination");
System.out.println("source:");
System.out.println(" an apk file, a directory containing an unpacked apk file, ");
System.out.println(" a .apklist text file containing a line-by-line list of absolute apk paths");
System.out.println(" or a directory (which will be recursively searched for any of the above)");
System.out.println("destination:");
System.out.println(" a folder that will contain the output");
}
static class Worker implements Runnable {
private ApkClassifier sharedClassifier;
private File uploadDirectory;
private File hashDirectory;
private File target;
private String[] classLabels;
public Worker(ApkClassifier sharedClassifier, File target, File uploadDirectory) {
this.sharedClassifier = sharedClassifier;
this.uploadDirectory = uploadDirectory;
this.target = target;
if (!uploadDirectory.exists())
if (!uploadDirectory.mkdir())
throw new RuntimeException("Cannot create upload directory!");
this.hashDirectory = new File(uploadDirectory, "hash");
if (!hashDirectory.exists())
if (!hashDirectory.mkdir())
throw new RuntimeException("Cannot create hash directory!");
this.classLabels = sharedClassifier.getClassLabels();
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName().toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
}
private void readFileList(File fileList) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileList));
String line = null;
while((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private void checkFile(File file) {
String result = buildResponseFromScan(file);
System.out.println(result);
}
private String buildResponseFromScan(File file) {
MetaFeatureGatherer gatherer = this.createGatherer();
ApplicationData applicationData;
try {
applicationData = ApplicationData.open(file);
} catch (Exception e) {
return "Error unpacking: " + e.getMessage();
}
gatherer.matchAllFilters(applicationData);
applicationData.dispose();
Collection<Feature> features = gatherer.getAllFiltersFeatures();
String prediction;
double[] classDistribution;
synchronized (this.sharedClassifier) {
prediction = this.sharedClassifier.classify(features);
classDistribution = this.sharedClassifier.computeDistribution(features);
}
return this.buildResponseFromResults(features, classDistribution, prediction);
}
private String buildResponseFromResults(Collection<Feature> features, double[] classDistribution, String prediction) {
StringBuilder builder = new StringBuilder();
boolean firstLine;
builder.append("{\n");
builder.append(" \"features\": [\n ");
firstLine = true;
for (Feature f : features) {
if (!firstLine) builder.append(",\n ");
builder.append(String.format("{ \"name\": \"%s\", value: \"%s\" }", f.getName(), f.getValue()));
firstLine = false;
}
builder.append("\n ],\n ");
firstLine = true;
for (int i = 0; i < classDistribution.length; i++) {
if (!firstLine) builder.append(",\n ");
builder.append(String.format("\"%s\": %s", this.classLabels[i], String.valueOf(classDistribution[i])));
firstLine = false;
}
builder.append(",\n \"prediction\": \"" + prediction + "\"");
builder.append("\n}");
return builder.toString();
}
private MetaFeatureGatherer createGatherer() {
MetaFeatureGatherer metaFeatureGatherer = new MetaFeatureGatherer();
metaFeatureGatherer.add(new DangerousPermissionsFilter());
metaFeatureGatherer.add(new DangerousApiFilter());
metaFeatureGatherer.add(new PotentialLeakageFilter());
metaFeatureGatherer.add(new AdwareFilter());
metaFeatureGatherer.add(new SuspiciousUrlsFilter());
metaFeatureGatherer.add(new PackageFilter());
metaFeatureGatherer.add(new FileMetricsFilter());
metaFeatureGatherer.add(new SystemCallsFilter());
metaFeatureGatherer.add(new HarmlessPermissionsFilter());
metaFeatureGatherer.add(new SuspiciousIntentFilter());
metaFeatureGatherer.add(new HiddenApkFilter());
metaFeatureGatherer.add(new SmsNumbersFilter());
metaFeatureGatherer.add(new ValidDomainFilter());
metaFeatureGatherer.add(new SuspiciousFlowFilter());
metaFeatureGatherer.disableAllFeatures();
metaFeatureGatherer.enableFeatures(this.sharedClassifier.getAttributesNames());
return metaFeatureGatherer;
}
}
}
| 7,910
| 34.79638
| 120
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/markets/GooglePlayStore.java
|
package it.polimi.elet.necst.heldroid.goodware.markets;
import com.gc.android.market.api.MarketSession;
import com.gc.android.market.api.model.Market;
import com.gc.android.market.api.model.Market.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class GooglePlayStore {
// TODO make this a property :-) but at the end of the day we don't care about leaking a dummy account
private static final String GOOGLE_USERNAME = "goodware.bot@gmail.com";
private static final String GOOGLE_PASSWORD = "mucca-fritta-007";
private static final String FAILURE_FILE_NAME = "google-play-failed-queries.txt";
private static BufferedWriter failureWriter;
private MarketSession session;
private boolean extendedInfo;
private int defaultEntriesCount;
static {
try {
failureWriter = new BufferedWriter(new FileWriter(new File(FAILURE_FILE_NAME), true));
} catch (IOException e) {
e.printStackTrace();
}
}
public GooglePlayStore() {
this.extendedInfo = true;
this.defaultEntriesCount = 10;
}
private void login() {
if (session != null)
return;
session = new MarketSession();
session.login(GOOGLE_USERNAME, GOOGLE_PASSWORD);
}
public Collection<App> search(String query, int startIndex, int entriesCount) {
this.login();
List<App> results = new ArrayList<App>();
for (int i = startIndex; i < entriesCount; i += 10) {
Market.AppsRequest appsRequest = Market.AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(i).setEntriesCount(10)
.setWithExtendedInfo(extendedInfo)
.build();
List<App> tmp = getAppsFromRequest(appsRequest);
results.addAll(tmp);
if (tmp.size() < 10)
break;
}
return results;
}
public Collection<App> searchByCategory(String category, int startIndex, int entriesCount) {
this.login();
List<App> results = new ArrayList<App>();
for (int i = startIndex; i < entriesCount; i += 10) {
Market.AppsRequest appsRequest = Market.AppsRequest.newBuilder()
.setStartIndex(i).setEntriesCount(10)
.setCategoryId(category)
.setOrderType(AppsRequest.OrderType.POPULAR)
.setWithExtendedInfo(extendedInfo)
.build();
List<App> tmp = getAppsFromRequest(appsRequest);
results.addAll(tmp);
if (tmp.size() < 10)
break;
}
return results;
}
private List<App> getAppsFromRequest(AppsRequest appsRequest) {
List<App> results = new ArrayList<App>();
try {
List<Object> responses = session.queryApp(appsRequest);
for(int i = 0; i < responses.size(); i++) {
AppsResponse response = (AppsResponse) responses.get(i);
if (response.getAppCount() == 0)
continue;
results.addAll(response.getAppList());
}
} catch (RuntimeException rex) {
// Too many requests
synchronized (failureWriter) {
if (failureWriter != null) {
try {
failureWriter.write(appsRequest.getQuery());
failureWriter.newLine();
failureWriter.flush();
} catch (IOException e) { }
}
}
}
return results;
}
public Collection<App> search(String query) {
return search(query, 0, defaultEntriesCount);
}
public Collection<App> searchByCategory(String category) {
return searchByCategory(category, 0, defaultEntriesCount);
}
public App findApplication(String appName) {
Collection<App> foundApps = search(appName, 0, 5);
if (foundApps.size() == 0)
return null;
Iterator<App> iterator = foundApps.iterator();
return iterator.next();
}
public App findPackage(String packageName) {
return findApplication("pname:" + packageName);
}
public static final String[] APP_CATEGORIES = {
"COMICS",
"FINANCE",
"LIFESTYLE",
"PRODUCTIVITY",
"SHOPPING",
"SPORTS",
"TOOLS",
"TRAVEL_AND_LOCAL",
"BUSINESS",
"EDUCATION",
"NEWS_AND_MAGAZINES",
"MEDIA_AND_VIDEO",
"MUSIC_AND_AUDIO",
"HEALTH_AND_FITNESS",
"MEDICAL",
"PERSONALIZATION",
"BOOKS_AND_REFERENCE",
"PHOTOGRAPHY",
"WEATHER",
"COMMUNICATION",
"SOCIAL"
};
public boolean hasExtendedInfo() {
return extendedInfo;
}
public void setExtendedInfo(boolean extendedInfo) {
this.extendedInfo = extendedInfo;
}
public int getDefaultEntriesCount() {
return defaultEntriesCount;
}
public void setDefaultEntriesCount(int defaultEntriesCount) {
this.defaultEntriesCount = defaultEntriesCount;
}
}
| 5,474
| 28.435484
| 106
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/PlayStorePermissionsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import com.gc.android.market.api.model.Market.App;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.goodware.markets.GooglePlayStore;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.Collection;
import java.util.List;
public class PlayStorePermissionsFilter extends FeatureGatherer {
private static final String FEATURE_NAME = "Overprivileged Permissions";
private GooglePlayStore store;
public PlayStorePermissionsFilter() {
store = new GooglePlayStore();
}
@Override
public OperationMode getOperationMode() {
return OperationMode.NETWORK_QUERY;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
String packageName = applicationData.getManifestReport().getPackageName();
Collection<String> permissions = applicationData.getManifestReport().getPermissions();
store.setExtendedInfo(true);
App app = store.findPackage(packageName);
if (app == null) {
super.setFeatureValue(0, 0);
return false;
}
List<String> appPermissions = app.getExtendedInfo().getPermissionIdList();
int overprivileges = 0;
for (String permission : permissions)
if (!appPermissions.contains(permission))
overprivileges++;
super.setFeatureValue(0, overprivileges);
return (overprivileges > 0);
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_NAME);
}
}
| 1,693
| 28.719298
| 94
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/FileMetricsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.pipeline.FileTree;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.names.SmaliClassName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import java.io.File;
public class FileMetricsFilter extends FeatureGatherer {
private ApplicationData currentData;
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
this.currentData = applicationData;
this.detectLanguageEncoding();
this.checkFileMetrics();
this.checkApplicationMetrics();
return false;
}
private void detectLanguageEncoding() {
if (!super.isFeatureEnabled(FEATURE_LANGUAGE))
return;
String apkName = currentData.getDecodedPackage().getOriginalApk().getName();
Character.UnicodeBlock detectedApkNameBlock = detectUnicodeBlock(apkName);
if (!detectedApkNameBlock.equals(Character.UnicodeBlock.BASIC_LATIN)) {
super.setFeatureValue(0, detectedApkNameBlock.toString());
}
SmaliLoader loader = currentData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
final Wrapper<String> language = new Wrapper<String>("BASIC_LATIN");
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
Character.UnicodeBlock block = detectUnicodeBlock(value);
if (!block.equals(Character.UnicodeBlock.BASIC_LATIN)) {
language.value = block.toString();
return true;
}
return false;
}
});
constantFinder.searchAllLiterals();
super.setFeatureValue(0, language.value);
}
private Character.UnicodeBlock detectUnicodeBlock(String string) {
for (int i = 0; i < string.length(); i++) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(string.charAt(i));
for (Character.UnicodeBlock interestingBlock : INTERESTING_UNICODE_BLOCKS) {
if (block.equals(interestingBlock))
return block;
}
}
return Character.UnicodeBlock.BASIC_LATIN;
}
private void checkFileMetrics() {
File apk = currentData.getDecodedPackage().getOriginalApk();
super.setFeatureValue(1, apk.length());
if (!super.isAnyFeatureEnabled(FEATURE_FILES_COUNT, FEATURE_IMAGES_COUNT))
return;
FileTree tree = currentData.getDecodedFileTree();
int totalFiles = 0;
int totalImages = 0;
for (File file : tree.getAllFiles()) {
String name = file.getName();
for (String imageExtension : IMAGE_EXTENSIONS)
if (name.endsWith(imageExtension)) {
totalImages++;
break;
}
totalFiles++;
}
super.setFeatureValue(2, totalImages);
super.setFeatureValue(3, totalFiles);
}
private void checkApplicationMetrics() {
super.setFeatureValue(4, currentData.getManifestReport().getPermissions().size());
if (!super.isAnyFeatureEnabled(FEATURE_RECEIVERS_COUNT, FEATURE_SERVICES_COUNT, FEATURE_ACTIVITIES_COUNT))
return;
SmaliLoader loader = currentData.getSmaliLoader();
int totalActivities = 0;
int totalServices = 0;
int totalReceivers = 0;
for (SmaliClass klass : loader.getClasses()) {
if (klass.isSubclassOf(ACTIVITY))
totalActivities++;
else if (klass.isSubclassOf(SERVICE))
totalServices++;
else if (klass.isSubclassOf(BROADCAST_RECEIVER))
totalReceivers++;
}
super.setFeatureValue(5, totalActivities);
super.setFeatureValue(6, totalServices);
super.setFeatureValue(7, totalReceivers);
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_LANGUAGE);
super.addFeature(FEATURE_TOTAL_SIZE);
super.addFeature(FEATURE_IMAGES_COUNT);
super.addFeature(FEATURE_FILES_COUNT);
super.addFeature(FEATURE_PERMISSIONS_COUNT);
super.addFeature(FEATURE_ACTIVITIES_COUNT);
super.addFeature(FEATURE_SERVICES_COUNT);
super.addFeature(FEATURE_RECEIVERS_COUNT);
}
private static final String FEATURE_LANGUAGE = "Language:";
private static final String FEATURE_TOTAL_SIZE = "Size of apk";
private static final String FEATURE_IMAGES_COUNT = "Number of images";
private static final String FEATURE_FILES_COUNT = "Number of files";
private static final String FEATURE_PERMISSIONS_COUNT = "Number of permissions";
private static final String FEATURE_ACTIVITIES_COUNT = "Number of activities";
private static final String FEATURE_SERVICES_COUNT = "Number of services";
private static final String FEATURE_RECEIVERS_COUNT = "Number of receivers";
private static final String[] IMAGE_EXTENSIONS = { ".jpg", ".jpeg", ".bmp", ".png", ".gif", ".tga", ".dds", ".blp" };
private static final SmaliClassName BROADCAST_RECEIVER = new SmaliClassName("Landroid/content/BroadcastReceiver;");
private static final SmaliClassName ACTIVITY = new SmaliClassName("Landroid/app/Activity;");
private static final SmaliClassName SERVICE = new SmaliClassName("Landroid/app/Service;");
private static final Character.UnicodeBlock[] INTERESTING_UNICODE_BLOCKS = {
Character.UnicodeBlock.ARABIC,
Character.UnicodeBlock.ARMENIAN,
Character.UnicodeBlock.BENGALI,
Character.UnicodeBlock.CHEROKEE,
Character.UnicodeBlock.CYRILLIC,
Character.UnicodeBlock.DEVANAGARI,
Character.UnicodeBlock.ETHIOPIC,
Character.UnicodeBlock.GEORGIAN,
Character.UnicodeBlock.GOTHIC,
Character.UnicodeBlock.GREEK,
Character.UnicodeBlock.GUJARATI,
Character.UnicodeBlock.GURMUKHI,
Character.UnicodeBlock.HANUNOO,
Character.UnicodeBlock.HEBREW,
Character.UnicodeBlock.HIRAGANA,
Character.UnicodeBlock.KANBUN,
Character.UnicodeBlock.KANNADA,
Character.UnicodeBlock.KATAKANA,
Character.UnicodeBlock.KHMER,
Character.UnicodeBlock.LAO,
Character.UnicodeBlock.LIMBU,
Character.UnicodeBlock.MALAYALAM,
Character.UnicodeBlock.MONGOLIAN,
Character.UnicodeBlock.MONGOLIAN,
Character.UnicodeBlock.OGHAM,
Character.UnicodeBlock.ORIYA,
Character.UnicodeBlock.OSMANYA,
Character.UnicodeBlock.SHAVIAN,
Character.UnicodeBlock.SINHALA,
Character.UnicodeBlock.SYRIAC,
Character.UnicodeBlock.TAGBANWA,
Character.UnicodeBlock.TAI_LE,
Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS,
Character.UnicodeBlock.TAMIL,
Character.UnicodeBlock.THAANA,
Character.UnicodeBlock.THAI,
Character.UnicodeBlock.TIBETAN,
Character.UnicodeBlock.UGARITIC
};
}
| 7,775
| 37.117647
| 121
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/AdwareFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliInspector;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import java.io.File;
import java.util.Collection;
import java.util.List;
public class AdwareFilter extends FeatureGatherer {
private static final String AIRPUSH_CLASS_NAME = "Airpush";
private ApplicationData applicationData;
@Override
public OperationMode getOperationMode() {
return OperationMode.FILE_ENUMERATION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
this.resetFeaturesValues();
this.applicationData = applicationData;
boolean result = this.airpushExists();
this.checkC2M();
this.checkNotificationApis();
this.checkAdClasses();
return result;
}
private boolean airpushExists() {
if (!super.isFeatureEnabled(FEATURE_AIRPUSH))
return false;
File smaliDirectory = applicationData.getDecodedPackage().getSmaliDirectory();
Collection<File> smaliFiles = applicationData.getDecodedFileTree().getAllFilesIn(smaliDirectory);
boolean result = false;
for (File file : smaliFiles)
if (file.getName().startsWith(AIRPUSH_CLASS_NAME)) {
result = true;
break;
}
if (result == false) {
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
final Wrapper<Boolean> airpushUrlFound = new Wrapper<Boolean>(false);
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
if (!value.startsWith("\"")) // not starting with " -> not a string literal
return false;
if (value.contains(AIRPUSH_URL)) {
airpushUrlFound.value = true;
return true;
}
return false;
}
});
result = airpushUrlFound.value;
}
super.setFeatureValue(0, result);
return result;
}
private void checkC2M() {
Collection<String> permissions = applicationData.getManifestReport().getPermissions();
Collection<String> intents = applicationData.getManifestReport().getIntentFilters();
int featureIndex = 1;
for (int i = 0; i < C2M_PERMISSIONS.length; i++) {
String c2mPermission = C2M_PERMISSIONS[i];
if (!super.isFeatureEnabled(FEATURE_C2M_PERMISSION_PREFIX + c2mPermission))
continue;
boolean present = false;
for (String permission : permissions)
if (permission.endsWith(c2mPermission)) {
present = true;
break;
}
super.setFeatureValue(featureIndex++, present);
}
for (int i = 0; i < C2M_INTENTS.length; i++) {
String c2mIntent = C2M_INTENTS[i];
if (!super.isFeatureEnabled(FEATURE_C2M_INTENT_PREFIX + c2mIntent))
continue;
boolean present = false;
for (String intent : intents)
if (intent.endsWith(c2mIntent)) {
present = true;
break;
}
super.setFeatureValue(featureIndex++, present);
}
}
private void checkNotificationApis() {
if (!super.isAnyFeatureEnabled(FEATURE_NOTIFICATION_PREFIX))
return;
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliInspector inspector = loader.generateInspector();
boolean[] invocationFound = inspector.invocationsExist(NOTIFICATION_METHODS);
int featureIndex = 1 + C2M_PERMISSIONS.length + C2M_INTENTS.length;
for (int j = 0; j < NOTIFICATION_METHODS.size(); j++)
super.setFeatureValue(featureIndex + j, invocationFound[j]);
}
private void checkAdClasses() {
if (!super.isFeatureEnabled(FEATURE_AD_CLASS))
return;
SmaliLoader loader = applicationData.getSmaliLoader();
int featureIndex = 1 + C2M_PERMISSIONS.length + C2M_INTENTS.length + NOTIFICATION_METHODS.size();
int adClasses = 0;
for (SmaliClass klass : loader.getClasses()) {
String name = klass.getName().getSimpleName();
// Follows Java naming conventions (eg. AdView, AdMob, etc..)
if (name.length() > 2 && name.startsWith("Ad") && Character.isUpperCase(name.charAt(2)))
adClasses++;
}
super.setFeatureValue(featureIndex, adClasses);
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_AIRPUSH);
for (int i = 0; i < C2M_PERMISSIONS.length; i++)
super.addFeature(FEATURE_C2M_PERMISSION_PREFIX + C2M_PERMISSIONS[i]);
for (int i = 0; i < C2M_INTENTS.length; i++)
super.addFeature(FEATURE_C2M_INTENT_PREFIX + C2M_INTENTS[i]);
for (int i = 0; i < NOTIFICATION_METHODS.size(); i++)
super.addFeature(FEATURE_NOTIFICATION_PREFIX + NOTIFICATION_METHODS.get(i).getCompleteName());
super.addFeature(FEATURE_AD_CLASS);
}
private static final String FEATURE_AIRPUSH = "Airpush Included";
private static final String FEATURE_C2M_PERMISSION_PREFIX = "C2M Permission: ";
private static final String FEATURE_C2M_INTENT_PREFIX = "C2M Intent: ";
private static final String FEATURE_NOTIFICATION_PREFIX = "Notification Api Call: ";
private static final String FEATURE_AD_CLASS = "Classes with Ad prefix";
private static final String AIRPUSH_URL = "airpush.com";
private static final String[] C2M_PERMISSIONS = {
"c2dm.permission.RECEIVE",
"C2D_MESSAGE",
"c2dm.permission.SEND"
};
private static final String[] C2M_INTENTS = {
"c2dm.intent.RECEIVE",
"c2dm.intent.REGISTRATION",
"c2dm.intent.REGISTER"
};
private static final List<SmaliMemberName> NOTIFICATION_METHODS = SmaliMemberName.newList(
"Landroid/support/v4/app/NotificationCompat.Builder;->build",
"Landroid/app/Notification;-><init>",
"Landroid/app/NotificationManager;->notify",
"Landroid/app/Notification$Builder;-><init>",
"Landroid/app/Notification$Builder;->setLargeIcon",
"Landroid/app/Notification$Builder;->setSound"
);
}
| 7,080
| 34.944162
| 106
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/PackageFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class PackageFilter extends FeatureGatherer {
private ApplicationData currentData;
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
this.currentData = applicationData;
boolean result = this.checkMainPackageName();
this.checkMetrics();
return result;
}
private boolean checkMainPackageName() {
if (!super.isAnyFeatureEnabled(FEATURE_SHORT_NAME, FEATURE_DOMAIN, FEATURE_TETRAGRAM))
return false;
if (validDomains == null)
loadValidDomains();
String packageName = currentData.getManifestReport().getPackageName();
String[] packageParts = packageName.split("\\.");
boolean shortName = (packageParts.length <= 1);
boolean validDomain = (validDomains.contains(packageParts[0].toUpperCase()));
boolean tetragrams = false;
for (String part : packageParts)
if (containsConsonantNGram(part, 4)) {
tetragrams = true;
break;
}
super.setFeatureValue(0, shortName);
super.setFeatureValue(1, validDomain);
super.setFeatureValue(2, tetragrams);
return shortName || !validDomain || tetragrams;
}
private void checkMetrics() {
if (!super.isAnyFeatureEnabled(FEATURE_AVG_CLASS_SIZE, FEATURE_CLASS_COUNT, FEATURE_CLASS_COUNT_IN_MAIN_PACKAGE,
FEATURE_MAIN_PACKAGE_OBFUSCATED, FEATURE_OBFUSCATION, FEATURE_PACKAGE_COUNT))
return;
String mainPackageName = currentData.getManifestReport().getPackageName().replace(".", "/"); // in
// smali
// format
SmaliLoader loader = currentData.getSmaliLoader();
Set<String> packages = new HashSet<String>();
boolean obfuscated = false;
boolean mainPackageObfuscated = false;
double totalClassSize = 0;
int classCountInMainPackage = 0;
int classCount = 0;
for (SmaliClass klass : loader.getClasses()) {
String packageName = klass.getName().getPackageName();
String className = klass.getName().getSimpleName();
boolean inMainPackage = packageName.startsWith(mainPackageName);
packages.add(packageName);
classCount++;
totalClassSize += klass.getSize();
if (inMainPackage)
classCountInMainPackage++;
if (className.length() == 1 && Character.isLowerCase(className.charAt(0))) {
obfuscated = true;
if (inMainPackage)
mainPackageObfuscated = true;
}
}
super.setFeatureValue(3, packages.size());
super.setFeatureValue(4, classCount);
super.setFeatureValue(5, classCountInMainPackage);
super.setFeatureValue(6, totalClassSize / classCount);
super.setFeatureValue(7, obfuscated);
super.setFeatureValue(8, mainPackageObfuscated);
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_SHORT_NAME);
super.addFeature(FEATURE_DOMAIN);
super.addFeature(FEATURE_TETRAGRAM);
super.addFeature(FEATURE_PACKAGE_COUNT);
super.addFeature(FEATURE_CLASS_COUNT);
super.addFeature(FEATURE_CLASS_COUNT_IN_MAIN_PACKAGE);
super.addFeature(FEATURE_AVG_CLASS_SIZE);
super.addFeature(FEATURE_OBFUSCATION);
super.addFeature(FEATURE_MAIN_PACKAGE_OBFUSCATED);
}
private static boolean containsConsonantNGram(String text, int n) {
int counter = 0;
for (Character c : text.toCharArray()) {
if (Character.isLetter(c) && !VOWELS.contains(Character.toLowerCase(c)))
counter++;
else
counter = 0;
if (counter >= n)
return true;
}
return false;
}
private static synchronized void loadValidDomains() {
InputStream stream = PackageFilter.class.getResourceAsStream(VALID_DOMAIN_LIST_NAME);
Reader reader = new InputStreamReader(stream);
BufferedReader textReader = new BufferedReader(reader);
String line;
validDomains = new ArrayList<String>();
try {
while ((line = textReader.readLine()) != null)
validDomains.add(line);
textReader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static final String FEATURE_SHORT_NAME = "Single Package Name";
private static final String FEATURE_DOMAIN = "Valid Domain in Package Name";
private static final String FEATURE_TETRAGRAM = "Package Name contains Tetragrams";
private static final String FEATURE_PACKAGE_COUNT = "Total number of packages";
private static final String FEATURE_CLASS_COUNT = "Total number of classes";
private static final String FEATURE_CLASS_COUNT_IN_MAIN_PACKAGE = "Number of classes in main package";
private static final String FEATURE_AVG_CLASS_SIZE = "Average class size";
private static final String FEATURE_OBFUSCATION = "Obsfuscation present";
private static final String FEATURE_MAIN_PACKAGE_OBFUSCATED = "Is main package obfuscated?";
private static final String VALID_DOMAIN_LIST_NAME = "domain-list.txt";
private static final List<Character> VOWELS = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
private static List<String> validDomains;
}
| 5,661
| 32.305882
| 116
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/DangerousApiFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliInspector;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import java.util.Collection;
import java.util.List;
public class DangerousApiFilter extends FeatureGatherer {
private SmaliLoader loader;
private SmaliInspector inspector;
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
this.resetFeaturesValues();
this.loader = applicationData.getSmaliLoader();
this.inspector = loader.generateInspector();
boolean result = this.checkDangerousApiExistence();
this.checkDangerousApiCalls();
return result;
}
private boolean checkDangerousApiExistence() {
if (!super.isAnyFeatureEnabled(FEATURE_PREFIX))
return false;
boolean[] methodsFound = inspector.invocationsExist(DANGEROUS_METHODS);
boolean result = false;
for (int i = 0; i < DANGEROUS_METHODS.size(); i++) {
SmaliMemberName methodName = DANGEROUS_METHODS.get(i);
boolean found = methodsFound[i];
super.setFeatureValue(i, found);
if (found)
result = true;
}
return result;
}
private void checkDangerousApiCalls() {
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
int i = DANGEROUS_METHODS.size();
if (super.isFeatureEnabled(FEATURE_TESTS_ADB)) {
boolean getAdbEnabled = constantFinder.testInvocationParameter(SECURE_GET_INT, 1, ADB_ENABLED);
super.setFeatureValue(i++, getAdbEnabled);
}
if (super.isFeatureEnabled(FEATURE_EDIT_ADB)) {
boolean setAdbEnabled = constantFinder.testInvocationParameter(SECURE_PUT_INT, 1, ADB_ENABLED);
super.setFeatureValue(i++, setAdbEnabled);
}
}
@Override
protected void defineFeatures() {
for (int i = 0; i < DANGEROUS_METHODS.size(); i++)
super.addFeature(FEATURE_PREFIX + DANGEROUS_METHODS.get(i).getCompleteName());
super.addFeature(FEATURE_TESTS_ADB);
super.addFeature(FEATURE_EDIT_ADB);
}
// Taken from http://www.cis.syr.edu/~wedu/Research/paper/Malware_Analysis_2013.pdf
private static final List<SmaliMemberName> DANGEROUS_METHODS = SmaliMemberName.newList(
"Landroid/content/Context;->startService",
"Landroid/telephony/TelephonyManager;->getSubscriberId",
"Landroid/telephony/TelephonyManager;->getDeviceId",
"Landroid/telephony/TelephonyManager;->getLine1Number",
"Landroid/telephony/TelephonyManager;->getSimSerialNumber",
"Landroid/telephony/TelephonyManager;->getSimOperatorName",
"Landroid/telephony/TelephonyManager;->getCellLocation",
"Landroid/telephony/cdma/CdmaCellLocation;->getSystemId",
"Landroid/telephony/SmsManager;->sendTextMessage",
"Landroid/content/Intent;->setDataAndType",
"Landroid/content/Intent;->setType",
"Landroid/app/ActivityManager;->getRunningServices",
"Landroid/app/ActivityManager;->getMemoryInfo",
"Landroid/app/ActivityManager;->restartPackage",
"Landroid/content/pm/PackageManager;->getInstalledPackages",
"Ljava/lang/System;->loadLibrary",
"Ljavax/crypto/Cipher;->getInstance",
"Landroid/provider/Browser;->getAllBookmarks",
"Landroid/content/pm/PackageManager;->queryContentProviders",
"Landroid/content/Intent;->describeContents",
"Landroid/content/pm/PackageManager;->getPreferredActivities",
"Landroid/app/Service;->onLowMemory",
"Landroid/os/Parcel;->marshall",
"Ldalvik/system/DexClassLoader;-><init>",
"Ljava/lang/ClassLoader;->loadClass",
"Landroid/accounts/AccountManager;->getAccounts",
"Landroid/content/BroadcastReceiver;->abortBroadcast"
);
private static final String FEATURE_PREFIX = "Api Call: ";
private static final String FEATURE_TESTS_ADB = "Checks adb_enabled";
private static final String FEATURE_EDIT_ADB = "Tries to modify adb_enabled";
private static Collection<SmaliMemberName> READ_PHONE_DATA_METHODS = SmaliMemberName.newList(
"Landroid/telephony/TelephonyManager;->getSubscriberId",
"Landroid/telephony/TelephonyManager;->getDeviceId",
"Landroid/telephony/TelephonyManager;->getLine1Number",
"Landroid/telephony/TelephonyManager;->getSimSerialNumber",
"Landroid/telephony/TelephonyManager;->getCellLocation",
"Landroid/telephony/TelephonyManager;->getSimOperatorName",
"Landroid/accounts/AccountManager->getAccounts",
"Landroid/provider/Browser;->getAllBookmarks"
);
private static final SmaliMemberName SEND_TEXT_MESSAGE = new SmaliMemberName("Landroid/telephony/SmsManager;->sendTextMessage");
private static final SmaliMemberName START_SERVICE = new SmaliMemberName("Landroid/content/Context;->startService");
private static final SmaliMemberName SECURE_GET_INT = new SmaliMemberName("Landroid/provider/Settings$Secure->getInt;");
private static final SmaliMemberName SECURE_PUT_INT = new SmaliMemberName("Landroid/provider/Settings$Secure->putInt;");
private static final String ADB_ENABLED = "adb_enabled";
}
| 5,867
| 43.120301
| 132
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/PotentialLeakageFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.utils.Literal;
import java.util.Collection;
public class PotentialLeakageFilter extends FeatureGatherer {
private static final String FEATURE_PREFIX_DATA = "Can Steal Data: ";
private static final String FEATURE_PREFIX_COM = "Communication: ";
private static final String FEATURE_PREFIX_CONTENT = "Content: ";
private ApplicationData currentData;
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
this.currentData = applicationData;
boolean result = this.checkPermissions();
this.checkContents();
return result;
}
private boolean checkPermissions() {
Collection<String> permissions = currentData.getManifestReport().getPermissions();
boolean canReadData = false;
boolean canSendData = false;
int featureIndex = 0;
for (int i = 0; i < SENDING_PERMISSIONS.length; i++) {
String communicationPermission = SENDING_PERMISSIONS[i];
if (!super.isFeatureEnabled(FEATURE_PREFIX_COM + communicationPermission))
continue;
boolean present = false;
for (String permission : permissions)
if (permission.endsWith(communicationPermission)) {
present = true;
canSendData = true;
break;
}
super.setFeatureValue(featureIndex++, present);
}
for (int i = 0; i < DATA_PERMISSIONS.length; i++) {
String dataPermission = DATA_PERMISSIONS[i];
if (!super.isFeatureEnabled(FEATURE_PREFIX_DATA + dataPermission))
continue;
boolean present = false;
for (String permission : permissions)
if (permission.endsWith(dataPermission)) {
present = true;
canReadData = true;
break;
}
super.setFeatureValue(featureIndex++, present);
}
return !(canReadData && canSendData);
}
private void checkContents() {
if (!super.isAnyFeatureEnabled(FEATURE_PREFIX_CONTENT))
return;
SmaliLoader loader = currentData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
final boolean[] contentFound = new boolean[CONTENTS.length];
for (int i = 0; i < CONTENTS.length; i++)
contentFound[i] = false;
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
if (!Literal.isString(value))
return false;
value = Literal.getStringValue(value);
for (int i = 0; i < CONTENTS.length; i++)
if (value.startsWith(CONTENTS[i])) {
contentFound[i] = true;
break;
}
return false;
}
});
constantFinder.searchAllLiterals();
int featureOffset = SENDING_PERMISSIONS.length + DATA_PERMISSIONS.length;
for (int i = 0; i < CONTENTS.length; i++)
super.setFeatureValue(featureOffset + i, contentFound[i]);
}
@Override
protected void defineFeatures() {
for (int i = 0; i < SENDING_PERMISSIONS.length; i++)
super.addFeature(FEATURE_PREFIX_COM + SENDING_PERMISSIONS[i]);
for (int i = 0; i < DATA_PERMISSIONS.length; i++)
super.addFeature(FEATURE_PREFIX_DATA + DATA_PERMISSIONS[i]);
for (int i = 0; i < CONTENTS.length; i++)
super.addFeature(FEATURE_PREFIX_CONTENT + CONTENTS[i]);
}
static final String[] SENDING_PERMISSIONS = new String[] {
"INTERNET",
"ACCESS_NETWORK_STATE",
"CHANGE_NETWORK_STATE",
"BLUETOOTH_ADMIN",
"BLUETOOTH",
"WRITE_APN_SETTINGS",
"NETWORK",
"SUBSCRIBED_FEEDS_WRITE",
"NFC",
"NETWORK_PROVIDER",
"WRITE_SOCIAL_STREAM",
"SEND_SMS",
"USE_SIP"
};
static final String[] DATA_PERMISSIONS = new String[] {
"ACCESS_FINE_LOCATION",
"ACCESS_COARSE_LOCATION",
"ACCESS_LOCATION_EXTRA_COMMANDS",
"ACCESS_MOCK_LOCATION",
"ACCESS_WIFI_STATE",
"CAMERA",
"CAPTURE_AUDIO_OUTPUT",
"CAPTURE_SECURE_VIDEO_OUTPUT",
"CAPTURE_VIDEO_OUTPUT",
"DIAGNOSTIC",
"DUMP",
"GET_ACCOUNTS",
"GET_TASKS",
"LOCATION_HARDWARE",
"READ_CALENDAR",
"READ_CALL_LOG",
"READ_CONTACTS",
"READ_EXTERNAL_STORAGE",
"READ_HISTORY_BOOKMARKS",
"READ_PHONE_STATE",
"READ_PROFILE",
"READ_SMS",
"READ_SOCIAL_STREAM",
"READ_SYNC_SETTINGS",
"RECEIVE_MMS",
"RECEIVE_SMS",
"RECORD_AUDIO"
};
private static final String[] CONTENTS = new String[] {
"content://com.android.calendar",
"content://calendar",
"content://mms",
"content://sms",
"content://com.facebook.katana.provider.AttributionIdProvider",
"content://telephony/carriers/preferapn",
"content://media",
};
}
| 5,988
| 31.198925
| 90
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/SuspiciousUrlsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.utils.Literal;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import java.net.MalformedURLException;
import java.net.URL;
public class SuspiciousUrlsFilter extends FeatureGatherer {
private static final String FEATURE_HARDCODED_URLS = "Contains Hardcoded URLs";
private static final String FEATURE_DIFFERENT_DOMAINS = "URLs Domains differ from Package";
private static final String FEATURE_KNOWN_SUSPIFICOUS_DOMAIN = "Contains URL known to be suspicious";
private static String[] SUSPICIOUS_DOMAINS = {
"nowisgame.com",
"leadbolt.net",
"leadboltapps.net",
"searchmobileonline.com",
"senddroid.com",
"airpush.com",
"apsalar.com",
"adsmogo.net",
"startappexchange.com"
};
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_HARDCODED_URLS);
super.addFeature(FEATURE_DIFFERENT_DOMAINS);
super.addFeature(FEATURE_KNOWN_SUSPIFICOUS_DOMAIN);
}
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isAnyFeatureEnabled(FEATURE_HARDCODED_URLS, FEATURE_DIFFERENT_DOMAINS, FEATURE_KNOWN_SUSPIFICOUS_DOMAIN))
return false;
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
final String packageName = applicationData.getManifestReport().getPackageName();
final String[] packageParts = packageName.split("\\.");
final Wrapper<Boolean> containsUrl = new Wrapper<Boolean>(false);
final Wrapper<Boolean> differentDomains = new Wrapper<Boolean>(false);
final Wrapper<Boolean> suspiciousDomain = new Wrapper<Boolean>(false);
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
if (!Literal.isString(value)) // not starting with " -> not a string literal
return false;
String literal = Literal.getStringValue(value); // string literals contain "
try {
URL url = new URL(literal);
String host = url.getHost();
containsUrl.value = true;
if (packageParts.length > 1) {
if (!host.endsWith(packageParts[1] + "." + packageParts[0]))
differentDomains.value = true;
} else if (packageParts.length > 0) {
if (!host.endsWith(packageParts[0]))
differentDomains.value = true;
}
for (String sd : SUSPICIOUS_DOMAINS)
if (host.endsWith(sd)) {
suspiciousDomain.value = true;
break;
}
} catch (MalformedURLException e) { }
return (containsUrl.value && differentDomains.value && suspiciousDomain.value);
}
});
constantFinder.searchAllLiterals();
super.setFeatureValue(0, containsUrl.value);
super.setFeatureValue(1, differentDomains.value);
super.setFeatureValue(2, suspiciousDomain.value);
return containsUrl.value;
}
}
| 3,902
| 38.03
| 124
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/DangerousPermissionsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.Collection;
public class DangerousPermissionsFilter extends FeatureGatherer {
private static final String FEATURE_PREFIX = "Dangerous Permission: ";
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
Collection<String> permissions = applicationData.getManifestReport().getPermissions();
boolean result = false;
for (int i = 0; i < DANGEROUS_PERMISSIONS.length; i++) {
String dangerousPermission = DANGEROUS_PERMISSIONS[i];
if (!super.isFeatureEnabled(FEATURE_PREFIX + dangerousPermission))
continue;
boolean permissionPresent = false;
for (String permission : permissions)
if (permission.endsWith(dangerousPermission)) {
permissionPresent = true;
result = true;
break;
}
super.setFeatureValue(i, permissionPresent);
}
return result;
}
@Override
protected void defineFeatures() {
for (int i = 0; i < DANGEROUS_PERMISSIONS.length; i++)
super.addFeature(FEATURE_PREFIX + DANGEROUS_PERMISSIONS[i]);
}
static final String[] DANGEROUS_PERMISSIONS = new String[] {
"ACCESS_SUPERUSER",
"BLUETOOTH_PRIVILEGED",
"BRICK",
"CHANGE_COMPONENT_ENABLED_STATE",
"CLEAR_APP_USER_DATA",
"DELETE_CACHE_FILES",
"DELETE_PACKAGES",
"DISABLE_KEYGUARD",
"FACTORY_TEST",
"INSTALL_PACKAGES",
"INJECT_EVENTS",
"INTERNAL_SYSTEM_WINDOW",
"KILL_BACKGROUND_PROCESSES",
"MASTER_CLEAR",
"MODIFY_PHONE_STATE",
"MOUNT_FORMAT_FILESYSTEM",
"MOUNT_UNMOUNT_FILESYSTEM",
"PROCESS_OUTGOING_CALLS",
"READ_LOGS",
"REBOOT",
"RECEIVE_BOOT_COMPLETED",
"STATUS_BAR",
"WRITE_EXTERNAL_STORAGE",
"WRITE_HISTORY_BOOKMARKS",
"WRITE_PROFILE",
"WRITE_SECURE_SETTINGS"
};
}
| 2,496
| 30.607595
| 94
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/HarmlessPermissionsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.Collection;
public class HarmlessPermissionsFilter extends FeatureGatherer {
private static final String FEATURE_PREFIX = "Harmless Permission: ";
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
Collection<String> permissions = applicationData.getManifestReport().getPermissions();
boolean result = false;
for (int i = 0; i < HARMLESS_PERMISSIONS.length; i++) {
String harmlessPermission = HARMLESS_PERMISSIONS[i];
if (!super.isFeatureEnabled(FEATURE_PREFIX + harmlessPermission))
continue;
boolean permissionPresent = false;
for (String permission : permissions)
if (permission.endsWith(harmlessPermission)) {
permissionPresent = true;
result = true;
break;
}
super.setFeatureValue(i, permissionPresent);
}
return result;
}
@Override
protected void defineFeatures() {
for (int i = 0; i < HARMLESS_PERMISSIONS.length; i++)
super.addFeature(FEATURE_PREFIX + HARMLESS_PERMISSIONS[i]);
}
static final String[] HARMLESS_PERMISSIONS = new String[] {
"ACCESS_SURFACE_FLINGER",
"ACCOUNT_MANAGER",
"ADD_VOICEMAIL",
"CONTROL_LOCATION_UPDATES",
"DEVICE_POWER",
"EXPAND_STATUS_BAR",
"FLASHLIGHT",
"FORCE_BACK",
"GET_PACKAGE_SIZE",
"GET_TOP_ACTIVITY_INFO",
"GLOBAL_SEARCH",
"INSTALL_SHORTCUT",
"MANAGE_DOCUMENTS",
"MEDIA_CONTENT_CONTROL",
"MODIFY_AUDIO_SETTINGS",
"READ_USER_DICTIONARY",
"REORDER_TASKS",
"SEND_RESPOND_VIA_MESSAGE",
"SET_ALARM",
"SET_ANIMATION_SCALE",
"SET_ORIENTATION",
"SET_POINTER_SPEED",
"SET_TIME",
"SET_TIME_ZONE",
"SET_WALLPAPER",
"UNINSTALL_SHORTCUT",
"VIBRATE",
"WAKE_LOCK",
"WRITE_CALENDAR",
"WRITE_CALL_LOG",
"WRITE_CONTACTS",
"WRITE_USER_DICTIONARY"
};
}
| 2,625
| 29.894118
| 94
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/PlayStorePopularityFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import com.gc.android.market.api.model.Market.App;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.goodware.markets.GooglePlayStore;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class PlayStorePopularityFilter extends FeatureGatherer {
private static volatile Map<String, Collection<App>> popularAppsByCategory;
private GooglePlayStore store;
private boolean topCategoryAnalysisEnabled;
private int topCount;
public PlayStorePopularityFilter() {
this.setTopCount(100);
this.setTopCategoryAnalysisEnabled(false);
this.store = new GooglePlayStore();
}
@Override
public OperationMode getOperationMode() {
return OperationMode.NETWORK_QUERY;
}
@Override
public synchronized boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (popularAppsByCategory == null) {
popularAppsByCategory = new HashMap<String, Collection<App>>();
}
String packageName = applicationData.getManifestReport().getPackageName();
boolean popular = isPopular(packageName);
boolean top = isTop(packageName);
return popular || top;
}
private boolean isPopular(String packageName) {
store.setExtendedInfo(true);
App target = store.findPackage(packageName);
boolean result = false;
if (target != null) {
if (Float.valueOf(target.getRating()) >= MIN_RATING && target.getRatingsCount() >= MIN_RATING_COUNT)
result = true;
if (target.getExtendedInfo().getDownloadsCount() >= MIN_DOWNLOADS_COUNT)
result = true;
super.setFeatureValue(0, target.getRating());
super.setFeatureValue(1, target.getRatingsCount());
super.setFeatureValue(2, target.getExtendedInfo().getDownloadsCount());
}
else {
super.setFeatureValue(0, 0);
super.setFeatureValue(1, 0);
super.setFeatureValue(2, 0);
}
return result;
}
private boolean isTop(String packageName) {
if (this.isTopCategoryAnalysisEnabled()) {
store.setExtendedInfo(false);
store.setDefaultEntriesCount(this.getTopCount());
for (String category : GooglePlayStore.APP_CATEGORIES) {
if (!popularAppsByCategory.containsKey(category)) {
popularAppsByCategory.put(category, store.searchByCategory(category));
}
int rank = 1;
for (App app : popularAppsByCategory.get(category)) {
if (app.getPackageName().equals(packageName)) {
super.setFeatureValue(3, category);
super.setFeatureValue(4, rank);
return true;
}
rank++;
}
}
}
super.setFeatureValue(3, "");
super.setFeatureValue(4, Integer.MAX_VALUE);
return false;
}
public int getTopCount() {
return topCount;
}
public void setTopCount(int value) {
if (value > 0)
this.topCount = value;
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_RATING);
super.addFeature(FEATURE_RATINGS_COUNT);
super.addFeature(FEATURE_DOWNLOADS);
super.addFeature(FEATURE_TOP_CATEGORY);
super.addFeature(FEATURE_TOP_POSITION);
}
public boolean isTopCategoryAnalysisEnabled() {
return topCategoryAnalysisEnabled;
}
public void setTopCategoryAnalysisEnabled(boolean value) {
this.topCategoryAnalysisEnabled = value;
}
private static final String FEATURE_RATING = "Google Play Rating";
private static final String FEATURE_RATINGS_COUNT = "Google Play Ratings Count";
private static final String FEATURE_DOWNLOADS = "Google Play Downloads";
private static final String FEATURE_TOP_POSITION = "Google Play Category Ranking";
private static final String FEATURE_TOP_CATEGORY = "Google Play Category";
private static final float MIN_RATING = 4.0f;
private static final int MIN_RATING_COUNT = 500;
private static final int MIN_DOWNLOADS_COUNT = 10000;
}
| 4,516
| 31.970803
| 112
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/SystemCallsFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
public class SystemCallsFilter extends FeatureGatherer {
private static final String FEATURE_PREFIX = "Calls a System Routine: ";
private static final SmaliMemberName EXEC = new SmaliMemberName("Ljava/lang/Runtime;->exec");
private static final int COMMAND_PARAMETER_INDEX = 0;
private boolean[] commandFound;
public SystemCallsFilter() {
this.commandFound = new boolean[DANGEROUS_COMMANDS.length];
}
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
private void reset() {
for (int i = 0; i < commandFound.length; i++)
commandFound[i] = false;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isAnyFeatureEnabled(FEATURE_PREFIX))
return false;
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
this.reset();
boolean result = false;
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
for (int i = 0; i < DANGEROUS_COMMANDS.length; i++)
if (value.contains(DANGEROUS_COMMANDS[i]))
commandFound[i] = true;
return false;
}
});
constantFinder.searchParameters(EXEC, COMMAND_PARAMETER_INDEX);
for (int i = 0; i < DANGEROUS_COMMANDS.length; i++) {
super.setFeatureValue(i, commandFound[i]);
if (commandFound[i])
result = true;
}
return result;
}
@Override
protected void defineFeatures() {
for (int i = 0; i < DANGEROUS_COMMANDS.length; i++)
super.addFeature(FEATURE_PREFIX + DANGEROUS_COMMANDS[i]);
}
private static final String[] DANGEROUS_COMMANDS = {
"su", "ls", "loadjar", "grep",
"/sh", "/bin", "pm install", "/dev/net", "insmod",
"rm", "mount", "root", "/system", "stdout",
"reboot", "killall", "chmod", "stderr", "ratc"
};
}
| 2,628
| 31.8625
| 97
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/HiddenApkFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.apk.DecodedPackage;
import it.polimi.elet.necst.heldroid.apk.DecodingException;
import it.polimi.elet.necst.heldroid.apk.PackageDecoder;
import it.polimi.elet.necst.heldroid.apk.PackageDecoders;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
public class HiddenApkFilter extends FeatureGatherer {
private static final String FEATURE_NAME = "Hidden Apk";
private static PackageDecoder decoder;
private static char[][] SIGNATURES = {
{0x50, 0x4B, 0x03, 0x04},
{0x50, 0x4B, 0x05, 0x06},
{0x50, 0x4B, 0x07, 0x08}
};
@Override
public OperationMode getOperationMode() {
return OperationMode.FILE_ANALYSIS;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isFeatureEnabled(FEATURE_NAME))
return false;
Collection<File> allFiles = applicationData.getDecodedFileTree().getAllFiles();
boolean apkPresent = false;
for (File file : allFiles)
if (isZipBased(file) && isApk(file)) {
apkPresent = true;
break;
}
super.setFeatureValue(0, apkPresent);
return apkPresent;
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_NAME);
}
public static boolean isZipBased(File file) {
try {
FileReader reader = new FileReader(file);
char[] signature = new char[SIGNATURES[0].length];
reader.read(signature, 0, signature.length);
reader.close();
for (char[] VALID_SIGNATURE : SIGNATURES) {
boolean match = true;
for (int i = 0; i < VALID_SIGNATURE.length; i++)
if (signature[i] != VALID_SIGNATURE[i]) {
match = false;
break;
}
if (match)
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
public static boolean isApk(File file) {
if (decoder == null)
decoder = PackageDecoders.apkTool();
try {
DecodedPackage dp = decoder.decode(file);
dp.dispose();
return true;
} catch (DecodingException e) {
return false;
}
}
}
| 2,682
| 27.242105
| 87
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/SuspiciousFlowFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliInspector;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.core.SmaliClass;
import it.polimi.elet.necst.heldroid.smali.core.SmaliMethod;
import it.polimi.elet.necst.heldroid.smali.names.SmaliClassName;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
import java.util.Arrays;
import java.util.Collection;
public class SuspiciousFlowFilter extends FeatureGatherer {
private SmaliLoader loader;
private SmaliInspector inspector;
private Collection<SmaliClass> activities;
private Collection<SmaliClass> services;
private SmaliClass smsReceiver;
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_DATA);
super.addFeature(FEATURE_SMS);
super.addFeature(FEATURE_SERVICE);
super.addFeature(FEATURE_SMS_SEND_SMS);
super.addFeature(FEATURE_SMS_INTERNET);
super.addFeature(FEATURE_SMS_DB);
}
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
this.resetFeaturesValues();
this.loader = applicationData.getSmaliLoader();
this.inspector = loader.generateInspector();
return this.performDeepFlowAnalysis();
}
private boolean performDeepFlowAnalysis() {
this.activities = loader.getSubclassesOf(ACTIVITY);
this.services = loader.getSubclassesOf(SERVICE);
boolean readsDataAtStartup = false;
boolean sendsSmsAtStartup = false;
boolean startsServiceAtStartup = false;
boolean smsSendSms = false;
boolean smsSendData = false;
boolean smsStoreData = false;
int i = 0;
if (super.isFeatureEnabled(FEATURE_DATA)) {
readsDataAtStartup = invokedAtStartup(READ_PHONE_DATA_METHODS);
super.setFeatureValue(i++, readsDataAtStartup);
}
if (super.isFeatureEnabled(FEATURE_SMS)) {
sendsSmsAtStartup = invokedAtStartup(SEND_TEXT_MESSAGE);
super.setFeatureValue(i++, sendsSmsAtStartup);
}
if (super.isFeatureEnabled(FEATURE_SERVICE)) {
startsServiceAtStartup = invokedAtStartup(START_SERVICE);
super.setFeatureValue(i++, startsServiceAtStartup);
}
smsReceiver = this.findSmsReceiver();
if (smsReceiver != null) {
SmaliMethod onReceive = smsReceiver.getMethodByName(ON_RECEIVE);
if (onReceive != null) {
if (super.isFeatureEnabled(FEATURE_SMS_SEND_SMS))
smsSendSms = inspector.is(SEND_TEXT_MESSAGE).reachableFrom(onReceive);
if (super.isFeatureEnabled(FEATURE_SMS_INTERNET))
smsSendData = inspector.isAnyClass(Arrays.asList(HTTP_CLIENT, HTTP_POST, HTTP_GET)).reachableFrom(onReceive);
if (super.isFeatureEnabled(FEATURE_SMS_DB))
smsStoreData = inspector.isAnyClass(Arrays.asList(CURSOR, SQLITE_DATABASE)).reachableFrom(onReceive);
}
}
super.setFeatureValue(i++, smsSendSms);
super.setFeatureValue(i++, smsSendData);
super.setFeatureValue(i++, smsStoreData);
return readsDataAtStartup | sendsSmsAtStartup | startsServiceAtStartup | smsSendSms | smsSendData | smsStoreData;
}
private boolean invokedAtStartup(SmaliMemberName methodName) {
return invokedAtStartup(inspector.is(methodName));
}
private boolean invokedAtStartup(Collection<SmaliMemberName> methodNames) {
return invokedAtStartup(inspector.isAny(methodNames));
}
private boolean invokedAtStartup(SmaliInspector.Inspection isApi) {
return
isApi.reachableFromAny(activities, ON_CREATE) ||
isApi.reachableFromAny(services, ON_CREATE_SERVICE) ||
isApi.reachableFromAny(activities, ON_START) ||
isApi.reachableFromAny(activities, ON_RESTART);
}
private SmaliClass findSmsReceiver() {
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
for (SmaliClass klass : loader.getSubclassesOf(BROADCAST_RECEIVER)) {
String klassSimpleName = klass.getName().getSimpleName();
if (klassSimpleName.toLowerCase().contains("sms"))
return klass;
final Wrapper<Boolean> readsPdus = new Wrapper<Boolean>(false);
// pdus is the name of the field in the extra attribute of a bundle that contains sms bodies
// only used in sms receivers
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
value = value.replace("\"", "");
if (value.equals("pdus")) {
readsPdus.value = true;
return true;
}
return false;
}
});
constantFinder.searchAllLiterals(klass);
if (readsPdus.value)
return klass;
}
return null;
}
private static final String FEATURE_DATA = "Reads phone data at startup";
private static final String FEATURE_SMS = "Sends SMS at startup"; // TODO: remove
private static final String FEATURE_SERVICE = "Starts service at startup";
private static final String FEATURE_SMS_SEND_SMS = "Sends SMS when receiving SMS"; // TODO: remove
private static final String FEATURE_SMS_INTERNET = "Sends data to a remote page when receiving SMS"; // TODO: remove
private static final String FEATURE_SMS_DB = "Accesses a database when receiving SMS"; // TODO: remove
private static Collection<SmaliMemberName> READ_PHONE_DATA_METHODS = SmaliMemberName.newList(
"Landroid/telephony/TelephonyManager;->getSubscriberId",
"Landroid/telephony/TelephonyManager;->getDeviceId",
"Landroid/telephony/TelephonyManager;->getLine1Number",
"Landroid/telephony/TelephonyManager;->getSimSerialNumber",
"Landroid/telephony/TelephonyManager;->getCellLocation",
"Landroid/telephony/TelephonyManager;->getSimOperatorName",
"Landroid/accounts/AccountManager->getAccounts",
"Landroid/provider/Browser;->getAllBookmarks"
);
private static final SmaliMemberName SEND_TEXT_MESSAGE = new SmaliMemberName("Landroid/telephony/SmsManager;->sendTextMessage");
private static final SmaliMemberName START_SERVICE = new SmaliMemberName("Landroid/content/Context;->startService");
private static final SmaliMemberName ON_RECEIVE = new SmaliMemberName("Landroid/content/BroadcastReceiver;->onReceive");
private static final SmaliMemberName ON_CREATE_SERVICE = new SmaliMemberName("Landroid/app/Service;->onCreate");
private static final SmaliMemberName ON_CREATE = new SmaliMemberName("Landroid/app/Activity;->onCreate");
private static final SmaliMemberName ON_START = new SmaliMemberName("Landroid/app/Activity;->onStart");
private static final SmaliMemberName ON_RESTART = new SmaliMemberName("Landroid/app/Activity;->onRestart");
private static final SmaliClassName BROADCAST_RECEIVER = new SmaliClassName("Landroid/content/BroadcastReceiver;");
private static final SmaliClassName ACTIVITY = new SmaliClassName("Landroid/app/Activity;");
private static final SmaliClassName SERVICE = new SmaliClassName("Landroid/app/Service;");
private static final SmaliClassName CURSOR = new SmaliClassName("Landroid/database/Cursor;");
private static final SmaliClassName SQLITE_DATABASE = new SmaliClassName("Landroid/database/sqlite/SQLiteDatabase;");
private static final SmaliClassName HTTP_CLIENT = new SmaliClassName("Lorg/apache/http/impl/client/DefaultHttpClient;");
private static final SmaliClassName HTTP_POST = new SmaliClassName("Lorg/apache/http/client/methods/HttpPost;");
private static final SmaliClassName HTTP_GET = new SmaliClassName("Lorg/apache/http/client/methods/HttpGet;");
}
| 8,567
| 43.393782
| 132
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/SmsNumbersFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
public class SmsNumbersFilter extends FeatureGatherer {
private static final String FEATURE_NAME = "Sends SMS to Suspicious Number(s)";
private static final SmaliMemberName SEND_TEXT_MESSAGE = new SmaliMemberName("Landroid/telephony/SmsManager;->sendTextMessage");
private static final int SMS_RECEIVER_PARAMETER_INDEX = 0;
// Numbers starting with #, ##, #*, * or ** are usually employed by carriers to provide
// instant services such as account balance and account management
private static final String[] CARRIER_NUMBERS_PREFIXES = { "#", "*" };
private static final Character ALLOWED_NUMBER_PREFIXE = '+';
@Override
public OperationMode getOperationMode() {
return OperationMode.DATA_INSPECTION;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isFeatureEnabled(FEATURE_NAME))
return false;
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
final Wrapper<Boolean> suspiciousNumberFound = new Wrapper<Boolean>();
suspiciousNumberFound.value = false;
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String value) {
if (!isPhoneNumber(value))
return false;
if (isSuspiciousNumber(value)) {
suspiciousNumberFound.value = true;
return true;
}
return false;
}
});
constantFinder.searchParameters(SEND_TEXT_MESSAGE, SMS_RECEIVER_PARAMETER_INDEX);
super.setFeatureValue(0, suspiciousNumberFound.value);
return suspiciousNumberFound.value;
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_NAME);
}
private boolean isPhoneNumber(String literal) {
boolean prefix = true;
boolean isNumber = true;
literal = literal.replace("\"", ""); // purge quotes
for (Character c : literal.toCharArray()) {
if (!Character.isDigit(c)) {
if (prefix && c.equals(ALLOWED_NUMBER_PREFIXE))
continue;
isNumber = false;
break;
}
prefix = false;
}
return isNumber;
}
private boolean isSuspiciousNumber(String number) {
boolean isCarrierServiceNumber = false;
for (String prefix : CARRIER_NUMBERS_PREFIXES)
if (number.startsWith(prefix)) {
isCarrierServiceNumber = true;
break;
}
return !isCarrierServiceNumber;
}
}
| 3,261
| 32.285714
| 132
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/SuspiciousIntentFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import it.polimi.elet.necst.heldroid.smali.SmaliConstantFinder;
import it.polimi.elet.necst.heldroid.smali.SmaliLoader;
import it.polimi.elet.necst.heldroid.smali.names.SmaliMemberName;
import it.polimi.elet.necst.heldroid.utils.Wrapper;
public class SuspiciousIntentFilter extends FeatureGatherer {
@Override
public OperationMode getOperationMode() {
return OperationMode.FILE_ANALYSIS;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isAnyFeatureEnabled(FEATURE_PREFIX))
return false;
final boolean[] intentFound = new boolean[SUSPICIOUS_INTENTS.length];
final Wrapper<Boolean> somethingFound = new Wrapper<Boolean>();
somethingFound.value = false;
for (String intent : applicationData.getManifestReport().getIntentFilters())
for (int i = 0; i < SUSPICIOUS_INTENTS.length; i++)
if (intent.endsWith(SUSPICIOUS_INTENTS[i])) {
intentFound[i] = true;
somethingFound.value = true;
}
if (somethingFound.value == false) {
SmaliLoader loader = applicationData.getSmaliLoader();
SmaliConstantFinder constantFinder = loader.generateConstantFinder();
constantFinder.setHandler(new SmaliConstantFinder.ConstantHandler() {
@Override
public boolean constantFound(String intentName) {
for (int i = 0; i < SUSPICIOUS_INTENTS.length; i++)
if (intentName.endsWith(SUSPICIOUS_INTENTS[i])) {
intentFound[i] = true;
somethingFound.value = true;
}
return false;
}
});
constantFinder.searchParameters(ADD_ACTION, 0);
}
for (int i = 0; i < SUSPICIOUS_INTENTS.length; i++)
super.setFeatureValue(i, intentFound[i]);
return somethingFound.value;
}
@Override
protected void defineFeatures() {
for (int i = 0; i < SUSPICIOUS_INTENTS.length; i++)
super.addFeature(FEATURE_PREFIX + SUSPICIOUS_INTENTS[i]);
}
private static String FEATURE_PREFIX = "Suspicious Intent Filter: ";
private static SmaliMemberName ADD_ACTION = new SmaliMemberName("Landroid/content/IntentFilter->addAction");
private static String[] SUSPICIOUS_INTENTS = new String[] {
"AIRPLANE_MODE_CHANGED",
"BOOT_COMPLETED",
"CONFIGURATION_CHANGED",
"BATTERY_CHANGED",
"DEVICE_STORAGE_LOW",
"DOCK_EVENT",
"EXTERNAL_APPLICATIONS_AVAILABLE",
"MANAGE_PACKAGE_STORAGE",
"MEDIA_MOUNTED",
"MY_PACKAGE_REPLACED",
"NEW_OUTGOING_CALL",
"PACKAGE_ADDED",
"PACKAGE_CHANGED",
"PACKAGE_DATA_CLEARED",
"PACKAGE_FIRST_LAUNCH",
"PACKAGE_INSTALL",
"PACKAGE_REMOVED",
"PACKAGE_REPLACED",
"PACKAGE_RESTARTED",
"POWER_CONNECTED",
"PROVIDER_CHANGED",
"REBOOT",
"SHUTDOWN",
"USER_PRESENT"
};
}
| 3,497
| 35.061856
| 112
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/ValidDomainFilter.java
|
package it.polimi.elet.necst.heldroid.goodware.features;
import it.polimi.elet.necst.heldroid.goodware.features.core.FeatureGatherer;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ValidDomainFilter extends FeatureGatherer {
private static final String FEATURE_NAME = "Package Domain Exists";
@Override
public OperationMode getOperationMode() {
return OperationMode.NETWORK_QUERY;
}
@Override
public boolean extractFeatures(ApplicationData applicationData) {
super.resetFeaturesValues();
if (!super.isFeatureEnabled(FEATURE_NAME))
return false;
String packageName = applicationData.getManifestReport().getPackageName();
String[] packageParts = packageName.split("\\.");
if (packageParts.length < 2) {
super.setFeatureValue(0, false);
return false;
}
try {
InetAddress inetAddress = InetAddress.getByName(packageParts[1] + "." + packageParts[0]);
super.setFeatureValue(0, true);
return true;
} catch (UnknownHostException uhe) {
super.setFeatureValue(0, false);
return false;
}
}
@Override
protected void defineFeatures() {
super.addFeature(FEATURE_NAME);
}
}
| 1,389
| 28.574468
| 101
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/core/FeatureCollection.java
|
package it.polimi.elet.necst.heldroid.goodware.features.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class FeatureCollection {
public static Collection<Feature> singleton(Feature feature) {
List<Feature> list = new ArrayList<Feature>();
list.add(feature);
return list;
}
public static Collection<Feature> singleton(String name, Object value) {
return singleton(new Feature(name, value));
}
public static Collection<Feature> build(Feature... features) {
List<Feature> list = new ArrayList<Feature>();
for (Feature f : features)
list.add(f);
return list;
}
public static Collection<Feature> map(String[] names, Object[] values) {
if (names.length != values.length)
throw new IndexOutOfBoundsException("Names and Values must have the same length, you fool!");
List<Feature> featureList = new ArrayList<Feature>();
for (int i = 0; i < names.length; i++)
featureList.add(new Feature(names[i], values[i]));
return featureList;
}
}
| 1,139
| 28.230769
| 105
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/core/MetaFeatureGatherer.java
|
package it.polimi.elet.necst.heldroid.goodware.features.core;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MetaFeatureGatherer {
private static final int MAX_THREAD_COUNT = 11;
private static final int MAX_TIMEOUT = 7;
private List<FeatureGatherer> filters;
private List<FeatureGatherer> dataInspectionFilters, fileEnumerationFilters, fileAnalysisFilters, networkQueryFilters;
public Collection<FeatureGatherer> getFilters() {
return filters;
}
public MetaFeatureGatherer() {
filters = new ArrayList<FeatureGatherer>();
dataInspectionFilters = new ArrayList<FeatureGatherer>();
fileEnumerationFilters = new ArrayList<FeatureGatherer>();
fileAnalysisFilters = new ArrayList<FeatureGatherer>();
networkQueryFilters = new ArrayList<FeatureGatherer>();
}
public void add(FeatureGatherer filter) {
filters.add(filter);
switch (filter.getOperationMode()) {
case DATA_INSPECTION:
dataInspectionFilters.add(filter);
break;
case FILE_ENUMERATION:
fileEnumerationFilters.add(filter);
break;
case FILE_ANALYSIS:
fileAnalysisFilters.add(filter);
break;
case NETWORK_QUERY:
networkQueryFilters.add(filter);
break;
}
}
public void remove(FeatureGatherer filter) {
filters.remove(filter);
switch (filter.getOperationMode()) {
case DATA_INSPECTION:
dataInspectionFilters.remove(filter);
break;
case FILE_ENUMERATION:
fileEnumerationFilters.remove(filter);
break;
case FILE_ANALYSIS:
fileAnalysisFilters.remove(filter);
break;
case NETWORK_QUERY:
networkQueryFilters.remove(filter);
break;
}
}
public void enableAllFeatures() {
for (FeatureGatherer filter : filters)
filter.enableAllFeatures();
}
public void disableAllFeatures() {
for (FeatureGatherer filter : filters)
filter.disableAllFeatures();
}
public void enableFeatures(Collection<String> featuresNames) {
for (FeatureGatherer filter : filters)
for (String name : featuresNames)
if (filter.isFeatureDefined(name))
filter.enableFeature(name);
}
public void matchAllFilters(final ApplicationData applicationData) {
ExecutorService executor = Executors.newFixedThreadPool(MAX_THREAD_COUNT);
for (final FeatureGatherer networkQueryFilter : networkQueryFilters)
executor.execute(new Runnable() {
@Override
public void run() {
networkQueryFilter.extractFeatures(applicationData);
}
});
for (final FeatureGatherer fileAnalysisFilter : fileAnalysisFilters)
executor.execute(new Runnable() {
@Override
public void run() {
fileAnalysisFilter.extractFeatures(applicationData);
}
});
for (final FeatureGatherer fileEnumerationFilter : fileEnumerationFilters)
executor.execute(new Runnable() {
@Override
public void run() {
fileEnumerationFilter.extractFeatures(applicationData);
}
});
for (final FeatureGatherer dataInspectionFilter : dataInspectionFilters)
executor.execute(new Runnable() {
@Override
public void run() {
dataInspectionFilter.extractFeatures(applicationData);
}
});
try {
executor.shutdown();
if (!executor.awaitTermination(MAX_TIMEOUT, TimeUnit.SECONDS))
executor.shutdownNow(); // forces threads termination if they don't end after timeout
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Collection<Feature> getAllFiltersFeatures() {
List<Feature> featureList = new ArrayList<Feature>();
for (FeatureGatherer filter : filters)
featureList.addAll(filter.getFeatures());
return featureList;
}
}
| 4,615
| 31.055556
| 122
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/core/FeatureGatherer.java
|
package it.polimi.elet.necst.heldroid.goodware.features.core;
import it.polimi.elet.necst.heldroid.pipeline.ApplicationData;
import java.util.*;
public abstract class FeatureGatherer {
private List<Feature> features;
private List<Object> defaultValues;
private Map<String, Boolean> featuresEnabled;
public enum OperationMode {
DATA_INSPECTION,
FILE_ENUMERATION,
FILE_ANALYSIS,
NETWORK_QUERY
}
public abstract OperationMode getOperationMode();
public abstract boolean extractFeatures(ApplicationData applicationData);
public FeatureGatherer() {
this.clearFeatures();
this.defineFeatures();
this.resetFeaturesValues();
this.enableAllFeatures();
}
public Collection<Feature> getFeatures() {
return features;
}
private void clearFeatures() {
if (features == null)
features = new ArrayList<Feature>();
features.clear();
}
protected int addFeature(Feature feature) {
features.add(feature);
return features.size() - 1;
}
protected int addFeature(String name, Object defaultValue) {
features.add(new Feature(name, defaultValue));
return features.size() - 1;
}
protected int addFeature(String name) {
features.add(new Feature(name));
return features.size() - 1;
}
protected void setFeatureValue(int index, Object value) {
features.get(index).setValue(value);
}
protected void resetFeaturesValues() {
for (Feature feature : features)
feature.setValue(feature.getDefaultValue());
}
protected abstract void defineFeatures();
protected void setAllFeaturesEnabled(boolean enabled) {
if (featuresEnabled == null)
featuresEnabled = new HashMap<String, Boolean>();
for (Feature feature : features)
featuresEnabled.put(feature.getName(), enabled);
}
protected void setFeatureEnabled(String name, boolean enabled) {
featuresEnabled.put(name, enabled);
}
public void enableAllFeatures() {
this.setAllFeaturesEnabled(true);
}
public void disableAllFeatures() {
this.setAllFeaturesEnabled(false);
}
public void enableFeature(String name) {
this.setFeatureEnabled(name, true);
}
public void disableFeature(String name) {
this.setFeatureEnabled(name, false);
}
public boolean isFeatureEnabled(String name) {
return featuresEnabled.get(name);
}
public boolean isFeatureDefined(String name) {
return featuresEnabled.containsKey(name);
}
public boolean isAnyFeatureEnabled(String prefix) {
for (String key : featuresEnabled.keySet())
if (featuresEnabled.get(key) == true)
return true;
return false;
}
public boolean isAnyFeatureEnabled(String... names) {
for (String name : names)
if (featuresEnabled.get(name) == true)
return true;
return false;
}
}
| 3,089
| 24.966387
| 77
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/features/core/Feature.java
|
package it.polimi.elet.necst.heldroid.goodware.features.core;
public class Feature {
public static final String UNKNOWN_VALUE = "?";
private String name;
private Object value, defaultValue;
public Object getDefaultValue() {
return defaultValue;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getName() {
return name;
}
public Feature(String name, Object defaultValue) {
this.name = name;
this.value = defaultValue;
this.defaultValue = defaultValue;
}
public Feature(String name) {
this.name = name;
this.value = UNKNOWN_VALUE;
this.defaultValue = UNKNOWN_VALUE;
}
@Override
public String toString() {
return value.toString();
}
}
| 870
| 19.738095
| 61
|
java
|
heldroid
|
heldroid-master/src/java/it/polimi/elet/necst/heldroid/goodware/weka/ApkClassifier.java
|
package it.polimi.elet.necst.heldroid.goodware.weka;
import it.polimi.elet.necst.heldroid.goodware.features.core.Feature;
import weka.classifiers.misc.SerializedClassifier;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import java.io.*;
import java.util.*;
public class ApkClassifier {
private File attributesFile;
private Map<Attribute, Double[]> discretizedAttributeSplitPoints;
private Collection<Attribute> discretizedAttributes;
private Collection<String> attributesNames;
private SerializedClassifier innerClassifier;
private Instances dummyDataSet;
public Collection<String> getAttributesNames() {
return attributesNames;
}
public ApkClassifier(File model, File attributes) throws IOException {
if (!model.exists() || !attributes.exists())
throw new FileNotFoundException("Model or attributes files not present.");
innerClassifier = new SerializedClassifier();
innerClassifier.setModelFile(model);
this.attributesFile = attributes;
this.createDummyDataSet();
}
private void createDummyDataSet() throws IOException {
InputStream stream = new FileInputStream(attributesFile);
Reader reader = new InputStreamReader(stream);
this.dummyDataSet = new Instances(reader);
this.dummyDataSet.setClassIndex(dummyDataSet.numAttributes() - 1);
this.discretizedAttributes = new HashSet<Attribute>();
this.attributesNames = new ArrayList<String>();
for (int i = 0; i < dummyDataSet.numAttributes(); i++) {
Attribute a = dummyDataSet.attribute(i);
if (a.value(0).contains("-inf"))
discretizedAttributes.add(a);
attributesNames.add(a.name());
}
}
private Instance createInstance(Collection<Feature> features) {
if (features.size() < dummyDataSet.numAttributes())
throw new RuntimeException("Wrong number of core provided.");
Instance result = new DenseInstance(dummyDataSet.numAttributes());
result.setDataset(dummyDataSet);
for (int i = 0; i < dummyDataSet.numAttributes(); i++)
{
Attribute attribute = dummyDataSet.attribute(i);
String attributeName = attribute.name();
for (Feature feature : features)
if (feature.getName().equals(attributeName)) {
String strValue = feature.getValue().toString();
if (strValue.equals(Feature.UNKNOWN_VALUE)) {
result.setMissing(i);
break;
}
if (!discretizedAttributes.contains(attribute)) {
if (attribute.isNumeric())
result.setValue(i, Double.parseDouble(strValue));
else
result.setValue(i, strValue);
} else {
Double value = Double.valueOf(strValue);
result.setValue(i, discretize(attribute, value));
}
}
}
return result;
}
private String discretize(Attribute binnedAttribute, double value) {
if (discretizedAttributeSplitPoints == null)
discretizedAttributeSplitPoints = new HashMap<Attribute, Double[]>();
Double[] splitPoints;
if (discretizedAttributeSplitPoints.containsKey(binnedAttribute)) {
splitPoints = discretizedAttributeSplitPoints.get(binnedAttribute);
} else {
splitPoints = new Double[binnedAttribute.numValues()];
int j = 0;
for (int i = 0; i < binnedAttribute.numValues(); i++) {
String bin = binnedAttribute.value(i);
Double upperBound = parseUpperBound(bin);
splitPoints[j++] = upperBound;
}
discretizedAttributeSplitPoints.put(binnedAttribute, splitPoints);
}
for (int i = 0; i < binnedAttribute.numValues(); i++)
if (value <= splitPoints[i])
return binnedAttribute.value(i);
return binnedAttribute.value(binnedAttribute.numValues() - 1);
}
private Double parseUpperBound(String bin) {
StringBuilder builder = new StringBuilder();
for (Character c : bin.toCharArray())
if (c == '\'' || c == '(' || c == ')' || c == '[' || c == ']')
continue;
else
builder.append(c);
String cleanedBin = builder.toString();
String[] bounds = cleanedBin.split("\\-");
String upperBound = bounds[bounds.length - 1];
if (upperBound.equals("inf"))
return Double.POSITIVE_INFINITY;
return Double.valueOf(upperBound);
}
public String classify(Collection<Feature> features) {
Instance instance = this.createInstance(features);
try {
double predictedClass = innerClassifier.classifyInstance(instance);
return dummyDataSet.classAttribute().value((int)predictedClass);
} catch (Exception e) {
e.printStackTrace();
return Feature.UNKNOWN_VALUE;
}
}
public double[] computeDistribution(Collection<Feature> features) {
Instance instance = this.createInstance(features);
try {
return innerClassifier.distributionForInstance(instance);
} catch (Exception e) {
e.printStackTrace();
return new double[0];
}
}
public String getClassLabelFromIndex(double index) {
return dummyDataSet.classAttribute().value((int)index);
}
public String[] getClassLabels() {
int count = dummyDataSet.classAttribute().numValues();
String[] classes = new String[count];
for (int i = 0; i < count; i++)
classes[i] = this.getClassLabelFromIndex(i);
return classes;
}
}
| 6,048
| 32.605556
| 86
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.