Beispiel #1
0
static CK_RV findObject(CK_SESSION_HANDLE hSession, CK_OBJECT_CLASS objClass, CK_CHAR* pObjLabel, CK_OBJECT_HANDLE* phObj){
    CK_RV rv = CKR_OK;

    /* This is the template used to search for the object. The C_FindObjects 
     * call matches all objects that have attributes matching all attributes 
     * within the search template.
     * 
     * The attributes in the search template are : 
     *  CKA_CLASS - Points to the objClass variable which contains the value
     *              CKO_SECRET_KEY, meaning this object is a secret key object.
     *  CKA_LABEL - Points to a char array containing what will be the label
     *              of the data object.
     *
     * The search will hit on all objects with the given class and label. Note
     * that it is possible to have multiple objects on a token with matching 
     * attributes, no matter what the attributes are. There is nothing 
     * precluding the existence of duplicate objects. In the case of duplicate
     * objects, the first one found is returned 
     */
    CK_ATTRIBUTE objectTemplate[] = 
    {
        {CKA_CLASS,         NULL,       0},
        {CKA_LABEL,         NULL,       0},
    };
    CK_SIZE templateSize = sizeof(objectTemplate) / sizeof(CK_ATTRIBUTE);

    CK_ULONG numObjectsToFind = 1;
    CK_ULONG numObjectsFound = 0;

    CK_ATTRIBUTE* pAttr = NULL;

    /* 
     * Fill out the template with the values to search for
     */

    /* First set the object class ... */
    pAttr = FindAttribute(CKA_CLASS, objectTemplate, templateSize);
    pAttr->pValue = &objClass;
    pAttr->ulValueLen = sizeof(CK_OBJECT_CLASS);

    /* Now set the label ... */
    pAttr = FindAttribute(CKA_LABEL, objectTemplate, templateSize);
    pAttr->pValue = pObjLabel;
    pAttr->ulValueLen = strlen((char*)pObjLabel);

    /* 
     * Now perform the search 
     */

    /* First initialise the search operation */
    rv = C_FindObjectsInit(hSession, objectTemplate, templateSize);
    CHECK_CK_RV_GOTO(rv, "C_FindObjectsInit", end);

    /* Search */
    rv = C_FindObjects(hSession,
                       phObj,
                       numObjectsToFind,
                       &numObjectsFound);
    CHECK_CK_RV_GOTO(rv, "C_FindObjects", end);

    /* Terminate the search */
    rv = C_FindObjectsFinal(hSession);
    CHECK_CK_RV_GOTO(rv, "C_FindObjects", end);

    /* Check to see if we found a matching object */
    if (numObjectsFound == 0)
    {
        fprintf(stderr, "Object not found.\n");
        rv = CKR_GENERAL_ERROR;
    }

end:
    return rv;
}
HRESULT Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_FindObjectEnum::FindObjects___SZARRAY_MicrosoftSPOTCryptokiCryptokiObject__I4( CLR_RT_StackFrame& stack )
{
    TINYCLR_HEADER();
    CLR_RT_HeapBlock* pThis      = stack.This();
    CLR_RT_HeapBlock* pSession   = pThis[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_FindObjectEnum::FIELD__m_session].Dereference();
    CLR_RT_HeapBlock  ref, *pRef;
    CK_SESSION_HANDLE hSession;
    CK_ULONG          cntObj     = (CK_ULONG)stack.Arg1().NumericByRef().u4;
    CK_OBJECT_HANDLE  objs[128];
    CK_OBJECT_CLASS   objType = CKO_DATA;
    CLR_INT32         i;
    CLR_RT_TypeDef_Index objIndex = g_CLR_RT_WellKnownTypes.m_CryptokiObject;
    BOOL isKey = FALSE;
    CK_ATTRIBUTE      attribs[] =
    {
        { CKA_CLASS, &objType, sizeof(objType) },
    };

    FAULT_ON_NULL(pSession);

    if(cntObj > ARRAYSIZE(objs)) TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);

    hSession = pSession[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_Session::FIELD__m_handle].NumericByRef().u4;

    CRYPTOKI_CHECK_RESULT(stack, C_FindObjects(hSession, objs, cntObj, &cntObj ));

    CRYPTOKI_CHECK_RESULT(stack, C_GetAttributeValue(hSession, objs[0], attribs, ARRAYSIZE(attribs)));

    SwapEndianAndAssignIfBEc32(objType, objType);
    
    switch(objType)
    {
        case CKO_CERTIFICATE:
            objIndex = g_CLR_RT_WellKnownTypes.m_CryptokiCertificate;
            break;
    
        case CKO_PRIVATE_KEY:
        case CKO_PUBLIC_KEY:
        case CKO_SECRET_KEY:
        case CKO_OTP_KEY:
            objIndex = g_CLR_RT_WellKnownTypes.m_CryptoKey;
            isKey = TRUE;
            break;
    }

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance(ref, (CLR_UINT32)cntObj, objIndex));

    if(cntObj == 0)
    {
        stack.SetResult_Object(ref.DereferenceArray());
        TINYCLR_SET_AND_LEAVE(S_OK);
    }

    pRef = (CLR_RT_HeapBlock*)ref.DereferenceArray()->GetFirstElement();

    for(i=0; i<(INT32)cntObj; i++)
    {
        CLR_RT_HeapBlock *pObject;        

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( *pRef, objIndex ));

        pObject = pRef->Dereference();
        pObject[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_CryptokiObject::FIELD__m_handle            ].SetInteger((CLR_INT32)objs[i]);
        pObject[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_SessionContainer::FIELD__m_session         ].SetObjectReference(pSession);
        pObject[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_SessionContainer::FIELD__m_ownsSession     ].SetBoolean(false);
        pObject[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_SessionContainer::FIELD__m_isDisposed      ].SetBoolean(false);
        pObject[Library_security_pkcs11_native_Microsoft_SPOT_Cryptoki_SessionContainer::FIELD__m_isSessionClosing].SetBoolean(false);

        if(isKey)
        {
            CK_ULONG keySize = (CK_ULONG)-1;
            CK_ULONG keyType = (CK_ULONG)-1;

            CK_ATTRIBUTE attribs[] =
            {
                { CKA_VALUE_BITS, &keySize, sizeof(keySize) },
                { CKA_KEY_TYPE  , &keyType, sizeof(keyType) },
            };

            pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_keyType].NumericByRef().s4 = SwapEndianIfBEc32(keyType);

            C_GetAttributeValue(hSession, objs[i], attribs, ARRAYSIZE(attribs));
            
            pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_length].NumericByRef().u4 = SwapEndianIfBEc32(keySize);

            switch(objType)
            {
                case CKO_PRIVATE_KEY:
                    pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_privateKeyHandle].NumericByRef().u4 = objs[i];
                    break;

                case CKO_PUBLIC_KEY:
                case CKO_SECRET_KEY:
                default:
                    pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_privateKeyHandle].NumericByRef().u4 = CK_OBJECT_HANDLE_INVALID;
                    break;
            }

        }
        else if(objType == CKO_CERTIFICATE)
        {
            CK_ULONG keySize   = (CK_ULONG)-1;
            CK_ULONG keyType   = (CK_ULONG)-1;
            BOOL     isPrivate = FALSE;
            
            CK_ATTRIBUTE attribs[] = 
            {
                { CKA_VALUE_BITS, &keySize, sizeof(keySize)},
                { CKA_KEY_TYPE  , &keyType, sizeof(keyType)},
                { CKA_PRIVATE   , &isPrivate, sizeof(isPrivate)},
            };

            C_GetAttributeValue(hSession, objs[i], attribs, ARRAYSIZE(attribs));            

            pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_keyType].NumericByRef().s4 = SwapEndianIfBEc32(keyType);

            pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_length].NumericByRef().u4 = SwapEndianIfBEc32(keySize);

            if(isPrivate == TRUE)
            {
                pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_privateKeyHandle].NumericByRef().u4 = objs[i];
            }
            else
            {
                pObject[Library_security_pkcs11_native_System_Security_Cryptography_CryptoKey::FIELD__m_privateKeyHandle].NumericByRef().u4 = CK_OBJECT_HANDLE_INVALID;
            }
        }

        pRef++;
    }

    stack.SetResult_Object(ref.DereferenceArray());

    TINYCLR_NOCLEANUP();
}
int ssl_connect_internal(int sd, const char* szTargetHost, int sslContextHandle)
{
    int err = SOCK_SOCKET_ERROR;
    SSL *ssl = NULL;
    int nonblock = 0;

    // Retrieve SSL struct from g_SSL_Driver    
    if((sslContextHandle >= ARRAYSIZE(g_SSL_Driver.m_sslContextArray)) || (sslContextHandle < 0))
    {
        goto error;
    }
    
    // sd should already have been created
    // Now do the SSL negotiation   
    ssl = (SSL*)g_SSL_Driver.m_sslContextArray[sslContextHandle].SslContext;
    if (ssl == NULL) goto error;

    if (!SSL_set_fd(ssl, sd))
    {
        goto error;
    }

    if(ssl->verify_mode != SSL_VERIFY_NONE)
    {
        SSL_CTX* pCtx = SSL_get_SSL_CTX(ssl);

        if(pCtx != NULL)
        {
            X509_STORE *pStore = SSL_CTX_get_cert_store(pCtx);

            if(sk_num(&pStore->objs->stack) == 0)
            {
                CryptokiSession* pSession;
                CK_SLOT_ID  slotID;
                OBJECT_DATA* pObj;
                CK_ATTRIBUTE attribs[2];
                CK_OBJECT_CLASS cls = SwapEndianIfBEc32(CKO_CERTIFICATE);
                LPSTR label = "CA";
                CK_SESSION_HANDLE hSess;

                if(CKR_OK == C_OpenSession(0, CKF_SERIAL_SESSION, NULL, NULL, &hSess) && 
                   CKR_OK == Cryptoki_GetSlotIDFromSession(hSess, &slotID, &pSession))
                {
                    attribs[0].type = CKA_CLASS;
                    attribs[0].pValue = &cls;
                    attribs[0].ulValueLen = sizeof(cls);

                    attribs[1].type = CKA_LABEL;
                    attribs[1].pValue = label;
                    attribs[1].ulValueLen = 2;

                    if(CKR_OK == C_FindObjectsInit(hSess, attribs, ARRAYSIZE(attribs)))
                    {
                        CK_OBJECT_HANDLE hObjs[20];
                        CK_ULONG cnt = 0;

                        if(CKR_OK == C_FindObjects(hSess, hObjs, ARRAYSIZE(hObjs), &cnt) && cnt > 0)
                        {
                            for(int i=0; i<cnt; i++)
                            {
                                pObj = PKCS11_Objects_OpenSSL::GetObjectFromHandle(&pSession->Context, hObjs[i]);

                                if(pObj != NULL && pObj->Type == 3 /*CertificateType*/)
                                {
                                    CERT_DATA* pCert = (CERT_DATA*)pObj->Data;

                                    X509_STORE_add_cert(pStore, pCert->cert);
                                }
                            }
                        }

                        C_FindObjectsFinal(hSess);
                    }
                }

                if(pStore->objs == NULL || 0 == sk_num(&pStore->objs->stack))
                {
                    ssl->verify_mode = SSL_VERIFY_NONE;
                }

                C_CloseSession(hSess);
            }
        }
    }

    if(szTargetHost != NULL && szTargetHost[0] != 0)
    {
        SSL_set_tlsext_host_name(ssl, szTargetHost);
    }

    SOCK_ioctl(sd, SOCK_FIONBIO, &nonblock);

    err = SSL_connect (ssl);    

    nonblock = 1;
    SOCK_ioctl(sd, SOCK_FIONBIO, &nonblock);

    err = SSL_get_error(ssl,err);
      
    if(err == SSL_ERROR_WANT_READ)
    {
        err = SOCK_EWOULDBLOCK;
#if !defined(TCPIP_LWIP) && !defined(TCPIP_LWIP_OS)
        SOCKET_DRIVER.ClearStatusBitsForSocket( sd, FALSE );        
#endif
    }
    else if(err == SSL_ERROR_WANT_WRITE)
    {
        err = SOCK_TRY_AGAIN;
#if !defined(TCPIP_LWIP) && !defined(TCPIP_LWIP_OS)
        SOCKET_DRIVER.ClearStatusBitsForSocket( sd, TRUE );        
#endif
    }

    SOCKET_DRIVER.SetSocketSslData(sd, (void*)ssl);

error:
    return err;
}
Beispiel #4
0
int
main (int argc, char *argv[])
{
  CK_RV err;
  CK_SLOT_ID_PTR slots;
  CK_ULONG slots_count;
  unsigned int i;

  (void) argc;
  (void) argv;

  if (argc > 1 && !strcmp ("--printable", argv[1]))
    printable = true;
    
  init_cryptoki ();

  err = C_GetSlotList (true, NULL, &slots_count);
  fail_if_err (err);

  if (slots_count == 0)
    {
      printf ("Skipping test because no token is present.\n");
      return 77;
    }

  printf ("Number of slots with tokens: %lu\n", slots_count);
  slots = malloc (sizeof (CK_SLOT_ID) * slots_count);
  if (!slots)
    fail_if_err (CKR_HOST_MEMORY);

  err = C_GetSlotList (true, slots, &slots_count);
  fail_if_err (err);

  for (i = 0; i < slots_count; i++)
    {
      CK_SESSION_HANDLE session;
      CK_OBJECT_HANDLE object;
      CK_ULONG count;

      printf ("%2i. Slot ID %lu\n", i, slots[i]);
      err = C_OpenSession (slots[i], CKF_SERIAL_SESSION, NULL, NULL,
			   &session);
      fail_if_err (err);
     
      printf ("    Session ID: %lu\n", session);

      err = C_FindObjectsInit (session, NULL, 0);
      fail_if_err (err);

      do
	{
	  err = C_FindObjects (session, &object, 1, &count);
	  fail_if_err (err);

	  if (count)
	    {
	      printf ("    Object Handle: %lu\n", object);

	      err = dump_object (session, object);
	      fail_if_err (err);
	    }
	}
      while (count);

      err = C_FindObjectsFinal (session);
      fail_if_err (err);

      err = C_CloseSession (session);
      fail_if_err (err);
    }

  return 0;
}