iphone_backup.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. const path = require('path')
  2. const sqlite3 = require('sqlite3')
  3. const bplist = require('bplist-parser')
  4. const fs = require('fs')
  5. const plist = require('plist')
  6. const tz_offset = 5
  7. const databases = {
  8. SMS: '3d0d7e5fb2ce288813306e4d4636395e047a3d28',
  9. Contacts: '31bb7ba8914766d4ba40d6dfb6113c8b614be442',
  10. Calendar: '2041457d5fe04d39d0ab481178355df6781e6858',
  11. Reminders: '2041457d5fe04d39d0ab481178355df6781e6858',
  12. Notes: 'ca3bc056d4da0bbf88b5fb3be254f3b7147e639c',
  13. Notes2: '4f98687d8ab0d6d1a371110e6b7300f6e465bef2',
  14. Calls: '2b2b0084a1bc3a5ac8c27afdf14afb42c61a19ca',
  15. Calls2: '5a4935c78a5255723f707230a451d79c540d2741',
  16. Locations: '4096c9ec676f2847dc283405900e284a7c815836',
  17. WebHistory: 'e74113c185fd8297e140cfcf9c99436c5cc06b57',
  18. Photos: '12b144c0bd44f2b3dffd9186d3f9c05b917cee25',
  19. WiFi: 'ade0340f576ee14793c607073bd7e8e409af07a8',
  20. Voicemail: '992df473bbb9e132f4b3b6e4d33f72171e97bc7a'
  21. }
  22. var cache = {}
  23. class iPhoneBackup {
  24. constructor (id, status, info, manifest, base) {
  25. this.id = id
  26. this.status = status
  27. this.info = info
  28. this.manifest = manifest
  29. this.base = base
  30. }
  31. // Open a backup with a specified ID
  32. // base is optional and will be computed if not used.
  33. static fromID (id, base) {
  34. // Get the path of the folder.
  35. if (base) {
  36. base = path.join(base, id)
  37. } else {
  38. base = path.join(process.env.HOME, '/Library/Application Support/MobileSync/Backup/', id)
  39. }
  40. // Parse manifest bplist files
  41. try {
  42. if (global.verbose) console.log('parsing status', base)
  43. var status = bplist.parseBuffer(fs.readFileSync(path.join(base, 'Status.plist')))[0]
  44. } catch (e) {
  45. console.log('Cannot open Status.plist', e)
  46. }
  47. try {
  48. if (global.verbose) console.log('parsing manifest', base)
  49. var manifest = bplist.parseBuffer(fs.readFileSync(path.join(base, 'Manifest.plist')))[0]
  50. } catch (e) {
  51. console.log('Cannot open Manifest.plist', e)
  52. }
  53. try {
  54. if (global.verbose) console.log('parsing status', base)
  55. var info = plist.parse(fs.readFileSync(path.join(base, 'Info.plist'), 'utf8'))
  56. } catch (e) {
  57. console.log('Cannot open Info.plist', e)
  58. }
  59. return new iPhoneBackup(id, status, info, manifest, base)
  60. }
  61. get iOSVersion () {
  62. return this.manifest.Lockdown.ProductVersion
  63. }
  64. getFileName (fileID, isAbsoulte) {
  65. isAbsoulte = isAbsoulte || false
  66. //const base = path.join(process.env.HOME, '/Library/Application Support/MobileSync/Backup/', this.id)
  67. // Return v2 filename
  68. if (this.status.Version < 3 || isAbsoulte) {
  69. return path.join(this.base, fileID)
  70. } else {
  71. // v3 has folders
  72. return path.join(this.base, fileID.substr(0, 2), fileID)
  73. }
  74. }
  75. getDatabase (fileID, isAbsoulte) {
  76. isAbsoulte = isAbsoulte || false
  77. // Get the backup folder
  78. // Return v2 filename
  79. if (this.status.Version < 3 || isAbsoulte) {
  80. return new sqlite3.Database(path.join(this.base, fileID), sqlite3.OPEN_READONLY)
  81. } else {
  82. // v3 has folders
  83. return new sqlite3.Database(path.join(this.base, fileID.substr(0, 2), fileID), sqlite3.OPEN_READONLY)
  84. }
  85. }
  86. queryDatabase (databaseID, sql) {
  87. return new Promise((resolve, reject) => {
  88. var messagedb = this.getDatabase(databaseID)
  89. messagedb.all(sql, async function (err, rows) {
  90. if (err) reject(err)
  91. resolve(rows)
  92. })
  93. })
  94. }
  95. getName (messageDest) {
  96. return new Promise((resolve, reject) => {
  97. if (messageDest.indexOf('@') === -1) {
  98. messageDest = messageDest.replace(/[\s+\-()]*/g, '')
  99. if (messageDest.length == 11 && messageDest[0] == '1') {
  100. messageDest = messageDest.substring(1)
  101. }
  102. }
  103. if (cache[messageDest] !== undefined) {
  104. return resolve(cache[messageDest])
  105. }
  106. var contactdb = this.getDatabase(databases.Contacts)
  107. contactdb.get(`SELECT
  108. c0First as first,
  109. c1Last as last,
  110. c2Middle as middle,
  111. c15Phone as phones
  112. from ABPersonFullTextSearch_content WHERE c15Phone like '%${messageDest}%'`,
  113. (err, row) => {
  114. if (err) return resolve()
  115. if (!row) return resolve()
  116. var result = {
  117. name: [row.first, row.middle, row.last].filter(el => el != null).join(' '),
  118. phones: row.phones.split(' '),
  119. query: messageDest
  120. }
  121. if (row) cache[messageDest] = result
  122. resolve(result)
  123. })
  124. })
  125. }
  126. getMessagesiOS9 (chatId) {
  127. var backup = this
  128. return new Promise((resolve, reject) => {
  129. var messagedb = this.getDatabase(databases.SMS)
  130. messagedb.all(`
  131. SELECT
  132. message.*,
  133. handle.id as sender_name,
  134. datetime(date + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING
  135. FROM chat_message_join
  136. INNER JOIN message
  137. ON message.rowid = chat_message_join.message_id
  138. INNER JOIN handle
  139. ON handle.rowid = message.handle_id
  140. WHERE chat_message_join.chat_id = ?`, [parseInt(chatId)],
  141. async function (err, chats) {
  142. if (err) return reject(err)
  143. chats = chats || []
  144. // Compute the user's name
  145. for (var i in chats) {
  146. var el = chats[i]
  147. el.x_sender = el.is_from_me ? 'Me' : el.sender_name
  148. if (!el.is_from_me) {
  149. var contact = await backup.getName(el.sender_name)
  150. if (contact) {
  151. el.x_sender = `${contact.name} <${contact.query}>`
  152. }
  153. }
  154. }
  155. resolve(chats)
  156. })
  157. })
  158. }
  159. getMessagesiOS10iOS11 (chatId) {
  160. var backup = this
  161. return new Promise((resolve, reject) => {
  162. var messagedb = this.getDatabase(databases.SMS)
  163. messagedb.all(`
  164. SELECT
  165. message.*,
  166. handle.id as sender_name,
  167. datetime(date / 1000000000 + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING
  168. FROM chat_message_join
  169. INNER JOIN message
  170. ON message.rowid = chat_message_join.message_id
  171. INNER JOIN handle
  172. ON handle.rowid = message.handle_id
  173. WHERE chat_message_join.chat_id = ?`, [parseInt(chatId)],
  174. async function (err, chats) {
  175. if (err) return reject(err)
  176. chats = chats || []
  177. // Compute the user's name
  178. for (var i in chats) {
  179. var el = chats[i]
  180. el.x_sender = el.is_from_me ? 'Me' : el.sender_name
  181. if (!el.is_from_me) {
  182. var contact = await backup.getName(el.sender_name)
  183. if (contact) {
  184. el.x_sender = `${contact.name} <${contact.query}>`
  185. }
  186. }
  187. }
  188. resolve(chats)
  189. })
  190. })
  191. }
  192. getMessages (chatId) {
  193. if (parseInt(this.manifest.Lockdown.BuildVersion) <= 13) {
  194. return this.getMessagesiOS9(chatId)
  195. } else {
  196. return this.getMessagesiOS10iOS11(chatId)
  197. }
  198. }
  199. getConversationsiOS9 () {
  200. var backup = this
  201. return new Promise((resolve, reject) => {
  202. var messagedb = this.getDatabase(databases.SMS)
  203. messagedb.all(`SELECT * FROM chat ORDER BY ROWID ASC`, async function (err, rows) {
  204. if (err) return reject(err)
  205. rows = rows || []
  206. // We need to do some manual parsing of these records.
  207. // The timestamp information is stored in a binary blob named `properties`
  208. // Which is formatted as a binary PLIST.
  209. for (var el of rows) {
  210. if (el.properties) el.properties = bplist.parseBuffer(el.properties)[0]
  211. // Interestingly, some of these do not have dates attached.
  212. if (el.properties) {
  213. el.date = new Date(el.properties.CKChatWatermarkTime * 1000)
  214. } else {
  215. el.date = new Date(0)
  216. }
  217. var contact = await backup.getName(el.chat_identifier)
  218. if (contact) {
  219. el.display_name = `${contact.name} <${contact.query}>`
  220. }
  221. // Format as YY-MM-DD HH:MM:SS
  222. try {
  223. el.XFORMATTEDDATESTRING = el.date.toISOString()
  224. .split('T')
  225. .join(' ')
  226. .split('Z')
  227. .join(' ')
  228. .split('.')[0]
  229. .trim()
  230. } catch (e) {
  231. el.XFORMATTEDDATESTRING = ''
  232. }
  233. }
  234. // Sort by the date.
  235. rows = rows.sort(function (a, b) {
  236. return (a.date.getTime() || 0) - (b.date.getTime() || 0)
  237. })
  238. resolve(rows)
  239. })
  240. })
  241. }
  242. getConversationsiOS10iOS11 () {
  243. return new Promise((resolve, reject) => {
  244. var messagedb = this.getDatabase(databases.SMS)
  245. messagedb.all(`SELECT *, datetime(last_read_message_timestamp / 1000000000 + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING FROM chat ORDER BY last_read_message_timestamp ASC`, async function (err, rows) {
  246. if (err) return reject(err)
  247. rows = rows || []
  248. resolve(rows)
  249. })
  250. })
  251. }
  252. getConversations () {
  253. if (parseInt(this.manifest.Lockdown.BuildVersion) <= 14) {
  254. return this.getConversationsiOS9()
  255. } else {
  256. return this.getConversationsiOS10iOS11()
  257. }
  258. }
  259. getFileManifest () {
  260. return new Promise((resolve, reject) => {
  261. var messagedb = this.getDatabase('Manifest.db', true)
  262. messagedb.all('SELECT * from FILES', async function (err, rows) {
  263. if (err) reject(err)
  264. resolve(rows)
  265. })
  266. })
  267. }
  268. getOldNotes () {
  269. return new Promise((resolve, reject) => {
  270. var messagedb = this.getDatabase(databases.Notes)
  271. messagedb.all(`SELECT *, datetime(ZCREATIONDATE + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING from ZNOTE LEFT JOIN ZNOTEBODY ON ZBODY = ZNOTEBODY.Z_PK`, async function (err, rows) {
  272. if (err) reject(err)
  273. resolve(rows)
  274. })
  275. })
  276. }
  277. getNewNotesiOS9 () {
  278. return new Promise((resolve, reject) => {
  279. var messagedb = this.getDatabase(databases.Notes2)
  280. messagedb.all(`SELECT *, datetime(ZCREATIONDATE + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING FROM ZICCLOUDSYNCINGOBJECT`, async function (err, rows) {
  281. if (err) reject(err)
  282. resolve(rows)
  283. })
  284. })
  285. }
  286. getNewNotesiOS10iOS11 () {
  287. return new Promise((resolve, reject) => {
  288. var messagedb = this.getDatabase(databases.Notes2)
  289. messagedb.all(`SELECT *, datetime(ZCREATIONDATE + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING, datetime(ZCREATIONDATE1 + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING1 FROM ZICCLOUDSYNCINGOBJECT`, async function (err, rows) {
  290. if (err) reject(err)
  291. resolve(rows)
  292. })
  293. })
  294. }
  295. getNotes () {
  296. if (parseInt(this.manifest.Lockdown.BuildVersion) <= 13) {
  297. // Legacy iOS 9 support
  298. // May work for earlier but I haven't tested it
  299. return this.getNewNotesiOS9()
  300. } else {
  301. return this.getNewNotesiOS10iOS11()
  302. }
  303. }
  304. getWebHistory () {
  305. return new Promise((resolve, reject) => {
  306. var messagedb = this.getDatabase(databases.WebHistory)
  307. messagedb.all(`SELECT *, datetime(visit_time + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING from history_visits LEFT JOIN history_items ON history_items.ROWID = history_visits.history_item`, async function (err, rows) {
  308. if (err) reject(err)
  309. resolve(rows)
  310. })
  311. })
  312. }
  313. getPhotoLocationHistory () {
  314. return new Promise((resolve, reject) => {
  315. var messagedb = this.getDatabase(databases.Photos)
  316. messagedb.all(`SELECT ZDATECREATED, ZLATITUDE, ZLONGITUDE, ZFILENAME, datetime(ZDATECREATED + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING FROM ZGENERICASSET ORDER BY ZDATECREATED ASC`, async function (err, rows) {
  317. if (err) reject(err)
  318. resolve(rows)
  319. })
  320. })
  321. }
  322. getGeofencesList () {
  323. return new Promise((resolve, reject) => {
  324. var messagedb = this.getDatabase(databases.Locations)
  325. messagedb.all(`SELECT datetime(Timestamp + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING, Latitude, Longitude, Distance FROM Fences ORDER BY Timestamp ASC`, async function (err, rows) {
  326. if (err) reject(err)
  327. resolve(rows)
  328. })
  329. })
  330. }
  331. getCallsList () {
  332. return new Promise((resolve, reject) => {
  333. var messagedb = this.getDatabase(databases.Calls2)
  334. messagedb.all(`SELECT *, datetime(ZDATE + 978307200, 'unixepoch') AS XFORMATTEDDATESTRING from ZCALLRECORD ORDER BY ZDATE ASC`, async function (err, rows) {
  335. if (err) reject(err)
  336. resolve(rows)
  337. })
  338. })
  339. }
  340. getVoicemailsList () {
  341. return new Promise((resolve, reject) => {
  342. var messagedb = this.getDatabase(databases.Voicemail)
  343. messagedb.all(`SELECT *, datetime(date, 'unixepoch') AS XFORMATTEDDATESTRING from voicemail ORDER BY date ASC`, async function (err, rows) {
  344. if (err) reject(err)
  345. resolve(rows)
  346. })
  347. })
  348. }
  349. getVoicemailFileList () {
  350. return new Promise((resolve, reject) => {
  351. var messagedb = this.getDatabase('Manifest.db', true)
  352. messagedb.all(`SELECT * from FILES where relativePath like 'Library/Voicemail/%.amr'`, async function (err, rows) {
  353. if (err) reject(err)
  354. resolve(rows)
  355. })
  356. })
  357. }
  358. getWifiList () {
  359. return new Promise((resolve, reject) => {
  360. var filename = this.getFileName(databases.WiFi)
  361. try {
  362. resolve(bplist.parseBuffer(fs.readFileSync(filename))[0])
  363. } catch (e) {
  364. reject(e)
  365. }
  366. })
  367. }
  368. }
  369. module.exports.availableBackups = function () {
  370. const base = path.join(process.env.HOME, '/Library/Application Support/MobileSync/Backup/')
  371. return new Promise((resolve, reject) => {
  372. resolve(fs.readdirSync(base, { encoding: 'utf8' })
  373. .map(file => iPhoneBackup.fromID(file)))
  374. })
  375. }
  376. module.exports.iPhoneBackup = iPhoneBackup