How to connect to MQTT over wss with swift? - swift

I´m using CocoaMQTT and trying to connect to a MQTT service, with the following code:
let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
//This is myHost: wss://myserver.test:9001
let mqtt = CocoaMQTT(clie.ntID: clientID, host: "myserver.test", port: 9001)
mqtt.keepAlive = 10000
mqtt.username = "username"
mqtt.password = "password"
mqtt.enableSSL = true
mqtt.delegate = self
mqtt.connect()
mqtt.autoReconnect = true
I get the error: Error Domain=GCDAsyncSocketErrorDomain Code=7 "Socket closed by remote peer" UserInfo={NSLocalizedDescription=Socket closed by remote peer}
Does CocoaMQTT support wss or only tcp? If it doesnt support, is there any other client for swift?

This is a example from CocoaMQTT. Maybe it helps.
let clientID = "CocoaMQTT-\(animal!)-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 8883)
mqtt!.username = ""
mqtt!.password = ""
mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt!.keepAlive = 60
mqtt!.delegate = self
mqtt!.enableSSL = true
let clientCertArray = getClientCertFromP12File(certName: "client-keycert", certPassword: "MySecretPassword")
var sslSettings: [String: NSObject] = [:]
sslSettings[GCDAsyncSocketManuallyEvaluateTrust as String] = NSNumber(value: true)
sslSettings[kCFStreamSSLCertificates as String] = clientCertArray
mqtt!.sslSettings = sslSettings

Related

AWS RDS for PostgreSQL Connection attempt timed out error

I created postgresql rds in aws with terraform. I'm checking from the aws console, everything seems normal. But I'm trying to connect to database with DBeaver but I can't connect. Likewise, I can't make the ssh connection for the ec2 I created, maybe there is a connection.
The terraform codes I wrote:
# postgres-db/main.tf
resource "aws_db_instance" "default" {
allocated_storage = 20
storage_type = "gp2"
engine = var.engine
engine_version = var.engine-version
instance_class = var.instance-class
db_name = var.db-name
identifier = var.identifier
username = var.username
password = var.password
port = var.port
publicly_accessible = var.publicly-accessible
db_subnet_group_name = var.db-subnet-group-name
parameter_group_name = var.parameter-group-name
vpc_security_group_ids = var.vpc-security-group-ids
apply_immediately = var.apply-immediately
skip_final_snapshot = true
}
module "service-db" {
source = "./postgres-db"
apply-immediately = true
db-name = var.service-db-name
db-subnet-group-name = data.terraform_remote_state.server.outputs.db_subnet_group
identifier = "${var.app-name}-db"
password = var.service-db-password
publicly-accessible = true # TODO: True for now, but should be false
username = var.service-db-username
vpc-security-group-ids = [data.terraform_remote_state.server.outputs.security_group_allow_internal_postgres]
}
resource "aws_security_group" "allow_internal_postgres" {
name = "allow-internal-postgres"
description = "Allow internal Postgres traffic"
vpc_id = aws_vpc.vpc.id
ingress {
from_port = 5432
to_port = 5432
protocol = "tcp"
cidr_blocks = [aws_vpc.vpc.cidr_block, "0.0.0.0/0"] # TODO: Remove public IP
}
}
In the research I did, it was written things like edit the security rules or set it to public, it seems like that anyway.
Security group inbound rules
Public accessible
How can I solve this problem can you please help?
I solved my problem by setting the subnet group to public.
module "service-db" {
source = "./postgres-db"
apply-immediately = true
db-name = var.service-db-name
db-subnet-group-name = data.terraform_remote_state.server.outputs.db_subnet_group_public
identifier = "${var.app-name}-db"
password = var.service-db-password
publicly-accessible = true # TODO: True for now, but should be false
username = var.service-db-username
vpc-security-group-ids = [data.terraform_remote_state.server.outputs.security_group_allow_internal_postgres]
}
resource "aws_db_subnet_group" "private" {
name = "${var.server_name}-db-subnet-group-private"
subnet_ids = aws_subnet.private.*.id
tags = {
Name = "${var.server_name} DB Subnet Group Private"
}
}
resource "aws_db_subnet_group" "public" {
name = "${var.server_name}-db-subnet-group-public"
subnet_ids = aws_subnet.public.*.id
tags = {
Name = "${var.server_name} DB Subnet Group Public"
}
}

How to get the http_Listener.hostname in azure terraform

Here's my application gateway terraform template:
resource "azurerm_application_gateway" "appgw" {
name = "${var.client_name_prefix}${var.environment_name}${var.location_abr}gw${var.instance}"
resource_group_name = azurerm_resource_group.rg.name
location = var.location
enable_http2 = true
backend_http_settings {
name = "backOfficeAppHttpSetting"
cookie_based_affinity = "Disabled"
port = var.backed_port
protocol = "Http"
probe_name = "nginx-ingress-prob"
request_timeout = var.backend_request_timeout_back_office
pick_host_name_from_backend_address = false
host_name = "local.backoffice.${var.sslcert}"
affinity_cookie_name = "ApplicationGatewayAffinity"
}
http_listener {
name = "backOfficeAppListener"
frontend_ip_configuration_name = local.frontend_ip_configuration_name
frontend_port_name = local.frontend_port_443_name
protocol = "Https"
host_name = "${var.client_name}-${var.environment_name}-admin.${var.sslcert}"
require_sni = true
ssl_certificate_name = var.sslcert
}
http_listener {
name = "frontWebAppListener"
frontend_ip_configuration_name = local.frontend_ip_configuration_name
frontend_port_name = local.frontend_port_443_name
protocol = "Https"
host_name = "${var.client_name}-${var.environment_name}.${var.sslcert}"
require_sni = true
ssl_certificate_name = var.sslcert
}
}
And In key-vault.tf. I want to create to secret in which I want to save the value of first http_listener (HOSTNAME).
BUT, I'm unable to get it. Is there any way to get http_listener.host_name?
I want to know is there any way to get it.
I have tried it but i couldn't get it.

Why do I get ACCESS_REFUSED using op-rabbit but not NewMotion/Akka?

Using these parameters:
canada {
hosts = ["dd.weather.gc.ca"]
username = "anonymous"
password = "anonymous"
port = 5671
exchange = "xpublic"
queue = "q_anonymous_gsk"
routingKey = "v02.post.observations.swob-ml.#"
requestedHeartbeat = 300
ssl = true
}
I can connect to a weather service in Canada using NewMotion/Akka, but when I try op-rabbit, I get:
ACCESS_REFUSED - access to exchange 'xpublic' in vhost '/' refused for user 'anonymous'
[INFO] [foo-akka.actor.default-dispatcher-7] [akka://foo/user/$a/connection] akka://foo/user/$a/connection connected to amqp://anonymous#{dd.weather.gc.ca:5671}:5671//
[INFO] [foo-op-rabbit.default-channel-dispatcher-6] [akka://foo/user/$a/connection/$a] akka://foo/user/$a/connection/$a connected
[INFO] [foo-akka.actor.default-dispatcher-4] [akka://foo/user/$a/connection/confirmed-publisher-channel] akka://foo/user/$a/connection/confirmed-publisher-channel connected
[INFO] [foo-akka.actor.default-dispatcher-4] [akka://foo/user/$a/connection/$b] akka://foo/user/$a/connection/$b connected
[ERROR] [foo-akka.actor.default-dispatcher-3] [akka://foo/user/$a/subscription-q_anonymous_gsk-1] Connection related error while trying to re-bind a consumer to q_anonymous_gsk. Waiting in anticipating of a new channel.
...
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=403, reply-text=ACCESS_REFUSED - access to exchange 'xpublic' in vhost '/' refused for user 'anonymous', class-id=40, method-id=10)
The following works in NewMotion/Akka:
val inQueue = "q_anonymous_gsk"
val inExchange = "xpublic"
val canadaQueue = canadaChannel.queueDeclare(inQueue, false, true, false, null).getQueue
canadaChannel.queueBind(canadaQueue, inExchange, inQueue)
val consumer = new DefaultConsumer(canadaChannel) {
override def handleDelivery(consumerTag: String, envelope: Envelope, properties: BasicProperties, body: Array[Byte]) {
val s = fromBytes(body)
if (republishElsewhere) {
// ...
}
}
}
canadaChannel.basicConsume(canadaQueue, true, consumer)
but using op-rabbit like this:
val inQueue = "q_anonymous_gsk"
val inExchange = "xpublic"
val inRoutingKey = "v02.post.observations.swob-ml.#""
val rabbitCanada: ActorRef = actorSystem.actorOf(Props(classOf[RabbitControl], connParamsCanada))
def runSubscription(): SubscriptionRef = Subscription.run(rabbitCanada) {
channel(qos = 3) {
consume(topic(queue(inQueue), List(inRoutingKey))) {
(body(as[String]) & routingKey) { (msg, key) =>
ack
}
}
}
}
I get the ACCESS_REFUSED error near the top of this post. Why? How do I fix this if I want to use op-rabbit?
Have you tried to use the correct vhost with permission to anonymous user

VPN Connection with NEVPNProtocolIKEv2 - ios/swift

I have to make a VPN connection with protocol IKEv2 using a certificate.
I already have the Network Extensions entitlements.
Starting with the certificate that i'm using:
I request that certificate with an ACS request that returns me the UserCertificate in Base64 that i need to send with the VPN connection.
Example User Certificate in Base64 received:
"MIIFqTCCA5GgAwIBAgIQdwPEs5oyDHNNp7e2ZyhwADANBgkqhkiG9w0 ... N972fR4pncgdIA=="
In order to pass that certificate in the "identityData" parameter i have to convert this to Data with the PKCS12 format as i understand.
This is my conversion from Base64 to Data:
certificate = SecCertificateCreateWithData(nil, Data(base64Encoded: "Base64_String_Here")! as CFData)!
certificateData = SecCertificateCopyData(certificate!) as Data
I'm able to print the Data as NSData and i get this example:
308205a9 30820391 a0030201 02021077 03c4b39a 320c734d a7b7b667 28700030 0d06092a 864886f7 0d01010b 05003060
311c301a 06035504 030c1354 45535420 5646435a 20455043 20537562 4341310c 300a0603 55040b0c 03455043 31253023
06035504 0a0c1c56 6f646166 6f6e6520 437a6563 68205265 7075626c 69632061 2e732e31 0b300906 03550406 1302435a
301e170d 31373131 31373131 32393531 5a170d31 39313131 38313132 3935315a 30818731 43304106 03550403 0c3a3467
66693233 30303339 39303030 30313433 31403467 66692e65 70632e6d 6e633030 332e6d63 63323330 2e336770 706e6574
776f726b 2e6f7267 310c300a 06035504 0b0c0345 50433125 30230603 55040a0c 1c566f64 61666f6e 6520437a 65636820
52657075 626c6963 20612e73 2e310b30 09060355 04061302 435a3082 0122300d 06092a86 4886f70d 01010105 00038201
0f003082 010a0282 010100cc 5effc8d7 fb357559 678fb8fc 48fd3558 8af4f236 a27295a6 b484bad0 921f8077 35ddbceb
5c064492 2f9df462 2a44c4fc 85b80cfa eec6b84b b13aefa1 69e4e6b3 db8ef30b 202229c7 421bfb8f 3f47c24f 6e3f7abc
ca7d216b 31d2a02c 94c3ef6c 9d50c2ab a590d99f 5d7afddb acbcc045 53949653 97034063 404cbe00 6aaec239 b37b2ce9
5c63d126 127247a5 75446c6b fa2e2217 6706a36c a0db0630 dac90d10 00ff24a8 2f189f18 37233151 f9825f60 aa8f66e7
89d656b9 5a52d9e3 b52cb3bc 5badb801 d9ea3685 8930cb3b 490ccba0 247f4bde 00b46d5e a63b1018 4ad8a581 978f5570
82f06f7f ba60db83 abcb4391 2f221e69 14bbdc46 ce19ae95 33773f02 03010001 a3820135 30820131 30370608 2b060105
05070101 042b3029 30270608 2b060105 05073001 861b6874 74703a2f 2f6f6373 702d6570 632e766f 6461666f 6e652e63
7a301d06 03551d0e 04160414 ea45a2e8 94fe37bc 08af3fab 60f9869b 5980d3cf 30090603 551d1304 02300030 1f060355
1d230418 30168014 f3c6b0f4 961565ab 232c6060 3e16f790 f63334b1 30440603 551d2004 3d303b30 39060960 86480186
f8420108 302c302a 06082b06 01050507 0201161e 68747470 3a2f2f70 6b692e76 6f646166 6f6e652e 637a2f70 6f6c6963
792f3040 0603551d 1f043930 373035a0 33a03186 2f687474 703a2f2f 706b692e 766f6461 666f6e65 2e637a2f 63726c2f
74657374 5f766663 7a5f6570 635f6361 2e63726c 300e0603 551d0f01 01ff0404 030203f8 30130603 551d2504 0c300a06
082b0601 05050703 02300d06 092a8648 86f70d01 010b0500 03820201 004cacde 1d7b7843 43aa546c 8984e308 57a12a27
0b9a2873 2adb598d da29fe4c ee087c92 3f18bbaa 1f3ef0b9 39e18d50 db982f87 36689c03 07ab7d11 a1665bf0 f6057de5
e89fe2fe 3f9c476b 8a28749c f9d7636c 8ece6012 d0a53902 ec437171 0af85024 0963bf85 518fa150 43dc7fe8 30c42f09
62cd2a31 c38e54ba de2b8a01 6e6804b2 b66c36c1 4626fc37 65064a65 d5087412 8e541e12 51525c4c e1f4a7e2 94a31397
2806d327 7a3c65c7 50e7db59 99460ae9 a446391e 5bbce05e 1f205e1c 118cd7aa 02e9881f 75b5b40d f2aa09bc bb7abf22
b11b3e31 2f0e78ae ee497d26 ef314b1d f16008af c433a653 983db0a9 97cbbca1 5a9e8d4d 3d34ee87 858e4f3d d2c5c111
05ccdcfa b1a41afe 2624ba31 decd561a 791e97e0 197b8bfe 97ebb3ad 7b511c1d e820c83f 81cdb9ed 21d59b49 7fb0bb39
69e735e7 350af763 ab26ee3d 7e954ef7 e5c994f6 c8f104ac 4f19ed25 9855f14c 619935d6 0d9f1206 910ffe03 74c312d5
b39da039 650d9004 e2186914 cfa19052 a2e47f1c 5af90903 959ab99f 2c52a9d8 f737b59f 00cababa 0b4f7236 e9102ee4
a76ed0a0 6d827860 653d6e62 f52fcc77 d9afdc90 53d942fe 434c8901 ab2a93e8 cc7c8555 eb6a94e5 0e1cc18c 9d6c8b48
ed9204eb 623f74d2 219a5ca9 032caa7c 900ed208 b88f5fb2 5c53bcd3 e82c48f8 80450f40 f05706c1 072427cb 815e8590
4fbf5137 def67d1e 299dc81d 20
So, basically the var certificateData is the one that i'm using in the parameter "identityData".
Here is what i do in order to connect the VPN:
First i set all the parameters that are required:
vpnManager = NEVPNManager.shared()
vpnManager!.loadFromPreferences { error in
var hasProtocolConfig = false;
if #available(iOS 9, *) {
hasProtocolConfig = self.vpnManager!.protocolConfiguration != nil
} else {
hasProtocolConfig = self.vpnManager!.`protocol` != nil
}
if hasProtocolConfig == true {
let p = NEVPNProtocolIKEv2()
p.serverAddress = "X.X.X.X"
p.localIdentifier = "My_Local_Identifier"
p.remoteIdentifier = "My_Remote_Identifier"
p.identityData = certificateData
p.ikeSecurityAssociationParameters.integrityAlgorithm = NEVPNIKEv2IntegrityAlgorithm.SHA256
p.ikeSecurityAssociationParameters.encryptionAlgorithm = NEVPNIKEv2EncryptionAlgorithm.algorithmAES128
p.ikeSecurityAssociationParameters.diffieHellmanGroup = NEVPNIKEv2DiffieHellmanGroup.group14
p.serverCertificateIssuerCommonName = "My_IssuerCommonName"
p.serverCertificateCommonName = "My_CommonName"
p.authenticationMethod = NEVPNIKEAuthenticationMethod.certificate
p.useExtendedAuthentication = true
p.disconnectOnSleep = false
if #available(iOS 9, *) {
self.vpnManager.protocolConfiguration = p
} else {
self.vpnManager.`protocol` = p
}
self.vpnManager.isEnabled = true
self.vpnManager.saveToPreferences { error in
if let e = error{
print("[VPN] error saving: " + e.localizedDescription)
} else {
print("[VPN] vpn saved")
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.connectVPN), userInfo: nil, repeats: false)
}
return
}
Then i establish the VPN connection:
do {
try vpnManager!.connection.startVPNTunnel()
} catch let error {
print("Error starting VPN Connection \(error.localizedDescription)");
}
If i understand this well, Since i am not able to force the "Notify: EAP_ONLY_AUTHENTICATION", i have to use "NEVPNIKEAuthentication.certificate", otherwise i could set it to ".none".
The ikeAssociationParameters are the right ones as i check with the server side.
When i try to connect to the VPN i get the status:
Connecting -> Disconnected
Any ideia of what i am doing wrong with this connection?

"A stable connection to the server could not be established"

I trying to connect to Google with OAuth2. I have got access_token and user email. Here is not problem.
let singleton: Singleton = Singleton.sharedInstance
singleton.session.authType = MCOAuthType.XOAuth2 // session:IMAPSession
singleton.session.OAuth2Token = singleton.accessToken
singleton.session.username = singleton.email
singleton.session.hostname = "imap.gmail.ru"
singleton.session.port = 993
singleton.session.connectionType = MCOConnectionType.StartTLS
Next step i create fetch operation and get an error
let requestKind = MCOIMAPMessagesRequestKind.Headers | MCOIMAPMessagesRequestKind.Flags | MCOIMAPMessagesRequestKind.Structure
let uids = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))
let folder = "INBOX"
let fetchOperation = singleton.session.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)
fetchOperation.start { (error, fetchedMessages, vanishedMessages) -> Void in
if (error != nil)
{
println("Error: \(error)") // this line return me error
}
Error: Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established." UserInfo=0x7f9e260036b0 {NSLocalizedDescription=A stable connection to the server could not be established.}
Error: Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established." UserInfo=0x7f9e23c46c00 {NSLocalizedDescription=A stable connection to the server could not be established.}
what could be the problem?
Here's the working code guys:
var smtpSession = MCOSMTPSession()
smtpSession.hostname = "xxxxxxxx"
smtpSession.username = "xxxxxxx"
smtpSession.password = "xxxxxxxx"
smtpSession.port = 8465
smtpSession.authType = MCOAuthType.SASLPlain
smtpSession.connectionType = MCOConnectionType.TLS
smtpSession.connectionLogger = {(connectionID, type, data) in
if data != nil {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
NSLog("Connectionlogger: \(string)")
}
}
}
var builder = MCOMessageBuilder()
builder.header.to = [MCOAddress(displayName: "Rool", mailbox: "xxxxxxx#hxxxx.com")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "xxxxxx#sxxxxxx.com")
builder.header.subject = "My message"
builder.htmlBody = "<h3>This is a test message!</h3>"
let rfc822Data = builder.data()
let sendOperation = smtpSession.sendOperationWithData(rfc822Data)
sendOperation.start { (error) -> Void in
if (error != nil) {
NSLog("Error sending email: \(error)")
} else {
NSLog("Successfully sent email!")
}
}
PS: I used this code for SMTP2GO and It's working flawlessly, just make sure you're using the right port.