Initial commit

This commit is contained in:
Milan Stute
2021-03-03 14:19:09 +01:00
commit 52dde375e3
93 changed files with 8048 additions and 0 deletions

35
.github/workflows/build-app.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: "Build application"
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
lint-swiftlint:
runs-on: macos-latest
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Run SwiftLint"
run: swiftlint --reporter github-actions-logging
build-app:
runs-on: macos-latest
needs: lint-swiftlint
env:
APP: OpenHaystack
PROJECT_DIR: OpenHaystack
defaults:
run:
working-directory: ${{ env.PROJECT_DIR }}
steps:
- name: "Checkout code"
uses: actions/checkout@v2
- name: "Select Xcode 12"
uses: devbotsxyz/xcode-select@v1
with:
version: "12"
- name: "Archive project"
run: xcodebuild archive -scheme ${APP} -configuration release -archivePath ${APP}.xcarchive

27
.github/workflows/build-firmware.yaml vendored Normal file
View File

@@ -0,0 +1,27 @@
name: "Build firmware"
on:
push:
branches: [ main ]
paths:
- Firmware/**
pull_request:
branches: [ main ]
paths:
- Firmware/**
defaults:
run:
working-directory: Firmware
jobs:
build-firmware:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
# Build firmware image
- name: "Install build dependencies"
run: brew install --cask gcc-arm-embedded
- name: "Build firmware image"
run: make

51
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,51 @@
name: "Create release"
on:
push:
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
jobs:
build-and-release:
name: "Create release on GitHub"
runs-on: macos-latest
env:
APP: OpenHaystack
PROJECT_DIR: OpenHaystack
defaults:
run:
working-directory: ${{ env.PROJECT_DIR }}
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: "Select Xcode 12"
uses: devbotsxyz/xcode-select@v1
with:
version: "12"
- name: "Archive project"
run: xcodebuild archive -scheme ${APP} -configuration release -archivePath ${APP}.xcarchive
- name: "Create ZIP"
run: |
pushd ${APP}.xcarchive/Products/Applications
zip -r ../../../${APP}.zip ${APP}.app
popd
- name: "Create release"
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
- name: "Upload release asset"
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ${{ env.PROJECT_DIR }}/${{ env.APP }}.zip
asset_name: ${{ env.APP }}.zip
asset_content_type: application/zip

109
.gitignore vendored Normal file
View File

@@ -0,0 +1,109 @@
# Created by https://www.toptal.com/developers/gitignore/api/xcode,swift
# Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift
### Swift ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
## Obj-C/Swift specific
*.hmap
## App packaging
*.ipa
*.dSYM.zip
*.dSYM
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
# Package.pins
# Package.resolved
# *.xcodeproj
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm
.build/
# CocoaPods
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
# Pods/
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build/
# Accio dependency management
Dependencies/
.accio/
# fastlane
# It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output
# Code Injection
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
### Xcode ###
# Xcode
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Gcc Patch
/*.gcno
### Xcode Patch ###
*.xcodeproj/*
!*.xcodeproj/project.pbxproj
!*.xcodeproj/xcshareddata/
!*.xcworkspace/contents.xcworkspacedata
**/xcshareddata/WorkspaceSettings.xcsettings
# End of https://www.toptal.com/developers/gitignore/api/xcode,swift
# Exports folder
Exports/

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "Firmware/blessed"]
path = Firmware/blessed
url = https://github.com/pauloborges/blessed.git

9
Firmware/.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
# nRF SDK
nrf51_sdk_v4_4_2_33551/
nrf51_sdk_v4_4_2_33551.zip
# Build artifacts
*.bin
*.map
*.out
*.o

8
Firmware/LICENSE Normal file
View File

@@ -0,0 +1,8 @@
Copyright 2021 Secure Mobile Networking Lab (SEEMOO)
Copyright 2021 The Open Wireless Link Project
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

34
Firmware/Makefile Normal file
View File

@@ -0,0 +1,34 @@
PLATFORM := nRF51822
NRF51_SDK_PATH := $(shell pwd)/nrf51_sdk_v4_4_2_33551
NRF51_SDK_DOWNLOAD_URL := https://developer.nordicsemi.com/nRF5_SDK/nRF51_SDK_v4.x.x/nrf51_sdk_v4_4_2_33551.zip
OPENHAYSTACK_FIRMWARE_PATH := $(shell pwd)/../OpenHaystack/OpenHaystack/HaystackApp/firmware.bin
export PLATFORM
export NRF51_SDK_PATH
ifeq ($(DEPLOY_PATH),)
DEPLOY_PATH := /Volumes/MICROBIT
endif
offline-finding/build/offline-finding.bin: $(NRF51_SDK_PATH) blessed/.git
$(MAKE) -C blessed
$(MAKE) -C offline-finding
$(NRF51_SDK_PATH):
wget $(NRF51_SDK_DOWNLOAD_URL)
unzip $(NRF51_SDK_PATH).zip -d $(NRF51_SDK_PATH)
blessed/.git:
git submodule update --init
clean:
$(MAKE) -C blessed $@
$(MAKE) -C offline-finding $@
install: offline-finding/build/offline-finding.bin
cp $< $(DEPLOY_PATH)
update-app: offline-finding/build/offline-finding.bin
cp $< $(OPENHAYSTACK_FIRMWARE_PATH)
.PHONY: clean install update-app

47
Firmware/README.md Normal file
View File

@@ -0,0 +1,47 @@
# OpenHaystack Firmware for nRF51822
This project contains a PoC firmware for Nordic nRF51822 chips such as used by the [BBC micro:bit](https://microbit.org).
After flashing our firmware, the device sends out Bluetooth Low Energy advertisements such that it can be found by [Apple's Find My network](https://developer.apple.com/find-my/).
## Disclaimer
Note that the firmware is just a proof-of-concept and currently only implements advertising a single static key. This means that **devices running this firmware are trackable** by other devices in proximity.
## Requirements
You need to [GNU Arm Embedded Toolchain](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads) to build the firmware.
On macOS, you can install it via [Homebrew](https://brew.sh):
```bash
brew install --cask gcc-arm-embedded
```
## Build
You need to specify a public key in the firmware image. You can either directly do so in the [source](offline-finding/main.c) (`public_key`) or patch the string `OFFLINEFINDINGPUBLICKEYHERE!` in the final firmware image.
To build the firmware, it should suffice to run:
```bash
make
```
from the main directory, which also takes care of downloading all dependencies. The deploy-ready image is then available at `offline-finding/build/offline-finding.bin`.
## Deploy
To deploy the image on a connected nRF device, you can run:
```bash
make install DEPLOY_PATH=/Volumes/MICROBIT
```
*We tested this procedure with the BBC micro:bit V1 only, but other nRF51822-based devices should work as well.*
## Author
- **Milan Stute** ([@schmittner](https://github.com/schmittner), [email](mailto:mstute@seemoo.tu-darmstadt.de), [web](https://seemoo.de/mstute))
## License
This firmware is licensed under the [**MIT License**](LICENSE).

1
Firmware/blessed Submodule

Submodule Firmware/blessed added at 48d5b6ccdf

View File

@@ -0,0 +1,6 @@
PROJECT_TARGET = offline-finding
PROJECT_SOURCE_FILES = main.c
BLESSED_PATH := ../blessed
include $(BLESSED_PATH)/examples/Makefile.common

View File

@@ -0,0 +1,70 @@
/**
* OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
*
* Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
* Copyright © 2021 The Open Wireless Link Project
*
* SPDX-License-Identifier: MIT
*/
#include <stdint.h>
#include <string.h>
#include <blessed/bdaddr.h>
#include <blessed/evtloop.h>
#include "ll.h"
#define ADV_INTERVAL LL_ADV_INTERVAL_MIN_NONCONN /* 100 ms */
/* don't make `const` so we can replace key in compiled binary image */
static char public_key[28] = "OFFLINEFINDINGPUBLICKEYHERE!";
static bdaddr_t addr = {
{ 0xFF, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF },
BDADDR_TYPE_RANDOM
};
static uint8_t offline_finding_adv_template[] = {
0x1e, /* Length (30) */
0xff, /* Manufacturer Specific Data (type 0xff) */
0x4c, 0x00, /* Company ID (Apple) */
0x12, 0x19, /* Offline Finding type and length */
0x00, /* State */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, /* First two bits */
0x00, /* Hint (0x00) */
};
void set_addr_from_key() {
/* copy first 6 bytes */
/* BLESSED seems to reorder address bytes, so we copy them in reverse order */
addr.addr[5] = public_key[0] | 0b11000000;
addr.addr[4] = public_key[1];
addr.addr[3] = public_key[2];
addr.addr[2] = public_key[3];
addr.addr[1] = public_key[4];
addr.addr[0] = public_key[5];
}
void fill_adv_template_from_key() {
/* copy last 22 bytes */
memcpy(&offline_finding_adv_template[7], &public_key[6], 22);
/* append two bits of public key */
offline_finding_adv_template[29] = public_key[0] >> 6;
}
int main(void) {
set_addr_from_key();
fill_adv_template_from_key();
ll_init(&addr);
ll_set_advertising_data(offline_finding_adv_template, sizeof(offline_finding_adv_template));
ll_advertise_start(LL_PDU_ADV_NONCONN_IND, ADV_INTERVAL, LL_ADV_CH_ALL);
evt_loop_run();
return 0;
}

619
LICENSE Normal file
View File

@@ -0,0 +1,619 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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

View File

@@ -0,0 +1,61 @@
# By default, SwiftLint uses a set of sensible default rules you can adjust:
disabled_rules: # rule identifiers turned on by default to exclude from running
- colon
- control_statement
- identifier_name
- force_try
opt_in_rules: # some rules are turned off by default, so you need to opt-in
- empty_count # Find all the available rules by running: `swiftlint rules`
# Alternatively, specify all rules explicitly by uncommenting this option:
# only_rules: # delete `disabled_rules` & `opt_in_rules` if using this
# - empty_parameters
# - vertical_whitespace
analyzer_rules: # Rules run by `swiftlint analyze` (experimental)
- explicit_self
# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast: warning # implicitly
force_try:
severity: warning # explicitly
# rules that have both warning and error levels, can set just the warning level
# implicitly
line_length: 180
# they can set both implicitly with an array
type_body_length:
- 400 # warning
- 500 # error
# or they can set both explicitly
file_length:
warning: 600
error: 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
type_name:
min_length: 1 # only warning
max_length: # warning and error
warning: 40
error: 50
excluded:
- iPhone
- BN
- ECC
- PSI
- Log
allowed_symbols: ["_"] # these are allowed in type names
identifier_name:
min_length: 1 # only min_length
excluded: # excluded via string array
- id
- URL
- GlobalAPIKey
- SHA256_SIZE
- SHA384_SIZE
- TWO
- EULER_THEOREM
- Log
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)

View File

@@ -0,0 +1,11 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "ReportsFetcher.h"
#import "BoringSSL.h"
#import "ALTAnisetteData.h"
#import "AppleAccountData.h"

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View File

@@ -0,0 +1,34 @@
{
"object": {
"pins": [
{
"package": "swift-crypto",
"repositoryURL": "https://github.com/apple/swift-crypto.git",
"state": {
"branch": null,
"revision": "9b9d1868601a199334da5d14f4ab2d37d4f8d0c5",
"version": "1.0.2"
}
},
{
"package": "swift-nio",
"repositoryURL": "https://github.com/apple/swift-nio.git",
"state": {
"branch": null,
"revision": "6d3ca7e54e06a69d0f2612c2ce8bb8b7319085a4",
"version": "2.26.0"
}
},
{
"package": "swift-nio-ssl",
"repositoryURL": "https://github.com/apple/swift-nio-ssl",
"state": {
"branch": null,
"revision": "bbb38fbcbbe9dc4665b2c638dfa5681b01079bfb",
"version": "2.10.4"
}
}
]
},
"version": 1
}

View File

@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78108B6B248E8FB50007E9C4"
BuildableName = "OFFetchReports.app"
BlueprintName = "OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78108B6B248E8FB50007E9C4"
BuildableName = "OFFetchReports.app"
BlueprintName = "OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78108B6B248E8FB50007E9C4"
BuildableName = "OFFetchReports.app"
BlueprintName = "OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78EC226025DAE0BE0042B775"
BuildableName = "OpenHaystackTests.xctest"
BlueprintName = "OpenHaystackTests"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
<SkippedTests>
<Test
Identifier = "OpenHaystackTests/testPluginInstallation()">
</Test>
</SkippedTests>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "-preview"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78EC226025DAE0BE0042B775"
BuildableName = "OpenHaystackTests.xctest"
BlueprintName = "OpenHaystackTests"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
<SkippedTests>
<Test
Identifier = "OpenHaystackTests/testPluginInstallation()">
</Test>
</SkippedTests>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "781EB3E425DAD7EA00FEAA19"
BuildableName = "OpenHaystack.app"
BlueprintName = "OpenHaystack"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78286C8D25E3AC0400F65511"
BuildableName = "OpenHaystackMail.mailbundle"
BlueprintName = "OpenHaystackMail"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = ""
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<PathRunnable
runnableDebuggingMode = "0"
BundleIdentifier = "com.apple.mail"
FilePath = "/System/Applications/Mail.app">
</PathRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "INSTALL_PLUGIN"
value = "1"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78286C8D25E3AC0400F65511"
BuildableName = "OpenHaystackMail.mailbundle"
BlueprintName = "OpenHaystackMail"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78EC226025DAE0BE0042B775"
BuildableName = "OpenHaystackTests.xctest"
BlueprintName = "OpenHaystackTests"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78F7253325ED02300039C718"
BuildableName = "Run OFFetchReports"
BlueprintName = "Run OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78108B6B248E8FB50007E9C4"
BuildableName = "OFFetchReports.app"
BlueprintName = "OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78F7253325ED02300039C718"
BuildableName = "Run OFFetchReports"
BlueprintName = "Run OFFetchReports"
ReferencedContainer = "container:OpenHaystack.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,161 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import OSLog
/// Uses the AltStore Mail plugin to access recent anisette data
public class AnisetteDataManager: NSObject {
@objc static let shared = AnisetteDataManager()
private var anisetteDataCompletionHandlers: [String: (Result<AppleAccountData, Error>) -> Void] = [:]
private var anisetteDataTimers: [String: Timer] = [:]
private override init() {
super.init()
dlopen("/System/Library/PrivateFrameworks/AuthKit.framework/AuthKit", RTLD_NOW)
DistributedNotificationCenter.default()
.addObserver(self, selector: #selector(AnisetteDataManager.handleAppleDataResponse(_:)),
name: Notification.Name("de.tu-darmstadt.seemoo.OpenHaystack.AnisetteDataResponse"), object: nil)
}
func requestAnisetteData(_ completion: @escaping (Result<AppleAccountData, Error>) -> Void) {
if let accountData = self.requestAnisetteDataAuthKit() {
os_log(.debug, "Anisette Data loaded %@", accountData.debugDescription)
completion(.success(accountData))
return
}
let requestUUID = UUID().uuidString
self.anisetteDataCompletionHandlers[requestUUID] = completion
let timer = Timer(timeInterval: 1.0, repeats: false) { (_) in
self.finishRequest(forUUID: requestUUID, result: .failure(AnisetteDataError.pluginNotFound))
}
self.anisetteDataTimers[requestUUID] = timer
RunLoop.main.add(timer, forMode: .default)
DistributedNotificationCenter.default()
.postNotificationName(Notification.Name("de.tu-darmstadt.seemoo.OpenHaystack.FetchAnisetteData"),
object: nil, userInfo: ["requestUUID": requestUUID], options: .deliverImmediately)
}
func requestAnisetteDataAuthKit() -> AppleAccountData? {
let anisetteData = ReportsFetcher().anisetteDataDictionary()
let dateFormatter = ISO8601DateFormatter()
guard let machineID = anisetteData["X-Apple-I-MD-M"] as? String,
let otp = anisetteData["X-Apple-I-MD"] as? String,
let localUserId = anisetteData["X-Apple-I-MD-LU"] as? String,
let dateString = anisetteData["X-Apple-I-Client-Time"] as? String,
let date = dateFormatter.date(from: dateString),
let deviceClass = NSClassFromString("AKDevice")
else {
return nil
}
let device: AKDevice = deviceClass.current()
let routingInfo = (anisetteData["X-Apple-I-MD-RINFO"] as? NSNumber)?.uint64Value ?? 0
let accountData = AppleAccountData(machineID: machineID,
oneTimePassword: otp,
localUserID: localUserId,
routingInfo: routingInfo,
deviceUniqueIdentifier: device.uniqueDeviceIdentifier(),
deviceSerialNumber: device.serialNumber(),
deviceDescription: device.serverFriendlyDescription(),
date: date,
locale: Locale.current,
timeZone: TimeZone.current)
if let spToken = ReportsFetcher().fetchSearchpartyToken() {
accountData.searchPartyToken = spToken
}
return accountData
}
@objc func requestAnisetteDataObjc(_ completion: @escaping ([AnyHashable: Any]?) -> Void) {
self.requestAnisetteData { result in
switch result {
case .failure:
completion(nil)
case .success(let data):
// Return only the headers
completion([
"X-Apple-I-MD-M": data.machineID,
"X-Apple-I-MD": data.oneTimePassword,
"X-Apple-I-TimeZone": String(data.timeZone.abbreviation() ?? "UTC"),
"X-Apple-I-Client-Time": ISO8601DateFormatter().string(from: data.date),
"X-Apple-I-MD-RINFO": String(data.routingInfo)
] as [AnyHashable: Any])
}
}
}
}
private extension AnisetteDataManager {
@objc func handleAppleDataResponse(_ notification: Notification) {
guard let userInfo = notification.userInfo, let requestUUID = userInfo["requestUUID"] as? String else { return }
if
let archivedAnisetteData = userInfo["anisetteData"] as? Data,
let appleAccountData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: AppleAccountData.self, from: archivedAnisetteData)
{
if let range = appleAccountData.deviceDescription.lowercased().range(of: "(com.apple.mail") {
var adjustedDescription = appleAccountData.deviceDescription[..<range.lowerBound]
adjustedDescription += "(com.apple.dt.Xcode/3594.4.19)>"
appleAccountData.deviceDescription = String(adjustedDescription)
}
self.finishRequest(forUUID: requestUUID, result: .success(appleAccountData))
} else {
self.finishRequest(forUUID: requestUUID, result: .failure(AnisetteDataError.invalidAnisetteData))
}
}
@objc func handleAnisetteDataResponse(_ notification: Notification) {
guard let userInfo = notification.userInfo, let requestUUID = userInfo["requestUUID"] as? String else { return }
if
let archivedAnisetteData = userInfo["anisetteData"] as? Data,
let anisetteData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ALTAnisetteData.self, from: archivedAnisetteData)
{
if let range = anisetteData.deviceDescription.lowercased().range(of: "(com.apple.mail") {
var adjustedDescription = anisetteData.deviceDescription[..<range.lowerBound]
adjustedDescription += "(com.apple.dt.Xcode/3594.4.19)>"
anisetteData.deviceDescription = String(adjustedDescription)
}
let appleAccountData = AppleAccountData(fromALTAnissetteData: anisetteData)
self.finishRequest(forUUID: requestUUID, result: .success(appleAccountData))
} else {
self.finishRequest(forUUID: requestUUID, result: .failure(AnisetteDataError.invalidAnisetteData))
}
}
func finishRequest(forUUID requestUUID: String, result: Result<AppleAccountData, Error>) {
let completionHandler = self.anisetteDataCompletionHandlers[requestUUID]
self.anisetteDataCompletionHandlers[requestUUID] = nil
let timer = self.anisetteDataTimers[requestUUID]
self.anisetteDataTimers[requestUUID] = nil
timer?.invalidate()
completionHandler?(result)
}
}
enum AnisetteDataError: Error {
case pluginNotFound
case invalidAnisetteData
}

View File

@@ -0,0 +1,48 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
private var mainView: some View {
#if ACCESSORY
if ProcessInfo().arguments.contains("-preview") {
return OpenHaystackMainView(accessoryController: AccessoryController(accessories: PreviewData.accessories))
}
return OpenHaystackMainView()
#else
return OFFetchReportsMainView()
#endif
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 750, height: 480),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: mainView)
window.makeKeyAndOrderFront(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 508 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 892 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

@@ -0,0 +1,68 @@
{
"images" : [
{
"filename" : "16.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"filename" : "32.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"filename" : "32.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"filename" : "64.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"filename" : "128.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"filename" : "256.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"filename" : "256.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"filename" : "512.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"filename" : "512.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"filename" : "1024.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.917",
"green" : "0.917",
"red" : "0.917"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.191",
"green" : "0.191",
"red" : "0.191"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,683 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="14814" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14814"/>
</dependencies>
<scenes>
<!--Application-->
<scene sceneID="JPo-4y-FX3">
<objects>
<application id="hnw-xV-0zn" sceneMemberID="viewController">
<menu key="mainMenu" title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="OfflineFinder" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="OfflineFinder" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About OfflineFinder" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide OfflineFinder" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit OfflineFinder" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="dMs-cI-mzQ">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="File" id="bib-Uj-vzu">
<items>
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
<connections>
<action selector="newDocument:" target="Ady-hI-5gd" id="4Si-XN-c54"/>
</connections>
</menuItem>
<menuItem title="Open…" keyEquivalent="o" id="IAo-SY-fd9">
<connections>
<action selector="openDocument:" target="Ady-hI-5gd" id="bVn-NM-KNZ"/>
</connections>
</menuItem>
<menuItem title="Open Recent" id="tXI-mr-wws">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Open Recent" systemMenu="recentDocuments" id="oas-Oc-fiZ">
<items>
<menuItem title="Clear Menu" id="vNY-rz-j42">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="clearRecentDocuments:" target="Ady-hI-5gd" id="Daa-9d-B3U"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
<connections>
<action selector="performClose:" target="Ady-hI-5gd" id="HmO-Ls-i7Q"/>
</connections>
</menuItem>
<menuItem title="Save…" keyEquivalent="s" id="pxx-59-PXV">
<connections>
<action selector="saveDocument:" target="Ady-hI-5gd" id="teZ-XB-qJY"/>
</connections>
</menuItem>
<menuItem title="Save As…" keyEquivalent="S" id="Bw7-FT-i3A">
<connections>
<action selector="saveDocumentAs:" target="Ady-hI-5gd" id="mDf-zr-I0C"/>
</connections>
</menuItem>
<menuItem title="Revert to Saved" keyEquivalent="r" id="KaW-ft-85H">
<connections>
<action selector="revertDocumentToSaved:" target="Ady-hI-5gd" id="iJ3-Pv-kwq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
<menuItem title="Page Setup…" keyEquivalent="P" id="qIS-W8-SiK">
<modifierMask key="keyEquivalentModifierMask" shift="YES" command="YES"/>
<connections>
<action selector="runPageLayout:" target="Ady-hI-5gd" id="Din-rz-gC5"/>
</connections>
</menuItem>
<menuItem title="Print…" keyEquivalent="p" id="aTl-1u-JFS">
<connections>
<action selector="print:" target="Ady-hI-5gd" id="qaZ-4w-aoO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="Ady-hI-5gd" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="Ady-hI-5gd" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="Ady-hI-5gd" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="Ady-hI-5gd" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="Ady-hI-5gd" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="Ady-hI-5gd" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="Ady-hI-5gd" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="Ady-hI-5gd" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="Ady-hI-5gd" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="Ady-hI-5gd" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="Ady-hI-5gd" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="Ady-hI-5gd" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="Ady-hI-5gd" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="Ady-hI-5gd" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="Ady-hI-5gd" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="Ady-hI-5gd" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="Ady-hI-5gd" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="Ady-hI-5gd" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="Ady-hI-5gd" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="Ady-hI-5gd" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="Ady-hI-5gd" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="Ady-hI-5gd" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="Ady-hI-5gd" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="Ady-hI-5gd" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="Ady-hI-5gd" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="Ady-hI-5gd" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Format" id="jxT-CU-nIS">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Format" id="GEO-Iw-cKr">
<items>
<menuItem title="Font" id="Gi5-1S-RQB">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Font" systemMenu="font" id="aXa-aM-Jaq">
<items>
<menuItem title="Show Fonts" keyEquivalent="t" id="Q5e-8K-NDq">
<connections>
<action selector="orderFrontFontPanel:" target="YLy-65-1bz" id="WHr-nq-2xA"/>
</connections>
</menuItem>
<menuItem title="Bold" tag="2" keyEquivalent="b" id="GB9-OM-e27">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="hqk-hr-sYV"/>
</connections>
</menuItem>
<menuItem title="Italic" tag="1" keyEquivalent="i" id="Vjx-xi-njq">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="IHV-OB-c03"/>
</connections>
</menuItem>
<menuItem title="Underline" keyEquivalent="u" id="WRG-CD-K1S">
<connections>
<action selector="underline:" target="Ady-hI-5gd" id="FYS-2b-JAY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="5gT-KC-WSO"/>
<menuItem title="Bigger" tag="3" keyEquivalent="+" id="Ptp-SP-VEL">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="Uc7-di-UnL"/>
</connections>
</menuItem>
<menuItem title="Smaller" tag="4" keyEquivalent="-" id="i1d-Er-qST">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="HcX-Lf-eNd"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kx3-Dk-x3B"/>
<menuItem title="Kern" id="jBQ-r6-VK2">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Kern" id="tlD-Oa-oAM">
<items>
<menuItem title="Use Default" id="GUa-eO-cwY">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardKerning:" target="Ady-hI-5gd" id="6dk-9l-Ckg"/>
</connections>
</menuItem>
<menuItem title="Use None" id="cDB-IK-hbR">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffKerning:" target="Ady-hI-5gd" id="U8a-gz-Maa"/>
</connections>
</menuItem>
<menuItem title="Tighten" id="46P-cB-AYj">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="tightenKerning:" target="Ady-hI-5gd" id="hr7-Nz-8ro"/>
</connections>
</menuItem>
<menuItem title="Loosen" id="ogc-rX-tC1">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="loosenKerning:" target="Ady-hI-5gd" id="8i4-f9-FKE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Ligatures" id="o6e-r0-MWq">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Ligatures" id="w0m-vy-SC9">
<items>
<menuItem title="Use Default" id="agt-UL-0e3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardLigatures:" target="Ady-hI-5gd" id="7uR-wd-Dx6"/>
</connections>
</menuItem>
<menuItem title="Use None" id="J7y-lM-qPV">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffLigatures:" target="Ady-hI-5gd" id="iX2-gA-Ilz"/>
</connections>
</menuItem>
<menuItem title="Use All" id="xQD-1f-W4t">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useAllLigatures:" target="Ady-hI-5gd" id="KcB-kA-TuK"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Baseline" id="OaQ-X3-Vso">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Baseline" id="ijk-EB-dga">
<items>
<menuItem title="Use Default" id="3Om-Ey-2VK">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unscript:" target="Ady-hI-5gd" id="0vZ-95-Ywn"/>
</connections>
</menuItem>
<menuItem title="Superscript" id="Rqc-34-cIF">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="superscript:" target="Ady-hI-5gd" id="3qV-fo-wpU"/>
</connections>
</menuItem>
<menuItem title="Subscript" id="I0S-gh-46l">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="subscript:" target="Ady-hI-5gd" id="Q6W-4W-IGz"/>
</connections>
</menuItem>
<menuItem title="Raise" id="2h7-ER-AoG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="raiseBaseline:" target="Ady-hI-5gd" id="4sk-31-7Q9"/>
</connections>
</menuItem>
<menuItem title="Lower" id="1tx-W0-xDw">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowerBaseline:" target="Ady-hI-5gd" id="OF1-bc-KW4"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="Ndw-q3-faq"/>
<menuItem title="Show Colors" keyEquivalent="C" id="bgn-CT-cEk">
<connections>
<action selector="orderFrontColorPanel:" target="Ady-hI-5gd" id="mSX-Xz-DV3"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="iMs-zA-UFJ"/>
<menuItem title="Copy Style" keyEquivalent="c" id="5Vv-lz-BsD">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="copyFont:" target="Ady-hI-5gd" id="GJO-xA-L4q"/>
</connections>
</menuItem>
<menuItem title="Paste Style" keyEquivalent="v" id="vKC-jM-MkH">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteFont:" target="Ady-hI-5gd" id="JfD-CL-leO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Text" id="Fal-I4-PZk">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Text" id="d9c-me-L2H">
<items>
<menuItem title="Align Left" keyEquivalent="{" id="ZM1-6Q-yy1">
<connections>
<action selector="alignLeft:" target="Ady-hI-5gd" id="zUv-R1-uAa"/>
</connections>
</menuItem>
<menuItem title="Center" keyEquivalent="|" id="VIY-Ag-zcb">
<connections>
<action selector="alignCenter:" target="Ady-hI-5gd" id="spX-mk-kcS"/>
</connections>
</menuItem>
<menuItem title="Justify" id="J5U-5w-g23">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="alignJustified:" target="Ady-hI-5gd" id="ljL-7U-jND"/>
</connections>
</menuItem>
<menuItem title="Align Right" keyEquivalent="}" id="wb2-vD-lq4">
<connections>
<action selector="alignRight:" target="Ady-hI-5gd" id="r48-bG-YeY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4s2-GY-VfK"/>
<menuItem title="Writing Direction" id="H1b-Si-o9J">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Writing Direction" id="8mr-sm-Yjd">
<items>
<menuItem title="Paragraph" enabled="NO" id="ZvO-Gk-QUH">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="YGs-j5-SAR">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionNatural:" target="Ady-hI-5gd" id="qtV-5e-UBP"/>
</connections>
</menuItem>
<menuItem id="Lbh-J2-qVU">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionLeftToRight:" target="Ady-hI-5gd" id="S0X-9S-QSf"/>
</connections>
</menuItem>
<menuItem id="jFq-tB-4Kx">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionRightToLeft:" target="Ady-hI-5gd" id="5fk-qB-AqJ"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="swp-gr-a21"/>
<menuItem title="Selection" enabled="NO" id="cqv-fj-IhA">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="Nop-cj-93Q">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionNatural:" target="Ady-hI-5gd" id="lPI-Se-ZHp"/>
</connections>
</menuItem>
<menuItem id="BgM-ve-c93">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionLeftToRight:" target="Ady-hI-5gd" id="caW-Bv-w94"/>
</connections>
</menuItem>
<menuItem id="RB4-Sm-HuC">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionRightToLeft:" target="Ady-hI-5gd" id="EXD-6r-ZUu"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="fKy-g9-1gm"/>
<menuItem title="Show Ruler" id="vLm-3I-IUL">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleRuler:" target="Ady-hI-5gd" id="FOx-HJ-KwY"/>
</connections>
</menuItem>
<menuItem title="Copy Ruler" keyEquivalent="c" id="MkV-Pr-PK5">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="copyRuler:" target="Ady-hI-5gd" id="71i-fW-3W2"/>
</connections>
</menuItem>
<menuItem title="Paste Ruler" keyEquivalent="v" id="LVM-kO-fVI">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="pasteRuler:" target="Ady-hI-5gd" id="cSh-wd-qM2"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="toggleToolbarShown:" target="Ady-hI-5gd" id="BXY-wc-z0C"/>
</connections>
</menuItem>
<menuItem title="Customize Toolbar…" id="1UK-8n-QPP">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="runToolbarCustomizationPalette:" target="Ady-hI-5gd" id="pQI-g3-MTW"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="hB3-LF-h0Y"/>
<menuItem title="Show Sidebar" keyEquivalent="s" id="kIP-vf-haE">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleSidebar:" target="Ady-hI-5gd" id="iwa-gc-5KM"/>
</connections>
</menuItem>
<menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleFullScreen:" target="Ady-hI-5gd" id="dU3-MA-1Rq"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="Ady-hI-5gd" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="Ady-hI-5gd" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="Ady-hI-5gd" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="wpr-3q-Mcd">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
<items>
<menuItem title="OfflineFinder Help" keyEquivalent="?" id="FKE-Sm-Kum">
<connections>
<action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/>
</connections>
</application>
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModuleProvider="target"/>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="75" y="0.0"/>
</scene>
</scenes>
</document>

View File

@@ -0,0 +1,27 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface BoringSSL : NSObject
+ (NSData * _Nullable) deriveSharedKeyFromPrivateKey: (NSData *) privateKey andEphemeralKey: (NSData*) ephemeralKeyPoint;
/// Derive a public key from a given private key
/// @param privateKeyData an EC private key on the P-224 curve
/// @returns The public key in a compressed format using 29 bytes. The first byte is used for identifying if its odd or even.
/// For OF the first byte has to be dropped
+ (NSData * _Nullable) derivePublicKeyFromPrivateKey: (NSData*) privateKeyData;
/// Generate a new EC private key and exports it as data
+ (NSData * _Nullable) generateNewPrivateKey;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,167 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "BoringSSL.h"
#include <CNIOBoringSSL.h>
#include <CNIOBoringSSL_ec.h>
#include <CNIOBoringSSL_ec_key.h>
#include <CNIOBoringSSL_evp.h>
#include <CNIOBoringSSL_hkdf.h>
#include <CNIOBoringSSL_pkcs7.h>
@implementation BoringSSL
+ (NSData * _Nullable) deriveSharedKeyFromPrivateKey: (NSData *) privateKey andEphemeralKey: (NSData*) ephemeralKeyPoint {
NSLog(@"Private key %@", [privateKey base64EncodedStringWithOptions:0]);
NSLog(@"Ephemeral key %@", [ephemeralKeyPoint base64EncodedStringWithOptions:0]);
EC_GROUP *curve = EC_GROUP_new_by_curve_name(NID_secp224r1);
EC_KEY *key = [self deriveEllipticCurvePrivateKey:privateKey group:curve];
const EC_POINT *genPubKey = EC_KEY_get0_public_key(key);
[self printPoint:genPubKey withGroup:curve];
EC_POINT *publicKey = EC_POINT_new(curve);
size_t load_success = EC_POINT_oct2point(curve, publicKey, ephemeralKeyPoint.bytes, ephemeralKeyPoint.length, NULL);
if (load_success == 0) {
NSLog(@"Failed loading public key!");
return nil;
}
NSMutableData *sharedKey = [[NSMutableData alloc] initWithLength:28];
int res = ECDH_compute_key(sharedKey.mutableBytes, sharedKey.length, publicKey, key, nil);
if (res < 1) {
NSLog(@"Failed with error: %d", res);
}
NSLog(@"Shared key: %@", [sharedKey base64EncodedStringWithOptions:0]);
return sharedKey;
}
+ (EC_POINT * _Nullable) loadEllipticCurvePublicBytesWith: (EC_GROUP *) group andPointBytes: (NSData *) pointBytes {
EC_POINT* point = EC_POINT_new(group);
//Create big number context
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
//Public key will be stored in point
int res = EC_POINT_oct2point(group, point, pointBytes.bytes, pointBytes.length, ctx);
[self printPoint:point withGroup:group];
//Free the big numbers
BN_CTX_free(ctx);
if (res != 1) {
//Failed
return nil;
}
return point;
}
/// Get the private key on the curve from the private key bytes
/// @param privateKeyData NSData representing the private key
/// @param group The EC group representing the curve to use
+ (EC_KEY * _Nullable) deriveEllipticCurvePrivateKey: (NSData *)privateKeyData group: (EC_GROUP *) group {
EC_KEY *key = EC_KEY_new_by_curve_name(NID_secp224r1);
EC_POINT *point = EC_POINT_new(group);
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *privateKeyNum = BN_bin2bn(privateKeyData.bytes, privateKeyData.length, nil);
int res = EC_POINT_mul(group, point, privateKeyNum, nil, nil, ctx);
if (res != 1) {
NSLog(@"Failed");
return nil;
}
res = EC_KEY_set_public_key(key, point);
if (res != 1) {
NSLog(@"Failed");
return nil;
}
privateKeyNum = BN_bin2bn(privateKeyData.bytes, privateKeyData.length, nil);
EC_KEY_set_private_key(key, privateKeyNum);
//Free the big numbers
BN_CTX_free(ctx);
return key;
}
/// Derive a public key from a given private key
/// @param privateKeyData an EC private key on the P-224 curve
+ (NSData * _Nullable) derivePublicKeyFromPrivateKey: (NSData*) privateKeyData {
EC_GROUP *curve = EC_GROUP_new_by_curve_name(NID_secp224r1);
EC_KEY *key = [self deriveEllipticCurvePrivateKey:privateKeyData group:curve];
const EC_POINT *publicKey = EC_KEY_get0_public_key(key);
size_t keySize = 28 + 1;
NSMutableData *publicKeyBytes = [[NSMutableData alloc] initWithLength:keySize];
size_t size = EC_POINT_point2oct(curve, publicKey, POINT_CONVERSION_COMPRESSED, publicKeyBytes.mutableBytes, keySize, NULL);
if (size == 0) {
return nil;
}
return publicKeyBytes;
}
+ (NSData * _Nullable)generateNewPrivateKey {
EC_KEY *key = EC_KEY_new_by_curve_name(NID_secp224r1);
if (EC_KEY_generate_key_fips(key) == 0) {
return nil;
}
const BIGNUM *privateKey = EC_KEY_get0_private_key(key);
size_t keySize = BN_num_bytes(privateKey);
//Convert to bytes
NSMutableData *privateKeyBytes = [[NSMutableData alloc] initWithLength:keySize];
size_t size = BN_bn2bin(privateKey, privateKeyBytes.mutableBytes);
if (size == 0) {
return nil;
}
return privateKeyBytes;
}
+ (void) printPoint: (const EC_POINT *)point withGroup:(EC_GROUP *)group {
NSMutableData *pointData = [[NSMutableData alloc] initWithLength:256];
size_t len = pointData.length;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
size_t res = EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, pointData.mutableBytes, len, ctx);
//Free the big numbers
BN_CTX_free(ctx);
NSData *written = [[NSData alloc] initWithBytes:pointData.bytes length:res];
NSLog(@"Point data is: %@", [written base64EncodedStringWithOptions:0]);
}
@end

View File

@@ -0,0 +1,95 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import CryptoKit
struct DecryptReports {
/// Decrypt a find my report with the according key
/// - Parameters:
/// - report: An encrypted FindMy Report
/// - key: A FindMyKey
/// - Throws: Errors if the decryption fails
/// - Returns: An decrypted location report
static func decrypt(report: FindMyReport, with key: FindMyKey) throws -> FindMyLocationReport {
let payloadData = report.payload
let keyData = key.privateKey
let privateKey = keyData
let ephemeralKey = payloadData.subdata(in: 5..<62)
guard let sharedKey = BoringSSL.deriveSharedKey(fromPrivateKey: privateKey, andEphemeralKey: ephemeralKey) else {
throw FindMyError.decryptionError(description: "Failed generating shared key")
}
let derivedKey = self.kdf(fromSharedSecret: sharedKey, andEphemeralKey: ephemeralKey)
print("Derived key \(derivedKey.base64EncodedString())")
let encData = payloadData.subdata(in: 62..<72)
let tag = payloadData.subdata(in: 72..<payloadData.endIndex)
let decryptedContent = try self.decryptPayload(payload: encData, symmetricKey: derivedKey, tag: tag)
let locationReport = self.decode(content: decryptedContent, report: report)
print(locationReport)
return locationReport
}
/// Decrypt the payload
/// - Parameters:
/// - payload: Encrypted payload part
/// - symmetricKey: Symmetric key
/// - tag: AES GCM tag
/// - Throws: AES GCM error
/// - Returns: Decrypted error
static func decryptPayload(payload: Data, symmetricKey: Data, tag: Data) throws -> Data {
let decryptionKey = symmetricKey.subdata(in: 0..<16)
let iv = symmetricKey.subdata(in: 16..<symmetricKey.endIndex)
print("Decryption Key \(decryptionKey.base64EncodedString())")
print("IV \(iv.base64EncodedString())")
let sealedBox = try AES.GCM.SealedBox(nonce: AES.GCM.Nonce(data: iv), ciphertext: payload, tag: tag)
let symKey = SymmetricKey(data: decryptionKey)
let decrypted = try AES.GCM.open(sealedBox, using: symKey)
return decrypted
}
static func decode(content: Data, report: FindMyReport) -> FindMyLocationReport {
var longitude: Int32 = 0
_ = withUnsafeMutableBytes(of: &longitude, {content.subdata(in: 4..<8).copyBytes(to: $0)})
longitude = Int32(bigEndian: longitude)
var latitude: Int32 = 0
_ = withUnsafeMutableBytes(of: &latitude, {content.subdata(in: 0..<4).copyBytes(to: $0)})
latitude = Int32(bigEndian: latitude)
var accuracy: UInt8 = 0
_ = withUnsafeMutableBytes(of: &accuracy, {content.subdata(in: 8..<9).copyBytes(to: $0)})
let latitudeDec = Double(latitude)/10000000.0
let longitudeDec = Double(longitude)/10000000.0
return FindMyLocationReport(lat: latitudeDec, lng: longitudeDec, acc: accuracy, dP: report.datePublished, t: report.timestamp, c: report.confidence)
}
static func kdf(fromSharedSecret secret: Data, andEphemeralKey ephKey: Data) -> Data {
var shaDigest = SHA256()
shaDigest.update(data: secret)
var counter: Int32 = 1
let counterData = Data(Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter)).reversed())
shaDigest.update(data: counterData)
shaDigest.update(data: ephKey)
let derivedKey = shaDigest.finalize()
return Data(derivedKey)
}
}

View File

@@ -0,0 +1,218 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import SwiftUI
import Combine
class FindMyController: ObservableObject {
static let shared = FindMyController()
@Published var error: Error?
@Published var devices = [FindMyDevice]()
func loadPrivateKeys(from data: Data, with searchPartyToken: Data, completion: @escaping (Error?) -> Void) {
do {
let devices = try PropertyListDecoder().decode([FindMyDevice].self, from: data)
self.devices.append(contentsOf: devices)
self.fetchReports(with: searchPartyToken, completion: completion)
} catch {
self.error = FindMyErrors.decodingPlistFailed(message: String(describing: error))
}
}
func importReports(reports: [FindMyReport], and keys: Data, completion:@escaping () -> Void) throws {
let devices = try PropertyListDecoder().decode([FindMyDevice].self, from: keys)
self.devices = devices
// Decrypt the reports with the imported keys
DispatchQueue.global(qos: .background).async {
var d = self.devices
// Add the reports to the according device by finding the right key for the report
for report in reports {
let dI = d.firstIndex { (device) -> Bool in
device.keys.contains { (key) -> Bool in
key.hashedKey.base64EncodedString() == report.id
}
}
guard let deviceIndex = dI else {
print("No device found for id")
continue
}
if var reports = d[deviceIndex].reports {
reports.append(report)
d[deviceIndex].reports = reports
} else {
d[deviceIndex].reports = [report]
}
}
// Decrypt the reports
self.decryptReports {
self.exportDevices()
DispatchQueue.main.async {
completion()
}
}
}
}
func importDevices(devices: Data) throws {
var devices = try PropertyListDecoder().decode([FindMyDevice].self, from: devices)
// Delete the decrypted reports
for idx in devices.startIndex..<devices.endIndex {
devices[idx].decryptedReports = nil
}
self.devices = devices
// Decrypt reports again with additional information
self.decryptReports {
}
}
func fetchReports(with searchPartyToken: Data, completion: @escaping (Error?) -> Void) {
DispatchQueue.global(qos: .background).async {
let fetchReportGroup = DispatchGroup()
let fetcher = ReportsFetcher()
var devices = self.devices
for deviceIndex in 0..<devices.count {
fetchReportGroup.enter()
devices[deviceIndex].reports = []
// Only use the newest keys for testing
let keys = devices[deviceIndex].keys
let keyHashes = keys.map({$0.hashedKey.base64EncodedString()})
// 21 days
let duration: Double = (24 * 60 * 60) * 21
let startDate = Date() - duration
fetcher.query(forHashes: keyHashes, start: startDate, duration: duration, searchPartyToken: searchPartyToken) { jd in
guard let jsonData = jd else {
fetchReportGroup.leave()
return
}
do {
// Decode the report
let report = try JSONDecoder().decode(FindMyReportResults.self, from: jsonData)
devices[deviceIndex].reports = report.results
} catch {
print("Failed with error \(error)")
devices[deviceIndex].reports = []
}
fetchReportGroup.leave()
}
}
// Completion Handler
fetchReportGroup.notify(queue: .main) {
print("Finished loading the reports. Now decrypt them")
// Export the reports to the desktop
var reports = [FindMyReport]()
for device in devices {
for report in device.reports! {
reports.append(report)
}
}
#if EXPORT
if let encoded = try? JSONEncoder().encode(reports) {
let outputDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
try? encoded.write(to: outputDirectory.appendingPathComponent("reports.json"))
}
#endif
DispatchQueue.main.async {
self.devices = devices
self.decryptReports {
completion(nil)
}
}
}
}
}
func decryptReports(completion: () -> Void) {
print("Decrypting reports")
// Iterate over all devices
for deviceIdx in 0..<devices.count {
devices[deviceIdx].decryptedReports = []
let device = devices[deviceIdx]
// Map the keys in a dictionary for faster access
guard let reports = device.reports else {continue}
let keyMap = device.keys.reduce(into: [String: FindMyKey](), {$0[$1.hashedKey.base64EncodedString()] = $1})
let accessQueue = DispatchQueue(label: "threadSafeAccess", qos: .userInitiated, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil)
var decryptedReports = [FindMyLocationReport](repeating: FindMyLocationReport(lat: 0, lng: 0, acc: 0, dP: Date(), t: Date(), c: 0), count: reports.count)
DispatchQueue.concurrentPerform(iterations: reports.count) { (reportIdx) in
let report = reports[reportIdx]
guard let key = keyMap[report.id] else {return}
do {
// Decrypt the report
let locationReport = try DecryptReports.decrypt(report: report, with: key)
accessQueue.async(flags: .barrier) {
decryptedReports[reportIdx] = locationReport
}
} catch {
return
}
}
accessQueue.sync {
devices[deviceIdx].decryptedReports = decryptedReports
}
}
completion()
}
func exportDevices() {
if let encoded = try? PropertyListEncoder().encode(self.devices) {
let outputDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
try? encoded.write(to: outputDirectory.appendingPathComponent("devices-\(Date()).plist"))
}
}
}
struct FindMyControllerKey: EnvironmentKey {
static var defaultValue: FindMyController = .shared
}
extension EnvironmentValues {
var findMyController: FindMyController {
get {self[FindMyControllerKey.self]}
set {self[FindMyControllerKey.self] = newValue}
}
}
enum FindMyErrors: Error {
case decodingPlistFailed(message: String)
}

View File

@@ -0,0 +1,105 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import CryptoKit
/// Decode key files found in newer macOS versions.
class FindMyKeyDecoder {
/// Key files can be in different format. The old <= 10.15.3 have been using normal plists. Newer once use a binary format which needs different parsing
enum KeyFileFormat {
/// Catalina > 10.15.4 key file format | Big Sur 11.0 Beta 1 uses a similar key file format that can be parsed identically. macOS 10.15.7 uses a new key file format that has not been reversed yet. (The key files are protected by sandboxing and only usable from a SIP disabled)
case catalina_10_15_4
}
var fileFormat: KeyFileFormat?
func parse(keyFile: Data) throws -> [FindMyKey] {
// Detect the format at first
if fileFormat == nil {
try self.checkFormat(for: keyFile)
}
guard let format = self.fileFormat else {
throw ParsingError.unsupportedFormat
}
switch format {
case .catalina_10_15_4:
let keys = try self.parseBinaryKeyFiles(from: keyFile)
return keys
}
}
func checkFormat(for keyFile: Data) throws {
// Key files need to start with KEY = 0x4B 45 59
let magicBytes = keyFile.subdata(in: 0..<3)
guard magicBytes == Data([0x4b, 0x45, 0x59]) else {
throw ParsingError.wrongMagicBytes
}
// Detect zeros
let potentialZeros = keyFile[15..<31]
guard potentialZeros == Data(repeating: 0x00, count: 16) else {
throw ParsingError.wrongFormat
}
// Should be big sur
self.fileFormat = .catalina_10_15_4
}
fileprivate func parseBinaryKeyFiles(from keyFile: Data) throws -> [FindMyKey] {
var keys = [FindMyKey]()
// First key starts at 32
var i = 32
while i + 117 < keyFile.count {
// We could not identify what those keys were
_ = keyFile.subdata(in: i..<i+32)
i += 32
if keyFile[i] == 0x00 {
// Public key only.
// No need to parse it. Just skip to the next key
i += 86
continue
}
guard keyFile[i] == 0x01 else {
throw ParsingError.wrongFormat
}
// Step over 0x01
i+=1
// Read the key (starting with 0x04)
let fullKey = keyFile.subdata(in: i..<i+85)
i += 85
// Create the sub keys. No actual need, but we do that to put them into a similar format as used before 10.15.4
let advertisedKey = fullKey.subdata(in: 1..<29)
let yCoordinate = fullKey.subdata(in: 29..<57)
var shaDigest = SHA256()
shaDigest.update(data: advertisedKey)
let hashedKey = Data(shaDigest.finalize())
let fmKey = FindMyKey(advertisedKey: advertisedKey,
hashedKey: hashedKey,
privateKey: fullKey,
startTime: nil,
duration: nil,
pu: nil,
yCoordinate: yCoordinate,
fullKey: fullKey)
keys.append(fmKey)
}
return keys
}
enum ParsingError: Error {
case wrongMagicBytes
case wrongFormat
case unsupportedFormat
}
}

View File

@@ -0,0 +1,177 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import CoreLocation
struct FindMyDevice: Codable, Hashable {
let deviceId: String
var keys = [FindMyKey]()
var catalinaBigSurKeyFiles: [Data]?
/// KeyHash: Report results
var reports: [FindMyReport]?
var decryptedReports: [FindMyLocationReport]?
func hash(into hasher: inout Hasher) {
hasher.combine(deviceId)
}
static func == (lhs: FindMyDevice, rhs: FindMyDevice) -> Bool {
lhs.deviceId == rhs.deviceId
}
}
struct FindMyKey: Codable {
internal init(advertisedKey: Data, hashedKey: Data, privateKey: Data, startTime: Date?, duration: Double?, pu: Data?, yCoordinate: Data?, fullKey: Data?) {
self.advertisedKey = advertisedKey
self.hashedKey = hashedKey
// The private key should only be 28 bytes long. If a 85 bytes full private public key is entered we truncate it here
if privateKey.count == 85 {
self.privateKey = privateKey.subdata(in: 57..<privateKey.endIndex)
} else {
self.privateKey = privateKey
}
self.startTime = startTime
self.duration = duration
self.pu = pu
self.yCoordinate = yCoordinate
self.fullKey = fullKey
}
/// The advertising key
let advertisedKey: Data
/// Hashed advertisement key using SHA256
let hashedKey: Data
/// The private key from which the advertisement keys can be derived
let privateKey: Data
/// When this key was used to send out BLE advertisements
let startTime: Date?
/// Duration from start time how long the key has been used to send out BLE advertisements
let duration: Double?
/// ?
let pu: Data?
/// As exported from Big Sur
let yCoordinate: Data?
/// As exported from BigSur
let fullKey: Data?
}
struct FindMyReportResults: Codable {
let results: [FindMyReport]
}
struct FindMyReport: Codable {
let datePublished: Date
let payload: Data
let id: String
let statusCode: Int
let confidence: UInt8
let timestamp: Date
enum CodingKeys: CodingKey {
case datePublished
case payload
case id
case statusCode
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let dateTimestamp = try values.decode(Double.self, forKey: .datePublished)
// Convert from milis to time interval
let dP = Date(timeIntervalSince1970: dateTimestamp/1000)
let df = DateFormatter()
df.dateFormat = "YYYY-MM-dd"
if dP < df.date(from: "2020-01-01")! {
self.datePublished = Date(timeIntervalSince1970: dateTimestamp)
} else {
self.datePublished = dP
}
self.statusCode = try values.decode(Int.self, forKey: .statusCode)
let payloadBase64 = try values.decode(String.self, forKey: .payload)
guard let payload = Data(base64Encoded: payloadBase64) else {
throw DecodingError.dataCorruptedError(forKey: CodingKeys.payload, in: values, debugDescription: "")
}
self.payload = payload
var timestampData = payload.subdata(in: 0..<4)
let timestamp: Int32 = withUnsafeBytes(of: &timestampData) { (pointer) -> Int32 in
// Convert the endianness
pointer.load(as: Int32.self).bigEndian
}
// It's a cocoa time stamp (counting from 2001)
self.timestamp = Date(timeIntervalSinceReferenceDate: TimeInterval(timestamp))
self.confidence = payload[4]
self.id = try values.decode(String.self, forKey: .id)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.datePublished.timeIntervalSince1970 * 1000, forKey: .datePublished)
try container.encode(self.payload.base64EncodedString(), forKey: .payload)
try container.encode(self.id, forKey: .id)
try container.encode(self.statusCode, forKey: .statusCode)
}
}
struct FindMyLocationReport: Codable {
let latitude: Double
let longitude: Double
let accuracy: UInt8
let datePublished: Date
let timestamp: Date?
let confidence: UInt8?
var location: CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
init(lat: Double, lng: Double, acc: UInt8, dP: Date, t: Date, c: UInt8) {
self.latitude = lat
self.longitude = lng
self.accuracy = acc
self.datePublished = dP
self.timestamp = t
self.confidence = c
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.latitude = try values.decode(Double.self, forKey: .latitude)
self.longitude = try values.decode(Double.self, forKey: .longitude)
do {
let uAcc = try values.decode(UInt8.self, forKey: .accuracy)
self.accuracy = uAcc
} catch {
let iAcc = try values.decode(Int8.self, forKey: .accuracy)
self.accuracy = UInt8(bitPattern: iAcc)
}
self.datePublished = try values.decode(Date.self, forKey: .datePublished)
self.timestamp = try? values.decode(Date.self, forKey: .timestamp)
self.confidence = try? values.decode(UInt8.self, forKey: .confidence)
}
}
enum FindMyError: Error {
case decryptionError(description: String)
}

View File

@@ -0,0 +1,49 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
class AccessoryController: ObservableObject {
static let shared = AccessoryController()
@Published var accessories: [Accessory]
init() {
self.accessories = KeychainController.loadAccessoriesFromKeychain()
}
init(accessories: [Accessory]) {
self.accessories = accessories
}
func save() throws {
try KeychainController.storeInKeychain(accessories: self.accessories)
}
func load() {
self.accessories = KeychainController.loadAccessoriesFromKeychain()
}
func updateWithDecryptedReports(devices: [FindMyDevice]) {
// Assign last locations
for device in FindMyController.shared.devices {
if let idx = self.accessories.firstIndex(where: {$0.id == Int(device.deviceId)}) {
self.objectWillChange.send()
let accessory = self.accessories[idx]
let report = device.decryptedReports?
.sorted(by: {$0.timestamp ?? Date.distantPast > $1.timestamp ?? Date.distantPast })
.first
accessory.lastLocation = report?.location
accessory.locationTimestamp = report?.timestamp
self.accessories[idx] = accessory
}
}
}
}

View File

@@ -0,0 +1,83 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import Security
import OSLog
struct KeychainController {
static func loadAccessoriesFromKeychain(test: Bool=false) -> [Accessory] {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrLabel: "FindMyAccessories",
kSecAttrService: "SEEMOO-FINDMY",
kSecMatchLimit: kSecMatchLimitOne,
kSecReturnData: true
]
if test {
query[kSecAttrService] = "SEEMOO-Test"
}
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess,
let resultData = result as? Data else {
return []
}
// Convert from PropertyList to an array of accessories
do {
let accessories = try PropertyListDecoder().decode([Accessory].self, from: resultData)
return accessories
} catch {
os_log("Could not decode accessories %@", String(describing: error))
}
return []
}
static func storeInKeychain(accessories: [Accessory], test: Bool=false) throws {
// Store or update
var attributes: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrLabel: "FindMyAccessories",
kSecAttrService: "SEEMOO-FINDMY",
kSecValueData: try PropertyListEncoder().encode(accessories)
]
if test {
attributes[kSecAttrService] = "SEEMOO-Test"
}
// Try to store the item
let storeStatus = SecItemAdd(attributes as CFDictionary, nil)
if storeStatus == errSecDuplicateItem {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrLabel: "FindMyAccessories",
kSecAttrService: "SEEMOO-FINDMY"
]
if test {
query[kSecAttrService] = "SEEMOO-Test"
}
// Update the existing item
let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
guard updateStatus == errSecSuccess else {
throw KeychainError.updatingItemFailed
}
}
}
}
enum KeychainError: Error {
case updatingItemFailed
}

View File

@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>20C69</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>HaystackMail</string>
<key>CFBundleIdentifier</key>
<string>de.tu-darmstadt.seemoo.HaystackMail</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>HaystackMail</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>12D4e</string>
<key>DTPlatformName</key>
<string>macosx</string>
<key>DTPlatformVersion</key>
<string>11.1</string>
<key>DTSDKBuild</key>
<string>20C63</string>
<key>DTSDKName</key>
<string>macosx11.1</string>
<key>DTXcode</key>
<string>1240</string>
<key>DTXcodeBuild</key>
<string>12D4e</string>
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2021 SEEMOO - TU Darmstadt. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string>HaystackPluginService</string>
<key>Supported10.15PluginCompatibilityUUIDs</key>
<array>
<string># UUIDs for versions from 10.12 to 99.99.99</string>
<string># For mail version 10.0 (3226) on OS X Version 10.12 (build 16A319)</string>
<string>36CCB8BB-2207-455E-89BC-B9D6E47ABB5B</string>
<string># For mail version 10.1 (3251) on OS X Version 10.12.1 (build 16B2553a)</string>
<string>9054AFD9-2607-489E-8E63-8B09A749BC61</string>
<string># For mail version 10.2 (3259) on OS X Version 10.12.2 (build 16D12b)</string>
<string>1CD3B36A-0E3B-4A26-8F7E-5BDF96AAC97E</string>
<string># For mail version 10.3 (3273) on OS X Version 10.12.4 (build 16G1036)</string>
<string>21560BD9-A3CC-482E-9B99-95B7BF61EDC1</string>
<string># For mail version 11.0 (3441.0.1) on OS X Version 10.13 (build 17A315i)</string>
<string>C86CD990-4660-4E36-8CDA-7454DEB2E199</string>
<string># For mail version 12.0 (3445.100.39) on OS X Version 10.14.1 (build 18B45d)</string>
<string>A4343FAF-AE18-40D0-8A16-DFAE481AF9C1</string>
<string># For mail version 13.0 (3594.4.2) on OS X Version 10.15 (build 19A558d)</string>
<string>6EEA38FB-1A0B-469B-BB35-4C2E0EEA9053</string>
</array>
<key>Supported11.0PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.1PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.2PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.3PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.4PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict/>
<key>files2</key>
<dict/>
<key>rules</key>
<dict>
<key>^Resources/</key>
<true/>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>

View File

@@ -0,0 +1,124 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import OSLog
import AppKit
let mailBundleName = "OpenHaystackMail"
/// Manages plugin installation
struct MailPluginManager {
let pluginsFolderURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Mail/Bundles")
let pluginURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Mail/Bundles").appendingPathComponent(mailBundleName + ".mailbundle")
var isMailPluginInstalled: Bool {
return FileManager.default.fileExists(atPath: pluginURL.path)
}
/// Shows a NSSavePanel to install the mail plugin at the required place
func askForPermission() -> Bool {
let panel = NSSavePanel()
panel.title = "Install Mail Plugin"
panel.prompt = "Install"
panel.canCreateDirectories = true
panel.showsTagField = false
panel.message = "OpenHaystack has no right to access the directory to install the plug-in automatically. By clicking install you grant the persmission."
if FileManager.default.fileExists(atPath: self.pluginsFolderURL.path) {
panel.directoryURL = self.pluginsFolderURL
panel.nameFieldLabel = "OpenHaystackMail Plugin"
panel.nameFieldStringValue = mailBundleName + ".mailbundle"
} else {
panel.directoryURL = self.pluginsFolderURL.deletingLastPathComponent()
panel.nameFieldLabel = "OpenHaystackMail Plugin"
panel.nameFieldStringValue = "Bundles"
}
panel.center()
let result = panel.runModal()
return result == .OK && (panel.nameFieldStringValue == "Bundles" || panel.nameFieldStringValue == mailBundleName + ".mailbundle")
}
/// Install the mail plug-in to the correct location
/// - Throws: An error if copying the fails fail. Due to permission or other errors
func installMailPlugin() throws {
guard self.askForPermission() else {
throw PluginError.permissionNotGranted
}
let localPluginURL = Bundle.main.url(forResource: mailBundleName, withExtension: "mailbundle")!
do {
try FileManager.default.createDirectory(at: pluginsFolderURL, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
}
try self.copyFolder(from: localPluginURL, to: pluginURL)
self.openAppleMail()
}
fileprivate func openAppleMail() {
NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/System/Applications/Mail.app"), configuration: NSWorkspace.OpenConfiguration(), completionHandler: nil)
}
/// Copy a folder recursively
/// - Parameters:
/// - from: Folder source
/// - to: Folder destination
/// - Throws: An error if copying or acessing files fails
func copyFolder(from: URL, to: URL) throws {
// Create the folder
try? FileManager.default.createDirectory(at: to, withIntermediateDirectories: false, attributes: nil)
let files = try FileManager.default.contentsOfDirectory(atPath: from.path)
for file in files {
// Check if file is a folder
var isDir: ObjCBool = .init(booleanLiteral: false)
let fileURL = from.appendingPathComponent(file)
FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isDir)
if isDir.boolValue == true {
try self.copyFolder(from: fileURL, to: to.appendingPathComponent(file))
} else {
// Copy file
try FileManager.default.copyItem(at: fileURL, to: to.appendingPathComponent(file))
}
}
}
func uninstallMailPlugin() throws {
try FileManager.default.removeItem(at: pluginURL)
}
/// Copy plugin to downloads folder
/// - Throws: An error if the copy fails, because of missing permissions
func pluginDownload() throws {
guard let localPluginURL = Bundle.main.url(forResource: mailBundleName, withExtension: "mailbundle"),
let downloadsFolder = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first else {
throw PluginError.downloadFailed
}
let downloadsPluginURL = downloadsFolder.appendingPathComponent(mailBundleName + ".mailbundle")
try self.copyFolder(from: localPluginURL, to: downloadsPluginURL)
}
}
enum PluginError: Error {
case installationFailed
case downloadFailed
case permissionNotGranted
}

View File

@@ -0,0 +1,77 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
struct MicrobitController {
/// Find all microbits connected to this mac
/// - Throws: If a volume is inaccessible
/// - Returns: an array of urls
static func findMicrobits() throws -> [URL] {
let fm = FileManager.default
let volumes = try fm.contentsOfDirectory(atPath: "/Volumes")
let microbits: [URL] = volumes.filter({$0.lowercased().contains("microbit")}).map({URL(fileURLWithPath: "/Volumes").appendingPathComponent($0)})
return microbits
}
/// Deploy the firmware to a USB connected microbit at the given URL
/// - Parameters:
/// - microbitURL: URL to the microbit
/// - firmwareFile: Firmware file as binary data
/// - Throws: An error if the write fails
static func deployToMicrobit(_ microbitURL: URL, firmwareFile: Data) throws {
let firmwareURL = microbitURL.appendingPathComponent("firware.bin")
try firmwareFile.write(to: firmwareURL, options: .atomicWrite)
}
/// Patch the given firmware.
/// This will replace the pattern data (the place for the key) with the actual key
/// - Parameters:
/// - firmware: The firmware data that should be patched
/// - pattern: The pattern that should be replaced
/// - key: The key that should be added
/// - returns: The patched firmware file
static func patchFirmware(_ firmware: Data, pattern: Data, with key: Data) throws -> Data {
guard pattern.count == key.count else {
throw PatchingError.inequalLength
}
var patchedFirmware = Data(firmware)
var patchingSuccessful = false
// Find the position of the pattern
for bytePosition in firmware.startIndex...firmware.endIndex {
// Use a sliding window to look for the pattern
// Check if the firmware is long enough
guard bytePosition.advanced(by: pattern.count) <= firmware.endIndex else { break }
let range = bytePosition..<bytePosition.advanced(by: pattern.count)
let potentialPattern = firmware[range]
assert(potentialPattern.count == pattern.count)
if Array(potentialPattern) == Array(pattern) {
// Found pattern. Replace in binary
patchedFirmware.replaceSubrange(range, with: key)
patchingSuccessful = true
}
}
guard patchingSuccessful else {
throw PatchingError.patternNotFound
}
return patchedFirmware
}
}
enum PatchingError: Error {
case inequalLength
case patternNotFound
}

View File

@@ -0,0 +1,139 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import CryptoKit
import Security
import SwiftUI
import CoreLocation
class Accessory: ObservableObject, Codable, Identifiable, Equatable {
let name: String
let id: Int
let privateKey: Data
let color: Color
let icon: String
@Published var lastLocation: CLLocation?
@Published var locationTimestamp: Date?
init(name: String, color: Color = Color.white, iconName: String = "briefcase.fill") throws {
self.name = name
guard let key = BoringSSL.generateNewPrivateKey() else {
throw KeyError.keyGenerationFailed
}
self.id = key.hashValue
self.privateKey = key
self.color = color
self.icon = iconName
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.id = try container.decode(Int.self, forKey: .id)
self.privateKey = try container.decode(Data.self, forKey: .privateKey)
self.icon = (try? container.decode(String.self, forKey: .icon)) ?? "briefcase.fill"
if var colorComponents = try? container.decode([CGFloat].self, forKey: .colorComponents),
let spaceName = try? container.decode(String.self, forKey: .colorSpaceName),
let cgColor = CGColor(colorSpace: CGColorSpace(name: spaceName as CFString)!, components: &colorComponents) {
self.color = Color(cgColor)
} else {
self.color = Color.white
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.name, forKey: .name)
try container.encode(self.id, forKey: .id)
try container.encode(self.privateKey, forKey: .privateKey)
try container.encode(self.icon, forKey: .icon)
if let colorComponents = self.color.cgColor?.components,
let colorSpace = self.color.cgColor?.colorSpace?.name {
try container.encode(colorComponents, forKey: .colorComponents)
try container.encode(colorSpace as String, forKey: .colorSpaceName)
}
}
/// The public key in the format used for Offline finding. It is 28 bytes long and can be transferred to a microbit
func getActualPublicKey() throws -> Data {
guard let publicKey = BoringSSL.derivePublicKey(fromPrivateKey: self.privateKey) else {
throw KeyError.keyDerivationFailed
}
return publicKey
}
func getAdvertisementKey() throws -> Data {
guard var publicKey = BoringSSL.derivePublicKey(fromPrivateKey: self.privateKey) else {
throw KeyError.keyDerivationFailed
}
// Drop the first byte to just have the 28 bytes version
publicKey = publicKey.dropFirst()
assert(publicKey.count == 28)
guard publicKey.count == 28 else {throw KeyError.keyDerivationFailed}
return publicKey
}
/// Offline finding uses an id for each key to identify a device / location report.
/// The key is a SHA256 hash of the public key bytes formatted as Base64
/// - Throws: An error if the key derivation or hashing fails
/// - Returns: A base64 id of the current key
func getKeyId() throws -> String {
try self.hashedPublicKey().base64EncodedString()
}
private func hashedPublicKey() throws -> Data {
let publicKey = try self.getAdvertisementKey()
var sha = SHA256()
sha.update(data: publicKey)
let digest = sha.finalize()
return Data(digest)
}
func toFindMyDevice() throws -> FindMyDevice {
let findMyKey = FindMyKey(advertisedKey: try self.getAdvertisementKey(),
hashedKey: try self.hashedPublicKey(),
privateKey: self.privateKey,
startTime: nil,
duration: nil,
pu: nil,
yCoordinate: nil,
fullKey: nil)
return FindMyDevice(deviceId: String(self.id),
keys: [findMyKey],
catalinaBigSurKeyFiles: nil,
reports: nil,
decryptedReports: nil)
}
enum CodingKeys: String, CodingKey {
case name
case id
case privateKey
case colorComponents
case colorSpaceName
case icon
}
static func == (lhs: Accessory, rhs: Accessory) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name && lhs.privateKey == rhs.privateKey && lhs.icon == rhs.icon
}
}
enum KeyError: Error {
case keyGenerationFailed
case keyDerivationFailed
}

View File

@@ -0,0 +1,39 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import SwiftUI
// swiftlint:disable force_try
struct PreviewData {
static let accessories: [Accessory] = {
return accessoryList()
}()
static func accessoryList() -> [Accessory] {
let latitude: Double = 52.5219814
let longitude: Double = 13.413306
let backpack = try! Accessory(name: "Backpack", color: Color.green, iconName: "briefcase.fill")
backpack.lastLocation = CLLocation(latitude: latitude + (Double(arc4random() % 1000))/100000, longitude: longitude + (Double(arc4random() % 1000))/100000)
let bag = try! Accessory(name: "Bag", color: Color.blue, iconName: "latch.2.case.fill")
bag.lastLocation = CLLocation(latitude: latitude + (Double(arc4random() % 1000))/100000, longitude: longitude + (Double(arc4random() % 1000))/100000)
let car = try! Accessory(name: "Car", color: Color.red, iconName: "car.fill")
car.lastLocation = CLLocation(latitude: latitude + (Double(arc4random() % 1000))/100000, longitude: longitude + (Double(arc4random() % 1000))/100000)
let keys = try! Accessory(name: "Keys", color: Color.orange, iconName: "key.fill")
keys.lastLocation = CLLocation(latitude: latitude + (Double(arc4random() % 1000))/100000, longitude: longitude + (Double(arc4random() % 1000))/100000)
let items = try! Accessory(name: "Items", color: Color.gray, iconName: "mappin")
items.lastLocation = CLLocation(latitude: latitude + (Double(arc4random() % 1000))/100000, longitude: longitude + (Double(arc4random() % 1000))/100000)
return [backpack, bag, car, keys, items]
}
}

View File

@@ -0,0 +1,100 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
import OSLog
struct AccessoryListEntry: View {
var accessory: Accessory
@Binding var alertType: OpenHaystackMainView.AlertType?
var delete: (Accessory) -> Void
var deployAccessoryToMicrobit: (Accessory) -> Void
var zoomOn: (Accessory) -> Void
var body: some View {
VStack {
HStack {
Button(action: {
self.zoomOn(self.accessory)
}, label: {
HStack {
Text(accessory.name)
Spacer()
}
.contentShape(Rectangle())
})
.buttonStyle(PlainButtonStyle())
HStack(alignment: .center) {
Button(action: {self.zoomOn(self.accessory)}, label: {
Circle()
.strokeBorder(accessory.color, lineWidth: 2.0)
.background(
ZStack {
Circle().fill(Color("PinColor"))
Image(systemName: accessory.icon)
.padding(3)
}
)
.frame(width: 30, height: 30)
})
.buttonStyle(PlainButtonStyle())
Button(action: {
self.deployAccessoryToMicrobit(accessory)
}, label: {
Text("Deploy")
})
}
.padding(.trailing)
}
Divider()
}
.contentShape(Rectangle())
.contextMenu {
Button("Delete", action: {self.delete(accessory)})
Divider()
Button("Copy advertisment key (Base64)", action: {self.copyPublicKey(of: accessory)})
Button("Copy key id (Base64)", action: {self.copyPublicKeyHash(of: accessory)})
}
}
func copyPublicKey(of accessory: Accessory) {
do {
let publicKey = try accessory.getAdvertisementKey()
let pasteboard = NSPasteboard.general
pasteboard.prepareForNewContents(with: .currentHostOnly)
pasteboard.setString(publicKey.base64EncodedString(), forType: .string)
} catch {
os_log("Failed extracing public key %@", String(describing: error))
assert(false)
}
}
func copyPublicKeyHash(of accessory: Accessory) {
do {
let keyID = try accessory.getKeyId()
let pasteboard = NSPasteboard.general
pasteboard.prepareForNewContents(with: .currentHostOnly)
pasteboard.setString(keyID, forType: .string)
} catch {
os_log("Failed extracing public key %@", String(describing: error))
assert(false)
}
}
}
// struct AccessoryListEntry_Previews: PreviewProvider {
// static var previews: some View {
// AccessoryListEntry()
// }
// }

View File

@@ -0,0 +1,137 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import MapKit
import SwiftUI
class AccessoryAnnotationView: MKAnnotationView {
var pinView: NSHostingView<AccessoryPinView>?
var myAnnotation: MKAnnotation? {
didSet {
self.updateView()
}
}
override var annotation: MKAnnotation? {
get {
self.myAnnotation
}
set(a) {
self.myAnnotation = a
}
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.image = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateView() {
guard let accessory = (self.annotation as? AccessoryAnnotation)?.accessory else {return}
self.pinView?.removeFromSuperview()
self.pinView = NSHostingView(rootView: AccessoryPinView(accessory: accessory))
self.addSubview(pinView!)
self.leftCalloutOffset = CGPoint(x: -13, y: -15)
self.rightCalloutOffset = CGPoint(x: -13, y: -15)
let calloutView = NSTextView()
calloutView.string = accessory.name
calloutView.frame = NSRect(x: 0, y: 0, width: 150, height: 30)
if let date = accessory.locationTimestamp {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
let dateString = dateFormatter.string(from: date)
calloutView.string = "\(accessory.name)\n\(dateString)"
calloutView.frame = NSRect(x: 0, y: 0, width: 150, height: 40)
}
calloutView.sizeToFit()
calloutView.backgroundColor = NSColor.clear
self.detailCalloutAccessoryView = calloutView
self.canShowCallout = true
}
// override func draw(_ dirtyRect: NSRect) {
// guard let accessoryAnnotation = self.annotation as? AccessoryAnnotation else {
// super.draw(dirtyRect)
// return
// }
//
// let path = NSBezierPath(ovalIn: dirtyRect)
// path.lineWidth = 2.0
//
// guard let cgColor = accessoryAnnotation.accessory.color.cgColor,
// let strokeColor = NSColor(cgColor: cgColor)?.withAlphaComponent(0.8) else {return}
//
// NSColor(named: NSColor.Name("PinColor"))?.setFill()
//
// path.fill()
//
// strokeColor.setStroke()
// path.stroke()
//
// let accessory = accessoryAnnotation.accessory
//
// guard let image = NSImage(systemSymbolName: accessory.icon, accessibilityDescription: accessory.name) else {return}
//
// let ratio = image.size.width / image.size.height
// let imageWidth: CGFloat = 20
// let imageHeight = imageWidth / ratio
// let imageRect = NSRect(
// x: dirtyRect.width/2 - imageWidth/2,
// y: dirtyRect.height/2 - imageHeight/2,
// width: imageWidth, height: imageHeight)
//
// image.draw(in: imageRect)
// }
struct AccessoryPinView: View {
var accessory: Accessory
var body: some View {
Circle()
.strokeBorder(accessory.color, lineWidth: 2.0)
.background(
ZStack {
Circle().fill(Color("PinColor"))
Image(systemName: accessory.icon)
.padding(3)
}
)
.frame(width: 30, height: 30)
}
}
}
class AccessoryAnnotation: NSObject, MKAnnotation {
let accessory: Accessory
var coordinate: CLLocationCoordinate2D {
return accessory.lastLocation!.coordinate
}
init(accessory: Accessory) {
self.accessory = accessory
}
}

View File

@@ -0,0 +1,31 @@
//
// AccessoryMapView.swift
// OpenHaystack
//
// Created by Alex - SEEMOO on 02.03.21.
// Copyright © 2021 SEEMOO - TU Darmstadt. All rights reserved.
//
import Foundation
import SwiftUI
import MapKit
struct AccessoryMapView: NSViewControllerRepresentable {
@ObservedObject var accessoryController: AccessoryController
@Binding var mapType: MKMapType
var focusedAccessory: Accessory?
func makeNSViewController(context: Context) -> MapViewController {
return MapViewController(nibName: NSNib.Name("MapViewController"), bundle: nil)
}
func updateNSViewController(_ nsViewController: MapViewController, context: Context) {
let accessories = self.accessoryController.accessories
nsViewController.zoom(on: focusedAccessory)
nsViewController.addLastLocations(from: accessories)
nsViewController.changeMapType(mapType)
}
}

View File

@@ -0,0 +1,34 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import SwiftUI
import AppKit
final class ActivityIndicator: NSViewRepresentable {
init(size: NSControl.ControlSize) {
self.size = size
}
let size: NSControl.ControlSize
typealias NSViewType = NSProgressIndicator
func makeNSView(context: Context) -> NSProgressIndicator {
let indicator = NSProgressIndicator()
indicator.style = .spinning
indicator.controlSize = self.size
indicator.startAnimation(nil)
return indicator
}
func updateNSView(_ nsView: NSProgressIndicator, context: Context) {
}
}

View File

@@ -0,0 +1,78 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
struct IconSelectionView: View {
@State var showImagePicker = false
@State var color: Color = .red
@Binding var selectedImageName: String
var body: some View {
ZStack {
Button(action: {
withAnimation {
self.showImagePicker.toggle()
}
}, label: {
Circle()
.strokeBorder(Color.gray, lineWidth: 0.5)
.background(
Image(systemName: self.selectedImageName)
)
.frame(width: 30, height: 30)
})
.buttonStyle(PlainButtonStyle())
.popover(isPresented: self.$showImagePicker, content: {
ImageSelectionList(selectedImageName: self.$selectedImageName) {
self.showImagePicker = false
}
})
}
}
}
struct ColorSelectionView_Previews: PreviewProvider {
@State static var selectedImageName: String = "briefcase.fill"
static var previews: some View {
Group {
IconSelectionView(selectedImageName: self.$selectedImageName)
ImageSelectionList(selectedImageName: self.$selectedImageName, dismiss: {})
}
}
}
struct ImageSelectionList: View {
let selectableIcons = ["briefcase.fill", "case.fill", "latch.2.case.fill", "key.fill", "mappin", "crown.fill", "gift.fill", "car.fill"]
@Binding var selectedImageName: String
let dismiss: () -> Void
var body: some View {
List(self.selectableIcons, id: \.self) { iconName in
Button(action: {
self.selectedImageName = iconName
self.dismiss()
}, label: {
HStack {
Spacer()
Image(systemName: iconName)
Spacer()
}
})
.buttonStyle(PlainButtonStyle())
.contentShape(Rectangle())
}
.frame(width: 100)
}
}

View File

@@ -0,0 +1,476 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
import OSLog
import MapKit
struct OpenHaystackMainView: View {
@State var keyName: String = ""
@State var accessoryColor: Color = Color.white
@State var selectedIcon: String = "briefcase.fill"
@State var loading = false
@ObservedObject var accessoryController = AccessoryController.shared
var accessories: [Accessory] {
return self.accessoryController.accessories
}
@State var showKeyError = false
@State var alertType: AlertType?
@State var popUpAlertType: PopUpAlertType?
@State var errorDescription: String?
@State var searchPartyToken: String = ""
@State var searchPartyTokenLoaded = false
@State var mapType: MKMapType = .standard
@State var isLoading = false
@State var focusedAccessory: Accessory?
var body: some View {
GeometryReader { geo in
ZStack {
VStack {
HStack {
self.accessoryView
.frame(width: geo.size.width * 0.5)
Spacer()
VStack {
self.mapView
}.frame(width: geo.size.width * 0.5, alignment: .trailing)
}
if searchPartyTokenLoaded == false {
TextField("Search Party token", text: self.$searchPartyToken)
}
}
if self.popUpAlertType != nil {
VStack {
Spacer()
PopUpAlertView(alertType: self.popUpAlertType!)
.transition(AnyTransition.move(edge: .bottom))
.padding(.bottom, 30)
}
}
}
.alert(item: self.$alertType, content: { alertType in
return self.alert(for: alertType)
})
.onChange(of: self.searchPartyToken) { (searchPartyToken) in
guard !searchPartyToken.isEmpty, self.accessories.isEmpty == false else {return}
self.downloadLocationReports()
}
.onChange(of: self.popUpAlertType, perform: { popUpAlert in
guard popUpAlert != nil else {return}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.popUpAlertType = nil
}
})
.onAppear {
self.onAppear()
}
}
.padding([.leading, .trailing, .bottom])
.frame(minWidth: 720, maxWidth: .infinity, minHeight: 480, maxHeight: .infinity)
}
// MARK: Subviews
/// Left side of the view. Shows a list of accessories and the possibility to add accessories
var accessoryView: some View {
VStack {
Text("Create a new tracking accessory")
.font(.title2)
.padding(.top)
Text("A BBC Microbit can be used to track anything you care about. Connect it over USB, name the accessory (e.g. Backpack) generate the key and deploy it")
.multilineTextAlignment(.center)
.font(.caption)
.foregroundColor(.gray)
HStack {
TextField("Name", text: self.$keyName)
ColorPicker("", selection: self.$accessoryColor)
.frame(maxWidth: 50, maxHeight: 20)
IconSelectionView(selectedImageName: self.$selectedIcon)
}
Button(action: self.addAccessory, label: {
Text("Generate key and deploy")
})
.disabled(self.keyName.isEmpty)
.padding(.bottom)
Divider()
Text("Your accessories")
.font(.title2)
.padding(.top)
if self.accessories.isEmpty {
Spacer()
Text("No accessories have been added yet. Go ahead and add one above")
.multilineTextAlignment(.center)
} else {
self.accessoryList
}
Spacer()
}
}
/// Accessory List view
var accessoryList: some View {
List(self.accessories) { accessory in
AccessoryListEntry(accessory: accessory,
alertType: self.$alertType,
delete: self.delete(accessory:),
deployAccessoryToMicrobit: self.deployAccessoryToMicrobit(accessory:),
zoomOn: {self.focusedAccessory = $0})
}
.background(Color.clear)
.cornerRadius(15.0)
}
/// Overlay for the map that is gray and shows an activity indicator when loading
var mapOverlay: some View {
ZStack {
if self.isLoading {
Rectangle()
.fill(Color.gray)
.opacity(0.5)
ActivityIndicator(size: .large)
}
}
}
/// Right side of the view showing a map with all items presented.
var mapView: some View {
ZStack {
AccessoryMapView(accessoryController: self.accessoryController, mapType: self.$mapType, focusedAccessory: self.focusedAccessory)
.overlay(self.mapOverlay)
.cornerRadius(15.0)
.clipped()
.padding([.top, .bottom], 15)
VStack {
Spacer()
HStack {
Picker("", selection: self.$mapType) {
Text("Satellite").tag(MKMapType.hybrid)
Text("Standard").tag(MKMapType.standard)
}
.pickerStyle(SegmentedPickerStyle())
.frame(width: 150, alignment: .center)
Button(action: self.downloadLocationReports, label: {
Image(systemName: "arrow.clockwise")
Text("Reload")
})
.opacity(1.0)
.disabled(self.accessories.isEmpty)
}
.padding(.bottom, 25)
}
}
}
/// Add an accessory with the provided details
func addAccessory() {
let keyName = self.keyName
self.keyName = ""
do {
let accessory = try Accessory(name: keyName, color: self.accessoryColor, iconName: self.selectedIcon)
let accessories = self.accessories + [accessory]
withAnimation {
self.accessoryController.accessories = accessories
}
try self.accessoryController.save()
self.deployAccessoryToMicrobit(accessory: accessory)
} catch {
self.errorDescription = String(describing: error)
self.showKeyError = true
}
}
/// Download the location reports for all current accessories. Shows an error if something fails, like plug-in is missing
func downloadLocationReports() {
self.checkPluginIsRunning { (running) in
guard running else {
self.alertType = .activatePlugin
return
}
guard !self.searchPartyToken.isEmpty,
let tokenData = self.searchPartyToken.data(using: .utf8) else {
self.alertType = .searchPartyToken
return
}
withAnimation {
self.isLoading = true
}
let findMyDevices = self.accessories.compactMap({ acc -> FindMyDevice? in
do {
return try acc.toFindMyDevice()
} catch {
os_log("Failed getting id for key %@", String(describing: error))
return nil
}
})
FindMyController.shared.devices = findMyDevices
FindMyController.shared.fetchReports(with: tokenData) { error in
let reports = FindMyController.shared.devices.compactMap({$0.reports}).flatMap({$0})
if reports.isEmpty {
withAnimation {
self.popUpAlertType = .noReportsFound
}
} else {
self.accessoryController.updateWithDecryptedReports(devices: FindMyController.shared.devices)
}
withAnimation {
self.isLoading = false
}
guard error != nil else {return}
os_log("Error: %@", String(describing: error))
}
}
}
/// Delete an accessory from the list of accessories
func delete(accessory: Accessory) {
do {
var accessories = self.accessories
guard let idx = accessories.firstIndex(of: accessory) else {return}
accessories.remove(at: idx)
withAnimation {
self.accessoryController.accessories = accessories
}
try self.accessoryController.save()
} catch {
self.alertType = .deletionFailed
}
}
/// Deploy the public key of the accessory to a BBC microbit
func deployAccessoryToMicrobit(accessory: Accessory) {
do {
let microbits = try MicrobitController.findMicrobits()
guard let microBitURL = microbits.first,
let firmwareURL = Bundle.main.url(forResource: "firmware", withExtension: "bin") else {
self.alertType = .deployFailed
return
}
let firmware = try Data(contentsOf: firmwareURL)
let pattern = "OFFLINEFINDINGPUBLICKEYHERE!".data(using: .ascii)!
let publicKey = try accessory.getAdvertisementKey()
let patchedFirmware = try MicrobitController.patchFirmware(firmware, pattern: pattern, with: publicKey)
try MicrobitController.deployToMicrobit(microBitURL, firmwareFile: patchedFirmware)
} catch {
os_log("Error occurred %@", String(describing: error))
self.alertType = .deployFailed
return
}
self.alertType = .deployedSuccessfully
}
func onAppear() {
/// Checks if the search party token can be fetched without the Mail Plugin. If true the plugin is not needed for this environment. (e.g. when SIP is disabled)
let reportsFetcher = ReportsFetcher()
if let token = reportsFetcher.fetchSearchpartyToken(),
let tokenString = String(data: token, encoding: .ascii) {
self.searchPartyToken = tokenString
return
}
let pluginManager = MailPluginManager()
// Check if the plugin is installed
if pluginManager.isMailPluginInstalled == false {
// Install the mail plugin
self.alertType = .activatePlugin
} else {
self.checkPluginIsRunning(nil)
}
}
/// Ask to install and activate the mail plugin
func installMailPlugin() {
let pluginManager = MailPluginManager()
guard pluginManager.isMailPluginInstalled == false else {
return
}
do {
try pluginManager.installMailPlugin()
} catch {
DispatchQueue.main.async {
self.alertType = .pluginInstallFailed
os_log(.error, "Could not install mail plugin\n %@", String(describing: error))
}
}
}
func checkPluginIsRunning(_ completion: ((Bool) -> Void)?) {
// Check if Mail plugin is active
AnisetteDataManager.shared.requestAnisetteData { (result) in
DispatchQueue.main.async {
switch result {
case .success(let accountData):
withAnimation {
self.searchPartyToken = String(data: accountData.searchPartyToken, encoding: .ascii) ?? ""
if self.searchPartyToken.isEmpty == false {
self.searchPartyTokenLoaded = true
}
}
completion?(true)
case .failure(let error):
if let error = error as? AnisetteDataError {
switch error {
case .pluginNotFound:
self.alertType = .activatePlugin
default:
self.alertType = .activatePlugin
}
}
completion?(false)
}
}
}
}
func downloadPlugin() {
do {
try MailPluginManager().pluginDownload()
} catch {
self.alertType = .pluginInstallFailed
}
}
// MARK: - Alerts
/// Create an alert for the given alert type
/// - Parameter alertType: current alert type
/// - Returns: A SwiftUI Alert
func alert(for alertType: AlertType) -> Alert {
switch alertType {
case .keyError:
return Alert(title: Text("Could not create accessory"), message: Text(String(describing: self.errorDescription)), dismissButton: Alert.Button.cancel())
case .searchPartyToken:
return Alert(title: Text("Add the search party token"),
message: Text(
"""
Please paste the search party token below after copying itfrom the macOS Keychain.
The item that contains the key can be found by searching for:
com.apple.account.DeviceLocator.search-party-token
"""
),
dismissButton: Alert.Button.okay())
case .deployFailed:
return Alert(title: Text("Could not deploy"),
message: Text("Deploying to microbit failed. Please reconnect the device over USB"),
dismissButton: Alert.Button.okay())
case .deployedSuccessfully:
return Alert(title: Text("Deploy successfull"),
message: Text("This device will now be tracked by all iPhones and you can use this app to find its last reported location"),
dismissButton: Alert.Button.okay())
case .deletionFailed:
return Alert(title: Text("Could not delete accessory"), dismissButton: Alert.Button.okay())
case .noReportsFound:
return Alert(title: Text("No reports found"),
message: Text("Your accessory might have not been found yet or it is not powered. Make sure it has enough power to be found by nearby iPhones"),
dismissButton: Alert.Button.okay())
case .activatePlugin:
let message =
"""
To access your Apple ID for downloading location reports we need to use a plugin in Apple Mail.
Please make sure Apple Mail is running.
Open Mail -> Preferences -> General -> Manage Plug-Ins... -> Select Haystack
We do not access any of your e-mail data. This is just necessary, because Apple blocks access to certain iCloud tokens otherwise.
"""
return Alert(title: Text("Install & Activate Mail Plugin"), message: Text(message),
primaryButton: .default(Text("Okay"), action: {self.installMailPlugin()}),
secondaryButton: .cancel())
case .pluginInstallFailed:
return Alert(title: Text("Mail Plugin installation failed"),
message: Text("To access the location reports of your devices an Apple Mail plugin is necessary" +
"\nThe installtion of this plugin has failed.\n\n Please download it manually unzip it and move it to /Library/Mail/Bundles"),
primaryButton: .default(Text("Download plug-in"), action: {
self.downloadPlugin()
}), secondaryButton: .cancel())
}
}
enum AlertType: Int, Identifiable {
var id: Int {
return self.rawValue
}
case keyError
case searchPartyToken
case deployFailed
case deployedSuccessfully
case deletionFailed
case noReportsFound
case activatePlugin
case pluginInstallFailed
}
}
struct OpenHaystackMainView_Previews: PreviewProvider {
static var accessories: [Accessory] = PreviewData.accessories
static var previews: some View {
OpenHaystackMainView(accessoryController: AccessoryController(accessories: accessories))
.frame(width: 640, height: 480, alignment: .center)
}
}
extension Alert.Button {
static func okay() -> Alert.Button {
Alert.Button.default(Text("Okay"))
}
}

View File

@@ -0,0 +1,45 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
struct PopUpAlertView: View {
let alertType: PopUpAlertType
var body: some View {
VStack {
switch self.alertType {
case .noReportsFound:
VStack {
Text("No reports found")
.font(.title2)
Text("Your accessory might have not been found yet or it is not powered. Make sure it has enough power to be found by nearby iPhones")
.font(.caption)
}.padding()
}
}
.background(RoundedRectangle(cornerRadius: 7.5)
.fill(Color.gray))
}
}
struct PopUpAlertView_Previews: PreviewProvider {
static var previews: some View {
PopUpAlertView(alertType: .noReportsFound)
}
}
enum PopUpAlertType: Int, Identifiable {
var id: Int {
return self.rawValue
}
case noReportsFound
}

Binary file not shown.

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>0.1</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2021 SEEMOO TU Darmstadt</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSSupportsAutomaticTermination</key>
<true/>
<key>NSSupportsSuddenTermination</key>
<true/>
</dict>
</plist>

View File

@@ -0,0 +1,99 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Cocoa
import MapKit
final class MapViewController: NSViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var pinsShown = false
var focusedAccessory: Accessory?
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
self.mapView.register(AccessoryAnnotationView.self, forAnnotationViewWithReuseIdentifier: "Accessory")
}
func addLocationsReports(from devices: [FindMyDevice]) {
if !self.mapView.annotations.isEmpty {
self.mapView.removeAnnotations(self.mapView.annotations)
}
// Zoom to first location
if let location = devices.first?.decryptedReports?.first {
let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let span = MKCoordinateSpan(latitudeDelta: 5.0, longitudeDelta: 5.0)
let region = MKCoordinateRegion(center: coordinate, span: span)
self.mapView.setRegion(region, animated: true)
}
// Add pins
for device in devices {
guard let reports = device.decryptedReports else {continue}
for report in reports {
let pin = MKPointAnnotation()
pin.title = device.deviceId
pin.coordinate = CLLocationCoordinate2D(latitude: report.latitude, longitude: report.longitude)
self.mapView.addAnnotation(pin)
}
}
}
func zoom(on accessory: Accessory?) {
self.focusedAccessory = accessory
guard let location = accessory?.lastLocation else {return}
let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
DispatchQueue.main.async {
self.mapView.setRegion(region, animated: true)
}
}
func addLastLocations(from accessories: [Accessory]) {
if !self.mapView.annotations.isEmpty {
self.mapView.removeAnnotations(self.mapView.annotations)
}
// Zoom to first location
if focusedAccessory == nil, let location = accessories.first(where: {$0.lastLocation != nil})?.lastLocation {
let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
DispatchQueue.main.async {
self.mapView.setRegion(region, animated: true)
}
}
// Add pins
for accessory in accessories {
guard accessory.lastLocation != nil else {continue}
let annotation = AccessoryAnnotation(accessory: accessory)
self.mapView.addAnnotation(annotation)
}
}
func changeMapType(_ mapType: MKMapType) {
self.mapView.mapType = mapType
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
switch annotation {
case is AccessoryAnnotation:
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "Accessory", for: annotation)
annotationView.annotation = annotation
return annotationView
default:
return nil
}
}
}

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="16097" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="16097"/>
<plugIn identifier="com.apple.MapKitIBPlugin" version="16097"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="MapViewController" customModule="OfflineFinder" customModuleProvider="target">
<connections>
<outlet property="mapView" destination="dZd-TY-owu" id="M74-qQ-z9o"/>
<outlet property="view" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customView id="Hz6-mo-xeY">
<rect key="frame" x="0.0" y="0.0" width="480" height="272"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<subviews>
<mapView mapType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="dZd-TY-owu">
<rect key="frame" x="0.0" y="0.0" width="480" height="272"/>
</mapView>
</subviews>
<constraints>
<constraint firstItem="dZd-TY-owu" firstAttribute="top" secondItem="Hz6-mo-xeY" secondAttribute="top" id="IQV-8E-Mz4"/>
<constraint firstAttribute="trailing" secondItem="dZd-TY-owu" secondAttribute="trailing" id="e19-Gs-Swb"/>
<constraint firstAttribute="bottom" secondItem="dZd-TY-owu" secondAttribute="bottom" id="fJ4-IC-PW6"/>
<constraint firstItem="dZd-TY-owu" firstAttribute="leading" secondItem="Hz6-mo-xeY" secondAttribute="leading" id="l08-bw-Y1N"/>
</constraints>
<point key="canvasLocation" x="66" y="37"/>
</customView>
</objects>
</document>

View File

@@ -0,0 +1,33 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
import Cocoa
import MapKit
struct MapView_ViewControllerRepresentable: NSViewControllerRepresentable {
var findMyController: FindMyController?
func makeNSViewController(context: Context) -> MapViewController {
return MapViewController(nibName: NSNib.Name("MapViewController"), bundle: nil)
}
func updateNSViewController(_ nsViewController: MapViewController, context: Context) {
if let controller = self.findMyController {
nsViewController.addLocationsReports(from: controller.devices)
}
}
}
struct MapView: View {
@Environment(\.findMyController) var findMyController
var body: some View {
MapView_ViewControllerRepresentable(findMyController: self.findMyController)
}
}

View File

@@ -0,0 +1,195 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import SwiftUI
struct OFFetchReportsMainView: View {
@Environment(\.findMyController) var findMyController
@State var targetedDrop: Bool = false
@State var error: Error?
@State var showMap = false
@State var loading = false
@State var searchPartyToken: Data?
@State var searchPartyTokenString: String = ""
@State var keyPlistFile: Data?
@State var showTokenPrompt = false
var dropView: some View {
ZStack(alignment: .center) {
HStack {
Spacer()
Spacer()
}
VStack {
Spacer()
Text("Drop exported keys here")
.font(Font.system(size: 44, weight: .bold, design: .default))
.padding()
Text("The keys can be exported into the right format using the Read FindMy Keys App.")
.font(.body)
.multilineTextAlignment(.center)
.padding()
Spacer()
}
}
.background(
RoundedRectangle(cornerRadius: 20.0)
.stroke(Color.gray, style: StrokeStyle(lineWidth: 5.0, lineCap: .round, lineJoin: .round, miterLimit: 10, dash: [15]))
)
.padding()
.onDrop(of: ["public.file-url"], isTargeted: self.$targetedDrop) { (droppedData) -> Bool in
return self.droppedData(data: droppedData)
}
}
var loadingView: some View {
VStack {
Text("Downloading locations and decrypting...")
.font(Font.system(size: 44, weight: .bold, design: .default))
.padding()
}
}
/// This view is shown if the search party token cannot be accessed from keychain
var missingSearchPartyTokenView: some View {
VStack {
Text("Search Party token could not be fetched")
Text("Please paste the search party token below after copying it from the macOS Keychain.")
Text("The item that contains the key can be found by searching for: ")
Text("com.apple.account.DeviceLocator.search-party-token")
.font(.system(Font.TextStyle.body, design: Font.Design.monospaced))
TextField("Search Party Token", text: self.$searchPartyTokenString)
Button(action: {
if !self.searchPartyTokenString.isEmpty,
let file = self.keyPlistFile,
let searchPartyToken = self.searchPartyTokenString.data(using: .utf8) {
self.searchPartyToken = searchPartyToken
self.downloadAndDecryptLocations(with: file, searchPartyToken: searchPartyToken)
}
}, label: {
Text("Download reports")
})
}
}
var mapView: some View {
ZStack {
MapView()
VStack {
HStack {
Spacer()
Button(action: {
self.showMap = false
self.showTokenPrompt = false
}, label: {
Text("Import other tokens")
})
Button(action: {
self.exportDecryptedLocations()
}, label: {
Text("Export")
})
}
.padding()
Spacer()
}
}
}
var body: some View {
GeometryReader { geo in
if self.loading {
self.loadingView
} else if self.showMap {
self.mapView
} else if self.showTokenPrompt {
self.missingSearchPartyTokenView
} else {
self.dropView
.frame(width: geo.size.width, height: geo.size.height)
}
}
}
func droppedData(data: [NSItemProvider]) -> Bool {
guard let itemProvider = data.first else {return false}
itemProvider.loadItem(forTypeIdentifier: "public.file-url", options: nil) { (u, _) in
guard let urlData = u as? Data,
let fileURL = URL(dataRepresentation: urlData, relativeTo: nil),
// Only plist supported
fileURL.pathExtension == "plist",
// Load the file
let file = try? Data(contentsOf: fileURL)
else {return}
print("Received data \(fileURL)")
self.keyPlistFile = file
let reportsFetcher = ReportsFetcher()
self.searchPartyToken = reportsFetcher.fetchSearchpartyToken()
if let searchPartyToken = self.searchPartyToken {
self.downloadAndDecryptLocations(with: file, searchPartyToken: searchPartyToken)
} else {
self.showTokenPrompt = true
}
}
return true
}
func downloadAndDecryptLocations(with keyFile: Data, searchPartyToken: Data) {
self.loading = true
self.findMyController.loadPrivateKeys(from: keyFile, with: searchPartyToken, completion: { error in
// Check if an error occurred
guard error == nil else {
self.error = error
return
}
// Show map view
self.loading = false
self.showMap = true
})
}
func exportDecryptedLocations() {
do {
let devices = self.findMyController.devices
let deviceData = try PropertyListEncoder().encode(devices)
SavePanel().saveFile(file: deviceData, fileExtension: "plist")
} catch {
print("Error: \(error)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
OFFetchReportsMainView()
}
}

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.get-task-allow</key>
<true/>
<key>com.apple.authkit.client.private</key>
<true/>
<key>com.apple.private.accounts.allaccounts</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
</dict>
</plist>

View File

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,61 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import <Foundation/Foundation.h>
//https://github.com/Matchstic/ReProvision/issues/96#issuecomment-551928795
#import <Security/Security.h>
NS_ASSUME_NONNULL_BEGIN
@interface AKAppleIDSession : NSObject
- (id)_pairedDeviceAnisetteController;
- (id)_nativeAnisetteController;
- (void)_handleURLResponse:(id)arg1 forRequest:(id)arg2 withCompletion:(id)arg3;
- (void)_generateAppleIDHeadersForSessionTask:(id)arg1 withCompletion:(id)arg2;
- (id)_generateAppleIDHeadersForRequest:(id)arg1 error:(id)arg2;
- (id)_genericAppleIDHeadersDictionaryForRequest:(id)arg1;
- (void)handleResponse:(id)arg1 forRequest:(id)arg2 shouldRetry:(char *)arg3;
- (id)appleIDHeadersForRequest:(id)arg1;
- (void)URLSession:(id)arg1 task:(id)arg2 getAppleIDHeadersForResponse:(id)arg3 completionHandler:(id)arg4;
- (id)relevantHTTPStatusCodes;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithIdentifier:(id)arg1;
- (id)init;
@end
@interface AKDevice
+ (AKDevice *)currentDevice;
- (NSString *)uniqueDeviceIdentifier;
- (NSString *)serialNumber;
- (NSString *)serverFriendlyDescription;
@end
@interface ReportsFetcher : NSObject
/// WARNING: Runs synchronous network request. Please run this in a background thread.
/// Query location reports for an array of public key hashes (ids)
/// @param publicKeys Array of hashed public keys (in Base64)
/// @param date Start date
/// @param duration Duration checked
/// @param searchPartyToken Search Party token
/// @param completion Called when finished
- (void) queryForHashes:(NSArray *)publicKeys startDate: (NSDate *) date duration: (double) duration searchPartyToken:(nonnull NSData *)searchPartyToken completion: (void (^)(NSData* _Nullable)) completion;
/// Fetches the search party token from the macOS Keychain. Returns null if it fails
- (NSData * _Nullable) fetchSearchpartyToken;
/// Get AnisetteData from AuthKit or return an empty dictionary
- (NSDictionary *_Nonnull) anisetteDataDictionary;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,179 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "ReportsFetcher.h"
#import <Security/Security.h>
#import <Accounts/Accounts.h>
#if ACCESSORY
#import "OpenHaystack-Swift.h"
#else
#import "OfflineFinder-Swift.h"
#endif
@implementation ReportsFetcher
- (NSData * _Nullable) fetchSearchpartyToken {
NSDictionary *query = @{
(NSString*) kSecClass : (NSString*) kSecClassGenericPassword,
(NSString*) kSecAttrService: @"com.apple.account.AppleAccount.search-party-token",
(NSString*) kSecMatchLimit: (id) kSecMatchLimitOne,
(NSString*) kSecReturnData: @true
};
CFTypeRef item;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, &item);
if (status == errSecSuccess) {
NSData *securityToken = (__bridge NSData *)(item);
NSLog(@"Fetched token %@", [[NSString alloc] initWithData:securityToken encoding:NSUTF8StringEncoding]);
if (securityToken.length == 0) {
return [self fetchSearchpartyTokenFromAccounts];
}
return securityToken;
}
return [self fetchSearchpartyTokenFromAccounts];;
}
- (NSData * _Nullable) fetchSearchpartyTokenFromAccounts {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:@"com.apple.account.AppleAccount"];
NSArray *appleAccounts = [accountStore accountsWithAccountType:accountType];
if (appleAccounts == nil && appleAccounts.count > 0) {return nil;}
ACAccount *iCloudAccount = appleAccounts[0];
ACAccountCredential *iCloudCredentials = iCloudAccount.credential;
if ([iCloudCredentials respondsToSelector:NSSelectorFromString(@"credentialItems")]) {
NSDictionary* credentialItems = [iCloudCredentials performSelector:NSSelectorFromString(@"credentialItems")];
NSString *searchPartyToken = credentialItems[@"search-party-token"];
NSData *tokenData = [searchPartyToken dataUsingEncoding:NSASCIIStringEncoding];
return tokenData;
}
return nil;
}
- (NSString *) fetchAppleAccountId {
NSDictionary *query = @{
(NSString*) kSecClass : (NSString*) kSecClassGenericPassword,
(NSString*) kSecAttrService: @"iCloud",
(NSString*) kSecMatchLimit: (id) kSecMatchLimitOne,
(NSString*) kSecReturnAttributes: @true
};
CFTypeRef item;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, &item);
if (status == errSecSuccess) {
NSDictionary *itemDict = (__bridge NSDictionary *)(item);
NSString *accountId = itemDict[(NSString *) kSecAttrAccount];
return accountId;
}
return nil;
}
- (NSString *) basicAuthForAppleID: (NSString *) appleId andToken: (NSData*) token {
NSString * tokenString = [[NSString alloc] initWithData:token encoding:NSUTF8StringEncoding];
NSString * authText = [NSString stringWithFormat:@"%@:%@", appleId, tokenString];
NSString * base64Auth = [[authText dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSString *auth = [NSString stringWithFormat:@"Basic %@", base64Auth];
return auth;
}
- (NSDictionary *) anisetteDataDictionary {
#if AUTHKIT
NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"https://gateway.icloud.com/acsnservice/fetch"]];
[req setHTTPMethod:@"POST"];
AKAppleIDSession* session = [[NSClassFromString(@"AKAppleIDSession") alloc] initWithIdentifier:@"com.apple.gs.xcode.auth"];
NSDictionary *appleHeadersDict = [session appleIDHeadersForRequest:req];
return appleHeadersDict;
#endif
return [NSDictionary new];
}
- (void) fetchAnisetteData:(void (^)(NSDictionary* _Nullable)) completion {
// Use the AltStore mail plugin
[[AnisetteDataManager shared] requestAnisetteDataObjc:^(NSDictionary * _Nullable dict) {
completion(dict);
}];
}
- (void) queryForHashes:(NSArray *)publicKeys startDate: (NSDate *) date duration: (double) duration searchPartyToken:(nonnull NSData *)searchPartyToken completion: (void (^)(NSData* _Nullable)) completion {
// calculate the timestamps for the defined duration
long long startDate = [date timeIntervalSince1970] * 1000;
long long endDate = ([date timeIntervalSince1970] + duration) * 1000.0;
NSLog(@"Requesting data for %@", publicKeys);
NSDictionary * query = @{
@"search": @[
@{
@"endDate": [NSString stringWithFormat:@"%lli", endDate],
@"ids": publicKeys,
@"startDate": [NSString stringWithFormat:@"%lli", startDate]
}
]
};
NSData *httpBody = [NSJSONSerialization dataWithJSONObject:query options:0 error:nil];
NSLog(@"Query : %@",query);
NSString *authKey = @"authorization";
NSData *securityToken = searchPartyToken;
NSString *appleId = [self fetchAppleAccountId];
NSString *authValue = [self basicAuthForAppleID:appleId andToken:securityToken];
[self fetchAnisetteData:^(NSDictionary * _Nullable dict) {
if (dict == nil) {
completion(nil);
return;
}
NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"https://gateway.icloud.com/acsnservice/fetch"]];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:authValue forHTTPHeaderField:authKey];
NSDictionary *appleHeadersDict = dict;
for(id key in appleHeadersDict)
[req setValue:[appleHeadersDict objectForKey:key] forHTTPHeaderField:key];
NSLog(@"Headers:\n%@",req.allHTTPHeaderFields);
[req setHTTPBody:httpBody];
NSURLResponse * response;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error) {
NSLog(@"Error during request: \n\n%@", error);
}
completion(data);
}];
}
@end

View File

@@ -0,0 +1,48 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import Foundation
import AppKit
class SavePanel: NSObject, NSOpenSavePanelDelegate {
static let shared = SavePanel()
var fileToSave: Data?
var fileExtension: String?
var panel: NSSavePanel?
func saveFile(file: Data, fileExtension: String) {
self.fileToSave = file
self.fileExtension = fileExtension
self.panel = NSSavePanel()
self.panel?.delegate = self
self.panel?.title = "Export Find My Locations"
self.panel?.prompt = "Export"
self.panel?.nameFieldLabel = "Find My Locations"
self.panel?.nameFieldStringValue = "findMyLocations.plist"
self.panel?.allowedFileTypes = ["plist"]
let result = self.panel?.runModal()
if result == NSApplication.ModalResponse.OK {
// Save file
let fileURL = self.panel?.url
// swiftlint:disable force_try
try! self.fileToSave?.write(to: fileURL!)
}
}
func panel(_ sender: Any, userEnteredFilename filename: String, confirmed okFlag: Bool) -> String? {
guard okFlag else {return nil}
return filename
}
}

View File

@@ -0,0 +1,47 @@
// ALTAnisetteData.h
// AltSign
//
// Created by Riley Testut on 11/13/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ALTAnisetteData : NSObject <NSCopying, NSSecureCoding>
@property (nonatomic, copy) NSString *machineID;
@property (nonatomic, copy) NSString *oneTimePassword;
@property (nonatomic, copy) NSString *localUserID;
@property (nonatomic) unsigned long long routingInfo;
@property (nonatomic, copy) NSString *deviceUniqueIdentifier;
@property (nonatomic, copy) NSString *deviceSerialNumber;
@property (nonatomic, copy) NSString *deviceDescription;
@property (nonatomic, copy) NSDate *date;
@property (nonatomic, copy) NSLocale *locale;
@property (nonatomic, copy) NSTimeZone *timeZone;
- (instancetype)initWithMachineID:(NSString *)machineID
oneTimePassword:(NSString *)oneTimePassword
localUserID:(NSString *)localUserID
routingInfo:(unsigned long long)routingInfo
deviceUniqueIdentifier:(NSString *)deviceUniqueIdentifier
deviceSerialNumber:(NSString *)deviceSerialNumber
deviceDescription:(NSString *)deviceDescription
date:(NSDate *)date
locale:(NSLocale *)locale
timeZone:(NSTimeZone *)timeZone;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,158 @@
// ALTAnisetteData.m
// AltSign
//
// Created by Riley Testut on 11/13/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "ALTAnisetteData.h"
@implementation ALTAnisetteData
- (instancetype)initWithMachineID:(NSString *)machineID oneTimePassword:(NSString *)oneTimePassword localUserID:(NSString *)localUserID routingInfo:(unsigned long long)routingInfo deviceUniqueIdentifier:(NSString *)deviceUniqueIdentifier deviceSerialNumber:(NSString *)deviceSerialNumber deviceDescription:(NSString *)deviceDescription date:(NSDate *)date locale:(NSLocale *)locale timeZone:(NSTimeZone *)timeZone {
self = [super init];
if (self)
{
_machineID = [machineID copy];
_oneTimePassword = [oneTimePassword copy];
_localUserID = [localUserID copy];
_routingInfo = routingInfo;
_deviceUniqueIdentifier = [deviceUniqueIdentifier copy];
_deviceSerialNumber = [deviceSerialNumber copy];
_deviceDescription = [deviceDescription copy];
_date = [date copy];
_locale = [locale copy];
_timeZone = [timeZone copy];
}
return self;
}
#pragma mark - NSObject -
- (NSString *)description
{
return [NSString stringWithFormat:@"Machine ID: %@\nOne-Time Password: %@\nLocal User ID: %@\nRouting Info: %@\nDevice UDID: %@\nDevice Serial Number: %@\nDevice Description: %@\nDate: %@\nLocale: %@\nTime Zone: %@ Search Party token %@",
self.machineID, self.oneTimePassword, self.localUserID, @(self.routingInfo), self.deviceUniqueIdentifier, self.deviceSerialNumber, self.deviceDescription, self.date, self.locale.localeIdentifier, self.timeZone];
}
- (BOOL)isEqual:(id)object
{
ALTAnisetteData *anisetteData = (ALTAnisetteData *)object;
if (![anisetteData isKindOfClass:[ALTAnisetteData class]])
{
return NO;
}
BOOL isEqual = ([self.machineID isEqualToString:anisetteData.machineID] &&
[self.oneTimePassword isEqualToString:anisetteData.oneTimePassword] &&
[self.localUserID isEqualToString:anisetteData.localUserID] &&
[@(self.routingInfo) isEqualToNumber:@(anisetteData.routingInfo)] &&
[self.deviceUniqueIdentifier isEqualToString:anisetteData.deviceUniqueIdentifier] &&
[self.deviceSerialNumber isEqualToString:anisetteData.deviceSerialNumber] &&
[self.deviceDescription isEqualToString:anisetteData.deviceDescription] &&
[self.date isEqualToDate:anisetteData.date] &&
[self.locale isEqual:anisetteData.locale] &&
[self.timeZone isEqualToTimeZone:anisetteData.timeZone]);
return isEqual;
}
- (NSUInteger)hash
{
return (self.machineID.hash ^
self.oneTimePassword.hash ^
self.localUserID.hash ^
@(self.routingInfo).hash ^
self.deviceUniqueIdentifier.hash ^
self.deviceSerialNumber.hash ^
self.deviceDescription.hash ^
self.date.hash ^
self.locale.hash ^
self.timeZone.hash);
;
}
#pragma mark - <NSCopying> -
- (nonnull id)copyWithZone:(nullable NSZone *)zone
{
ALTAnisetteData *copy = [[ALTAnisetteData alloc] initWithMachineID:self.machineID
oneTimePassword:self.oneTimePassword
localUserID:self.localUserID
routingInfo:self.routingInfo
deviceUniqueIdentifier:self.deviceUniqueIdentifier
deviceSerialNumber:self.deviceSerialNumber
deviceDescription:self.deviceDescription
date:self.date
locale:self.locale
timeZone:self.timeZone];
return copy;
}
#pragma mark - <NSSecureCoding> -
- (instancetype)initWithCoder:(NSCoder *)decoder
{
NSString *machineID = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(machineID))];
NSString *oneTimePassword = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(oneTimePassword))];
NSString *localUserID = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(localUserID))];
NSNumber *routingInfo = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(routingInfo))];
NSString *deviceUniqueIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceUniqueIdentifier))];
NSString *deviceSerialNumber = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceSerialNumber))];
NSString *deviceDescription = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceDescription))];
NSDate *date = [decoder decodeObjectOfClass:[NSDate class] forKey:NSStringFromSelector(@selector(date))];
NSLocale *locale = [decoder decodeObjectOfClass:[NSLocale class] forKey:NSStringFromSelector(@selector(locale))];
NSTimeZone *timeZone = [decoder decodeObjectOfClass:[NSTimeZone class] forKey:NSStringFromSelector(@selector(timeZone))];
self = [self initWithMachineID:machineID
oneTimePassword:oneTimePassword
localUserID:localUserID
routingInfo:[routingInfo unsignedLongLongValue]
deviceUniqueIdentifier:deviceUniqueIdentifier
deviceSerialNumber:deviceSerialNumber
deviceDescription:deviceDescription
date:date
locale:locale
timeZone:timeZone
];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.machineID forKey:NSStringFromSelector(@selector(machineID))];
[encoder encodeObject:self.oneTimePassword forKey:NSStringFromSelector(@selector(oneTimePassword))];
[encoder encodeObject:self.localUserID forKey:NSStringFromSelector(@selector(localUserID))];
[encoder encodeObject:@(self.routingInfo) forKey:NSStringFromSelector(@selector(routingInfo))];
[encoder encodeObject:self.deviceUniqueIdentifier forKey:NSStringFromSelector(@selector(deviceUniqueIdentifier))];
[encoder encodeObject:self.deviceSerialNumber forKey:NSStringFromSelector(@selector(deviceSerialNumber))];
[encoder encodeObject:self.deviceDescription forKey:NSStringFromSelector(@selector(deviceDescription))];
[encoder encodeObject:self.date forKey:NSStringFromSelector(@selector(date))];
[encoder encodeObject:self.locale forKey:NSStringFromSelector(@selector(locale))];
[encoder encodeObject:self.timeZone forKey:NSStringFromSelector(@selector(timeZone))];
}
+ (BOOL)supportsSecureCoding
{
return YES;
}
@end

View File

@@ -0,0 +1,52 @@
// AppleAccountData.h
// AltSign
//
// Created by Riley Testut on 11/13/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import <Foundation/Foundation.h>
#import "ALTAnisetteData.h"
NS_ASSUME_NONNULL_BEGIN
@interface AppleAccountData : NSObject <NSCopying, NSSecureCoding>
@property (nonatomic, copy) NSString *machineID;
@property (nonatomic, copy) NSString *oneTimePassword;
@property (nonatomic, copy) NSString *localUserID;
@property (nonatomic) unsigned long long routingInfo;
@property (nonatomic, copy) NSString *deviceUniqueIdentifier;
@property (nonatomic, copy) NSString *deviceSerialNumber;
@property (nonatomic, copy) NSString *deviceDescription;
@property (nonatomic, copy) NSDate *date;
@property (nonatomic, copy) NSLocale *locale;
@property (nonatomic, copy) NSTimeZone *timeZone;
@property (nonatomic, copy) NSData *searchPartyToken;
- (instancetype)initWithMachineID:(NSString *)machineID
oneTimePassword:(NSString *)oneTimePassword
localUserID:(NSString *)localUserID
routingInfo:(unsigned long long)routingInfo
deviceUniqueIdentifier:(NSString *)deviceUniqueIdentifier
deviceSerialNumber:(NSString *)deviceSerialNumber
deviceDescription:(NSString *)deviceDescription
date:(NSDate *)date
locale:(NSLocale *)locale
timeZone:(NSTimeZone *)timeZone;
- (instancetype) initFromALTAnissetteData:(ALTAnisetteData *) altAnisetteData;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,186 @@
// AppleAccountData.m
// AltSign
//
// Created by Riley Testut on 11/13/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "AppleAccountData.h"
#import "ALTAnisetteData.h"
@implementation AppleAccountData
- (instancetype)initWithMachineID:(NSString *)machineID oneTimePassword:(NSString *)oneTimePassword localUserID:(NSString *)localUserID routingInfo:(unsigned long long)routingInfo deviceUniqueIdentifier:(NSString *)deviceUniqueIdentifier deviceSerialNumber:(NSString *)deviceSerialNumber deviceDescription:(NSString *)deviceDescription date:(NSDate *)date locale:(NSLocale *)locale timeZone:(NSTimeZone *)timeZone {
self = [super init];
if (self)
{
_machineID = [machineID copy];
_oneTimePassword = [oneTimePassword copy];
_localUserID = [localUserID copy];
_routingInfo = routingInfo;
_deviceUniqueIdentifier = [deviceUniqueIdentifier copy];
_deviceSerialNumber = [deviceSerialNumber copy];
_deviceDescription = [deviceDescription copy];
_date = [date copy];
_locale = [locale copy];
_timeZone = [timeZone copy];
_searchPartyToken = nil;
}
return self;
}
- (instancetype) initFromALTAnissetteData:(ALTAnisetteData *) altAnisetteData {
self = [super init];
if (self) {
_machineID = [altAnisetteData.machineID copy];
_oneTimePassword = [altAnisetteData.oneTimePassword copy];
_localUserID = [altAnisetteData.localUserID copy];
_routingInfo = altAnisetteData.routingInfo;
_deviceUniqueIdentifier = [altAnisetteData.deviceUniqueIdentifier copy];
_deviceSerialNumber = [altAnisetteData.deviceSerialNumber copy];
_deviceDescription = [altAnisetteData.deviceDescription copy];
_date = [altAnisetteData.date copy];
_locale = [altAnisetteData.locale copy];
_timeZone = [altAnisetteData.timeZone copy];
_searchPartyToken = nil;
}
return self;
}
#pragma mark - NSObject -
- (NSString *)description
{
return [NSString stringWithFormat:@"Machine ID: %@\nOne-Time Password: %@\nLocal User ID: %@\nRouting Info: %@\nDevice UDID: %@\nDevice Serial Number: %@\nDevice Description: %@\nDate: %@\nLocale: %@\nTime Zone: %@ Search Party token %@",
self.machineID, self.oneTimePassword, self.localUserID, @(self.routingInfo), self.deviceUniqueIdentifier, self.deviceSerialNumber, self.deviceDescription, self.date, self.locale.localeIdentifier, self.timeZone, self.searchPartyToken];
}
- (BOOL)isEqual:(id)object
{
AppleAccountData *anisetteData = (AppleAccountData *)object;
if (![anisetteData isKindOfClass:[AppleAccountData class]])
{
return NO;
}
BOOL isEqual = ([self.machineID isEqualToString:anisetteData.machineID] &&
[self.oneTimePassword isEqualToString:anisetteData.oneTimePassword] &&
[self.localUserID isEqualToString:anisetteData.localUserID] &&
[@(self.routingInfo) isEqualToNumber:@(anisetteData.routingInfo)] &&
[self.deviceUniqueIdentifier isEqualToString:anisetteData.deviceUniqueIdentifier] &&
[self.deviceSerialNumber isEqualToString:anisetteData.deviceSerialNumber] &&
[self.deviceDescription isEqualToString:anisetteData.deviceDescription] &&
[self.date isEqualToDate:anisetteData.date] &&
[self.locale isEqual:anisetteData.locale] &&
[self.timeZone isEqualToTimeZone:anisetteData.timeZone]);
return isEqual;
}
- (NSUInteger)hash
{
return (self.machineID.hash ^
self.oneTimePassword.hash ^
self.localUserID.hash ^
@(self.routingInfo).hash ^
self.deviceUniqueIdentifier.hash ^
self.deviceSerialNumber.hash ^
self.deviceDescription.hash ^
self.date.hash ^
self.locale.hash ^
self.searchPartyToken.hash ^
self.timeZone.hash);
;
}
#pragma mark - <NSCopying> -
- (nonnull id)copyWithZone:(nullable NSZone *)zone
{
AppleAccountData *copy = [[AppleAccountData alloc] initWithMachineID:self.machineID
oneTimePassword:self.oneTimePassword
localUserID:self.localUserID
routingInfo:self.routingInfo
deviceUniqueIdentifier:self.deviceUniqueIdentifier
deviceSerialNumber:self.deviceSerialNumber
deviceDescription:self.deviceDescription
date:self.date
locale:self.locale
timeZone:self.timeZone];
return copy;
}
#pragma mark - <NSSecureCoding> -
- (instancetype)initWithCoder:(NSCoder *)decoder
{
NSString *machineID = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(machineID))];
NSString *oneTimePassword = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(oneTimePassword))];
NSString *localUserID = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(localUserID))];
NSNumber *routingInfo = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(routingInfo))];
NSString *deviceUniqueIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceUniqueIdentifier))];
NSString *deviceSerialNumber = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceSerialNumber))];
NSString *deviceDescription = [decoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(deviceDescription))];
NSDate *date = [decoder decodeObjectOfClass:[NSDate class] forKey:NSStringFromSelector(@selector(date))];
NSLocale *locale = [decoder decodeObjectOfClass:[NSLocale class] forKey:NSStringFromSelector(@selector(locale))];
NSTimeZone *timeZone = [decoder decodeObjectOfClass:[NSTimeZone class] forKey:NSStringFromSelector(@selector(timeZone))];
NSData *searchPartyToken = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(searchPartyToken))];
self = [self initWithMachineID:machineID
oneTimePassword:oneTimePassword
localUserID:localUserID
routingInfo:[routingInfo unsignedLongLongValue]
deviceUniqueIdentifier:deviceUniqueIdentifier
deviceSerialNumber:deviceSerialNumber
deviceDescription:deviceDescription
date:date
locale:locale
timeZone:timeZone
];
self.searchPartyToken = searchPartyToken;
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.machineID forKey:NSStringFromSelector(@selector(machineID))];
[encoder encodeObject:self.oneTimePassword forKey:NSStringFromSelector(@selector(oneTimePassword))];
[encoder encodeObject:self.localUserID forKey:NSStringFromSelector(@selector(localUserID))];
[encoder encodeObject:@(self.routingInfo) forKey:NSStringFromSelector(@selector(routingInfo))];
[encoder encodeObject:self.deviceUniqueIdentifier forKey:NSStringFromSelector(@selector(deviceUniqueIdentifier))];
[encoder encodeObject:self.deviceSerialNumber forKey:NSStringFromSelector(@selector(deviceSerialNumber))];
[encoder encodeObject:self.deviceDescription forKey:NSStringFromSelector(@selector(deviceDescription))];
[encoder encodeObject:self.date forKey:NSStringFromSelector(@selector(date))];
[encoder encodeObject:self.locale forKey:NSStringFromSelector(@selector(locale))];
[encoder encodeObject:self.timeZone forKey:NSStringFromSelector(@selector(timeZone))];
[encoder encodeObject:self.searchPartyToken forKey:NSStringFromSelector(@selector(searchPartyToken))];
}
+ (BOOL)supportsSecureCoding
{
return YES;
}
@end

View File

@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2021 SEEMOO TU Darmstadt</string>
<key>NSPrincipalClass</key>
<string>OpenHaystackPluginService</string>
<key>Supported10.15PluginCompatibilityUUIDs</key>
<array>
<string># UUIDs for versions from 10.12 to 99.99.99</string>
<string># For mail version 10.0 (3226) on OS X Version 10.12 (build 16A319)</string>
<string>36CCB8BB-2207-455E-89BC-B9D6E47ABB5B</string>
<string># For mail version 10.1 (3251) on OS X Version 10.12.1 (build 16B2553a)</string>
<string>9054AFD9-2607-489E-8E63-8B09A749BC61</string>
<string># For mail version 10.2 (3259) on OS X Version 10.12.2 (build 16D12b)</string>
<string>1CD3B36A-0E3B-4A26-8F7E-5BDF96AAC97E</string>
<string># For mail version 10.3 (3273) on OS X Version 10.12.4 (build 16G1036)</string>
<string>21560BD9-A3CC-482E-9B99-95B7BF61EDC1</string>
<string># For mail version 11.0 (3441.0.1) on OS X Version 10.13 (build 17A315i)</string>
<string>C86CD990-4660-4E36-8CDA-7454DEB2E199</string>
<string># For mail version 12.0 (3445.100.39) on OS X Version 10.14.1 (build 18B45d)</string>
<string>A4343FAF-AE18-40D0-8A16-DFAE481AF9C1</string>
<string># For mail version 13.0 (3594.4.2) on OS X Version 10.15 (build 19A558d)</string>
<string>6EEA38FB-1A0B-469B-BB35-4C2E0EEA9053</string>
</array>
<key>Supported11.0PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.1PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.2PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.3PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
<key>Supported11.4PluginCompatibilityUUIDs</key>
<array>
<string>D985F0E4-3BBC-4B95-BBA1-12056AC4A531</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,24 @@
// ALTPluginService.h
// AltPlugin
//
// Created by Riley Testut on 11/14/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface OpenHaystackPluginService : NSObject
+ (instancetype)sharedService;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,131 @@
// ALTPluginService.m
// AltPlugin
//
// Created by Riley Testut on 11/14/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
#import "OpenHaystackPluginService.h"
#import <dlfcn.h>
#import "AppleAccountData.h"
#import <Security/Security.h>
#import <Accounts/Accounts.h>
@import AppKit;
@interface AKAppleIDSession : NSObject
- (id)appleIDHeadersForRequest:(id)arg1;
@end
@interface AKDevice
+ (AKDevice *)currentDevice;
- (NSString *)uniqueDeviceIdentifier;
- (NSString *)serialNumber;
- (NSString *)serverFriendlyDescription;
@end
@interface OpenHaystackPluginService ()
@property (nonatomic, readonly) NSISO8601DateFormatter *dateFormatter;
@end
@implementation OpenHaystackPluginService
+ (instancetype)sharedService
{
static OpenHaystackPluginService *_service = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_service = [[self alloc] init];
});
return _service;
}
- (instancetype)init
{
self = [super init];
if (self)
{
_dateFormatter = [[NSISO8601DateFormatter alloc] init];
}
return self;
}
+ (void)initialize
{
[[OpenHaystackPluginService sharedService] start];
}
- (void)start
{
dlopen("/System/Library/PrivateFrameworks/AuthKit.framework/AuthKit", RTLD_NOW);
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"de.tu-darmstadt.seemoo.OpenHaystack.FetchAnisetteData" object:nil];
}
- (void)receiveNotification:(NSNotification *)notification
{
NSString *requestUUID = notification.userInfo[@"requestUUID"];
NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"https://developerservices2.apple.com/services/QH65B2/listTeams.action?clientId=XABBG36SBA"]];
[req setHTTPMethod:@"POST"];
AKAppleIDSession *session = [[NSClassFromString(@"AKAppleIDSession") alloc] initWithIdentifier:@"com.apple.gs.xcode.auth"];
NSDictionary *headers = [session appleIDHeadersForRequest:req];
AKDevice *device = [NSClassFromString(@"AKDevice") currentDevice];
NSDate *date = [self.dateFormatter dateFromString:headers[@"X-Apple-I-Client-Time"]];
NSData *sptoken = [self fetchSearchpartyToken];
AppleAccountData *anisetteData = [[NSClassFromString(@"AppleAccountData") alloc] initWithMachineID:headers[@"X-Apple-I-MD-M"]
oneTimePassword:headers[@"X-Apple-I-MD"]
localUserID:headers[@"X-Apple-I-MD-LU"]
routingInfo:[headers[@"X-Apple-I-MD-RINFO"] longLongValue]
deviceUniqueIdentifier:device.uniqueDeviceIdentifier
deviceSerialNumber:device.serialNumber
deviceDescription:device.serverFriendlyDescription
date:date
locale:[NSLocale currentLocale]
timeZone:[NSTimeZone localTimeZone]];
if (sptoken != nil) {
anisetteData.searchPartyToken = [sptoken copy];
}
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:anisetteData requiringSecureCoding:YES error:nil];
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"de.tu-darmstadt.seemoo.OpenHaystack.AnisetteDataResponse" object:nil userInfo:@{@"requestUUID": requestUUID, @"anisetteData": data} deliverImmediately:YES];
}
- (NSData * _Nullable) fetchSearchpartyToken {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:@"com.apple.account.AppleAccount"];
NSArray *appleAccounts = [accountStore accountsWithAccountType:accountType];
if (appleAccounts == nil && appleAccounts.count > 0) {return nil;}
ACAccount *iCloudAccount = appleAccounts[0];
ACAccountCredential *iCloudCredentials = iCloudAccount.credential;
if ([iCloudCredentials respondsToSelector:NSSelectorFromString(@"credentialItems")]) {
NSDictionary* credentialItems = [iCloudCredentials performSelector:NSSelectorFromString(@"credentialItems")];
NSString *searchPartyToken = credentialItems[@"search-party-token"];
NSData *tokenData = [searchPartyToken dataUsingEncoding:NSASCIIStringEncoding];
return tokenData;
}
return nil;
}
@end

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@@ -0,0 +1,239 @@
// OpenHaystack Tracking personal Bluetooth devices via Apple's Find My network
//
// Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
// Copyright © 2021 The Open Wireless Link Project
//
// SPDX-License-Identifier: AGPL-3.0-only
import XCTest
import CryptoKit
@testable import OpenHaystack
class OpenHaystackTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
measure {
// Put the code you want to measure the time of here.
}
}
func testAnisetteDataFromAltStore() throws {
let manager = AnisetteDataManager.shared
let expect = self.expectation(description: "Anisette data fetched")
manager.requestAnisetteData { result in
switch result {
case .failure(let error):
XCTFail(String(describing: error))
case .success(let data):
print("Accessed anisette data \(data.description)")
}
expect.fulfill()
}
self.wait(for: [expect], timeout: 3.0)
}
func testKeyGeneration() throws {
let key = BoringSSL.generateNewPrivateKey()!
XCTAssertNotEqual(key, Data(repeating: 0, count: 28))
}
func testDerivePublicKey() throws {
let privateKey = BoringSSL.generateNewPrivateKey()!
let publicKeyBytes = BoringSSL.derivePublicKey(fromPrivateKey: privateKey)
XCTAssertNotNil(publicKeyBytes)
}
func testGetPublicKey() throws {
let accessory = try Accessory(name: "Some item")
let publicKey = try accessory.getAdvertisementKey()
XCTAssertEqual(publicKey.count, 28)
XCTAssertNotEqual(publicKey, Data(repeating: 0, count: 28))
XCTAssertNotEqual(publicKey, accessory.privateKey)
}
func testStoreAccessories() throws {
let accessory = try Accessory(name: "Test accessory")
try KeychainController.storeInKeychain(accessories: [accessory], test: true)
let fetchedAccessories = KeychainController.loadAccessoriesFromKeychain(test: true)
XCTAssertEqual(accessory, fetchedAccessories[0])
// Add an accessory
let updatedAccessories = fetchedAccessories + [try Accessory(name: "Test 2")]
try KeychainController.storeInKeychain(accessories: updatedAccessories, test: true)
let fetchedAccessories2 = KeychainController.loadAccessoriesFromKeychain(test: true)
XCTAssertEqual(updatedAccessories, fetchedAccessories2)
// Remove the accessories
try KeychainController.storeInKeychain(accessories: [], test: true)
}
func testMicrobitDeploy() throws {
let urls = try MicrobitController.findMicrobits()
if let mBitURL = urls.first {
let firmware = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "sample", withExtension: "bin")!)
try MicrobitController.deployToMicrobit(mBitURL, firmwareFile: firmware)
}
}
func testBinaryPatching() throws {
// Patching sample.bin should fail
do {
let firmware = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "sample", withExtension: "bin")!)
let pattern = Data([0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x1])
let key = Data([1, 1, 1, 1, 1, 1, 1, 1])
_ = try MicrobitController.patchFirmware(firmware, pattern: pattern, with: key)
XCTFail("Should thrown an erorr before")
} catch PatchingError.patternNotFound {
// This should be thrown
} catch {
XCTFail("Unexpected error")
}
// Patching the sample should be successful
do {
let firmware = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "pattern_sample", withExtension: "bin")!)
let pattern = Data([0xaa, 0xaa, 0xaa, 0xaa, 0xbb, 0xbb, 0xbb, 0xcc])
let key = Data([1, 1, 1, 1, 1, 1, 1, 1])
_ = try MicrobitController.patchFirmware(firmware, pattern: pattern, with: key)
} catch {
XCTFail("Unexpected error \(String(describing: error))")
}
// Patching key too short
// Patching the sample should be successful
do {
let firmware = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "pattern_sample", withExtension: "bin")!)
let pattern = Data([0xaa, 0xaa, 0xaa, 0xaa, 0xbb, 0xbb, 0xbb, 0xcc])
let key = Data([1, 1, 1, 1, 1, 1, 1])
_ = try MicrobitController.patchFirmware(firmware, pattern: pattern, with: key)
} catch PatchingError.inequalLength {
} catch {
XCTFail("Unexpected error \(String(describing: error))")
}
// Testing with the actual firmware
do {
let firmware = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "offline-finding", withExtension: "bin")!)
let pattern = "OFFLINEFINDINGPUBLICKEYHERE!".data(using: .ascii)!
let key = Data(repeating: 0xaa, count: 28)
_ = try MicrobitController.patchFirmware(firmware, pattern: pattern, with: key)
} catch PatchingError.inequalLength {
} catch {
XCTFail("Unexpected error \(String(describing: error))")
}
}
func testKeyIDGeneration() throws {
// Import keys with their respective id from a plist
let plist = try Data(contentsOf: Bundle(for: Self.self).url(forResource: "sampleKeys", withExtension: "plist")!)
let devices = try PropertyListDecoder().decode([FindMyDevice].self, from: plist)
let keys = devices.first!.keys
for key in keys {
let publicKey = key.advertisedKey
var sha = SHA256()
sha.update(data: publicKey)
let digest = sha.finalize()
let hashedKey = Data(digest)
XCTAssertEqual(key.hashedKey, hashedKey)
}
}
func testECDHWithPublicKey() throws {
let receivedAccessory = try Accessory(name: "test")
let receivedPublicKey = try receivedAccessory.getActualPublicKey()
// Generate ephemeral key pair by using a second accessory
let ephAccessory = try Accessory(name: "Ephemeral Key")
let ephPrivate = ephAccessory.privateKey
let ephPublicKey = try ephAccessory.getActualPublicKey()
// Now we need a ECDH key exchange
// In the first round ephemeral key is the public key
let sharedKey = BoringSSL.deriveSharedKey(fromPrivateKey: ephPrivate, andEphemeralKey: receivedPublicKey)!
XCTAssertNotNil(sharedKey)
// Now we follow the standard key derivation used in OF
let derivedKey = DecryptReports.kdf(fromSharedSecret: sharedKey, andEphemeralKey: ephPublicKey )
// Let's encrypt some test string
let message = "This is a message that should be encrypted"
let messageData = message.data(using: .ascii)!
let encryptionKey = derivedKey.subdata(in: derivedKey.startIndex..<16)
let encryptionIV = derivedKey.subdata(in: 16..<derivedKey.endIndex)
let sealed = try AES.GCM.seal(messageData, using: SymmetricKey(data: encryptionKey), nonce: .init(data: encryptionIV))
// Now we decrypt it by performing it the other way around
// ECDH with public ephemeral and private received key
let sharedKey2 = BoringSSL.deriveSharedKey(fromPrivateKey: receivedAccessory.privateKey, andEphemeralKey: ephPublicKey)!
XCTAssertNotNil(sharedKey2)
XCTAssertEqual(sharedKey2, sharedKey)
// Decrypt to see if we get the same text
let derivedKey2 = DecryptReports.kdf(fromSharedSecret: sharedKey2, andEphemeralKey: ephPublicKey)
XCTAssertEqual(derivedKey2, derivedKey)
let decryptionKey = derivedKey2.subdata(in: derivedKey2.startIndex..<16)
let decryptionIV = derivedKey2.subdata(in: 16..<derivedKey2.endIndex)
XCTAssertEqual(decryptionIV, encryptionIV)
XCTAssertEqual(decryptionKey, encryptionKey)
let decryptedMessage = try AES.GCM.open(sealed, using: SymmetricKey(data: decryptionKey))
XCTAssertEqual(decryptedMessage, messageData)
let decryptedText = String(data: decryptedMessage, encoding: .ascii)
XCTAssertEqual(message, decryptedText)
}
func testGenerateKeyPair() {
let keyData = BoringSSL.generateNewPrivateKey()
XCTAssertNotNil(keyData)
}
func testPluginInstallation() {
do {
let pluginManager = MailPluginManager()
if pluginManager.isMailPluginInstalled {
try pluginManager.uninstallMailPlugin()
}
try pluginManager.installMailPlugin()
XCTAssert(FileManager.default.fileExists(atPath: pluginManager.pluginURL.path))
} catch {
XCTFail(String(describing: error))
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,14 @@
#bin/sh
identities=$(security find-identity -p codesigning -v)
#echo "${identities}"
pat=' ([0-9ABCDEF]+) '
[[ $identities =~ $pat ]]
# Can be set to a codesign identity manually
IDT="${BASH_REMATCH[1]}"
if [ -z ${IDT+x} ]; then
echo error: "error: Please set the codesigning identity above. \nThe identity can be found with $ security find-identities -v -p codesigning"
else
codesign --entitlements ${SRCROOT}/OpenHaystack/OfflineFinder.entitlements -fs ${IDT} ${TARGET_BUILD_DIR}/OfflineFinder.app/Contents/MacOS/OfflineFinder
fi

121
README.md Normal file
View File

@@ -0,0 +1,121 @@
# <img src="Resources/Icon/OpenHaystackIcon.png" alt="OpenHaystack application icon" height=42 width=42 valign=bottom /> OpenHaystack
OpenHaystack is a framework for tracking personal Bluetooth devices via Apple's massive Find My network. Use it to create your own tracking _tags_ that you can append to physical objects (keyrings, backpacks, ...) or integrate it into other Bluetooth-capable devices such as notebooks.
![Screenshot of the app](Resources/OpenHaystack-Screenshot.png)
## Table of contents
- [What is _OpenHaystack_?](#what-is-openhaystack)
- [History](#history)
- [Disclaimer](#disclaimer)
- [How to use _OpenHaystack_?](#how-to-use-openhaystack)
- [System requirements](#system-requirements)
- [Installation](#installation)
- [Usage](#usage)
- [How does Apple's Find My network work?](#how-does-apples-find-my-network-work)
- [Pairing](#pairing-1)
- [Loosing](#loosing-2)
- [Finding](#finding-3)
- [Searching](#searching-4)
- [How to track other Bluetooth devices?](#how-to-track-other-bluetooth-devices)
- [Authors](#authors)
- [References](#references)
- [License](#license)
## What is _OpenHaystack_?
OpenHaystack is an application that allows you to create your own tags that are tracked by Apple's [Find My network](#how-does-apples-find-my-network-work). All you need is a Mac and a [BBC micro:bit](https://microbit.org/) or any [other Bluetooth-capable device](#how-to-track-other-bluetooth-devices).
By using the app, you can track your micro:bit tag anywhere on earth without cellular coverage. Nearby iPhones will discover your tag and upload their location to Apple's servers when they have a network connection.
### History
OpenHaystack is the result of reverse-engineering and security analysis work of Apple's _Find My network_ (or _offline finding_). We at the [Secure Mobile Networking Lab](https://seemoo.de) of TU Darmstadt started analyzing offline finding after its initial announcement in June 2019. We identified how Apple devices can be found by iPhones devices, even when they are offline through this work. The whole system is a clever combination of Bluetooth advertisements, public-key cryptography, and a central database of encrypted location reports. We disclosed a specification of the closed parts of offline finding and conducted a comprehensive security and privacy analysis.
We found two distinct vulnerabilities. The most severe one, which allowed a malicious application to access location data, has meanwhile been fixed by Apple ([CVE-2020-9986](https://support.apple.com/en-us/HT211849)).
For more information about the security analysis, please read [our paper](#references).
### Disclaimer
OpenHaystack is experimental software. The code is untested and incomplete. For example, OpenHaystack tags using our [firmware](Firmware) broadcast a fixed public key and, therefore, are trackable by other devices in proximity (this might change in a future release). OpenHaystack is not affiliated with or endorsed by Apple Inc.
## How to use _OpenHaystack_?
OpenHaystack consists of two components. First, we provide a [macOS application](OpenHaystack) that can display the last reported location of your personal Bluetooth devices. Second, the [firmware image](Firmware) enables Bluetooth devices to broadcast beacons that make them discoverable by iPhones.
### System requirements
OpenHaystack requires macOS 11 (Big Sur).
### Installation
The OpenHaystack application requires a custom plugin for Apple Mail. It is used to download location reports from Apple's servers via a private API (technical explanation: the plugin inherits Apple Mail's entitlements required to use this API).
Therefore, the installation procedure is slightly different and requires you to temporarily disable [Gatekeeper](https://support.apple.com/guide/security/gatekeeper-and-runtime-protection-sec5599b66df/1/web/1).
Our plugin does not access any other private data such as emails (see [source code](OpenHaystack/OpenHaystackMail)).
1. Download a precompiled binary release from our <a href="https://github.com/seemoo-lab/openhaystack/releases">GitHub page</a>.
_Alternative:_ build the application from source via Xcode.
2. Open OpenHaystack. This will ask you to install the Mail plugin in `~/Library/Mail/Bundle`.
3. Open a terminal and run `sudo spctl --master-disable`, which will disable Gatekeeper and allow our Apple Mail plugin to run.
4. Open Apple Mail. Go to _Preferences__General__Manage Plug-Ins..._ and activate the checkbox next to _OpenHaystackMail.mailbundle_.
5. Allow access and restart Mail.
6. Open a terminal and enter `sudo spctl --master-enable`, which will enable Gatekeeper again prevent any other
### Usage
**Adding a new tag.**
To create a new tag, you just need to enter a name for it and optionally select a suitable icon and a color. The app then generates a new key pair that is used to encrypt and decrypt the location reports. The private key is stored in your Mac's keychain.
Upon deploying, the app will try to flash our firmware image with the new public key to a USB-connected [BBC micro:bit v1](https://microbit.org/).
However, you may also copy the public key used for advertising and deploy it via some other mechanism.
**Display devices' locations.**
It can take up to 30 minutes until you will see the first location report on the map on the right side. The map will always show all your items' most recent locations. You can click on every item to check when the last update was received.
By clicking the reload button, you can update the location reports.
## How does Apple's Find My network work?
We briefly explain Apple's offline finding system (aka [_Find My network_](https://developer.apple.com/find-my/)). Please refer to our [PETS paper and Apple's accessory specification](#references) for more details. We provide a schematic overview (from our paper) and explain how we integrate the different steps in OpenHaystack below.
![Find My Overview](Resources/FindMyOverview.png)
### Pairing (1)
To use Apple's Find My network, we generate a public-private key pair on an elliptic curve (P-224). The private key remains on the Mac securely stored in the keychain, and the public key will be deployed on the tag, e.g., an attached micro:bit.
### Loosing (2)
In short, the tags broadcast the public key as Bluetooth Low Energy (BLE) advertisements (see [firmware](Firmware).
Nearby iPhones will not be able to distinguish our tags from a genuine Apple device or certified accessory.
### Finding (3)
When a nearby iPhone receives a BLE advertisement, the iPhone fetches its current location via GPS, encrypts it using public key from the advertisement, and uploads the encrypted report to Apple's server.
All iPhones on iOS 13 or newer do this by default. OpenHaystack is not involved in this step.
### Searching (4)
Apple does not know which encrypted locations belong to which Apple account or device. Therefore, every Apple user can download any location report as long as they know the corresponding public key. This is not a security issue: all reports are end-to-end encrypted and cannot be decrypted unless one knows the corresponding private key (stored in the keychain). We leverage this feature to download the reports from Apple that have been created for our OpenHaystack tags. We use our private keys to decrypt the location reports and show the most recent one on the map.
Apple protects their database against arbitrary access by requiring an authenticated Apple user to download location reports.
We use our Apple Mail plugin, which runs with elevated privileges, to access the required authentication information. The OpenHaystack app communicates with the plugin while downloading reports. This is why you need to keep Mail open while using OpenHaystack.
## How to track other Bluetooth devices?
Currently, we only provide a convenient deployment method of our OpenHaystack firmware for the BBC micro:bit.
However, you should be able to implement the advertisements on other devices that support Bluetooth Low Energy based on the [source code of our firmware](Firmware) and the specification in [our paper](#references).
![Setup](Resources/Setup.jpg)
## Authors
- **Alexander Heinrich** ([@Sn0wfreezeDev](https://github.com/Sn0wfreezeDev), [email](mailto:aheinrich@seemoo.tu-darmstadt.de))
- **Milan Stute** ([@schmittner](https://github.com/schmittner), [email](mailto:mstute@seemoo.tu-darmstadt.de), [web](https://seemoo.de/mstute))
## References
- Alexander Heinrich, Milan Stute, Tim Kornhuber, Matthias Hollick. **Who Can _Find My_ Devices? Security and Privacy of Apple's Crowd-Sourced Bluetooth Location Tracking System.** _Proceedings on Privacy Enhancing Technologies (PoPETs)_, 2021.
- Tim Kornhuber. **Analysis of Apple's Crowd-Sourced Location Tracking System.** _Technical University of Darmstadt_, Master's thesis, 2020.
- Apple Inc. **Find My Network Accessory Specification Developer Preview Release R3.** 2020. [📄 Download](https://developer.apple.com/find-my/).
## License
OpenHaystack is licensed under the [**GNU Affero General Public License v3.0**](LICENSE).

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 671 KiB

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import os
from PIL import Image
basename = "OpenHaystackIcon"
imformat = "png"
export_folder = "../../OpenHaystack/OpenHaystack/Assets.xcassets/AppIcon.appiconset"
export_sizes = [16, 32, 64, 128, 256, 512, 1024]
with Image.open(f"{basename}.{imformat}") as im:
for size in export_sizes:
out = im.resize((size, size))
outfile = os.path.join(export_folder, f"{size}.{imformat}")
out.save(outfile)

Binary file not shown.

After

Width:  |  Height:  |  Size: 725 KiB

BIN
Resources/Setup.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB