Manhole is an in-process service, that will accept UNIX domain socket connections and present the stack traces for all threads and an interactive prompt.
Using it we can access and modify objects or definition in the running application, like change or add the method in any class, change the definition of any method of class or module.
This allows us to make modifications in running an application without restarting the application, it makes work easy like debugging the application, you are able to check the values of the object while the program is running.
How to configure it?
from twisted.internet import reactor
from twisted.conch import manhole, manhole_ssh
from twisted.conch.ssh.keys import Key
from twisted.cred import portal, checkers
DATA = {"Service": "Manhole"}
def get_manhole_factory(namespace, **passwords):
def get_manhole(arg):
return manhole.ColoredManhole(namespace)
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = get_manhole
p = portal.Portal(realm)
p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
f = manhole_ssh.ConchFactory(p)
f.publicKeys = {"ssh-rsa": Key.fromFile("keys/manhole.pub")}
f.privateKeys = {"ssh-rsa": Key.fromFile("keys/manhole")}
return f
reactor.listenTCP(2222, get_manhole_factory(globals(), admin='admin'))
reactor.run()
Once you run above snippet, the service will start on TCP port 2222.
You need to use SSH command to get login into the service.
a port scanner is an application designed to probe a server or host for open ports. Such an application may be used by administrators to verify the security policies of their networks and by attackers to identify network services running on a host and exploit vulnerabilities.
port-scanner.py
#!/usr/bin/env python2
from socket import *
if __name__ == '__main__':
target = raw_input('Enter host to scan: ')
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
#scan reserved ports
for i in range(20, 1025):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i))
if(result == 0) :
print 'Port %d: OPEN' % (i,)
s.close()
SSH is typically used to log into a remote machine and execute commands, but it also supports tunneling, forwarding TCP ports and X11 connections.
What is SSH Tunneling?
A tunneling protocol may, for example, allow a foreign protocol to run over a network that does not support that particular protocol, such as running IPv6 over IPv4.
SSH tunneling is a method of transporting arbitrary networking data over an encrypted SSH connection. It can be used to add encryption to legacy applications. … It also provides a way to secure the data traffic of any given application using port forwarding, basically tunneling any TCP/IP port over SSH.
sshuttle
sshuttle is not exactly a VPN, and not exactly port forwarding. It’s kind of both, and kind of neither.
It’s like a VPN, since it can forward every port on an entire network, not just ports you specify. Conveniently, it lets you use the “real” IP addresses of each host rather than faking port numbers on localhost.
On the other hand, the way it works is more like ssh port forwarding than a VPN. Normally, a VPN forwards your data one packet at a time, and doesn’t care about individual connections; ie. it’s “stateless” with respect to the traffic. sshuttle is the opposite of stateless; it tracks every single connection.
Installation
“` sudo pip install sshuttle“`
Example
“`$ sshuttle –dns -v -r <remote-host> 0/0“`
* This will forward all connections including DNS requests…
Usage
usage: sshuttle [-l [ip:]port] [-r [user@]sshserver[:port]] <subnets...>
positional arguments:
IP/MASK[:PORT[-PORT]]...
capture and forward traffic to these subnets
(whitespace separated)
optional arguments:
-h, --help show this help message and exit
-l [IP:]PORT, --listen [IP:]PORT
transproxy to this ip address and port number
-H, --auto-hosts continuously scan for remote hostnames and update
local /etc/hosts as they are found
-N, --auto-nets automatically determine subnets to route
--dns capture local DNS requests and forward to the remote
DNS server
--ns-hosts IP[,IP] capture and forward DNS requests made to the following
servers
--to-ns IP[:PORT] the DNS server to forward requests to; defaults to
servers in /etc/resolv.conf on remote side if not
given.
--method TYPE auto, nat, nft, tproxy, pf, ipfw
--python PATH path to python interpreter on the remote server
-r [USERNAME@]ADDR[:PORT], --remote [USERNAME@]ADDR[:PORT]
ssh hostname (and optional username) of remote
sshuttle server
-x IP/MASK[:PORT[-PORT]], --exclude IP/MASK[:PORT[-PORT]]
exclude this subnet (can be used more than once)
-X PATH, --exclude-from PATH
exclude the subnets in a file (whitespace separated)
-v, --verbose increase debug message verbosity
-V, --version print the sshuttle version number and exit
-e CMD, --ssh-cmd CMD
the command to use to connect to the remote [ssh]
--seed-hosts HOSTNAME[,HOSTNAME]
comma-separated list of hostnames for initial scan
(may be used with or without --auto-hosts)
--no-latency-control sacrifice latency to improve bandwidth benchmarks
--wrap NUM restart counting channel numbers after this number
(for testing)
--disable-ipv6 disable IPv6 support
-D, --daemon run in the background as a daemon
-s PATH, --subnets PATH
file where the subnets are stored, instead of on the
command line
--syslog send log messages to syslog (default if you use
--daemon)
--pidfile PATH pidfile name (only if using --daemon) [./sshuttle.pid]
--user USER apply all the rules only to this linux user
--firewall (internal use only)
--hostwatch (internal use only)
--no-sudo-pythonpath do not set PYTHONPATH when invoking sudo
Spinners provide a quick way to select one value from a set then we called it a single selector. A spinner shows its currently selected value from set. In the default state, it shows 0 index value from a set. Touching the spinner displays a dropdown menu or dialog with all other available values in the set, So we can be called it a dropdown.
Dropdown
Let’s check, how we can use it in an application.
Spinner integration has 3 key classes:-
1. Spinner
2. Spinner Adapter
3. Spinner OnItemSelectedListener
So we will discuss above these classes also, with integration. You can add a spinner to your layout XML file. You can use the below sample code –
Spinner Adapter uses for bind between data set and spinner widget and it manages view for the spinner row item. We can use data as an array of string. See sample code –
Above string array, we will use for the display. So now we need to get reference Spinner which we defined in the XML file. We can use the below sample code –
So now we need to set values in ArrayAdapter. and We set this ArrayAdapter in Spinner. Use below code –
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
// set Adapter
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. for manage event, we can use OnItemSelectedListener in the Spinner. Sample code –
//Register a callback to be invoked when an item in this AdapterView has been selected
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
onItemSelected gives us a selected position of the spinner.
AndroidX is an open-source project by Google that provides a major improvement to the original Android Support Library. AndroidX is replaced the Support Library. Like support library, Google keeps AndroidX is independently from the Android OS and provides backward-compatibility across Android releases. AndroidX package structure is to encourage smaller and more focused libraries.
AndroidX replaces the original support library APIs with packages in the androidx namespace. Only the package and import names changed. Class, method, and field names did not change in migration.
Example:-
android.support.v7.widget.RecyclerView is changed to androidx.recyclerview.widget.RecyclerView
android.support.v7 is replced by androidx.
Migrating existing project:-
Before start migration, we need to make sure to follow the below things:-
1. Android studio version should be higher than 3.2, You can check your android studio version from About Android Studio section. also use the latest Gradle version. Check project level Build.Gradle file to change the version.
2. Target SDK version and Compile SDKversion should be 28 or greater. Check your app level Build.Gradle file to change target and compile SDK version.
3. Take a backup of your project.
4. Add below properties to gradle.properties file. You can find this file on Project Level.
A.) android.useAndroidX: set to true, the Android plugin uses the AndroidX library instead of a Support Library. The value is false by default.
B.) android.enableJetifier: set to true, the Android plugin automatically migrates existing third-party libraries to use AndroidX. The value is false by default.
Let’s start migration:-
1. Click Refactor from the menu in Android studio.
2. Then Click on Migrate to AndroidX from Refactor dropdown.
3. After that, It will ask you to take a backup of the whole project. If you have already taken the backup then ignore this step.
4. After the backup process clicks on Migrate, It will show list all support library where we are using in this project. Just click on Do Refactor and wait for some time.
5. After some time, you can see the project all support library replaced by the AndroidX library. Most of the support library will merge automatically and few we need to replaced manually. If you found any error, Fix it manually. and test your app carefully. The application could crash due to incorrect auto-correction during migration.
If you are using the latest android application then you have noticed that now days android is following a design pattern. This is material design and it came with Android Lollipop (5.0). Though we can still use this design pattern for the older versions (>4.0) by using the support libraries. One of the component of material design is TabLayout. So in this TablLayout Example we will see how we can implement it in our android application.
What is TabLayout ?
Android TabLayout provides horizontal layout to display tabs. We can display more screens in a single screen using tabs. User can swipe the tabs quickly as you can see in the image below.
Creating a new project and add necessary libraries
Open Android Studio and create a new project. I have created DemoTabLayout.
After create a new project, First of all we have to need include design libraries in the dependencies section of our build.gradle file so include this libraries in your build.gradle file by below line.
Now since we will be using Android Toolbar and TabLayout classes to show tabs, lets remove the action bar from layout by using styles,
Go to style.xml file and change the parent of theme which you are using in your app.Change parent with “Theme.AppCompat.Light.NoActionBar”. So now your style file will look like below code
Now we will define a view pager adapter to create tab swipe functionality.
package com.vikas.demotablayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
tab1 tab1 = new tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
Now we will create an Activity named MainActivity which will hold the tabs . This Activity will have two part first is code file and second is layout file. layout file code given below
We can see above that here we add a Toolbar, second is Tablayout and third thing is Viewpager. Toolbar is for showing application name and menu icon. TabLayout is for showing Tabs and viewpager is for holding fragments. Now we write code for attach this layout with fragments in MainActivity code file. Code is given below:
Now we will create an example of datePicker in which we will set date picker on edit text and we will create date picker using java code also. In this example we will create a Textview and a button also. On button click we will show date in TextView.
Create a new android application using android studio and give name DatePickerDemo.
Now Open activity_main.xml file from \res\layout path and write code which is given below
Now open MainActivity.java file and write code which is given below
MainActivity.java
package com.vikas.datepickerdemo;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
DatePickerDialog datepicker;
EditText eText;
Button btn;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
datepicker = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
datepicker.show();
}
});
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ eText.getText());
}
});
}
}
In java code you can see that we set an Onclicklistener on EditText, when we click on EditText then will see calendar dialog, From which we can select date.
Contacts are We are going to use built in Contacts.framework to import all contacts in our app. To display a list of contacts, you must have access to the user’s address book. Apple does a great job of protecting the user’s privacy, so you can’t read any of their contacts’ data without asking the user for permission. Similar restrictions apply to access the user’s camera, location, photos, and more.
Whenever we need access to privacy-sensitive information, you are required to specify this in your app’s Info.plist file. This file keeps track of many of your app’s properties, such as its display name, supported interface orientations, and, in the case of accessing a user’s contacts, Info.plist also contains information about why you need access to the user’s contacts.
Let’s go step by step:-
Add usage description in Info.plist file for contacts.
Open Plist file and click on plus button to add new row for contact usage description.
Add “Privacy – Contacts Usage Description“ in key
Select Type as String
Write the usage purpose of contacts in your app.
Import Contacts Framework in your class.
import Contacts
Request for Contact permission
func getAuthStatus() -> CNAuthorizationStatus{
return CNContactStore.authorizationStatus(for: .contacts)
}
func requestForAccess(_ completionHandler: @escaping (_ accessGrandted: Bool, _ authStatus: CNAuthorizationStatus) -> Void) {
let authorizationStatus = getAuthStatus()
switch authorizationStatus {
case .authorized:
completionHandler(true, CNAuthorizationStatus.authorized)
break
case .notDetermined:
let store = CNContactStore()
store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in
if authorized {
completionHandler(true, CNAuthorizationStatus.authorized)
}
else {
if self.getAuthStatus() == CNAuthorizationStatus.denied {
completionHandler(false, CNAuthorizationStatus.denied)
}
}
} )
break
case .denied :
completionHandler(false, CNAuthorizationStatus.denied)
break
default:
completionHandler(false, CNAuthorizationStatus.notDetermined)
break
}
}
Above two function will check Contact authorisation status. If not determined it will show alert for contact permission. Keep in mind you can ask Contact permission only once. Once user denied you can just open Setting screen for enable Contact permission.
Fetch Contact Using CNContactStore:-
do {
let store = CNContactStore()
var results = [CNContact]()
let containers = try store.containers(matching: nil)
for container in containers {
let predicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
let keyToFetch = [CNContactIdentifierKey,
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactPostalAddressesKey,
CNContactNoteKey,
CNContactOrganizationNameKey] as [Any]
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keyToFetch as! [CNKeyDescriptor])
results.append(contentsOf: contacts)
}
return results
}
catch
{
// print("Error1 is \(error)")
}
We create a CNContactStore instance and this object is used to communicate directly with the Contacts system on iOS. In this method, we wrap our code in a do-catch statement because two of the methods we use are throwing methods.We can retrieve different values using different Keys like first name, last name, contact image, mobile number, address, emails etc. We then create an array that contains a number of constant keys. These keys directly relate to the information your app has access too.
There is different container Group in Native phonebook. We can retrieve Contacts from different Container according our need. Here we are retrieving contacts of all Groups using store.containers(matching: nil) and iterate it one by one to fetch contacts.
store.unifiedContacts will return array of CNContact which you can store in Your app data or in your app’s database and display contacts In your own tableview Format.
The reason it was added is primarily for privacy reasons — the notes field can contain any information you might have on the contact; and a lot of times this information is significantly more sensitive than just the contact information.