SSL error while implementing Apple Push Notification
Asked Answered
D

5

10

I am trying to implement Apple Push Notification using python and django.

i am using following library to implement it

http://leepa.github.com/django-iphone-push/

Here is my code that create that send the message

from django.http import HttpResponse
from django.utils import simplejson
import json
from push.models import iPhone

def SendMessage(request,data):

        t = iPhone('XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX ') # 64 digit token
        t.send_message("hi") # at this line i am getting ERROR
        return HttpResponse(data,mimetype='application/javascript')

settings.py

import os
PROJECT_ROOT = '/'

# Full path to the APN Certificate / Private Key .pem
IPHONE_SANDBOX_APN_PUSH_CERT = os.path.join(PROJECT_ROOT, "apns-dev-tubeteam.pem")
IPHONE_LIVE_APN_PUSH_CERT = os.path.join(PROJECT_ROOT, "apns-dev-tubeteam.pem")

# Set this to the hostname for the outgoing push server
IPHONE_SANDBOX_APN_HOST = 'gateway.sandbox.push.apple.com'
IPHONE_LIVE_APN_HOST = 'gateway.push.apple.com'

# Set this to the hostname for the feedback server
IPHONE_SANDBOX_FEEDBACK_HOST = 'feedback.sandbox.push.apple.com'
IPHONE_LIVE_FEEDBACK_HOST = 'feedback.push.apple.com'

Error

[Errno 336265218] _ssl.c:337: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib

Can anyone please do tell me how to get rid off it.

Disposable answered 26/4, 2011 at 12:52 Comment(2)
Did you READ the error? Clearly there is a problem with your 64-digit token or your SSL certificate or both. Did you follow the instructions on setting up your certificates?Summary
Well i do have a .pem file and i have specified the path of that file now i am not aware about the setting up the certificates , can you please tell me in detailDisposable
L
15

I had the exact same problem. Turns out it was a simple error - I had a mistake in IPHONE_SANDBOX_APN_PUSH_CERT and python could not locate my certificate. Once I pointed it to the right location, it started working.

Note that you might want to double-check your certificate first using openssl command line, such as:

openssl x509 -text -in cert.pem

That will give you textual information about your certificate, its validity, etc.

Also, double-check file permissions of the certificate file (the python process must have sufficient rights to access it).

Leyden answered 24/7, 2011 at 9:46 Comment(2)
+1 "could not locate certificate". In my case, it was just a typo in the filename. Really feels like ssl.wrap_socket could throw up a simple "file not found" instead of letting the ssl error bubble upAragonite
It is also worth noting that apparently Apple might close the connection if you try to send too many push messages to unregistered devices (source: github.com/jleclanche/django-push-notifications/issues/…)Seminole
R
0

In my case, what worked for me is like below:

Use the full path like

apns = APNs(use_sandbox=True, cert_file='/usr/local/etc/cert.pem', key_file='/usr/local/etc/key.pem')

rather than

apns = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')
Rocha answered 27/4, 2018 at 6:18 Comment(0)
W
-1

my solution was that when creating my .pem file i set a blank password and assumed it meant no password. so the server was still expecting to use a password. i had to manually remove the password.

here is a little how to guide if it helps anyone:

NOTE: need to follow directions from apple’s developer website to create certificate first then export the .p12 file, by exporting the embedded private key that is created (in ‘keychain access’), NOT the actual certificate ———————————————————————————————————— ———————————————————————————————————— FOR DEVELOPMENT CERT: After getting the p12 file, it needs to be converted to the PEM format by executing this command from the terminal: $ openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns_dev.p12 $ openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns_dev.p12

If you wish to remove the passphrase execute the following: (NOTE: using a ‘blank’ password when exporting/converting, is still indeed setting a password, hence you should still execute the following if you intend to have no password) $ openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:

$ cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

———————————————————————————————————— FOR PRODUCTION CERT: After getting the p12 file, it needs to be converted to the PEM format by executing this command from the terminal: $ openssl pkcs12 -clcerts -nokeys -out apns-prod-cert.pem -in apns_prod.p12 $ openssl pkcs12 -nocerts -out apns-prod-key.pem -in apns_prod.p12

If you wish to remove the passphrase execute the following: (NOTE: using a ‘blank’ password when exporting/converting, is still indeed setting a password, hence you should still execute the following if you intend to have no password) $ openssl rsa -in apns-prod-key.pem -out apns-prod-key-noenc.pem

Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:

$ cat apns-prod-cert.pem apns-prod-key-noenc.pem > apns-prod.pem

Weir answered 2/10, 2014 at 1:10 Comment(0)
R
-2

Try to use PyAPNs from
https://github.com/simonwhitaker/PyAPNs
or
pip install apns

And be sure to fetch the APNs certificate and key from iOS provisioning portal, install and convert them to .pem files following this guide:
http://jainmarket.blogspot.com/2009/11/generate-apple-push-notification.html

This library is quite strait-forward.

Redtop answered 18/1, 2013 at 6:33 Comment(0)
P
-3

USE THIS CODE:

#!/usr/bin/python2.7

import socket
import ssl
import json
import struct
import argparse



APNS_HOST = ( 'gateway.sandbox.push.apple.com', 2195 )


class Payload:
    PAYLOAD = '{"aps":{${MESSAGE}${BADGE}${SOUND}}}'
    def __init__(self):
        pass

    def set_message(self, msg):
        if msg is None:
            self.PAYLOAD = self.PAYLOAD.replace('${MESSAGE}', '')
        else:
            self.PAYLOAD = self.PAYLOAD.replace('${MESSAGE}', '"alert":"%s",' % msg)

    def set_badge(self, num):
        if num is None:
            self.PAYLOAD = self.PAYLOAD.replace('${BADGE}', '')
        else:
            self.PAYLOAD = self.PAYLOAD.replace('${BADGE}', '"badge":%s,' % num)

    def set_sound(self, sound):
        if sound is None:
            self.PAYLOAD = self.PAYLOAD.replace('${SOUND}', '')
        else:
            self.PAYLOAD = self.PAYLOAD.replace('${SOUND}', '"sound":"%s",' % sound)

    def toString(self):
        return (self.PAYLOAD.replace('${MESSAGE}','').replace('${BADGE}','').replace('${SOUND}',''))

def connectAPNS(host, cert):
    ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = cert )
    ssl_sock.connect( APNS_HOST )
    return ssl_sock

def sendNotification(sslSock, device, message, badge, sound):
    payload = Payload()
    payload.set_message(message)
    payload.set_badge(badge)
    payload.set_sound(sound)
    payloadAsStr = payload.toString()

    format = '!BH32sH%ds' % len(payloadAsStr)
    binaryDeviceToken = device.replace(' ','').decode('hex')
    binaryNotification = struct.pack( format, 0, 32, binaryDeviceToken, len(payloadAsStr), payloadAsStr )

    print ("sending payload: ["+payloadAsStr+"] as binary to device: ["+device+"]")
    sslSock.write(binaryNotification)

def printUsageAndExit():
    print("msg2ios - Version 0.1\nmsg2IOS.py -d <device> -m <message> -s[plays sound] -b <badgeint>  -c <certBundlePath>")
    exit(1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--device')
    parser.add_argument('-m', '--message')
    parser.add_argument('-s', '--sound')
    parser.add_argument('-b', '--badge')
    parser.add_argument('-c', '--cert')
    args = parser.parse_args()

    if (args.device is None) or ((args.message is None) and (args.sound is None) and (args.badge is None)) or (args.cert is None):
        printUsageAndExit()

    sslSock = connectAPNS(APNS_HOST, args.cert)
    sendNotification(sslSock, args.device, args.message, args.badge, args.sound)
    sslSock.close()
Phrenetic answered 8/12, 2011 at 21:56 Comment(1)
Some explanation here would be helpful.Daytime

© 2022 - 2024 — McMap. All rights reserved.