str0m-wincrypto 0.6.1

Supporting crate for str0m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use super::Certificate;
use super::WinCryptoError;
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use windows::Win32::Foundation::SEC_E_MESSAGE_ALTERED;
use windows::Win32::Foundation::SEC_E_OK;
use windows::Win32::Foundation::SEC_E_OUT_OF_SEQUENCE;
use windows::Win32::Foundation::SEC_I_CONTEXT_EXPIRED;
use windows::Win32::Foundation::SEC_I_MESSAGE_FRAGMENT;
use windows::Win32::Foundation::SEC_I_RENEGOTIATE;
use windows::Win32::Security::Authentication::Identity::ASC_REQ_CONFIDENTIALITY;
use windows::Win32::Security::Authentication::Identity::ASC_REQ_DATAGRAM;
use windows::Win32::Security::Authentication::Identity::ASC_REQ_EXTENDED_ERROR;
use windows::Win32::Security::Authentication::Identity::ASC_REQ_INTEGRITY;
use windows::Win32::Security::Authentication::Identity::ASC_REQ_MUTUAL_AUTH;
use windows::Win32::Security::Authentication::Identity::AcceptSecurityContext;
use windows::Win32::Security::Authentication::Identity::AcquireCredentialsHandleW;
use windows::Win32::Security::Authentication::Identity::DecryptMessage;
use windows::Win32::Security::Authentication::Identity::DeleteSecurityContext;
use windows::Win32::Security::Authentication::Identity::EncryptMessage;
use windows::Win32::Security::Authentication::Identity::FreeContextBuffer;
use windows::Win32::Security::Authentication::Identity::FreeCredentialsHandle;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_CONFIDENTIALITY;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_DATAGRAM;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_EXTENDED_ERROR;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_INTEGRITY;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_MANUAL_CRED_VALIDATION;
use windows::Win32::Security::Authentication::Identity::ISC_REQ_USE_SUPPLIED_CREDS;
use windows::Win32::Security::Authentication::Identity::InitializeSecurityContextW;
use windows::Win32::Security::Authentication::Identity::QueryContextAttributesExW;
use windows::Win32::Security::Authentication::Identity::QueryContextAttributesW;
use windows::Win32::Security::Authentication::Identity::SCH_CRED_FORMAT_CERT_CONTEXT;
use windows::Win32::Security::Authentication::Identity::SCH_CREDENTIALS;
use windows::Win32::Security::Authentication::Identity::SCH_CREDENTIALS_VERSION;
use windows::Win32::Security::Authentication::Identity::SCH_USE_DTLS_ONLY;
use windows::Win32::Security::Authentication::Identity::SEC_DTLS_MTU;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_ALERT;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_DATA;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_DTLS_MTU;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_EMPTY;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_EXTRA;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_SRTP_PROTECTION_PROFILES;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_STREAM_HEADER;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_STREAM_TRAILER;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_TOKEN;
use windows::Win32::Security::Authentication::Identity::SECBUFFER_VERSION;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR_KEYING_MATERIAL;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR_KEYING_MATERIAL_INFO;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR_REMOTE_CERT_CONTEXT;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR_SRTP_PARAMETERS;
use windows::Win32::Security::Authentication::Identity::SECPKG_ATTR_STREAM_SIZES;
use windows::Win32::Security::Authentication::Identity::SECPKG_CRED_INBOUND;
use windows::Win32::Security::Authentication::Identity::SECPKG_CRED_OUTBOUND;
use windows::Win32::Security::Authentication::Identity::SECURITY_NATIVE_DREP;
use windows::Win32::Security::Authentication::Identity::SecBuffer;
use windows::Win32::Security::Authentication::Identity::SecBufferDesc;
use windows::Win32::Security::Authentication::Identity::SecPkgContext_KeyingMaterial;
use windows::Win32::Security::Authentication::Identity::SecPkgContext_KeyingMaterialInfo;
use windows::Win32::Security::Authentication::Identity::SecPkgContext_SrtpParameters;
use windows::Win32::Security::Authentication::Identity::SecPkgContext_StreamSizes;
use windows::Win32::Security::Authentication::Identity::SetContextAttributesW;
use windows::Win32::Security::Authentication::Identity::UNISP_NAME_W;
use windows::Win32::Security::Credentials::SecHandle;
use windows::Win32::Security::Cryptography::CERT_CONTEXT;

// These are encoded as BE, since SChannel seemingly copies this buffer verbatim.
const SRTP_PROFILES: [u16; 3] = [
    u16::to_be(0x0008), /* SRTP_AES256_GCM (RFC7714 Sec 14.2) */
    u16::to_be(0x0007), /* SRTP_AES128_GCM (RFC7714 Sec 14.2) */
    u16::to_be(0x0001), /* SRTP_AES128_CM_SHA1_80 (RFC5764 Section 4.1.2) */
];

#[repr(C)]
struct SrtpProtectionProfilesBuffer {
    profiles_byte_len: u16,
    profiles: [u16; SRTP_PROFILES.len()],
}
const SRTP_PROTECTION_PROFILES_BUFFER_INSTANCE: SrtpProtectionProfilesBuffer =
    SrtpProtectionProfilesBuffer {
        profiles_byte_len: (SRTP_PROFILES.len() * std::mem::size_of::<u16>()) as u16,
        profiles: SRTP_PROFILES,
    };
const SRTP_PROTECTION_PROFILES_SECBUFFER: SecBuffer = SecBuffer {
    cbBuffer: std::mem::size_of::<SrtpProtectionProfilesBuffer>() as u32,
    BufferType: SECBUFFER_SRTP_PROTECTION_PROFILES,
    pvBuffer: &SRTP_PROTECTION_PROFILES_BUFFER_INSTANCE as *const _ as *mut _,
};

const DTLS_MTU_BUFFER_INSTANCE: SEC_DTLS_MTU = SEC_DTLS_MTU {
    PathMTU: DATAGRAM_MTU as u16,
};
const DTLS_MTU_SECBUFFER: SecBuffer = SecBuffer {
    cbBuffer: std::mem::size_of::<SEC_DTLS_MTU>() as u32,
    BufferType: SECBUFFER_DTLS_MTU,
    pvBuffer: &DTLS_MTU_BUFFER_INSTANCE as *const _ as *mut _,
};

// The label used for SRTP key derivation from: https://datatracker.ietf.org/doc/html/rfc5764#section-4.2
const DTLS_KEY_LABEL: &[u8] = b"EXTRACTOR-dtls_srtp\0";

// This size includes the encaptulation overhead of DTLS. So it must be larger than the MTU Str0m
// uses for SCTP.
const DATAGRAM_MTU: usize = 1200;

#[derive(Clone, Copy, Debug, PartialEq)]
enum EstablishmentState {
    Idle,
    Handshaking,
    Established,
    Failed,
}

pub enum DtlsEvent {
    None,
    WouldBlock,
    Connected {
        srtp_profile_id: u16,
        srtp_keying_material: Vec<u8>,
        peer_cert_der: Vec<u8>,
    },
    Data(Vec<u8>),
}

pub struct Dtls {
    cert: Arc<Certificate>,
    is_client: Option<bool>,
    state: EstablishmentState,
    cred_handle: Option<SecHandle>,
    security_ctx: Option<SecHandle>,
    encrypt_message_input_sizes: SecPkgContext_StreamSizes,

    output_datagrams: VecDeque<Vec<u8>>,
}

impl Dtls {
    pub fn new(cert: Arc<Certificate>) -> Result<Self, WinCryptoError> {
        Ok(Dtls {
            cert,
            is_client: None,
            state: EstablishmentState::Idle,
            cred_handle: None,
            security_ctx: None,
            encrypt_message_input_sizes: SecPkgContext_StreamSizes::default(),
            output_datagrams: VecDeque::default(),
        })
    }

    pub fn is_client(&self) -> Option<bool> {
        self.is_client
    }

    #[allow(dead_code)]
    pub fn is_connected(&self) -> bool {
        self.state == EstablishmentState::Established
    }

    pub fn set_as_client(&mut self, active: bool) -> Result<(), WinCryptoError> {
        self.is_client = Some(active);

        let mut cert_contexts = [self.cert.context()];
        let sch_cred = SCH_CREDENTIALS {
            dwVersion: SCH_CREDENTIALS_VERSION,
            dwCredFormat: SCH_CRED_FORMAT_CERT_CONTEXT,
            cCreds: cert_contexts.len() as u32,
            paCred: cert_contexts.as_mut_ptr() as *mut *mut CERT_CONTEXT,
            hRootStore: windows::Win32::Security::Cryptography::HCERTSTORE(std::ptr::null_mut()),
            cMappers: 0,
            aphMappers: std::ptr::null_mut(),
            dwSessionLifespan: 0,
            dwFlags: SCH_USE_DTLS_ONLY,
            cTlsParameters: 0,
            pTlsParameters: std::ptr::null_mut(),
        };

        // These are the outputs of AcquireCredentialsHandleA
        let mut cred_handle = SecHandle::default();
        let mut creds_expiry: i64 = 0;

        // SAFETY: The references passed are all borrow checked, the exception to
        // this is the pointer to the cert_context in schannel_cred, which
        // is kept alive by the `self.cert`.
        unsafe {
            AcquireCredentialsHandleW(
                None,
                UNISP_NAME_W,
                if active {
                    SECPKG_CRED_OUTBOUND
                } else {
                    SECPKG_CRED_INBOUND
                },
                None,
                Some(&sch_cred as *const _ as *const std::ffi::c_void),
                None,
                None,
                &mut cred_handle,
                Some(&mut creds_expiry),
            )?;
        }
        self.cred_handle = Some(cred_handle);

        self.state = EstablishmentState::Handshaking;
        Ok(())
    }

    pub fn handle_receive(&mut self, datagram: Option<&[u8]>) -> Result<DtlsEvent, WinCryptoError> {
        let state = self.state;
        match state {
            EstablishmentState::Established => {
                if let Some(datagram) = datagram {
                    self.process_packet(datagram)
                } else {
                    warn!("Unexpectedly asked to process no message!");
                    Ok(DtlsEvent::None)
                }
            }
            EstablishmentState::Handshaking => self.handshake(datagram),
            EstablishmentState::Failed => Err("Handshake failed".into()),
            EstablishmentState::Idle => Err("Handshake not initialized".into()),
        }
    }

    pub fn pull_datagram(&mut self) -> Option<Vec<u8>> {
        self.output_datagrams.pop_front()
    }

    #[allow(dead_code)]
    pub fn next_timeout(&mut self, now: Instant) -> Option<Instant> {
        match self.state {
            EstablishmentState::Idle | EstablishmentState::Handshaking => {
                Some(now + Duration::from_millis(500))
            }
            _ => None,
        }
    }

    // This is DATA sent from client over SCTP/DTLS
    pub fn send_data(&mut self, data: &[u8]) -> Result<bool, WinCryptoError> {
        if self.state != EstablishmentState::Established {
            return Ok(false);
        }
        let Some(security_ctx) = self.security_ctx.as_ref() else {
            return Err("Security Context not generated.".into());
        };

        let header_size = self.encrypt_message_input_sizes.cbHeader as usize;
        let trailer_size = self.encrypt_message_input_sizes.cbTrailer as usize;
        let message_size = data.len();

        let mut output = vec![0u8; header_size + trailer_size + message_size];
        output[header_size..header_size + message_size].copy_from_slice(data);

        let mut sec_buffers = [
            SecBuffer {
                BufferType: SECBUFFER_STREAM_HEADER,
                cbBuffer: header_size as u32,
                pvBuffer: output[0..].as_mut_ptr() as *mut _,
            },
            SecBuffer {
                BufferType: SECBUFFER_DATA,
                cbBuffer: message_size as u32,
                pvBuffer: output[header_size..].as_mut_ptr() as *mut _,
            },
            SecBuffer {
                BufferType: SECBUFFER_STREAM_TRAILER,
                cbBuffer: trailer_size as u32,
                pvBuffer: output[header_size + message_size..].as_mut_ptr() as *mut _,
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EMPTY,
                pvBuffer: std::ptr::null_mut(),
            },
        ];
        let sec_buffer_desc = SecBufferDesc {
            ulVersion: SECBUFFER_VERSION,
            cBuffers: 4,
            pBuffers: sec_buffers.as_mut_ptr() as *mut _,
        };

        // SAFETY: The references passed are all borrow checked. However,
        // it is important to note that `sec_buffer_desc` holds a pointer to
        // a sequence of SecBuffers. Those SecBuffers must exist for the
        // duration of the unsafe block.
        let status = unsafe { EncryptMessage(security_ctx, 0, &sec_buffer_desc, 0) };

        match status {
            SEC_E_OK => {
                self.output_datagrams.push_back(output);
                Ok(true)
            }
            status => Err(status.into()),
        }
    }

    fn handshake(&mut self, datagram: Option<&[u8]>) -> Result<DtlsEvent, WinCryptoError> {
        let Some(is_client) = self.is_client else {
            return Err("handshake attempted without setting is_client".into());
        };
        let mut new_ctx_handle = SecHandle::default();

        let mut buffers = [
            DTLS_MTU_SECBUFFER,
            SRTP_PROTECTION_PROFILES_SECBUFFER,
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_TOKEN,
                pvBuffer: std::ptr::null_mut(),
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EMPTY,
                pvBuffer: std::ptr::null_mut(),
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EXTRA,
                pvBuffer: std::ptr::null_mut(),
            },
        ];

        let in_buffer_desc = match datagram {
            Some(datagram) => {
                buffers[2].cbBuffer = datagram.len() as u32;
                buffers[2].pvBuffer = datagram as *const _ as *mut _;

                SecBufferDesc {
                    ulVersion: SECBUFFER_VERSION,
                    cBuffers: buffers.len() as u32,
                    pBuffers: buffers.as_mut_ptr() as *mut _,
                }
            }
            None => SecBufferDesc {
                ulVersion: SECBUFFER_VERSION,
                cBuffers: 2,
                pBuffers: buffers.as_mut_ptr() as *mut _,
            },
        };

        let mut token_buffer = [0u8; DATAGRAM_MTU];
        let mut alert_buffer = [0u8; DATAGRAM_MTU];
        let mut out_buffers = [
            SecBuffer {
                cbBuffer: token_buffer.len() as u32,
                BufferType: SECBUFFER_TOKEN,
                pvBuffer: token_buffer.as_mut_ptr() as *mut _,
            },
            SecBuffer {
                cbBuffer: alert_buffer.len() as u32,
                BufferType: SECBUFFER_ALERT,
                pvBuffer: alert_buffer.as_mut_ptr() as *mut _,
            },
        ];
        let mut out_buffer_desc = SecBufferDesc {
            cBuffers: out_buffers.len() as u32,
            pBuffers: out_buffers.as_mut_ptr() as *mut _,
            ulVersion: SECBUFFER_VERSION,
        };

        let mut attrs = 0;

        // SAFETY: The references passed are all borrow checked. However,
        // it is important to note that `in_buffer_desc` and `out_buffer_desc`
        // hold pointers to sequence of SecBuffers. Those SecBuffers must exist
        // for the duration of the unsafe block.
        let status = unsafe {
            if is_client {
                // Client
                debug!("InitializeSecurityContextW {:?}", in_buffer_desc);
                InitializeSecurityContextW(
                    self.cred_handle.as_ref().map(|r| r as *const _),
                    self.security_ctx.as_ref().map(|r| r as *const _),
                    None,
                    ISC_REQ_CONFIDENTIALITY
                        | ISC_REQ_EXTENDED_ERROR
                        | ISC_REQ_INTEGRITY
                        | ISC_REQ_DATAGRAM
                        | ISC_REQ_MANUAL_CRED_VALIDATION
                        | ISC_REQ_USE_SUPPLIED_CREDS,
                    0,
                    SECURITY_NATIVE_DREP,
                    Some(&in_buffer_desc),
                    0,
                    Some(&mut new_ctx_handle),
                    Some(&mut out_buffer_desc),
                    &mut attrs,
                    None,
                )
            } else {
                // Server
                debug!(
                    "AcceptSecurityContext {:?} {:?}",
                    in_buffer_desc, out_buffer_desc
                );
                AcceptSecurityContext(
                    self.cred_handle.as_ref().map(|r| r as *const _),
                    self.security_ctx.as_ref().map(|r| r as *const _),
                    Some(&in_buffer_desc),
                    ASC_REQ_CONFIDENTIALITY
                        | ASC_REQ_EXTENDED_ERROR
                        | ASC_REQ_INTEGRITY
                        | ASC_REQ_DATAGRAM
                        | ASC_REQ_MUTUAL_AUTH,
                    SECURITY_NATIVE_DREP,
                    Some(&mut new_ctx_handle),
                    Some(&mut out_buffer_desc),
                    &mut attrs,
                    None,
                )
            }
        };

        debug!("DTLS Handshake status: {status}");
        self.security_ctx = Some(new_ctx_handle);

        // Only output datagram if we have data to send and we didn't fail.
        if (status.is_ok() || status == SEC_E_OK) && out_buffers[0].cbBuffer > 0 {
            let len = out_buffers[0].cbBuffer;
            self.output_datagrams
                .push_back(token_buffer[..len as usize].to_vec());
        }

        match status {
            SEC_E_OK => {
                // Move to Done
                self.transition_to_completed()
            }
            SEC_I_MESSAGE_FRAGMENT => {
                // Fragment was sent, we need to call again to send the next fragment.
                debug!("Sent handshake fragment");
                self.handshake(None)
            }
            status if status.is_ok() => {
                // For any other "OK" status, we just wait for the peer, this
                // includes SEC_I_CONTINUE_NEEDED.
                debug!(?status, "Wait for peer");
                Ok(DtlsEvent::None)
            }
            e => {
                // Failed
                self.state = EstablishmentState::Failed;
                Err(e.into())
            }
        }
    }

    fn transition_to_completed(&mut self) -> Result<DtlsEvent, WinCryptoError> {
        let mut srtp_parameters = SecPkgContext_SrtpParameters::default();
        let Some(security_ctx) = self.security_ctx.as_ref() else {
            return Err("Security context missing".into());
        };

        // SAFETY: The references used in the unsafe block are all borrow checked.
        unsafe {
            QueryContextAttributesW(
                security_ctx as *const _,
                SECPKG_ATTR_STREAM_SIZES,
                &mut self.encrypt_message_input_sizes as *mut _ as *mut std::ffi::c_void,
            )?;

            QueryContextAttributesW(
                security_ctx as *const _,
                SECPKG_ATTR(SECPKG_ATTR_SRTP_PARAMETERS),
                &mut srtp_parameters as *mut _ as *mut std::ffi::c_void,
            )?;
        }

        let srtp_profile_id = u16::from_be(srtp_parameters.ProtectionProfile);
        let keying_material_info = SecPkgContext_KeyingMaterialInfo {
            cbLabel: DTLS_KEY_LABEL.len() as u16,
            pszLabel: windows::core::PSTR(DTLS_KEY_LABEL.as_ptr() as *mut u8),
            cbKeyingMaterial: srtp_keying_material_len(srtp_profile_id)?,
            cbContextValue: 0,
            pbContextValue: std::ptr::null_mut(),
        };
        let mut keying_material = SecPkgContext_KeyingMaterial::default();

        // SAFETY: The references used in the unsafe block are all borrow checked. The
        // only pointers used in those structs are to statically defined values.
        let srtp_keying_material = unsafe {
            SetContextAttributesW(
                security_ctx as *const _,
                SECPKG_ATTR_KEYING_MATERIAL_INFO,
                &keying_material_info as *const _ as *const std::ffi::c_void,
                std::mem::size_of::<SecPkgContext_KeyingMaterialInfo>() as u32,
            )?;

            QueryContextAttributesExW(
                security_ctx as *const _,
                SECPKG_ATTR(SECPKG_ATTR_KEYING_MATERIAL),
                &mut keying_material as *mut _ as *mut std::ffi::c_void,
                std::mem::size_of::<SecPkgContext_KeyingMaterial>() as u32,
            )?;

            // Copy the returned keying material to a Vec.
            let keying_material_vec = std::slice::from_raw_parts(
                keying_material.pbKeyingMaterial,
                keying_material.cbKeyingMaterial as usize,
            )
            .to_vec();

            // Now that we copied the key to the Rust heap, we can free the buffer.
            FreeContextBuffer(keying_material.pbKeyingMaterial as *mut _ as *mut std::ffi::c_void)?;

            keying_material_vec
        };

        // SAFETY: All the passed in values are borrow checked. The raw CERT_CONTEXT
        // pointer does not escpae the block, to avoid leaking the unwrapped pointer.
        let peer_certificate: Certificate = unsafe {
            let mut peer_cert_context: *mut CERT_CONTEXT = std::ptr::null_mut();
            QueryContextAttributesW(
                security_ctx as *const _,
                SECPKG_ATTR_REMOTE_CERT_CONTEXT,
                &mut peer_cert_context as *mut _ as *mut std::ffi::c_void,
            )?;
            (peer_cert_context as *const CERT_CONTEXT).into()
        };

        let peer_cert_der = peer_certificate.get_der_bytes()?;

        self.state = EstablishmentState::Established;
        Ok(DtlsEvent::Connected {
            srtp_profile_id,
            srtp_keying_material,
            peer_cert_der,
        })
    }

    fn process_packet(&mut self, datagram: &[u8]) -> Result<DtlsEvent, WinCryptoError> {
        if self.state != EstablishmentState::Established {
            return Ok(DtlsEvent::WouldBlock);
        }
        let Some(security_ctx) = self.security_ctx.as_ref() else {
            return Err("Security Context not generated.".into());
        };

        let header_size = self.encrypt_message_input_sizes.cbHeader as usize;
        let trailer_size = self.encrypt_message_input_sizes.cbTrailer as usize;

        let mut output = datagram.to_vec();
        let mut alert = [0u8; 512];

        let mut sec_buffers = [
            SecBuffer {
                BufferType: SECBUFFER_DATA,
                cbBuffer: output.len() as u32,
                pvBuffer: output.as_mut_ptr() as *mut _,
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EMPTY,
                pvBuffer: std::ptr::null_mut(),
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EMPTY,
                pvBuffer: std::ptr::null_mut(),
            },
            SecBuffer {
                cbBuffer: 0,
                BufferType: SECBUFFER_EMPTY,
                pvBuffer: std::ptr::null_mut(),
            },
            SecBuffer {
                BufferType: SECBUFFER_ALERT,
                cbBuffer: alert.len() as u32,
                pvBuffer: alert.as_mut_ptr() as *mut _,
            },
        ];
        let sec_buffer_desc = SecBufferDesc {
            ulVersion: SECBUFFER_VERSION,
            cBuffers: 4,
            pBuffers: sec_buffers.as_mut_ptr() as *mut _,
        };

        // SAFETY: All the passed in values are borrow checked. The `sec_buffer_desc`
        // however holds pointers to a SecBuffer list. It's important that those buffers
        // exist through this unsafe block.
        let status = unsafe { DecryptMessage(security_ctx, &sec_buffer_desc, 0, None) };
        match status {
            SEC_E_OK => {
                let data = output[header_size..output.len() - trailer_size].to_vec();
                Ok(DtlsEvent::Data(data))
            }
            SEC_E_MESSAGE_ALTERED => {
                warn!("Packet alteration detected, packet dropped");
                Ok(DtlsEvent::None)
            }
            SEC_E_OUT_OF_SEQUENCE => {
                warn!("Received out of sequence packet");
                Ok(DtlsEvent::None)
            }
            SEC_I_CONTEXT_EXPIRED => {
                self.state = EstablishmentState::Failed;
                Err("Context expired".into())
            }
            SEC_I_RENEGOTIATE => {
                // SChannel provides a token to feed into a new handshake
                if let Some(token_buffer) =
                    sec_buffers.iter().find(|p| p.BufferType == SECBUFFER_EXTRA)
                {
                    self.state = EstablishmentState::Handshaking;
                    let data = token_buffer.pvBuffer as *mut u8;
                    let len = token_buffer.cbBuffer as usize;

                    // SAFETY: We don't want to copy the data, so we will create a slice
                    // from the pointer and length, and pass it on. The pointer is required
                    // to actually be part of all of the buffers passed in, so the slice
                    // is valid so long as `sec_buffers` is.
                    self.handshake(Some(unsafe { std::slice::from_raw_parts(data, len) }))
                } else {
                    Err("Renegotiate didn't include a token".into())
                }
            }
            status => Err(status.into()),
        }
    }
}

impl Drop for Dtls {
    fn drop(&mut self) {
        // SAFETY: The handles here are no longer needed and cannot be accessed outside
        // this struct, so it's safe to Delete/Free them here.
        unsafe {
            if let Some(ctx_handle) = self.security_ctx {
                if let Err(e) = DeleteSecurityContext(&ctx_handle) {
                    debug!(
                        "DeleteSecurityContext returned error, likely already invalid: {:?}",
                        e
                    );
                }
            }
            if let Some(cred_handle) = self.cred_handle {
                if let Err(e) = FreeCredentialsHandle(&cred_handle) {
                    debug!(
                        "FreeCredentialsHandle returned error, likely already invalid: {:?}",
                        e
                    );
                }
            }
        }
    }
}

fn srtp_keying_material_len(srtp_profile_id: u16) -> Result<u32, WinCryptoError> {
    match srtp_profile_id {
        0x0001 => Ok(16 * 2 + 14 * 2),
        0x0007 => Ok(16 * 2 + 12 * 2),
        0x0008 => Ok(32 * 2 + 12 * 2),
        id => Err(format!("Unknown SRTP Profile Requested: {id}").into()),
    }
}