Android React Native App HostNameVerifier Error from Google Play Store - android

Please help, I have the below implementation in MainApplication.java file. I am checking fixed hostnames and then returning true or false accordingly.
Error Insecure hostname verifier
Security Your app is using an unsafe implementation of hostname
verifier. Please see this Google Help Centre article for details,
including the deadline for fixing the vulnerability.
Ld/a/a/a/a/c/e$1; Ld/a/a/a/a/c/f$1; sv:deadline:12/10/2020
#Override
public void onCreate() {
super.onCreate();
hostnameVerifier();
MobileCore.setApplication(this);
SoLoader.init(this, /* native exopackage */ false);
ReactNativeFirebaseApp.setApplicationContext(this);
}
private void hostnameVerifier(){
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
String hostList[] = {"in.appcenter.ms", "graph.facebook.com",
"assets.adobedtm.com", "codepushupdates.azureedge.net", "app-measurement.com",
"forter.com", "dmn1", "dmn2", "dmn3", "quantummetric.com", "urbanairship.com", "demdex.net", "search.unbxd.io",
"monetate.net", "bazaarvoice.com", "google.com", "stylitics.com", "getcandid.com","braintreegateway.com"
};
for (String host : hostList) {
if (host.contains(arg0) || arg0.endsWith(host)) {
return true;
}
}
return false;
}
});
}
What should I change, please help.

The security alert is correct. Your code is putting users at risk and should be rejected from the App Store.
Why do you need this code at all? Remove it and only connect to servers when you get valid certificates back.

On google play console go to Release Management -> Select apk version -> Security tab. There you will see list of security issues with that apk along with class in your code that's causing that security issue where ever possible.
If you do not see a class name and rather see some encoded code in the security warning message, upload another build by disabling whatever code compress tool you maybe using. In my case it was proguard, I disabled it and got the library name. FYI - THe library was Braintree in my case

Related

Spring Boot/Security - can I use X509 Certificate as an extra layer in authentication?

I am building an Android App which communicates with my REST API that is protected by Spring Security.
Since the Android App is "public" and no keys etc is secure I want to create diffrent obstacles and make things complicated to protect my API as much as possible.
One way in which I would like to add more security is to make sure that the one calling my API has a certificate. I don't want to create thousands of certificates in my APIs trust-store so I just want to make sure that the caller have one single certificate that I hid away in a keystore in my Android app.
In the examples I have found it seems like a "normal" X509Certificate authentication in Spring Security requires a unique certificate for every user and then this certificate replaces Basic auth or JWT auth. I would like to have individual client JWT tokens but make sure that every call brings my ONE Android App certificate to make (more) sure that someone is calling my API from my Android app.
Is this possible or is it just not what it is for?
When you create a RestTemplate you can configure it with a keystore and trust-store so in that end it should be easy. But as for protecting my REST API it seems more difficult since I want both certificate + JWT token or Basic auth.
I am not using XML configuration for my securityconfig. I instead extend WebSecurityConfigurerAdapter. It would be great if this was configurable in the configure(HttpSecurity http) method, but I'm thinking that maybe I could achieve this in a OncePerRequestFilter somehow? Perhaps configure a filter before my JwtAuthFilter?
Edit:
In all the examples I have found for configuration of spring security they always seems to use the certificate as an authentication. I just want to configure so that when someone call example.com/api/** it checks so that the certificate is approved by my custom trust store (so that I "know" it is probably a call from my app) but if someone call example.com/website it should use the default java trust store.
If someone call example.com/api/** I would like my server to
check certificate and kill the connection if the certificate is not approved in my custom truststore.
If certificate is ok, establish https (or move on if I can't kill the connection before it have already established https-connection) to user auth with Basic-/JWT-authentication.
I think I figured it out. Here is how I configured it and it seems to work.
The "/**" endpoint is the website which should work with any browser without any specific certificate, but it requires Admin authority (you need to login as admin).
The "/api/**" and "/connect/**" endpoints require the correct certificate, the correct API-key and valid Basic- or JWT-token authentification.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/loginForm")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.requestMatchers()
.antMatchers("/connect/**","/api/**")
.and()
.addFilterBefore(new APIKeyFilter(null), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtAuthorizationFilter(), BasicAuthenticationFilter.class)
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/connect/**").hasAnyRole("MASTER,APPCALLER,NEGOTIATOR,MEMBER")
.antMatchers("/api/**").hasAnyRole("MASTER,MEMBER,ANONYMOUS");
}
The ApiKeyFilter class is the one that check the api-key and also make sure that the certificate used in the call is approved in my server trust-store. The api-key check is all that I had to configure, the extended X509AuthenticationFilter will automatically check the request certificate. My ApiKeyFilter looks like this:
public class APIKeyFilter extends X509AuthenticationFilter {
private String principalRequestHeader = "x-api-key";
private String apiKey = "XXXX";
public APIKeyFilter(String principalRequestHeader) {
if (principalRequestHeader != null) {
this.principalRequestHeader = principalRequestHeader;
}
setAuthenticationManager(new AuthenticationManager() {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if(authentication.getPrincipal() == null) {
throw new BadCredentialsException("Access Denied.");
}
String rApiKey = (String) authentication.getPrincipal();
if (authentication.getPrincipal() != null && apiKey.equals(rApiKey)) {
return authentication;
} else {
throw new BadCredentialsException("Access Denied.");
}
}
});
}
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
return request.getHeader(principalRequestHeader);
}
#Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
X509Certificate[] certificates = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (certificates != null && certificates.length > 0) {
return certificates[0].getSubjectDN();
}
return super.getPreAuthenticatedCredentials(request);
}
}
Cred goes to these resources that helped me put things together:
Spring Boot - require api key AND x509, but not for all endpoints
spring security http antMatcher with multiple paths

Why Firebase is unable to get PlayGames AuthCode and pass it into its Credential?

To begin with, I'm working on a Unity Game where I'm authenticating user when the game starts. My build environment is android. I'm using Firebase authentication for Google Play Games Services to authenticate user.
When the game starts in my android device or emulator, it is able to authenticate Play Games Services as well as able to connect with Firebase (I'm getting analytics data). However, when I pass the PlayGames AuthCode into Firebase.Auth Credentials, it stops executing the code (I've debug log for it). It does not throw any error in LogCat except
Firebase | server_auth_code
I tried searching web for different issues, but nothing. I checked my keys in player setting, firebase settings, OAuth 2.0 credentials on my Google API console and even check keys from my Google Play Console (which I'm not using at this stage). I have even checked my test users email addresses in Game Services and tried multiple google play games account. But issue still persist.
I'm using similar script in my other unity project where authentication works like a charm. I tried to use same script here and ended up with this issue: here. However, I solved it by removing all the packages and re-importing them into unity and changed my call functions in the script. Now, I'm stuck at this issue.
Here is cs file:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading.Tasks;
public class SetFirebase : MonoBehaviour
{
string authCode;
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().
RequestServerAuthCode(false /* Don't force refresh */).Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
Social.localUser.Authenticate((bool success) =>
{
if (success)
{
authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("PlayGames successfully authenticated!");
Debug.Log("AuthCode: " + authCode);
}
else
{
Debug.Log("PlayGames SignIn Failed");
}
});
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
Debug.Log("Firebase Ready!!!");
RunFirebase();
}
else
{
Debug.LogError(System.String.Format("Could not resolve all Firebase dependencies: {0}", dependencyStatus));
}
});
}
private void RunFirebase(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Debug.Log("init firebase auth ");
Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
Debug.Log(" passed auth code ");
auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInOnClick was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
});
}
}
My LogCat executes everything till "init firebase auth" but does not execute "passed auth code" so I know there is some issue in passing the credentials. It also does not run anything inside auth.SignInWithCredentialAsync(credential).
Any help or suggestion would be highly appreciated. Thank you.
There are two things I may suggest:
1) Replace ContinueWith with ContinueWithOnMainThread. This is a Firebase Extension that will guarantee that your logic runs on the main Unity thread (which tends to resolve many Unity specific issues). I go into more detail about that here.
2) Your logic may have a race condition between the Authenticate callback and the CheckAndFixDependenciesAsync continuation. These will not necessarily run in the order that you see them in your logic.
If I were building this system, I might prefer using Coroutines and a custom yield instruction:
class Authenticate : CustomYieldInstruction
{
private bool _keepWaiting = true;
public override bool keepWaiting => _keepWaiting;
public Authenticate(Social.ILocalUser user) {
user.Authenticate((bool success)=>{
/* old authentication code here */
_keepWaiting = false;
});
}
}
Then in a coroutine have something like:
private IEnumerator InitializeCoroutine() {
/* old authentication code */
// I'm ignoring error checking for now, but it shouldn't be hard to figure in.
// I'm mostly going from memory now anyway
// start both authentication processes in parallel
var authenticate = new Authenticate(Social.localUser);
var firebaseDependenciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
// wait on social
yield return authenticate;
// wait on Firebase. If it finished in the meantime this should just fall through
yield return new WaitUntil(()=>firebaseDependenciesTask.IsComplete);
RunFirebase();
}
This way my logic looks roughly synchronous whilst still maintaining the asynchronosity (spell check claims that I made up that word) of the systems you're depending on and you avoid threading related issues that arise when using ContinueWith.
Let me know if that helps!
--Patrick

Xamarin Android Web Service over HTTPS

I'm having some difficulties consuming a web service that is available only over https.
I have read posts from several other people who is having issues with achieving this as well, but none of the answers I have seen so far has fixed the problem for me, so I will try to explain my issue here and hope some of you know how to get past this obstacle.
I'm using Xamarin Studio 6.1.1 developing for Android specifically.
I have set the "HttpClient Implementation" under "Android Build" for the project to "AndroidClientHandler" (which appears to be the latest implementation and should support TLS 1.2).
I have added a web reference (not as WCF) to the web service and supplied the login information when prompted... So far everything is going as expected.
Note: I have tested the web service from a console application in Visual Studio and it works as expected.
However, when I attempt to call one of the methods of the web service I get the same error that I can see so many others have encountered before me which is this "Error: TrustFailure (The authentication or decryption has failed.)".
I have tried several of the previous posted solutions but nothing seems to help.
1.A) providing the callback function for ServicePointManager:
ServicePointManager.ServerCertificateValidationCallback += CertificateValidationCallBack;
1.B) the callback function:
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
2) Creating an instance of the AesCryptoServiceProvider:
System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
If anyone can has a solution this the apparently pretty common problem, please don't hesitate to let me know, I only have so much hair...
kind regards,
Aidal
Possible known bug. Search this here for "https": https://releases.xamarin.com
[Mono], [Xamarin.iOS], [Xamarin.Android], [Xamarin.Mac] – 43566 –
“TrustFailure (The authentication or decryption has failed.) … Invalid
certificate received from server.” with “Error code: 0x5” or “Error
code: 0xffffffff800b010f” when attempting to access HTTPS servers on
ports other than 443
Bug reference: https://bugzilla.xamarin.com/show_bug.cgi?id=44708

Using gitskarios/GithubAndroidSdk

I'm trying to use the gitskarios/GithubAndroidSdk to provide my alpha and beta testers a way to view current github issues and report new ones. Here are the steps I've already taken:
Create a GitHub application at LINK.
Add the client info to my application's metadata:
com.alorma.github.sdk.client -> my client's ID
com.alorma.github.sdk.secret -> my client's secret
com.alorma.github.sdk.oauth -> my client's 'Authorization callback URL'
Run this code in my fragment's onCreate:
GithubDeveloperCredentials.init(new MetaDeveloperCredentialsProvider(mParent));
UserReposClient client = new UserReposClient(getActivity(), null);
client.setOnResultCallback(new BaseClient.OnResultCallback<List<Repo>>() {
#Override
public void onResponseOk(List<Repo> repos, Response response) {
Log.d("GitHub", "onResponseOK: " + response);
}
#Override
public void onFail(RetrofitError retrofitError) {
Log.d("GitHub", "onFail: " + retrofitError);
}
});
Log.d("GitHub", "getting repos");
client.execute();
The result is a single log for "getting repos" and no callback.
I've tried removing the call to GithubDeveloperCredentials.init() but that just causes a crash saying that provider is null. I then thought that maybe I didn't have an auth token so I made a call to the RequestTokenClient using null for the second parameter in RequestTokenClient(Context context, String code) but this too never gets a callback or return a null token if executed with executeSync().
UPDATE
I tried using the Personal access tokens (see comments) page to generate an access token then save it into StoreCredentials. When running the execute() command now it appears to be getting a little further but now I'm getting a new error saying:
retrofit.RetrofitError: LoginService.requestToken: HTTP method annotation is required (e.g., #GET, #POST, etc.).
Looking around I found an answer (see comments) saying this might be a proguard issue with the retrofit package. So I added those lines into my app's proguard file but no luck yet.
Can anybody help me? All I want to do is get a list of the open issues.
OK, so I got this working finally though not quite in the best way I wanted. I initially intended each of my Alpha testers to require having their own GitHub account and be added to the project then using their own credentials to obtain an auth token and accessing the bug list. Instead, using the auth token I generated in my update I was able to access the repo. I had to change the proguard to:
-keepattributes *Annotation*,Signature
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
#retrofit.http.* <methods>; }
(For some reason the *Annotation* and Signature nedded to be on the same line)

android in app billing purchase verification failed

i' having trouble implementing in app billing in my android app.
i'm getting a purchase signature verification failed.
In a first time i tough it was the base64 key but i checked it many times and i'm still getting the error, then after i took a look at the Security.java file and i found this method which i edited for get some informations about what was wrong:
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
if(TextUtils.isEmpty(signedData)) Log.d(TAG, "SIGNED DATA EMPTY");
if(TextUtils.isEmpty(base64PublicKey)) Log.d(TAG, "KEY IS EMPTY");
if(TextUtils.isEmpty(signature)) Log.d(TAG, "SIGNATURE IS EMPTY");
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
}
And i'm getting "signature is empty".
Even after i follow the steps below:
-Sign the apk with my release key
-upload it as a draft
-install it on a device with "adb -d install app.apk"
I'm testing with real purchases.
Thanks.
Edit The purchase flow is fine, i get the error when i call queryInventoryAsync
You can use the test SKU's to do testing, as explained here. These are:
android.test.purchased
android.test.canceled
android.test.refunded
android.test.item_unavailable
These purchases will be successful (at least the android.test.purchased) even in test and debug scenario's, without the need to cancel the purchase.
In the verifyPurchase I changed return false to:
Log.e(TAG, "Purchase verification failed: missing data.");
if (BuildConfig.DEBUG) {
return true;
}
return false;
but you should be aware to use this only in test scenario's.
This will return true, if you have a debug build, and the signature data is missing. Since the BuildConfig.DEBUG will be false in a production build this should be OK. But better is to remove this code after everything is debugged.
Replace your verifyPurchase() method with below one. Use old code that given below, google developer are trying to solve this error in the near future but before they updated their code you should prefer below code.
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (signedData == null) {
Log.e(TAG, "data is null");
return false;
}
boolean verified = false;
if (!TextUtils.isEmpty(signature)) {
PublicKey key = Security.generatePublicKey(base64PublicKey);
verified = Security.verify(key, signedData, signature);
if (!verified) {
Log.w(TAG, "signature does not match data.");
return false;
}
}
return true;
}
check this link for more information:
In App billing not working after update - Google Store
Use try to replace OLD CODE method verifyPurchase() method in your project. But It should be only happens when you are trying to purchase test products. Let me know for the real products purchase also after using this code.
Edit:
Why it happens because we will not get any signature while we are using dummy product like "android.test.purchased". So in the old code it is working good because we were return true even if signature is not given and for the New code we are returning false.
more information about the signature data null or blank from link1 and link2
So I suggest you just replace old code method verifyPurchase() instead of New Code method.
I think may be New Code will work fine for the real product but not in the dummy product. But yet I have not tested for the real product.
or
use GvS's answer for the test purchases it also the good solution for the new code.
Hope it will solve your problem.
Make sure that you are logged in with the right user on your phone or e.g. add your phone's google account as a test user in the developer console.
http://developer.android.com/google/play/billing/billing_testing.html#billing-testing-static:
In some cases, the reserved items may return signed static responses, which lets you test signature verification in your application. The reserved items only return signed responses if the user running the application has a developer or test account.
set return value to true In
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
return true;
}
after tesing undo the change

Categories

Resources