Verify P12 Certificate for VPN Conection - ios

I want to connect Vpn via Code Using Network Extension framework .
I have a P12 Certificate to make VPN Connection also a Root CA (Crt) Certificate to Verify the P12 Certificate .
My problem is to verify The P12 certificate programatically .
I am Using below code to connect to VPN .
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = "102.xxx.xxx.xx"
p.remoteIdentifier = "102.xxx.xxx.xx"
p.disconnectOnSleep = false
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = "Root-CA"
if #available(iOSApplicationExtension 8.3, *) {
p.certificateType = NEVPNIKEv2CertificateType.RSA
} else {
// Fallback on earlier versions
}
// Here i Provide Certificate Data .
let rootCertPath = NSBundle.mainBundle().pathForResource("certificate", ofType: "p12")
let certficiateData = NSData(contentsOfFile: rootCertPath!)
// I need to verify above P12 Certificate with rootCA.crt before Passing to identityData
p.identityData = certficiateData
}
manager.enabled = true
manager.`protocol` = p

Related

F# Akkling Unable to send message through sharding proxy

When I try to send a message to the akka.net region proxy with the following code,
open Akkling.Cluster.Sharding
open Akka.Actor
open Akka.Cluster
open Akka.Cluster.Sharding
open System
open Akkling
let configWithPort (port:int) =
let config = Configuration.parse ("""
akka {
actor {
provider = cluster
}
remote {
dot-netty.tcp {
public-hostname = "localhost"
hostname = "localhost"
port = """ + port.ToString() + """
}
}
cluster {
roles = ["Worker"]
sharding {
journal-plugin-id = "akka.persistence.journal.inmem"
snapshot-plugin-id = "akka.persistence.snapshot-store.inmem"
}
seed-nodes = [ "akka.tcp://cluster-system#localhost:5000" ]
}
}
""")
config
.WithFallback(Akka.Cluster.Tools.Singleton.ClusterSingletonManager.DefaultConfig())
.WithFallback(ClusterSharding.DefaultConfig())
let system1 = ActorSystem.Create("cluster-system", configWithPort 5000)
let system2 = ActorSystem.Create("cluster-system", configWithPort 5001)
/// Domain
type FileCommand = {
ProgramId : string
Duration : TimeSpan
FilePath : string
}
/// Actors
let aggregateRootActor (mailbox:Actor<_>) (msg:FileCommand) =
let nodeAddress = Cluster.Get(mailbox.System).SelfUniqueAddress
logInfof mailbox "Program: [%s] with path [%s] on [%A]" msg.ProgramId msg.FilePath nodeAddress
ignored ()
let extractorFunction (message:FileCommand) =
let entityId = message.ProgramId
let hash = entityId.GetHashCode()
let numberOfShards = 5
let shardId = sprintf "shard_%d" ((abs hash) % numberOfShards)
shardId, entityId, message
let region1 = spawnSharded extractorFunction system1 "fileRouter" (props (actorOf2 aggregateRootActor))
let region2 = spawnSharded extractorFunction system2 "fileRouter" (props (actorOf2 aggregateRootActor))
let shardRegionProxy =
spawnShardedProxy extractorFunction system1 "fileRouterProxy" None
And sending message to the proxy always failed.
shardRegionProxy <! { ProgramId = "a"; Duration = TimeSpan.FromMinutes 10.; FilePath = "\\a_1.mp4" } //this failed
The error message is
> [INFO][8/26/2020 5:13:15 PM][Thread 0027][akka://cluster-system/system/sharding/fileRouterProxyCoordinator/singleton/coordinator] Message [RegisterProxy] from akka://cluster-system/system/sharding/fileRouterProxyProxy to akka://cluster-system/system/sharding/fileRouterProxyCoordinator/singleton/coordinator was not delivered. [6] dead letters encountered. If this is not an expected behavior then akka://cluster-system/system/sharding/fileRouterProxyCoordinator/singleton/coordinator may have terminated unexpectedly. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
However these sends are successful.
region1 <! { ProgramId = "d"; Duration = TimeSpan.FromMinutes 8.; FilePath = "\\a_2.mp4" }
region2 <! { ProgramId = "a"; Duration = TimeSpan.FromMinutes 10.; FilePath = "\\a_1.mp4" }
Excuse me,
How do I correctly create the shardingcoordinator?
Or if it was incorrect, what's the problem using shardingcoordinator like this?
The name was wrong, change the code like this, and everything is FINE!
let shardRegionProxy = spawnShardedProxy extractorFunction system1 "fileRouter" (Some "Worker")

Post trade Order Binance Signature error

I am trying to make trade using binance api from ios.
Always gives error ["code": -1022, "msg": Signature for this request is not valid.]
Code:
public override func requestFor(api: APIType) -> NSMutableURLRequest {
let mutableURLRequest = api.mutableRequest
if let key = key, let secret = secret, api.authenticated {
var postData = api.postData
//postData["symbol"] = "BNBBTC"
//postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
postData["symbol"] = "BNBBTC"
postData["side"] = "SELL"
postData["type"] = "MARKET"
postData["recvWindow"] = "5000"
postData["quantity"] = "0.1"
postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
if let hmac_sha = try? HMAC(key: secret, variant: .sha256).authenticate(Array(postData.queryString.utf8)) {
let signature = Data(bytes: hmac_sha).toHexString()
postData["signature"] = signature
}
var postDataString = ""
if let data = postData.data, let string = data.string, postData.count > 0 {
postDataString = string
if case .GET = api.httpMethod {
mutableURLRequest.httpBody = data
} else if case .POST = api.httpMethod {
var urlString = mutableURLRequest.url?.absoluteString
urlString?.append("?")
urlString?.append(postData.queryString)
let url = URL(string: urlString!)
mutableURLRequest.url = url
}
api.print("Request Data: \(postDataString)", content: .response)
}
mutableURLRequest.setValue(key, forHTTPHeaderField: "X-MBX-APIKEY")
}
return mutableURLRequest
}
Edit: While using account api i am not facing any issues with the signature. It gives response as expected
I had same ... problem and I found answer. When you generate signature, inputs for Test Order and Account Info are different.
Inputs for account info:
string input = "timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
Inputs for test limit order:
string input = "symbol=ETHBTC&side=BUY&recvWindow=6500&type=LIMIT&timeInForce=GTC&quantity=100&price=0.1&timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
and generate signature working example (C#):
private string GenerateSignature(string input, string apiSecret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(apiSecret);
byte[] messageBytes = encoding.GetBytes(input);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
return String.Concat(hashMessage.Select(b => b.ToString("x2")));
}
}

I'm getting the errorNum :8 while sending the push notifications to ios devices

var apn = require('apn');
var gcm = require('android-gcm');
export default function notification( devicetype, devicetoken, alert, userid, action, profilepic, image, youtubeimage, id ) {
if(devicetoken != "(null)") {
var androidApiKey = '', cert = '', key = '', passphrase = '';
if(process.env.NODE_ENV.toLowerCase() == "production") {
cert = '/../config/ios_support/apns-cert.pem';
key = '/../config/ios_support/apns-key.pem';
passphrase = '*****';
androidApiKey = "*******";
}
else {
cert = '/../config/ios_support/apns-dev-cert.pem';
key = '/../config/ios_support/apns-dev-key.pem';
passphrase = '*******';
androidApiKey = "********";
}
if(devicetype == "ios"){
var myDevice = new apn.Device(devicetoken);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert = alert;
note.category = "respond"
note.device = myDevice;
note.payload = { 'action': action, 'userid': userid, 'profilepic': profilepic, 'id':id};
console.log("note.payload: "+ JSON.stringify(note.payload));
//, 'WatchKit Simulator Actions': [{"title": "Show", "identifier": "showButtonAction"}]
var callback = function (errorNum, notification) {
console.log('Error is:.....', errorNum);
}
var options = {
gateway: 'gateway.push.apple.com',
//'gateway.sandbox.push.apple.com',
// this URL is different for Apple's Production Servers and changes when you go to production
errorCallback: callback,
cert: __dirname.split('src/')[0] + cert,
key: __dirname.split('src/')[0] + key,
passphrase: passphrase,
port: ****,
cacheLength: 100
}
var apnsConnection = new apn.Connection(options);
apnsConnection.sendNotification(note);
}
else if(devicetype == "android"){
var gcmObject = new gcm.AndroidGcm(androidApiKey);
var message = new gcm.Message({
registration_ids: [devicetoken],
data: {
body: alert,
action: action,
userid: userid,
profilepic: profilepic,
id: id
}
});
gcmObject.send(message, function(err, response) {
if(err) console.error("error: "+err);
// else console.log("response: "+response);
});
}
}
}
Here is my code. In console I'm getting all the stuff and device token is also fine. Android mobiles are getting notifications. But notifications are not sending to ios devices. I'm getting this error in console : Error is:...... 8.
One more thing is, for the same device I'm able to send the notification for other functionality with other code.
Really I'm pulling my hair out for this issue. And can't understand what's wrong with my code. Anyone please give solution for this.
You are using an old version. Apple has changed some thing in the push api last year in march i guess.
Also you forgot to set your topic which is mandetory for apn push Notifications
Try something like this for you if (devicetype == "ios") block
if(devicetype == "ios") {
var myDevice = new apn.Device(devicetoken);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert = alert;
note.category = "respond"
note.payload = {'action': action, 'userid': userid, 'profilepic': profilepic, 'id': id};
//you missed this one i guess
note.topic = "<your-app-bundle-id>";
console.log("note.payload: " + JSON.stringify(note.payload));
//, 'WatchKit Simulator Actions': [{"title": "Show", "identifier": "showButtonAction"}]
var callback = function(errorNum, notification) {
console.log('Error is:.....', errorNum);
}
var options = {
token: {
key: __dirname.split('src/')[0] + cert,
keyId: __dirname.split('src/')[0] + key,
teamId: "developer-team-id"
},
production: false // for development
};
var apnProvider = new apn.Provider(options);
apnProvider.send(note, myDevice).then( (result) => {
// see documentation for an explanation of result
console.log(result);
});
}
You can find the documentation here apn

How do I resolve: Akka.Remote.EndpointDisassociatedException?

I have some code that involves remote deploying actors onto a separate process.
I am getting: Akka.Remote.EndpointDisassociatedException
[WARNING][3/24/2017 1:54:32 PM][Thread
0008][[akka://system1/system/endpointMana
ger/reliableEndpointWriter-akka.tcp%3A%2F%2Fsystem2%40localhost%3A8080-1#1408457
663]] Association with remote system akka.tcp://system2#localhost:8080
has faile d; address is now gated for 5000 ms. Reason is:
[Akka.Remote.EndpointDisassociat edException: Disassociated at
Akka.Remote.EndpointWriter.PublishAndThrow(Exception reason, LogLevel
leve l, Boolean needToThrow) at
Akka.Actor.ReceiveActor.ExecutePartialMessageHandler(Object message,
Parti alAction1 partialAction) at
Akka.Actor.ActorCell.<>c__DisplayClass114_0.<Akka.Actor.IUntypedActorConte
xt.Become>b__0(Object m) at
Akka.Actor.ActorBase.AroundReceive(Receive receive, Object message)
at Akka.Actor.ActorCell.ReceiveMessage(Object message) at
Akka.Actor.ActorCell.AutoReceiveMessage(Envelope envelope) at
Akka.Actor.ActorCell.Invoke(Envelope envelope)] [ERROR][3/24/2017
1:54:32 PM][Thread 0008][akka://system1/system/endpointManager
/reliableEndpointWriter-akka.tcp%3A%2F%2Fsystem2%40localhost%3A8080-1/endpointWr
iter] Disassociated Cause: Akka.Remote.EndpointDisassociatedException:
Disassociated at
Akka.Remote.EndpointWriter.PublishAndThrow(Exception reason, LogLevel
leve l, Boolean needToThrow) at
Akka.Actor.ReceiveActor.ExecutePartialMessageHandler(Object message,
Parti alAction1 partialAction) at
Akka.Actor.ActorCell.<>c__DisplayClass114_0.b__0(Object m) at
Akka.Actor.ActorBase.AroundReceive(Receive receive, Object message)
at Akka.Actor.ActorCell.ReceiveMessage(Object message) at
Akka.Actor.ActorCell.AutoReceiveMessage(Envelope envelope) at
Akka.Actor.ActorCell.Invoke(Envelope envelope)
Here's the code that I execute in a separate process that triggers that error:
use system = ActorSystem.Create("system1", config)
let reply = system.ActorOf<ReplyActor>("reply")
let props1 = Props.Create(typeof<SomeActor>, [||])
let props2 = Props.Create(typeof<SomeActor>, [||])
let props3 = Props.Create(typeof<SomeActor>, [||])
let remote1 = system.ActorOf(props1.WithRouter(FromConfig.Instance), "remoteactor1")
let remote2 = system.ActorOf(props2.WithRouter(FromConfig.Instance), "remoteactor2")
let remote3 = system.ActorOf(props3.WithRouter(FromConfig.Instance), "remoteactor3")
let hashGroup = system.ActorOf(Props.Empty.WithRouter(ConsistentHashingGroup(config)))
Task.Delay(500).Wait();
let routee1 = Routee.FromActorRef(remote1);
hashGroup.Tell(new AddRoutee(routee1));
let routee2 = Routee.FromActorRef(remote2);
hashGroup.Tell(new AddRoutee(routee2));
let routee3 = Routee.FromActorRef(remote3);
hashGroup.Tell(new AddRoutee(routee3));
Task.Delay(500).Wait();
for i = 0 to 5 do
for j = 0 to 7 do
let message = new HashMessage(j, sprintf "remote message: %i" j);
hashGroup.Tell(message, reply);
Console.ReadLine() |> ignore
Here's the configuration that my remote deploy code relies on:
open Akka.Configuration
let config = ConfigurationFactory.ParseString(#"
akka {
log-config-on-start = on
stdout-loglevel = DEBUG
loglevel = DEBUG
actor {
provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
debug {
receive = on
autoreceive = on
lifecycle = on
event-stream = on
unhandled = on
}
deployment {
/localactor {
router = consistent-hashing-pool
nr-of-instances = 5
virtual-nodes-factor = 10
}
/remoteactor1 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
/remoteactor2 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
/remoteactor3 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
}
}
remote {
helios.tcp {
port = 8090
hostname = localhost
}
}
}
")
Here's the C# code that actually works that my F# implementation is based off:
var config = ConfigurationFactory.ParseString(#"
akka {
log-config-on-start = on
stdout-loglevel = DEBUG
loglevel = DEBUG
actor {
provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
debug {
receive = on
autoreceive = on
lifecycle = on
event-stream = on
unhandled = on
}
deployment {
/localactor {
router = consistent-hashing-pool
nr-of-instances = 5
virtual-nodes-factor = 10
}
/remoteactor1 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
/remoteactor2 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
/remoteactor3 {
router = consistent-hashing-pool
nr-of-instances = 5
remote = ""akka.tcp://system2#localhost:8080""
}
}
}
remote {
dot-netty.tcp {
port = 8090
hostname = localhost
}
}
}
");
using (var system = ActorSystem.Create("system1", config))
{
var reply = system.ActorOf<ReplyActor>("reply");
//create a remote deployed actor
var remote1 = system.ActorOf(Props.Create(() => new SomeActor(null, 123)).WithRouter(FromConfig.Instance), "remoteactor1");
var remote2 = system.ActorOf(Props.Create(() => new SomeActor(null, 456)).WithRouter(FromConfig.Instance), "remoteactor2");
var remote3 = system.ActorOf(Props.Create(() => new SomeActor(null, 789)).WithRouter(FromConfig.Instance), "remoteactor3");
var hashGroup = system.ActorOf(Props.Empty.WithRouter(new ConsistentHashingGroup(config)));
Task.Delay(500).Wait();
var routee1 = Routee.FromActorRef(remote1);
hashGroup.Tell(new AddRoutee(routee1));
var routee2 = Routee.FromActorRef(remote2);
hashGroup.Tell(new AddRoutee(routee2));
var routee3 = Routee.FromActorRef(remote3);
hashGroup.Tell(new AddRoutee(routee3));
Task.Delay(500).Wait();
for (var i = 0; i < 5; i++)
{
for (var j = 0; j < 7; j++)
{
var message = new SomeMessage(j, $"remote message: {j}");
hashGroup.Tell(message, reply);
}
}
Console.ReadLine();
}
}
}
}
Can anyone provide guidance on why I'm getting this exception and how I can resolve it?
Hence, the F# implementation closely mirrors the working C# implementation.
The F# code can be found on GitHub.
When you're starting your application, you may read an exact exception that causes node disassociation: Could not load file or assembly 'System1....
What you've defined in your routers configuration is remote deployment. This means, that from one system you're trying to create actors on another node and communicate with them as if they were available locally. While this is possible, there is one requirement: a destination actor system must know how to build an actor. Since your actors are defined in System1 and created in System2, which doesn't know anything about SomeActor it fails and causes actor system to disassociate.
You need to pass SomeActor class to shared assembly, available for both systems, in order for your scenario to work.

AWS iOS SDK: Sending Email via AWSSES

Does anyone have any experience using the latest Amazon AWS SDK 2.3.6 for sending an email via SES SMTP? I currently have an api key, secret, and smtp_url.
Thanks!
Just figured it out. I confess Amazon's documentation is a little dense. Hope this helps someone else!
AWSSESSendEmailRequest *awsSESSendEmailRequest = [AWSSESSendEmailRequest new];
awsSESSendEmailRequest.source = #"source#email";
AWSSESDestination *awsSESDestination = [AWSSESDestination new];
awsSESDestination.toAddresses = [NSMutableArray arrayWithObjects:#"to#email",nil];
awsSESSendEmailRequest.destination = awsSESDestination;
AWSSESMessage *awsSESMessage = [AWSSESMessage new];
AWSSESContent *awsSESSubject = [AWSSESContent new];
awsSESSubject.data = #"Subject goes here";
awsSESSubject.charset = #"UTF-8";
awsSESMessage.subject = awsSESSubject;
AWSSESContent *awsSESContent = [AWSSESContent new];
awsSESContent.data = #"Message goes here";
awsSESContent.charset = #"UTF-8";
AWSSESBody *awsSESBody = [AWSSESBody new];
awsSESBody.text = awsSESContent;
awsSESMessage.body = awsSESBody;
awsSESSendEmailRequest.message = awsSESMessage;
AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc] initWithAccessKey:#"ACCESS-KEY"
secretKey:#"SECRET-KEY"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSWest2
credentialsProvider:credentialsProvider];
[AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
[[AWSSES defaultSES] sendEmail:awsSESSendEmailRequest completionHandler:^(AWSSESSendEmailResponse * _Nullable response, NSError * _Nullable error) {
if (error)
{
// error
}
else
{
// success
}
}];
The code snippet of Send email in Swift 3.0 below.
let serviceRegionType = AWSRegionType.usEast1
let credentialsProvider = AWSStaticCredentialsProvider.init(accessKey: "access", secretKey: "secret")
let configuration = AWSServiceConfiguration(region: serviceRegionType, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let subject = AWSSESContent()
subject?.data = "Subject"
subject?.charset = "UTF-8"
let messageBody = AWSSESContent()
messageBody?.data = "Sample Message body"
messageBody?.charset = "UTF-8"
let body = AWSSESBody()
body?.text = messageBody
let theMessage = AWSSESMessage()
theMessage?.subject = subject
theMessage?.body = body
let destination = AWSSESDestination()
destination?.toAddresses = ["toaddress"]
let send = AWSSESSendEmailRequest()
send?.source = "source mail"
send?.destination = destination
send?.message = theMessage
AWSSES.default().sendEmail(send!) { (response:AWSSESSendEmailResponse?, mailError: Error?) in
print(mailError?.localizedDescription)
if ((response?.messageId) != nil) {
print("Mail has delivered succesfully")
} else {
print("Mail has failed to delivered")
}
}
To add to unicornherder's answer: your code worked well for my iOS app. However, because my app users are authenticated by Cognito, I did not need your code used to set up AWSStaticCredentialsProvider. This already happens in my AppDelegate per the sample code.
I did need to give my Cognito-authorized users permission to use SES, however. This last step is accomplished by adding the permission to the authUser role.

Resources