setting up mbedtls for aws sdk embedded C - c

I am looking at upgrading to the latest aws sdk for embedded-c and can`t implement the openssl version as my device only supports openssl-1.0.2
Looking at using the mbedtls as transport protocol on top of pkcs11, there as some differences which I am probably missing...
This is part of the code we have used, which also is developed by the aws team for embedded-c:
#define ALPN_PROTOCOL_NAME "\x0ex-amzn-mqtt-ca"
const char * alpn[] = { ALPN_PROTOCOL_NAME, NULL };
MbedtlsPkcs11Status_t tlsStatus = MBEDTLS_PKCS11_SUCCESS;
MbedtlsPkcs11Credentials_t tlsCredentials = { 0 };
const char * alpn[] = { ALPN_PROTOCOL_NAME, NULL };
/* Set the pParams member of the network context with desired transport. */
pNetworkContext->pParams = &tlsContext;
/* Initialize credentials for establishing TLS session. */
tlsCredentials.pRootCaPath = rootCA;
tlsCredentials.pClientCertLabel = clientCRT;
tlsCredentials.pPrivateKeyLabel = clientKey;
pkcs11ret = xInitializePkcs11Session( &tlsCredentials.p11Session );
if( pkcs11ret != CKR_OK )
{
LogError( ( "Failed to initialize PKCS #11." ) );
}
/* AWS IoT requires devices to send the Server Name Indication (SNI)
* extension to the Transport Layer Security (TLS) protocol and provide
* the complete endpoint address in the host_name field. Details about
* SNI for AWS IoT can be found in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/transport-security.html
*/
tlsCredentials.disableSni = false;
uint16_t port = AWS_IOT_MQTT_PORT;
if( port == 443 )
{
/* Pass the ALPN protocol name depending on the port being used.
* Please see more details about the ALPN protocol for AWS IoT MQTT endpoint
* in the link below.
* https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-
why-it-is-useful-and-how-it-works/
*/
tlsCredentials.pAlpnProtos = alpn;
}
bool status = false;
if( pkcs11ret != CKR_OK )
{
LE_ERROR( "Failed to initialize PKCS #11.");
status = false;
}
else
{
printf( "===SUCCESSFULLY INITIALIZED PKCS #11.===");
// Insert the claim credentials into the PKCS #11 module
status = loadClaimCredentials( tlsCredentials.p11Session,
clientCRT,
pkcs11configLABEL_CLAIM_CERTIFICATE,
clientKey,
pkcs11configLABEL_CLAIM_PRIVATE_KEY );
if( status == false )
{
printf( "Failed to provision PKCS #11 with claim credentials." );
}
else
printf( "===SUCCESSFULLY PROVISIONED PKCS #11.===");
}
/* Initialize reconnect attempts and interval */
BackoffAlgorithm_InitializeParams( &reconnectParams,
CONNECTION_RETRY_BACKOFF_BASE_MS,
CONNECTION_RETRY_MAX_BACKOFF_DELAY_MS,
CONNECTION_RETRY_MAX_ATTEMPTS );
do
{
/* Establish a TLS session with the MQTT broker. This example connects
* to the MQTT broker as specified in BROKER_ENDPOINT and BROKER_PORT at
* the top of this file. */
LE_INFO("Establishing a TLS session to %.*s:%d.",
BROKER_ENDPOINT_LENGTH,
BROKER_ENDPOINT,
AWS_IOT_MQTT_PORT );
tlsStatus = Mbedtls_Pkcs11_Connect( pNetworkContext,
BROKER_ENDPOINT,
port,
&tlsCredentials,
TRANSPORT_SEND_RECV_TIMEOUT_MS );
}
This will always fails due to invalid certificates, but I am using those already and they are all valid, so I am thinking this has something to do with the way we load the certificates in the handler "tlsCredentials.p11Session" and I am probably missing something and not loading everything?
This is the log I get:
mqttClientAws.c connectToServerWithBackoffRetries() 654 | ===SUCCESSFULLY INITIALIZED PKCS #11.===
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:483] Successfully found object class attribute.^M
mqttClientAws[5879] | [INFO] [PKCS11] [core_pkcs11_mbedtls.c:2823] Creating a 0x3 type object.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:2057] Successfully found the key type in the template.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:2086] Successfully found the label in the template.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:1259] Key was private type.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:1268] Received RSA key type.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:1288] Allocating a 1200 bytes sized buffer to write the key to.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_pal_utils.c:123] Converted Device Priv TLS Key to corePKCS11_Key.dat^M
mqttClientAws[5879] | Successfully wrote 1192 to corePKCS11_Key.dat[DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:3352] Search parameters other than label are ignored.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:3446] Could not find the object handle in the list. Trying to search PKCS #11 PAL for object.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_pal_utils.c:123] Converted Device Cert to corePKCS11_Certificate.dat^M
mqttClientAws[5879] | [INFO] [PKCS11] [core_pkcs11_pal.c:63] Could not open corePKCS11_Certificate.dat for reading.^M
mqttClientAws[5879] | [ERROR] [PKCS11] [core_pkcs11.c:370] xFindObjectWithLabelAndClass ERROR CK_INVALID_HANDLE^M
mqttClientAws[5879] | [INFO] [FLEET_PROVISIONING_DEMO] [pkcs11_operations.c:770] Writing certificate into label "Device Cert".^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:483] Successfully found object class attribute.^M
mqttClientAws[5879] | [INFO] [PKCS11] [core_pkcs11_mbedtls.c:2823] Creating a 0x1 type object.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_pal_utils.c:123] Converted Device Cert to corePKCS11_Certificate.dat^M
mqttClientAws[5879]/mqttClientAwsComponent T=main | mqttClientAws.c connectToServerWithBackoffRetries() 668 | ===SUCCESSFULLY PROVISIONED PKCS #11.===
mqttClientAws.c connectToServerWithBackoffRetries() 686 | Establishing a TLS session to axxxxxx-ats.iot.ap-southeast-2.amazonaws.com:443.
mqttClientAws[5879] | Successfully wrote 861 to corePKCS11_Certificate.dat[DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:3352] Search parameters other than label are ignored.^M
mqttClientAws[5879] | [DEBUG] [PKCS11] [core_pkcs11_mbedtls.c:3352] Search parameters other than label are ignored.^M
mqttClientAws[5879] | [ERROR] [PKCS11] [core_pkcs11.c:370] xFindObjectWithLabelAndClass ERROR CK_INVALID_HANDLE^M
mqttClientAws[5879] | [ERROR] [Transport_MbedTLS_PKCS11] [mbedtls_pkcs11_posix.c:625] Function returned ERROR.^M
mqttClientAws[5879] | [ERROR] [Transport_MbedTLS_PKCS11] [mbedtls_pkcs11_posix.c:400] Failed to setup key handling by PKCS #11.^M
mqttClientAws[5879] | [WARN] [DEMO] [mqttClientAws.c:724] Connection to the broker failed. Retrying connection after 270 ms backoff.^M
Very much appreciated any help on this.

So the answer and also a commit to the aws sdk, when using the mbdetls the alpn should be indicated as follow: (remove the \x0e character:
#define ALPN_PROTOCOL_NAME "\x-amzn-mqtt-ca"
While the \x0e is necessary when using openssl.

Related

Winsock Bluetooth get socket handle of active connection

So I am trying to monitor the traffic of an active Bluetooth connection on my PC. I am able to get get several information about the active connection to the remote device, e.g. SOCKADDR_BTH. I thought I could use the port information of the remote device and bind a socket to it in order to monitor the traffic, but the device discovery is not providing the port information, see below:
Device name:WH-1000XM2
Device connected: 65536
Device remembered: 1
Device authenticated: 1
Remote Bluetooth device is 0x702605aba41d, server channel = 0
Local Bluetooth device is 0x84ef18b8460a, server channel = 0
Here is the corresponding code spinet:
/*Preparing the queryset return buffer*/
pwsaResults = (LPWSAQUERYSET)buffer;
pwsaResults->dwNameSpace = NS_BTH;
pwsaResults->dwSize = sizeof(WSAQUERYSET);
BTH_QUERY_DEVICE qDev{};
qDev.length = 1;
BLOB blb;
blb.cbSize = sizeof(BTH_QUERY_DEVICE);
blb.pBlobData = reinterpret_cast<PBYTE>(&qDev);
pwsaResults->lpBlob = &blb;
while (WSALookupServiceNext(hLookup, LUP_RETURN_ADDR | LUP_RETURN_NAME | LUP_CONTAINERS | LUP_RETURN_TYPE | LUP_RES_SERVICE | LUP_FLUSHCACH, &swSize, pwsaResults) == NO_ERROR)
{
pAddrInfo = (CSADDR_INFO*)pwsaResults->lpcsaBuffer;
pBtSockRemote = (SOCKADDR_BTH*)(pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr);
pBtSockLocal = (SOCKADDR_BTH*)(pwsaResults->lpcsaBuffer->LocalAddr.lpSockaddr);
wprintf(L"Device #:%d\n", nDevicesFound);
wprintf(L"Device name:%s\n", pwsaResults->lpszServiceInstanceName);
wprintf(L"Device connected: %d\n", (pwsaResults->dwOutputFlags & BTHNS_RESULT_DEVICE_CONNECTED));
wprintf(L"Device remembered: %d\n", (pwsaResults->dwOutputFlags & BTHNS_RESULT_DEVICE_REMEMBERED)>0);
wprintf(L"Device authenticated: %d\n", (pwsaResults->dwOutputFlags & BTHNS_RESULT_DEVICE_AUTHENTICATED)>0);
wprintf(L"Remote Bluetooth device is 0x%04x%08x, server channel = %d\n",
GET_NAP(pBtSockRemote->btAddr), GET_SAP(pBtSockRemote->btAddr), pBtSockRemote->port);
wprintf(L"Local Bluetooth device is 0x%04x%08x, server channel = %d\n",
GET_NAP(pBtSockLocal->btAddr), GET_SAP(pBtSockLocal->btAddr), pBtSockLocal->port);
nDevicesFound++;
}
I was thinking about using WSAIoctl in order to sniff the traffic.

How do I terminate an akka websocket connection from the server side?

I seem unable to terminate a websocket connection from the server side of the connection using the recommended approach of calling terminate() on the ServerBinding.
I have included code below that establishes a connection, terminates it from the server side, waits for termination, then sends messages from the client. All messages are successfully handled by the server after termination.
How do I terminate a web-socket connection from the server side?
public class AkkaWebSocketServerTerminateTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AkkaWebSocketServerTerminateTest.class);
#Test
public void clientConnectsServer_ServerGracefullyTerminatesConnection() throws ExecutionException, InterruptedException, TimeoutException {
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Http http = Http.get(system);
/* SERVER */
Flow<Message, Message, CompletionStage<Done>> serverSideHandlerFlow = Flow
.of(Message.class)
.via(WebsocketLayer.messageToStringFlow())
.map(s -> {
LOGGER.debug("handling {}", s);
return "handled " + s;
})
.map(s -> (Message) TextMessage.create(s))
.alsoToMat(Sink.ignore(), Keep.right());
CompletionStage<ServerBinding> serverBindingCompletionStage = http.bindAndHandleSync(
httpRequest -> WebSocket.handleWebSocketRequestWith(httpRequest, serverSideHandlerFlow),
ConnectHttp.toHost("localhost", 9999),
materializer);
ServerBinding serverBinding = serverBindingCompletionStage.toCompletableFuture().get(3, TimeUnit.SECONDS);// wait for binding
/* CLIENT */
Sink<Message, CompletionStage<Done>> sink
= Flow.of(Message.class)
.via(WebsocketLayer.messageToStringFlow())
.toMat(Sink.foreach(s -> LOGGER.debug("client received message: '{}'", s)), Keep.right());
CompletableFuture<SourceQueueWithComplete<String>> futureClientSideSourceQueue = new CompletableFuture<>();
Source<Message, SourceQueueWithComplete<String>> source
= Source.<String>queue(0, OverflowStrategy.backpressure())
.alsoToMat(Sink.foreach(s -> LOGGER.debug("client sending '{}'", s)), Keep.left())
.map(s -> (Message) TextMessage.create(s))
.mapMaterializedValue(sourceQueue -> {
futureClientSideSourceQueue.complete(sourceQueue);
return sourceQueue;
});
Flow<Message, Message, CompletionStage<Done>> clientFlow = Flow.fromSinkAndSourceCoupledMat(sink, source, Keep.left());
WebSocketRequest webSocketRequest
= WebSocketRequest.create("ws://localhost:9999");
Pair<CompletionStage<WebSocketUpgradeResponse>, CompletionStage<Done>> clientPair
= http.singleWebSocketRequest(webSocketRequest,
clientFlow,
materializer);
CompletionStage<WebSocketUpgradeResponse> clientSideUpgradeResponse = clientPair.first();
CompletionStage<Done> clientSideConnected = clientSideUpgradeResponse.thenApply(upgrade -> {
if (upgrade.response().status().equals(StatusCodes.SWITCHING_PROTOCOLS)) {
return Done.getInstance();
} else {
throw new RuntimeException("Connection failed: " + upgrade.response().status());
}
});
CompletionStage<Done> clientSideClosed = clientPair.second();
clientSideConnected.thenAccept(done -> {
LOGGER.debug("Client connected");
LOGGER.debug("Terminating all connections with a 1 second hard deadline");
CompletionStage<HttpTerminated> onceAllConnectionsTerminated
= serverBinding.terminate(Duration.ofSeconds(1));
serverBinding.whenTerminated().thenAccept(terminated -> {
LOGGER.debug("whenTerminated() -> terminated");
});
onceAllConnectionsTerminated.toCompletableFuture()
.thenAccept(terminated -> {
LOGGER.debug("All connections terminated.");
try {
LOGGER.debug("Waiting 5 seconds before sending messages from the client to the terminated server.");
Thread.sleep(5000); // wait 5 seconds
SourceQueueWithComplete<String> queue = futureClientSideSourceQueue.get();
queue.offer("message 1");
queue.offer("message 2");
queue.offer("message 3");
queue.offer("message 4");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
});
try {
LOGGER.debug("Waiting 15 seconds for client connection to close.");
clientSideClosed
.thenAccept(done -> LOGGER.debug("Client connection closed"))
.toCompletableFuture()
.get(15, TimeUnit.SECONDS); // wait for connection to close
} catch (InterruptedException e) {
LOGGER.error("Interrupted waiting for client connection to close", e);
} catch (TimeoutException e) {
LOGGER.error("Timeout waiting for client connection to close", e);
}
}
}
I get the following output:
[DEBUG] [10/25/2018 12:14:18.763] [main] [EventStream(akka://default)] logger log1-Logging$DefaultLogger started
[DEBUG] [10/25/2018 12:14:18.780] [main] [EventStream(akka://default)] Default Loggers started
[DEBUG] [10/25/2018 12:14:19.297] [main] [AkkaSSLConfig(akka://default)] Initializing AkkaSSLConfig extension...
[DEBUG] [10/25/2018 12:14:19.306] [main] [AkkaSSLConfig(akka://default)] buildHostnameVerifier: created hostname verifier: com.typesafe.sslconfig.ssl.DefaultHostnameVerifier#31c7528f
[DEBUG] [10/25/2018 12:14:20.343] [default-akka.actor.default-dispatcher-6]
[akka://default/system/IO-TCP/selectors/$a/0] Successfully bound to /127.0.0.1:9999
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:130 - Waiting 15 seconds for client connection to close.
[DEBUG] [10/25/2018 12:14:20.479] [default-akka.actor.default-dispatcher-4]
[akka://default/system/IO-TCP/selectors/$a/1] Resolving localhost before connecting
[DEBUG] [10/25/2018 12:14:20.496] [default-akka.actor.default-dispatcher-6]
[akka://default/system/IO-DNS] Resolution request for localhost from Actor[akka://default/system/IO-TCP/selectors/$a/1#1366663132]
[DEBUG] [10/25/2018 12:14:20.536] [default-akka.actor.default-dispatcher-6]
[akka://default/system/IO-TCP/selectors/$a/1] Attempting connection to [localhost/127.0.0.1:9999]
[DEBUG] [10/25/2018 12:14:20.537] [default-akka.actor.default-dispatcher-4]
[akka://default/system/IO-TCP/selectors/$a/0] New connection accepted
[DEBUG] [10/25/2018 12:14:20.538] [default-akka.actor.default-dispatcher-6]
[akka://default/system/IO-TCP/selectors/$a/1] Connection established to [localhost:9999]
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:104 - Client connected
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:105 - Terminating all connections with a 1 second hard deadline
[DEBUG] [10/25/2018 12:14:20.642] [default-akka.actor.default-dispatcher-13]
[akka://default/system/IO-TCP/selectors/$a/0] Unbinding endpoint /127.0.0.1:9999
[DEBUG] [10/25/2018 12:14:20.643] [default-akka.actor.default-dispatcher-13]
[akka://default/system/IO-TCP/selectors/$a/0] Unbound endpoint /127.0.0.1:9999, stopping listener
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:108 - whenTerminated() -> terminated
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:112 - All connections terminated.
2018-10-25 12:14:20 DEBUG AkkaWebSocketServerTerminateTest:114 - Waiting 5 seconds before sending messages from the client to the terminated server.
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:76 - client sending 'message 1'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:76 - client sending 'message 2'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:76 - client sending 'message 3'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:76 - client sending 'message 4'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:53 - handling message 1
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:53 - handling message 2
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:70 - client received message: 'handled message 1'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:53 - handling message 3
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:53 - handling message 4
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:70 - client received message: 'handled message 2'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:70 - client received message: 'handled message 3'
2018-10-25 12:14:25 DEBUG AkkaWebSocketServerTerminateTest:70 - client received message: 'handled message 4'
2018-10-25 12:14:35 ERROR AkkaWebSocketServerTerminateTest:138 - Timeout waiting for client connection to close
I think explicit termination is not possible but you can set akka.http.server.idle-timeout according to note from their documentation
Inactive WebSocket connections will be dropped according to the idle-timeout settings. In case you need to keep inactive connections alive, you can either tweak your idle-timeout or inject ‘keep-alive’ messages regularly.

How to fetch SSL cert subject, issuer, start date and expire date from the trust.p12 cert file

Environment - IBM websphere application server 8.5.5
File - trust.p12 and key.p12 (in trust.p12 , 20 certificates are
added)
by using openssl commnd, i can able to see complete certificate
details like below
MAC Iteration 2048 MAC verified OK PKCS7 Encrypted data:
pbeWithSHA1And40BitRC2-CBC, Iteration 2048 Certificate bag Bag
Attributes
localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
friendlyName: test-server subject=/C=US/ST=IC/L=test/O=XXX Security/OU=XXX/CN=something1 issuer=/C=US/ST=IC/L=test/O=XXX
Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE----- ... ... ...
-----END CERTIFICATE-----
Certificate bag Bag Attributes
localKeyID: XX XX XX XX XX XX XX XX
friendlyName: root subject=/C=US/ST=IC/L=test/O=XXX /OU=XXX/CN=testroot issuer=/C=US/ST=IC/L=test/O=XXX
/OU=XXXX/CN=testroot
-----BEGIN CERTIFICATE----- ... ... ...
-----END CERTIFICATE-----
But i tried to fetch subject, issuer, start date and expire date from
the trust.p12 cert file by using below commands.
1st Method
openssl pkcs12 -in trust.p12 -nokeys | openssl x509 -noout
-dates -subject -issuer -alias
2nd Method
openssl pkcs12 -in trust.p12 -out trust.pem -nodes
cat trust.pem | openssl x509 -noout -enddate
however i'm getting output for 1 certificate alone instead of 20
certificates trough above commands.
1) Is there any other way to fetch 20 certificate one by one something
like by passing alias name?
2) How to fetch subject, issuer, start date and expire date for 20 certificate one by one?
How about, if this could be done in java. You need to know the alias for all the 20 certificates and defined it as a string array.
Also you define alias as a config file so that if alias changes in future, you don't have to change the code.
static List<X509Certificate> certList = new ArrayList<>();
public static void main(String[] args) throws KeyStoreException
{
String[] alias = { "1","2"};
KeyStore keyStore = getKeyStore();
for (int i = 0; i < alias.length; i++) {
X509Certificate certFromKeyStore = (X509Certificate) keyStore.getCertificate(alias[i]);
System.out.println(certFromKeyStore.getSubjectDN());
certList.add(certFromKeyStore);
}
for (X509Certificate x509 : certList) {
// verify all the information you looking for
System.out.println(x509.getSerialNumber() + " "+ x509.getIssuerDN() );
}
}
public static KeyStore getKeyStore()
{
KeyStore keyStore = null;
try
{
keyStore = KeyStore.getInstance("PKCS12");
InputStream input = new FileInputStream("PATHTOP12");
keyStore.load(input, "YOUR_P12_PASSWORD".toCharArray());
} catch (Exception e)
{
// catch the exception
}
return keyStore;
}
Let me know if this helps.
Are you specifically looking this to be done in openssl ?

send Mail with javamail and posfix

I setup a postfix in my OS ubuntu 12.04 and i want to use it for sending a mail with javamail but doesn't work .
The error I'm getting is:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: ns303047.xxxxxxx.eu;
so this is my main.cf :
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific: Specifying a file name will cause the first
# line of that file to be used as the name. The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# SASL parameters
# ---------------------------------
# Use Dovecot to authenticate.
smtpd_sasl_type = dovecot
# Referring to /var/spool/postfix/private/auth
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =
smtpd_sasl_authenticated_header = yes
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtp_tls_security_level = may
smtpd_tls_security_level = may
#smtpd_tls_auth_only = no
smtp_tls_note_starttls_offer = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
# SMTPD parameters
# ---------------------------------
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
# will it be a permanent error or temporary
unknown_local_recipient_reject_code = 450
# how long to keep message on queue before return as failed.
# some have 3 days, I have 16 days as I am backup server for some people
# whom go on holiday with their server switched off.
maximal_queue_lifetime = 7d
# max and min time in seconds between retries if connection failed
minimal_backoff_time = 1000s
maximal_backoff_time = 8000s
# how long to wait when servers connect before receiving rest of data
smtp_helo_timeout = 60s
# how many address can be used in one message.
# effective stopper to mass spammers, accidental copy in whole address list
# but may restrict intentional mail shots.
smtpd_recipient_limit = 16
# how many error before back off.
smtpd_soft_error_limit = 3
# how many max errors before blocking it.
smtpd_hard_error_limit = 12
# This next set are important for determining who can send mail and relay mail
# to other servers. It is very important to get this right - accidentally producing
# an open relay that allows unauthenticated sending of mail is a Very Bad Thing.
#
# You are encouraged to read up on what exactly each of these options accomplish.
# Requirements for the HELO statement
smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit
# Requirements for the sender details
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
# Requirements for the connecting server
# Attention MODIFICATION de la config proposée.
# -------------------------------------------------------------
# Le serveur de blacklist dnsbl.njabl.org n'est plus en service depuis mars 2013 - Voir [[http://www.dnsbl.com/2007/03/how-well-do-various-blacklists-work.html]]
# Donc remplacer la ligne suivante
# smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl, reject_rbl_client dnsbl.njabl.org
# Par la nouvelle ligne
smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl
# Requirement for the recipient address. Note that the entry for
# "check_policy_service inet:127.0.0.1:10023" enables Postgrey.
smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit
smtpd_data_restrictions = reject_unauth_pipelining
# require proper helo at connections
smtpd_helo_required = yes
# waste spammers time before rejecting them
smtpd_delay_reject = yes
disable_vrfy_command = yes
# General host and delivery info
# ----------------------------------
myhostname = ns303047.xxxxxxxxx.eu
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = ns303047.xxxxxxxxx.eu, localhost.xxxxxxxxx.eu, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
# This specifies where the virtual mailbox folders will be located.
virtual_mailbox_base = /home/vmail
# This is for the mailbox location for each user. The domainaliases
# map allows us to make use of Postfix Admin's domain alias feature.
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf, mysql:/etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf
# and their user id
virtual_uid_maps = static:150
# and group id
virtual_gid_maps = static:1001
# This is for aliases. The domainaliases map allows us to make
# use of Postfix Admin's domain alias feature.
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf, mysql:/etc/postfix/mysql_virtual_alias_domainaliases_maps.cf
# This is for domain lookups.
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
# Integration with other packages
# ---------------------------------------
# Tell postfix to hand off mail to the definition for dovecot in master.cf
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
# Use amavis for virus and spam scanning
content_filter = amavis:[127.0.0.1]:10024
# Header manipulation
# --------------------------------------
# Getting rid of unwanted headers. See: https://posluns.com/guides/header-removal/
header_checks = regexp:/etc/postfix/header_checks
# getting rid of x-original-to
enable_original_recipient = no
and this is my code java
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "ns303047.xxxxxxxxx.eu");
props.put("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("dak#ns303047.xxxxxxxxx","mypass");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#no-spam.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("dev#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Any pointers or thoughts would help.
Thanks
I just tried to send you an test message, this is what your server says:
Trying xx.xx.204.16...
Connected to xxxxx.eu.
Escape character is '^]'.
220 xxxxxx.eu ESMTP Postfix (Ubuntu)
EHLO mail.wf-hosting.de
250-xxxxxxx
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
MAIL FROM: <bratkartoffel#stackoverflow.com>
250 2.1.0 Ok
RCPT TO: dak#xxxxxxx.eu
451 4.3.5 Server configuration problem
What says your /var/log/mail.log?
i find that
Jun 4 14:20:11 ns303047 postfix/smtpd[15379]: connect from obelix.wf-hosting.de[91.121.90.6]
Jun 4 14:20:58 ns303047 postfix/trivial-rewrite[15384]: warning: do not list domain ns303047.ip-94-23-204.eu in BOTH mydestination and virtual_mailbox_domains
Jun 4 14:20:58 ns303047 postfix/smtpd[15379]: warning: connect to 127.0.0.1:10023: Connection refused
Jun 4 14:20:58 ns303047 postfix/smtpd[15379]: warning: problem talking to server 127.0.0.1:10023: Connection refused
Jun 4 14:20:59 ns303047 postfix/smtpd[15379]: warning: connect to 127.0.0.1:10023: Connection refused
Jun 4 14:20:59 ns303047 postfix/smtpd[15379]: warning: problem talking to server 127.0.0.1:10023: Connection refused
Jun 4 14:20:59 ns303047 postfix/smtpd[15379]: NOQUEUE: reject: RCPT from obelix.wf-hosting.de[91.121.90.6]: 451 4.3.5 Server configuration problem; from=<bratkartoffel#stackoverflow.com> to=<dak#ns303047.ip-94-23-204.eu> proto=ESMTP helo=<obelix.wf-hosting.de>
Jun 4 14:21:12 ns303047 postfix/smtpd[15379]: disconnect from obelix.wf-hosting.de[91.121.90.6]
Jun 4 14:24:32 ns303047 postfix/anvil[15381]: statistics: max connection rate 1/60s for (smtp:91.121.90.6) at Jun 4 14:20:11
Jun 4 14:24:32 ns303047 postfix/anvil[15381]: statistics: max connection count 1 for (smtp:91.121.90.6) at Jun 4 14:20:11
Jun 4 14:24:32 ns303047 postfix/anvil[15381]: statistics: max cache size 1 at Jun 4 14:20:11

openssl Diffie Hellman public key to pem

I'm buiding a system using openssl.
We're going to use Diffie Hellman to share information between parties.
I had been able to create a DH using openssl.
Now I want to send the public key to the client using PEM format but I cannot find any function to convert DH public key to PEM format.
Anyone knows how to do this conversion?
Here you have the code I use to generate the DH structure:
BIGNUM * p = NULL, * g = NULL;
//Create DH MOD Group
DH * dh = dh_new_group14();
if (!dh)
puts("DH_new failed");
//Check everything is OK
int codes = 0;
if (!DH_check(dh, &codes))
puts("DH_check failed");
//Generate DH key
if (!DH_generate_key(dh))
puts("DH_generate_key failed");
I'm also capable of building a ASN1_INTEGER structure, but again I cannot find any function to generate the PEM from this structure.
Ok, I think I'm getting close.
I've managed to get an example with Java and what it generates is:
SEQUENCE {
SEQUENCE {
OBJECTIDENTIFIER 1.2.840.113549.1.3.1
SEQUENCE {
INTEGER 0x00ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff
INTEGER 0x02 (2 decimal)
}
}
BITSTRING 0x0282010100b9c13521bc982e69de3e139d2521f32187ca932fdb579344c37cf2a8effb1c589ac27446656c911aefb84c961be5c389cabae7012b9edbec439ce5b57df4ad427e8baaa334c18c8bbf0fc3b19b197d484ae174f3fb538183368cdb11ecc228fc3fbb0029ff9aa0c06ccebbba47c1d1208410e9506cc08ae3bdc71924e95ae74994268822637ad628af95cf8b09cba0e070c7a8126921f6a700792ef45d844b8812f4d67f19bbc809ad33ac1ea59f4e3a9542e26b3a5f1738de6b9f8092c5a323747a716f39a17f879b87981c00944c8e5fb8f1e4d5ace6c81c182f80711bc55865c8562688b7084ae42f706fb80081f9e97982ef0242df221b202cee9b9ffcaf : 0 unused bit(s)
}
But what I get using PEM_write_bio_DHparams is almost the same but without the BITSTRING and the OBJECTIDENTIFIER.
SEQUENCE {
INTEGER 0x00ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff
INTEGER 0x02 (2 decimal)
}
Any clue about where's the problem?
I've seen that Java version generates a X.509 certificate to send the data, maybe I should generate a X509 certificate from the DH on my c++ version?
I think public keys are stored not alone but inside certificate request (csr) or certificate. So, you can use either PEM_write_bio_X509_REQ() or PEM_write_bio_X509() to store them in PEM format. Results will:
Certificate Request:
Data:
Version: 0 (0x0)
Subject: CN=DH Server Certificate (DSA-signed)
Subject Public Key Info:
Public Key Algorithm: dhKeyAgreement
PKCS#3 DH Public-Key: (1024 bit)
public-key:
00:ad:0c:c3:73:26:1b:68:2e:b2:1f:36:0c:eb:3c:
0b:bb:62:b2:fd:ac:8a:92:97:b9:79:6f:1a:f9:2e:
20:21:ff:fd:c4:e2:70:2a:62:ad:62:fc:67:d8:33:
58:09:19:8f:92:a3:b8:5b:41:30:d7:a9:b9:49:01:
07:24:76:ec:f9:88:e6:58:4e:a7:21:83:a4:a8:18:
4e:9a:ca:c5:14:04:9d:85:65:ee:7b:6a:59:80:af:
5e:fd:56:34:3e:95:34:14:64:0c:99:2e:c7:cc:4d:
9f:60:0f:a2:18:60:80:fe:6f:ed:4a:45:f3:4e:49:
97:42:a2:ec:86:c4:fd:5e:e9
prime:
00:e6:7f:e7:4b:4c:5a:55:bf:5e:2d:42:5d:17:62:
f0:6f:ff:d2:55:3f:18:a1:9e:51:02:34:ac:2b:64:
1b:c6:07:5f:ea:02:4f:f0:31:ed:71:ad:06:21:47:
4b:36:2a:65:a0:2a:dc:fb:3a:6f:24:6f:fc:4a:67:
0a:50:eb:6d:73:a3:35:fd:6a:d8:2d:68:b4:f2:c5:
c1:0b:6e:a1:5a:49:47:d6:bc:ab:9c:3f:d2:7a:7b:
2a:cf:be:2b:34:7e:0c:4f:00:0d:20:3e:83:6e:f3:
6c:65:f6:f0:f5:2a:5d:5f:1a:f2:c1:86:b6:0c:44:
19:1e:b0:66:ee:ea:eb:83:73
generator: 2 (0x2)
Attributes:
a0:00
Signature Algorithm: itu-t
-----BEGIN CERTIFICATE REQUEST-----
MIIBZDCCAVgCAQAwLTErMCkGA1UEAxMiREggU2VydmVyIENlcnRpZmljYXRlIChE
U0Etc2lnbmVkKTCCASAwgZUGCSqGSIb3DQEDATCBhwKBgQDmf+dLTFpVv14tQl0X
YvBv/9JVPxihnlECNKwrZBvGB1/qAk/wMe1xrQYhR0s2KmWgKtz7Om8kb/xKZwpQ
621zozX9atgtaLTyxcELbqFaSUfWvKucP9J6eyrPvis0fgxPAA0gPoNu82xl9vD1
Kl1fGvLBhrYMRBkesGbu6uuDcwIBAgOBhQACgYEArQzDcyYbaC6yHzYM6zwLu2Ky
/ayKkpe5eW8a+S4gIf/9xOJwKmKtYvxn2DNYCRmPkqO4W0Ew16m5SQEHJHbs+Yjm
WE6nIYOkqBhOmsrFFASdhWXue2pZgK9e/VY0PpU0FGQMmS7HzE2fYA+iGGCA/m/t
SkXzTkmXQqLshsT9XumgADADBgEAAwEA
-----END CERTIFICATE REQUEST-----
and
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 1407830109 (0x53e9c85d)
Signature Algorithm: dsaWithSHA1
Issuer: CN=DSA Server Certificate
Validity
Not Before: Aug 12 07:55:14 2014 GMT
Not After : Aug 9 07:55:14 2024 GMT
Subject: CN=DH Server Certificate (DSA-signed)
Subject Public Key Info:
Public Key Algorithm: dhKeyAgreement
PKCS#3 DH Public-Key: (1024 bit)
public-key:
00:ad:0c:c3:73:26:1b:68:2e:b2:1f:36:0c:eb:3c:
0b:bb:62:b2:fd:ac:8a:92:97:b9:79:6f:1a:f9:2e:
20:21:ff:fd:c4:e2:70:2a:62:ad:62:fc:67:d8:33:
58:09:19:8f:92:a3:b8:5b:41:30:d7:a9:b9:49:01:
07:24:76:ec:f9:88:e6:58:4e:a7:21:83:a4:a8:18:
4e:9a:ca:c5:14:04:9d:85:65:ee:7b:6a:59:80:af:
5e:fd:56:34:3e:95:34:14:64:0c:99:2e:c7:cc:4d:
9f:60:0f:a2:18:60:80:fe:6f:ed:4a:45:f3:4e:49:
97:42:a2:ec:86:c4:fd:5e:e9
prime:
00:e6:7f:e7:4b:4c:5a:55:bf:5e:2d:42:5d:17:62:
f0:6f:ff:d2:55:3f:18:a1:9e:51:02:34:ac:2b:64:
1b:c6:07:5f:ea:02:4f:f0:31:ed:71:ad:06:21:47:
4b:36:2a:65:a0:2a:dc:fb:3a:6f:24:6f:fc:4a:67:
0a:50:eb:6d:73:a3:35:fd:6a:d8:2d:68:b4:f2:c5:
c1:0b:6e:a1:5a:49:47:d6:bc:ab:9c:3f:d2:7a:7b:
2a:cf:be:2b:34:7e:0c:4f:00:0d:20:3e:83:6e:f3:
6c:65:f6:f0:f5:2a:5d:5f:1a:f2:c1:86:b6:0c:44:
19:1e:b0:66:ee:ea:eb:83:73
generator: 2 (0x2)
Signature Algorithm: dsaWithSHA1
r:
30:1c:1d:8a:87:b3:83:de:b2:4b:a4:1c:69:71:a1:
93:ae:1b:c0:30:0e:e0:b1:94:eb:92:da:e8:3b:12:
8c:59
s:
36:14:4c:fd:ce:a3:de:ef:6a:ac:49:45:b3:69:7d:
bf:98:72:9a:b0:6c:7b:59:bc:80:ee:96:32:a6:a3:
e8:e0
-----BEGIN CERTIFICATE-----
MIIB/zCCAacCBFPpyF0wCQYHKoZIzjgEAzAhMR8wHQYDVQQDExZEU0EgU2VydmVy
IENlcnRpZmljYXRlMB4XDTE0MDgxMjA3NTUxNFoXDTI0MDgwOTA3NTUxNFowLTEr
MCkGA1UEAxMiREggU2VydmVyIENlcnRpZmljYXRlIChEU0Etc2lnbmVkKTCCASAw
gZUGCSqGSIb3DQEDATCBhwKBgQDmf+dLTFpVv14tQl0XYvBv/9JVPxihnlECNKwr
ZBvGB1/qAk/wMe1xrQYhR0s2KmWgKtz7Om8kb/xKZwpQ621zozX9atgtaLTyxcEL
bqFaSUfWvKucP9J6eyrPvis0fgxPAA0gPoNu82xl9vD1Kl1fGvLBhrYMRBkesGbu
6uuDcwIBAgOBhQACgYEArQzDcyYbaC6yHzYM6zwLu2Ky/ayKkpe5eW8a+S4gIf/9
xOJwKmKtYvxn2DNYCRmPkqO4W0Ew16m5SQEHJHbs+YjmWE6nIYOkqBhOmsrFFASd
hWXue2pZgK9e/VY0PpU0FGQMmS7HzE2fYA+iGGCA/m/tSkXzTkmXQqLshsT9Xukw
CQYHKoZIzjgEAwNHADBEAiAwHB2Kh7OD3rJLpBxpcaGTrhvAMA7gsZTrktroOxKM
WQIgNhRM/c6j3u9qrElFs2l9v5hymrBse1m8gO6WMqaj6OA=
-----END CERTIFICATE-----
Have a look at what is done by the PEM_write_bio_DHparams() function, I think it does what you want.
[Edit: sorry, wrong function the first time]
Try this;
EVP is used for generic keys (keypairs)
BIO *b;
b = BIO_new(BIO_s_file());
BIO_set_fp(b, stdout, BIO_NOCLOSE);
EVP_PKEY *key = EVP_PKEY_new();
EVP_PKEY_assign_DH(key, DHAlice);
PEM_write_bio_PUBKEY(b, key);

Resources