Personal book of passwords

main.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/md5"
  6. "crypto/sha512"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "os"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "text/template"
  17. )
  18. type Site struct {
  19. Host string `json:host`
  20. MinimumLength int `json:minimumLength`
  21. MaximumLength int `json:maximumLength`
  22. SpecialCharacters string `json:specialCharacters`
  23. NumberOfSpecialCharacters int `json:numberOfSpecialCharacters`
  24. NumberOfUpperCase int `json:numberOfUpperCase`
  25. NumberOfDigits int `json:numberOfDigits`
  26. Revision int `json:revision`
  27. Password string `json:",omitempty"`
  28. }
  29. type Page struct {
  30. Profile string
  31. Passphrase string
  32. Sites []Site
  33. }
  34. func main() {
  35. http.HandleFunc("/api/generate", func(w http.ResponseWriter, r *http.Request) {
  36. profile := r.FormValue("profile")
  37. passphrase := r.FormValue("p")
  38. host := r.FormValue("host")
  39. minimumLength, _ := strconv.Atoi(r.FormValue("minimumLength"))
  40. maximumLength, _ := strconv.Atoi(r.FormValue("maximumLength"))
  41. minimumDigits, _ := strconv.Atoi(r.FormValue("minimumDigits"))
  42. minimumUppercase, _ := strconv.Atoi(r.FormValue("minimumUppercase"))
  43. minimumSpecialCharacters, _ := strconv.Atoi(r.FormValue("minimumSpecialCharacters"))
  44. specialCharacters := r.FormValue("specialCharacters")
  45. if profile == "" || passphrase == "" || host == "" {
  46. http.Error(w, "Missing credentials", http.StatusUnauthorized)
  47. return
  48. }
  49. site := Site{
  50. Host: host,
  51. MinimumLength: minimumLength,
  52. MaximumLength: maximumLength,
  53. SpecialCharacters: specialCharacters,
  54. NumberOfSpecialCharacters: minimumSpecialCharacters,
  55. NumberOfDigits: minimumDigits,
  56. NumberOfUpperCase: minimumUppercase,
  57. Revision: 0,
  58. }
  59. book := getBookname(profile)
  60. sites, err := read(book, passphrase)
  61. if err != nil {
  62. http.Error(w, err.Error(), http.StatusInternalServerError)
  63. return
  64. }
  65. sites = append(sites, site)
  66. err = save(book, passphrase, sites)
  67. if err != nil {
  68. http.Error(w, err.Error(), http.StatusInternalServerError)
  69. return
  70. }
  71. http.Redirect(w, r, "/", 200)
  72. })
  73. http.HandleFunc("/api/update", func(w http.ResponseWriter, r *http.Request) {
  74. profile := r.FormValue("profile")
  75. passphrase := r.FormValue("p")
  76. newPassphrase := r.FormValue("newPassphrase")
  77. confirmPassphrase := r.FormValue("confirmPassphrase")
  78. cmd := r.FormValue("cmd")
  79. if profile == "" || passphrase == "" || newPassphrase == "" || confirmPassphrase == "" || cmd == "" {
  80. http.Error(w, "Missing credentials", http.StatusUnauthorized)
  81. return
  82. }
  83. book := getBookname(profile)
  84. if cmd == "delete" {
  85. err := os.Remove(book)
  86. if err != nil {
  87. // Return an error
  88. http.Error(w, err.Error(), http.StatusInternalServerError)
  89. return
  90. }
  91. } else if cmd == "update" {
  92. if newPassphrase != confirmPassphrase {
  93. }
  94. sites, err := read(book, passphrase)
  95. if err != nil {
  96. http.Error(w, err.Error(), http.StatusInternalServerError)
  97. return
  98. }
  99. err = save(book, newPassphrase, sites)
  100. if err != nil {
  101. http.Error(w, err.Error(), http.StatusInternalServerError)
  102. return
  103. }
  104. }
  105. http.Redirect(w, r, "/", 200)
  106. })
  107. http.HandleFunc("/api/refresh", func(w http.ResponseWriter, r *http.Request) {
  108. profile := r.FormValue("profile")
  109. passphrase := r.FormValue("p")
  110. host := r.FormValue("host")
  111. if profile == "" || passphrase == "" || host == "" {
  112. http.Error(w, "Missing credentials", http.StatusUnauthorized)
  113. return
  114. }
  115. // Update the revision number and generate a new password
  116. book := getBookname(profile)
  117. sites, err := read(book, passphrase)
  118. if err != nil {
  119. http.Error(w, err.Error(), http.StatusInternalServerError)
  120. return
  121. }
  122. for _, site := range sites {
  123. if site.Host == host {
  124. site.Revision++
  125. break
  126. }
  127. }
  128. err = save(book, passphrase, sites)
  129. if err != nil {
  130. http.Error(w, err.Error(), http.StatusInternalServerError)
  131. return
  132. }
  133. http.Redirect(w, r, "/", 200)
  134. })
  135. http.HandleFunc("/api/remove", func(w http.ResponseWriter, r *http.Request) {
  136. profile := r.FormValue("profile")
  137. passphrase := r.FormValue("p")
  138. host := r.FormValue("host")
  139. if profile == "" || passphrase == "" || host == "host" {
  140. http.Error(w, "Missing credentials", http.StatusUnauthorized)
  141. return
  142. }
  143. // Remove the site from our book and save it
  144. book := getBookname(profile)
  145. sites, err := read(book, passphrase)
  146. if err != nil {
  147. http.Error(w, err.Error(), http.StatusInternalServerError)
  148. return
  149. }
  150. for i, site := range sites {
  151. if site.Host == host {
  152. sites = append(sites[:i], sites[i+1:]...)
  153. break
  154. }
  155. }
  156. err = save(book, passphrase, sites)
  157. if err != nil {
  158. http.Error(w, err.Error(), http.StatusInternalServerError)
  159. return
  160. }
  161. http.Redirect(w, r, "/", 200)
  162. })
  163. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  164. profile := r.FormValue("profile")
  165. passphrase := r.FormValue("p")
  166. if profile == "" || passphrase == "" {
  167. fmt.Fprintf(w, templateIndex)
  168. } else {
  169. book := getBookname(profile)
  170. sites, err := read(book, passphrase)
  171. if err != nil {
  172. http.Error(w, err.Error(), http.StatusInternalServerError)
  173. return
  174. }
  175. for _, s := range sites {
  176. p, err := generatePassphrase(profile, passphrase, s)
  177. if err != nil {
  178. }
  179. s.Password = fmt.Sprintf("%s", string(p))
  180. }
  181. page := Page{
  182. Profile: profile,
  183. Passphrase: passphrase,
  184. Sites: sites,
  185. }
  186. t := template.Must(template.New("book").Parse(templateBook))
  187. err = t.Execute(w, page)
  188. if err != nil {
  189. http.Error(w, err.Error(), http.StatusInternalServerError)
  190. return
  191. }
  192. }
  193. })
  194. log.Fatal(http.ListenAndServe("localhost:8080", nil))
  195. }
  196. func save(file, passphrase string, sites []Site) error {
  197. // If the file doesn't exist then create it
  198. if _, err := os.Stat(file); os.IsNotExist(err) {
  199. _, err = os.Create(file)
  200. if err != nil {
  201. return err
  202. }
  203. }
  204. // Marshal the JSON
  205. b, err := json.Marshal(sites)
  206. if err != nil {
  207. return err
  208. }
  209. // Compress the contents
  210. var buffer bytes.Buffer
  211. gzip := gzip.NewWriter(&buffer)
  212. if err != nil {
  213. return err
  214. }
  215. gzip.Write(b)
  216. gzip.Close()
  217. // Write to the file
  218. fi, err := os.OpenFile(file, os.O_WRONLY, 0666)
  219. if err != nil {
  220. return err
  221. }
  222. _, err = fi.Write(buffer.Bytes())
  223. if err != nil {
  224. return err
  225. }
  226. fi.Close()
  227. return nil
  228. }
  229. // Read the password book
  230. func read(file, passphrase string) ([]Site, error) {
  231. // If the file doesn't exist yet no worries
  232. if _, err := os.Stat(file); os.IsNotExist(err) {
  233. return []Site{}, nil
  234. }
  235. // Bring in the compressed data
  236. fi, err := os.Open(file)
  237. if err != nil {
  238. return nil, err
  239. }
  240. // Decompress the file contents
  241. gzip, err := gzip.NewReader(fi)
  242. if err != nil {
  243. return nil, err
  244. }
  245. decompressed, err := ioutil.ReadAll(gzip)
  246. gzip.Close()
  247. // Unmarshal the JSON information
  248. var sites []Site
  249. err = json.Unmarshal(decompressed, &sites)
  250. if err != nil {
  251. return nil, err
  252. }
  253. fi.Close()
  254. return sites, nil
  255. }
  256. // Get the book name
  257. func getBookname(profile string) string {
  258. hash := md5.New()
  259. hash.Write([]byte(profile))
  260. return fmt.Sprintf("%x", string(hash.Sum(nil)))
  261. }
  262. // Encrypt the password book
  263. func encrypt(clearText, profile, passphrase string) ([]byte, error) {
  264. return nil, nil
  265. }
  266. // Decrypt the password book
  267. func decrypt(encryptedText, profile, passphrase string) ([]byte, error) {
  268. return nil, nil
  269. }
  270. // Generate the passphrase
  271. func generatePassphrase(profile, passphrase string, settings Site) ([]byte, error) {
  272. clearText := fmt.Sprintf(
  273. "%s-%s-%s-%s",
  274. strings.ToLower(profile),
  275. strings.ToLower(passphrase),
  276. strings.ToLower(settings.Host),
  277. settings.Revision)
  278. sha := sha512.New()
  279. sha.Write([]byte(clearText))
  280. hash := sha.Sum(nil)
  281. hash = []byte(fmt.Sprintf("%x", hash))
  282. // Apply site criteria
  283. applySiteSettings(hash, settings)
  284. // If there is a maximum length truncate the hash
  285. if settings.MaximumLength > -1 {
  286. hash = hash[:settings.MaximumLength]
  287. }
  288. // Ensure the length is adequate
  289. if !validateLength(hash, settings.MinimumLength, settings.MaximumLength) {
  290. log.Println("Does not meed the length requirements")
  291. }
  292. return hash, nil
  293. }
  294. // Apply site settings to the hashed value
  295. func applySiteSettings(source []byte, settings Site) []byte {
  296. if !containsUppercase(source, settings.NumberOfUpperCase) {
  297. i := 0
  298. r := regexp.MustCompile(`[a-z]+`)
  299. var matches [][]int
  300. if matches = r.FindAllIndex(source, -1); matches != nil {
  301. for _, v := range matches {
  302. if i < settings.NumberOfUpperCase {
  303. c := strings.ToUpper(string(source[v[0]]))
  304. source[v[0]] = []byte(c)[0]
  305. i += 1
  306. }
  307. }
  308. }
  309. }
  310. if !containsDigits(source, settings.NumberOfDigits) {
  311. i := 0
  312. r := regexp.MustCompile(`[a-z]+`)
  313. var matches [][]int
  314. if matches = r.FindAllIndex(source, -1); matches != nil {
  315. for _, v := range matches {
  316. if i < settings.NumberOfDigits {
  317. source[v[0]] = byte(i)
  318. i += 1
  319. }
  320. }
  321. }
  322. }
  323. if !containsSpecialCharacters(source, settings.SpecialCharacters, settings.NumberOfSpecialCharacters) {
  324. i := 0
  325. r := regexp.MustCompile(`[a-z]+`)
  326. var matches [][]int
  327. if matches = r.FindAllIndex(source, -1); matches != nil {
  328. for _, v := range matches {
  329. if i < settings.NumberOfSpecialCharacters {
  330. i += 1
  331. source[v[0]] = []byte(settings.SpecialCharacters)[len(settings.SpecialCharacters)-i]
  332. }
  333. }
  334. }
  335. }
  336. return source
  337. }
  338. // Determine if the hash currently contains the appropriate amount of digits
  339. func containsDigits(source []byte, minOccurrences int) bool {
  340. r := regexp.MustCompile(`\d`)
  341. var matches [][]byte
  342. if matches = r.FindAll(source, -1); matches == nil {
  343. return false
  344. }
  345. return len(matches) >= minOccurrences
  346. }
  347. // Determine if the hash currently contains the appropriate amount of uppercase characters
  348. func containsUppercase(source []byte, minOccurrences int) bool {
  349. r := regexp.MustCompile(`[A-Z]+`)
  350. var matches [][]byte
  351. if matches = r.FindAll(source, -1); matches == nil {
  352. return false
  353. }
  354. return len(matches) >= minOccurrences
  355. }
  356. // Determine if the hash currently contains the appropriate amount of special characters from the allowed
  357. // character set
  358. func containsSpecialCharacters(source []byte, specialCharacters string, minOccurrences int) bool {
  359. s := specialCharacters
  360. s = strings.Replace(s, "\\", "\\\\", -1)
  361. s = strings.Replace(s, ".", "\\.", -1)
  362. s = strings.Replace(s, " ", "\\s", -1)
  363. s = strings.Replace(s, "-", "\\-", -1)
  364. s = strings.Replace(s, "[", "\\[", -1)
  365. s = strings.Replace(s, "]", "\\]", -1)
  366. r := regexp.MustCompile(`[` + s + `]+`)
  367. var matches [][]byte
  368. if matches = r.FindAll(source, -1); matches == nil {
  369. return false
  370. }
  371. return len(matches) >= minOccurrences
  372. }
  373. // Determine if the hash currently abides by the length restrictions
  374. func validateLength(source []byte, minimum, maximum int) bool {
  375. if minimum > -1 && len(source) < minimum {
  376. return false
  377. }
  378. if maximum > -1 && len(source) > maximum {
  379. return false
  380. }
  381. return true
  382. }