Beispiel #1
0
    def login(self,pin):
        self.session = self.pkcs11.openSession(self.tokenSlot)
        self.session.login(pin=pin)
        random = ''.join(chr(i) for i in self.session.generateRandom(size=1024))
        objects = self.session.findObjects()
        my_cert = None
        privkey_id = None
        for obj in objects:
            print self.session.getAttributeValue(obj, [PyKCS11.CKA_LABEL])
            my_cert = self.FindMyCert(my_cert, obj)
            privkey_id = self.FindPrivateId(obj, privkey_id)
        self.key_id = ''.join(chr(c) for c in privkey_id[0]).encode('hex')
        self.my_cert = X509.load_cert_der_string(''.join(chr(c) for c in my_cert))
        Rand.rand_seed(random)
        #  init the OpenSSL engine and load the user cert & private key
        ssl_key = 'slot_' + str(self.tokenSlot) + '-id_' + self.key_id
        self.my_pkey = self.engine.load_private_key(ssl_key, pin)
        ctx = SSL.Context('sslv23')
        m2.ssl_ctx_use_x509(ctx.ctx,self.my_cert.x509)
        m2.ssl_ctx_use_pkey_privkey(ctx.ctx,self.my_pkey.pkey)

        if not m2.ssl_ctx_check_privkey(ctx.ctx):
            raise ValueError, 'public/private key mismatch'
        ctx.set_verify(SSL.verify_peer, 10)
        self.ssl_ctx = ctx
        print self.my_cert
        print self.my_pkey
        self.session.logout()
        print str(threading.currentThread().name)+" finished"
Beispiel #2
0
 def get_ctx(self, allow_unknown_ca=False, req_peer_cert=True, session=None):
     ctx = SSL.Context("sslv23")
     # Set certificate and private key
     m2.ssl_ctx_use_x509(ctx.ctx, self.cert.x509)
     m2.ssl_ctx_use_rsa_privkey(ctx.ctx, self.rsakey.rsa)
     if not m2.ssl_ctx_check_privkey(ctx.ctx):
         raise CryptoError('public/private key mismatch')
     # Ciphers/Options
     ctx.set_cipher_list(CIPHER_SET)
     ctx.set_options(CTX_OPTIONS)
     # CA settings
     cloc = os.path.join(global_certpath, 'cacert.root.pem')
     if ctx.load_verify_locations(cafile=cloc) != 1:
         log.error("Problem loading CA certificates")
         raise CryptoError('CA certificates not loaded')
     # Verification
     cb = mk_verify_cb(allow_unknown_ca=allow_unknown_ca)
     CTX_V_FLAGS = SSL.verify_peer
     if req_peer_cert:
         CTX_V_FLAGS |= SSL.verify_fail_if_no_peer_cert
     ctx.set_verify(CTX_V_FLAGS,3,cb)
     # Session
     if session:
         ctx.set_session_id_ctx(session)
     return ctx
def robot_init():
	
	e = Engine.load_dynamic_engine("pkcs11", "/usr/local/lib/engine_pkcs11.so")

        pk = Engine.Engine("pkcs11")
        pk.ctrl_cmd_string("MODULE_PATH", "/usr/lib/libeTPkcs11.so")
        ret = pk.init()

        print "Loading certificate DeRoberto"
        cert = e.load_certificate("30354530383037334131344144353636")
        print "Loading key ..."
        key = e.load_private_key("30354530383037334131344144353636", "indicate#2011")

	ctx = SSL.Context("sslv23")
        ctx.set_cipher_list("HIGH:!aNULL:!eNULL:@STRENGTH")
        ctx.set_session_id_ctx("foobar")
        m2.ssl_ctx_use_x509(ctx.ctx, cert.x509)
        m2.ssl_ctx_use_pkey_privkey(ctx.ctx, key.pkey)

	class SmartRedirectHandler(m2urllib2.HTTPRedirectHandler):
                def http_error_302(self, req, fp, code, msg, headers):
                        redirect = headers['Location']
                        return redirect

        opener = m2urllib2.build_opener(ctx, SmartRedirectHandler())
	return opener
Beispiel #4
0
 def get_ctx(self,
             allow_unknown_ca=False,
             req_peer_cert=True,
             session=None):
     ctx = SSL.Context("sslv23")
     # Set certificate and private key
     m2.ssl_ctx_use_x509(ctx.ctx, self.cert.x509)
     m2.ssl_ctx_use_rsa_privkey(ctx.ctx, self.rsakey.rsa)
     if not m2.ssl_ctx_check_privkey(ctx.ctx):
         raise CryptoError('public/private key mismatch')
     # Ciphers/Options
     ctx.set_cipher_list(CIPHER_SET)
     ctx.set_options(CTX_OPTIONS)
     # CA settings
     cloc = os.path.join(global_certpath, 'cacert.root.pem')
     if ctx.load_verify_locations(cafile=cloc) != 1:
         log.error("Problem loading CA certificates")
         raise CryptoError('CA certificates not loaded')
     # Verification
     cb = mk_verify_cb(allow_unknown_ca=allow_unknown_ca)
     CTX_V_FLAGS = SSL.verify_peer
     if req_peer_cert:
         CTX_V_FLAGS |= SSL.verify_fail_if_no_peer_cert
     ctx.set_verify(CTX_V_FLAGS, 3, cb)
     # Session
     if session:
         ctx.set_session_id_ctx(session)
     return ctx
Beispiel #5
0
    def _make_context(self):
        # Use False to prevent setting the crypto list which causes an NPE
        ctx = SSL.Context('sslv23', False)

        # Manually load the key and cert into the context because the helper
        # doesn't read from the smart card or handle DER-encoded certs
        m2.ssl_ctx_use_pkey_privkey(ctx.ctx, self.key._ptr())
        m2.ssl_ctx_use_x509(ctx.ctx, self.cert.x509)

        return ctx
Beispiel #6
0
 def _get_ssl_context(self, host):
     context = self._cached_ssl_context.get(host)
     if not context:
         context = SSL.Context()
         cert = self._new_certificate(host)
         pkey = self._get_shared_private_key()
         m2.ssl_ctx_use_x509(context.ctx, cert.x509)
         m2.ssl_ctx_use_pkey_privkey(context.ctx, pkey.pkey)
         self._cached_ssl_context.setdefault(host, context)
     return context
Beispiel #7
0
    def _initConnection(self, 
                        ownerCertFile=None, 
                        ownerKeyFile=None,
                        ownerPassphrase=None):
        """Initialise connection setting up SSL context and client and
        server side identity checks
        
        @type ownerCertFile: basestring
        @param ownerCertFile: client certificate and owner of credential
        to be acted on.  Can be a proxy cert + proxy's signing cert.  Cert
        and private key are not necessary for getDelegation / logon calls
        @type ownerKeyFile: basestring
        @param ownerKeyFile: client private key file
        @type ownerPassphrase: basestring
        @param ownerPassphrase: pass-phrase protecting private key if set - 
        not needed in the case of a proxy private key
        """

        # Must be version 3 for MyProxy
        context = SSL.Context(protocol='sslv3')

# SDF
#        context.load_verify_locations(cafile=self.caCertFilePath, capath='/etc/grid-security/certificates')

        if self.caCertFilePath or self.caCertDir:
            context.load_verify_locations(cafile=self.caCertFilePath,
                                          capath=self.caCertDir)


            # Stop if peer's certificate can't be verified
            context.set_allow_unknown_ca(False)
        else:
            context.set_allow_unknown_ca(True)

        from arcs.gsi import Certificate
        if ownerCertFile:
            try:
                if isinstance(ownerCertFile, Certificate):
                    m2.ssl_ctx_passphrase_callback(context.ctx, lambda *ar: ownerPassphrase)
                    m2.ssl_ctx_use_x509(context.ctx, ownerCertFile._certificate.x509)
                    m2.ssl_ctx_use_rsa_privkey(context.ctx, ownerKeyFile.rsa)
                    if not m2.ssl_ctx_check_privkey(context.ctx):
                        raise ValueError, 'public/private key mismatch'
                else:
                    context.load_cert_chain(ownerCertFile,
                                        keyfile=ownerKeyFile,
                                        callback=lambda *ar, **kw: ownerPassphrase)
            except Exception, e:
                raise MyProxyClientConfigError("Loading certificate "
                                               "and private key for SSL "
                                               "connection [also check CA "
                                               "certificate settings]: %s" % e) 
            
            # Verify peer's certificate
            context.set_verify(SSL.verify_peer, 1) 
def usage1():
    # form context by passing cert and private key content
    context = Context();
    context.set_allow_unknown_ca(False)

    cert_file = open('/opt/cisco/creds/id.cert', 'rb').read().encode('ascii')
    cert_file = X509.load_cert_string(cert_file)
    key_file = open('/opt/cisco/creds/id.cert', 'rb').read().encode('ascii') # pem-encoded pkey
    key_file = EVP.load_key_string(key_file)
    m2.ssl_ctx_use_x509(context.ctx, cert_file.x509)
    m2.ssl_ctx_use_pkey_privkey(context.ctx, key_file.pkey)

    # make server verification
    # capath should contain hash soft link to CA certifiates
    context.load_verify_info(capath='./')
    context.set_verify(SSL.verify_peer, 3)
    # context.set_verify(SSL.verify_none, 3)

    # using MyHTTPS to send request
    send_request(context)
Beispiel #9
0
    def __init__(self, use_datetime=0, pin='', key_name="01:01"):
        Transport.__init__(self, use_datetime=use_datetime)

        self.get_engine()
        cls = PKCS11Transport

        import getpass
        pin = getpass.getpass()

        self.cert = cls._pkcs11.load_certificate(key_name)
        self.key = cls._pkcs11.load_private_key(key_name, pin=pin)

        # Use False to prevent setting the crypto list which causes an NPE
        self.context = SSL.Context('tlsv1', False)

        # Manually load the key and cert into the context because the helper
        # doesn't read from the smart card or handle DER-encoded certs
        m2.ssl_ctx_use_pkey_privkey(self.context.ctx, self.key._ptr())
        m2.ssl_ctx_use_x509(self.context.ctx, self.cert._ptr())

        self.context.load_verify_locations("ca.pem", "")
        self.context.set_verify(SSL.verify_peer, 10)
        self.context.set_info_callback()
Beispiel #10
0
 def set_client_cert(self, cert):
     return m2.ssl_ctx_use_x509(self.ctx, cert.x509)