예제 #1
0
파일: main.cpp 프로젝트: Suneal/qt
void check(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug("unable to open file: '%s' (%s)", fileName.toLocal8Bit().constData(), file.errorString().toLocal8Bit().constData());
        return;
    }
    QStringList lines;
    bool found = false;
    while (true) {
        QByteArray bline = file.readLine(16384);
        if (bline.isEmpty())
            break;
        QString line = QString::fromLocal8Bit(bline);
        Q_ASSERT_X(line.endsWith("\n"), "check()", fileName.toLocal8Bit().constData());
        found |= checkSignature(fileName, line, "SLOT");
        found |= checkSignature(fileName, line, "SIGNAL");
        if (modify)
            lines << line;
    }
    file.close();

    if (found && modify) {
        printf("Modifying file: '%s'\n", fileName.toLocal8Bit().constData());
        writeChanges(fileName, lines);
    }
}
예제 #2
0
 void NodeTemplate::build(ComplexNode* parent, const std::string& id)
 {
     if (checkSignature())
     {
         m_body.at("__body__").copy(parent, id);
         std::vector<LinkNode*> attributeAddresses;
         for (NodeConstraintManager& constraintManager : m_signature)
             attributeAddresses.push_back(constraintManager.getLinkNode());
         parent->getComplexNode(id).walk([attributeAddresses](NodeIterator& complex)
         {
             for (LinkNode* link : complex->getAll<LinkNode>())
             {
                 for (LinkNode* compare : attributeAddresses)
                 {
                     if (*link == *compare)
                     {
                         link->apply();
                         break;
                     }
                 }
             }
         });
         if (m_defaultLinkRoot)
             parent->at(id).remove("__linkroot__");
     }
     else
         throw aube::ErrorHandler::Raise("Vili.Vili.NodeTemplate.BuildError", {{"element", id},{"parent", parent->getNodePath()}});
 }
예제 #3
0
bool ossimPngReader::open( std::istream* str, std::streamoff restartPosition, bool youOwnIt )
{
   bool result = false;
   if (isOpen())
   {
      close();
   }

   if ( str )
   {
      str->seekg( m_restartPosition, std::ios_base::beg );

      if ( checkSignature( str ) )
      {
         // Store the pointer:
         m_str = str;
         m_restartPosition = restartPosition;
         m_ownsStream = youOwnIt;
         
         result = readPngInit();
         if ( result )
         {
            result = initReader();
            if ( result )
            {
               completeOpen();
            }
         }
         else
         {
            destroy();
         }
      }
      else
      {
         if ( youOwnIt )
         {
            delete str;
            str = 0;
         }         
         
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "ossimPngReader::open NOTICE:\n"
               << "Could not open:  " << theImageFile.c_str()
               << endl;
         }
      }
   }
   
   return result;
}
예제 #4
0
bool TCJpegImageFormat::checkSignature(FILE *file)
{
	bool retValue = false;
	TCByte header[SIG_LENGTH];
	long filePos = ftell(file);

	if (fread(header, 1, SIG_LENGTH, file) == SIG_LENGTH)
	{
		retValue = checkSignature(header, SIG_LENGTH);
	}
	fseek(file, filePos, SEEK_SET);
	return retValue;
}
예제 #5
0
bool SignatureVerifierImpl::isSignatureOk() {
    bool ok = false;
    unsigned char *rsa_out = NULL;
    int rsa_out_len = 0;
    RSA *rsa = NULL;

    if (hash.len() != SHA256_DIGEST_LENGTH) {
        error = "Input hash is of unsuitable size";
        goto end;
    }

    if (signature.len() != RSA_SIGNATURE_LENGTH) {
        error = "Input signature is of unsuitable length";
        goto end;
    }

    rsa = getRSA((unsigned char *)pubkey.peek(), pubkey.len());
    if (!rsa) {
        error = "Error decoding RSA key: ";
        error += ERR_reason_error_string(ERR_get_error());
        goto end;
    }

    if (RSA_size(rsa) != RSA_SIGNATURE_LENGTH) {
        error = "Input public key is of unsuitable size";
        goto end;
    }

    rsa_out_len = message_decrypt((unsigned char *)signature.peek(),
                                  signature.len(), rsa, &rsa_out);
    if (rsa_out_len < 0) {
        error = "Error in decrypting: ";
        error += ERR_reason_error_string(ERR_get_error());
        goto end;
    }

    ok = checkSignature((unsigned char *)hash.peek(), hash.len(),
                        rsa_out, rsa_out_len);
    if (!ok) {
        error = "Error in verification";
    }

end:
    RSA_free(rsa);
    OPENSSL_free(rsa_out);
    return ok;
}
bool SignatureModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::EditRole)
        return QStandardItemModel::setData(index, value, role);
    // check via signal (unless it is the same), in which case we can't be bothered.
    const QStandardItem *item = itemFromIndex(index);
    Q_ASSERT(item);
    const QString signature = value.toString();
    if (item->text() == signature)
        return true;

    bool ok = true;
    emit checkSignature(signature, &ok);
    if (!ok)
        return false;

    return QStandardItemModel::setData(index, value, role);
}
예제 #7
0
void BytecodeTranslatorVisitor::visitCallNode(CallNode* node) {
    onVisitNode(node);

    AstFunction* f = scope()->lookupFunction(node->name());
    if (!f) ERROR("Unknown function " + f->name());
    checkSignature(node, f);

    for (uint16_t i = 0; i < node->parametersNumber(); i++)
        visitTyped(node->parameterAt(i), f->parameterType(i));

    if (isNative(f))
        EMIT(BC_CALLNATIVE);
    else
        EMIT(BC_CALL);

    EMIT_ID(getFunctionId(f));

    pushType(f->returnType());
}
예제 #8
0
/**
 * Check if signature is valid according to BDoc-BES format. Performs
 * any off-line checks that prove mathematical correctness.
 * However, there is no warranty against if the signature has expired. On-line
 * validation should be performed to check for signature expiration.
 *
 * @throws SignatureException containing details on what's wrong in this signature.
*/
void digidoc::SignatureBES::validateOffline() const throw(SignatureException)
{
    // A "master" exception containing all problems (causes) with this signature.
    // It'll be only thrown in case we have a reason (cause).
    SignatureException resultException(__FILE__, __LINE__, "Signature is invalid");


    try
    {
        checkQualifyingProperties();
    }
    catch (digidoc::Exception& e)
    {
        resultException.addCause(e); // remember and proceed
    }

    try
    {
        checkSignature();
    }
    catch (digidoc::Exception& e)
    {
        resultException.addCause(e); // remember and proceed
    }

    try
    {
        checkSigningCertificate();
    }
    catch (digidoc::Exception& e)
    {
        resultException.addCause(e); // remember and proceed
    }

    // now check if we've gathered some problems with this signature
    if ( resultException.hasCause() )
    {
        throw resultException;
    }
    // else: this signature is fine
}
예제 #9
0
void
Service_ActivateSession(UA_Server *server, UA_SecureChannel *channel,
                        UA_Session *session, const UA_ActivateSessionRequest *request,
                        UA_ActivateSessionResponse *response) {
    if(session->validTill < UA_DateTime_nowMonotonic()) {
        UA_LOG_INFO_SESSION(server->config.logger, session,
                            "ActivateSession: SecureChannel %i wants "
                            "to activate, but the session has timed out",
                            channel->securityToken.channelId);
        response->responseHeader.serviceResult =
            UA_STATUSCODE_BADSESSIONIDINVALID;
        return;
    }

    checkSignature(server, channel, session, request, response);
    if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
        return;

    /* Callback into userland access control */
    response->responseHeader.serviceResult =
        server->config.accessControl.activateSession(&session->sessionId,
                                                     &request->userIdentityToken,
                                                     &session->sessionHandle);
    if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
        return;

    /* Detach the old SecureChannel */
    if(session->channel && session->channel != channel) {
        UA_LOG_INFO_SESSION(server->config.logger, session,
                            "ActivateSession: Detach from old channel");
        UA_SecureChannel_detachSession(session->channel, session);
    }

    /* Attach to the SecureChannel and activate */
    UA_SecureChannel_attachSession(channel, session);
    session->activated = true;
    UA_Session_updateLifetime(session);
    UA_LOG_INFO_SESSION(server->config.logger, session,
                        "ActivateSession: Session activated");
}
예제 #10
0
UINT CPackage::execute( UINT uCommandTimeOut)
{
	CLog *pLog = getOcsLogger();
	CExecCommand cmProcess;
	CString csBuffer;
	UINT	uTry;

	// Check signature before executing package
	if (!checkSignature())
	{
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed verifying signature for Package <%s>"), m_csID);
		setDone( ERR_BAD_DIGEST);
		return FALSE;
	}
	// Check if package not crashing all time
	if (!getExecTry( &uTry))
		// Assuming first execution try
		uTry = 0;
	uTry++;
	if (uTry > MAX_ERROR_COUNT)
	{
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Max try count (%u) reached while executing Package <%s>"), uTry, m_csID);
		setDone( ERR_EXECUTE_TOO_MANY_TRY);
		return FALSE;
	}
	else
		setExecTry( uTry);
	
	if (m_csAction == OCS_DOWNLOAD_ACTION_LAUNCH)
	{
		// We need to wait for all threads/processes started
		// First, extrac build.zip to tmp folder
		if (!directoryCreate( m_csPath) || !unZip())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to unzip package <%s> to folder <%s>"), m_csID, m_csPath);
			setDone( ERR_UNZIP);
			return FALSE;
		}
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Launching command <%s> for package <%s> on <%s>"), m_csCommand, m_csID, CTime::GetCurrentTime().Format( _T( "%#c")));
		if (m_csCommand.IsEmpty())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => No command provided for <%s> action of package <%s>"), OCS_DOWNLOAD_ACTION_LAUNCH, m_csID);
			setDone( ERR_BAD_PARAM);
			return FALSE;
		}
		// Set command time out in milliseconds
		cmProcess.setTimeout( uCommandTimeOut * 60 * 1000);
		// Execute command and wait for all childs to terminate
		switch (cmProcess.execWaitForAllChilds( m_csCommand, m_csPath))
		{
		case EXEC_ERROR_START_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to launch command <%s> for package <%s> (%s)"), m_csCommand, m_csID, cmProcess.getOutput());
			setDone( ERR_EXECUTE);
			return FALSE;
		case EXEC_ERROR_WAIT_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to get command <%s> result code for package <%s> (%s)"), m_csCommand, m_csID, cmProcess.getOutput());
			csBuffer = ERR_EXECUTE_NO_EXIT_CODE;
			break;
		case EXEC_ERROR_TIMEOUT_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Command <%s> execution reached timeout on <%s> (%s)"), m_csCommand, CTime::GetCurrentTime().Format( _T( "%#c")), cmProcess.getOutput());
			csBuffer = ERR_EXECUTE_TIMEOUT;
			break;
		default:
			isExecSuccessful( cmProcess.getExitValue(), csBuffer);
			pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Package <%s> successfully launched. Command exit code is <%d>. Package return code is <%s>"), m_csID, cmProcess.getExitValue(), csBuffer);
			break;
		}
		setDone( csBuffer);
		return TRUE;
	}
	if (m_csAction == OCS_DOWNLOAD_ACTION_EXECUTE)
	{
		// We only need to wait for cmmand result
		// First, extrac build.zip to tmp folder
		if (!directoryCreate( m_csPath) || !unZip())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to unzip package <%s> to folder <%s>"), m_csID, m_csPath);
			setDone( ERR_UNZIP);
			return FALSE;
		}
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Executing command <%s> for package <%s> on <%s>"), m_csCommand, m_csID, CTime::GetCurrentTime().Format( _T( "%#c")));
		if (m_csCommand.IsEmpty())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => No command provided for <%s> action of package <%s>"), OCS_DOWNLOAD_ACTION_EXECUTE, m_csID);
			setDone( ERR_BAD_PARAM);
			return FALSE;
		}
		// Set command time out in milliseconds
		cmProcess.setTimeout( uCommandTimeOut * 60 * 1000);
		// Execute command and wait only for main process to terminate
		switch (cmProcess.execWait( m_csCommand, m_csPath))
		{
		case EXEC_ERROR_START_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to execute command <%s> for package <%s> (%s)"), m_csCommand, m_csID, cmProcess.getOutput());
			setDone( ERR_EXECUTE);
			return FALSE;
		case EXEC_ERROR_WAIT_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to get command <%s> result code for package <%s> (%s)"), m_csCommand, m_csID, cmProcess.getOutput());
			csBuffer = ERR_EXECUTE_NO_EXIT_CODE;
			break;
		case EXEC_ERROR_TIMEOUT_COMMAND:
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Command <%s> execution reached timeout on <%s> (%s)"), m_csCommand, CTime::GetCurrentTime().Format( _T( "%#c")), cmProcess.getOutput());
			csBuffer = ERR_EXECUTE_TIMEOUT;
			break;
		default:
			isExecSuccessful( cmProcess.getExitValue(), csBuffer);
			pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Package <%s> successfully executed. Command exit code is <%d>. Package return code is <%s>"), m_csID, cmProcess.getExitValue(), csBuffer);
		}
		setDone( csBuffer, GetUnicodeFromAnsi( cmProcess.getOutput()));
		return TRUE;
	}
	if (m_csAction == OCS_DOWNLOAD_ACTION_STORE)
	{
		// We just want to unzip data to specified folder
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Unzipping data to folder <%s> for package <%s> on <%s>"), m_csPath, m_csID, CTime::GetCurrentTime().Format( _T( "%#c")));
		if (m_csPath.IsEmpty())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => No path provided for <%s> action of package <%s>"), OCS_DOWNLOAD_ACTION_STORE, m_csID);
			setDone( ERR_BAD_PARAM);
			return FALSE;
		}
		if (!directoryCreate( m_csPath) || !unZip())
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to unzip package <%s> to folder <%s>"), m_csID, m_csPath);
			setDone( ERR_UNZIP);
			return FALSE;
		}
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Package <%s> successfully stored to folder <%s>"), m_csID, m_csPath);
		setDone( CODE_SUCCESS);
		return TRUE;
	}
	// Unknown action
	pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unknown action <%s> for package <%s>"), m_csAction, m_csID);
	setDone( ERR_BAD_PARAM);
	return FALSE;
}
예제 #11
0
BOOL CPackage::build()
{
	CString		csFile, csZipFile;
	CFileStatus cfStatus;
	__int64		i64BuildSize = 0;
	UINT		uIndex;
	CLog		*pLog = getOcsLogger();
	CFile		fileZip, fileFrag;

	if (m_uFrags == 0)
	{
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => No fragment files for package <%s>, nothing to build"), m_csID);
		return TRUE;
	}
	// Ensure all fragment are available
	pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Verifying fragment files of package <%s>"), m_csID);
	for (uIndex=1; uIndex<=m_uFrags; uIndex++)
	{
		csFile.Format( _T( "%s\\%s\\%s-%u"), getDownloadFolder(), m_csID, m_csID, uIndex);
		if (!CFile::GetStatus( csFile, cfStatus))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Fragment file <%s> is missing or unreadable"), csFile);
			setDone( ERR_BUILD);
			return FALSE;
		}
		i64BuildSize += cfStatus.m_size;
	}
	pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Checking free disk space for package <%s>"), m_csID);
	GetCurrentDirectory( 4*_MAX_PATH, csFile.GetBuffer( 4*_MAX_PATH));
	csFile.ReleaseBuffer();
	if (GetDiskFree( csFile) < (3*i64BuildSize))
	{
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Free disk space missing for package <%s> (required at least %I64d bytes)"), m_csID, 3*i64BuildSize);
		setDone( ERR_OUT_OF_SPACE);
		return FALSE;
	}
	// Concatenate each fragment file into build.zip
	pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Building ZIP for package <%s>"), m_csID);
	csZipFile.Format( _T( "%s\\%s\\%s"), getDownloadFolder(), m_csID, OCS_DOWNLOAD_BUILD);
	try
	{
		if (!fileZip.Open( csZipFile, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Cannot create Zip <%s> from fragment files"), csZipFile);
			setDone( ERR_BUILD);
			return FALSE;
		}
		for (uIndex=1; uIndex<=m_uFrags; uIndex++)
		{
			// Read data in frag file and write it in zip file
			csFile.Format( _T( "%s\\%s\\%s-%u"), getDownloadFolder(), m_csID, m_csID, uIndex);
			if (!fileFrag.Open( csFile, CFile::modeRead|CFile::shareDenyNone))
			{
				pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Cannot read Fragment file <%s>"), csFile);
				setDone( ERR_BUILD);
				return FALSE;
			}
			UINT uLength;
			BYTE pBuffer[1024];
			BOOL bContinue = TRUE;
			while (bContinue)
			{
				uLength = fileFrag.Read( pBuffer, 1024);
				fileZip.Write( pBuffer, uLength);
				// Stop if read less than 1024 bytes
				if (uLength < 1024)
					bContinue = FALSE;
			}
			fileFrag.Close();
		}
		fileZip.Close();	
	}
	catch (CException *pEx)
	{
		pEx->Delete();
		fileZip.Abort();
		fileFrag.Abort();
		DeleteFile( csZipFile);
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Cannot read Fragment file <%s>"), csFile);
		setDone( ERR_BUILD);
		return FALSE;
	}
	// Verify signature
	pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Verifying ZIP signature for package <%s>"), m_csID);
	if (!checkSignature())
	{
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed verifying signature for Package <%s>"), m_csID);
		setDone( ERR_BAD_DIGEST);
		return FALSE;
	}
	// Delete frag files, no more needed
	deleteFragement();
	return TRUE;
}