Debian Codegraph @

srtcore/crypto.h

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 /*****************************************************************************
12 written by
13 Haivision Systems Inc.
14 *****************************************************************************/
15
16 #ifndef INC_SRT_CRYPTO_H
17 #define INC_SRT_CRYPTO_H
18
19 #include <cstring>
20 #include <string>
21
22 // UDT
23 #include "udt.h"
24 #include "packet.h"
25 #include "utilities.h"
26 #include "logging.h"
27
28 #include <haicrypt.h>
29 #include <hcrypt_msg.h>
30
31
32
33 namespace srt_logging
34 {
35 std::string KmStateStr(SRT_KM_STATE state);
36 #if ENABLE_LOGGING
37 extern Logger cnlog;
38 #endif
39 }
40
41 namespace srt
42 {
43 class CUDT;
44 struct CSrtConfig;
45
46
47 // For KMREQ/KMRSP. Only one field is used.
48 const size_t SRT_KMR_KMSTATE = 0;
49
50 #define SRT_CMD_MAXSZ HCRYPT_MSG_KM_MAX_SZ /* Maximum SRT custom messages payload size (bytes) */
51 const size_t SRTDATA_MAXSIZE = SRT_CMD_MAXSZ/sizeof(uint32_t);
52
53 class CCryptoControl
54 {
55 SRTSOCKET m_SocketID;
56
57 size_t m_iSndKmKeyLen; //Key length
58 size_t m_iRcvKmKeyLen; //Key length from rx KM
59
60 // Temporarily allow these to be accessed.
61 public:
62 SRT_KM_STATE m_SndKmState; //Sender Km State (imposed by agent)
63 SRT_KM_STATE m_RcvKmState; //Receiver Km State (informed by peer)
64
65 private:
66 // Partial haicrypt configuration, consider
67 // putting the whole HaiCrypt_Cfg object here.
68 int m_KmRefreshRatePkt;
69 int m_KmPreAnnouncePkt;
70 int m_iCryptoMode;
71 bool m_bUseGcm153; // Older AES-GCM version existed up to SRT v1.5.3.
72
73 HaiCrypt_Secret m_KmSecret; //Key material shared secret
74 // Sender
75 sync::steady_clock::time_point m_SndKmLastTime;
76 sync::Mutex m_mtxLock; // A mutex to protect concurrent access to CCryptoControl.
77 struct {
78 unsigned char Msg[HCRYPT_MSG_KM_MAX_SZ];
79 size_t MsgLen;
80 int iPeerRetry;
81 } m_SndKmMsg[2];
82 HaiCrypt_Handle m_hSndCrypto;
83 // Receiver
84 HaiCrypt_Handle m_hRcvCrypto;
85
86 bool m_bErrorReported;
87
88 public:
89 static void globalInit();
90
91 static bool isAESGCMSupported();
92
93 bool sendingAllowed()
94 {
95 // This function is called to state as to whether the
96 // crypter allows the packet to be sent over the link.
97 // This is possible in two cases:
98 // - when Agent didn't set a password, no matter the crypto state
99 if (m_KmSecret.len == 0)
100 return true;
101 // - when Agent did set a password and the crypto state is SECURED.
102 if (m_KmSecret.len > 0 && m_SndKmState == SRT_KM_S_SECURED
103 // && m_iRcvPeerKmState == SRT_KM_S_SECURED ?
104 )
105 return true;
106
107 return false;
108 }
109
110 bool hasPassphrase() const
111 {
112 return m_KmSecret.len > 0;
113 }
114
115 int getCryptoMode() const
116 {
117 return m_iCryptoMode;
118 }
119
120 /// Regenerate cryptographic key material if needed.
121 /// @param[in] sock If not null, the socket will be used to send the KM message to the peer (e.g. KM refresh).
122 /// @param[in] bidirectional If true, the key material will be regenerated for both directions (receiver and sender).
123 SRT_ATTR_EXCLUDES(m_mtxLock)
124 void regenCryptoKm(CUDT* sock, bool bidirectional);
125
126 size_t KeyLen() { return m_iSndKmKeyLen; }
127
128 // Needed for CUDT
129 void updateKmState(int cmd, size_t srtlen);
130
131 /// Process the KM request message.
132 /// @param srtv peer's SRT version.
133 int processSrtMsg_KMREQ(const uint32_t* srtdata, size_t len, int hsv, unsigned srtv,
134 uint32_t srtdata_out[], size_t&);
135
136 /// Process the KM response message.
137 /// @param srtv peer's SRT version.
138 /// @returns
139 /// 1 - the given payload is the same as the currently used key
140 /// 0 - there's no key in agent or the payload is error message with agent NOSECRET.
141 /// -1 - the payload is error message with other state or it doesn't match the key
142 int processSrtMsg_KMRSP(const uint32_t* srtdata, size_t len, unsigned srtv);
143 void createFakeSndContext();
144
145 const unsigned char* getKmMsg_data(size_t ki) const { return m_SndKmMsg[ki].Msg; }
146 size_t getKmMsg_size(size_t ki) const { return m_SndKmMsg[ki].MsgLen; }
147
148 /// Check if the key stored at @c ki shall be sent. When during the handshake,
149 /// it only matters if the KM message for that index is recorded at all.
150 /// Otherwise returns true only if also the retry counter didn't expire.
151 ///
152 /// @param ki Key index (0 or 1)
153 /// @param runtime True, if this happens as a key update
154 /// during transmission (otherwise it's during the handshake)
155 /// @return Whether the KM message at given index needs to be sent.
156 bool getKmMsg_needSend(size_t ki, bool runtime) const
157 {
158 if (runtime)
159 return (m_SndKmMsg[ki].iPeerRetry > 0 && m_SndKmMsg[ki].MsgLen > 0);
160 else
161 return m_SndKmMsg[ki].MsgLen > 0;
162 }
163
164 /// Mark the key as already sent. When no 'runtime' (during the handshake)
165 /// it actually does nothing so that this will be retried as long as the handshake
166 /// itself is being retried. Otherwise this is during transmission and will expire
167 /// after several retries.
168 ///
169 /// @param ki Key index (0 or 1)
170 /// @param runtime True, if this happens as a key update
171 /// during transmission (otherwise it's during the handshake)
172 void getKmMsg_markSent(size_t ki, bool runtime)
173 {
174 #if ENABLE_LOGGING
175 using srt_logging::cnlog;
176 #endif
177
178 m_SndKmLastTime = sync::steady_clock::now();
179 if (runtime)
180 {
181 m_SndKmMsg[ki].iPeerRetry--;
182 HLOGC(cnlog.Debug, log << "getKmMsg_markSent: key[" << ki << "]: len=" << m_SndKmMsg[ki].MsgLen << " retry=" << m_SndKmMsg[ki].iPeerRetry);
183 }
184 else
185 {
186 HLOGC(cnlog.Debug, log << "getKmMsg_markSent: key[" << ki << "]: len=" << m_SndKmMsg[ki].MsgLen << " STILL IN USE.");
187 }
188 }
189
190 /// Check if the response returned by KMRSP matches the recorded KM message.
191 /// When it is, set also the retry counter to 0 to prevent further retries.
192 ///
193 /// @param ki KM message index (0 or 1)
194 /// @param srtmsg Message received through KMRSP
195 /// @param bytesize Size of the message
196 /// @return True if the message is identical to the recorded KM message at given index.
197 bool getKmMsg_acceptResponse(size_t ki, const uint32_t* srtmsg, size_t bytesize)
198 {
199 if ( m_SndKmMsg[ki].MsgLen == bytesize
200 && 0 == memcmp(m_SndKmMsg[ki].Msg, srtmsg, m_SndKmMsg[ki].MsgLen))
201 {
202 m_SndKmMsg[ki].iPeerRetry = 0;
203 return true;
204 }
205 return false;
206 }
207
208 CCryptoControl(SRTSOCKET id);
209
210 // DEBUG PURPOSES:
211 std::string CONID() const;
212 std::string FormatKmMessage(std::string hdr, int cmd, size_t srtlen);
213
214 bool init(HandshakeSide, const CSrtConfig&, bool bidir, bool bUseGcm153);
215 SRT_ATTR_EXCLUDES(m_mtxLock)
216 void close();
217
218 /// (Re)send KM request to a peer on timeout.
219 /// This function is used in:
220 /// - HSv4 (initial key material exchange - in HSv5 it's attached to handshake).
221 /// - The case of key regeneration (KM refresh), when a new key has to be sent again.
222 /// In this case the first sending happens in regenCryptoKm(..). This function
223 /// retransmits the KM request by timeout if not KM response has been received.
224 SRT_ATTR_EXCLUDES(m_mtxLock)
225 void sendKeysToPeer(CUDT* sock, int iSRTT);
226
227 void setCryptoSecret(const HaiCrypt_Secret& secret)
228 {
229 m_KmSecret = secret;
230 }
231
232 void setCryptoKeylen(size_t keylen)
233 {
234 m_iSndKmKeyLen = keylen;
235 m_iRcvKmKeyLen = keylen;
236 }
237
238 bool createCryptoCtx(HaiCrypt_Handle& rh, size_t keylen, HaiCrypt_CryptoDir tx, bool bAESGCM);
239
240 int getSndCryptoFlags() const
241 {
242 #ifdef SRT_ENABLE_ENCRYPTION
243 return(m_hSndCrypto ?
244 HaiCrypt_Tx_GetKeyFlags(m_hSndCrypto) :
245 // When encryption isn't on, check if it was required
246 // If it was, return -1 as flags, which means that
247 // encryption was requested and not possible.
248 hasPassphrase() ? -1 :
249 0);
250 #else
251 return 0;
252 #endif
253 }
254
255 bool isSndEncryptionOK() const
256 {
257 // Similar to this above, just quickly check if the encryption
258 // is required and possible, or not possible
259 if (!hasPassphrase())
260 return true; // no encryption required
261
262 if (m_hSndCrypto)
263 return true; // encryption is required and possible
264
265 return false;
266 }
267
268 /// Encrypts the packet. If encryption is not turned on, it
269 /// does nothing. If the encryption is not correctly configured,
270 /// the encryption will fail.
271 /// XXX Encryption flags in the PH_MSGNO
272 /// field in the header must be correctly set before calling.
273 EncryptionStatus encrypt(CPacket& w_packet);
274
275 /// Decrypts the packet. If the packet has ENCKEYSPEC part
276 /// in PH_MSGNO set to EK_NOENC, it does nothing. It decrypts
277 /// only if the encryption correctly configured, otherwise it
278 /// fails. After successful decryption, the ENCKEYSPEC part
279 // in PH_MSGNO is set to EK_NOENC.
280 EncryptionStatus decrypt(CPacket& w_packet);
281
282 ~CCryptoControl();
283 };
284
285 } // namespace srt
286
287 #endif // SRT_CONGESTION_CONTROL_H