-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathextauth_plugin_ADwinbind.ml
More file actions
1674 lines (1483 loc) · 57.1 KB
/
Copy pathextauth_plugin_ADwinbind.ml
File metadata and controls
1674 lines (1483 loc) · 57.1 KB
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
(*
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
(**
* @winbind group Access Control
*)
module D = Debug.Make (struct
let name = "extauth_plugin_ADwinbind"
end)
open D
open Xapi_stdext_std.Xstringext
open Auth_signature
module Scheduler = Xapi_stdext_threads_scheduler.Scheduler
let finally = Xapi_stdext_pervasives.Pervasiveext.finally
let krbtgt = "KRBTGT"
let ( let* ) = Result.bind
let ( let@ ) = ( @@ )
let ( <!> ) x f = Rresult.R.reword_error f x
let ( >>| ) = Rresult.( >>| )
let min_debug_level = 0
let max_debug_level = 10
let default_debug_level = 2
let clamp v ~low ~high ~default =
match v with n when n >= low && n <= high -> n | _ -> default
let maybe_raise (x : ('a, exn) result) : 'a =
match x with Ok x -> x | Error e -> raise e
let maybe_raise_not_found (x : ('a, exn) result) : 'a =
match x with
| Ok x ->
x
| Error e ->
D.error "found an exception, raising Not_found instead. ex: %s"
(Printexc.to_string e) ;
raise Not_found
let auth_ex uname =
let msg = Printf.sprintf "failed to authenticate user '%s'" uname in
Auth_signature.(Auth_failure msg)
let generic_ex fmt =
Printf.ksprintf
(fun msg -> Auth_signature.(Auth_service_error (E_GENERIC, msg)))
fmt
let net_cmd = !Xapi_globs.net_cmd
let wb_cmd = !Xapi_globs.wb_cmd
let tdb_tool = !Xapi_globs.tdb_tool
let domain_krb5_dir = Filename.concat Xapi_globs.samba_dir "lock/smb_krb5"
let debug_level () =
clamp
!Xapi_globs.winbind_debug_level
~low:min_debug_level ~high:max_debug_level ~default:default_debug_level
|> string_of_int
let err_msg_to_tag_map =
[
("not a properly formed account name", Auth_signature.E_INVALID_ACCOUNT)
; ("bad username or authentication", Auth_signature.E_CREDENTIALS)
(* Some other errors *)
]
type domain_info = {
service_name: string
; workgroup: string option
(* For upgrade case, the legacy db does not contain workgroup *)
; netbios_name: string option
(* Persist netbios_name to support hostname change *)
; machine_pwd_last_change_time: float option
}
let generic_error msg =
error "%s" msg ;
raise (Auth_service_error (E_GENERIC, msg))
let fail fmt = Printf.ksprintf generic_error fmt
(* Global cache for netbios name to domain name mapping using atomic map for thread safety *)
module StringMap = Map.Make (String)
let domain_netbios_name_map : string StringMap.t Atomic.t =
Atomic.make StringMap.empty
let krb5_conf_path ~domain_netbios =
Filename.concat domain_krb5_dir (Printf.sprintf "krb5.conf.%s" domain_netbios)
let env_of_krb5 domain_netbios =
let domain_krb5_cfg = krb5_conf_path ~domain_netbios in
[|Printf.sprintf "KRB5_CONFIG=%s" domain_krb5_cfg|]
let user_of_sam uname =
(* uname like DOMAIN\user1 *)
match String.split_on_char '\\' uname with
| [domain_netbios; user] ->
Ok (domain_netbios, user)
| _ ->
Error (generic_ex "Invalid domain user name %s" uname)
let user_of_upn uname =
(* uname like user1@DOMAIN *)
match String.split_on_char '@' uname with
| [user; domain] ->
Ok (domain, user)
| _ ->
Error (generic_ex "Invalid domain user name %s" uname)
(** Kerberos Domain Controller. The current implementation does not
work with non-standard ports *)
module KDC : sig
type t
val server : t -> string
(** IP address *)
val _port : t -> int
(** port number *)
val from_lookup : string -> t
(** parses net(1) command output format *)
val to_msg : t -> string
(** format for logging *)
end = struct
type t = {ip: Ipaddr.t (** IPv4/v6 of domain controller *); port: int}
let default_port = 88
let server t = Ipaddr.to_string t.ip
(** currently not used by client code *)
let _port t = t.port
let from_lookup str =
(* examples for IPv4 str returned by "net lookup kdc":
10.71.212.25:88 10.62.1.25:88. Based on experiments I believe
this is also true for IPv6 although the colon is used inside an
IPv6 address. So we split off the last number as port *)
match Astring.String.cut ~rev:true ~sep:":" str with
| Some (ip, "88") -> (
try {ip= Ipaddr.of_string ip |> Result.get_ok; port= default_port}
with _ -> fail "%s: can't parse %s as address:port" __FUNCTION__ str
)
| Some (ip, port) ->
fail "%s: KDC %s uses non-default port %s" __FUNCTION__ ip port
| None ->
fail "%s: can't parse %s as address:port" __FUNCTION__ str
(** this format is only used for logging *)
let to_msg t = Printf.sprintf "%s (port %d)" (Ipaddr.to_string t.ip) t.port
end
let max_netbios_name_length = 15
let tag_from_err_msg msg =
match
List.find_opt
(fun (k, _) -> Astring.String.is_infix ~affix:k msg)
err_msg_to_tag_map
with
| Some (_, v) ->
v
| None ->
Auth_signature.E_GENERIC
let get_domain_info_from_db () =
Server_helpers.exec_with_new_task "retrieving external auth domain workgroup"
@@ fun __context ->
let host = Helpers.get_localhost ~__context in
let service_name =
Db.Host.get_external_auth_service_name ~__context ~self:host
in
let workgroup, netbios_name, machine_pwd_last_change_time =
Db.Host.get_external_auth_configuration ~__context ~self:host
|> fun config ->
( List.assoc_opt "workgroup" config
, List.assoc_opt "netbios_name" config
, List.assoc_opt "machine_pwd_last_change_time" config
|> Option.map (fun s -> float_of_string s)
)
in
{service_name; workgroup; netbios_name; machine_pwd_last_change_time}
let update_extauth_configuration ~__context ~k ~v =
let self = Helpers.get_localhost ~__context in
Db.Host.get_external_auth_configuration ~__context ~self |> fun value ->
(k, v) :: List.remove_assoc k value |> fun value ->
Db.Host.set_external_auth_configuration ~__context ~self ~value
module Ldap = struct
module Escape = struct
(*
* Escape characters according to
* https://docs.microsoft.com/en-gb/windows/win32/adsi/search-filter-syntax?redirectedfrom=MSDN#special-characters
*)
let reg_star = {|*|} |> Re.str |> Re.compile
let reg_left_bracket = {|(|} |> Re.str |> Re.compile
let reg_right_bracket = {|)|} |> Re.str |> Re.compile
let reg_backward_slash = {|\|} |> Re.str |> Re.compile
let reg_null = "\000" |> Re.str |> Re.compile
let reg_slash = {|/|} |> Re.str |> Re.compile
let escape_map =
[
(* backward slash goes first as others will include backward slash*)
(reg_backward_slash, {|\5d|})
; (reg_star, {|\2a|})
; (reg_left_bracket, {|\28|})
; (reg_right_bracket, {|\29|})
; (reg_null, {|\00|})
; (reg_slash, {|\2f|})
]
let escape str =
List.fold_left
(fun acc element ->
let reg = fst element in
let value = snd element in
Re.replace_string reg ~by:value acc
)
str escape_map
end
let escape str = Escape.escape str
type user = {
name: string
; display_name: string
; upn: string
; account_disabled: bool
; account_expired: bool
; account_locked: bool
; password_expired: bool
}
[@@deriving rpcty]
let string_of_user x =
Rpcmarshal.marshal user.Rpc.Types.ty x |> Jsonrpc.to_string
let parse_user stdout : (user, string) result =
(* there are two steps here:
* 1. parse stdout to a (string, string) map
* 2. calculate user details using the map *)
let module Map = Map.Make (String) in
let module P = struct
open Angstrom
let space = char ' '
let not_spaces = take_while @@ function ' ' -> false | _ -> true
let is_whitespace = function
| ' ' | '\n' | '\t' | '\r' ->
true
| _ ->
false
let ws = skip_while is_whitespace
let header =
let* num_replies =
string "Got" *> space *> not_spaces
<* space
<* string "replies"
<?> "unexpected header"
in
match num_replies with
| "1" ->
return ()
| _ ->
Printf.sprintf "got %s replies" num_replies |> fail
(* example inputs: "key: value\n" or "key: value with spaces\r\n" *)
let kvp =
let* key = take_while (fun x -> x <> ':') <* char ':' in
let* value =
space *> take_while (function '\n' | '\r' -> false | _ -> true)
<* (end_of_line <|> end_of_input)
in
return (key, value)
let kvp_map =
let* () = ws *> header <* ws in
let* l = ws *> many kvp <* ws <* end_of_input in
return (l |> List.to_seq |> Map.of_seq)
let parse_kvp_map (x : string) : (string Map.t, string) result =
parse_string ~consume:All kvp_map x
end in
let ldap fmt = fmt |> Printf.ksprintf @@ Printf.sprintf "ldap %s" in
let* kvps = P.parse_kvp_map stdout <!> ldap "parsing failed '%s'" in
let get_string key =
match Map.find_opt key kvps with
| None ->
Error (ldap "missing key '%s'" key)
| Some x ->
Ok x
in
let get_string_with_default ~key ~default =
match get_string key with Ok x -> Ok x | Error _ -> Ok default
in
let get of_string key =
let* str = get_string key in
try Ok (of_string str)
with _ -> Error (ldap "invalid value for key '%s'" key)
in
let get_with_default of_string ~key ~default =
match get of_string key with Ok x -> Ok x | Error _ -> Ok default
in
let windows_nt_time_to_unix_time x =
Int64.sub (Int64.div x 10000000L) 11644473600L
in
let default = "" in
let* name = get_string_with_default ~key:"name" ~default in
let* upn = get_string_with_default ~key:"userPrincipalName" ~default in
let* display_name = get_string_with_default ~key:"displayName" ~default in
let* user_account_control = get Int32.of_string "userAccountControl" in
let* account_expires = get Int64.of_string "accountExpires" in
let* password_expires_computed =
get_with_default Int64.of_string
~key:"msDS-UserPasswordExpiryTimeComputed" ~default:Int64.max_int
in
(* see https://docs.microsoft.com/en-us/windows/win32/adschema/a-lockouttime *)
let* lockout_time =
get_with_default Int64.of_string ~key:"lockoutTime" ~default:0L
in
let is_expired zero_expired = function
| 0L ->
zero_expired
| i when i = Int64.max_int ->
false
| _ as t ->
let expire_unix_time =
windows_nt_time_to_unix_time t |> Int64.to_float
in
expire_unix_time < Unix.time ()
in
let open Int32 in
(* see https://docs.microsoft.com/en-us/windows/win32/adschema/a-useraccountcontrol#remarks
* for bit flag docs *)
let disabled_bit = of_string "0x2" in
Ok
{
name
; display_name
; upn
(* see https://docs.microsoft.com/en-us/windows/win32/adschema/a-accountexpires *)
; account_expired= is_expired false account_expires
; account_disabled= logand user_account_control disabled_bit <> 0l
; account_locked=
lockout_time <> 0L
(* see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f9e9b7e2-c7ac-4db6-ba38-71d9696981e9 *)
; password_expired= is_expired true password_expires_computed
}
let query_user ?(log_output = Helpers.On_failure) ?timeout sid domain_netbios
kdc =
let env = env_of_krb5 domain_netbios in
(* msDS-UserPasswordExpiryTimeComputed not in the default attrs list, define it explictly here *)
let attrs =
[
"name"
; "userPrincipalName"
; "displayName"
; "userAccountControl"
; "accountExpires"
; "msDS-UserPasswordExpiryTimeComputed"
; "lockoutTime"
]
in
let* stdout =
try
(* Query KDC instead of use domain here
* Just in case cannot resolve domain name from DNS *)
let args =
[
"ads"
; "sid"
; sid
; "-d"
; debug_level ()
; "--server"
; kdc
; "--machine-pass"
]
@ attrs
in
let stdout =
Helpers.call_script ~env ~log_output !Xapi_globs.net_cmd ?timeout args
in
Ok stdout
with _ -> Error (generic_ex "ldap query user info from sid failed")
in
parse_user stdout <!> generic_ex "%s"
let query_trusted_domain_name domain_netbios =
let key = "name" in
let env = env_of_krb5 domain_netbios in
let query =
Printf.sprintf "(&(objectClass=trustedDomain)(flatName=%s))"
domain_netbios
in
let args =
["ads"; "search"; "-d"; debug_level (); "--machine-pass"; query; key]
in
try
Helpers.call_script ~env !Xapi_globs.net_cmd args
|> Xapi_cmd_result.of_output ~sep:':' ~key
|> fun x -> Ok x
with _ -> Error (generic_ex "ldap query domain name failed")
let query_sid ~name ~kdc =
let key = "objectSid" in
let name = escape name in
(* Escape name to avoid injection detection *)
let query = Printf.sprintf "(|(sAMAccountName=%s)(name=%s))" name name in
let args =
["ads"; "search"; "-d"; debug_level (); "--server"; kdc; "--machine-pass"]
@ [query; key]
in
try
Helpers.call_script !Xapi_globs.net_cmd args
|> Xapi_cmd_result.of_output ~sep:':' ~key
|> fun x -> Ok x
with
| Forkhelpers.Spawn_internal_error (_, stdout, _) ->
Error (generic_ex "Ldap query sid failed: %s" stdout)
| Not_found ->
Error (generic_ex "%s not found in ldap result" key)
| _ ->
Error (generic_ex "Failed to lookup sid from username %s" name)
end
module Wbinfo = struct
let exception_of_stderr =
let open Auth_signature in
let regex = Re.Perl.(compile (re {|.*(WBC_ERR_[A-Z_]*).*|})) in
let get_regex_match x =
Option.bind (Re.exec_opt regex x) (fun g ->
match Re.Group.all g with [|_; code|] -> Some code | _ -> None
)
in
fun stderr ->
get_regex_match stderr
|> Option.map (fun code ->
(* see wbclient.h samba source code for this error list *)
match code with
| "WBC_ERR_AUTH_ERROR" ->
Auth_failure code
| "WBC_ERR_NOT_IMPLEMENTED"
| "WBC_ERR_UNKNOWN_FAILURE"
| "WBC_ERR_NO_MEMORY"
| "WBC_ERR_INVALID_PARAM"
| "WBC_ERR_WINBIND_NOT_AVAILABLE"
| "WBC_ERR_DOMAIN_NOT_FOUND"
| "WBC_ERR_INVALID_RESPONSE"
| "WBC_ERR_NSS_ERROR"
| "WBC_ERR_PWD_CHANGE_FAILED" ->
Auth_service_error (E_GENERIC, code)
| "WBC_ERR_INVALID_SID"
| "WBC_ERR_UNKNOWN_USER"
| "WBC_ERR_NOT_MAPPED"
| "WBC_ERR_UNKNOWN_GROUP" ->
Not_found
| _ ->
Auth_service_error
(E_GENERIC, Printf.sprintf "unknown error code: %s" code)
)
let call_wbinfo (args : string list) : (string, exn) result =
let generic_err () =
Error (generic_ex "'wbinfo %s' failed" (String.concat " " args))
in
(* we trust wbinfo will not print any sensitive info on failure *)
try
let stdout = Helpers.call_script ~log_output:On_failure wb_cmd args in
Ok stdout
with
| Forkhelpers.Spawn_internal_error (stderr, _stdout, _status) -> (
match exception_of_stderr stderr with
| Some e ->
Error e
| None ->
generic_err ()
)
| _ ->
generic_err ()
let parsing_ex args =
generic_ex "parsing 'wbinfo %s' failed" (String.concat " " args)
let can_resolve_krbtgt () =
match call_wbinfo ["-n"; krbtgt] with Ok _ -> true | Error _ -> false
let kerberos_auth uname passwd : (unit, exn) result =
try
let args = ["--krb5auth"; uname; "--krb5ccname"; "/dev/null"] in
let _stdout =
Helpers.call_script ~log_output:On_failure ~stdin:passwd wb_cmd args
in
Ok ()
with _ -> Error (auth_ex uname)
let sid_of_name name =
(* example:
*
* $ wbinfo -n user@domain.net
S-1-2-34-... SID_USER (1)
* $ wbinfo -n DOMAIN\user
# similar output *)
let args = ["--name-to-sid"; name] in
let* stdout = call_wbinfo args in
match String.split_on_char ' ' stdout with
| sid :: _ ->
Ok (String.trim sid)
| [] ->
Error (parsing_ex args)
let kdc_of_domain domain =
(*
* Get the domain controller name for a given domain
*
* example output:
* $ wbinfo --getdcname DOMAIN
* DC01.domain.local
*
* winbind already has some basic test for the netlogon respond time
* we just turst it
*)
let args = ["--getdcname"; domain] in
let* stdout = call_wbinfo args in
Ok (String.trim stdout)
type name = User of string | Other of string
let string_of_name = function User x -> x | Other x -> x
let name_of_sid =
(* example:
* $ wbinfo -s S-1-5-21-3143668282-2591278241-912959342-502
CONNAPP\krbtgt 1 *)
(* the number returned after the name is the 'SID type' (grep for wbcSidType
* in samba source code). for our purposes, it is sufficient to assume that
* everything that is not a user is some 'other' type*)
let regex = Re.Perl.(compile (re {|^([^\s].*)\ (\d+)\s*$|})) in
let get_regex_match x =
Option.bind (Re.exec_opt regex x) (fun g ->
match Re.Group.all g with
| [|_; name; "1"|] ->
Some (User name)
| [|_; name; _|] ->
Some (Other name)
| _ ->
None
)
in
fun sid ->
let args = ["--sid-to-name"; sid] in
let* stdout = call_wbinfo args in
match get_regex_match stdout with
| None ->
Error (parsing_ex args)
| Some x ->
Ok x
let gid_of_sid sid =
let args = ["--sid-to-gid"; sid] in
let* stdout = call_wbinfo args in
try Ok (String.trim stdout |> int_of_string)
with _ -> Error (parsing_ex args)
let user_domgroups sid =
(* example:
*
* $ wbinfo --user-domgroups S-1-2-34-...
S-1-2-34-...
S-1-5-21-...
... *)
let args = ["--user-domgroups"; sid] in
let* stdout = call_wbinfo args in
Ok (String.split_on_char '\n' stdout |> List.map String.trim)
let uid_of_sid sid =
let args = ["--sid-to-uid"; sid] in
let* stdout = call_wbinfo args in
try Ok (String.trim stdout |> int_of_string)
with _ -> Error (parsing_ex args)
type uid_info = {user_name: string; uid: int; gid: int; gecos: string}
[@@deriving rpcty]
let string_of_uid_info x =
Rpcmarshal.marshal uid_info.Rpc.Types.ty x |> Jsonrpc.to_string
let parse_uid_info stdout =
(* looks like one line from /etc/passwd: https://en.wikipedia.org/wiki/Passwd#Password_file *)
match String.split_on_char ':' stdout with
| user_name :: _passwd :: uid :: gid :: rest -> (
(* We expect at least homedir and shell at the end *)
let rest = List.rev rest in
match rest with
| _shell :: _homedir :: tail -> (
(* Rev it back to original order *)
let tail = List.rev tail in
let gecos = String.concat ":" tail in
try
Ok
{
user_name
; uid= int_of_string uid
; gid= int_of_string gid
; gecos
}
with _ -> Error ()
)
| _ ->
debug "%s uid_info format error: %s" __FUNCTION__ stdout ;
Error ()
)
| _ ->
debug "%s uid_info format error: %s" __FUNCTION__ stdout ;
Error ()
let uid_info_of_uid (uid : int) =
let args = ["--uid-info"; string_of_int uid] in
let* stdout = call_wbinfo args in
parse_uid_info stdout <!> fun () -> parsing_ex args
end
module Migrate_from_pbis = struct
(* upgrade-pbis-to-winbind handles most of the migration from PBIS database
* to winbind database
* This module just migrate necessary information to set to winbind configuration *)
let range _ e step =
let rec aux n acc =
if n >= e then
acc
else
aux (n + step) (n :: acc)
in
aux 0 [] |> List.rev
let min_valid_pbis_value_length = String.length "X''"
let extract_raw_value_from_pbis_db key =
let sql =
Printf.sprintf "select QUOTE(Value) from regvalues1 where ValueName='%s'"
key
in
let db = Xapi_globs.pbis_db_path in
let value =
Helpers.call_script ~log_output:On_failure !Xapi_globs.sqlite3 [db; sql]
|> String.trim
in
if String.length value <= min_valid_pbis_value_length then
raise (generic_ex "No value for %s in %s" key db)
else
value
let from_single_group reg input =
(* Extract value from single regular expression group
* raise Not_found if not match *)
let regex = Re.Perl.(compile (re reg)) in
Re.exec regex input |> Re.Group.all |> function
| [|_; v|] ->
v
| _ ->
raise (generic_ex "Failed to extract %s from %s" reg input)
let parse_value_from_pbis raw_value =
debug "parsing raw_value from pbis %s" raw_value ;
let hex_len = 2 in
(* Every hex value has two numbers *)
(* raw value like X'58005200540055004B002D00300032002D003000330024000000' *)
let stripped = from_single_group {|X'(.+)'$|} raw_value in
(* stripped like 58005200540055004B002D00300032002D003000330024000000 *)
range 0 (String.length stripped - hex_len) 4
|> List.map (fun p -> String.sub stripped p hex_len)
|> String.concat "" (* 585254554B2D30322D30332400 *)
|> from_single_group {|(.+)00$|}
(* 585254554B2D30322D303324 *)
|> fun s ->
Hex.to_string (`Hex s) (* XRTUK-02-03$ *) |> from_single_group {|(.+)\$$|}
(* XRTUK-02-03$ *)
let from_key ~key ~default =
try extract_raw_value_from_pbis_db key |> parse_value_from_pbis
with e ->
debug "Failed to migrate %s, error %s, fallback to %s" key
(ExnHelper.string_of_exn e)
default ;
default
let migrate_netbios_name ~__context =
(* Migrate netbios_name from PBIS db and persist to xapi db *)
let self = Helpers.get_localhost ~__context in
let default =
Db.Host.get_hostname ~__context ~self |> String.uppercase_ascii
in
let netbios_name = from_key ~key:"SamAccountName" ~default in
(* Persist migrated netbios_name *)
update_extauth_configuration ~__context ~k:"netbios_name" ~v:netbios_name ;
debug "Migrated netbios_name %s from PBIS" netbios_name ;
netbios_name
end
let kdcs_of_domain domain =
try
Helpers.call_script ~log_output:On_failure net_cmd
["lookup"; "kdc"; domain; "-d"; debug_level ()]
(* Result like 10.71.212.25:88\n10.62.1.25:88\n*)
|> String.split_on_char '\n'
|> List.filter (fun x -> String.trim x <> "") (* Remove empty lines *)
|> List.map KDC.from_lookup
with _ -> fail "%s: failed to lookup kdcs of domain %s" __FUNCTION__ domain
let workgroup_from_server kdc =
let err_msg =
Printf.sprintf "Failed to lookup workgroup from server %s" (KDC.server kdc)
in
let key = "Pre-Win2k Domain" in
try
Helpers.call_script ~log_output:On_failure net_cmd
["ads"; "lookup"; "-S"; KDC.server kdc; "-d"; debug_level ()]
|> Xapi_cmd_result.of_output ~sep:':' ~key
|> Result.ok
with _ ->
debug "Unable to query info from kdc %s, probably is broken down"
(KDC.to_msg kdc) ;
Error (Auth_service_error (E_LOOKUP, err_msg))
let kdc_of_domain_checked domain =
try
kdcs_of_domain domain
(* Does not trust DNS as it may cache some invalid kdcs, CA-360951 *)
|> List.find (fun kdc -> workgroup_from_server kdc |> Result.is_ok)
with Not_found ->
raise (generic_ex "No valid kdc found for domain %s" domain)
let query_domain_workgroup ~domain =
let err_msg = Printf.sprintf "Failed to look up domain %s workgroup" domain in
try
let kdc = kdc_of_domain_checked domain in
workgroup_from_server kdc |> Result.get_ok
with _ -> raise (Auth_service_error (E_LOOKUP, err_msg))
let config_winbind_daemon ~workgroup ~netbios_name ~domain =
let smb_config = "/etc/samba/smb.conf" in
let string_of_bool = function true -> "yes" | false -> "no" in
let scan_trusted_domains =
string_of_bool !Xapi_globs.winbind_scan_trusted_domains
in
( match (workgroup, netbios_name, domain) with
| Some wkgroup, Some netbios, Some dom ->
[
"# autogenerated by xapi"
; "[global]"
; "client use kerberos = required"
; "sync machine password to keytab = \
/etc/krb5.keytab:account_name:sync_etypes:sync_kvno:machine_password"
; "kerberos method = secrets and keytab"
; Printf.sprintf "realm = %s" dom
; "security = ADS"
; "template shell = /bin/bash"
; "winbind refresh tickets = yes"
; "winbind enum groups = no"
; "winbind enum users = no"
; Printf.sprintf "winbind scan trusted domains = %s"
scan_trusted_domains
; "winbind use krb5 enterprise principals = yes"
; Printf.sprintf "winbind cache time = %d"
!Xapi_globs.winbind_cache_time
; Printf.sprintf "machine password timeout = 0"
; Printf.sprintf "kerberos encryption types = %s"
(Kerberos_encryption_types.Winbind.to_string
!Xapi_globs.winbind_kerberos_encryption_type
)
; Printf.sprintf "workgroup = %s" wkgroup
; Printf.sprintf "netbios name = %s" netbios
; "idmap config * : backend = autorid"
; Printf.sprintf "idmap config * : range = %d-%d" 2_000_000 99_999_999
; Printf.sprintf "log level = %s" (debug_level ())
; "" (* Empty line at the end *)
]
| _ ->
["# autogenerated by xapi"; "[global]"; "" (* Empty line at the end *)]
)
|> String.concat "\n"
|> Xapi_stdext_unix.Unixext.write_string_to_file smb_config
let clear_winbind_config () =
(* Keep the winbind configuration if xapi config file specified explictly,
* The winbind configure file is useful for debug *)
if !Xapi_globs.winbind_keep_configuration then
()
else
config_winbind_daemon ~workgroup:None ~netbios_name:None ~domain:None
let from_config ~name ~err_msg ~config_params =
match List.assoc_opt name config_params with
| Some v ->
v
| _ ->
raise (Auth_service_error (E_GENERIC, err_msg))
let all_number_re = Re.Perl.re {|^\d+$|} |> Re.Perl.compile
let get_localhost_name () =
Server_helpers.exec_with_new_task "retrieving hostname" @@ fun __context ->
Helpers.get_localhost ~__context |> fun host ->
Db.Host.get_hostname ~__context ~self:host
let assert_hostname_valid ~hostname =
let all_numbers = Re.matches all_number_re hostname <> [] in
if all_numbers then
raise (generic_ex "hostname '%s' cannot contain only digits." hostname)
let assert_domain_equal_service_name ~service_name ~config_params =
(* For legeacy support, if domain exist in config_params, it must be equal to service_name *)
let domain_key = "domain" in
match List.assoc_opt domain_key config_params with
| Some domain when domain <> service_name ->
raise (generic_ex "if present, config:domain must match service-name.")
| _ ->
()
let extract_ou_config ~config_params =
try
let ou = from_config ~name:"ou" ~err_msg:"" ~config_params in
([("ou", ou)], [Printf.sprintf "createcomputer=%s" ou])
with Auth_service_error _ -> ([], [])
let persist_extauth_config ~domain ~user ~ou_conf ~workgroup ~netbios_name
~machine_pwd_last_change_time =
let value =
match
(domain, user, workgroup, netbios_name, machine_pwd_last_change_time)
with
| Some dom, Some u, Some wkg, Some netbios, Some pwd_time ->
[
("domain", dom)
; ("user", u)
; ("workgroup", wkg)
; ("netbios_name", netbios)
; ("machine_pwd_last_change_time", pwd_time)
]
@ ou_conf
| _ ->
[]
in
Server_helpers.exec_with_new_task "update external_auth_configuration"
@@ fun __context ->
Helpers.get_localhost ~__context |> fun self ->
Db.Host.set_external_auth_configuration ~__context ~self ~value ;
Db.Host.get_name_label ~__context ~self
|> debug "update external_auth_configuration for host %s"
let clear_machine_account ~service_name = function
| Some u, Some p -> (
(* Disable machine account in DC *)
let env = [|Printf.sprintf "PASSWD=%s" p|] in
let args = ["ads"; "leave"; "-U"; u; "-d"; debug_level ()] in
try
Helpers.call_script ~env net_cmd args |> ignore ;
debug "Succeed to clear the machine account for domain %s" service_name
with _ ->
let msg =
Printf.sprintf "Failed to clear the machine account for domain %s"
service_name
in
debug "%s" msg ;
raise (Auth_service_error (E_GENERIC, msg))
)
| _ ->
debug
"username or password not provided, skip clearing the machine account"
(* Clean local resources like machine password *)
let clear_local_resources () : unit =
let folder = "/var/lib/samba/private" in
let secrets_tdb = Filename.concat folder "secrets.tdb" in
try
(* Erase secrets database before clear the files *)
Helpers.call_script tdb_tool [secrets_tdb; "erase"] |> ignore ;
(* Clean local resource files *)
Xapi_stdext_unix.Unixext.rm_rec ~rm_top:false folder ;
debug "Succeed to clear local winbind resources"
with e ->
let msg = "Failed to clear local samba resources" in
error "%s : %s" msg (ExnHelper.string_of_exn e) ;
raise (Auth_service_error (E_GENERIC, msg))
let domainify_uname ~domain uname =
let open Astring.String in
if
is_infix ~affix:domain uname
|| is_infix ~affix:"@" uname
|| is_infix ~affix:{|\|} uname
|| uname = krbtgt
then
uname
else
Printf.sprintf "%s@%s" uname domain
module Winbind = struct
let name = "winbind"
let flush_cache () =
try
let args = ["cache"; "flush"] in
Helpers.call_script ~log_output:On_failure net_cmd args |> ignore
with _ -> debug "Failed to flush winbind cache, ignoring"
let is_ad_enabled ~__context =
( Helpers.get_localhost ~__context |> fun self ->
Db.Host.get_external_auth_type ~__context ~self
)
|> fun x -> x = Xapi_globs.auth_type_AD
let update_workgroup ~__context ~workgroup =
update_extauth_configuration ~__context ~k:"workgroup" ~v:workgroup
let start ~timeout ~wait_until_success =
Xapi_systemctl.start ~timeout ~wait_until_success name
let restart ~timeout ~wait_until_success =
Xapi_systemctl.restart ~timeout ~wait_until_success name
let stop ~timeout ~wait_until_success =
Xapi_systemctl.stop ~timeout ~wait_until_success name
let configure ~__context =
(* Refresh winbind configuration to handle upgrade from PBIS
* The winbind configuration needs to be refreshed before start winbind daemon *)
let {service_name; workgroup; netbios_name; _} =
get_domain_info_from_db ()
in
let netbios_name =
match netbios_name with
| None ->
Migrate_from_pbis.migrate_netbios_name ~__context
| Some name ->
name
in
let workgroup =
match workgroup with
| None ->
let workgroup = query_domain_workgroup ~domain:service_name in
(* Persist the workgroup to avoid lookup again on next startup *)
update_workgroup ~__context ~workgroup ;
workgroup
| Some workgroup ->
workgroup
in
config_winbind_daemon ~domain:(Some service_name)
~workgroup:(Some workgroup) ~netbios_name:(Some netbios_name)
let init_service ~__context =
if is_ad_enabled ~__context then (
configure ~__context ;
restart ~wait_until_success:false ~timeout:5.
) else
debug "Skip starting %s as AD is not enabled" name
let check_ready_to_serve ~timeout =