GithubHelp home page GithubHelp logo

lifepillar / csvkeychain Goto Github PK

View Code? Open in Web Editor NEW
344.0 25.0 48.0 54 KB

Import/export between Apple Keychain.app and plain CSV file.

AppleScript 80.50% Ruby 19.50%
security csv keychain apple password export import keepass

csvkeychain's Introduction

CSVKeychain AppleScript script

This repo contains scripts to export all your password items and secure notes from Apple's Keychain.app into plain text files in CSV format, merge such files and import them back into a keychain.

No trick or reverse engineering is used: exporting is performed by Apple's security tool, using macOS's assistive support to streamline the process.

The current master should work in (High) Sierra. Earlier versions of macOS/OS X are not supported.

How to use

To import/export password items, open the AppleScript script in Script Editor. The script may be run from source.

Before running the script, go to System Preferences > Security & Privacy > Privacy > Accessibility, and allow Script Editor to control your computer. This step is required to avoid SecurityAgent to prompt you with a dialog for each item you want to export. It basically allows AppleScript to press the Allow button in such dialogs for you.

You may also build the script into an application if you want. In this case, you must grant the app control of your computer in the same way.

The script always asks for the password to unlock your keychain (you recognise the dialog by the Script Editor icon). Since that dialog is not very secure, it is recommended that you change your keychain's password in Keychain.app before exporting your keychain, and restore the original password afterwards. You may also be asked to unlock your keychain by SecurityAgent (which you do by providing your keychain's password). So, you may have to enter your keychain's password once or twice. After that, SecurityAgent will keep prompting for a password for each exported item, but the script should fill it out for you automatically, so no further action from you will be required.

The script makes a backup of the keychain before importing or exporting data. Backups are timestamped and saved into the same folder containing the keychain. In any case, it is a good idea to keep a separate backup, just in case.

When importing items into a keychain, matching items already present in the keychain are overwritten if their timestamps are older than the timestamps of the items being imported. If there are items without timestamps in the CSV file, the script will ask the user what to do with them. Note that this will be asked once and the choice applied to all the items being imported.

Also note that all new or updated items are assigned the current time as their new timestamps. There is no possibility to retain the original timestamps from the CSV file.

Finally, access control lists are not exported.

Troubleshooting

If you get this error:

This script will be terminated prematurely because the following error has
occurred:

security: SecKeychainUnlock [...]: The user name or
passphrase you entered is not correct. (Error number: 51)

open Keychain.app and lock your keychain. Then, run the script again.

Merging files

A Ruby script is provided to merge two CSV files containing password data into one. See ./merge_csv.rb --help for the details.

Is it possible to export the Local Items (aka iCloud) keychain?

Note: the workaround described in this section does not appear to work in macOS High Sierra or later. You may have better luck with Get passwords from iCloud keychain directly and Get passwords from Safari.

Not directly. The Local Items keychain, located at ~/Library/Keychains/<UUID>/<name>.db, is a SQLite database containing obfuscated data, so its format is different from the format of a standard keychain. As far as I can see, security cannot dump such keychains, and I do not know of any tool that would do that.

You may proceed as follows:

  1. In Keychain.app, create a new keychain: File > New Keychain…
  2. Select the Local Items keychain in the sidebar, then select all the items (or the ones you want to export) and copy them by choosing Edit > Copy.
  3. Select the keychain created at step one and choose Edit > Paste.

Such process is painful, though, because Keychain.app will keep asking for a password for each item. You may automate such process with a bit of scripting. For your convenience, the script that allows you to fill in the password prompts for you is reported below:

tell application "System Events"
	repeat while exists (processes where name is "SecurityAgent")
		tell process "SecurityAgent"
			set frontmost to true
			try
				keystroke "PUT YOUR KEYCHAIN'S PASSWORD HERE"
				delay 0.1
				keystroke return
				delay 0.1
			on error
				-- do nothing to skip the error
			end try
		end tell
		delay 0.5
	end repeat
end tell

You may run this directly from Script Editor. A similar approach can be used to export /Library/Keychains/System.keychain.

Note: Keychain.app won't allow you to paste some items (most likely, automatically created by the system, not yours). In such case, the snippet above will produce a script error and Keychain.app will show an error dialog, too. Dismiss both and run the script again. Repeat every time you get an error.

Migrate passwords and notes into KeePass

If you want to import the CSV file generated by CSVKeychain into a KeePass 2 database and you are on macOS, you may need to convert it to XML first. For such purpose, add a category column to the CSV file using the included add_category.rb script. Then, use my csv2keepassxml to generate a KeePass 2 XML file.

License

Copyright (c) 2011–2018, Lifepillar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

csvkeychain's People

Contributors

lifepillar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

csvkeychain's Issues

Accessibility Issue

screen shot 2018-02-08 at 11 50 37 am

I've tried to run the script twice but I am being asked for my password every time. I followed the provided directions and gave script editor full access before running the script. Any advice?

Script Error In New Versions of Safari

Hi,

Your script is awesome, thank you! The recently built-in Safari import of passwords from Chrome does not work properly so I reverted back to your script and I get the error in the below/attached screenshot. Any help would be greatly appreciated. Thanks!
Screen Capture 2021-04-04 at 6 00 06 PM

How to import old AirPort passwords

I didn't know where else to put this, but I thought I'd mention it in case anyone was having the same issue.

There are no built-in tools for decrypting the System keychain, but there is a python script called chainbreaker.py which can:
https://github.com/n0fate/chainbreaker

I did a simple edit of the script around line 848:


            cmd = '/usr/bin/security add-generic-password -a "%s"' % record[8].strip('\0')
            cmd += ' -l "%s"' % record[8].strip('\0')
            cmd += ' -s "%s"' % record[9].strip('\0')
            cmd += ' -D "%s"' % record[3].strip('\0')
            cmd += ' -w "%s"' % passwd.strip('\0')
            cmd += ' -T "/usr/libexec/airportd" "/Library/Keychains/System.keychain"'
            print 'cmd: %s' % cmd
 #           hexdump(cmd)
            print ''
            os.system(cmd)

This will only modify your System keychain if you run it as root. Be careful before you do, and make sure you're well enough versed in how the security program works, particularly the add-generic-password command. You can also copy and paste the individual commands for each wifi password you wish to migrate which is probably the safer option (although I had so many I just dumped it).

No applescript/automator magic needed.

Can't import CSV

I have a .csv file to import into keychain. But after clicking on import, the .csv files are greyed out in the finder.

macOS: 10.13.2(High Sierra)

1

2

Input wrong password, not able to enter correct one...

I entered the wrong password and now when running the script again I'm unable to enter the correct info...how can I resolve that issue?

Getting the error:

This script will be terminated prematurely because the following error has occurred: 

security: SecKeychainUnlock /Users/mlawler/Library/Keychains/login.keychain-db: The user name or passphrase you entered is not correct.
(Error number: 51)

Can't select keychain file

I can't select the User.keychain file on my desktop to convert it to a CSV.

File isn't encrypted and everyone has full read/write permissions.

Error when trying to export

This script will be terminated prematurely because the following error has occurred:

Can’t make alias "Macintosh HD:Users:esalberg:Library:Keychains:" into type alias.
(Error number: -1700)

This is on macOS 10.15 Beta (19A501i).

Import declares success but hasn't

I created a new keychain and a passwort item in this keychain.
I edited the exported csv, altered the entry and imported the csv to the same (also tried another new) keychain.
The script declares the import succeeded but the entry doesn't show in the keychain.

Security Considerations?

You mention that the "script always asks for the password to unlock your keychain (you recognise the dialog by the Script Editor icon). Since that dialog is not very secure, it is recommended that you change your keychain's password in Keychain.app before exporting your keychain, and restore the original password afterwards."

Do you have further information on the attack vector here? Is it based on:
o Unknown origin of this script?
o Applescript security vulnerability?
o Memory storage of the password? But then, how would Keychain app handle this?

I'm trying to keep a portable backup of my Keychain data and was hoping this script would solve this. I'm just concerned about security implications and having to change the Keychain login password every time.

Thanks for the pointers.

Script to automate password input won't work

When I try to copy my System keychain data to a new Keychain, it asks for a username and password. It works with the administrator user, but having to do this for 100 items makes this really annoying as hell. Obviously the script doesn't work for this situation.

The whole endeavor is quite maddening. I tried using security export -k /Users/ball/SystemExport.keychain -o /tmp/SystemExport -P but the System password is, of course, in binary.

Security Question

The comments say "The script always asks for the password to unlock your keychain (you recognise the dialog by the Script Editor icon). Since that dialog is not very secure, it is recommended that you change your keychain's password in Keychain.app before exporting your keychain, and restore the original password afterwards."

Can anyone comment further on the security issue with more details of how an exploit could occur? Thanks

Mojave: EXC_BAD_ACCESS (SIGSEGV) after importing

Steps to reproduce:

  1. Export on MacBook Air running Mojave
  2. Transfer file
  3. Import on brand new MacBook Pro running Mojave
  4. Run Keychain.app
  5. Scroll down. After 4 pages, Keychain will crash with the following error.
Process:               Keychain Access [14513]
Path:                  /Applications/Utilities/Keychain Access.app/Contents/MacOS/Keychain Access
Identifier:            com.apple.keychainaccess
Version:               10.5 (55237.220.1)
Build Info:            KeychainAccess-55237220001000000~105
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Keychain Access [14513]
User ID:               501

Date/Time:             2018-11-15 08:07:07.230 +0100
OS Version:            Mac OS X 10.14.1 (18B75)
Report Version:        12
Bridge OS Version:     3.1 (16P1065)
Anonymous UUID:        C7CB0C10-B4F2-6ED0-77FA-F29DBCD7C577

Sleep/Wake UUID:       A8DF03D8-0031-4A7F-9C63-950760D50213

Time Awake Since Boot: 19000 seconds
Time Since Wake:       2500 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000004
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Segmentation fault: 11
Termination Reason:    Namespace SIGNAL, Code 0xb
Terminating Process:   exc handler [14513]

VM Regions Near 0x4:
--> 
    __TEXT                 0000000104f59000-0000000104fbb000 [  392K] r-x/rwx SM=COW  /Applications/Utilities/Keychain Access.app/Contents/MacOS/Keychain Access

Application Specific Information:
dyld3 mode

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.security            	0x00007fff5221fef3 Security::NameValueDictionary::NameValueDictionary(Security::CssmData const&) + 77
1   com.apple.security            	0x00007fff523d0a71 SecKeychainItemCopyFromPersistentReference + 319
2   com.apple.security            	0x00007fff5221dd70 SecIdentityCopyPreference + 873
3   com.apple.keychainaccess      	0x0000000104f77f41 0x104f59000 + 126785
4   com.apple.keychainaccess      	0x0000000104f760cb 0x104f59000 + 118987
5   com.apple.AppKit              	0x00007fff43e01a5e -[NSTableView preparedCellAtColumn:row:] + 473
6   com.apple.AppKit              	0x00007fff44095db6 -[NSOutlineView preparedCellAtColumn:row:] + 51
7   com.apple.AppKit              	0x00007fff43e01704 -[NSTableView _drawContentsAtRow:column:withCellFrame:] + 47
8   com.apple.AppKit              	0x00007fff44095d22 -[NSOutlineView _drawContentsAtRow:column:withCellFrame:] + 77
9   com.apple.AppKit              	0x00007fff43e00e4e -[NSTableView drawRow:clipRect:] + 2011
10  com.apple.AppKit              	0x00007fff43e001f1 -[NSTableView drawRowIndexes:clipRect:] + 500
11  com.apple.AppKit              	0x00007fff44093d2f -[NSOutlineView drawRowIndexes:clipRect:] + 98
12  com.apple.AppKit              	0x00007fff43dfdfc3 -[NSTableView drawRect:] + 1341
13  com.apple.AppKit              	0x00007fff43dfa755 _NSViewDrawRect + 66
14  com.apple.AppKit              	0x00007fff43df900d -[NSView(NSInternal) _recursive:displayRectIgnoringOpacity:inContext:shouldChangeFontReferenceColor:stopAtLayerBackedViews:] + 1545
15  com.apple.AppKit              	0x00007fff43df89f2 __46-[NSView(NSLayerKitGlue) drawLayer:inContext:]_block_invoke + 192
16  com.apple.AppKit              	0x00007fff43df8751 -[NSView(NSLayerKitGlue) _drawViewBackingLayer:inContext:drawingHandler:] + 1769
17  com.apple.AppKit              	0x00007fff43ece780 -[_NSBackingLayerContents drawLayer:inContext:] + 165
18  com.apple.QuartzCore          	0x00007fff51748d6e -[CALayer drawInContext:] + 281
19  com.apple.AppKit              	0x00007fff43ece3da -[_NSTiledLayer drawTile:inContext:] + 605
20  com.apple.AppKit              	0x00007fff43ece123 -[_NSTiledLayerContents drawLayer:inContext:] + 181
21  com.apple.QuartzCore          	0x00007fff51748d6e -[CALayer drawInContext:] + 281
22  com.apple.AppKit              	0x00007fff43ece063 -[NSTileLayer drawInContext:] + 148
23  com.apple.QuartzCore          	0x00007fff51735a83 CABackingStoreUpdate_ + 577
24  com.apple.QuartzCore          	0x00007fff5179682d invocation function for block in CA::Layer::display_() + 53
25  com.apple.QuartzCore          	0x00007fff51734c78 -[CALayer _display] + 1839
26  com.apple.AppKit              	0x00007fff43ecdfab -[NSTileLayer display] + 114
27  com.apple.AppKit              	0x00007fff43ecc46a -[_NSTiledLayerContents update:shouldCallPrepareContent:] + 4780
28  com.apple.AppKit              	0x00007fff43ecaf2a -[_NSTiledLayer display] + 411
29  com.apple.QuartzCore          	0x00007fff517341a4 CA::Layer::display_if_needed(CA::Transaction*) + 634
30  com.apple.QuartzCore          	0x00007fff5172242f CA::Context::commit_transaction(CA::Transaction*) + 319
31  com.apple.QuartzCore          	0x00007fff51721d00 CA::Transaction::commit() + 576
32  com.apple.AppKit              	0x00007fff44043d56 -[_NSScrollingConcurrentMainThreadSynchronizer _synchronize:completionHandler:] + 331
33  com.apple.AppKit              	0x00007fff44043bd9 __80-[_NSScrollingConcurrentMainThreadSynchronizer initWithSharedData:constantData:]_block_invoke + 145
34  libdispatch.dylib             	0x00007fff7390ddcf _dispatch_client_callout + 8
35  libdispatch.dylib             	0x00007fff739105dc _dispatch_continuation_pop + 427
36  libdispatch.dylib             	0x00007fff7391f8ed _dispatch_source_invoke + 2013
37  libdispatch.dylib             	0x00007fff73918e25 _dispatch_main_queue_callback_4CF + 807
38  com.apple.CoreFoundation      	0x00007fff4677ae8b __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
39  com.apple.CoreFoundation      	0x00007fff4677a59a __CFRunLoopRun + 2335
40  com.apple.CoreFoundation      	0x00007fff46779a28 CFRunLoopRunSpecific + 463
41  com.apple.HIToolbox           	0x00007fff45a12b35 RunCurrentEventLoopInMode + 293
42  com.apple.HIToolbox           	0x00007fff45a1286b ReceiveNextEventCommon + 618
43  com.apple.HIToolbox           	0x00007fff45a125e8 _BlockUntilNextEventMatchingListInModeWithFilter + 64
44  com.apple.AppKit              	0x00007fff43cceeb7 _DPSNextEvent + 997
45  com.apple.AppKit              	0x00007fff43ccdc56 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1362
46  com.apple.AppKit              	0x00007fff43cc7cb9 -[NSApplication run] + 699
47  com.apple.AppKit              	0x00007fff43cb73f7 NSApplicationMain + 780
48  libdyld.dylib                 	0x00007fff7395c08d start + 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.