Showing posts with label Hacking. Show all posts
Showing posts with label Hacking. Show all posts

Sunday, 10 September 2023

Unmasking the Threat: The Technical Anatomy of Keyloggers.

 In today's digital age, personal and sensitive information is constantly being transmitted through our devices. With the increasing reliance on computers and smartphones, the security of our data has become more important than ever. Unfortunately, there are malicious tools and software out there designed to steal this information, and one of the most notorious among them is the keylogger. In this blog post, we'll delve into the technical aspects of keyloggers, exploring how they work and the potential risks they pose.

What is a Keylogger?

A keylogger, short for "keystroke logger," is a type of malicious software or hardware device designed to covertly record every keystroke made on a computer or mobile device. These keystrokes can include usernames, passwords, credit card numbers, and other sensitive information. Keyloggers are often used by cybercriminals to steal personal information, compromise user accounts, or conduct espionage.

How Does a Keylogger Work Technically?

Keyloggers can be implemented in various ways, and their technical workings may differ depending on whether they are software-based or hardware-based. Let's explore both types:

Software-Based Keyloggers:

Installation: Software keyloggers are typically installed on a victim's device through malicious email attachments, infected software downloads, or compromised websites. They may also be bundled with other malware.

Execution: Once installed, the keylogger runs in the background, hidden from the user's view. It typically starts automatically with the operating system or may be triggered by specific events.

Keystroke Logging: Software keyloggers capture keystrokes by intercepting keyboard input. They can hook into the operating system's input events to record every keystroke made, regardless of the application or platform.

Data Storage: The recorded keystrokes are often stored in encrypted files or transmitted to a remote server controlled by the attacker. Advanced keyloggers may use techniques to evade detection by antivirus software.

Hardware-Based Keyloggers:

Physical Installation: Hardware keyloggers are physical devices that need to be physically connected between the keyboard and the computer. They are often disguised as connectors or adapters.

Keystroke Logging: Hardware keyloggers intercept keystrokes as they travel between the keyboard and the computer. They do not require any software installation and can capture keystrokes from any operating system or application.

Data Retrieval: To retrieve the recorded data, an attacker must physically access the hardware keylogger. This can be done by removing it from the victim's computer and extracting the stored data.

Risks Associated with Keyloggers:

Keyloggers pose significant risks to individuals, businesses, and organizations:

  • Privacy Invasion: Keyloggers can capture personal and sensitive information, leading to privacy breaches and identity theft.
  • Financial Loss: Stolen credit card numbers and login credentials can result in financial losses for victims.
  • Corporate Espionage: Keyloggers can be used by cybercriminals or competitors to steal business-critical information and trade secrets.
  • Legal Consequences: The use of keyloggers is illegal in many jurisdictions, and individuals caught using them may face criminal charges.

Protecting Against Keyloggers:

To protect yourself and your devices from keyloggers, consider the following precautions:

  1. Keep your software and operating systems up to date.
  2. Use strong, unique passwords for each online account.
  3. Install reputable antivirus and anti-malware software.
  4. Be cautious of suspicious email attachments and downloads.
  5. Avoid public computers for sensitive tasks.
  6. Physically inspect your devices for any suspicious hardware.
  7. Use two-factor authentication (2FA) whenever possible.

Conclusion

Keyloggers are a potent threat to digital security, capable of silently capturing sensitive information. Understanding how they work technically is essential for safeguarding your personal and financial data. By following best practices for cybersecurity and staying vigilant, you can reduce the risk of falling victim to keyloggers and other malicious software. Always prioritize security to keep your digital life safe from prying eyes and potential threats.

Monday, 28 August 2023

Unveiling the Threat Landscape: IoT Botnets and the Menace of DDoS Attacks.

 In today's interconnected world, the Internet of Things (IoT) has brought about transformative changes by connecting devices and systems like never before. However, with this wave of connectivity comes a darker side – the rise of IoT botnets and their potential to launch devastating Distributed Denial of Service (DDoS) attacks. In this blog, we delve into the intricacies of IoT botnets, their role in DDoS attacks, and the steps to mitigate these threats.

Understanding IoT Botnets

An IoT botnet is a network of compromised IoT devices, such as cameras, smart thermostats, and routers, that are infected with malware and controlled by a central command-and-control server. This control allows hackers to harness the collective power of these devices to carry out malicious activities, with DDoS attacks being one of the most common and concerning.

IoT botnets are particularly attractive to attackers due to several reasons:

Sheer Volume: The proliferation of IoT devices has resulted in an expansive attack surface. Hackers can enlist thousands or even millions of devices in their botnets, amplifying their attack capabilities.

Limited Security: Many IoT devices lack robust security measures. Default passwords, unpatched vulnerabilities, and weak security protocols make them easy targets for exploitation.

Always-On Nature: IoT devices are typically online 24/7, making them ideal for launching sustained attacks that can cripple target systems over an extended period.

The Role of IoT Botnets in DDoS Attacks

DDoS attacks are designed to overwhelm a target system or network with a flood of traffic, rendering it inaccessible to legitimate users. IoT botnets are increasingly being used to execute these attacks due to their significant computational power and bandwidth capacity. The basic working principle involves the following steps:

  • Compromising Devices: Hackers exploit vulnerabilities in IoT devices, gaining unauthorized access and infecting them with malware.
  • Building the Botnet: Once a few devices are compromised, the malware spreads across the IoT network, recruiting more devices into the botnet.
  • Command and Control: The attacker controls the botnet through a central server, issuing commands to coordinate the attack.
  • Launch of DDoS Attack: The compromised devices simultaneously flood the target with an overwhelming volume of traffic, causing it to become inaccessible.

Types of DDoS Attacks

IoT botnets can execute various types of DDoS attacks, including:

Volumetric Attacks: These flood the target with massive amounts of traffic, consuming network resources and causing congestion.

TCP/UDP Amplification Attacks: Attackers send small requests to publicly accessible servers using the victim's IP address as the source. These servers then respond with larger replies, overwhelming the target.

Application Layer Attacks: Targeting specific applications or services, these attacks exploit vulnerabilities to exhaust server resources.

Mitigating IoT Botnet Threats and DDoS Attacks

  • Security Measures for IoT Devices: Manufacturers should enforce strong security protocols, including unique passwords, regular software updates, and robust authentication mechanisms.
  • Network Segmentation: Isolating IoT devices from critical systems can prevent attackers from infiltrating sensitive networks.
  • Behavioral Anomaly Detection: Employ AI and machine learning to monitor device behavior and identify unusual patterns that may indicate a compromise.
  • Traffic Filtering and Scrubbing: Employ services that filter out malicious traffic before it reaches the target network.
  • Traffic Shaping: Implement rate limiting and traffic prioritization to manage and mitigate the impact of DDoS attacks.

Conclusion

The rise of IoT botnets and their potential to unleash destructive DDoS attacks poses a significant challenge to our increasingly connected world. As technology continues to evolve, so do the tactics of malicious actors. By understanding the mechanics of IoT botnets and their role in DDoS attacks, we can better prepare ourselves to safeguard our devices, networks, and critical infrastructure. Only through collaborative efforts between manufacturers, cybersecurity experts, and end-users can we effectively mitigate these threats and secure the promising future of the IoT landscape.

Sunday, 6 August 2023

Unlocking the Potential: Weighing the Pros and Cons of Jailbreaking or Rooting Your Mobile Device.

 In today's tech-savvy world, smartphones have become an indispensable part of our lives, offering a wide array of features and functionalities. However, some users seek even more control and customization over their devices, leading them to explore the world of jailbreaking (for iOS devices) or rooting (for Android devices). While these practices provide users with additional freedom, they also come with potential risks and drawbacks. In this blog, we'll explore the pros and cons of jailbreaking or rooting your mobile device, helping you make an informed decision.

What is Jailbreaking or Rooting?

Jailbreaking (for iOS devices) and rooting (for Android devices) are procedures that remove restrictions imposed by the operating system, granting users administrative access to the device's file system and allowing them to run custom software or modify system settings. This process essentially liberates your device from the manufacturer's limitations, giving you greater control over its functionality.

Pros of Jailbreaking or Rooting

  • Enhanced Customization: Jailbreaking or rooting grants users access to the device's core system files, enabling them to customize their devices extensively. Users can install themes, custom fonts, and tweak the user interface to their liking, giving their smartphones a unique and personalized look and feel.
  • Access to Unofficial Apps: The official app stores, such as Apple's App Store and Google Play Store, have strict guidelines that sometimes lead to the rejection of certain apps. By jailbreaking or rooting, users can access third-party app repositories, offering a wide range of apps and tweaks not available in official stores. This opens up a world of possibilities and experimentation.
  • Removal of Bloatware: Manufacturers often pre-install unwanted apps, commonly known as bloatware, on mobile devices. Jailbreaking or rooting allows users to uninstall or disable these pre-installed applications, freeing up valuable storage space and potentially improving device performance.
  • System Tweaks and Improvements: With jailbreaking or rooting, users can apply system-level tweaks and improvements that can optimize device performance, enhance battery life, and even overclock the CPU for better processing power.
  • Advanced Backup and Restore: Jailbreaking or rooting provides users with the ability to create full system backups, enabling easy restoration in case of software issues or data loss. This is especially beneficial for advanced users who frequently experiment with their devices.

Cons of Jailbreaking or Rooting

  • Voiding Warranty and Security Risks: Jailbreaking or rooting your device typically voids the warranty provided by the manufacturer, leaving users with no official support for hardware and software issues. Additionally, by accessing core system files, users expose their devices to potential security risks, including malware and unauthorized access.
  • Stability and Performance Issues: Modifying the device's operating system can lead to stability and performance problems. Users might encounter frequent crashes, freezes, or battery drainage, especially if they install poorly optimized or incompatible software.
  • Software Incompatibility: As manufacturers continuously update their devices and operating systems, jailbreaking or rooting might make your device incompatible with the latest software updates. This means you could miss out on crucial security patches and exciting new features.
  • Reduced Device Lifespan: Due to potential software complications and increased vulnerability to malware, jailbroken or rooted devices might experience a reduced lifespan. Constant tweaking and experimentation can accelerate wear and tear on the hardware.
  • Legal Implications: In some regions, jailbreaking or rooting your mobile device might be considered illegal or against the terms of service of the manufacturer or carrier. Users should be aware of the legal implications in their specific jurisdiction before attempting such modifications.

Precautions and Steps to Jailbreak or Root:
  • Backup: Before attempting any modification, back up your device to safeguard your data.
  • Research: Find a reputable and reliable guide specific to your device and software version. Follow the steps meticulously and ensure you understand each action you take.
  • Use Trusted Sources: Download jailbreak or rooting tools from trustworthy sources to reduce the risk of malware infection.
  • Security Software: Install reputable security software to protect your device from potential threats.
Post-Jailbreak/Rooting:
  • Be Selective: Exercise caution when installing third-party apps and tweaks. Stick to trusted sources to minimize security risks.
  • Regular Updates: Keep your device's software up-to-date, even if it means losing root access temporarily. This will ensure you have the latest security patches.
  • Revoke Root Access: If needed, you can reverse the jailbreak or root process to restore your device's original state.

Conclusion

Jailbreaking or rooting your mobile device can provide a thrilling and liberating experience, granting you unprecedented control over your smartphone. Enhanced customization, access to unofficial apps, and the ability to remove bloatware are alluring benefits that many users find attractive. However, the risks associated with voiding the warranty, security concerns, and potential software issues cannot be ignored.

Ultimately, the decision to jailbreak or root your mobile device should be made with caution and careful consideration of the potential consequences. If you're an advanced user who values customization and is willing to take on the associated risks, proceed with care and be mindful of the potential drawbacks. For the average user, sticking with the official operating system is likely the safer and more convenient option. Always remember that the responsibility lies with the user, and staying informed about the risks and benefits is crucial in making a well-informed decision for your mobile device.

Wednesday, 15 March 2023

Mobile Development: Safeguarding Against Hacking with Advanced Security Measures.

 In the rapidly evolving landscape of mobile development, security and protection against hacking have become paramount concerns. As mobile devices store and transmit vast amounts of sensitive user data, developers must implement robust security measures to thwart potential cyber threats. In this technical blog post, we will delve into the intricate aspects of mobile app security, exploring advanced techniques to fortify applications against hacking attempts.

Understanding Mobile Threats and Vulnerabilities:

To effectively counter hacking attempts, mobile developers must comprehend the diverse range of threats and vulnerabilities present in the mobile ecosystem. These include but are not limited to malware attacks, SQL injection, cross-site scripting (XSS), session hijacking, and insecure data storage. Staying updated on emerging threat vectors and common vulnerabilities is essential for devising appropriate security strategies.

Secure Coding Techniques:

Secure coding practices form the foundation of robust mobile app security. Developers must adhere to industry-standard secure coding guidelines, such as the OWASP Mobile Top 10, to prevent common attack vectors. Key practices include input validation, output encoding, parameterized queries, and secure session management. By utilizing cryptographic algorithms for data encryption and hashing, developers can protect sensitive data from unauthorized access.

Secure Authentication and Authorization Mechanisms:

Authentication and authorization mechanisms play a critical role in mobile app security. Developers should adopt strong authentication methods, such as OAuth 2.0 or OpenID Connect, along with secure password storage techniques like salted hashes. Implementing granular access control mechanisms and token-based authentication can prevent unauthorized access and session hijacking attacks.

Data Encryption and Secure Data Transmission:

To safeguard sensitive data at rest and in transit, mobile developers must employ robust encryption techniques. Encryption algorithms like AES (Advanced Encryption Standard) and RSA (Rivest-Shamir-Adleman) ensure data confidentiality. Additionally, secure data transmission can be achieved by implementing transport layer security (TLS) protocols, including SSL/TLS certificate pinning to protect against man-in-the-middle attacks.

Secure Storage of User Data:

Mobile applications often store user data locally on the device. Developers must ensure that this data is securely stored to prevent unauthorized access. Leveraging secure storage techniques like SQLCipher or encrypted key-value stores adds an additional layer of protection. Moreover, sensitive information, such as authentication tokens or API keys, should be stored in secure hardware containers like the Android KeyStore or Apple's Secure Enclave.

Regular Security Assessments and Code Reviews:

Periodic security assessments, including penetration testing and code reviews, are indispensable for identifying vulnerabilities in mobile applications. Conducting dynamic analysis, examining the application's attack surface, and simulating real-world attack scenarios help uncover potential weaknesses. Swift remediation of identified issues and the integration of security patches are crucial to maintaining a robust security posture.

Runtime Application Self-Protection (RASP):

Runtime Application Self-Protection (RASP) solutions can actively monitor and protect mobile apps from potential attacks. RASP tools employ techniques such as code instrumentation, behavior monitoring, and anomaly detection to detect and mitigate runtime threats. Integrating RASP into mobile apps can help detect and respond to attacks in real-time, enhancing overall security.

Secure Backend Infrastructure:

Securing the backend infrastructure is as important as securing the mobile app itself. Developers must ensure the use of secure APIs, validate and sanitize inputs, and employ strong access controls. Implementing Web Application Firewalls (WAFs), Intrusion Detection Systems (IDS), and Intrusion Prevention Systems (IPS) can help protect against server-side attacks and unauthorized access to backend resources.

Conclusion:

Building secure mobile applications requires a thorough understanding of the technical aspects of security and hacking. By following secure coding practices, implementing encryption and authentication mechanisms, securing data transmission, and conducting regular security assessments, developers can significantly mitigate risks. By prioritizing mobile app security from the development stage to ongoing maintenance, developers can build trustworthy applications that protect user data and provide a secure user experience.

Friday, 1 September 2017

HB Blog 143: Implementing Video Call using Sinch Android SDK.

Introduction

The Sinch SDK is a product that makes adding voice calling and/or instant messaging to mobile apps easy. It handles all the complexity of signalling and audio management while providing you the freedom to create a stunning user interface.
Refer the below link for complete sample code:-

Download Sample Code

First time setup

Below is a step-by-step guide on setting up the Sinch SDK for the first time.

Register an Application
1.    Register a Sinch Developer account at http://www.sinch.com/signup.
2.    Setup a new Application using the Dashboard where you can then obtain an Application Key and an Application Secret.

Download
The Sinch SDK can be downloaded at www.sinch.com/download/. It contains: the library aar, this user guide, reference documentation, and sample apps for calling and instant messaging.

Add the Sinch library
The Sinch SDK library is distributed in AAR format. To use it in your project choose File -> New -> New Module -> Import .JAR/.AAR Package option

Permissions
A minimum set of permissions are needed for the app to use the Sinch SDK. These are specified in the AndroidManifest.xml file. If the calling functionality will be used, all five permissions listed here are needed. However, if the calling functionality isn’t used, the last three (RECORD_AUDIO, MODIFY_AUDIO_SETTINGS and READ_PHONE_STATE) can be omitted.
1
2
3
4
5
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Note: By default, the Sinch SDK hangs up any Sinch call if the regular phone app has an active call. This functionality requires the permission READ_PHONE_STATE. However, if this default functionality isn’t wanted, turn it off by calling sinchClient.getCallClient().setRespectNativeCalls(false); and the permission READ_PHONE_STATE is not needed.

Sinch client

The SinchClient is the Sinch SDK entry point. It is used to configure the user’s and device’s capabilities, as well as to provide access to feature classes such as the CallClient, MessageClient and AudioController.

Create a SinchClient
1
2
3
4
5
6
7
8
// Instantiate a SinchClient using the SinchClientBuilder.
android.content.Context context = this.getApplicationContext();
SinchClient sinchClient = Sinch.getSinchClientBuilder().context(context)
.applicationKey("<application key>")
.applicationSecret("<application secret>")
.environmentHost("sandbox.sinch.com")
.userId("<user id>")
.build();
The Application Key and Application Secret are obtained from the Sinch Developer Dashboard. The User ID should uniquely identify the user on the particular device.
Note: All listener callbacks emitted from the Sinch SDK are invoked on the same thread that the call to SinchClientBuilder.build is made on. If the invoking thread is not the main-thread, it needs to have an associated Looper.

Start the Sinch client
Before starting the client, add a client listener
1
2
3
4
5
6
7
8
sinchClient.addSinchClientListener(new SinchClientListener() {
public void onClientStarted(SinchClient client) { }
public void onClientStopped(SinchClient client) { }
public void onClientFailed(SinchClient client, SinchError error) { }
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration registrationCallback) { }
public void onLogMessage(int level, String area, String message) { }
});
sinchClient.start();
Terminate the Sinch client
When the app is done using the SinchClient, it should be stopped. If the client is currently listening for incoming events, it needs to stop listening as well. After terminate is called, any object retrieved directly from the client object (that is, CallClient, MessageClient, and AudioController) is considered invalid.
Terminating the client:
1.    sinchClient.stopListeningOnActiveConnection();
2.    sinchClient.terminate();

Setting up a video call
Just like audio calls, video calls are placed through the CallClient and events are received using the CallClientListener. The call client is owned by the SinchClient and accessed using sinchClient.getCallClient(). Calling is not enabled by default. 

Showing the video streams
Once you have created a VideoCallListener and added it to a call, the onVideoTrackAdded() method will be called.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Override
public void onVideoTrackAdded(Call call) {
// Get a reference to your SinchClient, in the samples this is done through the service interface:
VideoController vc = getSinchServiceInterface().getVideoController();
View myPreview = vc.getLocalView();
View remoteView = vc.getRemoteView();
// Add the views to your view hierarchy
}

After the call has ended, dont forget to remove the views from your view hierarchy again.
@Override
public void onCallEnded(Call call) {
// Remove Sinch video views from your view hierarchy
}
Pausing video stream
To pause the local video stream, use the pauseVideo() method on the call.
1.        // User pause the video stream
2.        call.pauseVideo();

Resuming video stream
To resume the local video stream, use the resumeVideo() method on the call.
1.       // User resumes the video stream
2.       call.resumeVideo();

Pausing video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackPaused() method will be called when the remote user pause the video stream.
1.       @Override
2.       public void onVideoTrackPaused(Call call) {
3.            // Implement what to be done when remote user pause video stream.
4.       }

Resuming video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackResumed() method will be called when the remote user resumes the video stream..
1.       @Override
2.       public void onVideoTrackResumed(Call call) {
3.            // Implement what to be done when remote user resumes video stream.
4.       }

Video content fitting and aspect ratio
How the remote video stream is fitted into a view can be controller by the setResizeBehaviour() method with possible arguments VideoScalingType.ASPECT_FIT, VideoScalingType.ASPECT_FILL and VideoScalingType.ASPECT_BALANCED. The local preview will always use VideoScalingType.ASPECT_FIT.

Switching capturing device
The capturing device can be switched using videoController.setCaptureDevicePosition(int facing) with possible values Camera.CameraInfo.CAMERA_FACING_FRONT and Camera.CameraInfo.CAMERA_FACING_BACK. Use videoController.toggleCaptureDevicePosition() to alternate the two.

Accessing video frames of the remote streams
The Sinch SDK can provide access to raw video frames via a callback function. This callback can be used to achieve rich functionality such as applying filters, adding stickers to the video frames, or saving the video frame as an image.
Your video frame handler needs to implement VideoFrameListener interface by implementing the onFrame() callback. Note that it is important to explicitly release the video frame by calling release().
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Example:
import com.sinch.android.rtc.video.VideoFrame;
import com.sinch.android.rtc.video.VideoFrameListener;
public class YourVideoFrameHandler implements VideoFrameListener {
public synchronized void onFrame(String callId, VideoFrame videoFrame) {
// Process videoFrame
videoFrame.release(); // Release videoFrame}}

Use setVideoFrameListener() to register your video frame handler as the callback to receive video frames.

Example:
YourVideoFrameHandler videoFrameHandler = new YourVideoFrameHandler();
VideoController vc = getSinchServiceInterface().getVideoController();
vc.setVideoFrameListener(videoFrameHandler);

Tuesday, 15 August 2017

HB Blog 142: Android Configure Using Build Variants - Part 2.

Hello friends, Thanks for reading my previous post on HB Blog 141: Android Configure Build Variants - Part 1.
This post will show you how you can configure build variants to create different versions of your app from a single project, and how to properly manage your dependencies and signing configurations.
Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Each build variant represents a different version of your app that you can build. For example, you might want to build one version of your app that's free, with a limited set of content, and another paid version that includes more. You can also build different versions of your app that target different devices, based on API level or other device variations.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.harshalbenake.buildvariant"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }

    /**
     * The following sample specifies an applicationIdSuffix for the debug build type,
     * and configures a "jnidebug" build type that is initialized using settings from
     * the debug build type.
     */
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            applicationIdSuffix ".debug"
        }

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */
        jnidebug {
            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }

    // Specifies the flavor dimensions you want to use. The order in which you
    // list each dimension determines its priority, from highest to lowest,
    // when Gradle merges variant sources and configurations. You must assign
    // each product flavor you configure to one of the flavor dimensions.
    flavorDimensions "api", "mode"

    /**
     * The following code sample creates "demo" and "full" product flavors
     * which provide their own applicationIdSuffix and versionNameSuffix.
     * The following code sample uses the flavorDimensions property
     * to create a "mode" flavor dimension to group the "full" and "demo" product flavors,
     * and an "api" flavor dimension to group product flavor configurations based on API level
     */
    productFlavors {
        demo {
            applicationIdSuffix ".demo"
            versionNameSuffix "-demo"
            // Assigns this product flavor to the "mode" flavor dimension.
            dimension "mode"
            resValue "string", "app_name", "HB Demo"
        }
        full {
            applicationIdSuffix ".full"
            versionNameSuffix "-full"
            dimension "mode"
            resValue "string", "app_name", "HB Full"
        }

        // Configurations in the "api" product flavors override those in "mode"
        // flavors and the defaultConfig block. Gradle determines the priority
        // between flavor dimensions based on the order in which they appear next
        // to the flavorDimensions property above--the first dimension has a higher
        // priority than the second, and so on.
        minApi24 {
            dimension "api"
            minSdkVersion '24'
            // To ensure the target device receives the version of the app with
            // the highest compatible API level, assign version codes in increasing
            // value with API level. To learn more about assigning version codes to
            // support app updates and uploading to Google Play, read Multiple APK Support
            versionCode 30000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi24"
        }

        minApi23 {
            dimension "api"
            minSdkVersion '23'
            versionCode 20000  + android.defaultConfig.versionCode
            versionNameSuffix "-minApi23"
        }

        minApi21 {
            dimension "api"
            minSdkVersion '21'
            versionCode 10000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi21"
        }
}

    /**
     * Using the build configuration from the previous section as an example,
     * suppose you plan to support only API levels 23 and higher for the demo version of the app.
     * You can use the variantFilter block to filter out all build variant configurations that
     * combine the "minApi21" and "demo" product flavors.
     */
    variantFilter { variant ->
        def names = variant.flavors*.name
        // To check for a certain build type, use variant.buildType.name == "<buildType>"
        if (names.contains("minApi23") && names.contains("full")) {
            // Gradle ignores any variants that satisfy the conditions above.
            setIgnore(true)
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
}

Tuesday, 1 August 2017

HB Blog 141: Android Configure Using Build Variants - Part 1.

The Android build system compiles app resources and source code, and packages them into an Android Application Package (APK), that you can test, deploy, sign, and distribute.  Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process, while allowing you to define flexible custom build configurations.
 The build process for a typical Android app module follows these general steps:
  1.     The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  2.     The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  3.     Before generating your final APK, the packager uses the zipalign tool to optimize your app to use less memory when running on a device.
At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Gradle and the Android plugin help you configure the following aspects of your build:

 Build Types :-
    Build types define certain properties that Gradle uses when building and packaging your app, and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default.

 Product Flavors :-
    Product flavors represent different versions of your app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually.

 Build Variants :-
    A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants.

 Manifest Entries :-
    You can specify values for some properties of the manifest file in the build variant configuration. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version.

 Dependencies :-
    The build system manages project dependencies from your local filesystem and from remote repositories. This prevents you from having to manually search, download, and copy binary packages of your dependencies into your project directory.

 Signing :-
    The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate using known credentials to avoid a password prompt at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build.
For more details, visit my post, HB Blog 120: How To Sign Your APKs Using Android Studio.

 ProGuard :-
    The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.
For more details, visit my post, HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

 Multiple APK Support :-
    The build system enables you to automatically build different APKs that each contain only the code and resources needed for a specific screen density or Application Binary Interface (ABI).

Custom Build Configurations :-

Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM).

When starting a new project, Android Studio automatically creates some of these files for you, as shown in below image, and populates them based on sensible defaults.
 ......Continue, to read more on Build Variant gradle in my next post, Android Configure Using Build Variants - Part 2.

Saturday, 1 July 2017

HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.

ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
1. Shrinking – detects and removes unused classes, fields, methods, and attributes.
2. Optimization – analyzes and optimizes the bytecode of the methods.
3. Obfuscation – renames the remaining classes, fields, and methods using short meaningless names.

How to Enable Proguard in Android Studio ?
  • In Android Studio project, the minifyEnabled  property in the build.gradle file enables and disables Proguard for release builds.
  • The minifyEnabled property is part of the buildTypes release block that controls the settings applied to release builds.
  • The getDefaultProguardFile(‘proguard-android.txt’) method obtains the default Proguard settings from the Android SDK tools/proguard folder.
  • Android Studio adds the proguard-rules.pro file at the root of the module, which helps to add custom Proguard rules.

Wednesday, 1 March 2017

HB Blog 130: How To Scan Network With Nmap GUI.

Nmap is popular network scanner software that can actively probe a particular host or a network to infer in-depth information about them. Nmap can conduct host discovery, service detection, OS version identification, port scanning, network stack fingerprinting, etc. It will help you to discover hosts, protocols, open ports, services and its configuration and vulnerabilities on networks. While Nmap itself is a command-line utility, you can run it along with its GUI front-end called Zenmap. Network Mapper is an Android frontend for well known Nmap scanner. Frontend will help you to download and install Nmap as well as use it. Frontend supports all known Android architectures: arm, mips and x86. Nmap binaries are transferred using HTTPS by default.

In this tutorial, I will describe how to scan particular hosts or networks by using Nmap GUI.
The following screenshot shows the main window of Zenmap.
Scan Particular Host(s):-
Using Zenmap interface, you can probe a particular host. Fill in the IP address or host name of a destination host in "Target" field, and choose a desired scan profile from "Profile" drop down menu. Then, click on "Scan" button. For multiple hosts, you can specify them in a comma-separated list.
To check the detailed system information of a particular host after scanning, highlight a host in the left panel, and click on "Host Details" tab on the right panel.
To view available services and open ports of a host, click on "Ports / Hosts" tab.
Scan an Entire Network:-
Zenmap can also probe an entire local network by specifying an address prefix (e.g., 192.168.1.0/24) in the "Target" field.
Once network scanning is completed, you can view the topology of discovered hosts by clicking on "Topology" tab.
To view a list of available services, click on "Services" button on the left panel. You can see a list of all discovered services and their associated hosts, as shown below.

Tuesday, 1 November 2016

HB Blog 122: Android Tools For Analyzing RAM Usage.

Random-access memory (RAM) is a valuable resource in any software development environment, but it's even more valuable on a mobile operating system where physical memory is often constrained. Although both the Android Runtime (ART) and Dalvik virtual machine perform routine garbage collection, this does not mean you can ignore when and where your app allocates and releases memory. You still need to avoid introducing memory leaks, usually caused by holding onto object references in static member variables, and release any Reference objects at the appropriate time as defined by lifecycle callbacks.
Tools for analyzing RAM usage :-
Before you can fix the memory usage problems in your app, you first need to find them. Android Studio and the Android SDK include several tools for analyzing memory usage in your app,

  1. The Device Monitor has a Dalvik Debug Monitor Server (DDMS) tool that allows you to inspect memory allocation within your app process. You can use this information to understand how your app uses memory overall. For example, you can force a garbage collection event and then view the types of objects that remain in memory. You can use this information to identify operations or actions within your app that allocate or leave excessive amounts of objects in memory. 
  2. The Memory Monitor in Android Studio shows you how your app allocates memory over the course of a single session. The tool shows a graph of available and allocated Java memory over time, including garbage collection events. You can also initiate garbage collection events and take a snapshot of the Java heap while your app runs. The output from the Memory Monitor tool can help you identify points when your app experiences excessive garbage collection events, leading to app slowness.
  3. Garbage collection events also show up in the Traceview viewer. Traceview allows you to view trace log files as both a timeline and as a profile of what happened within a method. You can use this tool to determine what code was executing when a garbage collection event occurred. 
  4. The Allocation Tracker tool in Android Studio gives you a detailed look at how your app allocates memory. The Allocation Tracker records an app's memory allocations and lists all allocated objects within the profiling snapshot. You can use this tool to track down parts of your code that allocate too many objects.

Saturday, 1 October 2016

HB Blog 120: How To Sign Your APKs Using Android Studio.

                 Android is open source but, it has security checks at its own level too. It requires that all APKs be digitally signed with a certificate before they can be installed. This tutorial describes how to sign your APKs using Android Studio.
A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.
When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a "fingerprint" that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author.
A keystore is a binary file that contains one or more private keys. When you sign an APK for release using Android Studio, you can choose to generate a new keystore and private key or use a keystore and private key you already have. You should choose a strong password for your keystore, and a separate strong password for each private key stored in the keystore. You must keep your keystore in a safe and secure place. You must use the same certificate throughout the lifespan of your app in order for users to be able to install new versions as updates to the app.
You can use Android Studio to manually generate signed APKs, either one at a time, or for multiple build variants at once. Instead of manually signing APKs, you can also configure your Gradle build settings to handle signing automatically during the build process.

To sign your APK for release in Android Studio, follow these steps:
  1. In the menu bar, click Build > Generate Signed APK.
  2. Select the module you would like to release from the drop down, and click Next.
  3. If you already have a keystore, go to step 5. If you want to create a new keystore, click Create new.
  4. On the New Key Store window, provide the following information for your keystore and key, as shown below,
    Keystore
  •         Key store path: Select the location where your keystore should be created.
  •         Password: Create and confirm a secure password for your keystore.
    Key
  •         Alias: Enter an identifying name for your key.
  •         Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
  •         Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
  •         Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.
Once you complete the form, click OK.
    5. On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. (If you created your keystore in the last step, these fields are already populated for you.) Then click Next.
    6. On the next window, select a destination for the signed APK(s), select the build type, (if applicable) choose the product flavor(s), and click Finish.
When the process completes, you will find your signed APK in the destination folder you selected above. You may now distribute your signed APK through an app marketplace like the Google Play Store, or using the mechanism of your choice.  For more about how to publish your signed APK to the Google Play Store, you can follow my blog,  How To Publish Android Application On Google Play.

Friday, 2 September 2016

HB Blog 118: Cell Broadcast - The Mobile Technology For Mass Message Broadcast.

Cell Broadcast (CB) is a mobile technology that allows messages (currently of up to 15 pages of up to 93 characters) to be broadcast to all mobile handsets and similar devices within a designated geographical area. The broadcast range can be varied, from a single cell to the entire network.
This technology is used in deploying location-based subscriber services, such as regional auctions, local weather, traffic conditions and 'nearest' services (like requesting the nearest service station or restaurant).
It is designed for simultaneous delivery of messages to multiple users in a specified area. Whereas the Short Message Service (SMS) is a one-to-one and one-to-a-few service, It is one-to-many geographically focused service.
It enables messages to be communicated to multiple mobile phone customers who are located within a given part of its network coverage area at the time the message is broadcast. Cell Broadcast is more akin to other mass distribution media such as teletext or Radio Data System (RDS).
It  is a technology that allows a text or binary message to be defined and distributed to all mobile terminals connected to a set of cells. Whereas SMS messages are sent point-to-point, Cell Broadcast (SMS-CB) messages are sent point-to-area. This means that one SMS-CB message can reach a huge number of terminals at once. In other words, SMS-CB messages are directed to radio cells, rather than to a specific terminal. SMS-CB is an unconfirmed push service, meaning that the originator of the message does not know who has received the message, allowing for services based on anonymity.

A Cell Broadcast Entity (CBE) is a multi-user front-end that allows the definition and control of SMS-CB messages. A CBE can be located at the site of a content provider. At the site of the operator a so-called Cell Broadcast Centre (CBC) is located. The CBC is the heart of the Cell Broadcast System and acts as a server for all CBE clients. It takes care of the administration of all SMS-CB messages it receives from the CBEs and does the communication towards the GSM network. The GSM network itself takes care of delivering the SMS-CB messages to the mobile terminals.
Cell Broadcast can be used for a number of different services and has been de-ployed by several network operators.

Early Warning System (EWS) for citizen alert
Cell Broadcast on mobile telephones can be used for Early Warning Systems (EWS) by Governments. A few countries in the world have already adopted this technique, in addition to older and already existing forms of communication like siren, or radio and TV. The advantage of this system is that it allows sending messages without having to know the phone numbers of the users in the region. Instead of sending a message to a specific known mobile phone you can send a text to all mobile phones in a specific zone. Mass communication, very fast, in case it really matters.

Advertising
Retail outlets in certain areas would be interested in sending customers and potential customers information about special offers and attractions such as sales, special offers, extended opening times and so on. Shopping centers, exhibition halls, airports and sports stadiums are the kinds of location that could be targeted for Cell Broadcast based services.

Information Services
Cell Broadcast is ideal for delivering local or regional information which is suited to all the people in that area, rather than just one or a few people. Examples include hazard warnings, cinema programs, local weather, flight or bus delays, tourist information, parking and traffic information. Cell Broadcast can also be used for managing and communicating with a remote but local team such as emergency services or airport staff. The emergency services could send an encrypted message out to all officers or other staff in a certain area to respond to an incident. This is particularly useful for standby workers who only need to be called in and present in a certain place when certain events occur.

SMS versus Cell Broadcast: -

Short Message Service (SMS)
Characteristic
Cell Broadcast (CELL BROADCAST)
Messages sent point-to-point
Transmission type
Messages sent point-to-area
Required. Requires specific phone numbers to be known
Mobile Number dependency
Independent. Does not require phone numbers to be known
No. Only pre-registered numbers will be notified; message will be received regardless of actual location
Location based targeting
Yes. All phones within a targeted geographical area (cells) will be notified.
Static messages will be sent to pre-registered numbers.
Message type
Location specific. Tailored messages can be sent to different areas.
Direct. Users can receive messages and respond directly to the sender via SMS.
Bi-directionality
Indirect. The message should contain a URL or number to reply.
Subject to network congestion. Delivery is queued. Congestion can occur
Congestion and delay
CELL BROADCAST is always available.
140-160 characters. Longer 'concatenated' messages are supported.
Message length
93 characters. Longer 'multiple page’ messages are supported.
Poor authenticity. The source of the message cannot be verified.
Security
Good security. Only the mobile operator can broadcast messages.
No barring.
Service barring
Yes. Users can turn off CELL BROADCAST reception or a specific channel.
By default. When phone is turned on messages can be received.
Reception
Requires action. CELL BROADCAST needs to be turned on in order to receive messages.
Yes. Senders can request delivery confirmation.
Delivery confirmation
No. Confirmation of delivery to the handset is not available, however actual broadcast in the network is.
No repetition rate.
Repetition rate
Yes. Can be repeated between 2 seconds and 32 minutes.
No. Identical to all receivers.
Language selection
Yes. Messages can be broadcasted in subscriber’s preferred language
Yes.
Message storage
Handset dependant.