text
stringlengths
0
601k
let pp_protocol_error ppf = function | ` Other_error -> Format . pp_print_string ppf " other error " | ` Bad_request -> Format . pp_print_string ppf " bad request " | ` Configuration_unsupported -> Format . pp_print_string ppf " configuration unsupported " | ` Device_ineligible -> Format . pp_print_string ppf " device ...
type error = [ | ` Protocol of protocol_error | ` Json_decoding of string * string * string | ` Base64_decoding of string * string * string | ` Binary_decoding of string * string * string | ` Version_mismatch of string * string | ` Typ_mismatch of string * string | ` Challenge_mismatch of string * string | ` Unknown_ke...
let pp_error ppf = function | ` Protocol p -> pp_protocol_error ppf p | ` Json_decoding ( name , err , value ) -> Format . fprintf ppf " json decoding of % s failed with % S ( input % S ) " name err value | ` Base64_decoding ( name , err , value ) -> Format . fprintf ppf " base64 decoding of % s failed with % S ( input...
let b64_enc = Base64 . ( encode_string ~ pad : false ~ alphabet : uri_safe_alphabet )
let b64_dec thing s = Result . map_error ( function ` Msg m -> ` Base64_decoding ( thing , m , s ) ) Base64 . ( decode ~ pad : false ~ alphabet : uri_safe_alphabet s )
type register_request = { version : string ; challenge : string ;
type registered_key = { version : string ; keyHandle : string ;
type u2f_register_request = { appId : string ; registerRequests : register_request list ; registeredKeys : registered_key list ;
let challenge ( ) = let random = Cstruct . to_string ( Mirage_crypto_rng . generate 32 ) in b64_enc random
let register_request ( ? key_handles = [ ] ) { version ; application_id } = let challenge = challenge ( ) in let reg_req = { appId = application_id ; registerRequests = [ { version ; challenge } ] ; registeredKeys = List . map ( fun keyHandle -> { version ; keyHandle } ) key_handles } in challenge , Yojson . Safe . to_...
let res_typ_to_string = function | ` Sign -> " navigator . id . getAssertion " | ` Register -> " navigator . id . finishEnrollment "
let res_typ = function | " navigator . id . getAssertion " -> Ok ` Sign | " navigator . id . finishEnrollment " -> Ok ` Register | x -> Error ( ` Msg ( " unknown type " ^ x ) )
type clientData = { challenge : string ; origin : string ; typ : string ;
let error_code_of_int = function | 0 -> Ok ( ) | 1 -> Error ` Other_error | 2 -> Error ` Bad_request | 3 -> Error ` Configuration_unsupported | 4 -> Error ` Device_ineligible | 5 -> Error ` Timeout | n -> Error ( ` Unrecognized n )
type u2f_register_response = { clientData : string ; errorCode : int ; registrationData : string ; version : string ;
let ( let * ) = Result . bind
let guard p e = if p then Ok ( ) else Error e
let seq_len cs = let * ( ) = guard ( Cstruct . get_uint8 cs 0 = 0x30 ) ( ` Msg " Certificate is not an ASN . 1 sequence " ) in let first_len = Cstruct . get_uint8 cs 1 in if first_len > 0x80 then let len_bytes = first_len - 0x80 in let * ( ) = guard ( Cstruct . length cs > len_bytes + 2 ) ( ` Msg " Certificate with too...
let decode_reg_data data = let cs = Cstruct . of_string data in let * ( ) = guard ( Cstruct . length cs >= 67 ) ( ` Msg " registration data too small ( < 67 ) " ) in let * ( ) = guard ( Cstruct . get_uint8 cs 0 = 0x05 ) ( ` Msg " registration data first byte must be 0x05 " ) in let pubkey , rest = Cstruct . ( split ( s...
let verify_sig pub ~ signature data = match X509 . Public_key . verify ` SHA256 ~ signature pub ( ` Message data ) with | Error ` Msg m -> Error ( ` Signature_verification m ) | Ok ( ) -> Ok ( )
let verify_reg_sig cert app client_data kh key signature = let h s = Mirage_crypto . Hash . SHA256 . digest ( Cstruct . of_string s ) in let data = Cstruct . concat [ Cstruct . create 1 ; h app ; h client_data ; kh ; Mirage_crypto_ec . P256 . Dsa . pub_to_cstruct key ] in verify_sig ( X509 . Certificate . public_key ce...
let verify_auth_sig key app presence counter client_data signature = let data = let h s = Mirage_crypto . Hash . SHA256 . digest ( Cstruct . of_string s ) in let p_c = let b = Cstruct . create 5 in if presence then Cstruct . set_uint8 b 0 1 ; Cstruct . BE . set_uint32 b 1 counter ; b in Cstruct . concat [ h app ; p_c ;...
let of_json_or_err thing p json = Result . map_error ( fun msg -> ` Json_decoding ( thing , msg , Yojson . Safe . to_string json ) ) ( p json )
let of_json thing p s = let * json = try Ok ( Yojson . Safe . from_string s ) with Yojson . Json_error msg -> Error ( ` Json_decoding ( thing , msg , s ) ) in of_json_or_err thing p json
let register_response ( t : t ) challenge data = let * reg_resp = of_json " RegisterResponse " u2f_register_response_of_yojson data in let * ( ) = Result . map_error ( fun p -> ` Protocol p ) ( error_code_of_int reg_resp . errorCode ) in let * ( ) = guard ( String . equal t . version reg_resp . version ) ( ` Version_mi...
type u2f_authentication_request = { appId : string ; challenge : string ; registeredKeys : registered_key list ;
let authentication_request { version ; application_id } key_handles = let challenge = challenge ( ) in let ar = { appId = application_id ; challenge ; registeredKeys = List . map ( fun keyHandle -> { version ; keyHandle } ) key_handles } in challenge , Yojson . Safe . to_string ( u2f_authentication_request_to_yojson ar...
type u2f_authentication_response = { clientData : string ; errorCode : int ; keyHandle : string ; signatureData : string ;
let decode_sigdata data = let cs = Cstruct . of_string data in let * ( ) = guard ( Cstruct . length cs > 5 ) ( ` Msg " sigData too small " ) in let user_presence = Cstruct . get_uint8 cs 0 = 1 in let counter = Cstruct . BE . get_uint32 cs 1 in let signature = Cstruct . shift cs 5 in Ok ( user_presence , counter , signa...
let authentication_response ( t : t ) key_handle_keys challenge data = let * sig_resp = of_json " AuthenticationResponse " u2f_authentication_response_of_yojson data in let * ( ) = Result . map_error ( fun p -> ` Protocol p ) ( error_code_of_int sig_resp . errorCode ) in let * client_data_json = b64_dec " clientData " ...
let users = Hashtbl . create 7
module KhPubHashtbl = Hashtbl . Make ( struct type t = U2f . key_handle * Mirage_crypto_ec . P256 . Dsa . pub let cs_of_pub = Mirage_crypto_ec . P256 . Dsa . pub_to_cstruct let equal ( kh , pub ) ( kh ' , pub ' ) = String . equal kh kh ' && Cstruct . equal ( cs_of_pub pub ) ( cs_of_pub pub ' ) let hash ( kh , pub ) = H...
let counters = KhPubHashtbl . create 7
let check_counter kh_pub counter = let r = match KhPubHashtbl . find_opt counters kh_pub with | Some counter ' -> Int32 . unsigned_compare counter counter ' > 0 | None -> true in if r then KhPubHashtbl . replace counters kh_pub counter ; r
let retrieve_form request = Dream . body request >|= fun body -> let form = Dream__pure . Formats . from_form_urlencoded body in List . stable_sort ( fun ( key , _ ) ( key ' , _ ) -> String . compare key key ' ) form
let to_string err = Format . asprintf " % a " U2f . pp_error err
let add_routes t = let main req = let authenticated_as = Dream . session " authenticated_as " req in let flash = Flash_message . get_flash req |> List . map snd in Dream . html ( Template . overview flash authenticated_as users ) in let register req = let user = match Dream . session " authenticated_as " req with | Non...
let setup_app level port host application_id https = let u2f = U2f . create application_id in let level = match level with None -> None | Some Logs . Debug -> Some ` Debug | Some Info -> Some ` Info | Some Warning -> Some ` Warning | Some Error -> Some ` Error | Some App -> None in Dream . initialize_log ? level ( ) ; ...
let port = let doc = " port " in Arg . ( value & opt int 4000 & info [ " p " ; " port " ] ~ doc )
let host = let doc = " host " in Arg . ( value & opt string " 0 . 0 . 0 . 0 " & info [ " h " ; " host " ] ~ doc )
let application_id = let doc = " the u2f application id - usually protocol :// host ( : port ) " in Arg . ( value & opt string " https :// u2f - demo . robur . coop " & info [ " application - id " ] ~ doc )
let tls = let doc = " tls " in Arg . ( value & flag & info [ " tls " ] ~ doc )
let ( ) = let term = Term . ( pure setup_app $ Logs_cli . level ( ) $ port $ host $ application_id $ tls ) in let info = Term . info " U2f app " ~ doc " : U2f app " ~ man [ ] : in match Term . eval ( term , info ) with | ` Ok ( ) -> exit 0 | ` Error _ -> exit 1 | _ -> exit 0
let is_spec attr = attr . attr_name . txt = " gospel "
let rec get_spec_attr = function | [ ] -> ( None , [ ] ) | h :: t when is_spec h -> ( Some h , t ) | h :: t -> let elt , rest = get_spec_attr t in ( elt , h :: rest )
let get_spec_content attr = match attr . attr_payload with | PStr [ { pstr_desc = Pstr_eval ( { pexp_desc = Pexp_constant ( Pconst_string ( spec , _ , _ ) ) ; _ } , _ ) ; _ ; } ; ] -> ( spec , attr . attr_loc ) | _ -> assert false
let get_inner_spec attr = match attr . attr_payload with | PStr [ { pstr_desc = Pstr_eval ( _ , attrs ) ; _ } ] -> get_spec_attr attrs | _ -> assert false
let set_position ( lexbuf : Lexing . lexbuf ) ( position : Lexing . position ) = lexbuf . lex_curr_p <- { position with pos_fname = lexbuf . lex_curr_p . pos_fname } ; lexbuf . lex_abs_pos <- position . pos_cnum
let set_filename ( lexbuf : Lexing . lexbuf ) ( fname : string ) = lexbuf . lex_curr_p <- { lexbuf . lex_curr_p with pos_fname = fname }
let parse_gospel ~ filename parse attr = let spec , _ = get_spec_content attr in let lb = Lexing . from_string spec in set_position lb attr . attr_loc . loc_start ; set_filename lb filename ; try ( spec , parse Ulexer . token lb ) with Uparser . Error -> let loc = { loc_start = lb . lex_start_p ; loc_end = lb . lex_cur...
let type_declaration ~ filename t = let spec_attr , other_attrs = get_spec_attr t . ptype_attributes in let parse attr = let ty_text , spec = parse_gospel ~ filename Uparser . type_spec attr in { spec with ty_text ; ty_loc = attr . attr_loc } in let spec = Option . map parse spec_attr in { tname = t . ptype_name ; tpar...
let val_description ~ filename v = let spec_attr , other_attrs = get_spec_attr v . pval_attributes in let parse attr = let sp_text , spec = parse_gospel ~ filename Uparser . val_spec attr in { spec with sp_text ; sp_loc = attr . attr_loc } in let spec = Option . map parse spec_attr in { vname = v . pval_name ; vtype = ...
let ghost_spec ~ filename attr = let spec , loc = get_spec_content attr in let lb = Lexing . from_string spec in let sigs = try Parse . interface lb with _ -> W . error ~ loc W . Syntax_error in match sigs with | [ { psig_desc = Psig_type ( r , [ t ] ) ; _ } ] -> let type_ = type_declaration ~ filename t in if type_ . ...
let floating_spec ~ filename a = try let fun_text , fun_ = parse_gospel ~ filename Uparser . func a in let fun_ = { fun_ with fun_text } in if fun_ . fun_spec = None then let fun_spec = get_inner_spec a |> fst |> Option . map ( parse_gospel ~ filename Uparser . func_spec ) |> Option . map ( fun ( fun_text , ( spec : fu...
let with_constraint c = let no_spec_type_decl t = { tname = t . ptype_name ; tparams = t . ptype_params ; tcstrs = t . ptype_cstrs ; tkind = t . ptype_kind ; tprivate = t . ptype_private ; tmanifest = t . ptype_manifest ; tattributes = t . ptype_attributes ; tspec = None ; tloc = t . ptype_loc ; } in match c with | Pwi...
let rec signature_item_desc ~ filename = function | Psig_value v -> Sig_val ( val_description ~ filename v ) | Psig_type ( r , tl ) -> Sig_type ( r , List . map ( type_declaration ~ filename ) tl ) | Psig_attribute a -> if not ( is_spec a ) then Sig_attribute a else floating_spec ~ filename a | Psig_module m -> Sig_mod...
let err_no_pred = " U + 0000 has no predecessor "
let err_no_succ = " U + 10FFFF has no successor "
let err_not_sv i = format_int " % X " i ^ " is not an Unicode scalar value "
let err_not_latin1 u = " U " + ^ format_int " % 04X " u ^ " is not a latin1 character "
let succ u = if u = lo_bound then hi_bound else if u = max then invalid_arg err_no_succ else u + 1
let pred u = if u = hi_bound then lo_bound else if u = min then invalid_arg err_no_pred else u - 1
let is_valid i = ( min <= i && i <= lo_bound ) || ( hi_bound <= i && i <= max )
let of_int i = if is_valid i then i else invalid_arg ( err_not_sv i )
let is_char u = u < 256
let of_char c = Char . code c
let to_char u = if u > 255 then invalid_arg ( err_not_latin1 u ) else Char . unsafe_chr u
let equal : int -> int -> bool = ( = )
let compare : int -> int -> int = Stdlib . compare
let log_err s = Printf . printf " % s : % s \ n " %! ( Filename . basename Sys . executable_name ) s
let is_white = function ' ' | ' \ t ' . . ' \ r ' -> true | _ -> false
let is_digit = function ' 0 ' . . ' 9 ' -> true | _ -> false
let hex_digit_value c = let c = Char . code c in if c <= 0x39 then c - 48 else if c <= 0x46 then c - 55 else c - 87
let str_starts s pre = let plen = String . length pre in let slen = String . length s in if plen > slen then false else try for i = 0 to plen - 1 do if pre . [ i ] <> s . [ i ] then raise Exit ; done ; true with Exit -> false
let str_is_ascii s = let max = String . length s - 1 in let rec loop s i = if i > max then true else if Char . code s . [ i ] > 0x7F then false else loop s ( i + 1 ) in loop s 0
let esc_non_ascii s = let b = Buffer . create 255 in let add_byte = function | c when Char . code c > 0x7F -> Buffer . add_string b ( strf " \\ x % 02X " ( Char . code c ) ) | c -> Buffer . add_char b c in String . iter add_byte s ; Buffer . contents b
let uchars_to_utf_bytes utf uchars = let b = Buffer . create 255 in let add_utf = match utf with | ` UTF_8 -> Uutf . Buffer . add_utf_8 | ` UTF_16BE -> Uutf . Buffer . add_utf_16be | ` UTF_16LE -> Uutf . Buffer . add_utf_16le in List . iter ( add_utf b ) uchars ; Buffer . contents b
let uchars_to_utf_bytes_esc utf uchars = let utf = uchars_to_utf_bytes utf uchars in let b = Buffer . create 255 in let add_byte c = Buffer . add_string b ( strf " \\ x % 02X " ( Char . code c ) ) in String . iter add_byte utf ; Buffer . contents b
let uchars_to_cps uchars = let to_str u = strf " U +% 04X " ( Uchar . to_int u ) in String . concat " " ( List . map to_str uchars )
let uchars_to_named_cps uchars = let to_str u = strf " % s ( U +% 04X ) " ( Uucp . Name . name u ) ( Uchar . to_int u ) in String . concat " " ( List . map to_str uchars )
let uchar_of_utf utf s = let fold = match utf with | ` UTF_8 -> Uutf . String . fold_utf_8 | ` UTF_16BE -> Uutf . String . fold_utf_16be | ` UTF_16LE -> Uutf . String . fold_utf_16le in match fold ( fun acc _ decode -> decode :: acc ) [ ] s with | [ ` Uchar u ] -> Some u | _ -> None
let try_uchar_of_utfs s = let rec try_decs s = function | [ ] -> None | enc :: encs -> match uchar_of_utf enc s with | None -> try_decs s encs | Some _ as u -> u in try_decs s [ ` UTF_8 ; ` UTF_16BE ; ` UTF_16LE ]
let parse_decimal_esc s = let max = String . length s - 1 in let rec loop s i acc = match i = max with | true -> if s . [ max ] = ' ; ' && Uchar . is_valid acc then Some ( Uchar . of_int acc ) else None | false -> if not ( is_digit s . [ i ] ) then None else loop s ( i + 1 ) ( acc * 10 + ( Char . code s . [ i ] - 48 ) ...
let parse_hex_esc s ~ finish = let max = String . length s - 1 in let parse_hex s start = let rec loop s i acc = if i > max then acc , max else if not ( is_hex_digit s . [ i ] ) then acc , i - 1 else loop s ( i + 1 ) ( acc * 16 + hex_digit_value s . [ i ] ) in loop s start 0 in let hex , last = parse_hex s 0 in let to_...
let uchar_of_uchar_esc s = let prefixes = [ " U " ; + " u " ; + " U " ; " u " ; " \\ u { " ; " \\ U { " ; " \\ u " ; " \\ U " ; " &# x " ; " " &# ] in match try Some ( List . find ( str_starts s ) prefixes ) with Not_found -> None with | None -> None | Some pre -> let pre_len = String . length pre in let s = String . s...
let uchar_of_utf_8_bytes_esc s = let b = Buffer . create 255 in let max = String . length s - 1 in let parse_hex_byte s i = match i + 1 <= max && is_hex_digit s . [ i ] && is_hex_digit s . [ i + 1 ] with | false -> None | true -> Some ( 16 * ( hex_digit_value s . [ i ] ) + ( hex_digit_value s . [ i + 1 ] ) ) in let rec...
let guess_spec s = match str_is_ascii s with match uchar_of_uchar_esc s with | Some _ as u -> u | None -> uchar_of_utf_8_bytes_esc s
let parse_spec spec_fmt s = match spec_fmt with
let unicode_version ( ) = Printf . printf " % s \ n " %! Uucp . unicode_version
type out_fmt = { ascii : bool ; no_labels : bool ; raw_bytes : bool ; }
let str ( pp , key ) ( out_fmt : out_fmt ) u = strf " % a " pp ( key u )
let str_bool key ( out_fmt : out_fmt ) u = strf " % b " ( key u )
let str_int key ( out_fmt : out_fmt ) u = strf " % d " ( key u )
let str_uchar ( out_fmt : out_fmt ) u = uchars_to_cps [ u ]
let str_str key ( out_fmt : out_fmt ) u = key u
let str_utf utf out_fmt u = match out_fmt . raw_bytes with
let str_cps out_fmt uchars = let cps = uchars_to_cps uchars in match out_fmt . ascii with | true -> cps | false -> let utf_8 = uchars_to_utf_bytes ` UTF_8 uchars in strf " % s ( % s ) " utf_8 cps
let str_case_map map ( out_fmt : out_fmt ) u = let uchars = match map u with ` Self -> [ u ] | ` Uchars uchars -> uchars in str_cps out_fmt uchars
let str_decomposition_mapping ( out_fmt : out_fmt ) u = let uchars = match Uunf . decomp u with | [ ] || -> [ u ] | a -> let to_uchar i u = match i = 0 with | true -> Uunf . d_uchar u | false -> Uchar . of_int u in Array . ( to_list @@ mapi to_uchar a ) in str_cps out_fmt uchars
let str_name_alias key ( out_fmt : out_fmt ) u = let str_alias ( t , n ) = strf " % s ( % a ) " n Uucp . Name . pp_alias_tag t in String . concat " , " ( List . map str_alias ( key u ) )