Files
pip/libs/main/crypt/piauth.h
2026-03-07 17:00:45 +03:00

157 lines
7.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*! \file piauth.h
* \ingroup Crypt
* \~\brief
* \~english Authentication API
* \~russian API аутентификации
*/
/*
PIP - Platform Independent Primitives
PIP Authentication API
Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIAUTH_H
#define PIAUTH_H
#include "picrypt.h"
#include "piobject.h"
#include "pip_crypt_export.h"
//! \ingroup Crypt
//! \~\brief
//! \~english Peer authentication state machine with signed key exchange.
//! \~russian Машина состояний аутентификации узлов с подписанным обменом ключами.
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
PIOBJECT(PIAuth)
public:
//! \~english Handshake state.
//! \~russian Состояние рукопожатия.
enum State {
NotConnected /** \~english No active authentication session. \~russian Активной сессии аутентификации нет. */,
AuthProbe /** \~english Initial probe stage with signed peer introduction. \~russian Начальный этап с подписанным представлением узла. */,
PassRequest /** \~english Password verification stage for unknown peers. \~russian Этап проверки пароля для неизвестных узлов. */,
AuthReply /** \~english Reply with client authentication data. \~russian Ответ с данными аутентификации клиента. */,
KeyExchange /** \~english Session key exchange stage. \~russian Этап обмена сеансовым ключом. */,
Connected /** \~english Authentication finished and session key is established. \~russian Аутентификация завершена и сеансовый ключ установлен. */
};
//! \~english Creates an authentication endpoint from a signing secret key.
//! \~russian Создает конечную точку аутентификации из секретного ключа подписи.
PIAuth(const PIByteArray & sign);
//! \~english Sets application-defined info exchanged during authorization.
//! \~russian Задает прикладные данные, передаваемые во время авторизации.
void setInfoData(const PIByteArray & info) { custom_info = info; }
//! \~english Sets the server password used for password-based peer validation.
//! \~russian Устанавливает пароль сервера, используемый для проверки узла по паролю.
void setServerPassword(const PIString & ps);
//! \~english Replaces the list of trusted peer signing public keys.
//! \~russian Заменяет список доверенных открытых ключей подписи удаленных узлов.
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
//! \~english Returns the list of trusted peer signing public keys.
//! \~russian Возвращает список доверенных открытых ключей подписи удаленных узлов.
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
//! \~english Returns the public signing key derived from the local secret key.
//! \~russian Возвращает открытый ключ подписи, полученный из локального секретного ключа.
PIByteArray getSignPublicKey() { return sign_pk; }
//! \~english Stops the current authorization session and clears transient keys.
//! \~russian Останавливает текущую сессию авторизации и очищает временные ключи.
void stop();
//! \~english Starts the handshake in client mode.
//! \~russian Запускает рукопожатие в режиме клиента.
void startClient();
//! \~english Starts the handshake in server mode and returns the first packet for the client.
//! \~russian Запускает рукопожатие в режиме сервера и возвращает первый пакет для клиента.
PIByteArray startServer();
//! \~english Processes an incoming handshake packet, updates the state and writes the reply back to \a ba.
//! \~russian Обрабатывает входящий пакет рукопожатия, обновляет состояние и записывает ответ обратно в \a ba.
State receive(PIByteArray & ba);
//! \~english Returns the session secret key after the state becomes \a Connected.
//! \~russian Возвращает сеансовый секретный ключ после перехода в состояние \a Connected.
PIByteArray getSecretKey();
//! \~english Generates a signing secret key from \a seed.
//! \~russian Генерирует секретный ключ подписи из \a seed.
static PIByteArray generateSign(const PIByteArray & seed);
EVENT1(disconnected, PIString, reason);
EVENT1(connected, PIString, info);
EVENT2(authorize, PIByteArray, info, bool *, ok);
EVENT1(passwordRequest, PIString *, pass);
EVENT1(passwordCheck, bool, result);
//! \events
//! \{
//! \fn void disconnected(PIString reason)
//! \~english Raised when the handshake is aborted or an established session is dropped.
//! \~russian Вызывается при прерывании рукопожатия или разрыве установленной сессии.
//!
//! \fn void connected(PIString info)
//! \~english Raised after the peer reaches state \a Connected.
//! \~russian Вызывается после перехода узла в состояние \a Connected.
//!
//! \fn void authorize(PIByteArray info, bool * ok)
//! \~english Client-side callback used to approve an unknown server and optionally trust its signing key.
//! \~russian Клиентский вызов для подтверждения неизвестного сервера и, при необходимости, доверия его ключу подписи.
//!
//! \fn void passwordRequest(PIString * pass)
//! \~english Client-side callback requesting the server password.
//! \~russian Клиентский вызов для запроса пароля сервера.
//!
//! \fn void passwordCheck(bool result)
//! \~english Server-side callback reporting the result of client password validation.
//! \~russian Серверный вызов, сообщающий результат проверки пароля клиента.
//! \}
private:
enum Role {
Client,
Server
};
State disconnect(PIByteArray & ba, const PIString & error = PIString());
bool isAuthorizedKey(const PIByteArray & pkey);
PIByteArray createSKMessage();
Role role;
State state;
PIByteArray custom_info;
PICrypt crypt;
PIByteArray sign_sk, sign_pk;
PIByteArray auth_sign;
PIByteArray box_sk, box_pk;
PIByteArray my_pk;
PIByteArray secret_key;
PIByteArray pass_hash;
PIVector<PIByteArray> auth_pkeys;
};
#endif // PIAUTH_H