-
Notifications
You must be signed in to change notification settings - Fork 48
/
CSVKeychain.applescript
1371 lines (1020 loc) · 33.1 KB
/
CSVKeychain.applescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*!
@header
Keychain CSV Import/Export
@abstract
Export/import Keychain.app's keychains to/from CSV format.
@discussion
The following table shows the correspondence between some of the codes and terminology
used by the <tt>security</tt> tool in OS X Lion and the corresponding terminology
in Keychain Access, when available.
<table border="1">
<tr><th>Code</th><th>security</th><th>Keychain Access</th></tr>
<tr><td>0x00000007</td><td>label</td><td>Name</td></tr>
<tr><td>"acct"</td><td>account</td><td>Account</td></tr>
<tr><td>"cdat"</td><td>(creation timestamp)</td><td>NA</td></tr>
<tr><td>"crtr"</td><td>creator</td><td>NA</td></tr>
<tr><td>"desc"</td><td>kind</td><td>Kind (e.g., <tt>"application password"</tt>)</td></tr>
<tr><td>"icmt"</td><td>comment string</td><td>Comments</td></tr>
<tr><td>"mdat"</td><td>(modification timestamp)</td><td>Date Modified</td></tr>
<tr><td>"svce"</td><td>service</td><td>Where</td></tr>
<tr><td>"type"</td><td>Type</td><td>NA (1)</td></tr>
<tr><td>"atyp"</td><td>authentication type</td><td>NA</td></tr>
<tr><td>"path"</td><td>path</td><td>Where (2)</td></tr>
<tr><td>"port"</td><td>port</td><td>Where (2)</td></tr>
<tr><td>"ptcl"</td><td>protocol</td><td>Where (2)(3)</td></tr>
<tr><td>"sdmn"</td><td>security domain</td><td>NA</td></tr>
<tr><td>"srvr"</td><td>server name</td><td>Where (2)</td></tr>
</table>
Notes:
<dl>
<dt>(1)</dt><dd>In Keychain Access, the type is not explicitly available.
Generic passwords whose type is <tt>note</tt>, however, are displayed as secure notes.</dd>
<dt>(2)</dt><dd>For internet passwords, the <em>Where</em> field in Keychain Access
contains the compound value <tt>protocol://server/path:port</tt>.</dd>
<dt>(3)</dt><dd>The four-letter protocol codes are:</dd>
</dl>
<pre>
"ftp ", "ftpa", "http", "irc ", "nntp", "pop3", "smtp", "sox ", "imap", "ldap",
"atlk", "afp ", "teln", "ssh ", "ftps", "htps", "htpx", "htsx", "ftpx", "cifs", "smb ",
"rtsp", "rtsx", "daap", "eppc", "ipp ", "ntps", "ldps", "tels", "imps", "ircs", "pops",
"cvsp", "svn ".
</pre>
In this script, we use <tt>security</tt>'s terminology, with only one exception: the variable
<tt>|where|</tt> is used to refer to a value that can be either the service (for generic passwords)
or the compound value <tt>protocol://server/path:port</tt> (for internet passwords), that is, what
in Keychain Access is the <em>Where</em> field.
@version 2.0.0
@copyright 2011-2018 Lifepillar
@charset utf-8
*)
(*! @abstract <em>[text]</em> This script's name. *)
property name : "CSVKeychain"
(*! @abstract <em>[text]</em> This script's version. *)
property version : "2.0.0"
(*! @abstract <em>[text]</em> This script's id. *)
property id : "me.lifepillar.CSVKeychain"
(*! The names of a password item's fields. *)
property FIELDS : ({"Where", "Account", "Password", "Label", "Comment", "Created", "Modified", "Kind", "Type", "Domain", "AuthType", "Class", "Creator"})
(*! @abstract Flag to enable or disable exporting of secure notes. *)
property EXPORT_SECURE_NOTES : true
(*! Feasible values are <tt>"Allow"</tt> and <tt>"Always allow"</tt>. *)
property ALLOW_SECURITY : "Allow"
property LF : linefeed
property CR : return
property SP : space
property ERR_NOT_PASSWORD_ITEM : 9999
global PasswordItem
----------
-- Main --
----------
try
activate
display dialog Â
"Please choose if you want to export a keychain into a CSV file or you want to import data from a CSV file into a keychain." buttons {"Cancel", "Export", "Import"} Â
default button "Export" cancel button "Cancel" with title "Export or Import Data?" with icon note
set action to the button returned in the result
on error number -128
return
end try
try
if action is "Import" then
importCSV()
else if action is "Export" then
exportKeychain()
else
error "This task cannot be performed: " & action
end if
on error errMsg number errNum
if errMsg's length is greater than 480 then set errMsg to text 1 thru 480 of errMsg
if errNum is not -128 then criticalDialog((errMsg & return & "(Error number: " & errNum as text) & ")")
return
end try
set info to action & " operation completed successfully!"
activate
display dialog info buttons {"Quit"} default button 1 with title "Success!" with icon note
return -- THE END
----------------------------------------------------------------------------
-- Auxiliary handlers
----------------------------------------------------------------------------
(*!
@abstract
Exports the content of a keychain file (passwords and secure notes)
into a plain CSV file.
@return
Nothing.
@throws
ÒUser canceledÓ error if the user interrupts the process.
*)
on exportKeychain()
set {keychainName, keychainPath} to Â
chooseFile("Please select the keychain file to be exported:", "com.apple.keychain", path to keychain folder from user domain)
display dialog Â
"Do you want to also export secure notes?" buttons {"Yes", "No", "Cancel"} Â
default button "Yes" cancel button "Cancel" with title "Export secure notes?" with icon note
if button returned in the result is "No" then
set EXPORT_SECURE_NOTES to false
end if
set outputDirectory to choose folder with prompt Â
"Where do you want to save the result?" default location (path to downloads folder from user domain) Â
without invisibles, multiple selections allowed and showing package contents
set keychainDump to (POSIX path of outputDirectory) & "/" & keychainName & "-dump.txt"
askIfFileExists(keychainDump)
set keychainCSV to (POSIX path of outputDirectory) & "/" & keychainName & ".csv"
askIfFileExists(keychainCSV)
do shell script Â
"ditto " & quoted form of POSIX path of keychainPath & " " & quoted form of (POSIX path of keychainPath & "-" & timestamp() & ".backup")
unlockKeychain(keychainPath)
set keychainData to dumpKeychainWithPasswords(keychainPath, keychainDump, ALLOW_SECURITY)
set passwordItems to PasswordItemsFromKeychainDump(keychainData)
writeUTF8File(keychainCSV, toCSV(passwordItems))
end exportKeychain
(*!
@abstract
Imports password items and secure notes from a plain CSV file.
@discussion
TODO
@return
Nothing.
@throws
ÒUser cancelledÓ error if the user interrupts the process.
*)
on importCSV()
set {csvName, csvPath} to Â
chooseFile("Please select the CSV file to be imported:", "public.comma-separated-values-text", path to home folder from user domain)
set {keychainName, keychainPath} to Â
chooseFile("Please select the keychain to import items into:", "com.apple.keychain", path to keychain folder from user domain)
do shell script Â
"ditto " & quoted form of POSIX path of keychainPath & " " & quoted form of (POSIX path of keychainPath & "-" & timestamp() & ".backup")
set csvData to readUTF8File(csvPath)
set csvPasswordItems to PasswordItemsFromCSV(csvData, ",")
unlockKeychain(keychainPath)
toKeychain(keychainPath, csvPasswordItems)
end importCSV
(*!
@abstract
Returns a CSV-formatted text from a list of (homogeneous) lists.
@discussion
TODO
@param
listOfLists <em>[list]</em> A list of lists.
@return
a CSV-formatted text.
@throws
Nothing.
*)
on toCSV(listOfLists)
script CSVWriter
property lol : listOfLists
set {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, quote & "," & quote}
set csv to ""
repeat with rec in (a reference to lol)
repeat with i from 1 to count rec
-- Escape quotes
set item i of rec to replace(item i of rec, quote, quote & quote)
end repeat
set csv to csv & quote & (rec as text) & quote & LF
end repeat
set AppleScript's text item delimiters to tid
return csv
end script
run CSVWriter
end toCSV
(*!
@abstract
Imports a CSV-formatted list of password items and secure notes into a keychain.
@discussion
TODO
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>) The absolute path to a keychain file.
@param
csvPasswordItems <em>[text]</em> CSV-formatted text.
@return
Nothing.
*)
on toKeychain(keychain, csvPasswordItems)
script KeychainImporter
property pItems : csvPasswordItems
set override to false
-- Check whether there are items without a timestamp. If so, ask the user what to do with them.
repeat with rec in (a reference to pItems)
if rec's |modified| is "" then
activate
display dialog Â
"Among the items to be imported, some do not have the Òlast modifiedÓ timestamp, " & Â
"so I cannot determine whether they are newer than a corresponding item in the keychain. " & Â
"What should I do with such items when they match an item in the keychain?" buttons {"Skip Items", "Overwrite"} Â
default button "Skip Items" with icon note
if the button returned of the result is "Overwrite" then
set override to true
end if
exit repeat
end if
end repeat
repeat with rec in (a reference to pItems)
if rec's |class| is "genp" then
set ts to timestampGenericPassword(keychain, rec's account, rec's |where|)
if ts is missing value or rec's |modified| is greater than ts or (rec's |modified| is "" and override) then
addGenericPassword(true, Â
keychain, Â
rec's account, Â
rec's |where|, Â
rec's label, Â
rec's comment, Â
rec's |kind|, Â
rec's type, Â
rec's creator, Â
rec's |password|)
end if
else if rec's |class| is "inet" then
set w to decodeURL(rec's |where|)
set ptcl to encodeProtocol(w's protocol)
set ts to timestampInternetPassword(keychain, rec's account, w's server, w's |path|, w's |port|, ptcl, rec's domain, rec's authtype)
if ts is missing value or rec's |modified| is greater than ts or (rec's |modified| is "" and override) then
addInternetPassword(true, Â
keychain, Â
rec's account, Â
w's server, Â
w's |path|, Â
w's |port|, Â
ptcl, Â
rec's domain, Â
rec's authtype, Â
rec's label, Â
rec's comment, Â
rec's |kind|, Â
rec's type, Â
rec's creator, Â
rec's |password|)
end if
end if
end repeat
end script
run KeychainImporter
end toKeychain
(*!
@abstract
Displays an error dialog.
@param
msg <em>[text]</em> The error message.
@return
Nothing.
*)
on criticalDialog(msg)
activate
display dialog Â
Â
"This script will be terminated prematurely because the following error has occurred: " & return & return & msg Â
buttons {"Gosh!"} default button 1 with title "Fatal error" with icon stop Â
giving up after 30
end criticalDialog
(*!
@abstract
Unlocks the given keychain.
@discussion
Uses the <tt>security</tt> tool to unlock the specified keychain.
Prompts for a password as necessary.
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>) The absolute path to a keychain file.
@return
Nothing.
@throws
ÒUser cancelledÓ error if the keychain cannot be unlocked (e.g.,
because the password is wrong).
*)
on unlockKeychain(keychain)
try
do shell script "security -q unlock-keychain -u " & quoted form of POSIX path of the keychain
on error errMsg number 128
error errMsg number -128
end try
end unlockKeychain
(*!
@abstract
Determines whether a generic password exists in a keychain.
@discussion
TODO
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>)
The absolute path to a keychain file.
@param
account (<em>text</em>) the account field of the password item.
@param
service (<em>text</em>) the service field of the password item.
@return
(<em>text</em>) The last modification time of the given password item,
or <tt>missing value</tt> if the item does not exist in the keychain.
@throws
Nothing.
*)
on timestampGenericPassword(keychain, account, service)
try
set PasswordItem's rawData to Â
do shell script Â
"security -q find-generic-password -a " & ansiQuoted(account) & Â
" -s " & ansiQuoted(service) & " " & quoted form of POSIX path of the keychain
PasswordItem's attribute("mdat")
on error number 44 -- Not found
missing value
end try
end timestampGenericPassword
(*!
@abstract
Determines whether an internet password exists in a keychain..
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>) The absolute path to a keychain file.
@param
account <em>[text]</em> An account name.
@param
server <em>[text]</em> TODO.
@param
path <em>[text]</em> TODO.
@param
port <em>[text]</em> TODO.
@param
protocol <em>[text]</em> TODO.
@param
domain <em>[text]</em> TODO.
@param
authtype <em>[text]</em> TODO.
@return
(<em>text</em>) The last modification time of the given password item,
or <tt>missing value</tt> if the item does not exist in the keychain.
@throws
Nothing.
*)
on timestampInternetPassword(keychain, account, server, |path|, |port|, protocol, domain, authtype)
set {ptcl, atyp} to {"", "", ""}
try
if protocol's length is 4 then
set ptcl to " -r " & quoted form of protocol & " "
end if
if authtype's length is 4 then
set atyp to " -t " & quoted form of reversetext(authtype) & " "
end if
set PasswordItem's rawData to Â
do shell script "security -q find-internet-password -a " & ansiQuoted(account) & Â
" -s " & ansiQuoted(server) & " -p " & ansiQuoted(|path|) & " -P " & ansiQuoted(|port|) & Â
" -d " & ansiQuoted(domain) & ptcl & atyp & " " & quoted form of POSIX path of the keychain
PasswordItem's attribute("mdat")
on error number 44 -- Not found
missing value
end try
end timestampInternetPassword
(*!
@abstract
Adds a generic password to the specified keychain.
@discussion
TODO
@param
TODO
@return
TODO
@throws
TODO
*)
on addGenericPassword(update, keychain, account, service, label, comment, |kind|, type, creator, |password|)
set cmd to Â
"security -q add-generic-password -a " & ansiQuoted(account) & " -s " & ansiQuoted(service) Â
& " -w " & ansiQuoted(|password|)
set options to ""
if label is "" then
set options to options & " -l " & ansiQuoted(service)
else
set options to options & " -l " & ansiQuoted(label)
end if
set options to options & " -j " & ansiQuoted(comment) & " -D " & ansiQuoted(|kind|)
if type's length is 4 then
set options to options & " -C " & quoted form of type
end if
if creator's length is 4 then
set options to options & " -c " & quoted form of creator
end if
if update then
set cmd to cmd & " -U"
end if
do shell script cmd & options & " " & quoted form of POSIX path of keychain
end addGenericPassword
(*!
@abstract
Adds an internet password to the specified keycain.
@discussion
TODO
@param
TODO
@return
TODO
@throws
TODO
*)
on addInternetPassword(update, keychain, account, server, |path|, |port|, protocol, domain, authtype, label, comment, |kind|, type, creator, |password|)
set cmd to Â
"security -q add-internet-password -a " & ansiQuoted(account) & " -s " & ansiQuoted(server) Â
& " -w " & ansiQuoted(|password|) & " -p " & ansiQuoted(|path|) & " -d " & ansiQuoted(domain)
if |port| is not "" then
set cmd to cmd & " -P " & quoted form of |port|
end if
if protocol's length is 4 then
set cmd to cmd & " -r " & quoted form of protocol
end if
if authtype's length is 4 then
set cmd to cmd & " -t " & quoted form of reversetext(authtype)
end if
set options to ""
if label is "" then
set options to options & " -l " & ansiQuoted(server)
else
set options to options & " -l " & ansiQuoted(label)
end if
set options to options & " -j " & ansiQuoted(comment) & " -D " & ansiQuoted(|kind|)
if type's length is 4 then
set options to options & " -C " & quoted form of type
end if
if creator's length is 4 then
set options to options & " -c " & quoted form of creator
end if
if update then
set cmd to cmd & " -U"
end if
try
do shell script cmd & options & " " & quoted form of POSIX path of the keychain
on error number 45 -- Item exists
-- For some unknown reason (a bug?), an internet password cannot be updated
-- when additional options are given together with -U (not sure if this is still
-- the case in Sierra). In this case, try to update only the password:
if update then
do shell script cmd & " " & quoted form of POSIX path of the keychain
else
error number 45
end if
end try
end addInternetPassword
(*!
@abstract
Returns a textual dump of the given keychain.
@discussion
Works even when the keychain is locked. Never prompts for passwords.
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>)
The absolute path to a keychain file.
@return
<em>[text]</em> A textual keychain dump (without passwords).
*)
on dumpKeychainWithoutPasswords(keychain)
do shell script "security -q dump-keychain " & quoted form of POSIX path of the keychain
end dumpKeychainWithoutPasswords
(*!
@abstract
Returns a textual dump of the given keychain, including sensitive data.
@discussion
The keychain should be unlocked.
The dump is written into a plain text file, so be careful where you write it!
@param
keychain (<em>alias</em> | <em>file</em> | <em>text</em>)
The absolute path to a keychain file.
@param
dumpPath (<em>alias</em> | <em>file</em> | <em>text</em>)
The absolute path of the keychain dump.
@param
mode <em>[text]</em> Can be <tt>Allow</tt> or <tt>Always Allow</tt>.
@return
Nothing.
@throws
TODO.
*)
on dumpKeychainWithPasswords(keychain, dumpPath, mode)
display dialog Â
"Type password to unlock keychain items" default answer "" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" with title "Set password" with icon note with hidden answer
set thePassword to the text returned of the result
-- Run security in the background and redirect the output to a file
-- TODO: DUMP ACLs?
do shell script Â
"security -q dump-keychain -d " & quoted form of POSIX path of the keychain & " &>" & quoted form of dumpPath & " &"
delay 0.5 -- Wait a bit for SecurityAgent to start
allowSecurityAccess(thePassword)
readUTF8File(dumpPath)
end dumpKeychainWithPasswords
(*!
@abstract
Dismisses a SecurityAgent's dialog by pressing the specified button.
@discussion
It is recommended that you allow this script to control your computer
in System Preferences > Security & Privacy > Accessibility,
otherwise you will be prompted with a dialog for each item.
@param
mode <em>[text]</em> Can be <tt>Allow</tt> or <tt>Always Allow</tt>.
@return
Nothing.
@throws
Nothing.
*)
on allowSecurityAccess(thePassword)
tell application "System Events"
repeat while exists (processes where name is "SecurityAgent")
tell process "SecurityAgent"
set frontmost to true
try
keystroke thePassword
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
end allowSecurityAccess
(*!
@abstract
Encodes an Internet protocol's name in a format that <tt>security</tt> understands.
@param
p <em>[text]</em> The name of a protocol (e.g., <tt>https</tt>).
@return
The encoded protocol's name (e.g., <tt>htps</tt>),
or the protocol's name itself if it cannot be encoded.
@throws
Nothing.
*)
on encodeProtocol(p)
if p's length is 3 then
p & " "
else if p is "https" then
"htps"
else if p is "pop" then
"pop3"
else if p is "telnet" then
"teln"
else
p
end if
end encodeProtocol
(*!
@abstract
Handlers to manipulate a password item as dumped by the <tt>security</tt> tool.
@discussion
TODO.
*)
script PasswordItem
property rawData : missing value
(*!
@abstract
Parses a raw record as output from a <tt>security</tt> dump.
@discussion
TODO.
@throws
An error if the item cannot be parsed.
*)
on parse()
if my rawData does not contain "class: \"genp\"" and my rawData does not contain "class: \"inet\"" then
error "Not a generic or internet password." number ERR_NOT_PASSWORD_ITEM
end if
set type to my attribute("type")
if type is "note" and not EXPORT_SECURE_NOTES then
error "Secure note not exported." number ERR_NOT_PASSWORD_ITEM
end if
if type is "note" then
set |password| to my decodeSecureNote()
else
set |password| to my attribute("data")
end if
set label to my attribute("0x00000007")
set account to my attribute("acct")
set comment to my attribute("icmt")
set created to my attribute("cdat")
set |modified| to my attribute("mdat")
set |kind| to my attribute("desc")
set creator to my attribute("crtr")
if my rawData contains "class: \"genp\"" then
set |class| to "genp"
set |where| to my attribute("svce")
set {domain, authtype} to {"", ""} -- Not meaningful for generic passwords
else -- internet password
set |class| to "inet"
set server to my attribute("srvr")
set |path| to my attribute("path")
set protocol to my attribute("ptcl") -- Either a four-letter code or 0x00000000
if protocol is not "0" then
set protocol to my decodeProtocol(protocol) & "://"
else
set protocol to ""
end if
set |port| to my attribute("port")
if |port| is not "0" then
set |port| to ":" & |port|
else
set |port| to ""
end if
set |where| to protocol & server & |path| & |port|
set domain to my attribute("sdmn")
-- Possible authentication types are:
-- 'ntlm' (NTLM), 'msna' (MSN), 'dpaa' (DPA), 'rpaa' (RPA), 'http', (HTTP Basic),
-- 'httd' (HTTP Digest), 'form' (HTML Form), 'dflt' (Default), '0' (any)
set authtype to my attribute("atyp")
end if
return {|where|, account, |password|, label, comment, created, |modified|, |kind|, type, domain, authtype, |class|, creator}
end parse
(*!
@abstract
Returns the value of the given field.
@discussion
TODO
*)
on attribute(field)
set type to my fieldtype(field)
if field is "data" then
set theKey to {"data:" & LF, "data:" & CR}
else if field starts with "0x" then
set theKey to field & " <" & type & ">=" -- E.g., 0x00000007 <blob>=
else
set theKey to quote & field & quote & "<" & type & ">=" -- E.g., "acct"<blob>=
end if
set v to textBetween(my rawData, theKey, {LF, CR}) as text
if v starts with "0x" then
my decodeValue(v, type)
else
cleanupValue(v)
end if
end attribute
(*!
@abstract
TODO
@discussion
TODO
*)
on fieldtype(field)
if field starts with "0x" or field is in {"acct", "atyp", "data", "desc", "gena", "icmt", "path", "prot", "sdmn", "srvr", "svce"} then
"blob"
else if field is in {"cdat", "mdat"} then
"timedate"
else if field is in {"crtr", "port", "ptcl", "type"} then
"uint32"
else if field is in {"cusi", "invi", "nega", "scrp"} then
"sint32"
else
missing value
end if
end fieldtype
(*!
@abstract
TODO
@discussion
TODO
*)
on cleanupValue(v)
if v is "<NULL>" then
""
else
unquote(v)
end if
end cleanupValue
(*!
@abstract
Decodes a value of the form Ò0x<hexadecimal string> "<ascii string>"Ó.
@discussion
TODO
*)
on decodeValue(v, type)
if type is equal to "blob" then
textBetweenGreedy(v, quote, quote) -- Note that v may contain quotes
else if type is equal to "timedate" then
text 1 thru -6 of textBetweenGreedy(v, quote, quote) -- Timestamps end with "Z\000"
else if type starts with "uint" then
hexToDec(text 3 thru -1 of the first item of split(v, {SP, LF})) -- Get the hex part and convert it to decimal
else
error "Cannot decode the given data type: " & type
end if
end decodeValue
(*!
@abstract
Returns the protocol scheme for the given four-letter code.
@discussion
FIXME: only the most common protocol's names are decoded.
*)
on decodeProtocol(p)
if p ends with " " then -- e.g., 'ftp '
text 1 thru 3 of p
else if p is "htps" then
"https"
else if p is "pop3" then
"pop"
else if p is "teln" then
"telnet"
else
p
end if
end decodeProtocol
(*!
@abstract
TODO
@discussion
TODO
*)
on decodeSecureNote()
set v to textBetween(my rawData, {"data:" & LF, "data:" & CR}, {LF, CR}) as text
if v starts with "0x" then
try
set secureNote to hexToUTF8(textBetween(v, "0x", SP))
if secureNote starts with "<?xml version=" then
tell application "System Events" to get the value of (make new property list item with data secureNote)
|note| of the result
else
secureNote
end if
on error
textBetweenGreedy(v, "<string>", "</string>")
end try
else
cleanupValue(secureNote)
end if
end decodeSecureNote
end script -- script PasswordItem
(*!
@abstract
TODO
@discussion
Requires:
1. Fields are quoted;
2. The first record is the header;
3. There is no field of the form "\n" (containing just a newline).
4. There is no field containing the string: quote & quote & separator & quote & quote.
*)
on PasswordItemsFromCSV(source, separator)
script Parser
property passwordItems : {}
property csvRecords : split(source, quote & LF & quote)
set header to split(the first item of csvRecords, separator)
set {Â
i_where, Â
i_account, Â
i_password, Â
i_label, Â
i_comment, Â
i_class, Â
i_created, Â
i_modified, Â
i_kind, Â
i_type, Â
i_domain, Â
i_authtype, Â
i_creator} to Â
{Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value, Â
missing value}
repeat with i from 1 to count header
set f to item i of header
if f contains "Where" then