Giter VIP home page Giter VIP logo

bluesslservice's Introduction

Kitura

A Swift Web Framework and HTTP Server

Docs Build Status - Master macOS Linux Apache 2 codecov codebeat badge Slack Status

Summary

Kitura is a web framework and web server that is created for web services written in Swift. For more information, visit www.kitura.dev.

Table of Contents

Features

  • URL routing (e.g., GET, POST, PUT, DELETE, PATCH)
  • Codable routing
  • URL parameters
  • Static file serving
  • FastCGI support
  • SSL/TLS support
  • Pluggable middleware

Getting Started

Visit https://www.kitura.dev for a Getting Started guide, tutorials, and API reference documentation.

Contributing to Kitura

All improvements to Kitura are very welcome! Here's how to get started with developing Kitura itself.

  1. Clone this repository.

$ git clone https://github.com/Kitura/Kitura

  1. Build and run tests.

$ swift test

You can find more info on contributing to Kitura in our contributing guidelines.

Notes

  • Swift-NIO is now the default network engine via the Kitura-NIO package. If for some reason you require the old Kitura-net package, you can still enable it by setting an environment variable KITURA_NIO=0 during build.
  • Most Kitura packages have been updated to require at least Swift 5.2 in order to maintain backward compatibility.

Community

We love to talk server-side Swift, and Kitura. Join our Slack to meet the team!

bluesslservice's People

Contributors

bdhernand avatar billabt avatar dannys42 avatar djones6 avatar helenmasters avatar ianpartridge avatar kkieffer avatar kyemaloy97 avatar mbarnach avatar nethraravindran avatar niklassaers avatar quanvo87 avatar saihemak avatar shihabmehboob avatar ymesika avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bluesslservice's Issues

Which key/cert is which?

this is not really an issue with the project but with my understanding of it.

We are trying to figure out where to get which keys and certificates.

We guess the client needs the server certificate, and the client needs its own keypair?

we are overwhelmed by the configuration possibilities and dont get the differences or advantage/disadvatage of the different methods.

Out server implementation is not made with this framework, which does not make things easier..

what is the CAcertificateFilePath/Directory and why can you set it to nil?

can we just configure with just the server cert and nil as CAcert like this?
SSLService.Configuration(withCACertificateFilePath: nil, usingCertificateFile: serverCert)

Or do i need to take this method with a clientsided generated private key and certificate? or clientsided key but server cert?
SSLService.Configuration(withCACertificateFilePath: nil, usingCertificateFile: serverCert, withKeyFile: clientPrivateKey, usingSelfSignedCerts: true)

Also in the desciption it states that .pem files are needed for all keys and certs, but i always get this error: PKCS12 file not specified.
what does this mean?

thanks in advance, i hope someone can shine a little light in my confusion

Our setup: Our server has created a self signed certificate, this certificate is available for the app to use to be able to connect to the server.
Where do i put it? is this the desired cert part?
is the CAcert the same as the server cert? since it is self signed?

what are these private keys? does the client need a keypair before connecting?

Missing documentation and example for client use

One big issue with Swift on Linux is that the the module "security" can not be used (it does not exist). Therefore URLSession can not be used with an URLDessionDelegate.

Can this client use be achieved with the BlueSSLService? So far I have only seen examples for the server side.

If this is possible it would be helpful to have an example in the documentation. In this example the BlueSSLService would be used like URLSession.dataTask to get data from a remote server via SSL.

Take TLS Certificates by string

Right now the library assumes a file that contains the certificate. It would be helpful to have the library also take a String that's Base64 encoded, as well. Bluemix users will receive a Base64 string for their certificate through the Bluemix environment variables to be used to connect with MongoDB, for instance.

Error when running via ssh on macOS

In SSLService.swift, the line

status = SecPKCS12Import(p12Data, options, &items)

will return status == 0 and items as an empty array if I ssh into a macOS system and exercise it there. If I log in via Screen Sharing an do the same exercise, it runs well.

I suspect this has to do with the keychain services not being available. I submitted a PR to make the error nicer (it resulted in an index-out-of-bounds before), but I don't know what to replace SecPKCS12Import with that doesn't require keychain services

How to connect to SSL TCP sockets using a trusted certificate (not self signed?)

I have a server to which I can connect using openssl as so:

$ openssl s_client -connect example.com:port

and it establishes fine. The certificate is issued by Digicert.

How can I connect to this socket using BlueSSLService? I am using the follow code

import Socket
import SSLService

//snip
let conf = SSLService.Configuration();
let socket = try Socket.create(family: .inet, type: .stream, proto: .tcp);
socket.delegate = try SSLService(usingConfiguration: conf)

which fails with The operation couldn’t be completed. (Socket.SSLError error 0.)

I can only find documentation for self signed certificates in the repo.

Socket does not write until data is read

On iOS, when connected with TLS, if there is a read pending (i.e., it's waiting for data), and I attempt to write data to the socket, the socket will not actually writing anything until something is read. There are no errors when writing to the socket.

The code I'm using to connect:

let configuration = SSLService.Configuration() 
socket.delegate = try SSLService(usingConfiguration: configuration)
try socket.connect(to: "...", port: 1337)

Everything works fine if I don't connect with TLS. I tried other libraries and this doesn't occur, so it seems to be an issue with BlueSSLService (and not the server).

BlueSSLService cannot be cross-compiled

BlueSSLService uses #if os(...) in the Package.swift file which prevents it from being cross-compiled because that makes the assumption that the Package.swift is executed on the same OS as the resulting binaries will be which isn't true for cross-compilation.

I know this is to make it compatible with macOS without installing Open/LibreSSL using homebrew on macOS and I don't know if there's a full solution to get it to properly work with SwiftPM. There might be a way using conditional imports in the .swift files rather than in the Package.swift but I'm not 100% sure.

The other option is that we do something hacky and we change the

#if os(Linux)

to something like

#if CROSS_COMPILATION_TARGET_LINUX || os(Linux)

and in the cross compilation toolchain builder script we'd just add

-DCROSS_COMPILATION_TARGET_LINUX

to the extra-swiftc-flags list.

SIGPIPE when SSL clients disconnect

I'm seeing a similar issue with SSL connections to the one seen in regular (unsecured) connections in Kitura/BlueSocket#48 - when my workload driver (wrk) shuts down at the end of the testing period, Kitura almost always terminates with RC 141 (which is SIGPIPE).

Although Socket is used to create the sockets, on Linux the SO_NOSIGPIPE option is not available, so we instead set MSG_NOSIGNAL each time we write to the socket.

In the case of SSLService, writes are performed via SSL_write() which does not provide a facility to set this flag. The remaining option is to receive but ignore the SIGPIPE signal.

SSL accept hang with badly behaved connections

Detail in this Kitura issue: Kitura/Kitura#1143

An incoming connection that establishes a TCP session but then sends no data will block the server from accepting connections indefinitely.

Steps to recreate:

  • Start the server, make some SSL requests (demonstrate it is functional)
  • Connect a rogue client, eg: telnet localhost 8443 and leave it doing nothing
  • Try to make further requests. The server appears to be unresponsive

The problem seems to be that SSL_accept blocks, expecting to read the start of an SSL handshake from the client, which will never time out or allow the server to continue accepting connections. In the Kitura issue above, we block here:
https://github.com/IBM-Swift/BlueSSLService/blob/335495c857b7062ecf7e228d8e021d0f7d51c5c9/Sources/SSLService.swift#L493

App Transport Security

It looks like the Apple App Transport Security list of ciphers are not supported currently. By default App Transport Security is enabled and requires the following list of ciphers that support PFS.

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

I built a Kitura-1.6.1 service on Ubuntu-14.01 and using nmap probe I get the below list of ciphers. Trying to connect using URLSession reports a "no shared ciphers available" error.

|   TLSv1.2:
|     ciphers:
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A
|       TLS_RSA_WITH_CAMELLIA_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_CAMELLIA_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_DES_CBC_SHA (rsa 2048) - C
|       TLS_RSA_WITH_RC4_128_MD5 (rsa 2048) - C
|       TLS_RSA_WITH_RC4_128_SHA (rsa 2048) - C
|       TLS_RSA_WITH_SEED_CBC_SHA (rsa 2048) - A

I can't seem to find any stack overflow or github issues related to this. Is this a new bug or am i just missing something obvious ?

No such module 'SSLService'

Hello ,
My Application wants to user smtp service to send mail.
i have created package.swift file and add all the dependencies . It is not giving me any error.
but when i build my project . It is giving me this error : "No such module 'SSLService'" .When i try to import sslservice .
Please guide me through process .

Failing build under Linux

It is not possible to build an Kitura application under Linux using IBM`s Linux docker (Ubuntu 14.04 and Swift 4.2) when BlueSSLService is included alongside Kitura.

Interestingly enough, theres no problem on macOS, probably related to a fact that some of the Kitura packages uses OpenSSL only for Linux builds.

Output:
'OpenSSL' /root/VojacekJan/.build/checkouts/OpenSSL.git-8485872258080618489: warning: Ignoring declared target(s) 'OpenSSL' in the system package error: multiple targets named 'OpenSSL' in: OpenSSL, SSLService

Packages:
`
import PackageDescription

let package = Package(
name: "Name",
products: [
.executable(name: "Name", targets: ["Name"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/Kitura.git", from: "2.5.3"),
.package(url: "https://github.com/IBM-Swift/HeliumLogger", from: "1.7.1"),
.package(url: "https://github.com/IBM-Swift/Kitura-Session.git", from: "3.2.0"),
.package(url: "https://github.com/thevojacek/Kitura-MiniHandlebars", from: "1.2.2"),
.package(url: "https://github.com/OpenKitten/MongoKitten", from: "4.1.3"),
.package(url: "https://github.com/thevojacek/Kitura-MongoDbSessionStore", from: "0.2.2"),
.package(url: "https://github.com/IBM-Swift/Swift-JWT", from: "2.0.0"),
.package(url: "https://github.com/krzyzanowskim/CryptoSwift", from: "0.12.0")
],
targets: [
.target(
name: "Name",
dependencies: [
"Kitura",
"HeliumLogger",
"Kitura-MiniHandlebars",
"KituraSession", "MongoKitten",
"Kitura-MongoDbSessionStore",
"SwiftJWT",
"CryptoSwift"
]),
]
)
`

Any help is much appreciated.

The SSL methods are deprecated and not supported in iOS13 and Mac-catalina

'SSLClose' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLWrite' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLRead' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'serverSide' was deprecated in iOS 13.0
'clientSide' was deprecated in iOS 13.0
'SSLCreateContext' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'streamType' was deprecated in iOS 13.0
'SSLSetIOFuncs' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLSetCertificate' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLSetEnabledCiphers' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLSetConnection' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLSetSessionOption' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'breakOnServerAuth' was deprecated in iOS 13.0
'SSLHandshake' was deprecated in iOS 13.0: No longer supported. Use Network.framework.
'SSLCopyPeerTrust' was deprecated in iOS 13.0: No longer supported. Use Network.framework.

Socket reads with SSL delegate recv failing on osx and linux

Socket reads with SSL delegate recv() fails on linux and mac depending on the size of the incoming data.

It looks like it has something to do with how errSSLWouldBlock/SSL_ERROR_WANT_* is handled in SSLService recv:

#if os(Linux)
    if lastError == SSL_ERROR_WANT_READ || lastError == SSL_ERROR_WANT_WRITE {
        errno = EAGAIN
        return 0
    }
#else
    if status == errSSLWouldBlock {
        errno = EWOULDBLOCK
        return Int(errSSLWouldBlock)
    }
#endif

... but in Socket readDataIntoStorage() and readDatagramIntoStorage(), it appears to be expecting delegate.recv() to throw SSLError.retryNeeded when this happens.

It appears to fails when the data is >= 4096 bytes and

  • on linux when the data is an exact multiple of 4096 (say 4096 bytes)
  • on osx when the data is NOT an exact multiple of 4096 (say 4097 bytes)

Listener infinite loop with >= 0.12.42

With BlueSSLService >= 0.12.42, I get an infinite loop (and an unresponsive Kitura server) if I use wrk to attempt to drive load:
wrk -c1 -t1 -d1s https://localhost:8443/plaintext

Once wrk completes, the Kitura process is left burning 100% cpu. Other tools (such as curl) are also now unable to connect.

I was able to replicate this problem without using wrk, by using curl to deliberately issue a non-HTTPS request to the HTTPS port:

curl http://localhost:8443/plaintext &
curl -k https://localhost:8443/plaintext
<ctrl+C>
fg
<ctrl+C>

The infinite loop only occurs if I kill them in this order. If I were to kill the bogus (HTTP) one first, then the second (HTTPS) completes normally.

Build fail on Linux (wrong OpenSSL version?)

Ca July 10th my Linux build of BlueSSLService started to fail: "swift build" fails with:

/usr/include/openssl/bn.h:189:28: error: integer literal is too large to be represented in any integer type
# define BN_MASK (0xffffffffffffffffffffffffffffffffLL)
SSLService.swift:848:4: error: use of unresolved identifier 'SSL_CTX_setAutoECDH'
SSLService.swift:951:4: error: use of unresolved identifier 'SSL_CTX_set_alpn_select_cb_wrapper'
SSLService.swift:1156:4: error: use of unresolved identifier 'SSL_get0_alpn_selected_wrapper'

To be sure there are no out-of-date dependencies, I've run "sudo apt-get update; sudo apt-get upgrade" and rerun the build, but same error. The version of openssl is "1.0.2g-1ubuntu4.8"

Any idea why I get the error from OpenSSL and unresolved identifiers?

App gets stuck on line 1450 of SSLService.swift, if our web host doesn't send the SSL Handshake data over the socket

I use this library and BlueSocket to communicate with a Java server running on a separate machine, but I noticed something strange. When the Java server had its SSL certificates updated while the web server was still running, it wouldn't send data during the SSL handshake like it was supposed to. A restart of the server fixed the problem.

The issue, is that our client applications try to automatically log in via the server, and instead of just failing and reporting the failure to us, the apps would hang and become unresponsive until force closed, with the debugger showing us it gets stuck in SSLService.swift at line 1450, which is a read.

Is there a way to make this read timeout after say, 15 seconds? That would solve my entire issue.

Want to enable Pre-Shared Key communication using SSL Service class

Hi,
Thanks for this Awesome Library

I want to do Pre Shared Key(PSK) communication using this Library. But I don't know how do I able to achieve it? Can anyone help me with this?

let p12File = bundle!.path(forResource: "Certificate", ofType: "p12")
let config = SSLService.Configuration(withChainFilePath: p12File, withPassword: "root", usingSelfSignedCerts: true, clientAllowsSelfSignedCertificates: true, cipherSuite: nil)

Above code, I have used to do p12 communication and it works. But here nothing helper methods or function for PSK to pass. In Swift NIO Transport Services They are giving me a Parameter like TLS Options to pass when connect.

Like:

 sec_protocol_options_add_pre_shared_key(tlsOptions.securityProtocolOptions, psk as __DispatchData, psk as __DispatchData)
 sec_protocol_options_add_tls_ciphersuite(tlsOptions.securityProtocolOptions, TLS_PSK_WITH_AES_128_GCM_SHA256)
        
        do {
            try NIOTSConnectionBootstrap(group: self.group)
                .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
                .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
                .connectTimeout(TimeAmount.seconds(1))
                .tlsOptions(tlsOptions)
                .channelInitializer { channel in
                    channel.pipeline.add(handler: self.handler!)
                }.connect(host: host, port: port).wait()
        }catch(let e) {
            print("Error:\(e)")
        }

Note: In using Swift NIO Transport Services am getting an error like:

Peer disconnected during the middle of a handshake. Sending errSSLClosedNoNotify(-9816) alert
Error:connectTimeout(NIO.TimeAmount(nanoseconds: 1000000000))

How do I able to achieve the same thing in using BlueSocket SSL?

SSLRead bad certificate

Hi all. In my app, I integrate the BluseSocket library and with other ios apps, it works perfectly. Now we are trying to connect to the server from Web with WebSocket. I create a self-signed certificate with this instruction:
https://www.ibm.com/docs/en/api-connect/10.0.1.x?topic=overview-generating-self-signed-certificate-using-openssl
And now when I want to connect, I am getting an error

Error code: -9825(0x-2661), ERROR: SSLRead, code: -9825, reason: misc. bad certificate

The common name of the certificate is localhost. Anyone can help me?

EllipticCurve Ciphers Support iOS

Using EllipticCurveCiphers(for ex: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384) is not working at least on iOS. Always results in SSLHandshake Error when using CipherSuites.

let enabledCipherSuites = "C024,C02C" var config = SSLService.Configuration(withCipherSuite: enabledCipherSuites, clientAllowsSelfSignedCertificates: false) config.useDefaultCiphers = false blueSocketInstance.delegate = try SSLService(usingConfiguration: config)

If I don't set SSLService delegate on BlueSocket instance, then the SSLHandshake works. If the delegate is set with BlueSSLService(like above) then SSLHandshake fails.

Forward Secrecy & App Transport Security test fails

Attempting to deploy a website as a Kitura-based project. Running on DigitalOcean Ubuntu 16.04 with a LetsEncrypt set of certificates. Swift 4.1. OpenSSL 1.0.2g

The default cipher suite (DEFAULT:!DH) fails the Qualys SSL Report very badly, and does not support Apple's App Transport Security standards.

My modified cipher suite, ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:-LOW:-SSLv2:-SSLv3:-EXP:!kEDH, passes the test generally well except for no Forward Secrecy support, as well as Apple ATS 9 / iOS 9 | Server sent fatal alert: handshake_failure.

This is reflected by attempting to load a webpage inside of a WKWebView on iOS. When these clients attempt to load a webpage, the server gives the following error:

[ERROR] [HTTPServer.swift:217 listen(listenSocket:socketManager:)] Error initializing client connection from 162.155.251.250:31852: Error code: 336109761(0x1408A0C1), ERROR: SSL_accept, code: 336109761, reason: SSL3_GET_CLIENT_HELLO:no shared cipher

#16 seems to acknowledge a fix for this, and SSLService.swift line 856 claims to be the solution, but still no luck.

Edit: Workaround for now, FastCGI server with nginx works great.

OpenSSL v1.1.0 compatibility issues

I'm getting the following errors, on Fedora26, which uses OpenSSL v1.1.0:

/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:318:54: error: use of undeclared type 'SSL'
                public private(set) var cSSL: UnsafeMutablePointer<SSL>? = nil
                                                                   ^~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:322:49: error: use of undeclared type 'SSL_METHOD'
                public private(set) var method: UnsafePointer<SSL_METHOD>? = nil
                                                              ^~~~~~~~~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:325:57: error: use of undeclared type 'SSL_CTX'
                public private(set) var context: UnsafeMutablePointer<SSL_CTX>? = nil
                                                                      ^~~~~~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:1120:80: error: use of undeclared type 'SSL'
        private func prepareConnection(socket: Socket) throws -> UnsafeMutablePointer<SSL> {
                                                                                      ^~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:405:5: error: use of unresolved identifier 'SSL_library_init'
                                SSL_library_init()
                                ^~~~~~~~~~~~~~~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:406:5: error: use of unresolved identifier 'SSL_load_error_strings'
                                SSL_load_error_strings()
                                ^~~~~~~~~~~~~~~~~~~~~~
OpenSSL.ERR_lib_error_string:1:13: note: did you mean 'ERR_lib_error_string'?
public func ERR_lib_error_string(_ e: UInt) -> UnsafePointer<Int8>!
            ^
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:407:5: warning: 'OPENSSL_config' is deprecated
                                OPENSSL_config(nil)
                                ^
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:408:5: error: use of unresolved identifier 'OPENSSL_add_all_algorithms_conf'
                                OPENSSL_add_all_algorithms_conf()
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:415:19: error: use of unresolved identifier 'SSLv23_server_method'
                                self.method = SSLv23_server_method()
                                              ^~~~~~~~~~~~~~~~~~~~
OpenSSL.SSLv3_server_method:2:13: note: did you mean 'SSLv3_server_method'?
public func SSLv3_server_method() -> OpaquePointer!
            ^
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:419:19: error: use of unresolved identifier 'SSLv23_client_method'
                                self.method = SSLv23_client_method()
                                              ^~~~~~~~~~~~~~~~~~~~
OpenSSL.SSLv3_client_method:2:13: note: did you mean 'SSLv3_client_method'?
public func SSLv3_client_method() -> OpaquePointer!
            ^
/homer/leif/swift/Kitura/.build/checkouts/BlueSSLService.git--774207894858193348/Sources/SSLService.swift:853:27: error: use of unresolved identifier 'SSL_CTRL_OPTIONS'
                                SSL_CTX_ctrl(context, SSL_CTRL_OPTIONS, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION, nil)
                                                      ^~~~~~~~~~~~~~~~
OpenSSL.SSL_CTRL_CHAIN:1:12: note: did you mean 'SSL_CTRL_CHAIN'?
public var SSL_CTRL_CHAIN: Int32 { get }
           ^
OpenSSL.SSL_CTRL_SET_MTU:1:12: note: did you mean 'SSL_CTRL_SET_MTU'?
public var SSL_CTRL_SET_MTU: Int32 { get }
           ^
error: terminated(1): /opt/swift/usr/bin/swift-build-tool -f /homer/leif/swift/Kitura/.build/debug.yaml

Unable to fetch BlueSSLService

Using the following package.swift file:

import PackageDescription
let package = Package(
name: "project5",
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura.git",majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1)
]
)

running 'swift build' gets stuck on the following and the swift build process

Fetching https://github.com/IBM-Swift/Kitura.git
Fetching https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git
Fetching https://github.com/IBM-Swift/HeliumLogger.git
Fetching https://github.com/twostraws/SwiftGD.git
Fetching https://github.com/IBM-Swift/Kitura-net.git
Fetching https://github.com/IBM-Swift/SwiftyJSON.git
Fetching https://github.com/IBM-Swift/Kitura-TemplateEngine.git
Fetching https://github.com/IBM-Swift/LoggerAPI.git
Fetching https://github.com/IBM-Swift/BlueSocket.git
Fetching https://github.com/IBM-Swift/CCurl.git
Fetching https://github.com/IBM-Swift/BlueSSLService.git

The swift-build process then begins to consume memory and CPU usage

Problem with expired certificate

Hello,
In our project we have a standard configuration like this:
_configuration = SSLService.Configuration() _socket = try Socket.create(family: .inet6, type: .stream, proto: .tcp) _socket.delegate = try SSLService(usingConfiguration: _configuration)

and we have a problem that when the certificate on server expires our app still is sending messages. How can we check this or stop sending if we detect that certificate is corrupted?

Can we use an asymmetric key pair instead of a p12 for iOS?

I'm trying to avoid bundling the p12 with the app. For this I have created a public/private key pair,

    private var privateKey: SecKey?
    private var publicKey: SecKey?
    
    private func generateAsymmetricKeyPair() throws {
        let tag = "com.mycompany.keys.myapp".data(using: .utf8)!
        let attributes: [String: Any] =
            [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
             kSecAttrKeySizeInBits as String:      2048,
             kSecPrivateKeyAttrs as String:
                [kSecAttrIsPermanent as String:    true,
                 kSecAttrApplicationTag as String: tag],
             kSecAttrIsExtractable as String: true
        ]
        
        var error: Unmanaged<CFError>?
        guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
            throw error!.takeRetainedValue() as Error
        }
        publicKey = SecKeyCopyPublicKey(key)
        privateKey = key
    }

Is there a way to use this in BlueSSLService instead of a p12?

@niklassaers , has tried to avoid bundling the p12 sometime back,
#28

Can we use the constructor init(withCipherSuite cipherSuite: String? = nil, clientAllowsSelfSignedCertificates: Bool = true) in iOS?

According the documentation provided iOS apps require a p12 to work. Sorry for multiple questions. I'm in desperate need of help.

Client certificates

Hey guys,

I'm wondering, when using BlueSSLService as a client, I have to supply a PKCS12 file on iOS, tvOS and macOS just like I would if it was running as a server, right? Is there a way I could allow it to make one up itself either first time it runs or every time? If so, what are the major downsides to this I should keep in mind?

I'm working on Bolt Support for Theo, which uses BlueSocket with BlueSSLService as a client to connect to a Neo4j database server using the Bolt protocol over SSL. I've written code to generate the certificates on macOS and Linux, and am planning adding a build step to generate them for iOS and tvOS. But if at all possible I'd love to drop this and having it be just an option to add your own client keys. After all, I know no other something-via-SSL clients that require keys and certificates to be generated before using the client. Also, I worry that when distributing an app that contains both private key, public key and passphrase, whatever security I added by using SSL is really out the window. But while I can generate them at run-time on macOS and Linux, I don't know how I could do that on iOS and tvOS.

Cheers

Niklas

SSL client without certificate ?

Hi guys,
This is not really an issue, rather a request.
I have today a piece of code that uses CFNetwork to establish an SSL connection. I would like to make that code multi-platform, using BlueSocket and BlueSSLService.

In my current code, I don't provide any certificate for the client.
With BlueSSLService, it seems I have to provide a PKCS12 certificate chain, I have tried to generate one, but with no success up to now (I'm clearly no ssl expert).

My questions are :

  1. is the certificate-less client valid, or is it a kind of hack, made possible by CFNetwork ?
  2. is there any chance that BlueSSLService will support that kind of thing some day ? If not, is there a plan to support self-signed certificates on MacOS as well as Linux ?

Thanks for the work you are doing on those components !

Connection established, but everythings frozen

Hi

I got a connection between my server and client using a key chain, the server says the user is signed in, but the app is frozen completely.

The console just gives me..

subsystem: com.apple.securityd, category: SecError, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 2, enable_private_data: 0

but i think thats just xcode 8...

It doenst actually crash, its in some kind of frozen state.

If the server cancels the connection while "connected but frozen" i actually get a console output saying : Error code: -9806, ERROR: SSLHandshake, code: -9806, reason: errSSLClosedAbort

App still frozen

I am really out of any ideas now..
Any idea what went wrong?

EDIT: i debuged my project and came to the conclusion that the app fleezes at this spot in SSLService.swift:


private func prepareConnection(socket: Socket) throws {

..

repeat {

            status = SSLHandshake(sslContext)

        } while status == errSSLWouldBlock

...

Socket error: PKCS12 file not specified.

Hi there

I'm trying to connect and create an ssl socket using the following code snippet:
let fileCertURL = Bundle.main.url(forResource:"cert", withExtension: "pem")?.path
let fileKeyURL = Bundle.main.url(forResource:"key", withExtension: "pem")?.path
let myConfig = SSLService.Configuration(withCACertificateFilePath: nil, usingCertificateFile: fileCertURL, withKeyFile: fileKeyURL, usingSelfSignedCerts: true, cipherSuite: nil)
var socket = try Socket.create()
socket.delegate = try SSLService(usingConfiguration: myConfig)
try socket.connect(to: "******", port: ****)

But I keep getting this error:
ERROR: Socket error: PKCS12 file not specified.

I am running this code on my actual iPhone device (not macOS) and by the documentation it doesn't says that I need to add a .pkcs12 file anywhere

any help is appreciated

SecPKCS12Import bottleneck for acceptance from a listening socket

Testing Kitura with SSLService causes a significant slowdown on osx (but not on linux). On investigating, it appears that SecPKCS12Import() (that runs every time a listening socket accepts a connection and initializes it's delegate) is very expensive. If we cache and reuse the pkcs12 certs in SSLService.Configuration we get a significant performance increase.

Testing this change with wrk shows a performance improvement from about 150 Requests/sec to about 5200 Requests/sec (35x improvement). It still is much slower than without SSL (24k Requests/sec).

On linux, using OpenSSL, the performance is comparable to without SSL. So there are probably other areas of potential improvement.

I will submit a pull request with my changes.

PEM support for macOS

We need a way to use PEM strings and file paths on macOS. We currently have a Linux version: withPEMCertificateString, but a macOS version has not been implemented.

PKCS12 file not specified

I get "PKCS12 file not specified." error when trying to use SSL with my BlueSocket in iOS. Code below fails for me.

    private func setupSSL() throws {
        guard let cPath = certPath, let kPath = keyPath, let socket = listenSocket else {
            return
        }
        let config = SSLService.Configuration(withCACertificateDirectory: nil, usingCertificateFile: cPath, withKeyFile: kPath)
        do {
            socket.delegate = try SSLService(usingConfiguration: config)
        } catch {
            throw error
        }
    }

Please help.

Write to socket error

Tried to enable TLS by following sample from kitura.io in linux

but encountered this error when accesing the server

ERROR: handleWriteHelper() IncomingSocketHandler.swift line 194 - Write to socket (file descriptor 10 failed. Error number=0. Message=Success.

.

.

Compile SSLService.swift - Redefinition of module ...

Hi there,

I'm working with Kitura and after initialising the package dependecies and building the project in Xcode Version 8.3.3 (8E3004b) I got the following errors. I' happy about every hint. Thank you so much.

screen shot 2017-06-15 at 02 12 10

Documentation example showing a TLS client needed

It's possible to use BlueSSLService and BlueSocket to write a client socket that talks over TLS.

To do this you create a BlueSSLService.Configuration() passing no parameters, then create an SSLService from that, then set your socket's delegate and call connect().

It would be good to have an example in the README showing this. Currently, although it's mentioned, all the code samples involve using BlueSSLService.Configuration to load a certificate from disk.

It would be nice to have a simple example showing how BlueSSLService can be used to create a TLS client socket.

Carthage build

Hi,
I make my Cartfile

github "IBM-Swift/BlueSSLService" ~> 0.12

and do

carthage update

But the result I get is

Dependency "BlueSSLService" has no shared framework schemes

That seems fair, given that swift build doesn't build a framework, and there is no framework target in the xcodeproj. But then how do I build a BlueSocket framework with BlueSSLService included if I do not build them separately?

My motivation is that I want to make Theo available as a Carthage build, and it uses BlueSocket and BlueSSLService for its SSL Bolt connection.

Cheers

Nik

Compile 'SSLService' problem: bn.h:187:19: error: integer literal is too large to be represented in any integer type

The following problem blocked our pushing swift application to Bluemix:

STG/0
Compile Swift Module 'SSLService' (1 sources)
Mar 7, 2017 11:41:08 AM
STG/0
/tmp/app/.apt/usr/include/openssl/bn.h:187:19: error: integer literal is too large to be represented in any integer type
Mar 7, 2017 11:41:11 AM
STG/0
^
Mar 7, 2017 11:41:11 AM
STG/0
^~~~~~~~~~~~~~~~~~~~~~
Mar 7, 2017 11:41:11 AM
STG/0
SSL_CTX_ctrl(context, SSL_CTRL_SET_ECDH_AUTO, 1, nil)
Mar 7, 2017 11:41:11 AM
STG/0
#define BN_MASK (0xffffffffffffffffffffffffffffffffLL)
Mar 7, 2017 11:41:11 AM
STG/0
OpenSSL.SSL_CTRL_SET_READ_AHEAD:1:12: note: did you mean 'SSL_CTRL_SET_READ_AHEAD'?
Mar 7, 2017 11:41:11 AM
STG/0
public var SSL_CTRL_SET_READ_AHEAD: Int32 { get }
Mar 7, 2017 11:41:11 AM
STG/0
^
Mar 7, 2017 11:41:11 AM
STG/0
^
Mar 7, 2017 11:41:11 AM
STG/0
public var SSL_CTRL_SET_SRP_ARG: Int32 { get }
Mar 7, 2017 11:41:11 AM
STG/0
/tmp/app/Packages/SSLService-0.12.25/Sources/SSLService.swift:817:31: error: use of unresolved identifier 'SSL_CTRL_SET_ECDH_AUTO'
Mar 7, 2017 11:41:11 AM
STG/0
OpenSSL.SSL_CTRL_SET_SRP_ARG:1:12: note: did you mean 'SSL_CTRL_SET_SRP_ARG'?
Mar 7, 2017 11:41:11 AM
STG/0
:0: error: build had 1 command failures
Mar 7, 2017 11:41:21 AM
STG/0
Failed to compile droplet
Mar 7, 2017 11:41:21 AM
STG/0
Exit status 223
Mar 7, 2017 11:41:21 AM
STG/0
Staging failed: Exited with status 223
Mar 7, 2017 11:41:21 AM
STG/0
Destroying container
Mar 7, 2017 11:41:21 AM
API/0
Failed to stage application: staging failed
Mar 7, 2017 11:41:21 AM
STG/0
swift-build: error: exit(1): /tmp/cache/swift-3.0.2/swift-3.0.2-RELEASE-ubuntu14.04/usr/bin/swift-build-tool -f /tmp/app/.build/release.yaml
Mar 7, 2017 11:41:21 AM
STG/0
Successfully destroyed container

Does not work with macOS in Terminal

After digging through the code and documentation, I learned that
SSLService.Configuration(withChainFilePath ... is the only supported method on macOS. This wasn't clear to me from the README, but this PKCS12 method is also not working for me.

When I try to connect, it gives me an error:
Error code: 2(0x2), ERROR: Could not load content of PKCS12 file

Here is my code:

let config = SSLService.Configuration(withChainFilePath: "cert/cert.pfx",
                                  withPassword: "password",
                                  usingSelfSignedCerts: true)
socket.delegate = try SSLService(usingConfiguration: config)
try socket.connect(to: "https://----", port: XXXX)

I thought it could've been my certificate so I've also tried generating PKCS12 from following this blog but gave me the same error
https://developer.ibm.com/swift/2016/09/22/securing-kitura-part-1-enabling-ssltls-on-your-swift-server/

`verifyCallback` not being called

I am using SSLService like so:

let listeningSocket = try Socket.create(family: .inet)
let configuration = ...
let sslService = try SSLService(usingConfiguration: configuration)
sslService?.skipVerification = true
sslService?.verifyCallback = { service in
    return (false, "invalid client cert")
}
listeningSocket.delegate = sslService
let newConnectionSocket = try socketConnection.acceptClientConnection()

Debugging led me to notice that neither skipVerification nor verifyCallback is being copied onto the new socket created by the last line.

This diff seems to fix it. I can open a PR but first wanted to make sure that a) I am not missing something and b) this won't have any unintended side effects.

diff --git a/Sources/SSLService/SSLService.swift b/Sources/SSLService/SSLService.swift
index f64f6fe..644a7ae 100644
--- a/Sources/SSLService/SSLService.swift
+++ b/Sources/SSLService/SSLService.swift
@@ -404,6 +404,8 @@ public class SSLService: SSLServiceDelegate {
        private init?(with source: SSLService) throws {
                
                self.configuration = source.configuration
+               self.skipVerification = source.skipVerification
+               self.verifyCallback = source.verifyCallback
                
                // Validate the config...
                try self.validate(configuration: source.configuration)

Cannot compile v0.12.25 on linux (Ubuntu 14.04).

app_1 | Compile Swift Module 'SSLService' (1 sources)
app_1 | /usr/include/openssl/bn.h:187:19: error: integer literal is too large to be represented in any integer type
app_1 | #define BN_MASK (0xffffffffffffffffffffffffffffffffLL)
app_1 | ^
app_1 | /root/Kitura-Starter/Packages/SSLService-0.12.25/Sources/SSLService.swift:817:31: error: use of unresolved identifier 'SSL_CTRL_SET_ECDH_AUTO'
app_1 | SSL_CTX_ctrl(context, SSL_CTRL_SET_ECDH_AUTO, 1, nil)
app_1 | ^~~~~~~~~~~~~~~~~~~~~~
app_1 | OpenSSL.SSL_CTRL_SET_READ_AHEAD:1:12: note: did you mean 'SSL_CTRL_SET_READ_AHEAD'?
app_1 | public var SSL_CTRL_SET_READ_AHEAD: Int32 { get }
app_1 | ^
app_1 | OpenSSL.SSL_CTRL_SET_SRP_ARG:1:12: note: did you mean 'SSL_CTRL_SET_SRP_ARG'?
app_1 | public var SSL_CTRL_SET_SRP_ARG: Int32 { get }
app_1 | ^
app_1 | :0: error: build had 1 command failures
app_1 | swift-build: error: exit(1): /root/swift-3.0.2-RELEASE-ubuntu14.04/usr/bin/swift-build-tool -f /root/Kitura-Starter/.build/debug.yaml
kiturastarter_app_1 exited with code 1
Ricardos-MacBook-Pro:Kitura-Starter olivieri$

Socket.read(...) unexpectedly returns 0

On a "blocking" client socket, Socket.read(into data: inout Data) sometimes unexpectedly returns 0, even when the remote connection has not closed (Socket.remoteConnectionClosed == false).

This only reproduces on macOS.

This only happens using SSL/TLS (BlueSSLService).

Environment

  • Client on macOS (10.14.5), using Swift 5.0.1 (Xcode 10.2.1), BlueSocket 1.0.47, BlueSSLService 1.0.47. (The client software is a Swift database driver for the PostgreSQL database.)

  • Server is a PostgreSQL database server (PostgreSQL 10.9) running on Ubuntu 18.04 LTS.

The issue reproduces in multiple client and server environments. The issue reproduces more consistently on "distant" servers (e.g. running on AWS EC2 or Linode) than on "nearby" servers (e.g. on the same LAN as the client).

(I tried to reproduce the problem with the client running against a simple standalone Swift server, but was not able to reproduce the problem that way. So I'm not able to provide code for a standalone reproducible test case.)

Analysis

The Xcode debugger was used to analyze why Socket.read(...) is returning 0.

In SSLService.swift, the function sslReadCallback(...) is the callback function for SSLRead. In line 1406, sslReadCallback(...) invokes the read(...) system call, which sometimes returns fewer bytes than requested.

(lldb) po bytesRequested
8216

(lldb) po bytesRead
4339

When this occurs, sslReadCallback(...) returns errSSLWouldBlock. When control returns to the SSLRead call site (SSLService.swift, line 687), we see:

(lldb) po status
-9803

(lldb) po errSSLWouldBlock
-9803

(lldb) po processed
0

(I suspect processed == 0 because SSLRead requires its callback to return all requested bytes before SSLRead decrypts the received message.)

SSLService.recv(...) then returns -1 with errno set to EWOULDBLOCK (line 695).

Socket.readDataIntoStore() detects this error and returns 0 (Socket.swift, line 3589).

Socket.read(...) then returns 0 (line 2772).

Potential fix

In the sslReadCallback(...) function, I changed the "read" system call to request MSG_WAITALL.

Line 1406 changed from:

    let bytesRead = read(socketfd, data, bytesRequested)

to:

    let bytesRead = recv(socketfd, data, bytesRequested, MSG_WAITALL)

MSG_WAITALL forces the socket read to block until the requested number of bytes are available (or an error occurs).

This one-line change appears to resolve this issue. However, I don't have sufficient familiarity with BlueSocket/BlueSSLService internals (or low level network programming, for that matter) to assess whether it would cause other problems.

Please let me know if there is other information I can provide.

[edited to correct typo]

Duplicate: "Unable to fetch BlueSSLService #23"

Since late last week, I've been unable to fetch BlueSSLService - or maybe something after it? I have the exact situation described at the closed issue #23: Unable to fetch BlueSSLService.

My Package.swift looks like:

import PackageDescription
let package = Package(
	name: "KituraAPI",
	targets: [],
	dependencies: [
		.Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 7),
		.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1, minor: 7),
		.Package(url: "https://github.com/IBM-Swift/Swift-SMTP.git", Version(1,1,2)),
	]
)

swift build never gets past BlueSSLService:

$ swift build
Fetching https://github.com/IBM-Swift/Kitura.git
Fetching https://github.com/IBM-Swift/HeliumLogger.git
Fetching https://github.com/IBM-Swift/Swift-SMTP.git
Fetching https://github.com/IBM-Swift/Kitura-net.git
Fetching https://github.com/IBM-Swift/SwiftyJSON.git
Fetching https://github.com/IBM-Swift/Kitura-TemplateEngine.git
Fetching https://github.com/IBM-Swift/LoggerAPI.git
Fetching https://github.com/IBM-Swift/BlueSocket.git
Fetching https://github.com/IBM-Swift/CCurl.git
Fetching https://github.com/IBM-Swift/BlueSSLService.git

The Terminal title bar keeps flashing as though something is looping. I can't tell what the text is changing between, though, if it is indeed changing...

I'm on MacOS Sierra 10.12.6, using Swift 3.1:

Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42)
Target: x86_64-apple-macosx10.9

Hmm... maybe a Target issue?

Just guessing here, as it seems others have been able to use it recently judging by the most recent issue reports...

iOS Product Target

I cannot build it for iOS because there is no such target. Every time I need to put a source file SSLService.swift into my project to make it work which is quite annoying. Below I'm enclosing command line for building it.

carthage update --platform iOS --no-use-binaries --cache-builds

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.