Using wireguard to interconnect 2 hosts via a gateway - wireguard

I have 3 VPS servers, with public IPs, let's call them wireguard1, wireguard2 and wireguard3.
I have successfully managed to connect wireguard1 and wireguard2 using the following DigitalOcean tutorial.
I have then successfully managed to connect wireguard1 and wireguard3.
The configuration files look like this :
On wireguard1:
[Interface]
Address = 10.0.0.1/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard1 private key>
[Peer]
PublicKey = <wireguard2 public key>
AllowedIPs = 10.0.0.2/32
Endpoint = <wireguard2 public ip address>:5555
[Peer]
PublicKey = <wireguard3 public key>
AllowedIPs = 10.0.0.3/32
Endpoint = <wireguard3 public ip address>:5555
On wireguard2:
[Interface]
Address = 10.0.0.2/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard2 private key>
[Peer]
PublicKey = <wireguard1 public key>
AllowedIPs = 10.0.0.0/24
Endpoint = <wireguard1 public ip address>:5555
On wireguard3:
[Interface]
Address = 10.0.0.3/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard3 private key>
[Peer]
PublicKey = <wireguard1 public key>
AllowedIPs = 10.0.0.0/24
Endpoint = <wireguard1 public ip address>:5555
I can ping wireguard1 (10.0.0.1) from wireguard2 (10.0.0.2) and vice-versa, so that works fine.
I can ping wireguard1 (10.0.0.1) from wireguard3 (10.0.0.3) and vice-versa, so that works fine.
I can however not ping wireguard2 (10.0.0.2) from wireguard3 (10.0.0.3) or vice-versa. I could indeed at a [Peer] section in wireguard2 referencing wireguard3, but I would like to find a solution where all trafic goes through wireguard1.
I thought that setting the AllowedIP to 10.0.0.0/24 would do the trick, but it does not seem to work.
Has anyone a working solution?

I was having this same issue for a while. It seems to be that you need to have all peers have the public keys of all the other clients for this to work. However, I'm not sure if having they all need the endpoints or not. For your configuration, it would look something like this:
On wireguard1:
[Interface]
Address = 10.0.0.1/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard1 private key>
[Peer]
PublicKey = <wireguard2 public key>
AllowedIPs = 10.0.0.2/32
Endpoint = <wireguard2 public ip address>:5555
[Peer]
PublicKey = <wireguard3 public key>
AllowedIPs = 10.0.0.3/32
Endpoint = <wireguard3 public ip address>:5555
On wireguard2:
[Interface]
Address = 10.0.0.2/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard2 private key>
[Peer]
PublicKey = <wireguard1 public key>
AllowedIPs = 10.0.0.1/32
Endpoint = <wireguard1 public ip address>:5555
[Peer]
PublicKey = <wireguard3 public key>
AllowedIPs = 10.0.0.3/32
Endpoint = <wireguard3 public ip address>:5555
On wireguard3:
[Interface]
Address = 10.0.0.3/24
SaveConfig = true
ListenPort = 5555
PrivateKey = <wireguard3 private key>
[Peer]
PublicKey = <wireguard1 public key>
AllowedIPs = 10.0.0.1/32
Endpoint = <wireguard1 public ip address>:5555
[Peer]
PublicKey = <wireguard2 public key>
AllowedIPs = 10.0.0.2/32
Endpoint = <wireguard2 public ip address>:5555

Related

Decrypt by Public key in angularjs And decrypt by Java using private key - RSA Asymmetric

I am generating a asymmetric key pair (public and private) in java using RSA algorithm and trying to use the public key in java-script to decrypt some text and after modification of data again encrypt the data using same public key sent to spring-boot server , so that spring boot can decrypt using by private key
source link : https://github.com/jeebendu/RSA_Asymetric_Encryption/blob/main/AsymmetricMain.java
Can anyone help how to achieve in angularjs or any javascript framework CryptoJS
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class AsymmetricMain {
private static final String ALGORITHM = "RSA";
private static final String PVTKEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCa1OwhIXq10pykhtCap/stVCL0 X/1VyyeAl82HXEHotvw8F6TR8y9AsARdgSpHn6ozPaHSvo39QqTPvni065iaYidXFt4rR6dLrQ8S Ar1edbVQ/L//DCSQPQezmr0fL88R2oMO/MdPVPLlnwTJMXhMCQTnKydD/otShjSfpd9FVqII9BGh MR68pUBCtLgNcmn1YgBqXUyUGWahFbPsOAn0yRD+/28Y3xDYu3y3rNINITNf2bS2GKbmhKV1QLjp 0v7N5VppWBrrYlRSmlMyf2/1ChZPWEPUjdC117aR+PDY6t6dPtcap/pCxU4vQo1oIZBre1AEfoCe mt5bNj4yB30rAgMBAAECggEAeXfn1EomsfSMTYsyptJ4fORQE/YmkqMx13HAnZwkXQUJt7844Dlv 7cjpc838tHovlcmZZfN3A6TAFfcxTYazjxLIGEvpenzZY8ZeV1vs4ulnmSThH5+QI9StcRtJmejx A+mw/hYT60oS0VBC+fCklspQnWc+g9pzxQdiy4jfM8534yjv8FnFQqRxuqAZfbJraSx5E+nT3XSt IrLriMoKsNaLSzXn+RulGJndxRmcZ63j+rmoiEPxl9nrU0S/ZwLfvuaCv1wy7kuJB80Gfc8W3N7m 8sq5o8pAqxRe6nz1WnI5EabArSyysOOeZdXC9lt3liLUMy2EO3QYX7chiewdWQKBgQDzLB90HI5H o1pNzPA/SNVD1pZIENtgCI+ssrJymjwZNAZBP8OKYCbygmXsO3cwTvxJ7F3d0kif+aa6ndjgU+9B 71z/QZD81pKmbTHqvOU/ceEEP02DufIANaUPzR/ZRAtzgRmW3o1O2qQu7uZyFQAbgqh9sci3NqTb f2FfvMfLvQKBgQCi/9HJZHZwSdhpRVEYfQPVCa4Wmhd/PNc7nWCrex0RpTxCx7ov67O4kDnwRKVa 6en2D2GDgB0nZRq54tURrAe+J63gEqghlEI8kgC3jZazZyTtyVm4vL+Sb0ssadc+47LnGtoR6ibE +LId5RPKmmTwR0UUgVDZOtQwZf+xYIXHBwKBgQCvFtH+9KCtjDz1T96ccoC8O8IxWZHbb86jdndu dQdYzlDConrVI65nZuSkV5zWN8kIIRzlHwgTx9n4/Lavrz/Spdq8ICWZJ5aoJm+OqTwXlpOCT2Is urI43GdhHT0VXx0vqYEXVF9Cq8MT2AgtlFljdYyEFIKFCN9i/DDMkkz5sQKBgHm1OMj+2az4hr38 AxSc7EqbYsD/qAHaxP9/gJoqYEc3sOpQRgbYISbzkj+Ekk9zD74qN+6/r4Ul6jHYXK5IXLOw3xTL +XyxPlAJ2L013MvyfVGMIhFd5lGKBoCQOyd7T69ejmwIAZDb/etyjDeg1zPOk5c/A8ZgNeY5kxW3 88vrAoGBAIfCKxtchHtCDj0mp+mBmXUCxzywMJgHfdnBXd1McUdeJS0ExTNKifY3YESCQdwfVgFX 681wzsNdENQpGrN1VF47zZvra33/2cwy2eGB1wOb9wDuJiYwZWV5uTkvaf3q9+N8m03V9gJrR4tj wXnJZOeA1/4gjkmWdzoTCg0zO1LT";
private static final String PUBKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmtTsISF6tdKcpIbQmqf7LVQi9F/9VcsngJfNh1xB6Lb8PBek0fMvQLAEXYEqR5+qMz2h0r6N/UKkz754tOuYmmInVxbeK0enS60PEgK9XnW1UPy//wwkkD0Hs5q9Hy/PEdqDDvzHT1Ty5Z8EyTF4TAkE5ysnQ/6LUoY0n6XfRVaiCPQRoTEevKVAQrS4DXJp9WIAal1MlBlmoRWz7DgJ9MkQ/v9vGN8Q2Lt8t6zSDSEzX9m0thim5oSldUC46dL+zeVaaVga62JUUppTMn9v9QoWT1hD1I3Qtde2kfjw2OrenT7XGqf6QsVOL0KNaCGQa3tQBH6AnpreWzY+Mgd9KwIDAQAB";
// Generating public & private keys
// using RSA algorithm.
public static KeyPair generateRSAKkeyPair() throws Exception {
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(2048, secureRandom);
return keyPairGenerator.generateKeyPair();
}
// Encryption function which converts
// the plainText into a cipherText
// using private Key.
public static byte[] encrypt(String plainText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(plainText.getBytes());
}
// Decryption function which converts
// the ciphertext back to the
// original plaintext.
public static String decrypt(byte[] cipherText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(cipherText);
return new String(result);
}
public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
PublicKey pub = kf.generatePublic(publicKeySpec);
return pub;
}
public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privk);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
return privKey;
}
// Driver code
public static void main(String args[]) throws Exception {
springToAngularJS();
}
// Encrypt the data by private key and send to angularjs
private static void springToAngularJS() {
try {
/*
KeyPair keypair = generateRSAKkeyPair();
System.out.println ("-----BEGIN PRIVATE KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( keypair.getPrivate().getEncoded()));
System.out.println ("-----END PRIVATE KEY-----");
System.out.println ("-----BEGIN PUBLIC KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( keypair.getPublic().getEncoded()));
System.out.println ("-----END PUBLIC KEY-----");
*/
String plainText = "This is the PlainText " + "I want to Encrypt using RSA.";
byte[] encodedPublicKey = Base64.getDecoder().decode((PUBKEY.replace(" ", "").getBytes()));
byte[] encodedPrivateKey = Base64.getDecoder().decode((PVTKEY.replace(" ", "").getBytes()));
PublicKey publicKey = getPublicKey(encodedPublicKey);
PrivateKey privateKey = getPrivateKey(encodedPrivateKey);
byte[] cipherText = encrypt(plainText, privateKey);
//System.out.println( "The Public Key is: " + DatatypeConverter.printHexBinary(keypair.getPublic().getEncoded()));
//System.out.println( "The Private Key is: " + DatatypeConverter.printHexBinary(keypair.getPrivate().getEncoded()));
System.out.print("Backend :The Encrypted Text is: ");
System.out.println(Base64.getEncoder().encodeToString(cipherText));
String decryptedText = decrypt(cipherText, publicKey);
System.out.println("Backend : The decrypted text is: " + decryptedText);
angularjsToSpringboot(Base64.getEncoder().encodeToString(cipherText));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Receive encrypted data from springboot and decrypt by public key
//After any modification encrypt by public key and sent to springboot
private static void angularjsToSpringboot(String cipherText) {
try {
byte[] encodedPublicKey = Base64.getDecoder().decode((PUBKEY.replace(" ", "").getBytes()));
PublicKey publicKey = getPublicKey(encodedPublicKey);
String decryptedText = decrypt(Base64.getDecoder().decode(cipherText), publicKey);
System.out.println("Public : The decrypted text is: " + decryptedText);
byte[] dataEncByPublicKey = encrypt(decryptedText, publicKey);
System.out.print("Public : The Encrypted Text is: ");
System.out.println(Base64.getEncoder().encodeToString(dataEncByPublicKey));
decryptBySpringboot(Base64.getEncoder().encodeToString(dataEncByPublicKey));
//decryptBySpringboot(DatatypeConverter.printHexBinary(dataEncByPublicKey));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//receive encrypted data and decrypt by private key and save to db
private static void decryptBySpringboot(String cipherText) {
try {
byte[] encodedPrivateKey = Base64.getDecoder().decode((PVTKEY.replace(" ", "").getBytes()));
PrivateKey privateKey = getPrivateKey(encodedPrivateKey);
String decryptedText = decrypt(Base64.getDecoder().decode(cipherText), privateKey);
System.out.println("Backend : The decrypted text is: " + decryptedText);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am generating a asymmetric key pair (public and private) in java
using RSA algorithm and trying to use the public key in java-script to
decrypt some text
You can not use the public key to decrypt. In Asymmetric encryption only private key can decrypt.
and after modification of data again encrypt the
data using same public key sent to spring-boot server , so that spring
boot can decrypt using by private key
Why don't you just use HTTPS/SSL protocol instead of doing your own encryption/decryption. Asymmetric encryption is not good for large content anyway.

ASP .NET Core: Get User IP Address

I have a table : with a model
public class ArticleLike:BaseEntity
{
public long? UserId { get; set; }
public string UserIp { get; set; }
public ICollection<User> User { get; set; }
}
How can I get Ipaddress of user ?
I had to write method of it on service or repository?
Get client user IP address
var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
Client IP address can be retrieved via HttpContext.Connection object.
Property RemoteIpAddress is the client IP address. The returned object (System.Net.IpAddress) can be used to check whether it is IPV4 or IPV6 address.
For example, if you get a result like ::1, this is the IPv6 format
var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
or
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
Simple Usage :
In Controller
public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IActionResult Index()
{
var ip = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
return Content(ip);
}
}
And in Startup File :
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}

How to make BasicAuthentication in SolrJ - CloudSolrClient?

I am using Solr 7.5 Server and I had used External Zookeeper.When I browse using the Solr Admin UI It ask authentication to me.
For Java Client I had used the below Code
BasicAuthSolrClientCache bs = new BasicAuthSolrClientCache("solr", "SolrRocks");
CloudSolrClient solrCloudClient = bs.getCloudSolrClient(zkHost);
solrCloudClient.setDefaultCollection("sample");
SolrInputDocument doc = new SolrInputDocument();
doc.addField("cat", "book");
doc.addField("id", "book-1");
doc.addField("name", "The Legend of the Hobbit part 1");
solrCloudClient.add(doc);
solrCloudClient.commit();
solrCloudClient.close();
BasicAuthSolrClientCache.java
public class BasicAuthSolrClientCache extends SolrClientCache {
private static final Logger log =
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final Map<String, SolrClient> solrClients = new HashMap<>();
private final String username;
private final String password;
public BasicAuthSolrClientCache(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public synchronized CloudSolrClient getCloudSolrClient(String zkHost) {
CloudSolrClient client;
if (solrClients.containsKey(zkHost)) {
client = (CloudSolrClient) solrClients.get(zkHost);
} else {
client = new CloudSolrClient.Builder()
.withZkHost(zkHost)
.withHttpClient(getHttpClient())
.build();
client.connect();
solrClients.put(zkHost, client);
}
return client;
}
#Override
public synchronized HttpSolrClient getHttpSolrClient(String host) {
HttpSolrClient client;
if (solrClients.containsKey(host)) {
client = (HttpSolrClient) solrClients.get(host);
} else {
client = new HttpSolrClient.Builder(host)
.withHttpClient(getHttpClient())
.build();
solrClients.put(host, client);
}
return client;
}
#Override
public synchronized void close() {
for(Map.Entry<String, SolrClient> entry : solrClients.entrySet()) {
try {
entry.getValue().close();
} catch (IOException e) {
log.error("Error closing SolrClient for " + entry.getKey(), e);
}
}
solrClients.clear();
}
private HttpClient getHttpClient() {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new
UsernamePasswordCredentials(this.username, this.password);
provider.setCredentials(AuthScope.ANY, credentials);
return
HttpClientBuilder.create().setDefaultCredentialsProvider(provider).
build();
}
}
But it give the exception like the below,
Exception in thread "main" org.apache.solr.client.solrj.impl.CloudSolrClient$RouteException: IOException occured when talking to server at: http://192.168.0.104:8983/solr/gettingstarted_shard2_replica1 at
How to authenticate SolrCloud using SolrJ
I found a easy way to do this.
You add a request interceptor like this so you do not have to worry about creating a properly configured HttpClient instance yourself. This will just add the interceptor to the default HttpClient that Solrj creates.
org.apache.solr.client.solrj.impl.HttpClientUtil.addRequestInterceptor(new SolrPreemptiveAuthInterceptor());
The RequestInterceptor looks like this:
public class SolrPreemptiveAuthInterceptor implements HttpRequestInterceptor {
final static Logger log = LoggerFactory.getLogger(SolrPreemptiveAuthInterceptor.class);
#Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
// If no auth scheme available yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
log.info("No AuthState: set Basic Auth");
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
Credentials creds = credsProvider.getCredentials(authScope);
if(creds == null){
log.info("No Basic Auth credentials: add them");
creds = getCredentials(authScope);
}
authState.update(new BasicScheme(), creds);
}
}
private Credentials getCredentials(AuthScope authScope) {
String user = "";
String password = "";
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, creds);
log.info("Creating Basic Auth credentials for user {}", user);
return credsProvider.getCredentials(authScope);
}
}
You can also use UpdateRequest for indexing requests to do a basic authentication via SolrJ:
UpdateRequest ur = new UpdateRequest();
ur.add(doc);
ur.setBasicAuthCredentials("YOU USER NAME", "USER PASSWORD");
ur.setCommitWithin(COMMIT_WITHIN_INTERVAL);
ur.process(cloudSolrClient);

How to Enable TLS1.1 in Java7 for Axis1 webservice client

Summary: Salesforce.com recently disabled TLSv1 for their sandbox instances(test.salesforce.com) and can only support TLSv1.1 and above for API integrations for both inbound and outbound requests.
I am using Java Axis1.0 client code with JDK 7.0 to connect (via webservice soap) to salesforce.com. I get exception "UNSUPPORTED_CLIENT: TLS 1.0 has been disabled in this organization. Please use TLS 1.1 or higher when connecting to Salesforce using https."
With Java7.0
Supported Protocols:SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2
Enabled Protocols: TLSv1
`With Java8.0
when i try to connect to salesforce.com with java8 client, connection is successful.
Supported Protocols: SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2
Enabled Protocols: TLSv1, TLSv1.1, TLSv1.2`
I have to used Java 7 because our application is using it.
I tried setting vm args:
-Dhttps.protocols=TLSv1.1,TLSv1.2 -Ddeployment.security.SSLv2Hello=false -Ddeployment.security.SSLv3=false -Ddeployment.security.TLSv1=false -Ddeployment.security.TLSv1.1=true -Ddeployment.security.TLSv1.2=true"
but no success.
can you help me to find out settings in Java7 to enable TLSv1.1?
Found a solution:
I had to write custom JSSESocketFactory (because i am using Java webservice Axis1.0 client) and AxisProperties settings.
Something like,
public class TLSSocketSecureFactory extends JSSESocketFactory {
private final String TLS_VERSION_1_1 = "TLSv1.1";
private final String TLS_VERSION_1_2 = "TLSv1.2";
public TLSSocketSecureFactory(#SuppressWarnings("rawtypes") Hashtable attributes) {
super(attributes);
}
#Override
protected void initFactory() throws IOException {
SSLContext context;
try {
context = SSLContext.getInstance(TLS_VERSION_1_1);
context.init(null, null, null);
sslFactory = context.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
//printstacktrace or throw IOException
}
}
#Override
public Socket create(String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception {
if (sslFactory == null) {
initFactory();
}
Socket s = super.create(host, port, otherHeaders, useFullURL);
((SSLSocket) s).setEnabledProtocols(new String[] {TLS_VERSION_1_1, TLS_VERSION_1_2 });
return s;
}
}
AxisProperties.setProperty("axis.socketSecureFactory",TLSSocketSecureFactory.class.getCanonicalName());
This is required only for JDK7. when application is migrated to JDK8, this class is not required. In Java8 TLSv1.1 and TLS1.2 is enabled by default.
Note: Setting VM config at server will not help here for Axis java client.
From Salesforce documentation:
Java 7: Enable TLS 1.1 and TLS 1.2 using the https.protocols Java system property for HttpsURLConnection. To enable TLS 1.1 and TLS 1.2 on non-HttpsURLConnection connections, set the enabled protocols on the created SSLSocket and SSLEngine instances within the application source code.
The solution above works well when the Axis transport is the default HTTPSender. Also, it's useful to know that the new socket factory can be replaced not just with AxisProperties but also with a system property, which can be passed on the command line like this:
-Dorg.apache.axis.components.net.SecureSocketFactory=your.package.TLSv12JSSESocketFactory
Here is the code for my TLSv12JSSESocketFactory:
package your.package;
import java.util.Hashtable;
import java.io.IOException;
import java.net.Socket;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import org.apache.axis.components.net.JSSESocketFactory;
import org.apache.axis.components.net.BooleanHolder;
public class TLSv12JSSESocketFactory extends JSSESocketFactory {
private final String TLS_VERSION_1_2 = "TLSv1.2";
public TLSv12JSSESocketFactory( #SuppressWarnings("rawtypes") Hashtable attributes ) {
super(attributes);
}
#Override
protected void initFactory() throws IOException {
SSLContext context;
try {
context = SSLContext.getInstance( TLS_VERSION_1_2 );
context.init( null, null, null );
sslFactory = context.getSocketFactory();
} catch ( Exception e ) {
throw new IOException( "Could not init SSL factory with TLS context: " + TLS_VERSION_1_2, e );
}
}
#Override
public Socket create( String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL ) throws Exception {
Socket s = super.create( host, port, otherHeaders, useFullURL );
((SSLSocket) s).setEnabledProtocols( new String[] { TLS_VERSION_1_2 } );
return s;
}
}
In my case I had to change Axis 1.4 using Apache Commons HttpClient as the transport. This involved creating a class implementing interface SecureProtocolSocketFactory. Here is my code:
package your.package;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import javax.net.ssl.SSLSocket;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
public class TLSv12HttpsSocketFactory implements SecureProtocolSocketFactory
{
private static final String TLS_VERSION_1_2 = "TLSv1.2";
private final SecureProtocolSocketFactory base;
public TLSv12HttpsSocketFactory( ProtocolSocketFactory base )
{
if ( base == null || !(base instanceof SecureProtocolSocketFactory) ) throw new IllegalArgumentException();
this.base = (SecureProtocolSocketFactory) base;
}
private Socket acceptOnlyTLS12( Socket socket )
{
if ( socket != null && (socket instanceof SSLSocket) ) {
((SSLSocket) socket).setEnabledProtocols( new String[] { TLS_VERSION_1_2 } );
}
return socket;
}
#Override
public Socket createSocket( String host, int port ) throws IOException
{
return acceptOnlyTLS12( base.createSocket(host, port) );
}
#Override
public Socket createSocket( String host, int port, InetAddress localAddress, int localPort ) throws IOException
{
return acceptOnlyTLS12( base.createSocket(host, port, localAddress, localPort) );
}
#Override
public Socket createSocket( String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params ) throws IOException
{
return acceptOnlyTLS12( base.createSocket(host, port, localAddress, localPort, params) );
}
#Override
public Socket createSocket( Socket socket, String host, int port, boolean autoClose ) throws IOException
{
return acceptOnlyTLS12( base.createSocket(socket, host, port, autoClose) );
}
}
But I also had to modify the org.apache.axis.transport.http.CommonsHTTPSender class (generates a few class files when compiled) like this:
// import the new socket factory
import your.package.TLSv12HttpsSocketFactory;
...
// add this at the end of the initialize() method
// setup to our custom TLSv1.2 socket factory
String scheme = "https";
Protocol baseHttps = Protocol.getProtocol( scheme );
int defaultPort = baseHttps.getDefaultPort();
ProtocolSocketFactory baseFactory = baseHttps.getSocketFactory();
ProtocolSocketFactory customFactory = new TLSv12HttpsSocketFactory( baseFactory );
Protocol customHttps = new Protocol( scheme, customFactory, defaultPort );
Protocol.registerProtocol( scheme, customHttps );

Failed to load resource: the server responded with a status of 415

I have a error when call the POST. I am using AngularJS, Tomee, restful
Error: Failed to load resource: the server responded with a status of 415
POST:
$http({method: 'POST', url:'http://localhost:8080/WSGestionCobros/webresources/atenciones/',data: {"atenciones" : $scope.atencion}}).success(function(data, status, headers, config) {
...
}
My class
#Stateless
#Path("atenciones")
public class AtencionesFacadeREST extends AbstractFacade<Atenciones> {
#PersistenceContext(unitName = "WSCobrosPU")
private EntityManager em;
public AtencionesFacadeREST() {
super(Atenciones.class);
}
#POST
#Override
#Consumes({"application/json"})
public void create(Atenciones entity) {
super.create(entity);
}
...
...
...
The entity class:
#Entity
#Table(name = "atenciones")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Atenciones.findAll", query = "SELECT a FROM Atenciones a"),
#NamedQuery(name = "Atenciones.findByCasoid", query = "SELECT a FROM Atenciones a WHERE a.casoid = :casoid"),
#NamedQuery(name = "Atenciones.findByCedula", query = "SELECT a FROM Atenciones a WHERE a.cedula = :cedula"),
#NamedQuery(name = "Atenciones.findByUsuario", query = "SELECT a FROM Atenciones a WHERE a.usuario = :usuario"),
#NamedQuery(name = "Atenciones.findByEstado", query = "SELECT a FROM Atenciones a WHERE a.estado = :estado"),
#NamedQuery(name = "Atenciones.findByFechaCreacion", query = "SELECT a FROM Atenciones a WHERE a.fechaCreacion = :fechaCreacion")})
public class Atenciones implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "casoid")
private Integer casoid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "cedula")
private String cedula;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "usuario")
private String usuario;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 3)
#Column(name = "estado")
private String estado;
#Basic(optional = false)
#NotNull
#Column(name = "fecha_creacion")
#Temporal(TemporalType.TIMESTAMP)
private Date fechaCreacion;
...
I tried put header Content-Type: application/json but nothing
Maybe add #Produces("application/json") ont the method or class

Resources