How to use Netcipher with Retrofit in android? - android

Netcipher is an Android Library Project that provides multiple means to improve network security in mobile applications. The “Onion” name refers to not only the Onion Routing concept used by Tor (which provides anonymity and resistance to traffic surveillance), but also the idea of multiple layers of security that any application should utilize.
More specifically this library provides:
1. Stronger Sockets: Through support for the right cipher suites, pinning and more, we ensure your encrypted connections are as strong as possible.
2. Proxied Connection Support: HTTP and SOCKS proxy connection support for HTTP and HTTP/S traffic through specific configuration of the Apache HTTPClient library
https://guardianproject.info/code/netcipher/

You need to implement your own Client that will execute Retrofit request on Netcipher http client.
Translate Request to appropriate Netcipher request (copy http method, headers, body)
Execute the translated request on Netcipher http client
Obtain response and translated it to retrofit Response (copy http status code, response, headers)
Return response to be deserialized to type.
Pass your Client to RestAdapter.Builder.
Done.
public class NetcipherClient implements Client{
private Context mContext;
public NetcipherClient(Context context){
mContext = context;
//As far as I could see from the sample, Netcipher seems to be dependant on application `Context`.
}
#Override
public retrofit.client.Response execute(retrofit.client.Request request) throws IOException {
//Set up configuration for Netcipher (proxy, timeout etc)
// Translate Request to Netcipher request
// Execute and obtain the response
// Build Response from response
return response;
}
}

We've recently implemented support for OkHTTP in NetCipher so it should be easy to add Tor support to Retrofit via OkHTTP. Here's how:
compile 'info.guardianproject.netcipher:netcipher-okhttp3:2.0.0-alpha1'
The core of this is just running the method to set things up:
StrongOkHttpClientBuilder
.forMaxSecurity(this)
.withTorValidation()
.build(this);
See the included sample-okhttp3 project for a full example, which is part of the git repo https://github.com/guardianproject/NetCipher

Except Tor-like routing OkHttp also have the certificate pinning ability & proxy support. And it works with Retrofit out-of-the-box! So, if Tor-like functions are not so important for you, I recommend to utilize OkHttp's awesomeness. Otherwise, answer by #NikolaDespotoski is your perfect choice.

Related

Issue while accessing WooCommerce Rest API from OkHttp based app

I want to build an android client that can interact with the WooCommerce based site using the Rest Api provided by WooCommerce
This is my android code. I am using OkHttp library for networking.
public class MainActivity extends AppCompatActivity {
OkHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String cred = Credentials.basic("ck_...","cs_...");
OkHttpClient client = new OkHttpClient
.Builder()
.build();
Request req = new Request
.Builder()
.addHeader("Authorization",cred)
.url("http://10.0.2.2:8080/woocom/wp-json/wc/v2/products")
.build();
client.newCall(req).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("api resp", "onFailure: ");
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Api resp", "onResponse: "+response.body().string());
}
});
}
}
This is the error log after running the app
com.example.android.woocommerceapiintegration D/Api resp: onResponse: {"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
What am I doing wrong here. I tried out the NodeJS client provided by WooCommerce which works fine.
Also I cannot access the rest api via curl according to the command given in the docs
Can someone tell me what I am doing wrong ?
Update: The selected answer is what needs to be done in production environments, and is the technically right thing to do. If you want to avoid the hassle of OAuth while on a development server, I have answered it seperately.
The 401 code indicates an authorization issue with your connection. Specifically your issue is caused by your usage of BasicAuth with an HTTP connection.
The WooCommerce REST API Documentation indicates that BasicAuth is only supported for HTTPS connections, and HTTP connections must use OAuth 1.0a "one-Legged" authentication to "ensure" your credentials aren't intercepted by an attacker.
It's important to note that even with OAuth 1.0a, an HTTP connection will never be truly secure and it's highly recommended to switch your app over to a secure HTTPS connection.
Meanwhile, in order to get your code working, you'll have to implement the OAuth 1.0a authentication method for your Android app.
You can find a complete set of instructions and a complete project example of OAuth 1.0a implementation for Android here. The GitHub Page has an excellent guide with step-by-step instructions on using the library linked above. Just make sure that when using the code provided you make sure to account for the fact that you're using OKHttp. Luckily, the author has commented the code in the instructions very well and makes a note of changes to make when using something like OkHttp.
You could use Retrofit and simply write an Interceptor which takes care of the 'nitty-gritty' part as detailed in the documentation here.
You could also follow the step by step guide detailed in the WooCommerce Documentation here to generate your OAuth signature and finally encodedUrl and then pass it to your http client. This processs involves: (see the Documentation for detailed specs for each section)
Collecting the request method and URL
Collecting all oauth_* parameters and encoding them into a single string using percent encoding and correct ordering. For Example (taken from WooCommerce Docs):
oauth_consumer_key=abc123&oauth_signature_method=HMAC-SHA1
Create the base string for the signature by joining the values from 1 and 2. For example: (once again from Docs):
GET&http%3A%2F%2Fwww.example.com%2Fwp-json%2Fwc%2Fv2%2Forders&oauth_consumer_key%3Dabc123%26oauth_signature_method%3DHMAC-SHA1
Finally generate the signature using HMAC-SHA1 (HMAC-SHA256 is also supported).
Personally I would recommend either the first or second approach. "No need to reinvent the wheel".
EDIT:
You can look at this question which discusses how you can use self-signed certificates in a local dev environment with OkHttp.
Thanks akseli for answering my question.I've also awarded you the bounty and thanks for adding to my knowledge. Despite everything, I've found a simple solution to this problem.
My concern was that while development, We generally don't have an https based server and hence have to go through that tedious OAuth based process which won't be used is production anyway as the server we will probably use will be https enabled.
So, to use basic authentication while on an http dev server, you need to go to [your wordpress directory]/wp-content/woocommerce/includes/api. Find out class-wc-rest-authentication.php. This class handles the api authentication. Find the authenticate function which looks like this
public function authenticate( $user_id ) {
// Do not authenticate twice and check if is a request to our endpoint in the WP REST API.
if ( ! empty( $user_id ) || ! $this->is_request_to_rest_api() ) {
return $user_id;
}
if ( is_ssl() ) {
return $this->perform_basic_authentication();
}
return $this->perform_oauth_authentication();
}
comment out the condition is_ssl and simply return $this->perform_basic_authentication(), so that in any case, basic authentication is performed.
Note:This is a hack just to avoid the hassle of OAuth authentication while in dev environment and is not at all recomended in production.

Android sdk architecture

I'm newbie in development and I have to develop android sdk. It's going to wrap network API and provide OAuth 2.0 authentication functionality. Also web sockets for session ending and push notifications will be included in sdk. I'm planning to use Facade design pattern:
public interface SdkFacadeInterface {
AuthenticateRequest authenticate(); // http request
StartCallRequest starCall(); // http request with establishing websocket connection, push notification sending
SelectGatewayRequest selectGateway(); //http request
EndCall endCall(); // http request called after web sockets connection closes
HistoryRequest getHistory(); // http request
void setFirebaseToken(Context context, String firebaseToken);
interface Builder {
Builder setCliendId(String cliendId);
Builder setClientSecret(String clientSecret);
Builder enablePushNotifications(booleanenablePushNotifications);
Session build();
}
}
After authentication I need to save refresh token and access tocken to the phone storage, I'am planning to use SharedPrefs for it. I have the following questions:
What architecture should I use? Is there some architectural patterns for sdks which I can use
Maybe you know some sdk on github which I can use as reference for my project.
Can I use retrofit for http request or I rather use AsynTask with HttpUrlConnection so my sdk will have as little external dependencies as possible
Sdk development is different from applications development, what should I take in consideration for developing sdk(all suggestions and ideas a welcomed)
How should I handle bad input from clients, should I throw exception or just write error to logs (Log.e(..))
Thanks in advance

Retrofit2 with local Tor HTTP proxy does not adapt to Tor-circuit change

Im using Retrofit2 in my Android project and configure it's okhttp3 client with the netcipher library's StrongOkHttpClientBuilder to use the local HTTP proxy (127.0.0.1:8118) provided by the Orbot application in the background.
For testing purpose, I create for every request a new Retrofit2 client (with new Okhttp3 client) and send a request to http://api.ipify.org/ to verify the current public IP.
Everything is working fine, the connection goes through the local Tor proxy and the public IP I get as response from ipify.org is an IP from the Tor network.
BUT: When I change the circuit in Orbot manually, so that the local proxy resolves to a different Tor-network IP and test again, the oldTor-network IP gets used...
Has anyone an idea, what could be the reason for this? Maybe the way how okhttp3 is processing proxies?
Notes:
- Removing the local proxy in Retrofit2 and retry, it resolves correctly to my normal public IP
- It's not an Orbot issue, because when I configure 127.0.0.1:8118 as browser proxy and change the circuit it works (public IP changes)
- It shouldn't be a Retrofit caching problem, because I haven't configured cache and for every new try I build the Retrofit and okhttp3 client new.

Retrofit dynamic HTTP methods

I'm planning to replace Apache HTTP client with retrofit in my project.
The problem I'm facing is that retrofit didn't(I couldn't find) support setting HTTP method to request at runtime.
In my Web Service I don't know what HTTP method to call in advance, so annotations #GET, #POST, ... are useless.
Retrofit is not designed for dynamic url requests. You configure retrofit with your API base URL then make specific requests.
For a more flexible dynamic option use out OkHttp. It is the HTTP Client used by Retrofit and it easy to work with.
You can use Retrofit 2 for dynamic URL request with the new #Url annotation:
public interface CarService {
#GET
public Call<ImageResponse> getPicture(#Url String url);
}
Then just also create #POST, #PUT etc. You are going to have to make the choice somewhere.

App Engine endpoint with Retrofit

Would like to use Retrofit for handling network requests between Android Client and GAE endpoints.
GAE endpoints give Client/Server endpoint libraries to handle all the networking and also Oauth2 authentication which is nice.
Retrofit helps well for asynchronous call, cancellation, parallel calls...so is better than android client asynctask.
So can this Retrofit lib be configured with Appengine GAE endpoints or need to go through normal GAE servlet?
Just to clarify my question and make answers clear for any who read this :
I had for my App :
Client side : cloud endpoint library generated by google plug in for eclipse
Back end side GAE : different API with methods coded in JPA such as :
#ApiMethod(name = "insertMyShareItem")
public ShareItemData insertMyShareItemData(ShareItemData shareitemdata) {
logger.log(Level.SEVERE, "insertMyShareItem");
}
Advantages of google cloud endpoint was endpoint libray , easy use of Auth2 and automatically use of secure connections via HTTPS
Now I want to give up Async task in order to implement Retrofit or Volley. I understood I cannot use google cloud endpoint anymore and need to transform my methods on GAE Back end side in methods which extends HttpServlet so I can access them by URL call with normal setup of Retrofit.
Which means now I need to care :
how I pass my object to Retrofit and how I retrieve them on back end
how I transform Retrofit HTTP call in a HTTPS call for secure connection
how I implement and manage Auth2 and tokens between Client and GAE back end to establish secure authentication.
This is what I understood from search and below answers.Thks
Use the Google Cloud API URL as the base URL and proceed with the normal setup of Retrofit. I don't think it is a big deal. Here is a link to a tutorial that could help you get started with Retrofit.
[source]

Categories

Resources