database.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. # -*- coding: utf-8 -*-
  2. """
  3. #
  4. # Simple password manager
  5. # Encrypted database
  6. #
  7. # Copyright (c) 2011-2023 Michael Büsch <m@bues.ch>
  8. # Licensed under the GNU/GPL version 2 or later.
  9. #
  10. """
  11. from libpwman.cryptsql import *
  12. from libpwman.exception import *
  13. from libpwman.util import *
  14. import csv
  15. import io
  16. import os
  17. import pathlib
  18. import sys
  19. from copy import deepcopy
  20. from dataclasses import dataclass
  21. __all__ = [
  22. "CSQLError",
  23. "PWManDatabase",
  24. "PWManEntry",
  25. "PWManEntryAttr",
  26. "PWManEntryBulk",
  27. "PWManEntryTOTP",
  28. "getDefaultDatabase",
  29. ]
  30. def getDefaultDatabase():
  31. """Get the default database path.
  32. Returns a pathlib.Path() instance.
  33. """
  34. db = os.getenv("PWMAN_DATABASE")
  35. if db:
  36. return pathlib.Path(db)
  37. home = pathlib.Path.home()
  38. if home:
  39. return home / ".pwman.db"
  40. return pathlib.Path(".pwman.db")
  41. @dataclass
  42. class PWManEntry:
  43. """Database entry data structure.
  44. """
  45. category : str
  46. title : str
  47. user : str = None
  48. pw : str = None
  49. entryId : int = None
  50. @dataclass
  51. class PWManEntryAttr:
  52. """Entry attribute data structure.
  53. """
  54. name : str
  55. data : str = None
  56. entry : PWManEntry = None
  57. attrId : int = None
  58. @dataclass
  59. class PWManEntryBulk:
  60. """Entry bulk-data data structure.
  61. """
  62. data : str = None
  63. entry : PWManEntry = None
  64. bulkId : int = None
  65. @dataclass
  66. class PWManEntryTOTP:
  67. """Entry TOTP-data data structure.
  68. """
  69. key : str
  70. digits : int = 6
  71. hmacHash : str = "SHA1"
  72. entry : PWManEntry = None
  73. totpId : int = None
  74. class PWManDatabase(CryptSQL):
  75. """Encrypted pwman database.
  76. """
  77. DB_TYPE = "PWMan database"
  78. DB_VER = ("0", "1")
  79. def __init__(self, filename, passphrase, key=None, readOnly=True, silent=False):
  80. """filename: Path to the database file.
  81. If it does not exist, a new file is created.
  82. passphrase: The passphrase string for the database file.
  83. key: An optional key to use instead of the passphrase. Don't use it.
  84. readOnly: Open the filename read-only. Commits will raise an exception.
  85. silent: Do not print information messages to the console.
  86. """
  87. try:
  88. super().__init__(readOnly=readOnly)
  89. self.__silent = silent
  90. self.__dirty = False
  91. self.__openFile(filename, passphrase, key)
  92. except (CSQLError) as e:
  93. raise PWManError(str(e))
  94. def __openFile(self, filename, passphrase, key):
  95. """Open the database file and parse the contents.
  96. """
  97. super().setPassphrase(passphrase)
  98. self.setKey(key)
  99. self.open(filename)
  100. self.__setDirty(False)
  101. initDBVer = False
  102. if self.sqlIsEmpty():
  103. initDBVer = True
  104. else:
  105. dbType = self.getGlobalAttr("db_type")
  106. dbVer = self.getGlobalAttr("db_version")
  107. if dbType is None and dbVer is None: # Compat v0
  108. dbType = self.DB_TYPE
  109. dbVer = self.DB_VER[0]
  110. if (dbType != self.DB_TYPE or
  111. dbVer not in self.DB_VER):
  112. raise PWManError("Unsupported database version '%s / %s'. "
  113. "Expected '%s / %s'" % (
  114. str(dbType),
  115. str(dbVer),
  116. self.DB_TYPE,
  117. ", ".join(self.DB_VER)))
  118. if dbVer != self.DB_VER[-1]:
  119. self.__migrateVersion(dbVer)
  120. initDBVer = True
  121. self.__initTables()
  122. if initDBVer:
  123. self.setGlobalAttr("db_type", self.DB_TYPE, setDirty=False)
  124. self.setGlobalAttr("db_version", self.DB_VER[-1], setDirty=False)
  125. def __migrateVersion(self, dbVer):
  126. """Migrate the database format to the latest version.
  127. """
  128. if dbVer == self.DB_VER[0]:
  129. if not self.__silent:
  130. print("Migrating database from version %s to version %s..." % (
  131. dbVer, self.DB_VER[-1]),
  132. file=sys.stderr)
  133. self.__initTables()
  134. c = self.sqlExec("SELECT DISTINCT category FROM pw ORDER BY category;")
  135. categories = c.fetchAll()
  136. for (category, ) in categories:
  137. c = self.sqlExec("SELECT title FROM pw WHERE category=? ORDER BY title;",
  138. (category,))
  139. titles = c.fetchAll()
  140. for (title, ) in titles:
  141. c = self.sqlExec("SELECT category, title, user, pw, bulk FROM pw "
  142. "WHERE category=? AND title=? "
  143. "LIMIT 1;",
  144. (category, title))
  145. data = c.fetchOne()
  146. if not data:
  147. continue
  148. c = self.sqlExec("INSERT INTO entries(category, title, user, pw) "
  149. "VALUES(?,?,?,?);",
  150. (data[0], data[1], data[2], data[3]))
  151. entryId = c.lastRowID()
  152. if data[4]:
  153. c = self.sqlExec("INSERT INTO bulk(entry, data) "
  154. "VALUES(?,?);",
  155. (entryId, data[4]))
  156. c = self.sqlExec("SELECT name, data FROM info;")
  157. infos = c.fetchAll()
  158. for name, data in infos:
  159. c = self.sqlExec("INSERT INTO globalattr(name, data) VALUES(?,?);",
  160. (name, data))
  161. c = self.sqlExec("DROP TABLE IF EXISTS pw;")
  162. c = self.sqlExec("DROP TABLE IF EXISTS info;")
  163. self.sqlVacuum()
  164. else:
  165. assert(0)
  166. def __initTables(self):
  167. """Create the SQL tables, if they don't exist.
  168. """
  169. c = self.sqlExecScript("""
  170. CREATE TABLE IF NOT EXISTS
  171. globalattr(id INTEGER PRIMARY KEY AUTOINCREMENT,
  172. name TEXT, data TEXT);
  173. CREATE TABLE IF NOT EXISTS
  174. entries(id INTEGER PRIMARY KEY AUTOINCREMENT,
  175. category TEXT, title TEXT, user TEXT, pw TEXT);
  176. CREATE TABLE IF NOT EXISTS
  177. bulk(id INTEGER PRIMARY KEY AUTOINCREMENT,
  178. entry INTEGER, data TEXT);
  179. CREATE TABLE IF NOT EXISTS
  180. entryattr(id INTEGER PRIMARY KEY AUTOINCREMENT,
  181. entry INTEGER, name TEXT, data TEXT);
  182. CREATE TABLE IF NOT EXISTS
  183. totp(id INTEGER PRIMARY KEY AUTOINCREMENT,
  184. entry INTEGER, key TEXT, digits INTEGER, hash TEXT);
  185. """)
  186. def __garbageCollect(self):
  187. """Remove rows from the SQL database that are not needed anymore.
  188. """
  189. # Do not use sqlExecScript here, as that would commit transactions.
  190. c = self.sqlExec("DELETE FROM bulk WHERE entry NOT IN (SELECT id FROM entries);")
  191. c = self.sqlExec("DELETE FROM entryattr WHERE entry NOT IN (SELECT id FROM entries);")
  192. c = self.sqlExec("DELETE FROM totp WHERE entry NOT IN (SELECT id FROM entries);")
  193. def setPassphrase(self, passphrase):
  194. super().setPassphrase(passphrase)
  195. self.__setDirty()
  196. def categoryExists(self, category):
  197. """Returns True, if a category exists in the database.
  198. category: The name string of the category.
  199. """
  200. c = self.sqlExec("SELECT EXISTS(SELECT 1 FROM entries "
  201. "WHERE category=? "
  202. "LIMIT 1);",
  203. (category,))
  204. data = c.fetchOne()
  205. return data and data[0]
  206. def getCategoryNames(self):
  207. """Get all category names in the database.
  208. Returns a sorted list of strings.
  209. """
  210. c = self.sqlExec("SELECT DISTINCT category FROM entries "
  211. "ORDER BY category;")
  212. return [ data[0] for data in c.fetchAll() ]
  213. def getEntryTitles(self, category):
  214. """Get all titles from one category in the database.
  215. category: The category name string.
  216. Returns a sorted list of strings.
  217. """
  218. c = self.sqlExec("SELECT title FROM entries "
  219. "WHERE category=? "
  220. "ORDER BY title;",
  221. (category,))
  222. return [ data[0] for data in c.fetchAll() ]
  223. def getEntry(self, category, title):
  224. """Get an entry from the database.
  225. category: The name string of the category to get an entry from.
  226. title: The title string of the entry to get.
  227. Returns a PWManEntry() instance.
  228. """
  229. c = self.sqlExec("SELECT id, category, title, user, pw FROM entries "
  230. "WHERE category=? AND title=? "
  231. "LIMIT 1;",
  232. (category,
  233. title))
  234. data = c.fetchOne()
  235. if not data:
  236. return None
  237. return PWManEntry(category=data[1],
  238. title=data[2],
  239. user=data[3],
  240. pw=data[4],
  241. entryId=data[0])
  242. def findEntries(self, pattern,
  243. useRegexp=False,
  244. search=True,
  245. inCategory=None,
  246. matchCategory=False,
  247. matchTitle=False,
  248. matchUser=False,
  249. matchPw=False,
  250. matchBulk=False,
  251. matchAttrName=False,
  252. matchAttrData=False):
  253. """Search the database for entries that match a pattern.
  254. useRegexp: If True, then the pattern is a regular expression string.
  255. If False, then the pattern is a SQL LIKE pattern string.
  256. inCategory: If specified as non-zero length string, then only search
  257. the category with this name.
  258. matchCategory: Match the pattern to the category name string of an entry.
  259. matchTitle: Match the pattern to the title string of an entry.
  260. matchUser: Match the pattern to the user string of an entry.
  261. matchPw: Match the pattern to the password string of an entry.
  262. matchBulk: Match the pattern to the bulk data string of an entry.
  263. matchAttrName: Match the pattern to all attribute name strings of an entry.
  264. matchAttrData: Match the pattern to all attribute data strings of an entry.
  265. Returns a list of PWManEntry() instances that match the pattern.
  266. """
  267. if useRegexp:
  268. self.setRegexpFlags(search=search,
  269. ignoreCase=True,
  270. multiLine=True,
  271. dotAll=True)
  272. else:
  273. if search:
  274. pattern = "%" + pattern + "%"
  275. def dump(sql, params):
  276. pass
  277. # print(sql, "\nparams =", params)
  278. def match(leftHand):
  279. if useRegexp:
  280. return "%s REGEXP ?" % leftHand
  281. return "%s LIKE ?" % leftHand
  282. IDs = set()
  283. if matchCategory or matchTitle or matchUser or matchPw:
  284. conditions = []
  285. if matchCategory:
  286. conditions.append( (match("entries.category"), pattern) )
  287. if matchTitle:
  288. conditions.append( (match("entries.title"), pattern) )
  289. if matchUser:
  290. conditions.append( (match("entries.user"), pattern) )
  291. if matchPw:
  292. conditions.append( (match("entries.pw"), pattern) )
  293. sql = "SELECT id FROM entries WHERE "
  294. params = []
  295. if inCategory:
  296. sql += "category=? AND "
  297. params.append(inCategory)
  298. sql += "( " + (" OR ".join(c[0] for c in conditions)) + " );"
  299. params.extend(c[1] for c in conditions)
  300. dump(sql, params)
  301. c = self.sqlExec(sql, params)
  302. IDs.update(entryId[0] for entryId in (c.fetchAll() or []))
  303. if matchBulk:
  304. conditions = [ (match("bulk.data"), pattern) ]
  305. sql = "SELECT entries.id "\
  306. "FROM entries, bulk "\
  307. "WHERE bulk.entry = entries.id AND "
  308. params = []
  309. if inCategory:
  310. sql += "entries.category = ? AND "
  311. params.append(inCategory)
  312. sql += match("bulk.data") + ";"
  313. params.append(pattern)
  314. dump(sql, params)
  315. c = self.sqlExec(sql, params)
  316. IDs.update(entryId[0] for entryId in (c.fetchAll() or []))
  317. if matchAttrName or matchAttrData:
  318. conditions = []
  319. if matchAttrName:
  320. conditions.append( (match("entryattr.name"), pattern) )
  321. if matchAttrData:
  322. conditions.append( (match("entryattr.data"), pattern) )
  323. sql = "SELECT entries.id "\
  324. "FROM entries, entryattr "\
  325. "WHERE entryattr.entry = entries.id AND "
  326. params = []
  327. if inCategory:
  328. sql += "entries.category = ? AND "
  329. params.append(inCategory)
  330. sql += "( " + (" OR ".join(c[0] for c in conditions)) + " );"
  331. params.extend(c[1] for c in conditions)
  332. dump(sql, params)
  333. c = self.sqlExec(sql, params)
  334. IDs.update(entryId[0] for entryId in (c.fetchAll() or []))
  335. if not IDs:
  336. return []
  337. IDs = sorted(IDs) # stable sorting
  338. sql = "SELECT entries.id, entries.category, "\
  339. "entries.title, entries.user, entries.pw "\
  340. "FROM entries "\
  341. "WHERE entries.id IN ( "
  342. sql += ", ".join("?" for ID in IDs)
  343. sql += " );"
  344. params = [ str(ID) for ID in IDs ]
  345. dump(sql, params)
  346. c = self.sqlExec(sql, params)
  347. dataSet = c.fetchAll()
  348. if not dataSet:
  349. return []
  350. return [ PWManEntry(category=data[1],
  351. title=data[2],
  352. user=data[3],
  353. pw=data[4],
  354. entryId=data[0])
  355. for data in dataSet ]
  356. def entryExists(self, category, title):
  357. """Returns True, if an entry exists in the database.
  358. category: The name string of the category.
  359. title: The title string of the entry.
  360. """
  361. c = self.sqlExec("SELECT EXISTS(SELECT 1 FROM entries "
  362. "WHERE category=? AND title=? "
  363. "LIMIT 1);",
  364. (category,
  365. title))
  366. data = c.fetchOne()
  367. return data and data[0]
  368. def addEntry(self, entry):
  369. """Create a new entry in the database.
  370. entry: A PWManEntry() instance.
  371. """
  372. if self.entryExists(entry.category, entry.title):
  373. raise PWManError("Entry does already exist")
  374. c = self.sqlExec("INSERT INTO entries(category, title, user, pw) "
  375. "VALUES(?,?,?,?);",
  376. (entry.category,
  377. entry.title,
  378. entry.user,
  379. entry.pw))
  380. entry.entryId = c.lastRowID()
  381. self.__setDirty()
  382. def editEntry(self, entry):
  383. """Update the contents of an existing entry.
  384. entry: A PWManEntry() containing the new data of the entry/
  385. """
  386. oldEntry = self.getEntry(entry.category, entry.title)
  387. if not oldEntry:
  388. raise PWManError("Entry does not exist")
  389. if entry.user is None:
  390. entry.user = oldEntry.user
  391. if entry.pw is None:
  392. entry.pw = oldEntry.pw
  393. entry.entryId = oldEntry.entryId
  394. c = self.sqlExec("UPDATE entries SET "
  395. "category=?, title=?, user=?, pw=? "
  396. "WHERE id=?;",
  397. (entry.category,
  398. entry.title,
  399. entry.user,
  400. entry.pw,
  401. entry.entryId))
  402. self.__setDirty()
  403. def moveEntry(self, entry, newCategory, newTitle, toDb=None, copy=False):
  404. """Move or copy an existing entry to a new category and/or set a new entry title.
  405. entry: The PWManEntry() instance to move/copy.
  406. newCategory: The target category name string.
  407. newTitle: The target title string.
  408. toDb: The target database. Defaults to self.
  409. copy: If False, then move. If True, then copy.
  410. """
  411. toDb = toDb or self
  412. if toDb.entryExists(newCategory, newTitle):
  413. raise PWManError("Entry does already exist.")
  414. oldEntry = self.getEntry(entry.category, entry.title)
  415. if not oldEntry:
  416. raise PWManError("Entry does not exist.")
  417. if toDb is self and not copy:
  418. entry.category = newCategory
  419. entry.title = newTitle
  420. c = self.sqlExec("UPDATE entries SET "
  421. "category=?, title=? "
  422. "WHERE id=?;",
  423. (entry.category,
  424. entry.title,
  425. oldEntry.entryId))
  426. self.__setDirty()
  427. else:
  428. newEntry = deepcopy(oldEntry)
  429. bulk = self.getEntryBulk(newEntry)
  430. attrs = self.getEntryAttrs(newEntry)
  431. totp = self.getEntryTotp(newEntry)
  432. newEntry.entryId = None
  433. newEntry.category = newCategory
  434. newEntry.title = newTitle
  435. toDb.addEntry(newEntry)
  436. if bulk:
  437. bulk.bulkId = None
  438. toDb.setEntryBulk(bulk)
  439. for attr in attrs:
  440. attr.attrId = None
  441. toDb.setEntryAttr(attr)
  442. if totp:
  443. totp.totpId = None
  444. toDb.setEntryTotp(totp)
  445. if not copy:
  446. entry.entryId = newEntry.entryId
  447. entry.category = newEntry.category
  448. entry.title = newEntry.title
  449. self.delEntry(oldEntry)
  450. def moveEntries(self, fromCategory, toCategory, toDb=None, copy=False):
  451. """Move or copy all entries from one category to another category.
  452. fromCategory: The category to move all entries from.
  453. toCategory: The (new) category to move all entries to.
  454. toDb: The target database. Defaults to self.
  455. copy: If False, then move. If True, then copy.
  456. """
  457. toDb = toDb or self
  458. if not self.categoryExists(fromCategory):
  459. raise PWManError("Source category does not exist.")
  460. if toDb is self and fromCategory == toCategory:
  461. return
  462. fromTitles = self.getEntryTitles(fromCategory)
  463. for fromTitle in fromTitles:
  464. if toDb.entryExists(toCategory, fromTitle):
  465. raise PWManError("Target entry %s/%s does already exist." % (
  466. toCategory, fromTitle))
  467. if toDb is self and not copy:
  468. c = self.sqlExec("UPDATE entries SET category=? "
  469. "WHERE category=?;",
  470. (toCategory,
  471. fromCategory))
  472. self.__setDirty()
  473. else:
  474. for fromTitle in fromTitles:
  475. entry = self.getEntry(fromCategory, fromTitle)
  476. bulk = self.getEntryBulk(entry)
  477. attrs = self.getEntryAttrs(entry)
  478. totp = self.getEntryTotp(entry)
  479. entry.entryId = None
  480. entry.category = toCategory
  481. toDb.addEntry(entry)
  482. if bulk:
  483. bulk.bulkId = None
  484. toDb.setEntryBulk(bulk)
  485. for attr in attrs:
  486. attr.attrId = None
  487. toDb.setEntryAttr(attr)
  488. if totp:
  489. totp.totpId = None
  490. toDb.setEntryTotp(totp)
  491. if not copy:
  492. for fromTitle in fromTitles:
  493. entry = self.getEntry(fromCategory, fromTitle)
  494. self.delEntry(entry)
  495. def delEntry(self, entry):
  496. """Delete an existing entry from the database.
  497. entry: The PWManEntry() instance to delete from the database.
  498. """
  499. c = self.sqlExec("SELECT id FROM entries "
  500. "WHERE category=? AND title=? "
  501. "LIMIT 1;",
  502. (entry.category,
  503. entry.title))
  504. entryId = c.fetchOne()
  505. if entryId is None:
  506. raise PWManError("Entry does not exist")
  507. entryId = entryId[0]
  508. c = self.sqlExec("DELETE FROM entries WHERE id=?;",
  509. (entryId,))
  510. self.__garbageCollect()
  511. self.__setDirty()
  512. def getEntryBulk(self, entry):
  513. """Get the bulk data associated with an entry.
  514. entry: The PWManEntry() to get the bulk data for.
  515. Returns a PWManEntryBulk() instance or None, if there is no bulk data.
  516. """
  517. c = self.sqlExec("SELECT bulk.id, bulk.data "
  518. "FROM bulk, entries "
  519. "WHERE entries.category=? AND entries.title=? AND "
  520. "bulk.entry = entries.id "
  521. "LIMIT 1;",
  522. (entry.category,
  523. entry.title))
  524. data = c.fetchOne()
  525. if not data:
  526. return None
  527. return PWManEntryBulk(data=data[1],
  528. entry=entry,
  529. bulkId=data[0])
  530. def setEntryBulk(self, entryBulk):
  531. """Set the bulk data associated with an entry.
  532. entryBulk: The new PWManEntryBulk() instance to write to the database.
  533. If entryBulk.data is None, then the bulk data is deleted.
  534. """
  535. entry = entryBulk.entry
  536. if not entry or entry.entryId is None:
  537. raise PWManError("Bulk: Entry does not exist.")
  538. if entryBulk.data:
  539. c = self.sqlExec("SELECT id FROM bulk WHERE entry=? LIMIT 1;",
  540. (entry.entryId, ))
  541. bulkId = c.fetchOne()
  542. if bulkId is None:
  543. c = self.sqlExec("INSERT INTO bulk(entry, data) "
  544. "VALUES(?,?);",
  545. (entry.entryId,
  546. entryBulk.data))
  547. else:
  548. bulkId = bulkId[0]
  549. c = self.sqlExec("UPDATE bulk "
  550. "SET entry=?, data=? "
  551. "WHERE id=?;",
  552. (entry.entryId,
  553. entryBulk.data,
  554. bulkId))
  555. else:
  556. c = self.sqlExec("DELETE FROM bulk WHERE id=?;",
  557. (entryBulk.bulkId,))
  558. self.__setDirty()
  559. def getEntryTotp(self, entry):
  560. """Get the TOTP parameters associated with an entry.
  561. entry: The PWManEntry() to get the TOTP parameters for.
  562. Returns a PWManEntryTOTP() instance, or None if there is no TOTP data.
  563. """
  564. c = self.sqlExec("SELECT totp.id, totp.key, totp.digits, totp.hash "
  565. "FROM totp, entries "
  566. "WHERE entries.category=? AND entries.title=? AND "
  567. "totp.entry = entries.id "
  568. "LIMIT 1;",
  569. (entry.category,
  570. entry.title))
  571. data = c.fetchOne()
  572. if not data:
  573. return None
  574. return PWManEntryTOTP(key=data[1],
  575. digits=data[2],
  576. hmacHash=data[3],
  577. entry=entry,
  578. totpId=data[0])
  579. def setEntryTotp(self, entryTotp):
  580. """Set the TOTP data associated with an entry.
  581. entryTotp: The new PWManEntryTOTP() instance to write to the database.
  582. If entryTotp.key is None, then the TOTP data is deleted.
  583. """
  584. entry = entryTotp.entry
  585. if not entry or entry.entryId is None:
  586. raise PWManError("TOTP: Entry does not exist.")
  587. if entryTotp.key:
  588. c = self.sqlExec("SELECT id FROM totp WHERE entry=? LIMIT 1;",
  589. (entry.entryId, ))
  590. totpId = c.fetchOne()
  591. if totpId is None:
  592. c = self.sqlExec("INSERT INTO totp(entry, key, digits, hash) "
  593. "VALUES(?,?,?,?);",
  594. (entry.entryId,
  595. entryTotp.key,
  596. entryTotp.digits,
  597. entryTotp.hmacHash))
  598. else:
  599. totpId = totpId[0]
  600. c = self.sqlExec("UPDATE totp "
  601. "SET entry=?, key=?, digits=?, hash=? "
  602. "WHERE id=?;",
  603. (entry.entryId,
  604. entryTotp.key,
  605. entryTotp.digits,
  606. entryTotp.hmacHash,
  607. totpId))
  608. else:
  609. c = self.sqlExec("DELETE FROM totp WHERE id=?;",
  610. (entryTotp.totpId,))
  611. self.__setDirty()
  612. def getEntryAttr(self, entry, attrName):
  613. """Get an attribute associated with an entry.
  614. entry: The PWManEntry() to get the attribute for.
  615. attrName: The name string of the attribute to get.
  616. Returns a PWManEntryAttr() instance, or None if there is such attribute.
  617. """
  618. c = self.sqlExec("SELECT entryattr.id, entryattr.name, entryattr.data "
  619. "FROM entryattr, entries "
  620. "WHERE entries.category=? AND entries.title=? AND "
  621. "entryattr.entry = entries.id AND entryattr.name=? "
  622. "LIMIT 1;",
  623. (entry.category,
  624. entry.title,
  625. attrName))
  626. data = c.fetchOne()
  627. if not data:
  628. return None
  629. return PWManEntryAttr(name=data[1],
  630. data=data[2],
  631. entry=entry,
  632. attrId=data[0])
  633. def getEntryAttrs(self, entry):
  634. """Get all attributes associated with an entry.
  635. entry: The PWManEntry() to get the attributes for.
  636. Returns a list of PWManEntryAttr() instances,
  637. or an empty list if there are no attributes.
  638. """
  639. c = self.sqlExec("SELECT entryattr.id, entryattr.name, entryattr.data "
  640. "FROM entryattr, entries "
  641. "WHERE entries.category=? AND entries.title=? AND "
  642. "entryattr.entry = entries.id;",
  643. (entry.category,
  644. entry.title))
  645. dataSet = c.fetchAll()
  646. if not dataSet:
  647. return []
  648. return [ PWManEntryAttr(name=data[1],
  649. data=data[2],
  650. entry=entry,
  651. attrId=data[0])
  652. for data in dataSet ]
  653. def setEntryAttr(self, entryAttr):
  654. """Set an attribute associated with an entry.
  655. entryAttr: The new PWManEntryAttr() instance to write to the database.
  656. If entryAttr.data is None, then the attribute is deleted.
  657. """
  658. entry = entryAttr.entry
  659. if not entry or entry.entryId is None:
  660. raise PWManError("Attr: Entry does not exist.")
  661. if entryAttr.data:
  662. c = self.sqlExec("SELECT id FROM entryattr "
  663. "WHERE entry=? AND name=? "
  664. "LIMIT 1;",
  665. (entry.entryId,
  666. entryAttr.name))
  667. attrId = c.fetchOne()
  668. if attrId is None:
  669. c = self.sqlExec("INSERT INTO entryattr(entry, name, data) "
  670. "VALUES(?,?,?);",
  671. (entry.entryId,
  672. entryAttr.name,
  673. entryAttr.data))
  674. else:
  675. attrId = attrId[0]
  676. c = self.sqlExec("UPDATE entryattr "
  677. "SET entry=?, name=?, data=? "
  678. "WHERE id=?;",
  679. (entry.entryId,
  680. entryAttr.name,
  681. entryAttr.data,
  682. attrId))
  683. else:
  684. c = self.sqlExec("DELETE FROM entryattr WHERE id=?;",
  685. (entryAttr.attrId,))
  686. self.__setDirty()
  687. def getGlobalAttr(self, name):
  688. """Get a global attribute.
  689. A global attribute is not associated with an entry.
  690. Returns None, if the attribute does not exist.
  691. """
  692. try:
  693. c = self.sqlExec("SELECT id, data FROM globalattr "
  694. "WHERE name=? "
  695. "LIMIT 1;",
  696. (name,))
  697. data = c.fetchOne()
  698. return data[1] if data else None
  699. except (CSQLError) as e:
  700. return None
  701. def setGlobalAttr(self, name, data, setDirty=True):
  702. """Set a global attribute.
  703. A global attribute is not associated with an entry.
  704. If data is None or empty, the attribute is deleted from the database.
  705. """
  706. if data:
  707. c = self.sqlExec("SELECT id FROM globalattr "
  708. "WHERE name=? "
  709. "LIMIT 1;",
  710. (name,))
  711. attrId = c.fetchOne()
  712. if attrId is None:
  713. c = self.sqlExec("INSERT INTO globalattr(name, data) "
  714. "VALUES(?,?);",
  715. (name, data))
  716. else:
  717. attrId = attrId[0]
  718. c = self.sqlExec("UPDATE globalattr "
  719. "SET data=? "
  720. "WHERE name=?;",
  721. (data, name))
  722. else:
  723. c = self.sqlExec("DELETE FROM globalattr WHERE name=?;",
  724. (name,))
  725. if setDirty:
  726. self.__setDirty()
  727. def __setDirty(self, d=True):
  728. """Set the flag for uncommitted data.
  729. """
  730. self.__dirty = d
  731. def isDirty(self):
  732. """Returns True, if the database contains uncommitted data.
  733. """
  734. return self.__dirty
  735. def flunkDirty(self):
  736. """Print a warning, if the database contains uncommitted data.
  737. Then set the flag for uncommitted data to False.
  738. """
  739. if self.isDirty():
  740. print("WARNING: Dropping uncommitted data",
  741. file=sys.stderr)
  742. self.__setDirty(False)
  743. def dropUncommitted(self):
  744. super().dropUncommitted()
  745. self.__setDirty(False)
  746. def commit(self):
  747. self.__garbageCollect()
  748. super().commit()
  749. self.__setDirty(False)
  750. def importSqlScript(self, *args, **kwargs):
  751. self.__setDirty()
  752. super().importSqlScript(*args, **kwargs)
  753. def getOnDiskDb(self):
  754. """Get a read-only instance of PWManDatabase that contains
  755. the current on-disk data. The on-disk data is the data
  756. at the last commit.
  757. """
  758. db = self.__class__(filename=self.getFilename(),
  759. passphrase=self.getPassphrase(),
  760. key=self.getKey(),
  761. readOnly=True,
  762. silent=True)
  763. return db
  764. def dumpEntry(self, entry, showTotpKey=False):
  765. """Returns a human readable dump string of an entry.
  766. If showTotpKey=True: Also dump the TOTP key and parameters.
  767. """
  768. res = []
  769. res.append("=== %s ===" % entry.category)
  770. res.append("\t--- %s ---" % entry.title)
  771. if entry.user:
  772. res.append("\tUser:\t\t%s" % entry.user)
  773. if entry.pw:
  774. res.append("\tPassword:\t%s" % entry.pw)
  775. entryBulk = self.getEntryBulk(entry)
  776. if entryBulk:
  777. res.append("\tBulk data:\t%s" % entryBulk.data)
  778. entryTotp = self.getEntryTotp(entry)
  779. if entryTotp:
  780. if showTotpKey:
  781. res.append("\tTOTP key:\t%s" % entryTotp.key)
  782. res.append("\tTOTP digits:\t%d" % entryTotp.digits)
  783. res.append("\tTOTP hash:\t%s" % entryTotp.hmacHash)
  784. else:
  785. res.append("\tTOTP:\t\tavailable")
  786. entryAttrs = self.getEntryAttrs(entry)
  787. if entryAttrs:
  788. res.append("\tAttributes:")
  789. maxLen = max(len(a.name) for a in entryAttrs)
  790. for entryAttr in entryAttrs:
  791. align = maxLen - len(entryAttr.name)
  792. res.append("\t %s:%s %s" % (
  793. entryAttr.name,
  794. align * " ",
  795. entryAttr.data))
  796. return "\n".join(res) + "\n"
  797. def dumpEntries(self, showTotpKey=False):
  798. """Returns a human readable dump string of all entries.
  799. If showTotpKey=True: Also dump the TOTP key and parameters.
  800. """
  801. ret = []
  802. for category in self.getCategoryNames():
  803. for title in self.getEntryTitles(category):
  804. entry = self.getEntry(category, title)
  805. dump = self.dumpEntry(entry, showTotpKey)
  806. ret.append(dump)
  807. return "\n".join(ret)
  808. def dumpEntriesCsv(self, showTotpKey=False):
  809. """Returns a CSV format dump string of all entries.
  810. If showTotpKey=True: Also dump the TOTP key and parameters.
  811. """
  812. csvHeads = [
  813. "Category",
  814. "Title",
  815. "User",
  816. "Password",
  817. "Bulk data",
  818. "TOTP key",
  819. "TOTP digits",
  820. "TOTP hash",
  821. ]
  822. rows = []
  823. attrNames = set()
  824. for category in self.getCategoryNames():
  825. for title in self.getEntryTitles(category):
  826. entry = self.getEntry(category, title)
  827. row = {
  828. "Category" : entry.category,
  829. "Title" : entry.title,
  830. "User" : entry.user,
  831. "Password" : entry.pw,
  832. }
  833. entryBulk = self.getEntryBulk(entry)
  834. if entryBulk:
  835. row["Bulk data"] = entryBulk.data
  836. entryTotp = self.getEntryTotp(entry)
  837. if entryTotp:
  838. if showTotpKey:
  839. row["TOTP key"] = entryTotp.key
  840. row["TOTP digits"] = entryTotp.digits
  841. row["TOTP hash"] = entryTotp.hmacHash
  842. else:
  843. row["TOTP key"] = "available"
  844. entryAttrs = self.getEntryAttrs(entry)
  845. if entryAttrs:
  846. for entryAttr in entryAttrs:
  847. attrNames.add(entryAttr.name)
  848. row[entryAttr.name] = entryAttr.data
  849. rows.append(row)
  850. csvHeads.extend(sorted(attrNames))
  851. f = io.StringIO()
  852. w = csv.DictWriter(f, fieldnames=csvHeads, dialect="excel")
  853. w.writeheader()
  854. for r in rows:
  855. w.writerow(r)
  856. return f.getvalue()