Import Firefox passwords to KeepassX

I wanted to import my Firefox password into KeepassX. After looking around for a while I decided to write my own little script.

It converts the exported Firefox XML file into another XML structure liked by KeepassX.

Here the steps:

1. Install “Password Exporter 1.2.1” from Justin Scott (fligtar)

2. Export your Firefox password into an XML file e.g. “ff_passwords-export.xml”

3. Run the Ruby script to change the Firefox’s exported XML file into one understandable by KeepassX.

$ convert-firefox-pwd-to-keepassx.rb > keepass-import-pwd.xml

3. Run KeepassX and import passwords from the file “keepass-import-pwd.xml”.

The passwords will be imported into a special group called “Imported from Firefox”. If you don’t like it, just change the name in the script.

Here convert-firefox-pwd-to-keepassx.rb

$ cat convert-firefox-pwd-to-keepassx.rb

#!/bin/env ruby

require 'rexml/document'
require 'digest/md5'

xml = File.read('ff_passwords-export.xml')
doc = REXML::Document.new(xml)

head = ""
foot = ""

head += "<!DOCTYPE KEEPASSX_DATABASE>\n"
head += "<database>\n"
head += " <group>\n"
head += "  <title>Imported from Firefox</title>\n"
head += "  <icon>1</icon>\n"

puts head

doc.elements.each("xml/entries/entry") do |e| 
    entry = ""
    if e.attributes['httpRealm'] != "" 
        title = e.attributes['httpRealm']
    else
        title = e.attributes['formSubmitURL']
    end
    url = e.attributes['host']
    username = e.attributes['user']
    password = e.attributes['password']
    notes = "Form Submit URL: " + e.attributes['formSubmitURL'] + " HTTP Realm: " + e.attributes['httpRealm'] + " User Field Name: " + e.attributes['userFieldName'] +  " Pass Field Name: "+ e.attributes['passFieldName']
    import_time = Time.new.utc.strftime("%Y-%m-%dT%H:%M:%S")
      uuid = Digest::MD5.hexdigest(import_time+username+url+notes)
    entry += "  <entry>\n"
    entry += "   <title>#{title}</title>\n"
    entry += "   <username>#{username}</username>\n"
    entry += "   <url>#{url}</url>\n"
    entry += "   <password>#{password}</password>\n"
    entry += "   <comment>#{notes}</comment>\n"
    entry += "   <icon>0</icon>\n"
    entry += "   <creation>#{import_time}</creation>\n"
    entry += "   <lastmod>#{import_time}</lastmod>\n"
    entry += "   <lastaccess>#{import_time}</lastaccess>\n"
    entry += "   <expire>never</expire>\n"
    entry += "  </entry>\n"
    puts entry
end

foot += " </group>\n"
foot += "</database>\n"

puts foot

This script is written in Ruby but it doesn’t contain any fancy stuff and easily adaptable into almost any language e.g. Perl, Bash, awk, sed, …