code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def change add_column :users, :lat, :decimal, precision: 8, scale: 6 add_column :users, :lng, :decimal, precision: 9, scale: 6 end
Adds geolocation lat/lng to users based on their public GH location
change
ruby
24pullrequests/24pullrequests
db/migrate/20151122220446_add_lat_lng_to_users.rb
https://github.com/24pullrequests/24pullrequests/blob/master/db/migrate/20151122220446_add_lat_lng_to_users.rb
MIT
def mock_pull_request { 'payload' => { 'pull_request' => { 'title' => Faker::Lorem.words.first, '_links' => { 'html' => { 'href' => Faker::Internet.url } }, 'created_at' => DateTime.now.to_s, 'state' => 'open', 'body' => Faker::Lorem.paragraphs.join('\n'), 'merged' => false } }, 'repo' => { 'name' => Faker::Lorem.words.first, 'language' => Project::LANGUAGES.sample } } end
Creates a mock pull request in json format.
mock_pull_request
ruby
24pullrequests/24pullrequests
spec/support/pull_request_helpers.rb
https://github.com/24pullrequests/24pullrequests/blob/master/spec/support/pull_request_helpers.rb
MIT
def default_options_date_format(format) format || '%Y-%m-%d - %l:%M:%S%p' end
def default_datetime_options(options) format = define_format(options) align = default_options_align(options[:align]) width = default_options_width(options[:width]) [format, align, width] end
default_options_date_format
ruby
wbailey/command_line_reporter
lib/command_line_reporter.rb
https://github.com/wbailey/command_line_reporter/blob/master/lib/command_line_reporter.rb
Apache-2.0
def output return if rows.empty? # we got here with nothing to print to the screen auto_adjust_widths if width == :auto puts separator('first') if border rows.each_with_index do |row, index| row.output puts separator('middle') if border && (index != rows.size - 1) end puts separator('last') if border end
rubocop:disable Metrics/AbcSize rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/MethodLength
output
ruby
wbailey/command_line_reporter
lib/command_line_reporter/table.rb
https://github.com/wbailey/command_line_reporter/blob/master/lib/command_line_reporter/table.rb
Apache-2.0
def auto_adjust_widths column_widths = [] rows.each do |row| row.columns.each_with_index do |col, i| column_widths[i] = [col.required_width, (column_widths[i] || 0)].max end end rows.each do |row| row.columns.each_with_index do |col, i| col.width = column_widths[i] end end end
TODO: This doesn't appear to be used and if it is, it will not handle span appropriately
auto_adjust_widths
ruby
wbailey/command_line_reporter
lib/command_line_reporter/table.rb
https://github.com/wbailey/command_line_reporter/blob/master/lib/command_line_reporter/table.rb
Apache-2.0
def initialize(root_folder, type, output_folder, decrypter=AppleDecrypter.new) @root_folder = root_folder @type = type @output_folder = output_folder @logger = Logger.new(@output_folder + "debug_log.txt") @note_stores = Array.new @note_store_modern_location = @output_folder + "NoteStore.sqlite" @note_store_legacy_location = @output_folder + "notes.sqlite" @note_store_temporary_location = @output_folder + "test.sqlite" @decrypter = decrypter @decrypter.logger = @logger # Set up date ranges, if desired @range_start = 0 @range_end = Time.now.to_i @retain_order = false # Track whether the backup uses an accounts folder or not. Default to true @uses_account_folder = check_for_accounts_folder end
# Creates a new AppleBackup. Expects a Pathname +root_folder+ that represents the root of the backup, an Integer +type+ that represents the type of backup, and a Pathname +output_folder+ which will hold the results of this run. Backup +types+ are defined in this class. The child classes will immediately set the NoteStore database file, based on the +type+ of backup.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def set_range_start(range_start) @range_start = range_start @note_stores.each do |notestore| notestore.range_start = @range_start end end
# Explicitly sets the range start of the notestores
set_range_start
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def set_range_end(range_end) @range_end = range_end @note_stores.each do |notestore| notestore.range_end = @range_end end end
# Explicitly sets the range end of the notestores
set_range_end
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def create_and_add_notestore(location, version) tmp_notestore = AppleNoteStore.new(location, version) tmp_notestore.backup=(self) @note_stores.push(tmp_notestore) @logger.debug("Guessed Notes Version: #{version.to_s}") puts "Guessed Notes Version: #{version.to_s}" end
# This method handles creating and adding a new AppleNoteStore. it expects a Pathname +location+ for the location of the NoteStore.sqlite database and an Integer +version+ representing the version of the AppleNoteStore.
create_and_add_notestore
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def valid? @logger.error("Returning 'invalid' as no specific type of backup was specified") raise "AppleBackup cannot stand on its own" return false end
# No backup on its own is valid, it must be a abckup type that is recognized. In those cases, instantiate the appropriate child (such as AppleBackupHashed).
valid?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def copy_notes_database(filepath, destination) begin # Copy the actual NoteStore.sqlite file FileUtils.cp(filepath, destination) # Compute the paths to the WAL and SHM files tmp_path, tmp_name = filepath.split wal_filename = tmp_name.to_s + "-wal" shm_filename = tmp_name.to_s + "-shm" wal_filepath = tmp_path + wal_filename shm_filepath = tmp_path + shm_filename # Copy the WAL and SHM files if they exist FileUtils.cp(wal_filepath, @output_folder) if wal_filepath.exist? FileUtils.cp(shm_filepath, @output_folder) if shm_filepath.exist? rescue @logger.error("Failed to copy #{filepath} or its journals to #{destination}.") end end
# This method copies a notes database and checks for any journals that also need to be copied. It expects a Pathname +filepath+ that represents the location of a notes database file and a Pathname +destination+ that represents the name the database file should end up as. It copies the database to our expected output location. It also checks for WAL and SHM files for inclusion. Note: the AppleBackupHashed class does *not* use this because the filenames aren't computed the same.
copy_notes_database
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def strip_account_path(pathstring) return "" if !pathstring.is_a? String return pathstring if !pathstring.start_with?("Accounts/") pathstring.sub(/Accounts\/[^\/]+\//,"") end
# This method sanitizes the "Account/[account identifier]" from the front of paths. It expects a String +pathstring+ and returns a String having removed the beginngin path
strip_account_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def check_for_accounts_folder return true end
# This method should be overridden by each specific backup class to return true if the backup is using an accounts folder and false if not. It defaults to true, because that's the way it SHOULD be.
check_for_accounts_folder
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def find_valid_file_path(possibilities) return nil if !possibilities.is_a? Array # Make sure we have the input we want return nil if @type == SINGLE_FILE_BACKUP_TYPE # Don't bother running on a single file to spare the log file # Loop over all the possibilities possibilities.each do |possibility| # If we know not to use an accounts folder, don't try # Rip off prefixes that might not exist (https://github.com/threeplanetssoftware/apple_cloud_notes_parser/issues/24) if (!@uses_account_folder and possibility.start_with?("Accounts\/")) possibility = strip_account_path(possibility) end @logger.debug("Checking if #{possibility} exists as a real file on disk") pathname = get_real_file_path(possibility) # If this file exists on disk, create a new AppleStoredFileResult, calculate # the filename and on disk fields, and return it. if pathname and pathname.exist? @logger.debug("Found #{possibility}! Creating a new AppleStoredFileResult") tmp_stored_file_result = AppleStoredFileResult.new tmp_stored_file_result.original_filepath = possibility tmp_stored_file_result.original_filename = Pathname.new(possibility).basename.to_s tmp_stored_file_result.storage_filepath = pathname return tmp_stored_file_result end end @logger.debug("Could not find a matching file on disk for any permutation") return nil end
# This method expects an Array of Strings +possibilities+ representing potential paths on disk. It will then iterate over each and use return the first one that is actually found. If none are found, it will return `nil`.
find_valid_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def get_real_file_path(filename) @logger.error("Returning nil for get_real_file_path as no specific type of backup was specified") raise "Cannot return file_path for AppleBackup" return nil end
# This method returns a Pathname that represents the location on this disk of the requested file or nil. It expects a String +filename+ to look up. This returns nil by default, and specific types of backups will override this to provide the correct location.
get_real_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def back_up_file(filepath_on_phone, filename_on_phone, filepath_on_disk, is_password_protected=false, password=nil, salt=nil, iterations=nil, key=nil, iv=nil, tag=nil, debug_text=nil) # Fail out if we do not have a filepath to copy and log appropriately if !filepath_on_disk @logger.error("Can't call back_up_file with filepath_on_disk that is nil") if @type != SINGLE_FILE_BACKUP_TYPE return end # Fail out if we do not have a filename to copy and log appropriately if !filename_on_phone @logger.error("Can't call back_up_file with filename_on_phone that is nil") if @type != SINGLE_FILE_BACKUP_TYPE return end # Fail out if the file simply can't be found and log appropriately if !File.exist?(filepath_on_disk) @logger.error("Can't call back_up_file with filepath_on_disk that does not exist: #{filepath_on_disk}") if @type != SINGLE_FILE_BACKUP_TYPE return end # Turn the filepath on the phone into a Pathname object for manipulation phone_filepath = Pathname.new(filepath_on_phone) # Create the output folder of output/[datetime]/files/[filepath]/filename file_output_directory = @output_folder + "files" + phone_filepath.parent # Create a relative link for the file to reference in HTML file_relative_output_path = Pathname.new("files") + phone_filepath.parent + filename_on_phone # Create the output directory file_output_directory.mkpath if !file_output_directory.exist? # Decrypt and write a new file, or copy the file depending on if we are password protected tmp_target_filepath = file_output_directory + filename_on_phone @logger.debug("Copying #{filepath_on_disk} to #{tmp_target_filepath}") begin FileUtils.cp(filepath_on_disk, tmp_target_filepath) rescue @logger.error("Failed to copy #{filepath_on_disk} to #{tmp_target_filepath}") end # Handle encrypted iTunes backups if (@type == HASHED_BACKUP_TYPE and is_encrypted?) decrypt_in_place(phone_filepath.to_s, 'files') end # If the file was password protected, go ahead and decrypt it if is_password_protected encrypted_data = File.read(tmp_target_filepath) decrypt_result = @decrypter.decrypt_with_password(password, salt, iterations, key, iv, tag, encrypted_data, "Apple Backup encrypted file") File.write(tmp_target_filepath.sub(/\.encrypted$/,""), decrypt_result[:plaintext]) if decrypt_result end # return where we put it return file_relative_output_path.sub(/\.encrypted$/,"") end
# This method copies a file from the backup into the output directory. It expects a String +filepath_on_phone+ representing where it came from, a String +filename_on_phone+ representing the actual filename on the phone, and a Pathname +filepath_on_disk+ representing where on this computer the file can be found. Takes an optional boolean +is_password_protected+ and all the cryptographic settings to indicate if the file needs to be decrypted. Returns a Pathname representing the relative position of the file in the output folder. If the file was encrypted, reads the original, decrypts and writes the decrypted content to the new file name.
back_up_file
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def is_sqlite?(file) File.open(file, 'rb') do |file_handle| return true if file_handle.gets(nil, 15) == "SQLite format 3" end return false end
# This method takes a FilePath +file+ and checks the first 15 bytes to see if there is a SQLite magic number at the start. Not perfect, but good enough.
is_sqlite?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def has_correct_columns?(file) to_return = false # Open the database and pull the table list database = SQLite3::Database.new(file.to_s, {results_as_hash: true}) results = database.execute("PRAGMA table_list;") legacy_columns = ['ZACCOUNT', 'ZNOTE', 'ZNOTEBODY', 'ZSTORE'] modern_columns = ['ACHANGE', 'ZICCLOUDSYNCINGOBJECT','ZICLOCATION', 'ZICNOTEDATA'] results.each do |result| legacy_columns.delete(result["name"]) modern_columns.delete(result["name"]) end # Close the database now that we're done with it database.close # This should be an iOS 9+ database if modern_columns.length == 0 to_return = true end # This is a legacy database if legacy_columns.length == 0 to_return = true end return to_return end
# This method takes a FilePath +file+ and checks to make sure the list of tables looks a bit like what we expect from a NoteStore.
has_correct_columns?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def rip_notes @note_stores.each do |note_store| note_store.retain_order = @retain_order @logger.debug("Apple Backup: Ripping notes from Note Store version #{note_store.version}") note_store.rip_all_objects() end end
# This function kicks off the parsing of notes
rip_notes
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackup.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackup.rb
MIT
def initialize(root_folder, output_folder, decrypter=AppleDecrypter.new) super(root_folder, AppleBackup::SINGLE_FILE_BACKUP_TYPE, output_folder, decrypter) # Check to make sure we're all good if self.valid? puts "Created a new AppleBackup from single file: #{@root_folder}" # Copy the database to a temporary spot to fingerprint copy_notes_database(@root_folder, @note_store_temporary_location) # Fingerprint it note_version = AppleNoteStore.guess_ios_version(@note_store_temporary_location) # Move that to the right name, based on the version note_store_new_location = @note_store_modern_location if note_version.modern? note_store_new_location = @note_store_legacy_location if note_version.legacy? # Rename the file to be the right database FileUtils.mv(@note_store_temporary_location, note_store_new_location) # Create the AppleNoteStore object create_and_add_notestore(@note_store_modern_location, note_version) end end
# Creates a new AppleBackupFile. Expects a Pathname +root_folder+ that represents the root of the backup and a Pathname +output_folder+ which will hold the results of this run. Immediately sets the NoteStore database file.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupFile.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupFile.rb
MIT
def valid? return (@root_folder.file? and is_sqlite?(@root_folder) and has_correct_columns?(@root_folder)) end
# This method returns true if it is a value backup of the specified type. For the SINGLE_FILE_BACKUP_TYPE this means that the +root_folder+ given is the NoteStore.sqlite directly.
valid?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupFile.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupFile.rb
MIT
def get_real_file_path(filename) return nil end
# This method returns a Pathname that represents the location on this disk of the requested file or nil. It expects a String +filename+ to look up. For single file backups, this will always be nil.
get_real_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupFile.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupFile.rb
MIT
def initialize(root_folder, output_folder, decrypter=AppleDecrypter.new) super(root_folder, AppleBackup::HASHED_BACKUP_TYPE, output_folder, decrypter) @hashed_backup_manifest_database = nil # Check to make sure we're all good if self.valid? puts "Created a new AppleBackup from iTunes backup: #{@root_folder}" # Snag the manifest.plist file @manifest_plist = AppleBackupHashedManifestPlist.new((@root_folder + "Manifest.plist"), @decrypter, @logger) if (@manifest_plist.encrypted? and !@manifest_plist.can_decrypt?) @logger.error("Manifest Plist file cannot be decrypted, likely due to a bad password.") puts "Manifest PList file cannot be decrypted, have you included any passwords?" exit end # Define where the modern notes live hashed_note_store = @root_folder + "4f" + "4f98687d8ab0d6d1a371110e6b7300f6e465bef2" hashed_note_store_wal = @root_folder + "7d" + "7dc1d0fa6cd437c0ad9b9b573ea59c5e62373e92" hashed_note_store_shm = @root_folder + "55" + "55901f4cbd89916628b4ec30bf19717aca78fb2c" # Define where the Manifest file lives manifest_db = @root_folder + "Manifest.db" manifest_db_wal = @root_folder + "Manifest.db-wal" manifest_db_shm = @root_folder + "Manifest.db-shm" # Define where the legacy notes live hashed_legacy_note_store = @root_folder + "ca" + "ca3bc056d4da0bbf88b5fb3be254f3b7147e639c" hashed_legacy_note_store_wal = @root_folder + "12" + "12be33d156731173c5ec6ea09ab02f07a98179ed" hashed_legacy_note_store_shm = @root_folder + "ef" + "efaa1bfb59fcb943689733e2ca1595db52462fb9" # Copy the NoteStore.sqlite file FileUtils.cp(hashed_note_store, @note_store_modern_location) FileUtils.cp(hashed_note_store_wal, @output_folder + "NoteStore.sqlite-wal") if hashed_note_store_wal.exist? FileUtils.cp(hashed_note_store_shm, @output_folder + "NoteStore.sqlite-shm") if hashed_note_store_shm.exist? # Copy the legacy NoteStore to our output directory FileUtils.cp(hashed_legacy_note_store, @note_store_legacy_location) FileUtils.cp(hashed_legacy_note_store_wal, @output_folder + "notes.sqlite-wal") if hashed_legacy_note_store_wal.exist? FileUtils.cp(hashed_legacy_note_store_shm, @output_folder + "notes.sqlite-shm") if hashed_legacy_note_store_shm.exist? # Copy the Manifest.db to our output directory in case we want to look up files FileUtils.cp(manifest_db, @output_folder + "Manifest.db") FileUtils.cp(manifest_db_wal, @output_folder + "Manifest.db-wal") if manifest_db_wal.exist? FileUtils.cp(manifest_db_shm, @output_folder + "manifest.db-shm") if manifest_db_shm.exist? # Check if we have to decrypt the relevant file(s) if @manifest_plist.encrypted? @logger.debug("Detected encrypted iTunes backup. Attempting to decrypt.") # Snag the encrypted database into memory encrypted_data = '' File.open(@output_folder + "Manifest.db", 'rb') do |file| encrypted_data = file.read end # Fetch the right AppleProtectionClass from the manifest plist protection_class = @manifest_plist.get_class_by_id(@manifest_plist.manifest_key_class) # Bail out if we don't have the right key for some reason if !protection_class @logger.error("Unable to locate the appropriate protection class to decrypt the Manifest.db. Unfortunately, this is the end.") puts "Unable to decrypt the Manifest.db file, we cannot continue." exit end # Unwrap the key protecting the Manifest.db file manifest_key = @decrypter.aes_key_unwrap(@manifest_plist.manifest_key, protection_class.unwrapped_key) # Decrypt the database into memory decrypted_manifest = @decrypter.aes_cbc_decrypt(manifest_key, encrypted_data) # Write the file out to where we expect the manifest to be File.open(@output_folder + "Manifest.db", 'wb') do |output| @logger.debug("Wrote out decrypted Manifest database to #{@output_folder + "Manifest.db"}") output.write(decrypted_manifest) end @hashed_backup_manifest_database = SQLite3::Database.new((@output_folder + "Manifest.db").to_s, {results_as_hash: true}) # Overwrite the other critical files decrypt_in_place("NoteStore.sqlite") decrypt_in_place("notes.sqlite") else @hashed_backup_manifest_database = SQLite3::Database.new((@output_folder + "Manifest.db").to_s, {results_as_hash: true}) end modern_note_version = AppleNoteStore.guess_ios_version(@note_store_modern_location) legacy_note_version = AppleNoteStore.guess_ios_version(@note_store_legacy_location) # Create the AppleNoteStore objects create_and_add_notestore(@note_store_modern_location, modern_note_version) create_and_add_notestore(@note_store_legacy_location, legacy_note_version) # Rerun the check for an Accounts folder now that the database is open @uses_account_folder = check_for_accounts_folder end end
# Creates a new AppleBackupHashed. Expects a Pathname +root_folder+ that represents the root of the backup, a Pathname +output_folder+ which will hold the results of this run, and an AppleDecrypter +decrypter+ to assist in decrypting files. Immediately sets the NoteStore database file to be the appropriate hashed file.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def is_encrypted? return (@manifest_plist and @manifest_plist.encrypted?) end
# This method is a helper to identify if this is an encrypted iTunes backup.
is_encrypted?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def valid? return (@root_folder.directory? and (@root_folder + "Manifest.db").file?) end
# This method returns true if it is a valid backup of the specified type. For a HASHED_BACKUP_TYPE, that means it has a Manifest.db at the root level.
valid?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def check_for_accounts_folder return true if !@hashed_backup_manifest_database # Check for any files that have Accounts in front of them, if so this should be true @hashed_backup_manifest_database.execute("SELECT fileID FROM Files WHERE relativePath LIKE 'Accounts/%' AND domain='AppDomainGroup-group.com.apple.notes' LIMIT 1") do |row| return true end # If we get here, there isn't an accounts folder return false end
# This method overrides the default check_for_accounts_folder to determine if this backup uses an accounts folder or not. It takes no arguments and returns true if an accounts folder is used and false if not.
check_for_accounts_folder
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def get_real_file_path(filename) @hashed_backup_manifest_database.execute("SELECT fileID FROM Files WHERE relativePath=? AND domain='AppDomainGroup-group.com.apple.notes'", filename) do |row| tmp_filename = row["fileID"] tmp_filefolder = tmp_filename[0,2] return @root_folder + tmp_filefolder + tmp_filename end #@logger.debug("AppleBackupHashed: Could not find a real file path for #{filename}") return nil end
# This method returns a Pathname that represents the location on this disk of the requested file or nil. It expects a String +filename+ to look up. For hashed backups, that involves checking Manifest.db to get the appropriate hash value.
get_real_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def get_file_plist(filename) @hashed_backup_manifest_database.execute("SELECT file FROM Files WHERE (relativePath=? AND domain='AppDomainGroup-group.com.apple.notes') OR (relativePath LIKE ? AND domain='HomeDomain')", filename) do |row| file_plist = row["file"] tmp_plist = CFPropertyList::List.new tmp_plist.load_binary_str(file_plist) return CFPropertyList.native_types(tmp_plist.value) end # If we get this far, consider if it is a legacy notes file, unsure if this is the best way to go about it filename = "Library/Notes/#{filename}" @hashed_backup_manifest_database.execute("SELECT file FROM Files WHERE relativePath=? AND domain='HomeDomain'", filename) do |row| file_plist = row["file"] tmp_plist = CFPropertyList::List.new tmp_plist.load_binary_str(file_plist) return CFPropertyList.native_types(tmp_plist.value) end # If we get here, we just need to give up return nil end
# This method returns a binary plist object that represents the data in the Files.file column. It expects a String +filename+ to look up. For hashed backups, that involves checking Manifest.db to get the appropriate hash value.
get_file_plist
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def get_file_encryption_key(plist) # Find the root object ID tmp_root = plist["$top"]["root"] # Use the root object ID to find the Encryption Key index tmp_key_position = plist["$objects"][tmp_root]["EncryptionKey"] # Get the data for the encryption key, this has the protection class at the start tmp_wrapped_key = plist["$objects"][tmp_key_position]["NS.data"] # Return the key itself return tmp_wrapped_key[4,tmp_wrapped_key.length - 4] end
# This method fetches the encryption key for a file from the file's plist in Manifest.db. It expects a CFProperty +plist+ and returns the wrapped encryption key as a binary string.
get_file_encryption_key
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def get_file_protection_class(plist) # Find the root object ID tmp_root = plist["$top"]["root"] # Use the root object ID to find the Encryption Key index tmp_key_position = plist["$objects"][tmp_root]["EncryptionKey"] # Get the data for the encryption key, this has the protection class at the start tmp_wrapped_key = plist["$objects"][tmp_key_position]["NS.data"] # Return the key itself return tmp_wrapped_key[0,4].reverse.unpack("N")[0] end
# This method pulls the relevant protection class from the Manifest.db file plist for an encrypted file. It expects a CFPropertyList +plist+ and returns the protection class as an Integer.
get_file_protection_class
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def get_file_expected_size(plist) # Find the root object ID tmp_root = plist["$top"]["root"] # Use the root object ID to find the Encryption Key index return plist["$objects"][tmp_root]["Size"] end
# This method pulls the expected file size from the Manifest.db file plist for an encrypted file. It expects a CFPropertyList +plist+ and returns the file size as an Integer.
get_file_expected_size
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def decrypt_in_place(filename, folder='') @logger.debug("Attempting to decrypt in place #{filename}") target_destination = @output_folder + folder + filename return if !target_destination.exist? # Snag the File Plist for this file from the Manifest.db file tmp_plist = get_file_plist(filename) if !tmp_plist @logger.error("Unable to find the file plist for #{filename}.") return end tmp_wrapped_key = get_file_encryption_key(tmp_plist) tmp_class = get_file_protection_class(tmp_plist) tmp_size = get_file_expected_size(tmp_plist) # Fetch the protection class from the manifest Plist to get its unwrapped key tmp_protection_class = @manifest_plist.get_class_by_id(tmp_class) tmp_unwrapped_key = @decrypter.aes_key_unwrap(tmp_wrapped_key, tmp_protection_class.unwrapped_key) # Actually decrypt the file itself decrypted_file = @decrypter.aes_cbc_decrypt(tmp_unwrapped_key, File.read(@output_folder + folder + filename)) if !decrypted_file @logger.error("Failed to decrypt #{target_destination}") return end # Overwrite the results File.open(target_destination, 'wb') do |output| @logger.debug("Wrote out decrypted #{filename} to #{target_destination}") # Only write the first tmp_size bytes, don't write the padding that decrypting introduced. # This ensures encrypted files can be decrypted, as they were encrypted prior to the padding # being introduced. output.write(decrypted_file[0, tmp_size]) end end
# This method is used to decrypt an iTunes encrypted backup file in place. It expects the file to already have been copied to the output folder and to receive the +filename+ as a String. It checks the filename in Manifest.db, looks up the corresponding encryption key, and uses that to decrypt the file contents, overwriting was was in output.
decrypt_in_place
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashed.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashed.rb
MIT
def parse_keybag current_location = 0 tmp_keybag = @manifest_plist_data["BackupKeyBag"] pbkdf2_salt = nil pbkdf2_iters = 0 pbkdf2_double_protection_salt = nil pbkdf2_double_protection_iters = 0 @keybag_uuid = nil @keybag_wrap = nil tmp_protection_class = nil while current_location < tmp_keybag.length # First four bytes are the string type tmp_string_type = tmp_keybag[current_location, 4] current_location += 4 # Next four bytes are the length, in big-endian tmp_length = tmp_keybag[current_location, 4].unpack("N")[0] current_location += 4 # next X bytes are the value itself tmp_value = tmp_keybag[current_location, tmp_length] current_location += tmp_length # Read in values case tmp_string_type when "VERS" @keybag_version = tmp_value.unpack("N")[0] when "HMCK" @keybag_hmac = tmp_value when "TYPE" @keybag_type = tmp_value.unpack("N")[0] when "SALT" @pbkdf2_salt = tmp_value when "ITER" @pbkdf2_iter = tmp_value.unpack("N")[0] when "DPSL" @pbkdf2_double_protection_salt = tmp_value when "DPIC" @pbkdf2_double_protection_iter = tmp_value.unpack("N")[0] when "UUID" if not @keybag_uuid @keybag_uuid = tmp_value else # We have a new protection class @protection_classes.push(tmp_protection_class) if tmp_protection_class tmp_protection_class = AppleProtectionClass.new(tmp_value) end when "CLAS" tmp_protection_class.clas = tmp_value.unpack("N")[0] when "KTYP" tmp_protection_class.ktyp = tmp_value.unpack("N")[0] when "WPKY" tmp_protection_class.wrapped_key = tmp_value when "WRAP" if not @keybag_wrap @keybag_wrap = tmp_value else tmp_protection_class.wrap = tmp_value end end end @protection_classes.push(tmp_protection_class) if tmp_protection_class if self.key_values_present # First use a SHA256 round with DPSL and DPIC @logger.debug("AppleBackupHashedManifestPlist: Generating key, step 1") initial_key_size = 32 initial_unwrapped_key = nil puts "Checking #{@decrypter.passwords.length} passwords, be aware that the initial step for each password is computationally intensive." @decrypter.passwords.each do |password| initial_unwrapped_key = @decrypter.generate_key_encrypting_key(password, @pbkdf2_double_protection_salt, @pbkdf2_double_protection_iter, '', initial_key_size) if !initial_unwrapped_key end return if !initial_unwrapped_key puts "Successfully generated encrypted iTunes key encrypting key using password" # then a SHA1 round with ITER and SALT @logger.debug("AppleBackupHashedManifestPlist: Generating key, step 2") @unwrapped_key = @decrypter.generate_key_encrypting_key(initial_unwrapped_key, @pbkdf2_salt, @pbkdf2_iter, '', initial_key_size, OpenSSL::Digest::SHA1.new) # Unwrap every key @protection_classes.each do |protection_class| protection_class.unwrapped_key = @decrypter.aes_key_unwrap(protection_class.wrapped_key, @unwrapped_key) @logger.debug("AppleBackupHashedManifestPlist: Unwrapped key for protection class #{protection_class.clas}") end end end
# This method parses the manifest's keybag into internal data structures.
parse_keybag
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashedManifestPlist.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashedManifestPlist.rb
MIT
def get_class_by_id(class_id) @protection_classes.each do |protection_class| return protection_class if protection_class.clas == class_id end return nil end
# This method takes an Integer +class_id+ and returns the AppleProtectionClass that corresponds to that class id. Returns nil if not found.
get_class_by_id
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashedManifestPlist.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashedManifestPlist.rb
MIT
def can_decrypt? return @unwrapped_key != nil end
# This method identifies if we can decrypt the file. It solely checks if an +@unwrapped_key+ exists.
can_decrypt?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupHashedManifestPlist.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupHashedManifestPlist.rb
MIT
def initialize(root_folder, output_folder, decrypter=AppleDecrypter.new) super(root_folder, AppleBackup::MAC_BACKUP_TYPE, output_folder, decrypter) # Check to make sure we're all good if self.valid? puts "Created a new AppleBackup from Mac backup: #{@root_folder}" # Copy the modern NoteStore to our output directory copy_notes_database(@root_folder + "NoteStore.sqlite", @note_store_modern_location) modern_note_version = AppleNoteStore.guess_ios_version(@note_store_modern_location) modern_note_version.platform=(AppleNoteStoreVersion::VERSION_PLATFORM_MAC) # Create the AppleNoteStore objects create_and_add_notestore(@note_store_modern_location, modern_note_version) @uses_account_folder = check_for_accounts_folder end end
# Creates a new AppleBackupMac. Expects a Pathname +root_folder+ that represents the root of the physical backup and a Pathname +output_folder+ which will hold the results of this run. Immediately sets the NoteStore database file to be the appropriate application's NoteStore.sqlite.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupMac.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupMac.rb
MIT
def valid? return (@root_folder.directory? and (@root_folder + "NoteStore.sqlite").file? and has_correct_columns?(@root_folder + "NoteStore.sqlite") and (@root_folder + "NotesIndexerState-Modern").file?) end
# This method returns true if it is a value backup of the specified type. For MAC_BACKUP_TYPE this means that the +root_folder+ given is where the root of the directory structure is and the NoteStore.sqlite file is directly underneath.
valid?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupMac.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupMac.rb
MIT
def check_for_accounts_folder accounts_folder = @root_folder + "Accounts" return accounts_folder.exist? end
# This method overrides the default check_for_accounts_folder to determine if this backup uses an accounts folder or not. It takes no arguments and returns true if an accounts folder is used and false if not.
check_for_accounts_folder
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupMac.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupMac.rb
MIT
def get_real_file_path(filename) pathname = @root_folder + filename return pathname if pathname and pathname.exist? return nil end
# This method returns a Pathname that represents the location on this disk of the requested file or nil. It expects a String +filename+ to look up.
get_real_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupMac.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupMac.rb
MIT
def initialize(root_folder, output_folder, decrypter=AppleDecrypter.new) super(root_folder, AppleBackup::PHYSICAL_BACKUP_TYPE, output_folder, decrypter) @physical_backup_app_folder = nil @physical_backup_app_uuid = find_physical_backup_app_uuid # Check to make sure we're all good if self.valid? puts "Created a new AppleBackup from physical backup: #{@root_folder}" # Set the app's folder for ease of reference later @physical_backup_app_folder = (@root_folder + "private" + "var" + "mobile" + "Containers" + "Shared" + "AppGroup" + @physical_backup_app_uuid) # Copy the modern NoteStore to our output directory copy_notes_database(@physical_backup_app_folder + "NoteStore.sqlite", @note_store_modern_location) modern_note_version = AppleNoteStore.guess_ios_version(@note_store_modern_location) # Copy the legacy notes.sqlite to our output directory copy_notes_database(@root_folder + "private" + "var" + "mobile" + "Library" + "Notes" + "notes.sqlite", @note_store_legacy_location) legacy_note_version = AppleNoteStore.guess_ios_version(@note_store_legacy_location) # Create the AppleNoteStore objects create_and_add_notestore(@note_store_modern_location, modern_note_version) create_and_add_notestore(@note_store_legacy_location, legacy_note_version) # Call this a second time, now that we know we are valid and have the right file path @uses_account_folder = check_for_accounts_folder end end
# Creates a new AppleBackupPhysical. Expects a Pathname +root_folder+ that represents the root of the physical backup and a Pathname +output_folder+ which will hold the results of this run. Immediately sets the NoteStore database file to be the appropriate application's NoteStore.sqlite.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupPhysical.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupPhysical.rb
MIT
def valid? return (@physical_backup_app_uuid != nil) end
# This method returns true if it is a value backup of the specified type. For PHYSICAL_BACKUP_TYPE this means that the +root_folder+ given is where the root of the directory structure is, i.e one step above private.
valid?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupPhysical.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupPhysical.rb
MIT
def find_physical_backup_app_uuid # Bail out if this doesn't look obviously right return nil if (!@root_folder or !@root_folder.directory? or !(@root_folder + "private" + "var" + "mobile" + "Containers" + "Shared" + "AppGroup").directory?) # Create a variable to return app_uuid = nil # Create a variable for simplicity app_folder = @root_folder + "private" + "var" + "mobile" + "Containers" + "Shared" + "AppGroup" # Loop over each child entry to check them for what we want app_folder.children.each do |child_entry| if child_entry.directory? and (child_entry + "NoteStore.sqlite").exist? app_uuid = child_entry.basename end end return app_uuid end
# This method iterates through the app UUIDs of a physical backup to identify which one contains Notes. It does it this way to ensure that all files were correctly pulled. It returns the String representing the UUID or nil if not appropriate.
find_physical_backup_app_uuid
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupPhysical.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupPhysical.rb
MIT
def check_for_accounts_folder return true if !@physical_backup_app_folder accounts_folder = @physical_backup_app_folder + "Accounts" return accounts_folder.exist? end
# This method overrides the default check_for_accounts_folder to determine if this backup uses an accounts folder or not. It takes no arguments and returns true if an accounts folder is used and false if not.
check_for_accounts_folder
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupPhysical.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupPhysical.rb
MIT
def get_real_file_path(filename) return @physical_backup_app_folder + filename end
# This method returns a Pathname that represents the location on this disk of the requested file or nil. It expects a String +filename+ to look up.
get_real_file_path
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleBackupPhysical.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleBackupPhysical.rb
MIT
def initialize() # Tracks the AppleCloudKitParticipants this is shared with @share_participants = Array.new() @server_record_data = nil @cloudkit_last_modified_device = nil @cloudkit_creator_record_id = nil @cloudkit_modifier_record_id = nil end
# Creates a new AppleCloudKitRecord. Requires nothing and initializes the share_participants.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitRecord.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitRecord.rb
MIT
def add_cloudkit_sharing_data(cloudkit_data) keyed_archive = KeyedArchive.new(:data => cloudkit_data) unpacked_top = keyed_archive.unpacked_top() total_added = 0 if unpacked_top unpacked_top["Participants"]["NS.objects"].each do |participant| # Pull out the relevant values if participant["UserIdentity"] participant_user_identity = participant["UserIdentity"] # Initialize a new AppleCloudKitShareParticipant tmp_participant = AppleCloudKitShareParticipant.new() # Read in the user's contact information if participant_user_identity["LookupInfo"] tmp_participant.email = participant_user_identity["LookupInfo"]["EmailAddress"] tmp_participant.phone = participant_user_identity["LookupInfo"]["PhoneNumber"] end # Read in user's record id if participant_user_identity["UserRecordID"] tmp_participant.record_id = participant_user_identity["UserRecordID"]["RecordName"] end # Read in name components if participant_user_identity["NameComponents"] participant_name_components = participant["UserIdentity"]["NameComponents"]["NS.nameComponentsPrivate"] # Split the name up into its components tmp_participant.name_prefix = participant_name_components["NS.namePrefix"] tmp_participant.first_name = participant_name_components["NS.givenName"] tmp_participant.middle_name = participant_name_components["NS.middleName"] tmp_participant.last_name = participant_name_components["NS.familyName"] tmp_participant.name_suffix = participant_name_components["NS.nameSuffix"] tmp_participant.nickname = participant_name_components["NS.nickname"] tmp_participant.name_phonetic = participant_name_components["NS.phoneticRepresentation"] end # Add them to this object @share_participants.push(tmp_participant) total_added += 1 end end end total_added end
# This method adds CloudKit Share data to an AppleCloudKitRecord. It requires a binary String +cloudkit_data+ from the ZSERVERSHAREDATA column.
add_cloudkit_sharing_data
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitRecord.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitRecord.rb
MIT
def add_cloudkit_server_record_data(server_record_data) @server_record_data = server_record_data keyed_archive = KeyedArchive.new(:data => server_record_data) unpacked_top = keyed_archive.unpacked_top() if unpacked_top @cloudkit_last_modified_device = unpacked_top["ModifiedByDevice"] @cloudkit_creator_record_id = unpacked_top["CreatorUserRecordID"]["RecordName"] @cloudkit_modifier_record_id = unpacked_top["LastModifiedUserRecordID"]["RecordName"] # Sometimes folders don't have their parent reflected in the ZPARENT column and instead # are reflected in this field. Let's set the parent_uuid field and let AppleNoteStore # play cleanup later. if unpacked_top["RecordType"] == "Folder" and unpacked_top["ParentReference"] @parent_uuid = unpacked_top["ParentReference"]["recordID"]["RecordName"] end end end
# This method takes a the binary String +server_record_data+ which is stored in ZSERVERRECORDDATA. Currently just pulls out the last modified device.
add_cloudkit_server_record_data
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitRecord.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitRecord.rb
MIT
def cloud_kit_record_known?(record_id) @share_participants.each do |participant| return participant if participant.record_id.eql?(record_id) end return false end
# This method takes a String +record_id+ to determine if the particular cloudkit record is known. It returns an AppleCloudKitParticipant object, or False.
cloud_kit_record_known?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitRecord.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitRecord.rb
MIT
def to_csv [@record_id, @email, @phone, @name_prefix, @first_name, @middle_name, @last_name, @name_suffix, @name_phonetic] end
# This method generates an Array containing the information necessary to build a CSV
to_csv
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitShareParticipant.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitShareParticipant.rb
MIT
def prepare_json to_return = Hash.new() to_return[:email] = @email to_return[:record_id] = @record_id to_return[:first_name] = @first_name to_return[:last_name] = @last_name to_return[:middle_name] = @middle_name to_return[:name_prefix] = @name_prefix to_return[:name_suffix] = @name_suffix to_return[:name_phonetic] = @name_phonetic to_return[:phone] = @phone to_return end
# This method prepares the data structure that JSON will use to generate JSON later.
prepare_json
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleCloudKitShareParticipant.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleCloudKitShareParticipant.rb
MIT
def initialize @logger = Logger.new(STDOUT) @passwords = Array.new @successful_passwords = Array.new @warned_about_empty_password_list = false end
# Creates a new AppleDecrypter. Immediately initalizes +@passwords+ and +@successful_passwords+ as Arrays to keep track of loaded passwords and the ones that worked. Also sets +@warned_about_empty_password_list+ to false in order to nicely warn the user ones if they should be trying to decrypt. Make sure to call logger= at some point if you don't want to dump to STDOUT.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def add_passwords_from_file(password_file) if password_file @passwords = Array.new() # Read in each line and add them to our list File.readlines(password_file).each do |password| #@logger.debug("Apple Decrypter: Adding password number #{passwords.length} to our list") @passwords.push(password.chomp) end puts "Added #{@passwords.length} passwords to the AppleDecrypter from #{password_file}" end return @passwords.length end
# This function takes a FilePath +file+ and reads passwords from it one per line to build the overall +@passwords+ Array.
add_passwords_from_file
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def decrypt(salt, iterations, key, iv, tag, data, debug_text=nil) # Initialize plaintext variable to be false so we can check if we don't succeed decrypt_result = false # Warn the user if we come across something encrypted and they haven't provided a password list if @passwords.length == 0 and !@warned_about_empty_password_list puts "Apple Decrypter: Attempting to decrypt objects without a password list set, check the -w option for more success" @logger.error("Apple Decrypter: Attempting to decrypt objects without a password list set, check the -w option for more success") @warned_about_empty_password_list = true end # Start with the known good passwords @successful_passwords.each do |password| decrypt_result = decrypt_with_password(password, salt, iterations, key, iv, tag, data, debug_text) if decrypt_result break end end # Only try the full list if we haven't already found the password if !decrypt_result @passwords.each do |password| decrypt_result = decrypt_with_password(password, salt, iterations, key, iv, tag, data, debug_text) if decrypt_result @successful_passwords.push(password) break end end end return decrypt_result end
# This function attempts to decrypt the specified data by looping over all the loaded passwords. It expects a +salt+ as a binary String, the number of +iterations+ as an Integer, a +key+ representing the wrapped key as a binary String, an +iv+ as a binary String, a +tag+ as a binary String, the +data+ to be decrypted as a binary String, and the +item+ being decrypted as an Object to help with debugging. Any successful decrypts will add the corresponding password to the +@successful_passwords+ to be tried first the next time.
decrypt
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def check_cryptographic_settings(password, salt, iterations, wrapped_key) tmp_key_encrypting_key = generate_key_encrypting_key(password, salt, iterations) tmp_unwrapped_key = aes_key_unwrap(wrapped_key, tmp_key_encrypting_key) if tmp_key_encrypting_key @successful_passwords.push(password) if (tmp_unwrapped_key and !@successful_passwords.include?(password)) return (tmp_unwrapped_key != nil) end
# This function checks a suspected password, salt, iteration count, and wrapped key to determine if the settings are valid. It does this by checking that the unwrapped key has the correct iv. It returns true if the settings are valid, false otherwise. It expects the +password+ as a String, the +salt+ as a binary String, and the number of +iterations+ as an integer, and the +wrapped_key+ as a binary String.
check_cryptographic_settings
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def generate_key_encrypting_key(password, salt, iterations, debug_text=nil, key_size=16, hash_function=OpenSSL::Digest::SHA256.new) # Key length in bytes, multiple by 8 for bits. Apple is using 16 (128-bit) # key_size = 16 generated_key = nil begin generated_key = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, key_size, hash_function) rescue OpenSSL::Cipher::CipherError puts "Caught CipherError trying to generate PBKDF2 key" @logger.error("Apple Decrypter: #{debug_text} caught a CipherError while trying to generate PBKDF2 key.") rescue OpenSSL::KDF::KDFError puts "Caught KDFError trying to generate PBKDF2 key" @logger.error("Apple Decrypter: #{debug_text} caught a KDFError while trying to generate PBKDF2 key. Length: #{key_size}, Iterations: #{iterations}") end return generated_key end
# This function calls PBKDF2 with Apple's settings to generate a key encrypting key. It expects the +password+ as a String, the +salt+ as a binary String, and the number of +iterations+ as an integer. It returns either nil or the generated key as a binary String. It an error occurs, it will rescue a OpenSSL::Cipher::CipherError and log it.
generate_key_encrypting_key
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def aes_key_unwrap(wrapped_key, key_encrypting_key) unwrapped_key = nil begin unwrapped_key = AESKeyWrap.unwrap!(wrapped_key, key_encrypting_key) rescue AESKeyWrap::UnwrapFailedError => error puts error # Not logging this because it will get spammy if different accounts have different passwords end return unwrapped_key end
# This function performs an AES key unwrap function. It expects the +wrapped_key+ as a binary String and the +key_encrypting_key+ as a binary String. It returns either nil or the unwrapped key as a binary String.
aes_key_unwrap
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def aes_cbc_decrypt(key, encrypted_data, iv=EMPTY_IV, debug_text=nil) decrypted_data = nil if (!key or !iv or !encrypted_data) @logger.error("AES CBC Decrypt called without either key, iv, or encrypted data.") end begin decrypter = OpenSSL::Cipher.new('aes-256-cbc').decrypt decrypter.decrypt decrypter.padding = 0 # If this is not set to 0, openssl appears to generate an extra block decrypter.key = key decrypter.iv = iv decrypted_data = decrypter.update(encrypted_data) + decrypter.final rescue OpenSSL::Cipher::CipherError => error puts "Failed to decrypt #{debug_text}, unwrapped key likely isn't right." @logger.error("Apple Decrypter: #{debug_text} caught a CipherError while trying final decrypt, likely the unwrapped key is not correct.") end return decrypted_data end
# This function performs an AES-CBC decryption. It expects the +key+ as a binary String, an +iv+ as a binary String, which should be 16 0x00 bytes if you don't have another, and the +encrypted_data+ as a binary String. It returns either nil or the decrypted data as a binary String.
aes_cbc_decrypt
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def aes_gcm_decrypt(key, iv, tag, encrypted_data, debug_text=nil) plaintext = nil begin decrypter = OpenSSL::Cipher.new('aes-128-gcm').decrypt decrypter.key = key decrypter.iv_len = iv.length # Just in case the IV isn't 16-bytes decrypter.iv = iv decrypter.auth_tag = tag plaintext = decrypter.update(encrypted_data) + decrypter.final rescue OpenSSL::Cipher::CipherError puts "Failed to decrypt #{debug_text}, unwrapped key likely isn't right." @logger.error("Apple Decrypter: #{debug_text} caught a CipherError while trying final decrypt, likely the unwrapped key is not correct.") end return plaintext end
# This function performs the AES-GCM decryption. It expects a +key+ as a binary String, an +iv+ as a binary String, a +tag+ as a binary String, the +encrypted_data+ as a binary String, and optional +debug_text+ if you want something helpful to hunt in the debug logs. It sets the iv length explicitly to the length of the iv and returns either nil or the plaintext if there was a decrypt. It rescues an OpenSSL::Cipher::CipherError and logs the issue.
aes_gcm_decrypt
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def decrypt_with_password(password, salt, iterations, key, iv, tag, data, debug_text=nil) # Create the key with our password @logger.debug("Apple Decrypter: #{debug_text} Attempting decryption.") # Create variables to track our generated and unwrapped keys between blocks decrypt_result = false plainext = false # Generate the key-encrypting key from the user's password generated_key = generate_key_encrypting_key(password, salt, iterations) # Unwrap the key unwrapped_key = aes_key_unwrap(key, generated_key) if generated_key # Decrypt the content only if we have a key plaintext = aes_gcm_decrypt(unwrapped_key, iv, tag, data, debug_text) if unwrapped_key if plaintext decrypt_result = { plaintext: plaintext, password: password } @logger.debug("Apple Decrypter: #{debug_text} decrypted") end return decrypt_result end
# This function attempts to decrypt the note with a specified password. It expects a +password+ as a normal String, a +salt+ as a binary String, the number of +iterations+ as an Integer, a +key+ representing the wrapped key as a binary String, an +iv+ as a binary String, a +tag+ as a binary String, the +data+ to be decrypted as a binary String, and the +item+ being decrypted as an Object to help with debugging. This starts by unwrapping the +wrapped_key+ using the given +password+ by computing the PBDKF2 with the given +salt+ and +iterations+. With the unwrapped key, we can then use the +iv+ to decrypt the +data+ and authenticate it with the +tag+.
decrypt_with_password
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleDecrypter.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleDecrypter.rb
MIT
def initialize(z_pk, znote, ztitle, zdata, creation_time, modify_time, account, folder) super() # Initialize some other variables while we're here @plaintext = nil @decompressed_data = nil @encrypted_data = nil @widget_snippet = nil @note_proto = nil @crypto_iv = nil @crypto_tag = nil @crypto_key = nil @crypto_salt = nil @crypto_iterations = nil @crypto_password = nil @is_password_protected = false # This holds objects directly in the note itself @embedded_objects = Array.new() # This holds objets embedded in other objects @embedded_objects_recursive = Array.new() # Feed in our arguments @primary_key = z_pk @note_id = znote @title = ztitle @compressed_data = zdata @creation_time = convert_core_time(creation_time) @modify_time = convert_core_time(modify_time) @account = account @folder = folder @notestore = nil @database = nil @backup = nil @logger = Logger.new(STDOUT) @uuid = "" @version = AppleNoteStoreVersion.new # Default to unknown, override this with version= # Handle pinning, added in iOS 11 @is_pinned = false # Cache HTML once generated, useful for multiple outputs that all want the HTML @html = nil end
# Creates a new AppleNote. Expects an Integer +z_pk+, an Integer +znote+ representing the ZICNOTEDATA.ZNOTE field, a String +ztitle+ representing the ZICCLOUDSYNCINGOBJECT.ZTITLE field, a binary String +zdata+ representing the ZICNOTEDATA.ZDATA field, an Integer +creation_time+ representing the iOS CoreTime number found in ZICCLOUDSYNCINGOBJECT.ZCREATIONTIME1 field, an Integer +modify_time+ representing the iOS CoreTime number found in ZICCLOUDSYNCINGOBJECT.ZMODIFICATIONTIME1 field, an AppleNotesAccount +account+ representing the owning account, an AppleNotesFolder +folder+ representing the holding folder, and an AppleNoteStore +notestore+ representing the actual NoteStore representing the full backup.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def process_note # Treat legacy stuff different if @version.legacy? @plaintext = @compressed_data @compressed_data = nil else # Unpack what we can @is_compressed = is_gzip(@compressed_data) decompress_data if @is_compressed extract_plaintext if @decompressed_data replace_embedded_objects if (@plaintext and @database) end end
# This method handles processing the AppleNote's text. For legacy notes that is fairly straightforward and for modern notes that means decompressing and parsing the protobuf.
process_note
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def extract_plaintext if @decompressed_data begin tmp_note_store_proto = NoteStoreProto.decode(@decompressed_data) @plaintext = tmp_note_store_proto.document.note.note_text @note_proto = tmp_note_store_proto rescue Exception puts "Error parsing the protobuf for Note #{@note_id}, have to skip it, see the debug log for more details" @logger.error("Error parsing the protobuf for Note #{@note_id}, have to skip it") @logger.error("Run the following sqlite query to find the appropriate note data, export the ZDATA column as #{@note_id}.blob.gz, gunzip it, and the resulting #{@note_id}.blob contains your protobuf to check with protoc.") @logger.error("\tSELECT ZDATA FROM ZICNOTEDATA WHERE ZNOTE=#{@note_id}") end end end
# This method takes the +decompressed_data+ as an AppleNotesProto protobuf and assigned the plaintext from that protobuf into the +plaintext+ variable.
extract_plaintext
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def replace_embedded_objects if (@plaintext and @account and @folder) tmp_note_store_proto = NoteStoreProto.decode(@decompressed_data) replaced_objects = AppleNotesEmbeddedObject.generate_embedded_objects(self, tmp_note_store_proto) @plaintext = replaced_objects[:to_string] replaced_objects[:objects].each do |replaced_object| @embedded_objects.push(replaced_object) end end end
# This method takes the +plaintext+ that is stored and the +decompressed_data+ as an AppleNotesProto protobuf and loops over all the embedded objects. For each embedded object it finds, it creates a new AppleNotesEmbeddedObject and replaces the "obj" placeholder wth the new object's to_s method. This method creates sub-classes of AppleNotesEmbeddedObject depending on the ZICCLOUDSYNCINGOBJECT.ZTYPEUTI column.
replace_embedded_objects
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def to_csv tmp_pinned = "N" tmp_pinned = "Y" if @is_pinned [@primary_key, @note_id, tmp_pinned, @account.name, @folder.name, @cloudkit_last_modified_device, @cloudkit_creator_record_id, @title, @creation_time, @modify_time, @plaintext, @widget_snippet, @is_password_protected, @crypto_iterations, get_crypto_salt_hex, get_crypto_tag_hex, get_crypto_key_hex, get_crypto_iv_hex, get_encrypted_data_hex, @uuid] end
# This method returns an Array representing the AppleNote CSV export row of this object. Currently that is the +primary_key+, +note_id+, AppleNotesAccount name, AppleNotesFolder name, +title+, +creation_time+, +modify_time+, +plaintext+, and +is_password_protected+. If there are cryptographic variables, it also includes the +crypto_salt+, +crypto_tag+, +crypto_key+, +crypto_iv+, and +encrypted_data+, all as hex, vice binary.
to_csv
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_crypto_iv_hex return @crypto_iv if ! @crypto_iv @crypto_iv.unpack("H*") end
# This function returns the +crypto_iv+ as hex, if it exists.
get_crypto_iv_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_crypto_key_hex return @crypto_key if ! @crypto_key @crypto_key.unpack("H*") end
# This function returns the +crypto_key+ as hex, if it exists.
get_crypto_key_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_crypto_tag_hex return @crypto_tag if ! @crypto_tag @crypto_tag.unpack("H*") end
# This function returns the +crypto_tag+ as hex, if it exists.
get_crypto_tag_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_crypto_salt_hex return @crypto_salt if ! @crypto_salt @crypto_salt.unpack("H*") end
# This function returns the +crypto_salt+ as hex, if it exists.
get_crypto_salt_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_encrypted_data_hex return @encrypted_data if ! @encrypted_data @encrypted_data.unpack("H*") end
# This function returns the +encrypted_data+ as hex, if it exists.
get_encrypted_data_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_note_contents return "Error, note not yet decrypted" if @encrypted_data and !@decompressed_data return "Error, note not yet decompressed" if !@decompressed_data return "Error, note not yet plaintexted" if !@plaintext @plaintext end
# This function returns the +plaintext+ for the note.
get_note_contents
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def is_gzip(data) return false if !data.is_a?(String) return (data.length > 2 and data.bytes[0] == 0x1f and data.bytes[1] == 0x8B) end
# This function checks if specified +data+ is a GZip object by matching the first two bytes.
is_gzip
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def convert_core_time(core_time) return Time.at(0) unless core_time return Time.at(core_time + 978307200) end
# This function converts iOS Core Time, specified as an Integer +core_time+, to a Time object.
convert_core_time
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def decompress_data @decompressed_data = nil # Check for GZip magic number if is_gzip(@compressed_data) zlib_inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 16) begin @decompressed_data = zlib_inflater.inflate(@compressed_data) rescue StandardError => error # warn "\033[101m#{error}\033[m" # Prettified colors @logger.error("AppleNote: Note #{@note_id} somehow tried to decompress something that was GZIP but had to rescue error: #{error}") end else @logger.error("AppleNote: Note #{@note_id} somehow tried to decompress something that was not a GZIP") end end
# This function decompresses the orginally GZipped data present in +compressed_data+. It stores the result in +decompressed_data+
decompress_data
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def add_cryptographic_settings(crypto_iv, crypto_tag, crypto_salt, crypto_iterations, crypto_verifier, crypto_wrapped_key) @encrypted_data = @compressed_data # Move what was in compressed by default over to encrypted @compressed_data = nil @is_password_protected = true @crypto_iv = crypto_iv @crypto_tag = crypto_tag @crypto_salt = crypto_salt @crypto_iterations = crypto_iterations @crypto_key = crypto_verifier if crypto_verifier @crypto_key = crypto_wrapped_key if crypto_wrapped_key end
# This function adds cryptographic settings to the AppleNote. It expects a +crypto_iv+ as a binary String, a +crypto_tag+ as a binary String, a +crypto_salt+ as a binary String, the +crypto_iterations+ as an Integer, a +crypto_verifier+ as a binary String, and a +crypto_wrapped_key+ as a binary String. No AppleNote should ahve both a +crypto_verifier+ and a +crypto_wrapped_key+.
add_cryptographic_settings
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def has_cryptographic_variables? return (@is_password_protected and @encrypted_data and @crypto_iv and @crypto_tag and @crypto_salt and @crypto_iterations and @crypto_key) end
# This function ensures all cryptographic variables are set.
has_cryptographic_variables?
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def decrypt return false if !has_cryptographic_variables? decrypt_result = @backup.decrypter.decrypt(@crypto_salt, @crypto_iterations, @crypto_key, @crypto_iv, @crypto_tag, @encrypted_data, "Apple Note: #{@note_id}") # If we made a decrypt, then kick the result into our normal process to extract everything if decrypt_result @crypto_password = decrypt_result[:password] @compressed_data = decrypt_result[:plaintext] decompress_data extract_plaintext if @decompressed_data replace_embedded_objects if (@plaintext and @database) end return (plaintext != false) end
# This function attempts to decrypt the note by providing its cryptographic variables to the AppleDecrypter.
decrypt
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def has_tags @embedded_objects.each do |embedded_object| return true if embedded_object.is_a? AppleNotesEmbeddedInlineHashtag end return false end
# This method returns true if the AppleNote has any tags on it.
has_tags
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def get_all_tags to_return = [] @embedded_objects.each do |embedded_object| to_return.push(embedded_object) if embedded_object.is_a? AppleNotesEmbeddedInlineHashtag end return to_return end
# This method returns an Array of each AppleNotesEmbeddedInlineHashtag on the AppleNote.
get_all_tags
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def all_embedded_objects @embedded_objects + @embedded_objects_recursive end
# This method returns all the embedded objects in an AppleNote as an Array.
all_embedded_objects
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNote.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNote.rb
MIT
def initialize(primary_key, name, identifier) # Initialize some variables we may need later @crypto_salt = nil @crypto_iterations = nil @crypto_key = nil @password = nil @server_record_data = nil # Initialize notes and folders Arrays for this account @notes = Array.new() @folders = Array.new() @retain_order = false # Set this account's variables @primary_key = primary_key @name = name # Default html to empty until we build it @html = nil # Defaulting to the same value as the name, this can be overridden if the sort order is known @sort_order_name = name @identifier = identifier @user_record_name = "" # Figure out the Account's folder for attachments @account_folder = "Accounts/#{@identifier}/" # Uncomment the below line if you want to see the account names during creation # puts "Account #{@primary_key} is called #{@name}" end
# This creates a new AppleNotesAccount. It requires an Integer +primary_key+, a String +name+, and a String +identifier+ representing the ZIDENTIFIER column.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def add_crypto_variables(crypto_salt, crypto_iterations, crypto_key) @crypto_salt = crypto_salt @crypto_iterations = crypto_iterations @crypto_key = crypto_key end
# This method adds the cryptographic variables to the account. This is outside of initialize as older Apple Notes didn't have this functionality. This requires a String of binary +crypto_salt+, an Integer of the number of +iterations+, and a String of binary +crypto_key+. Do not feed in hex.
add_crypto_variables
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def clean_name @name.tr('/:\\', '_') end
# Returns a name with things removed that might allow for poorly placed files
clean_name
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def add_password(password) @password = password end
# This function takes a String +password+. It is unclear how or if this password matters right now.
add_password
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def add_folder(folder) # Remove any copy if we already have it @folders.delete_if {|old_folder| old_folder.primary_key == folder.primary_key} @folders.push(folder) end
# This method requies an AppleNotesFolder object as +folder+ and adds it to the accounts's Array.
add_folder
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def to_csv [@primary_key, @name, @user_record_name, @identifier, @cloudkit_last_modified_device, @notes.length, get_crypto_salt_hex, @crypto_iterations, get_crypto_key_hex] end
# This method generates an Array containing the information needed for CSV generation.
to_csv
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def get_crypto_key_hex return @crypto_key if ! @crypto_key @crypto_key.unpack("H*") end
# This returns the account's cryptowrapped key, if one exists, in hex.
get_crypto_key_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def get_crypto_salt_hex return @crypto_salt if ! @crypto_salt @crypto_salt.unpack("H*") end
# This returns the account's salt, if one exists, in hex.
get_crypto_salt_hex
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def sorted_folders return @folders if !@retain_order @folders.sort_by{|folder| [folder.sort_order]} end
# This method returns an Array containing the AppleNotesFolders for the account, sorted in appropriate order
sorted_folders
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def generate_html(individual_files: false, use_uuid: false) params = [individual_files, use_uuid] if @html && @html[params] return @html[params] end builder = Nokogiri::HTML::Builder.new(encoding: "utf-8") do |doc| doc.div { doc.h1 { doc.a(id: "account_#{@primary_key}") { doc.text @name } } if @user_record_name.length > 0 doc.div { doc.b { doc.text "Cloudkit Identifier:" } doc.text " " doc.text @user_record_name } end doc.div { doc.b { doc.text "Account Identifier:" } doc.text " " doc.text @identifier } if @cloudkit_last_modified_device doc.div { doc.b { doc.text "Last Modified Device:" } doc.text " " doc.text @cloudkit_last_modified_device } end doc.div { doc.b { doc.text "Number of Notes:" } doc.text " " doc.text @notes.length } doc.div { doc.b { doc.text "Folders:" } doc.ul { sorted_folders.each do |folder| doc << folder.generate_folder_hierarchy_html(individual_files: individual_files, use_uuid: use_uuid) if !folder.is_child? end } } } end @html ||= {} @html[params] = builder.doc.root end
# This method generates HTML to display on the overall output.
generate_html
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def prepare_json to_return = Hash.new() to_return[:primary_key] = @primary_key to_return[:name] = @name to_return[:identifier] = @identifier to_return[:cloudkit_identifier] = @user_record_name to_return[:cloudkit_last_modified_device] = @cloudkit_last_modified_device to_return[:html] = generate_html to_return end
# This method prepares the data structure that JSON will use to generate JSON later.
prepare_json
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesAccount.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesAccount.rb
MIT
def initialize(primary_key, uuid, uti, note, backup) # Set this folder's variables super(primary_key, uuid, uti, note) @filename = get_media_filename @filepath = get_media_filepath @backup = backup add_possible_location(@filepath) # Find where on this computer that file is stored tmp_stored_file_result = find_valid_file_path if tmp_stored_file_result @backup_location = tmp_stored_file_result.backup_location @filepath = tmp_stored_file_result.filepath @filename = tmp_stored_file_result.filename # Copy the file to our output directory if we can @reference_location = @backup.back_up_file(@filepath, @filename, @backup_location, @is_password_protected, @crypto_password, @crypto_salt, @crypto_iterations, @crypto_key, @crypto_asset_iv, @crypto_asset_tag) end end
# Creates a new AppleNotesEmbeddedCalendar object. Expects an Integer +primary_key+ from ZICCLOUDSYNCINGOBJECT.Z_PK, String +uuid+ from ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER, String +uti+ from ZICCLOUDSYNCINGOBJECT.ZTYPEUTI, AppleNote +note+ object representing the parent AppleNote, and AppleBackup +backup+ from the parent AppleNote. Immediately sets the +filename+ and +filepath+ to point to were the ics file is stored. Finally, it attempts to copy the file to the output folder.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedCalendar.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedCalendar.rb
MIT
def to_s to_s_with_data("iCal ICS") end
# This method just returns a readable String for the object. Adds to the AppleNotesEmbeddedObject.to_s by pointing to where the media is.
to_s
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedCalendar.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedCalendar.rb
MIT
def generate_html(individual_files=false) generate_html_with_link("iCal ICS", individual_files) end
# This method generates the HTML necessary to display the image inline.
generate_html
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedCalendar.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedCalendar.rb
MIT
def initialize(uuid, uti, note) # Set this object's variables super("Deleted", uuid, uti, note) end
# Creates a new AppleNotesEmbeddedDeletedObject object. Expects a +uuid+ that would have been the ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER, String +uti+ that would have been the ZICCLOUDSYNCINGOBJECT.ZTYPEUTI, and an AppleNote +note+ object representing the parent AppleNote.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDeletedObject.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDeletedObject.rb
MIT
def to_s return "{Deleted embedded #{@type} object which had ZICCLOUDSYNCINGOBJECTS.ZIDENTIFIER: #{uuid}}" end
# This method just returns a readable String for the object. Adds to the AppleNotesEmbeddedObject.to_s by pointing to where the media is.
to_s
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDeletedObject.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDeletedObject.rb
MIT
def initialize(primary_key, uuid, uti, note, backup) # Set this folder's variables super(primary_key, uuid, uti, note) @filename = get_media_filename @filepath = get_media_filepath @backup = backup add_possible_location(@filepath) # Find where on this computer that file is stored tmp_stored_file_result = find_valid_file_path if tmp_stored_file_result @backup_location = tmp_stored_file_result.backup_location @filepath = tmp_stored_file_result.filepath @filename = tmp_stored_file_result.filename # Copy the file to our output directory if we can @reference_location = @backup.back_up_file(@filepath, @filename, @backup_location, @is_password_protected, @crypto_password, @crypto_salt, @crypto_iterations, @crypto_key, @crypto_asset_iv, @crypto_asset_tag) end end
# Creates a new AppleNotesEmbeddedDocument object. Expects an Integer +primary_key+ from ZICCLOUDSYNCINGOBJECT.Z_PK, String +uuid+ from ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER, String +uti+ from ZICCLOUDSYNCINGOBJECT.ZTYPEUTI, AppleNote +note+ object representing the parent AppleNote, and AppleBackup +backup+ from the parent AppleNote. Immediately sets the +filename+ and +filepath+ to point to were the vcard is stored. Finally, it attempts to copy the file to the output folder.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDocument.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDocument.rb
MIT
def generate_html(individual_files=false) generate_html_with_link("Document", individual_files) end
# This method generates the HTML necessary to display the file download link.
generate_html
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDocument.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDocument.rb
MIT
def initialize(primary_key, uuid, uti, note, backup) # Set this folder's variables super(primary_key, uuid, uti, note) @filename = "" @filepath = "" @backup = backup @zgeneration = get_zgeneration_for_fallback_image compute_all_filepaths tmp_stored_file_result = find_valid_file_path if tmp_stored_file_result @filepath = tmp_stored_file_result.filepath @filename = tmp_stored_file_result.filename @backup_location = tmp_stored_file_result.backup_location @reference_location = @backup.back_up_file(@filepath, @filename, @backup_location, @is_password_protected, @crypto_password, @crypto_salt, @crypto_iterations, @crypto_key, @crypto_fallback_iv, @crypto_fallback_tag) end end
# Creates a new AppleNotesEmbeddedDrawing object. Expects an Integer +primary_key+ from ZICCLOUDSYNCINGOBJECT.Z_PK, String +uuid+ from ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER, String +uti+ from ZICCLOUDSYNCINGOBJECT.ZTYPEUTI, AppleNote +note+ object representing the parent AppleNote, and AppleBackup +backup+ from the parent AppleNote. Immediately sets the +filename+ and +filepath+ to point to were the media is stored. Finally, it attempts to copy the file to the output folder.
initialize
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDrawing.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDrawing.rb
MIT
def add_cryptographic_settings @database.execute("SELECT ZICCLOUDSYNCINGOBJECT.ZCRYPTOINITIALIZATIONVECTOR, ZICCLOUDSYNCINGOBJECT.ZCRYPTOTAG, " + "ZICCLOUDSYNCINGOBJECT.ZCRYPTOSALT, ZICCLOUDSYNCINGOBJECT.ZCRYPTOITERATIONCOUNT, " + "ZICCLOUDSYNCINGOBJECT.ZCRYPTOVERIFIER, ZICCLOUDSYNCINGOBJECT.ZCRYPTOWRAPPEDKEY, " + "ZICCLOUDSYNCINGOBJECT.ZFALLBACKIMAGECRYPTOTAG, ZICCLOUDSYNCINGOBJECT.ZFALLBACKIMAGECRYPTOINITIALIZATIONVECTOR " + "FROM ZICCLOUDSYNCINGOBJECT " + "WHERE Z_PK=?", @primary_key) do |media_row| @crypto_iv = media_row["ZCRYPTOINITIALIZATIONVECTOR"] @crypto_tag = media_row["ZCRYPTOTAG"] @crypto_fallback_iv = media_row["ZFALLBACKIMAGECRYPTOINITIALIZATIONVECTOR"] @crypto_fallback_tag = media_row["ZFALLBACKIMAGECRYPTOTAG"] @crypto_salt = media_row["ZCRYPTOSALT"] @crypto_iterations = media_row["ZCRYPTOITERATIONCOUNT"] @crypto_key = media_row["ZCRYPTOVERIFIER"] if media_row["ZCRYPTOVERIFIER"] @crypto_key = media_row["ZCRYPTOWRAPPEDKEY"] if media_row["ZCRYPTOWRAPPEDKEY"] end @crypto_password = @note.crypto_password end
# This function overrides the default AppleNotesEmbeddedObject add_cryptographic_settings to include the fallback image settings from ZFALLBACKIMAGECRYPTOTAG and ZFALLBACKIMAGECRYPTOINITIALIZATIONVECTOR for content on disk.
add_cryptographic_settings
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDrawing.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDrawing.rb
MIT
def get_media_uuid return get_media_uuid_from_zidentifer(@uuid) end
# Uses database calls to fetch the actual media object's ZICCLOUDSYNCINGOBJECT.ZIDENTIFIER +uuid+. This requires taking the ZICCLOUDSYNCINGOBJECT.ZMEDIA field on the entry with this object's +uuid+ and reading the ZICCOUDSYNCINGOBJECT.ZIDENTIFIER of the row identified by that number in the ZICCLOUDSYNCINGOBJECT.Z_PK field.
get_media_uuid
ruby
threeplanetssoftware/apple_cloud_notes_parser
lib/AppleNotesEmbeddedDrawing.rb
https://github.com/threeplanetssoftware/apple_cloud_notes_parser/blob/master/lib/AppleNotesEmbeddedDrawing.rb
MIT