ifd-jcecard 0.2.0

PC/SC IFD Handler for jcecard virtual OpenPGP and PIV smart card
Documentation
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! PIV Applet implementation
//!
//! Main dispatcher for PIV card commands following NIST SP 800-73-4.

use crate::apdu::{APDU, Response, SW};
use crate::tlv::{TLVBuilder, TLVEncoder};
use crate::crypto::rsa::RsaOperations;
use crate::crypto::ecc_nist::{EccNistOperations, EccCurve};
use crate::crypto::tdes::TDesOperations;
use super::data_objects::{PIVDataObjects, PIVKeySlot, PIVAlgorithm, PIVKeyData};
use super::security_state::PIVSecurityState;
use log::{debug, info, warn};

/// PIV Application Identifier
pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08];

/// PIV Key Reference bytes
pub mod key_ref {
    pub const PIV_PIN: u8 = 0x80;
    pub const PIV_PUK: u8 = 0x81;
    pub const MGMT_KEY: u8 = 0x9B;
}

/// PIV Card Applet
pub struct PIVApplet {
    data_objects: PIVDataObjects,
    security_state: PIVSecurityState,
    response_buffer: Vec<u8>,
    response_offset: usize,
    current_challenge: Option<Vec<u8>>,
    version: (u8, u8, u8),
    serial: u32,
    /// Buffer for command chaining (PUT DATA with large certificates)
    command_chain_buffer: Vec<u8>,
    /// INS of the command being chained
    command_chain_ins: Option<u8>,
    /// P1 of the command being chained
    command_chain_p1: u8,
    /// P2 of the command being chained
    command_chain_p2: u8,
}

impl PIVApplet {
    /// Create a new PIV applet
    pub fn new() -> Self {
        // Generate random serial
        let mut serial_bytes = [0u8; 4];
        use rand::RngCore;
        rand::rngs::OsRng.fill_bytes(&mut serial_bytes);
        let serial = u32::from_be_bytes(serial_bytes);

        Self {
            data_objects: PIVDataObjects::new(),
            security_state: PIVSecurityState::new(),
            response_buffer: Vec::new(),
            response_offset: 0,
            current_challenge: None,
            version: (1, 0, 0),
            serial,
            command_chain_buffer: Vec::new(),
            command_chain_ins: None,
            command_chain_p1: 0,
            command_chain_p2: 0,
        }
    }

    /// Process an APDU command and return the response
    pub fn process_apdu(&mut self, cmd: &APDU) -> Response {
        debug!("PIV APDU: CLA={:02X} INS={:02X} P1={:02X} P2={:02X} data_len={}",
               cmd.cla, cmd.ins, cmd.p1, cmd.p2, cmd.data.len());

        // Check for command chaining (CLA bit 4 set means more data follows)
        let is_chaining = (cmd.cla & 0x10) != 0;

        // Handle command chaining for PUT DATA (large certificates)
        if is_chaining || self.command_chain_ins.is_some() {
            // If this is a new chain, store the command parameters
            if self.command_chain_ins.is_none() {
                self.command_chain_ins = Some(cmd.ins);
                self.command_chain_p1 = cmd.p1;
                self.command_chain_p2 = cmd.p2;
                self.command_chain_buffer.clear();
            }

            // Verify same instruction for chained commands
            if self.command_chain_ins != Some(cmd.ins) {
                self.command_chain_ins = None;
                self.command_chain_buffer.clear();
                return Response::error(SW::CONDITIONS_NOT_SATISFIED);
            }

            // Append data to buffer
            self.command_chain_buffer.extend_from_slice(&cmd.data);
            debug!("Command chaining: buffered {} bytes, total {}",
                   cmd.data.len(), self.command_chain_buffer.len());

            if is_chaining {
                // More data expected, return success
                return Response::ok();
            } else {
                // Last in chain - process the complete data
                let complete_cmd = APDU {
                    cla: cmd.cla & 0xEF, // Clear chaining bit
                    ins: self.command_chain_ins.unwrap(),
                    p1: self.command_chain_p1,
                    p2: self.command_chain_p2,
                    data: std::mem::take(&mut self.command_chain_buffer),
                    le: cmd.le,
                };
                self.command_chain_ins = None;

                debug!("Command chain complete: {} bytes total", complete_cmd.data.len());

                // Process the complete command
                return match complete_cmd.ins {
                    0xDB => self.handle_put_data(&complete_cmd),
                    _ => {
                        warn!("Command chaining not supported for INS {:02X}", complete_cmd.ins);
                        Response::error(SW::INS_NOT_SUPPORTED)
                    }
                };
            }
        }

        match cmd.ins {
            0xA4 => self.handle_select(cmd),
            0x20 => self.handle_verify(cmd),
            0x24 => self.handle_change_reference_data(cmd),
            0x2C => self.handle_reset_retry_counter(cmd),
            0xCB => self.handle_get_data(cmd),
            0xDB => self.handle_put_data(cmd),
            0x47 => self.handle_generate_key(cmd),
            0x87 => self.handle_general_authenticate(cmd),
            0xC0 => self.handle_get_response(cmd),
            0xFD => self.handle_get_version(cmd),
            0xF8 => self.handle_get_serial(cmd),
            _ => {
                warn!("Unknown PIV instruction: {:02X}", cmd.ins);
                Response::error(SW::INS_NOT_SUPPORTED)
            }
        }
    }

    /// Get a reference to the data objects
    pub fn get_data_objects(&self) -> &PIVDataObjects {
        &self.data_objects
    }

    /// Get a mutable reference to the data objects
    pub fn get_data_objects_mut(&mut self) -> &mut PIVDataObjects {
        &mut self.data_objects
    }

    /// Reset security state (on card reset)
    pub fn reset(&mut self) {
        self.security_state.clear_all();
        self.response_buffer.clear();
        self.response_offset = 0;
        self.current_challenge = None;
    }

    // =========================================================================
    // Command Handlers
    // =========================================================================

    /// Handle SELECT command (INS A4)
    fn handle_select(&mut self, cmd: &APDU) -> Response {
        if cmd.p1 != 0x04 {
            return Response::error(SW::WRONG_P1_P2);
        }

        // Check AID
        if !cmd.data.starts_with(PIV_AID) {
            return Response::error(SW::FILE_NOT_FOUND);
        }

        self.security_state.clear_all();
        self.current_challenge = None;

        // Build response: Application Property Template
        let response_data = [
            0x4F, 0x06, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00,  // Application identifier (PIV version 1.0)
            0x79, 0x07,  // Coexistent tag allocation authority
            0x4F, 0x05,  // AID tag
        ].iter().chain(PIV_AID.iter()).copied().collect::<Vec<u8>>();

        info!("PIV application selected");
        Response::success(response_data)
    }

    /// Handle VERIFY command (INS 20)
    fn handle_verify(&mut self, cmd: &APDU) -> Response {
        match cmd.p2 {
            key_ref::PIV_PIN => {
                if cmd.data.is_empty() {
                    // Return retry counter
                    return Response::counter_warning(self.data_objects.pin_retries);
                }

                // Strip FF padding
                let pin: Vec<u8> = cmd.data.iter()
                    .take_while(|&&b| b != 0xFF)
                    .copied()
                    .collect();

                if self.data_objects.pin_retries == 0 {
                    return Response::error(SW::AUTH_METHOD_BLOCKED);
                }

                if pin == self.data_objects.pin {
                    self.security_state.set_pin_verified(true);
                    self.data_objects.pin_retries = 3; // Reset counter
                    info!("PIV PIN verified successfully");
                    Response::ok()
                } else {
                    self.data_objects.pin_retries = self.data_objects.pin_retries.saturating_sub(1);
                    warn!("PIV PIN verification failed, {} retries remaining", self.data_objects.pin_retries);
                    if self.data_objects.pin_retries == 0 {
                        Response::error(SW::AUTH_METHOD_BLOCKED)
                    } else {
                        Response::counter_warning(self.data_objects.pin_retries)
                    }
                }
            }
            key_ref::PIV_PUK => {
                if cmd.data.is_empty() {
                    return Response::counter_warning(self.data_objects.puk_retries);
                }

                if self.data_objects.puk_retries == 0 {
                    return Response::error(SW::AUTH_METHOD_BLOCKED);
                }

                if cmd.data == self.data_objects.puk {
                    self.data_objects.puk_retries = 3;
                    Response::ok()
                } else {
                    self.data_objects.puk_retries = self.data_objects.puk_retries.saturating_sub(1);
                    if self.data_objects.puk_retries == 0 {
                        Response::error(SW::AUTH_METHOD_BLOCKED)
                    } else {
                        Response::counter_warning(self.data_objects.puk_retries)
                    }
                }
            }
            _ => Response::error(SW::WRONG_P1_P2),
        }
    }

    /// Handle CHANGE REFERENCE DATA command (INS 24)
    fn handle_change_reference_data(&mut self, cmd: &APDU) -> Response {
        if cmd.data.len() != 16 {
            return Response::error(SW::WRONG_LENGTH);
        }

        let old_value: Vec<u8> = cmd.data[..8].iter()
            .take_while(|&&b| b != 0xFF)
            .copied()
            .collect();
        let new_value: Vec<u8> = cmd.data[8..].iter()
            .take_while(|&&b| b != 0xFF)
            .copied()
            .collect();

        match cmd.p2 {
            key_ref::PIV_PIN => {
                if self.data_objects.pin_retries == 0 {
                    return Response::error(SW::AUTH_METHOD_BLOCKED);
                }

                if old_value == self.data_objects.pin {
                    self.data_objects.pin = new_value;
                    self.data_objects.pin_retries = 3;
                    info!("PIV PIN changed successfully");
                    Response::ok()
                } else {
                    self.data_objects.pin_retries = self.data_objects.pin_retries.saturating_sub(1);
                    if self.data_objects.pin_retries == 0 {
                        Response::error(SW::AUTH_METHOD_BLOCKED)
                    } else {
                        Response::counter_warning(self.data_objects.pin_retries)
                    }
                }
            }
            key_ref::PIV_PUK => {
                if self.data_objects.puk_retries == 0 {
                    return Response::error(SW::AUTH_METHOD_BLOCKED);
                }

                if old_value == self.data_objects.puk {
                    self.data_objects.puk = new_value;
                    self.data_objects.puk_retries = 3;
                    info!("PIV PUK changed successfully");
                    Response::ok()
                } else {
                    self.data_objects.puk_retries = self.data_objects.puk_retries.saturating_sub(1);
                    if self.data_objects.puk_retries == 0 {
                        Response::error(SW::AUTH_METHOD_BLOCKED)
                    } else {
                        Response::counter_warning(self.data_objects.puk_retries)
                    }
                }
            }
            _ => Response::error(SW::WRONG_P1_P2),
        }
    }

    /// Handle RESET RETRY COUNTER command (INS 2C)
    fn handle_reset_retry_counter(&mut self, cmd: &APDU) -> Response {
        if cmd.p2 != key_ref::PIV_PIN {
            return Response::error(SW::WRONG_P1_P2);
        }

        if cmd.data.len() != 16 {
            return Response::error(SW::WRONG_LENGTH);
        }

        let puk = &cmd.data[..8];
        let new_pin: Vec<u8> = cmd.data[8..].iter()
            .take_while(|&&b| b != 0xFF)
            .copied()
            .collect();

        if self.data_objects.puk_retries == 0 {
            return Response::error(SW::AUTH_METHOD_BLOCKED);
        }

        if puk == self.data_objects.puk.as_slice() {
            self.data_objects.pin = new_pin;
            self.data_objects.pin_retries = 3;
            self.data_objects.puk_retries = 3;
            info!("PIV PIN reset with PUK successfully");
            Response::ok()
        } else {
            self.data_objects.puk_retries = self.data_objects.puk_retries.saturating_sub(1);
            if self.data_objects.puk_retries == 0 {
                Response::error(SW::AUTH_METHOD_BLOCKED)
            } else {
                Response::counter_warning(self.data_objects.puk_retries)
            }
        }
    }

    /// Handle GET DATA command (INS CB)
    fn handle_get_data(&self, cmd: &APDU) -> Response {
        if cmd.p1 != 0x3F || cmd.p2 != 0xFF {
            return Response::error(SW::WRONG_P1_P2);
        }

        // Parse TLV to get object ID (5C tag)
        if cmd.data.len() < 2 || cmd.data[0] != 0x5C {
            return Response::error(SW::WRONG_DATA);
        }

        let tag_len = cmd.data[1] as usize;
        if cmd.data.len() < 2 + tag_len {
            return Response::error(SW::WRONG_DATA);
        }

        let object_id = &cmd.data[2..2 + tag_len];

        // Get the data object
        let data = match object_id {
            // Card Holder Unique Identifier (CHUID) - 5FC102
            [0x5F, 0xC1, 0x02] => {
                if self.data_objects.chuid.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.chuid
            }
            // Cardholder Capability Container (CCC) - 5FC107
            [0x5F, 0xC1, 0x07] => {
                if self.data_objects.ccc.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.ccc
            }
            // X.509 Certificate for PIV Authentication - 5FC105
            [0x5F, 0xC1, 0x05] => {
                if self.data_objects.key_9a.certificate.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.key_9a.certificate
            }
            // X.509 Certificate for Digital Signature - 5FC10A
            [0x5F, 0xC1, 0x0A] => {
                if self.data_objects.key_9c.certificate.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.key_9c.certificate
            }
            // X.509 Certificate for Key Management - 5FC10B
            [0x5F, 0xC1, 0x0B] => {
                if self.data_objects.key_9d.certificate.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.key_9d.certificate
            }
            // X.509 Certificate for Card Authentication - 5FC101
            [0x5F, 0xC1, 0x01] => {
                if self.data_objects.key_9e.certificate.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.key_9e.certificate
            }
            // Discovery Object - 7E
            [0x7E] => {
                if self.data_objects.discovery.is_empty() {
                    return Response::error(SW::FILE_NOT_FOUND);
                }
                &self.data_objects.discovery
            }
            _ => {
                debug!("Unknown PIV data object: {:02X?}", object_id);
                return Response::error(SW::FILE_NOT_FOUND);
            }
        };

        // Wrap in 53 tag
        let response = TLVEncoder::encode(0x53, data);
        debug!("GET DATA for object {:02X?}: {} bytes", object_id, response.len());
        Response::success(response)
    }

    /// Handle PUT DATA command (INS DB)
    fn handle_put_data(&mut self, cmd: &APDU) -> Response {
        if !self.security_state.is_management_key_authenticated() {
            return Response::error(SW::SECURITY_STATUS_NOT_SATISFIED);
        }

        if cmd.p1 != 0x3F || cmd.p2 != 0xFF {
            return Response::error(SW::WRONG_P1_P2);
        }

        // Parse TLV to get object ID (5C tag)
        if cmd.data.len() < 2 || cmd.data[0] != 0x5C {
            return Response::error(SW::WRONG_DATA);
        }

        let tag_len = cmd.data[1] as usize;
        if cmd.data.len() < 2 + tag_len {
            return Response::error(SW::WRONG_DATA);
        }

        let object_id = &cmd.data[2..2 + tag_len];
        let remaining = &cmd.data[2 + tag_len..];

        // Find the data (53 tag)
        if remaining.is_empty() || remaining[0] != 0x53 {
            return Response::error(SW::WRONG_DATA);
        }

        // Parse length
        let (data_len, data_offset) = if remaining.len() < 2 {
            return Response::error(SW::WRONG_DATA);
        } else if remaining[1] == 0x82 {
            if remaining.len() < 4 {
                return Response::error(SW::WRONG_DATA);
            }
            let len = ((remaining[2] as usize) << 8) | (remaining[3] as usize);
            (len, 4)
        } else if remaining[1] == 0x81 {
            if remaining.len() < 3 {
                return Response::error(SW::WRONG_DATA);
            }
            (remaining[2] as usize, 3)
        } else {
            (remaining[1] as usize, 2)
        };

        if remaining.len() < data_offset + data_len {
            return Response::error(SW::WRONG_DATA);
        }

        let data = remaining[data_offset..data_offset + data_len].to_vec();

        // Store the data
        match object_id {
            [0x5F, 0xC1, 0x02] => self.data_objects.chuid = data,
            [0x5F, 0xC1, 0x07] => self.data_objects.ccc = data,
            [0x5F, 0xC1, 0x05] => self.data_objects.key_9a.certificate = data,
            [0x5F, 0xC1, 0x0A] => self.data_objects.key_9c.certificate = data,
            [0x5F, 0xC1, 0x0B] => self.data_objects.key_9d.certificate = data,
            [0x5F, 0xC1, 0x01] => self.data_objects.key_9e.certificate = data,
            [0x7E] => self.data_objects.discovery = data,
            _ => {
                debug!("Unknown PIV data object for PUT: {:02X?}", object_id);
                return Response::error(SW::FILE_NOT_FOUND);
            }
        }

        info!("PUT DATA for object {:02X?}: {} bytes", object_id, data_len);
        Response::ok()
    }

    /// Handle GENERATE ASYMMETRIC KEY PAIR command (INS 47)
    fn handle_generate_key(&mut self, cmd: &APDU) -> Response {
        if !self.security_state.is_management_key_authenticated() {
            return Response::error(SW::SECURITY_STATUS_NOT_SATISFIED);
        }

        // Get slot from P2
        let slot = match PIVKeySlot::from_byte(cmd.p2) {
            Some(s) => s,
            None => return Response::error(SW::WRONG_P1_P2),
        };

        // Parse algorithm from data (AC 03 80 01 XX)
        if cmd.data.len() < 5 || cmd.data[0] != 0xAC {
            return Response::error(SW::WRONG_DATA);
        }

        // Find 80 tag for algorithm
        let mut idx = 2;
        let mut algorithm_byte = None;
        while idx + 2 <= cmd.data.len() {
            let tag = cmd.data[idx];
            let length = cmd.data[idx + 1] as usize;
            if tag == 0x80 && length == 1 && idx + 2 < cmd.data.len() {
                algorithm_byte = Some(cmd.data[idx + 2]);
                break;
            }
            idx += 2 + length;
        }

        let algorithm = match algorithm_byte.and_then(PIVAlgorithm::from_byte) {
            Some(a) => a,
            None => return Response::error(SW::WRONG_DATA),
        };

        info!("Generating {:?} key in slot {:?}", algorithm, slot);

        match algorithm {
            PIVAlgorithm::RSA2048 => self.generate_rsa_key(slot, 2048),
            PIVAlgorithm::ECCP256 => self.generate_ecc_key(slot, algorithm),
            PIVAlgorithm::ECCP384 => self.generate_ecc_key(slot, algorithm),
            PIVAlgorithm::TDES => Response::error(SW::FUNCTION_NOT_SUPPORTED),
        }
    }

    /// Generate RSA key pair
    fn generate_rsa_key(&mut self, slot: PIVKeySlot, bits: usize) -> Response {
        match RsaOperations::generate_keypair(bits) {
            Ok((priv_key, pub_key_data)) => {
                let n = RsaOperations::get_modulus(&pub_key_data).unwrap_or_default();
                let e = RsaOperations::get_exponent(&pub_key_data).unwrap_or_default();

                // Build public key response (7F49 template)
                let pub_tlv = TLVBuilder::new()
                    .add(0x81, &n)
                    .add(0x82, &e)
                    .wrap(0x7F49)
                    .build();

                // Store key
                if let Some(key_data) = self.data_objects.get_key_mut(slot) {
                    key_data.algorithm = PIVAlgorithm::RSA2048 as u8;
                    key_data.private_key = priv_key;
                    key_data.public_key = pub_tlv.clone();
                }

                info!("Generated RSA-{} key in slot {:?}, modulus {} bytes", bits, slot, n.len());
                Response::success(pub_tlv)
            }
            Err(_) => Response::error(SW::EXEC_ERROR),
        }
    }

    /// Generate ECC key pair
    fn generate_ecc_key(&mut self, slot: PIVKeySlot, algorithm: PIVAlgorithm) -> Response {
        let curve = if algorithm == PIVAlgorithm::ECCP256 {
            EccCurve::P256
        } else {
            EccCurve::P384
        };

        match EccNistOperations::generate_keypair(curve) {
            Ok((priv_key, pub_point)) => {
                // Build public key response (7F49 template with 86 tag for EC point)
                let pub_tlv = TLVBuilder::new()
                    .add(0x86, &pub_point)
                    .wrap(0x7F49)
                    .build();

                // Store key
                if let Some(key_data) = self.data_objects.get_key_mut(slot) {
                    key_data.algorithm = algorithm as u8;
                    key_data.private_key = priv_key;
                    key_data.public_key = pub_tlv.clone();
                }

                info!("Generated ECC {:?} key in slot {:?}", algorithm, slot);
                Response::success(pub_tlv)
            }
            Err(_) => Response::error(SW::EXEC_ERROR),
        }
    }

    /// Handle GENERAL AUTHENTICATE command (INS 87)
    fn handle_general_authenticate(&mut self, cmd: &APDU) -> Response {
        let _algo = cmd.p1;
        let key_ref = cmd.p2;

        // Parse 7C template
        if cmd.data.is_empty() || cmd.data[0] != 0x7C {
            return Response::error(SW::WRONG_DATA);
        }

        // Parse contents
        let contents = if cmd.data.len() > 2 { &cmd.data[2..] } else { &[] };
        let mut tags: std::collections::HashMap<u8, Vec<u8>> = std::collections::HashMap::new();
        let mut idx = 0;
        while idx + 1 < contents.len() {
            let tag = contents[idx];
            let length = contents[idx + 1] as usize;
            let value = if idx + 2 + length <= contents.len() {
                contents[idx + 2..idx + 2 + length].to_vec()
            } else {
                Vec::new()
            };
            tags.insert(tag, value);
            idx += 2 + length;
        }

        // Management key authentication
        if key_ref == key_ref::MGMT_KEY {
            return self.authenticate_mgmt_key(&tags);
        }

        // Key operations (signing, decryption)
        let slot = match PIVKeySlot::from_byte(key_ref) {
            Some(s) => s,
            None => return Response::error(SW::WRONG_P1_P2),
        };

        // Check PIN for slots that require it (not card authentication)
        if slot != PIVKeySlot::CardAuthentication && !self.security_state.is_pin_verified() {
            return Response::error(SW::SECURITY_STATUS_NOT_SATISFIED);
        }

        // Get key for this slot
        let key_data = match self.data_objects.get_key(slot) {
            Some(k) if !k.private_key.is_empty() => k.clone(),
            _ => return Response::error(SW::REFERENCED_DATA_NOT_FOUND),
        };

        // Handle signing (82 tag with empty value = request signature)
        if let Some(empty_82) = tags.get(&0x82) {
            if empty_82.is_empty() {
                if let Some(challenge) = tags.get(&0x81) {
                    return self.sign_data(&key_data, challenge);
                }
                return Response::error(SW::WRONG_DATA);
            }
        }

        // Handle decryption/ECDH (85 tag for cipher text)
        if let Some(cipher_text) = tags.get(&0x85) {
            return self.decrypt_data(&key_data, cipher_text);
        }

        Response::error(SW::WRONG_DATA)
    }

    /// Authenticate management key using challenge-response
    fn authenticate_mgmt_key(&mut self, tags: &std::collections::HashMap<u8, Vec<u8>>) -> Response {
        // Step 1: Request challenge (empty 80 tag)
        if let Some(witness_tag) = tags.get(&0x80) {
            if witness_tag.is_empty() && !tags.contains_key(&0x81) {
                // Generate random witness (challenge)
                let mut witness = vec![0u8; 8];
                use rand::RngCore;
                rand::rngs::OsRng.fill_bytes(&mut witness);
                self.current_challenge = Some(witness.clone());

                // Encrypt the witness with management key
                match TDesOperations::encrypt_ecb(&self.data_objects.management_key, &witness) {
                    Ok(encrypted_witness) => {
                        let mut response = vec![0x7C, 0x0A, 0x80, 0x08];
                        response.extend_from_slice(&encrypted_witness);
                        debug!("Management key auth: witness {:02X?}, encrypted {:02X?}", witness, encrypted_witness);
                        return Response::success(response);
                    }
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                }
            }
        }

        // Step 2: Verify response and host challenge
        if let (Some(host_witness), Some(host_challenge)) = (tags.get(&0x80), tags.get(&0x81)) {
            let original_challenge = match &self.current_challenge {
                Some(c) => c.clone(),
                None => return Response::error(SW::CONDITIONS_NOT_SATISFIED),
            };

            debug!("Original witness: {:02X?}", original_challenge);
            debug!("Host witness (plaintext): {:02X?}", host_witness);

            // Host should have decrypted our encrypted witness to get the original witness
            if host_witness.as_slice() != original_challenge.as_slice() {
                warn!("Management key authentication failed");
                self.current_challenge = None;
                return Response::error(SW::SECURITY_STATUS_NOT_SATISFIED);
            }

            // Encrypt host challenge and return in 82 tag
            match TDesOperations::encrypt_ecb(&self.data_objects.management_key, host_challenge) {
                Ok(our_response) => {
                    self.security_state.set_management_key_authenticated(true);
                    self.current_challenge = None;

                    let mut response = vec![0x7C, 0x0A, 0x82, 0x08];
                    response.extend_from_slice(&our_response);
                    info!("Management key authenticated successfully");
                    return Response::success(response);
                }
                Err(_) => {
                    self.current_challenge = None;
                    return Response::error(SW::EXEC_ERROR);
                }
            }
        }

        Response::error(SW::WRONG_DATA)
    }

    /// Sign data with the private key
    fn sign_data(&self, key_data: &PIVKeyData, data: &[u8]) -> Response {
        let algorithm = PIVAlgorithm::from_byte(key_data.algorithm);

        let signature = match algorithm {
            Some(PIVAlgorithm::RSA2048) => {
                // For RSA, need to decode private key and sign
                let n = match RsaOperations::get_modulus(&key_data.public_key) {
                    Some(n) => n,
                    None => return Response::error(SW::EXEC_ERROR),
                };
                let rsa_key = match RsaOperations::decode_private_key(&key_data.private_key, &n) {
                    Ok(key) => key,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                };
                match RsaOperations::raw_sign(&rsa_key, data) {
                    Ok(sig) => sig,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                }
            }
            Some(PIVAlgorithm::ECCP256) => {
                match EccNistOperations::sign(EccCurve::P256, &key_data.private_key, data) {
                    Ok(sig) => sig,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                }
            }
            Some(PIVAlgorithm::ECCP384) => {
                match EccNistOperations::sign(EccCurve::P384, &key_data.private_key, data) {
                    Ok(sig) => sig,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                }
            }
            _ => return Response::error(SW::FUNCTION_NOT_SUPPORTED),
        };

        // Return signature in 7C template with 82 tag
        let response = if signature.len() <= 127 {
            let mut resp = vec![0x7C, (signature.len() + 2) as u8, 0x82, signature.len() as u8];
            resp.extend_from_slice(&signature);
            resp
        } else {
            let mut resp = vec![0x7C, 0x81, (signature.len() + 3) as u8, 0x82, 0x81, signature.len() as u8];
            resp.extend_from_slice(&signature);
            resp
        };

        debug!("Signed {} bytes, signature {} bytes", data.len(), signature.len());
        Response::success(response)
    }

    /// Decrypt data or perform ECDH
    fn decrypt_data(&self, key_data: &PIVKeyData, cipher_text: &[u8]) -> Response {
        let algorithm = PIVAlgorithm::from_byte(key_data.algorithm);

        let plaintext = match algorithm {
            Some(PIVAlgorithm::RSA2048) => {
                let n = match RsaOperations::get_modulus(&key_data.public_key) {
                    Some(n) => n,
                    None => return Response::error(SW::EXEC_ERROR),
                };
                let rsa_key = match RsaOperations::decode_private_key(&key_data.private_key, &n) {
                    Ok(key) => key,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                };
                match RsaOperations::decrypt(&rsa_key, cipher_text) {
                    Ok(pt) => pt,
                    Err(_) => return Response::error(SW::EXEC_ERROR),
                }
            }
            Some(PIVAlgorithm::ECCP256) | Some(PIVAlgorithm::ECCP384) => {
                // ECDH not implemented yet
                // TODO: Add ECDH support to ecc_nist module
                return Response::error(SW::FUNCTION_NOT_SUPPORTED);
            }
            _ => return Response::error(SW::FUNCTION_NOT_SUPPORTED),
        };

        // Return result in 7C template with 82 tag
        let response = if plaintext.len() <= 127 {
            let mut resp = vec![0x7C, (plaintext.len() + 2) as u8, 0x82, plaintext.len() as u8];
            resp.extend_from_slice(&plaintext);
            resp
        } else {
            let mut resp = vec![0x7C, 0x81, (plaintext.len() + 3) as u8, 0x82, 0x81, plaintext.len() as u8];
            resp.extend_from_slice(&plaintext);
            resp
        };

        debug!("Decrypted/ECDH result: {} bytes", plaintext.len());
        Response::success(response)
    }

    /// Handle GET RESPONSE command (INS C0)
    fn handle_get_response(&mut self, cmd: &APDU) -> Response {
        if self.response_buffer.is_empty() {
            return Response::error(SW::CONDITIONS_NOT_SATISFIED);
        }

        let le = cmd.le.unwrap_or(256) as usize;
        let remaining = self.response_buffer.len() - self.response_offset;
        let to_send = std::cmp::min(le, remaining);

        let data = self.response_buffer[self.response_offset..self.response_offset + to_send].to_vec();
        self.response_offset += to_send;

        if self.response_offset >= self.response_buffer.len() {
            // All data sent
            self.response_buffer.clear();
            self.response_offset = 0;
            Response::success(data)
        } else {
            // More data available
            let still_remaining = self.response_buffer.len() - self.response_offset;
            Response::more_data(data, std::cmp::min(still_remaining, 255) as u8)
        }
    }

    /// Handle GET VERSION command (INS FD) - Yubico extension
    fn handle_get_version(&self, _cmd: &APDU) -> Response {
        let data = vec![self.version.0, self.version.1, self.version.2];
        Response::success(data)
    }

    /// Handle GET SERIAL command (INS F8) - Yubico extension
    fn handle_get_serial(&self, _cmd: &APDU) -> Response {
        let data = self.serial.to_be_bytes().to_vec();
        Response::success(data)
    }
}

impl Default for PIVApplet {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_select_piv() {
        let mut applet = PIVApplet::new();
        let cmd = APDU {
            cla: 0x00,
            ins: 0xA4,
            p1: 0x04,
            p2: 0x00,
            data: PIV_AID.to_vec(),
            le: None,
        };
        let response = applet.process_apdu(&cmd);
        assert!(response.is_okay());
    }

    #[test]
    fn test_verify_pin() {
        let mut applet = PIVApplet::new();

        // First select
        let select_cmd = APDU {
            cla: 0x00,
            ins: 0xA4,
            p1: 0x04,
            p2: 0x00,
            data: PIV_AID.to_vec(),
            le: None,
        };
        applet.process_apdu(&select_cmd);

        // Verify PIN
        let mut pin_data = b"123456".to_vec();
        pin_data.extend(vec![0xFF; 2]); // Pad to 8 bytes
        let verify_cmd = APDU {
            cla: 0x00,
            ins: 0x20,
            p1: 0x00,
            p2: 0x80,
            data: pin_data,
            le: None,
        };
        let response = applet.process_apdu(&verify_cmd);
        assert!(response.is_okay());
    }

    #[test]
    fn test_get_version() {
        let mut applet = PIVApplet::new();
        let cmd = APDU {
            cla: 0x00,
            ins: 0xFD,
            p1: 0x00,
            p2: 0x00,
            data: Vec::new(),
            le: None,
        };
        let response = applet.process_apdu(&cmd);
        assert!(response.is_okay());
        assert_eq!(response.data.len(), 3);
        assert_eq!(response.data[0], 1); // Major version
    }

    #[test]
    fn test_get_serial() {
        let mut applet = PIVApplet::new();
        let cmd = APDU {
            cla: 0x00,
            ins: 0xF8,
            p1: 0x00,
            p2: 0x00,
            data: Vec::new(),
            le: None,
        };
        let response = applet.process_apdu(&cmd);
        assert!(response.is_okay());
        assert_eq!(response.data.len(), 4);
    }
}