Debian Codegraph @

main.ml

raw
1 (* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Initial Developer of the Original Code is
15 * Stéphane Glondu <[email protected]>
16 * Portions created by the Initial Developer are Copyright (C) 2010-2011
17 * the Initial Developer. All Rights Reserved.
18 *
19 * Alternatively, the contents of this file may be used under the terms of
20 * either the GNU General Public License Version 2 or later (the "GPL"), or
21 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
22 * in which case the provisions of the GPL or the LGPL are applicable instead
23 * of those above. If you wish to allow use of your version of this file only
24 * under the terms of either the GPL or the LGPL, and not to allow others to
25 * use your version of this file under the terms of the MPL, indicate your
26 * decision by deleting the provisions above and replace them with the notice
27 * and other provisions required by the GPL or the LGPL. If you do not delete
28 * the provisions above, a recipient may use your version of this file under
29 * the terms of any one of the MPL, the GPL or the LGPL.
30 *
31 * ***** END LICENSE BLOCK ***** *)
32
33 open Ppx_yojson_conv_lib.Yojson_conv.Primitives
34
35 type login = {
36 hostname : string;
37 encryptedUsername : string;
38 encryptedPassword : string;
39 }
40 [@@deriving yojson] [@@yojson.allow_extra_fields]
41
42 type logins = { logins : login list }
43 [@@deriving yojson] [@@yojson.allow_extra_fields]
44
45 type output_login = { hostname : string; username : string; password : string }
46 [@@deriving yojson]
47
48 type output = output_login list [@@deriving yojson]
49
50 (** C interface *)
51
52 exception NSS_init_failed
53 exception NSS_cleanup_failed
54 exception NSS_base64_decode_failed of string * int
55 exception NSS_decrypt_failed of string * int * exn option
56
57 let () = Callback.register_exception "NSS_init_failed" NSS_init_failed
58 let () = Callback.register_exception "NSS_cleanup_failed" NSS_cleanup_failed
59
60 let () =
61 Callback.register_exception "NSS_base64_decode_failed"
62 (NSS_base64_decode_failed ("", 0))
63
64 let () =
65 Callback.register_exception "NSS_decrypt_failed"
66 (NSS_decrypt_failed ("", 0, None))
67
68 external nss_cleanup : unit -> unit = "caml_nss_cleanup"
69 external nss_init : string -> unit = "caml_nss_init"
70
71 external do_decrypt : callback:(bool -> string) -> data:string -> string
72 = "caml_do_decrypt"
73
74 external ttyname : Unix.file_descr -> string = "caml_ttyname"
75
76 (** Command-line arguments parsing and initialization *)
77
78 let dir = ref ""
79 let pinentry = ref "pinentry"
80 let queries = ref []
81 let json_output = ref false
82
83 let spec =
84 Arg.align
85 [
86 ( "-d",
87 Arg.Set_string dir,
88 "profile directory (default: Firefox default profile)" );
89 ( "-p",
90 Arg.Set_string pinentry,
91 "pinentry program to use (default: pinentry)" );
92 ("-j", Arg.Set json_output, " output result in JSON");
93 ]
94
95 let usage_msg =
96 "nss-passwords [-d <dir>] [-p <pinentry>] query [...]\n\
97 A query is either hostname:string, username:string, or string (which\n\
98 translates to hostname:string)."
99
100 exception Found of string
101
102 let chop_prefix ~prefix x =
103 let n = String.length x and nprefix = String.length prefix in
104 if n >= nprefix && String.sub x 0 nprefix = prefix then
105 Some (String.sub x nprefix (n - nprefix))
106 else None
107
108 let parse_query x =
109 match chop_prefix ~prefix:"hostname:" x with
110 | Some x -> `Hostname x
111 | None -> (
112 match chop_prefix ~prefix:"username:" x with
113 | Some x -> `Username x
114 | None -> `Hostname x)
115
116 let () =
117 Arg.parse spec (fun x -> queries := parse_query x :: !queries) usage_msg;
118 if !queries = [] then (
119 Arg.usage spec usage_msg;
120 exit 1);
121 if !dir = "" then
122 try
123 let () =
124 FileUtil.find ~follow:FileUtil.Follow
125 ~match_compile:FileUtilStr.match_compile
126 (FileUtil.And (FileUtil.Is_dir, FileUtil.Match ".*\\.default$"))
127 (FilePath.concat (Sys.getenv "HOME") ".mozilla/firefox")
128 (fun _ x -> raise (Found x))
129 ()
130 in
131 Printf.eprintf "No default profile directory found\n";
132 exit 1
133 with Found x -> dir := x
134 else if not (FileUtil.test FileUtil.Is_dir !dir) then (
135 Printf.eprintf "Invalid profile directory: %s\n" !dir;
136 exit 1);
137 nss_init !dir;
138 at_exit nss_cleanup
139
140 (** Decrypt passwords *)
141
142 let check line =
143 assert (String.length line >= 2 && String.sub line 0 2 = "OK");
144 ()
145
146 let lc_ctype =
147 try Some (Sys.getenv "LC_ALL")
148 with Not_found -> ( try Some (Sys.getenv "LANG") with Not_found -> None)
149
150 let callback retry =
151 if retry then failwith "invalid password"
152 else
153 let ((stdin, stdout) as child) = Unix.open_process !pinentry in
154 check (input_line stdin);
155 let ttyname =
156 try ttyname Unix.stdin
157 with Unix.Unix_error (_, _, _) -> failwith "stdin is not a tty"
158 in
159 Printf.fprintf stdout "OPTION ttyname=%s\n%!" ttyname;
160 check (input_line stdin);
161 (match lc_ctype with
162 | Some x ->
163 Printf.fprintf stdout "OPTION lc-ctype=%s\n%!" x;
164 check (input_line stdin)
165 | None -> ());
166 Printf.fprintf stdout "GETPIN\n%!";
167 let line = input_line stdin in
168 let _ = Unix.close_process child in
169 let n = String.length line in
170 if n > 2 then String.sub line 2 (n - 2) else failwith "missing password"
171
172 let quote_query buf x =
173 Buffer.add_string buf "'%";
174 String.iter
175 (function
176 | '\'' -> Buffer.add_string buf "''"
177 | '%' -> Buffer.add_string buf "x%"
178 | '_' -> Buffer.add_string buf "x_"
179 | 'x' -> Buffer.add_string buf "xx"
180 | c -> Buffer.add_char buf c)
181 x;
182 Buffer.add_string buf "%'"
183
184 let results = ref []
185
186 let exec_hostname db query =
187 let cb = function
188 | [| hostname; encryptedUsername; encryptedPassword |] ->
189 let username = do_decrypt ~callback ~data:encryptedUsername in
190 let password = do_decrypt ~callback ~data:encryptedPassword in
191 results := { hostname; username; password } :: !results
192 | _ -> assert false
193 in
194 let buf = Buffer.create ((2 * String.length query) + 128) in
195 Printf.bprintf buf
196 "SELECT hostname, encryptedUsername, encryptedPassword FROM moz_logins \
197 WHERE hostname LIKE %a ESCAPE 'x';"
198 quote_query query;
199 let r = Sqlite3.exec_not_null_no_headers ~cb db (Buffer.contents buf) in
200 assert (r = Sqlite3.Rc.OK)
201
202 let exec_username db query =
203 let rex = Str.regexp (".*" ^ Str.quote query ^ ".*") in
204 let cb = function
205 | [| hostname; encryptedUsername; encryptedPassword |] ->
206 let username = do_decrypt ~callback ~data:encryptedUsername in
207 if Str.string_match rex username 0 then
208 let password = do_decrypt ~callback ~data:encryptedPassword in
209 results := { hostname; username; password } :: !results
210 | _ -> assert false
211 in
212 let sql =
213 "SELECT hostname, encryptedUsername, encryptedPassword FROM moz_logins;"
214 in
215 let r = Sqlite3.exec_not_null_no_headers ~cb db sql in
216 assert (r = Sqlite3.Rc.OK)
217
218 let exec db = function
219 | `Hostname x -> exec_hostname db x
220 | `Username x -> exec_username db x
221
222 let exec_sqlite () =
223 let db = Sqlite3.db_open (FilePath.concat !dir "signons.sqlite") in
224 List.iter (exec db) !queries;
225 let r = Sqlite3.db_close db in
226 assert (r = true)
227
228 let iter_try f l = List.iter (fun x -> try f x with _ -> ()) l
229
230 let json_process logins query =
231 let string_match =
232 match query with
233 | `Hostname x ->
234 let rex = Str.regexp (".*" ^ Str.quote x ^ ".*") in
235 fun hostname _ -> Str.string_match rex hostname 0
236 | `Username x ->
237 let rex = Str.regexp (".*" ^ Str.quote x ^ ".*") in
238 fun _ username -> Str.string_match rex (Lazy.force username) 0
239 in
240 iter_try
241 (fun (l : login) ->
242 let hostname = l.hostname in
243 let username = lazy (do_decrypt ~callback ~data:l.encryptedUsername) in
244 if string_match hostname username then
245 let username = Lazy.force username in
246 let password = do_decrypt ~callback ~data:l.encryptedPassword in
247 results := { hostname; username; password } :: !results)
248 logins
249
250 let exec_json () =
251 let ic = open_in (FilePath.concat !dir "logins.json") in
252 let ls = Yojson.init_lexer () in
253 let lb = Lexing.from_channel ic in
254 let logins = Yojson.Safe.read_json ls lb |> logins_of_yojson in
255 close_in ic;
256 List.iter (json_process logins.logins) !queries
257
258 let print_as_table results =
259 let a, b, c =
260 List.fold_left
261 (fun (a, b, c) o ->
262 let a = max a (String.length o.hostname) in
263 let b = max b (String.length o.username) in
264 let c = max c (String.length o.password) in
265 (a, b, c))
266 (0, 0, 0) results
267 in
268 List.iter
269 (fun o ->
270 Printf.printf "| %-*s | %-*s | %-*s |\n" a o.hostname b o.username c
271 o.password)
272 results
273
274 let print_as_json results =
275 print_endline (results |> yojson_of_output |> Yojson.Safe.to_string)
276
277 let () =
278 try
279 if Sys.file_exists (FilePath.concat !dir "logins.json") then exec_json ()
280 else exec_sqlite ();
281 let results = List.sort compare !results in
282 (if !json_output then print_as_json else print_as_table) results
283 with NSS_decrypt_failed (_, _, Some e) ->
284 Printf.eprintf "Error while decrypting: %s\n" (Printexc.to_string e);
285 exit 2