Search in sources :

Example 1 with Cleanup

use of lombok.Cleanup in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class CellTracker method compareLac.

/**
     *          I removed the timer that activated this code and now the code will be run when
     *          the cell changes so it will detect faster rather than using a timer that might
     *          miss an imsi catcher, also says cpu rather than refreshing every x seconds.
     *
     *          original comments below from xLaMbChOpSx
     *
     *
     *  Description:    (From xLaMbChOpSx commit comment)
     *
     *      Initial implementation for detection method 1 to compare the CID & LAC with the Cell
     *      Information Table contents as an initial implementation for detection of a changed LAC,
     *      once OCID issues (API key use etc) have been finalised this detection method can be
     *      extended to include checking of external data.
     *
     *      REMOVED: refresh timer info
     *
     *      As I have no real way of testing this I require testing by other project members who
     *      do have access to equipment or an environment where a changing LAC can be simulated
     *      thus confirming the accuracy of this implementation.
     *
     *      Presently this will only invoke the MEDIUM threat level through the notification and
     *      does not fully implement the capturing and score based method as per the issue details
     *      once further testing is complete the alert and tracking of information can be refined.
     *
     *      See:
     *        https://github.com/xLaMbChOpSx/Android-IMSI-Catcher-Detector/commit/43ae77e2a0cad10dfd50f92da5a998f9ece95b38
     *        https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/91#issuecomment-64391732
     *
     *  Short explanation:
     *
     *                  This is a polling mechanism for getting the LAC/CID and location
     *                  info for the currently connected cell.
     *
     *  Variables:
     *                  FIXED: now updates on cell change rather than a timer
     *                  There is a "timer" here (REFRESH_RATE), what exactly is it timing?
     *                  "Every REFRESH_RATE seconds, get connected cell details."
     *
     *  Issues:     [ ] We shouldn't do any detection here!
     *              [ ] We might wanna use a listener to do this?
     *                  Are there any reasons why not using a listener?
     *
     *  ChangeLog:
     *              2015-03-03  E:V:A           Changed getProp() to use TinyDB (SharedPreferences)
     *              2015-0x-xx  banjaxbanjo     Update: ??? (hey dude what did you do?)
     *
     */
public void compareLac(CellLocation location) {
    @Cleanup Realm realm = Realm.getDefaultInstance();
    switch(device.getPhoneId()) {
        case TelephonyManager.PHONE_TYPE_NONE:
        case TelephonyManager.PHONE_TYPE_SIP:
        case TelephonyManager.PHONE_TYPE_GSM:
            GsmCellLocation gsmCellLocation = (GsmCellLocation) location;
            if (gsmCellLocation != null) {
                monitorCell.setLocationAreaCode(gsmCellLocation.getLac());
                monitorCell.setCellId(gsmCellLocation.getCid());
                // Check if LAC is ok
                boolean lacOK = dbHelper.checkLAC(realm, monitorCell);
                if (!lacOK) {
                    changedLAC = true;
                    dbHelper.toEventLog(realm, 1, "Changing LAC");
                    // Detection Logs are made in checkLAC()
                    vibrate(100, Status.MEDIUM);
                } else {
                    changedLAC = false;
                }
                if (tinydb.getBoolean("ocid_downloaded")) {
                    if (!dbHelper.openCellExists(realm, monitorCell.getCellId())) {
                        dbHelper.toEventLog(realm, 2, "CID not in Import realm");
                        log.info("ALERT: Connected to unknown CID not in Import realm: " + monitorCell.getCellId());
                        vibrate(100, Status.MEDIUM);
                        cellIdNotInOpenDb = true;
                    } else {
                        cellIdNotInOpenDb = false;
                    }
                }
            }
            break;
        case TelephonyManager.PHONE_TYPE_CDMA:
            CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) location;
            if (cdmaCellLocation != null) {
                monitorCell.setLocationAreaCode(cdmaCellLocation.getNetworkId());
                monitorCell.setCellId(cdmaCellLocation.getBaseStationId());
                boolean lacOK = dbHelper.checkLAC(realm, monitorCell);
                if (!lacOK) {
                    changedLAC = true;
                    /*dbHelper.insertEventLog(
                                MiscUtils.getCurrentTimeStamp(),
                                monitorCell.getLAC(),
                                monitorCell.getCid(),
                                monitorCell.getPSC(),//This is giving weird values like 21478364... is this right?
                                String.valueOf(monitorCell.getLat()),
                                String.valueOf(monitorCell.getLon()),
                                (int)monitorCell.getAccuracy(),
                                1,
                                "Changing LAC"
                        );*/
                    dbHelper.toEventLog(realm, 1, "Changing LAC");
                } else {
                    changedLAC = false;
                }
            }
    }
    setNotification();
}
Also used : CdmaCellLocation(android.telephony.cdma.CdmaCellLocation) GsmCellLocation(android.telephony.gsm.GsmCellLocation) Cleanup(lombok.Cleanup) Realm(io.realm.Realm)

Example 2 with Cleanup

use of lombok.Cleanup in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class SignalStrengthTracker method isMysterious.

/**
     * Uses previously saved calculations and signal measurements to guesstimate if a given signal
     * strength for a given cell ID looks mysterious or not.
     *
     * @param cellID
     * @param signalStrength
     */
public boolean isMysterious(int cellID, int signalStrength) {
    // If moving, return false
    if (deviceIsMoving()) {
        log.info("Cannot check signal strength for CID: " + cellID + " because of device movements.");
        return false;
    }
    int storedAvg;
    // Cached?
    if (averageSignalCache.get(cellID) != null) {
        storedAvg = averageSignalCache.get(cellID);
        log.debug("Cached average SS for CID: " + cellID + " is: " + storedAvg);
    } else {
        // Not cached, check DB
        @Cleanup Realm realm = Realm.getDefaultInstance();
        storedAvg = mDbHelper.getAverageSignalStrength(realm, cellID);
        averageSignalCache.put(cellID, storedAvg);
        log.debug("Average SS in DB for  CID: " + cellID + " is: " + storedAvg);
    }
    boolean result;
    if (storedAvg > signalStrength) {
        result = storedAvg - signalStrength > mysteriousSignalDifference;
    } else {
        result = signalStrength - storedAvg > mysteriousSignalDifference;
    }
    log.debug("Signal Strength mystery check for CID: " + cellID + " is " + result + ", avg:" + storedAvg + ", this signal: " + signalStrength);
    return result;
}
Also used : Cleanup(lombok.Cleanup) Realm(io.realm.Realm)

Example 3 with Cleanup

use of lombok.Cleanup in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class ImportTask method onPostExecute.

/**
     * This is where we:
     * <ol>
     * <li>Check the success for data import</li>
     * <li>call the updateOpenCellID() to populate the {@link com.secupwn.aimsicd.data.model.Import Import} realm</li>
     * <li>call the {@link RealmHelper#checkDBe()} to cleanup bad cells from imported data</li>
     * <li>present a failure/success toast message</li>
     * <li>set a shared preference to indicate that data has been downloaded:
     * {@code ocid_downloaded true}</li>
     * </ol>
     */
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    TinyDB tinydb = TinyDB.getInstance();
    @Cleanup Realm realm = Realm.getDefaultInstance();
    // if `result` is null, it will evaluate to false, no need to check for null
    if ("Successful".equals(result)) {
        Helpers.msgShort(mAppContext, mAppContext.getString(R.string.celltowers_data_successfully_imported));
        realm.executeTransaction(mDbAdapter.checkDBe());
        tinydb.putBoolean("ocid_downloaded", true);
    } else {
        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.error_importing_celltowers_data));
    }
    if (mListener != null) {
        if ("Successful".equals(result)) {
            mListener.onAsyncTaskSucceeded();
        } else {
            mListener.onAsyncTaskFailed(result);
        }
    }
}
Also used : Cleanup(lombok.Cleanup) Realm(io.realm.Realm)

Example 4 with Cleanup

use of lombok.Cleanup in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class RequestTask method doInBackground.

@Override
protected String doInBackground(String... commandString) {
    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch(mType) {
        // OCID upload request from "APPLICATION" drawer title
        case DBE_UPLOAD_REQUEST:
            try {
                @Cleanup Realm realm = Realm.getDefaultInstance();
                boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);
                log.info("OCID upload data prepared - " + String.valueOf(prepared));
                if (prepared) {
                    File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv");
                    publishProgress(25, 100);
                    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)).build();
                    Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv").post(requestBody).build();
                    publishProgress(60, 100);
                    Response response = okHttpClient.newCall(request).execute();
                    publishProgress(80, 100);
                    if (response != null) {
                        log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                        if (response.code() == 200) {
                            Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                            realm.executeTransaction(transaction);
                        }
                        publishProgress(95, 100);
                    }
                    return "Successful";
                } else {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                    return null;
                }
            // all caused by httpclient.execute(httppost);
            } catch (UnsupportedEncodingException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (FileNotFoundException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (IOException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (Exception e) {
                log.error("Upload OpenCellID data Exception", e);
            }
        // DOWNLOADING...
        case // OCID download request from "APPLICATION" drawer title
        DBE_DOWNLOAD_REQUEST:
            mTimeOut = REQUEST_TIMEOUT_MENU;
        case // OCID download request from "Antenna Map Viewer"
        DBE_DOWNLOAD_REQUEST_FROM_MAP:
            int count;
            try {
                long total;
                int progress = 0;
                String dirName = getOCDBDownloadDirectoryPath(mAppContext);
                File dir = new File(dirName);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, OCDB_File_Name);
                log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);
                Request request = new Request.Builder().url(commandString[0]).get().build();
                Response response;
                try {
                    // OCID's API can be slow. Give it up to a minute to do its job. Since this
                    // is a backgrounded task, it's ok to wait for a while.
                    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                    response = okHttpClient.newCall(request).execute();
                    // Restore back to default
                    okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
                } catch (SocketTimeoutException e) {
                    log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                    return "Timeout";
                }
                if (response.code() != 200) {
                    try {
                        String error = response.body().string();
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                        log.error("Download OCID data error: " + error);
                    } catch (Exception e) {
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage());
                        log.error("Download OCID exception: ", e);
                    }
                    return "Error";
                } else {
                    // This returns "-1" for streamed response (Chunked Transfer Encoding)
                    total = response.body().contentLength();
                    if (total == -1) {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                        // Let's set it arbitrarily to something other than "-1"
                        total = 1024;
                    } else {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                        // Let's show something!
                        publishProgress((int) (0.25 * total), (int) total);
                    }
                    FileOutputStream output = new FileOutputStream(file, false);
                    InputStream input = new BufferedInputStream(response.body().byteStream());
                    byte[] data = new byte[1024];
                    while ((count = input.read(data)) > 0) {
                        // writing data to file
                        output.write(data, 0, count);
                        progress += count;
                        publishProgress(progress, (int) total);
                    }
                    input.close();
                    // flushing output
                    output.flush();
                    output.close();
                }
                return "Successful";
            } catch (IOException e) {
                log.warn("Problem reading data from steam", e);
                return null;
            }
    }
    return null;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Cleanup(lombok.Cleanup) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.squareup.okhttp.Response) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) Realm(io.realm.Realm) File(java.io.File) RequestBody(com.squareup.okhttp.RequestBody)

Example 5 with Cleanup

use of lombok.Cleanup in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class RequestTask method onPostExecute.

/**
     * This is where we:
     * <ol>
     * <li>Check the success for OCID data download</li>
     * <li>call the updateOpenCellID() to populate the {@link com.secupwn.aimsicd.data.model.Import Import} realm</li>
     * <li>call the {@link RealmHelper#checkDBe()} to cleanup bad cells from imported data</li>
     * <li>present a failure/success toast message</li>
     * <li>set a shared preference to indicate that data has been downloaded:
     * {@code ocid_downloaded true}</li>
     * </ol>
     */
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    TinyDB tinydb = TinyDB.getInstance();
    @Cleanup Realm realm = Realm.getDefaultInstance();
    switch(mType) {
        case DBE_DOWNLOAD_REQUEST:
            // if `result` is null, it will evaluate to false, no need to check for null
            if ("Successful".equals(result)) {
                if (mDbAdapter.populateDBeImport(realm)) {
                    Helpers.msgShort(mAppContext, mAppContext.getString(R.string.opencellid_data_successfully_received));
                }
                realm.executeTransaction(mDbAdapter.checkDBe());
                tinydb.putBoolean("ocid_downloaded", true);
            } else if ("Timeout".equals(result)) {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_timed_out));
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.error_retrieving_opencellid_data));
            }
            break;
        case DBE_DOWNLOAD_REQUEST_FROM_MAP:
            if ("Successful".equals(result)) {
                if (mDbAdapter.populateDBeImport(realm)) {
                    Intent intent = new Intent(MapFragment.updateOpenCellIDMarkers);
                    LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
                    Helpers.msgShort(mAppContext, mAppContext.getString(R.string.opencellid_data_successfully_received_markers_updated));
                    realm.executeTransaction(mDbAdapter.checkDBe());
                    tinydb.putBoolean("ocid_downloaded", true);
                }
            } else if ("Timeout".equals(result)) {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_timed_out));
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.error_retrieving_opencellid_data));
            }
            showHideMapProgressBar(false);
            TinyDB.getInstance().putBoolean(TinyDbKeys.FINISHED_LOAD_IN_MAP, true);
            break;
        case DBE_UPLOAD_REQUEST:
            if ("Successful".equals(result)) {
                Helpers.msgShort(mAppContext, mAppContext.getString(R.string.uploaded_bts_data_successfully));
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.error_uploading_bts_data));
            }
            break;
    }
    if (mListener != null) {
        if ("Successful".equals(result)) {
            mListener.onAsyncTaskSucceeded();
        } else {
            mListener.onAsyncTaskFailed(result);
        }
    }
}
Also used : Intent(android.content.Intent) Cleanup(lombok.Cleanup) Realm(io.realm.Realm)

Aggregations

Cleanup (lombok.Cleanup)16 Realm (io.realm.Realm)13 SmsDetectionString (com.secupwn.aimsicd.data.model.SmsDetectionString)4 SmsData (com.secupwn.aimsicd.data.model.SmsData)3 IOException (java.io.IOException)3 BitmapDrawable (android.graphics.drawable.BitmapDrawable)2 Drawable (android.graphics.drawable.Drawable)2 CdmaCellLocation (android.telephony.cdma.CdmaCellLocation)2 GsmCellLocation (android.telephony.gsm.GsmCellLocation)2 Import (com.secupwn.aimsicd.data.model.Import)2 CellTowerMarker (com.secupwn.aimsicd.map.CellTowerMarker)2 MarkerData (com.secupwn.aimsicd.map.MarkerData)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 Date (java.util.Date)2 LinkedList (java.util.LinkedList)2 GeoPoint (org.osmdroid.util.GeoPoint)2 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1