//-------------------------------------------------- // Prepares a new signature for signing and calculates // the final hash value to sign. // pSigDoc - signed document object // ppSigInfo - pointer for address of newly allocated signature // manifest - manifest or role // city - signers address , city // state - signers address , state or province // zip - signers address , postal code // country - signers address , country name // id - id for new signature. Optional, use NULL for default // return returns error code or ERR_OK //-------------------------------------------------- EXP_OPTION int ddocPrepareSignature(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo, const char* manifest, const char* city, const char* state, const char* zip, const char* country, X509* pCert, const char* id) { int err = ERR_OK, l1; DigiDocMemBuf mbuf1, *pMBuf1; char buf1[50]; mbuf1.pMem = 0; mbuf1.nLen = 0; ddocDebug(3, "ddocPrepareSignature", "Preparing signature manifest: %s country: %s, state: %s, city: %s, zip: %s, cert: %s, id: %s", (manifest ? manifest : "NULL"), (country ? country : "NULL"), (state ? state : "NULL"), (city ? city : "NULL"), (zip ? zip : "NULL"), (pCert ? "OK" : "ERROR"), (id ? id : "NULL")); // check mandator fields RETURN_IF_NULL_PARAM(pSigDoc); RETURN_IF_NULL_PARAM(ppSigInfo); RETURN_IF_NULL_PARAM(pCert); clearErrors(); // add new signature err = SignatureInfo_new(ppSigInfo, pSigDoc, id); RETURN_IF_NOT(err == ERR_OK, err); // automatically calculate doc-info elements for this signature addAllDocInfos(pSigDoc, *ppSigInfo); // add signature production place if (city || state || zip || country) err = setSignatureProductionPlace(*ppSigInfo, city, state, zip, country); // add user roles/manifests if (manifest) err = addSignerRole(*ppSigInfo, 0, manifest, -1, 0); RETURN_IF_NOT(err == ERR_OK, err); // add signers certificate err = setSignatureCert(*ppSigInfo, pCert); RETURN_IF_NOT(err == ERR_OK, err); // timestamp createTimestamp(pSigDoc, (char*)buf1, sizeof(buf1)); setString((char**)&((*ppSigInfo)->szTimeStamp), (const char*)buf1, -1); // now calculate signed properties digest err = calculateSignedPropertiesDigest(pSigDoc, *ppSigInfo); // TODO: replace later pMBuf1 = ddocDigestValue_GetDigestValue((*ppSigInfo)->pSigPropDigest); ddocSigInfo_SetSigPropRealDigest(*ppSigInfo, (const char*)pMBuf1->pMem, pMBuf1->nLen); // signature type & val ddocSignatureValue_new(&((*ppSigInfo)->pSigValue), 0, SIGN_RSA_NAME, 0, 0); // calc signed-info digest l1 = sizeof(buf1); err = calculateSignedInfoDigest(pSigDoc, *ppSigInfo, (byte*)buf1, &l1); err = ddocSigInfo_SetSigInfoRealDigest(*ppSigInfo, buf1, l1); // debug output - final hash to sign pMBuf1 = ddocDigestValue_GetDigestValue((*ppSigInfo)->pSigInfoRealDigest); ddocEncodeBase64(pMBuf1, &mbuf1); ddocDebug(3, "ddocPrepareSignature", "signing hash %s len: %d b64len: %d", (char*)mbuf1.pMem, mbuf1.nLen, l1); ddocMemBuf_free(&mbuf1); return err; }
byte ProcFileManager_AllocateFD(int* fd, const char* szFileName, const byte mode, int iDriveID, const unsigned uiFileSize, unsigned uiStartSectorID) { byte bStatus ; RETURN_IF_NOT(bStatus, ProcFileManager_GetFD(fd), ProcFileManager_SUCCESS) ; if(mode & O_APPEND) PROCESS_FD_TABLE[*fd].uiOffset = uiFileSize ; else PROCESS_FD_TABLE[*fd].uiOffset = 0 ; PROCESS_FD_TABLE[*fd].mode = mode ; PROCESS_FD_TABLE[*fd].uiFileSize = uiFileSize ; PROCESS_FD_TABLE[*fd].iDriveID = iDriveID ; PROCESS_FD_TABLE[*fd].szFileName = (char*)DMM_AllocateForKernel(strlen(szFileName) + 1) ; strcpy(PROCESS_FD_TABLE[*fd].szFileName, szFileName) ; PROCESS_FD_TABLE[*fd].RefCount = 1 ; PROCESS_FD_TABLE[*fd].iLastReadSectorIndex = 0 ; PROCESS_FD_TABLE[*fd].uiLastReadSectorNumber = uiStartSectorID ; return ProcFileManager_SUCCESS ; }
//============================================================ // Decodes binary (DER) OCSP_RESPONSE data and returns a OCSP_RESPONSE object // ppResp - pointer to a buffer to receive newly allocated OCSP_RESPONSE pointer // data - (DER) OCSP_RESPONSE data // len - length of data in bytes //============================================================ EXP_OPTION int ddocDecodeOCSPResponseData(OCSP_RESPONSE **ppResp, const byte* data, int len) { BIO* b1 = 0; // check input params RETURN_IF_NULL_PARAM(data); RETURN_IF_NULL_PARAM(ppResp); // mark as not read yet *ppResp = 0; // create BIO b1 = BIO_new_mem_buf((void*)data, len); RETURN_IF_NOT(b1, ERR_NULL_POINTER); // decode OCSP *ppResp = d2i_OCSP_RESPONSE_bio(b1, NULL); BIO_free(b1); ddocDebug(3, "ddocDecodeOCSPResponseData", "Decoding %d bytes DER data - OCSP_RESPONSE %s", len, (*ppResp ? "OK" : "ERROR")); RETURN_IF_NOT(*ppResp, ERR_OCSP_UNKNOWN_TYPE); return ERR_OK; }
byte FileSystem_Mount(FileSystem_MountInfo* FSMountInfo) { byte bStatus ; if(FSMountInfo->bMounted == TRUE) return FileSystem_ERR_ALREADY_MOUNTED ; RETURN_IF_NOT(bStatus, FileSystem_GetFSBootBlock(FSMountInfo), FileSystem_SUCCESS) ; printf("\n Sector Per Track @ Mount = %d", FSMountInfo->FSBootBlock.BPB_SecPerTrk); RETURN_IF_NOT(bStatus, FileSystem_FSTableMounter(FSMountInfo, FS_MOUNT), FileSystem_SUCCESS) ; RETURN_IF_NOT(bStatus, FileSystem_ReadRootDirectory(FSMountInfo), FileSystem_SUCCESS) ; FSMountInfo->bMounted = TRUE ; return FileSystem_SUCCESS ; }
//============================================================ // Sets the signatures certificate and calculates // certificate digest & serial number // pSigInfo - signature info object // certFile - certficate file in PEM //============================================================ EXP_OPTION int setSignatureCertFile(SignatureInfo* pSigInfo, const char* certFile) { X509 *cert = NULL; int err = ERR_OK; RETURN_IF_NULL_PARAM(pSigInfo); RETURN_IF_NULL_PARAM(certFile); err = ReadCertificate(&cert, certFile); RETURN_IF_NOT(err == ERR_OK, err); return setSignatureCert(pSigInfo, cert);; }
byte FileSystem_UnMount(FileSystem_MountInfo* FSMountInfo) { byte bStatus ; if(FSMountInfo->bMounted == FALSE) return FileSystem_ERR_NOT_MOUNTED ; RETURN_IF_NOT(bStatus, FileSystem_FSTableMounter(FSMountInfo, FS_UNMOUNT), FileSystem_SUCCESS) ; FSMountInfo->bMounted = FALSE ; if(FSMountBuffer) { free(FSMountBuffer) ; FSMountBuffer = NULL ; } return FileSystem_SUCCESS ; }
byte FileSystem_AllocateSector(FileSystem_MountInfo* FSMountInfo, unsigned* uiFreeSectorID) { byte bStatus ; unsigned uiSectorID = 1 ; unsigned uiSectorEntryValue = EOC ; while(TRUE) { if(FileSystem_GetSectorEntryValue(FSMountInfo, uiSectorID, &uiSectorEntryValue) != FileSystem_SUCCESS) return FileSystem_ERR_NO_FREE_CLUSTER ; if(uiSectorEntryValue == 0) break ; uiSectorID++ ; } RETURN_IF_NOT(bStatus, FileSystem_SetSectorEntryValue(FSMountInfo, uiSectorID, EOC), FileSystem_SUCCESS) ; *uiFreeSectorID = uiSectorID ; return FileSystem_SUCCESS ; }
//============================================================ // Calculates and stores a signature for this SignatureInfo object // Uses EstEID card to sign the info // pSigInfo - signature info object // nSigType - signature type code // keyfile - RSA key file // passwd - key password // certfile - certificate file //============================================================ EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, int slot, const char* passwd) { int err = ERR_OK, nKey; LIBHANDLE pLibrary = 0; CK_ULONG certLen, sigLen, padDigLen; CK_RV rv; CK_SLOT_ID slotids[20], slId = 0; CK_SESSION_HANDLE hSession = 0; CK_OBJECT_HANDLE hPrivateKey, hKeys[20], hCert; char keyId[20][20]; CK_ULONG keyIdLen[20]; CK_BYTE certData[2048]; CK_BYTE sigDig[100], padDig[130]; CK_BYTE signature[256]; CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 }; CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32}; //CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32}; char* buf1; int l1, l2; X509* x509; DigiDocMemBuf mbuf1; RETURN_IF_NULL_PARAM(pSigInfo); RETURN_IF_NULL_PARAM(pSigDoc); // try active driver driver first snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1)); for(l1 = 0; l1 < 20; l1++) slotids[l1] = INVALID_SLOTIID; // initialize err = loadAndTestDriver(ConfigItem_lookup((const char*)signature), &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot); ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", pLibrary, err, slot); RETURN_IF_NOT(err == ERR_OK, err); // inittialize slId = INVALID_SLOTIID; // not found yet //err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, // &slId, (char*)signature, sizeof(signature)); // find suitable slotid for(l1 = 0; l1 < 20; l1++) { if(slotids[l1] != INVALID_SLOTIID) ddocDebug(3, "calculateSignatureWithEstID", "Slot idx: %d = %d", l1, slotids[l1]); if(slotids[l1] != INVALID_SLOTIID && l1 == slot) { slId = slotids[l1]; ddocDebug(3, "calculateSignatureWithEstID", "Select idx: %d slot: %d", l1, slId); } } // open session if(slId != INVALID_SLOTIID) { hSession = OpenSession(slId, passwd); ddocDebug(3, "calculateSignatureWithEstID", "Open sess for slot: %d sess = %uld\n", slId, hSession); if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; } ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession = %d\n", (int)hSession); // get private key for(l1 = 0; l1 < 20; l1++) { memset(keyId[l1], 0, 20); keyIdLen[l1] = 0; } err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys); //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId); //if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; } // get cert memset(certData, 0, sizeof(certData)); certLen = sizeof(certData); hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey); hPrivateKey = hKeys[nKey]; ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]); ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen); //printf("Cert: %s", certData); if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; } // set cert data err = ddocDecodeX509Data(&x509, certData, certLen); if (!x509) { err = ERR_PKCS_CERT_DECODE; } // save cert in file if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3) saveCert(x509, "signer.pem", FILE_FORMAT_PEM); //AM 07.03.08 setSignatureCert for BDOC if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { setSignatureCertBDOC(pSigInfo, x509); }else{ setSignatureCert(pSigInfo, x509); } //AM 12.03.08 //VS 23.02.2010 - not necessary? /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { findCAForCertificate(&ppCA, x509); err = bdocSigInfo_addCert(pSigInfo, ppCA, CERTID_TYPE_CA_CERTID); }*/ // FIXME createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig)); setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1); // Signed properties digest buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0); //dumpInFile("sigprop-sign1.txt", buf1); if (!buf1) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err; } mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1)); mbuf1.nLen = strlen((const char*)mbuf1.pMem); ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1); l2 = sizeof(sigDig); //AM 24.04.08 if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, BDOC_DIGEST, sigDig, &l2); else err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2); free(buf1); ddocMemBuf_free(&mbuf1); if (err != ERR_OK) { SET_LAST_ERROR(err); return err; } ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2); ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2); // create signed info //AM 11.03.08 createXMLSignedInfo for BDOC if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) buf1 = createXMLSignedInfoBDoc(pSigDoc, pSigInfo); else buf1 = createXMLSignedInfo(pSigDoc, pSigInfo); if (!buf1) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err ; } // get digest l2 = sizeof(sigDig); /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) err = calculateDigest((const byte*)buf1, strlen(buf1), BDOC_DIGEST, sigDig, &l2); else*/ err = calculateDigest((const byte*)buf1, strlen(buf1), DIGEST_SHA1, sigDig, &l2); free(buf1); if (err != ERR_OK) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err; } ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2); // sign data sigLen = sizeof(signature); memset(signature, 0, sizeof(signature)); // pad PKCS#1 ver 1 /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME) && BDOC_DIGEST==DIGEST_SHA256) { padDigLen = 51; memset(padDig, 0, sizeof(padDig)); memcpy(padDig, padding256, 19); memcpy(padDig + 19, sigDig, l2); } else {*/ padDigLen = 35; memset(padDig, 0, sizeof(padDig)); memcpy(padDig, padding, 15); memcpy(padDig + 15, sigDig, l2); //} //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2); //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1); // checkErrors(); // sign data rv = SignData(hSession, hPrivateKey, signature, &sigLen, padDig, padDigLen); if (rv != CKR_OK) { err = ERR_PKCS_SIGN_DATA; SET_LAST_ERROR(err); return err; } // set signature value ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen); } // if slotid found if(hSession) closePKCS11Library(pLibrary, hSession); return err; }
//============================================================ // Initializes NotaryInfo object with data from OCSP object // pSigDoc - digidoc main object pointer // pNotary - NotaryInfo object to be initialized // resp - OCSP response object // notCert - Notary cert object // return error code //============================================================ int initializeNotaryInfoWithOCSP(SignedDoc *pSigDoc, NotaryInfo *pNotary, OCSP_RESPONSE *resp, X509 *notCert, int initDigest) { int n, err = ERR_OK; char buf[500]; OCSP_RESPBYTES *rb = NULL; OCSP_BASICRESP *br = NULL; OCSP_RESPDATA *rd = NULL; OCSP_RESPID *rid = NULL; // OCSP_CERTSTATUS *cst = NULL; OCSP_SINGLERESP *single = NULL; OCSP_CERTID *cid = NULL; X509_EXTENSION *nonce; //AM 26.09.08 DigiDocMemBuf mbuf1; mbuf1.pMem = 0; mbuf1.nLen = 0; RETURN_IF_NULL_PARAM(pNotary); RETURN_IF_NULL_PARAM(resp); // check the OCSP Response validity switch(OCSP_response_status(resp)) { case OCSP_RESPONSE_STATUS_SUCCESSFUL: // OK break; case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_MALFORMED); case OCSP_RESPONSE_STATUS_INTERNALERROR: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_INTERNALERR); case OCSP_RESPONSE_STATUS_TRYLATER: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_TRYLATER); case OCSP_RESPONSE_STATUS_SIGREQUIRED: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_SIGREQUIRED); case OCSP_RESPONSE_STATUS_UNAUTHORIZED: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_UNAUTHORIZED); default: SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_UNSUCCESSFUL); } RETURN_IF_NULL_PARAM(resp->responseBytes);; rb = resp->responseBytes; if(OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_UNKNOWN_TYPE); if((br = OCSP_response_get1_basic(resp)) == NULL) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_NO_BASIC_RESP); rd = br->tbsResponseData; if(ASN1_INTEGER_get(rd->version) != 0) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_WRONG_VERSION); n = sk_OCSP_SINGLERESP_num(rd->responses); if(n != 1) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_ONE_RESPONSE); single = sk_OCSP_SINGLERESP_value(rd->responses, 0); RETURN_IF_NULL(single); cid = single->certId; RETURN_IF_NULL(cid); ddocDebug(4, "initializeNotaryInfoWithOCSP", "CertStatus-type: %d", single->certStatus->type); //printf("TYPE: %d\n", single->certStatus->type); if(single->certStatus->type != 0) { ddocDebug(4, "initializeNotaryInfoWithOCSP", "errcode: %d", handleOCSPCertStatus(single->certStatus->type)); SET_LAST_ERROR_RETURN_CODE(handleOCSPCertStatus(single->certStatus->type)); } //Removed 31.10.2003 //if(single->singleExtensions) // SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_NO_SINGLE_EXT); if(!rd->responseExtensions || (sk_X509_EXTENSION_num(rd->responseExtensions) != 1) || ((nonce = sk_X509_EXTENSION_value(rd->responseExtensions, 0)) == NULL)) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_NO_NONCE); i2t_ASN1_OBJECT(buf,sizeof(buf),nonce->object); if(strcmp(buf, OCSP_NONCE_NAME)) SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_NO_NONCE); rid = rd->responderId; if(rid->type == V_OCSP_RESPID_NAME) { pNotary->nRespIdType = RESPID_NAME_TYPE; } else if(rid->type == V_OCSP_RESPID_KEY) { pNotary->nRespIdType = RESPID_KEY_TYPE; } else { SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_WRONG_RESPID); } // producedAt err = asn1time2str(pSigDoc, rd->producedAt, buf, sizeof(buf)); setString(&(pNotary->timeProduced), buf, -1); n = sizeof(buf); if(rid->type == V_OCSP_RESPID_NAME) { //X509_NAME_oneline(rid->value.byName,buf,n); //AM 26.09.08 err = ddocCertGetDNFromName(rid->value.byName, &mbuf1); RETURN_IF_NOT(err == ERR_OK, err); err = ddocNotInfo_SetResponderId(pNotary, (char*)mbuf1.pMem, -1); ddocMemBuf_free(&mbuf1); } if(rid->type == V_OCSP_RESPID_KEY) { err = ddocNotInfo_SetResponderId(pNotary, (const char*)rid->value.byKey->data, rid->value.byKey->length); } // digest type i2t_ASN1_OBJECT(buf,sizeof(buf),cid->hashAlgorithm->algorithm); setString(&(pNotary->szDigestType), buf, -1); // signature algorithm i2t_ASN1_OBJECT(buf,sizeof(buf),br->signatureAlgorithm->algorithm); setString(&(pNotary->szSigType), buf, -1); // notary cert if(notCert && !err) err = addNotaryInfoCert(pSigDoc, pNotary, notCert); // save the response in memory err = ddocNotInfo_SetOCSPResponse_Value(pNotary, resp); // get the digest from original OCSP data if(initDigest && notCert) { err = calcNotaryDigest(pSigDoc, pNotary); } if(br != NULL) OCSP_BASICRESP_free(br); if (err != ERR_OK) SET_LAST_ERROR(err); return err; }
//============================================================ // Calculates and stores a signature for this SignatureInfo object // Uses EstEID card to sign the info // pSigInfo - signature info object // nSigType - signature type code // keyfile - RSA key file // passwd - key password // certfile - certificate file //============================================================ EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, int slot, const char* passwd) { int err = ERR_OK, nKey; LIBHANDLE pLibrary = 0; CK_ULONG certLen, sigLen, padDigLen; CK_RV rv; CK_SLOT_ID slotids[20], slId = 0; CK_SESSION_HANDLE hSession = 0; CK_OBJECT_HANDLE hPrivateKey = 0, hKeys[20], hCert; char keyId[20][20], kId[20]; CK_ULONG keyIdLen[20]; CK_BYTE certData[2048]; CK_BYTE sigDig[100], padDig[130]; CK_BYTE signature[256]; CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 }; //CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32}; //CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32}; char* buf1; int l1, l2, kILen; X509* x509 = 0; DigiDocMemBuf mbuf1; RETURN_IF_NULL_PARAM(pSigInfo); RETURN_IF_NULL_PARAM(pSigDoc); // try active driver driver first snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1)); for(l1 = 0; l1 < 20; l1++) slotids[l1] = INVALID_SLOTIID; // initialize err = loadAndTestDriver(ConfigItem_lookup((const char*)signature), &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot); ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", pLibrary, err, slot); RETURN_IF_NOT(err == ERR_OK, err); // inittialize slId = INVALID_SLOTIID; // not found yet // try key-usage check if(ConfigItem_lookup_int("KEY_USAGE_CHECK", 1)) { kILen = sizeof(kId); ddocDebug(3, "calculateSignatureWithEstID", "Find slot by key-usage, slot: %d", slot); err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, &slId, &x509, kId, &kILen, slot, &l1); ddocDebug(3, "calculateSignatureWithEstID", "Select by key-usage slot idx: %d = %d err: %d key-id: %s, kid-len: %d", l1, slId, err, kId, kILen); if(err != ERR_OK || l1 < 0 || l1 >= 20) { SET_LAST_ERROR(ERR_SIGNERS_CERT_NON_REPU); return ERR_SIGNERS_CERT_NON_REPU; } } else { ddocDebug(3, "calculateSignatureWithEstID", "Find slot by slot idx: %d", slot); for(l1 = 0; (l1 < 20) && (slId == INVALID_SLOTIID); l1++) { if(slotids[l1] != INVALID_SLOTIID) ddocDebug(3, "calculateSignatureWithEstID", "Slot idx: %d = %d", l1, slotids[l1]); if(slotids[l1] != INVALID_SLOTIID && l1 == slot) { slId = slotids[l1]; ddocDebug(3, "calculateSignatureWithEstID", "Select idx: %d slot: %d", l1, slId); } // if slotid } // for } // use default if not found by key-id or direct if(slId == INVALID_SLOTIID) { l1 = ConfigItem_lookup_int("DIGIDOC_SIGNATURE_SLOT", 0); if(slotids[l1] != INVALID_SLOTIID) { ddocDebug(3, "calculateSignatureWithEstID", "Select default slot idx: %d = %d", l1, slotids[l1]); slId = slotids[l1]; } } // open session if(slId != INVALID_SLOTIID) { hSession = OpenSession(slId, passwd); ddocDebug(3, "calculateSignatureWithEstID", "Open sess for slot: %d sess = %d", slId, hSession); if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; } ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession1 = %d", (int)hSession); if(!x509) { ddocDebug(3, "calculateSignatureWithEstID", "Cert ok"); // get private key for(l1 = 0; l1 < 20; l1++) { memset(keyId[l1], 0, 20); keyIdLen[l1] = 0; } err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys); //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId); // // get cert memset(certData, 0, sizeof(certData)); certLen = sizeof(certData); hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey); hPrivateKey = hKeys[nKey]; ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]); ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen); //printf("Cert: %s", certData); if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; } // set cert data err = ddocDecodeX509Data(&x509, certData, certLen); } else { // cert already found //kILen = sizeof(kId); ddocDebug(3, "calculateSignatureWithEstID", "Locate priv key2 id: %s, len: %d, hkey: %d", kId, kILen, hPrivateKey); err = LocatePrivateKeyWithId(hSession, (CK_BYTE_PTR)kId, kILen, &hPrivateKey); ddocDebug(3, "calculateSignatureWithEstID", "Priv key-id: %s len: %d hkey: %d err: %d", kId, kILen, hPrivateKey, err); } ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %d err: %d", hPrivateKey, err); if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; } if (!x509) { err = ERR_PKCS_CERT_DECODE; } // save cert in file if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3) saveCert(x509, "signer.pem", FILE_FORMAT_PEM); setSignatureCert(pSigInfo, x509); // FIXME createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig)); setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1); // Signed properties digest buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0); //dumpInFile("sigprop-sign1.txt", buf1); if (!buf1) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err; } mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1)); mbuf1.nLen = strlen((const char*)mbuf1.pMem); ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1); l2 = sizeof(sigDig); err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2); free(buf1); ddocMemBuf_free(&mbuf1); if (err != ERR_OK) { SET_LAST_ERROR(err); return err; } ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2); ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2); // create signed info buf1 = createXMLSignedInfo(pSigDoc, pSigInfo); if (!buf1) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err ; } // get digest l2 = sizeof(sigDig); err = calculateDigest((const byte*)buf1, strlen(buf1), DIGEST_SHA1, sigDig, &l2); free(buf1); if (err != ERR_OK) { err = ERR_NULL_POINTER; SET_LAST_ERROR(err); return err; } ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2); // sign data sigLen = sizeof(signature); memset(signature, 0, sizeof(signature)); // pad PKCS#1 ver 1 padDigLen = 35; memset(padDig, 0, sizeof(padDig)); memcpy(padDig, padding, 15); memcpy(padDig + 15, sigDig, l2); //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2); //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1); // checkErrors(); // sign data rv = SignData(hSession, hPrivateKey, signature, &sigLen, padDig, padDigLen); if (rv != CKR_OK) { err = ERR_PKCS_SIGN_DATA; SET_LAST_ERROR(err); return err; } // set signature value ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen); ddocDebug(3, "calculateSignatureWithEstID", "Sig-len: %ld", sigLen); } // if slotid found if(hSession) closePKCS11Library(pLibrary, hSession); return err; }
/** * FSEvents event stream callback function called by the FSEvents API in * response to each file system event. * * This callback handler in turn calls our Python callback which is used * in the API layers above to dispatch events to appropriate event handlers. * * .. ADMONITION:: Handling callback failure * If calling the Python callback function fails for any reason, the run loop * associated with the given stream is stopped and hence monitoring will be * shut down. * * .. ADMONITION:: Thread synchronization * This method acquires the GIL on entry and releases it on exit. * * :param stream: * The stream for which to call this handler. * :type stream: * A pointer to an ``FSEventStream``. * :param stream_callback_info * Information that will be supplied by FSEvents to the callback when it * is called. * :type stream_callback_info: * A pointer to a ``StreamCallbackInfo`` struct. This information is passed * to this callback function by the stream run loop. * :param num_events: * The number of events reported by the FSEvents stream. * :param event_paths: * C strings of event source paths. * :param event_flags: * Stream event flags for a given event. * :type event_flags: * An array of ``uint32_t`` event flags. * :param event_ids: * Stream event IDs for the given event. * :type event_ids: * An array of ``uint64_t`` event ids. */ static void Watchdog_FSEventStream_Callback(ConstFSEventStreamRef stream, StreamCallbackInfo *stream_callback_info, const size_t num_events, const char * const event_paths[], const FSEventStreamEventFlags event_flags[], const FSEventStreamEventId event_ids[]) { PyThreadState *saved_thread_state = NULL; PyObject *event_path = NULL; PyObject *event_flag = NULL; PyObject *event_path_list = NULL; PyObject *event_flag_list = NULL; size_t i = 0; /* Acquire lock and save thread state. */ PyEval_AcquireLock(); saved_thread_state = PyThreadState_Swap(stream_callback_info->thread_state); /* Create Python lists that will contain event paths and flags. */ event_path_list = PyList_New(num_events); event_flag_list = PyList_New(num_events); RETURN_IF_NOT(event_path_list && event_flag_list); /* Enumerate event paths and flags into Python lists. */ for (i = 0; i < num_events; ++i) { event_path = PyString_FromString(event_paths[i]); event_flag = PyInt_FromLong(event_flags[i]); if (!(event_flag && event_path)) { Py_DECREF(event_path_list); Py_DECREF(event_flag_list); return; } PyList_SET_ITEM(event_path_list, i, event_path); PyList_SET_ITEM(event_flag_list, i, event_flag); } /* Call the callback event handler function with the enlisted event flags * and paths as arguments. On failure check whether an error occurred and * stop this instance of the run loop. */ if (NULL == PyObject_CallFunction(stream_callback_info->callback, "OO", event_path_list, event_flag_list)) { /* An exception may have occurred. */ if (!PyErr_Occurred()) { /* If one didn't occur, raise an exception informing that * we could not execute the callback function. */ PyErr_SetString(PyExc_ValueError, ERROR_MESSAGE_CANNOT_CALL_CALLBACK); } /* Stop listening for events. */ CFRunLoopStop(stream_callback_info->runloop); } /* Restore original thread state and release lock. */ PyThreadState_Swap(saved_thread_state); PyEval_ReleaseLock(); }