-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_api.go
More file actions
1148 lines (1004 loc) · 37.3 KB
/
client_api.go
File metadata and controls
1148 lines (1004 loc) · 37.3 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
// Package adws - High-level ADWS client for Active Directory query and transfer operations
package adws
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"os"
"strings"
"time"
soap "github.com/Macmod/go-adws/soap"
"github.com/Macmod/go-adws/transport"
"github.com/Macmod/go-adws/wscap"
"github.com/Macmod/go-adws/wsenum"
"github.com/Macmod/go-adws/wsmex"
"github.com/Macmod/go-adws/wstransfer"
"github.com/mattn/go-isatty"
)
const (
defaultADWSPort = 9389
defaultLDAPPort = 389
defaultDNSTimeout = 10 * time.Second
defaultTCPTimeout = 30 * time.Second
defaultMaxElementsPerPull = 10
)
// ADWSItem is the public alias for an ADWS object item.
type ADWSItem = soap.ADWSItem
// ADWSValue is the public alias for an ADWS attribute value.
type ADWSValue = soap.ADWSValue
// WSClient represents an ADWS client for querying and transfer operations in Active Directory.
//
// ADWS provides an alternative to traditional LDAP (ports 389/3268) by using
// port 9389 with SOAP/XML over an authenticated and encrypted channel.
//
// Protocol stack (bottom to top):
// 1. TCP connection to dc.domain.com:9389
// 2. NNS (.NET NegotiateStream) - NTLM/Kerberos authentication with signing/sealing
// 3. NMF (.NET Message Framing) - Record boundaries and encoding negotiation
// 4. SOAP/XML - WS-Enumeration/WS-Transfer protocol operations
type WSClient struct {
properDCAddr string // DC address resolved at construction time (FQDN or IP)
port int // ADWS port (default 9389)
ldapPort int // LDAP instance port advertised in SOAP headers (default 389)
username string // Domain\username or username@domain
password string // Password
ntHash string // NT hash (hex)
aesKey string // Kerberos AES key (hex, 32 or 64 chars)
ccache string // Kerberos ccache path
pfxFile string // PKCS#12 certificate file for PKINIT
pfxPassword string // Password for PFX file
certFile string // PEM certificate file for PKINIT
keyFile string // PEM private key file for PKINIT
kerberosNeeded bool // Prefer Kerberos/SPNEGO when true
domain string // Domain name
dnsTimeout time.Duration // Timeout for DNS operations (DC discovery / PTR lookup)
tcpTimeout time.Duration // Timeout for TCP dial and protocol operations
resolverOpts transport.ResolverOptions // DNS resolver options
tlsConfig *tls.Config // TLS config (for future TLS support)
// Connection state
conn net.Conn // TCP connection
nnsConn *transport.NNSConnection // NNS layer
nmfConn *transport.NMFConnection // NMF layer
connected bool // Connection state
debugXML bool // Print raw SOAP XML for debugging
}
// Config contains ADWS client configuration.
type Config struct {
DCAddr string // DC address: FQDN, IP, or empty to trigger SRV-based discovery
Port int // ADWS port (default 9389)
LDAPPort int // LDAP port used in SOAP headers for the target directory service (default 389; use 3268 for GC)
Username string // Domain\username or username@domain (required)
Password string // Password (optional if NTHash/CCachePath/PFX/Cert provided)
NTHash string // NT hash auth (optional)
AESKey string // Kerberos AES-128 or AES-256 session key, hex-encoded (optional, implies Kerberos)
CCachePath string // Kerberos ccache path (optional, implies Kerberos)
PFXFile string // PKCS#12 (.pfx/.p12) certificate file for PKINIT (optional)
PFXPassword string // Password for PFX file (optional, default empty)
CertFile string // PEM certificate file for PKINIT (use with KeyFile)
KeyFile string // PEM RSA private key file for PKINIT (use with CertFile)
UseKerberos bool // Use SPNEGO/Kerberos negotiation
Domain string // Domain name (required)
DNSTimeout time.Duration // Timeout for DNS operations - DC discovery and PTR lookup (default 10s)
TCPTimeout time.Duration // Timeout for TCP dial and ADWS protocol operations (default 30s)
UseTLS bool // Use TLS (future - currently not supported by ADWS)
DebugXML bool // Print raw SOAP XML when true (or via ADWS_DEBUG_XML=1)
ResolverOptions transport.ResolverOptions // DNS resolver options for DC discovery and dialling
}
// NewWSClient creates a new ADWS client with the given configuration.
// Credential fields (Username, Password, etc.) are validated at Connect() time,
// so callers that only intend to call GetMetadata() may omit them.
// DCAddr may be empty when Domain is set; in that case a DC is discovered via
// DNS SRV records (_ldap._tcp.<domain>) immediately during construction.
func NewWSClient(cfg Config) (*WSClient, error) {
if cfg.CertFile != "" && cfg.KeyFile == "" {
return nil, fmt.Errorf("KeyFile is required when CertFile is set")
}
if cfg.Port == 0 {
cfg.Port = defaultADWSPort
}
if cfg.LDAPPort == 0 {
cfg.LDAPPort = defaultLDAPPort
}
if cfg.LDAPPort <= 0 || cfg.LDAPPort > 65535 {
return nil, fmt.Errorf("LDAPPort out of range: %d", cfg.LDAPPort)
}
if cfg.DNSTimeout == 0 {
cfg.DNSTimeout = defaultDNSTimeout
}
if cfg.TCPTimeout == 0 {
cfg.TCPTimeout = defaultTCPTimeout
}
hasCert := cfg.PFXFile != "" || cfg.CertFile != ""
kerberosNeeded := cfg.UseKerberos || cfg.CCachePath != "" || cfg.AESKey != "" || hasCert
ctx, cancel := context.WithTimeout(context.Background(), cfg.DNSTimeout)
defer cancel()
properDCAddr, err := resolveProperDCAddr(ctx, cfg.DCAddr, cfg.Domain, kerberosNeeded, cfg.ResolverOptions)
if err != nil {
return nil, fmt.Errorf("failed to resolve DC address: %w", err)
}
return &WSClient{
properDCAddr: properDCAddr,
port: cfg.Port,
ldapPort: cfg.LDAPPort,
username: cfg.Username,
password: cfg.Password,
ntHash: cfg.NTHash,
aesKey: cfg.AESKey,
ccache: cfg.CCachePath,
pfxFile: cfg.PFXFile,
pfxPassword: cfg.PFXPassword,
certFile: cfg.CertFile,
keyFile: cfg.KeyFile,
kerberosNeeded: kerberosNeeded,
domain: cfg.Domain,
dnsTimeout: cfg.DNSTimeout,
tcpTimeout: cfg.TCPTimeout,
resolverOpts: cfg.ResolverOptions,
debugXML: cfg.DebugXML,
}, nil
}
// Connect establishes a connection to the ADWS server.
func (c *WSClient) Connect() error {
if c.connected {
return fmt.Errorf("already connected")
}
// Validate credentials here — they are only needed for authenticated connections.
if c.username == "" {
return fmt.Errorf("Username is required")
}
if c.domain == "" {
return fmt.Errorf("Domain is required")
}
hasCert := c.pfxFile != "" || c.certFile != ""
if c.password == "" && c.ntHash == "" && c.aesKey == "" && c.ccache == "" && !hasCert {
return fmt.Errorf("one of Password, NTHash, AESKey, CCachePath, PFXFile, or CertFile+KeyFile is required")
}
ctx, cancel := context.WithTimeout(context.Background(), c.tcpTimeout)
defer cancel()
conn, err := transport.DialADWS(ctx, c.properDCAddr, c.port, c.resolverOpts)
if err != nil {
return err
}
c.conn = conn
targetSPN := c.buildTargetSPN(c.properDCAddr)
c.nnsConn = c.newNNSConnection(c.conn, targetSPN)
c.nmfConn = transport.NewNMFConnection(c.nnsConn, c.properDCAddr, c.port)
resource := wsenum.EndpointEnumeration
if err := c.nmfConn.Connect(resource); err != nil {
c.conn.Close()
return fmt.Errorf("NMF connection failed: %w", err)
}
c.connected = true
return nil
}
// Query performs an LDAP query via ADWS and returns all results.
func (c *WSClient) Query(baseDN, filter string, attrs []string, scope int) ([]ADWSItem, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
baseDN, filter, attrs, err := wsenum.ValidateQueryInput(baseDN, filter, attrs, scope)
if err != nil {
return nil, err
}
service := wsenum.NewWSEnumClient(c.nmfConn, c.properDCAddr, c.port, c.ldapPort, c.debugPrintXML, c.debugPrintPullResult)
return wsenum.ExecuteQuery(service, baseDN, filter, attrs, scope, defaultMaxElementsPerPull, defaultMaxElementsPerPull, nil)
}
// Get retrieves a single AD object by distinguished name.
func (c *WSClient) Get(dn string, attrs []string) (*ADWSItem, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
dn = strings.TrimSpace(dn)
if dn == "" {
return nil, fmt.Errorf("dn is required")
}
return c.WSTransferGet(dn, attrs)
}
// GetMetadata fetches and parses the WS-MetadataExchange document from the unauthenticated
// ADWS MEX endpoint. No credentials are required.
func (c *WSClient) GetMetadata() (*wsmex.ADWSMetadata, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.tcpTimeout)
defer cancel()
conn, err := transport.DialADWS(ctx, c.properDCAddr, c.port, c.resolverOpts)
if err != nil {
return nil, err
}
targetSPN := c.buildTargetSPN(c.properDCAddr)
nnsConn := transport.NewNNSConnectionAnonymous(conn, targetSPN, false, transport.ProtectionNone)
nmfConn := transport.NewNMFConnection(nnsConn, c.properDCAddr, c.port)
if err := nmfConn.Connect(wsmex.EndpointMEX); err != nil {
_ = nnsConn.Close()
return nil, fmt.Errorf("NMF connection to MEX endpoint failed: %w", err)
}
defer nnsConn.Close()
client := wsmex.NewWSMexClient(nmfConn, c.properDCAddr, c.port, c.debugPrintXML)
return client.GetMetadata()
}
// Close closes the ADWS connection.
func (c *WSClient) Close() error {
if !c.connected {
return nil
}
var closeErr error
if c.nnsConn != nil {
closeErr = errors.Join(closeErr, c.nnsConn.Close())
} else if c.conn != nil {
closeErr = errors.Join(closeErr, c.conn.Close())
}
c.connected = false
return closeErr
}
// QueryWithCallback performs an LDAP query and calls a callback for each batch of results.
func (c *WSClient) QueryWithCallback(baseDN, filter string, attrs []string, scope int, callback func(items []ADWSItem) error) error {
if !c.connected {
return fmt.Errorf("not connected")
}
if callback == nil {
return fmt.Errorf("callback is required")
}
baseDN, filter, attrs, err := wsenum.ValidateQueryInput(baseDN, filter, attrs, scope)
if err != nil {
return err
}
batchCh := make(chan []ADWSItem, 1)
execErrCh := make(chan error, 1)
go func() {
execErrCh <- c.QueryWithBatchChannel(baseDN, filter, attrs, scope, defaultMaxElementsPerPull, batchCh)
close(batchCh)
}()
var callbackErr error
for batch := range batchCh {
if callbackErr != nil {
continue
}
if err := callback(batch); err != nil {
callbackErr = fmt.Errorf("callback error: %w", err)
}
}
execErr := <-execErrCh
if execErr != nil {
return execErr
}
return callbackErr
}
// QueryWithBatchChannel performs an LDAP query and streams each Pull batch to batchChannel.
func (c *WSClient) QueryWithBatchChannel(baseDN, filter string, attrs []string, scope, maxElementsPerPull int, batchChannel chan<- []ADWSItem) error {
if !c.connected {
return fmt.Errorf("not connected")
}
if batchChannel == nil {
return fmt.Errorf("batchChannel is required")
}
baseDN, filter, attrs, err := wsenum.ValidateQueryInput(baseDN, filter, attrs, scope)
if err != nil {
return err
}
service := wsenum.NewWSEnumClient(c.nmfConn, c.properDCAddr, c.port, c.ldapPort, c.debugPrintXML, c.debugPrintPullResult)
_, err = wsenum.ExecuteQuery(service, baseDN, filter, attrs, scope, maxElementsPerPull, defaultMaxElementsPerPull, batchChannel)
return err
}
func (c *WSClient) isDebugXML() bool {
if c.debugXML {
return true
}
return os.Getenv("ADWS_DEBUG_XML") == "1"
}
func (c *WSClient) debugPrintXML(label, xmlPayload string) {
if !c.isDebugXML() {
return
}
pretty := soap.PrettyXML(xmlPayload)
if c.shouldColorDebugXML() {
pretty = colorizeXMLTags(pretty)
}
fmt.Printf("[adws-debug] %s XML:\n%s\n", label, pretty)
}
func (c *WSClient) shouldColorDebugXML() bool {
if strings.TrimSpace(os.Getenv("NO_COLOR")) != "" {
return false
}
if strings.EqualFold(strings.TrimSpace(os.Getenv("TERM")), "dumb") {
return false
}
if strings.TrimSpace(os.Getenv("SOPA_FORCE_COLOR")) == "1" {
return true
}
return isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
}
func colorizeXMLTags(prettyXML string) string {
// Minimal highlighting: colorize "<...>" segments.
const (
cCyan = "\x1b[36m"
cReset = "\x1b[0m"
)
var b strings.Builder
b.Grow(len(prettyXML) + 32)
for i := 0; i < len(prettyXML); i++ {
ch := prettyXML[i]
if ch != '<' {
b.WriteByte(ch)
continue
}
j := strings.IndexByte(prettyXML[i:], '>')
if j < 0 {
b.WriteByte(ch)
continue
}
j = i + j
b.WriteString(cCyan)
b.WriteString(prettyXML[i : j+1])
b.WriteString(cReset)
i = j
}
return b.String()
}
func (c *WSClient) debugPrintPullResult(pr *soap.PullResponse) {
if !c.isDebugXML() {
return
}
fmt.Printf("[adws-debug] Parsed pull items=%d end=%v nextCtx=%q\n", len(pr.Items), pr.EndOfSequence, pr.EnumerationContext)
}
// IsConnected returns true if the client is connected.
func (c *WSClient) IsConnected() bool {
return c.connected
}
// GetDCAddr returns the DC address this client resolved at construction time.
// This is an FQDN when Kerberos is in use, or whatever was passed / discovered otherwise.
func (c *WSClient) GetDCFQDN() string {
return c.properDCAddr
}
// SetDNSTimeout sets the timeout for DNS operations (DC discovery and PTR lookup).
func (c *WSClient) SetDNSTimeout(timeout time.Duration) {
c.dnsTimeout = timeout
}
// SetTCPTimeout sets the timeout for TCP dial and ADWS protocol operations.
func (c *WSClient) SetTCPTimeout(timeout time.Duration) {
c.tcpTimeout = timeout
}
// SetDebugXML enables/disables raw SOAP response logging.
func (c *WSClient) SetDebugXML(enabled bool) {
c.debugXML = enabled
}
// WSTransferGet executes a WS-Transfer Get against the Resource endpoint.
func (c *WSClient) WSTransferGet(dn string, attrs []string) (*ADWSItem, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
result, err := c.withEndpointWSTransferClientResult(wstransfer.EndpointResource, func(tx *wstransfer.WSTransferClient) (interface{}, error) {
return tx.Get(dn, attrs)
})
if err != nil {
return nil, err
}
if item, ok := result.(*ADWSItem); ok {
return item, nil
}
return nil, nil
}
// WSTransferDelete executes a WS-Transfer Delete against the Resource endpoint.
func (c *WSClient) WSTransferDelete(dn string) error {
if !c.connected {
return fmt.Errorf("not connected")
}
_, err := c.withEndpointWSTransferClientResult(wstransfer.EndpointResource, func(tx *wstransfer.WSTransferClient) (interface{}, error) {
return nil, tx.Delete(dn)
})
return err
}
// WSTransferPut executes a WS-Transfer Put against the Resource endpoint.
func (c *WSClient) WSTransferPut(dn, instanceXML string) error {
if !c.connected {
return fmt.Errorf("not connected")
}
_, err := c.withEndpointWSTransferClientResult(wstransfer.EndpointResource, func(tx *wstransfer.WSTransferClient) (interface{}, error) {
return nil, tx.Put(dn, instanceXML)
})
return err
}
// WSTransferModifyAttribute performs a WS-Transfer Put using an IMDA ModifyRequest.
//
// operation must be one of: add, replace, delete.
// attr may be either a local attribute name (e.g. "description") or a fully-qualified type (e.g. "addata:description").
// Values are treated as xsd:string.
func (c *WSClient) WSTransferModifyAttribute(dn, operation, attr string, values []string) error {
if !c.connected {
return fmt.Errorf("not connected")
}
modifyXML, err := soap.BuildModifyRequest(operation, attr, values, "xsd:string")
if err != nil {
return err
}
return c.WSTransferPut(dn, modifyXML)
}
// WSTransferCreate executes a WS-Transfer Create against the ResourceFactory endpoint.
//
// The returned address is best-effort and may be empty if the server response does not include
// a parsable ResourceCreated/Address or objectReferenceProperty.
func (c *WSClient) WSTransferCreate(instanceXML string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.Create(instanceXML)
})
}
// WSTransferCreateComputer executes a WS-Transfer Create (IMDA AddRequest) against the
// ResourceFactory endpoint to create a simple computer object under parentDN.
//
// This is a state-changing operation.
func (c *WSClient) WSTransferCreateComputer(parentDN, computerName string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.CreateComputer(parentDN, computerName)
})
}
// WSTransferAddComputer executes a WS-Transfer Create (IMDA AddRequest) against the
// ResourceFactory endpoint to create a computer account under parentDN.
//
// This mirrors SharpADWS' AddComputer method and sets unicodePwd, dNSHostName,
// userAccountControl, and servicePrincipalName.
func (c *WSClient) WSTransferAddComputer(parentDN, computerName, computerPass string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.AddComputer(parentDN, computerName, c.domain, computerPass)
})
}
// WSTransferAddUser creates a user object under parentDN via ResourceFactory.
func (c *WSClient) WSTransferAddUser(parentDN, userName, userPass string, enabled bool) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.AddUser(parentDN, userName, c.domain, userPass, enabled)
})
}
// WSTransferAddGroup creates a group object under parentDN via ResourceFactory.
func (c *WSClient) WSTransferAddGroup(parentDN, groupName, groupType string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.AddGroup(parentDN, groupName, groupType)
})
}
// WSTransferAddOU creates an organizationalUnit object under parentDN via ResourceFactory.
func (c *WSClient) WSTransferAddOU(parentDN, ouName string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.AddOU(parentDN, ouName)
})
}
// WSTransferAddContainer creates a container object under parentDN via ResourceFactory.
func (c *WSClient) WSTransferAddContainer(parentDN, cn string) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
return c.withEndpointWSTransferClient(wstransfer.EndpointResourceFactory, func(tx *wstransfer.WSTransferClient) (string, error) {
return tx.AddContainer(parentDN, cn)
})
}
func (c *WSClient) withEndpointWSTransferClient(endpoint string, fn func(tx *wstransfer.WSTransferClient) (string, error)) (string, error) {
result, err := c.withEndpointWSTransferClientResult(endpoint, func(tx *wstransfer.WSTransferClient) (interface{}, error) {
return fn(tx)
})
if err != nil {
return "", err
}
if str, ok := result.(string); ok {
return str, nil
}
return "", nil
}
func (c *WSClient) withEndpointWSTransferClientResult(endpoint string, fn func(tx *wstransfer.WSTransferClient) (interface{}, error)) (interface{}, error) {
if fn == nil {
return nil, fmt.Errorf("fn is required")
}
ctx, cancel := context.WithTimeout(context.Background(), c.tcpTimeout)
defer cancel()
conn, err := transport.DialADWS(ctx, c.properDCAddr, c.port, c.resolverOpts)
if err != nil {
return nil, err
}
targetSPN := c.buildTargetSPN(c.properDCAddr)
nnsConn := c.newNNSConnection(conn, targetSPN)
nmfConn := transport.NewNMFConnection(nnsConn, c.properDCAddr, c.port)
if err := nmfConn.Connect(endpoint); err != nil {
_ = nnsConn.Close()
return nil, fmt.Errorf("NMF connection failed for endpoint %s: %w", endpoint, err)
}
defer nnsConn.Close()
tx := wstransfer.NewWSTransferClient(nmfConn, c.properDCAddr, c.port, endpoint, c.ldapPort, c.debugPrintXML)
return fn(tx)
}
func (c *WSClient) buildTargetSPN(target string) string {
return fmt.Sprintf("host/%s", target)
}
// resolveProperDCAddr determines the address (FQDN or IP) to use for connecting
// to the DC and for Kerberos targeting.
//
// - Empty dcAddr + domain set → SRV discovery (_ldap._tcp.<domain>)
// - IP + kerberosNeeded → PTR reverse lookup to obtain the FQDN
// - Anything else → returned unchanged
func resolveProperDCAddr(ctx context.Context, dcAddr, domain string, kerberosNeeded bool, opts transport.ResolverOptions) (string, error) {
if dcAddr == "" {
if domain == "" {
return "", fmt.Errorf("DCAddr and Domain are both empty: cannot discover a DC")
}
return transport.DiscoverDC(ctx, domain, opts)
}
if net.ParseIP(dcAddr) != nil && kerberosNeeded {
return transport.ResolveIPToFQDN(ctx, dcAddr, opts)
}
return dcAddr, nil
}
func (c *WSClient) newNNSConnection(conn net.Conn, targetSPN string) *transport.NNSConnection {
chosenLevel := transport.ProtectionEncryptAndSign
// PKINIT: PFX takes precedence over cert+key.
if c.pfxFile != "" || c.certFile != "" {
var (
rsaKey *rsa.PrivateKey
x509Cert *x509.Certificate
loadErr error
)
if c.pfxFile != "" {
rsaKey, x509Cert, loadErr = transport.LoadPFX(c.pfxFile, c.pfxPassword)
} else {
rsaKey, x509Cert, loadErr = transport.LoadPEM(c.certFile, c.keyFile)
}
if loadErr == nil {
return transport.NewNNSConnectionWithPKINIT(conn, c.domain, c.username, x509Cert, rsaKey, targetSPN, chosenLevel).
WithResolverOptions(c.resolverOpts)
}
// If credential load fails, fall through so Connect() surfaces the real error at auth time.
_, _ = fmt.Fprintf(os.Stderr, "sopa: PKINIT credential load error: %v\n", loadErr)
}
if c.ccache != "" {
return transport.NewNNSConnectionWithCCache(
conn,
c.domain,
c.username,
c.ccache,
targetSPN,
chosenLevel,
).WithResolverOptions(c.resolverOpts)
}
if c.aesKey != "" {
return transport.NewNNSConnectionWithAESKey(
conn,
c.domain,
c.username,
c.aesKey,
targetSPN,
chosenLevel,
).WithResolverOptions(c.resolverOpts)
}
if c.ntHash != "" {
return transport.NewNNSConnectionWithNTHash(
conn,
c.domain,
c.username,
c.ntHash,
targetSPN,
c.kerberosNeeded,
chosenLevel,
).WithResolverOptions(c.resolverOpts)
}
return transport.NewNNSConnection(
conn,
c.domain,
c.username,
c.password,
targetSPN,
c.kerberosNeeded,
chosenLevel,
).WithResolverOptions(c.resolverOpts)
}
// NameTranslateResult is the public alias for an MS-ADCAP TranslateName result.
type NameTranslateResult = soap.NameTranslateResult
// ADCAPActiveDirectoryObject is the public alias for an MS-ADCAP ActiveDirectoryObject.
type ADCAPActiveDirectoryObject = soap.ADCAPActiveDirectoryObject
// ADCAPActiveDirectoryPrincipal is the public alias for an MS-ADCAP ActiveDirectoryPrincipal.
type ADCAPActiveDirectoryPrincipal = soap.ADCAPActiveDirectoryPrincipal
// ADCAPActiveDirectoryGroup is the public alias for an MS-ADCAP ActiveDirectoryGroup.
type ADCAPActiveDirectoryGroup = soap.ADCAPActiveDirectoryGroup
// ADCAPActiveDirectoryDomain is the public alias for an MS-ADCAP ActiveDirectoryDomain.
type ADCAPActiveDirectoryDomain = soap.ADCAPActiveDirectoryDomain
// ADCAPActiveDirectoryForest is the public alias for an MS-ADCAP ActiveDirectoryForest.
type ADCAPActiveDirectoryForest = soap.ADCAPActiveDirectoryForest
// ADCAPActiveDirectoryDomainController is the public alias for an MS-ADCAP ActiveDirectoryDomainController.
type ADCAPActiveDirectoryDomainController = soap.ADCAPActiveDirectoryDomainController
// ADCAPVersionInfo is the public alias for an MS-ADCAP GetVersion result.
type ADCAPVersionInfo = soap.ADCAPVersionInfo
// ADCAPSetPassword sets the password for the specified account DN in the specified partition.
func (c *WSClient) ADCAPSetPassword(accountDN, partitionDN, newPassword string) error {
if !c.connected {
return fmt.Errorf("not connected")
}
accountDN = strings.TrimSpace(accountDN)
partitionDN = strings.TrimSpace(partitionDN)
if accountDN == "" {
return fmt.Errorf("accountDN is required")
}
if partitionDN == "" {
return fmt.Errorf("partitionDN is required")
}
return c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
return am.SetPassword(accountDN, partitionDN, newPassword)
})
}
// ADCAPChangePassword changes the password for the specified account DN in the specified partition.
func (c *WSClient) ADCAPChangePassword(accountDN, partitionDN, oldPassword, newPassword string) error {
if !c.connected {
return fmt.Errorf("not connected")
}
accountDN = strings.TrimSpace(accountDN)
partitionDN = strings.TrimSpace(partitionDN)
if accountDN == "" {
return fmt.Errorf("accountDN is required")
}
if partitionDN == "" {
return fmt.Errorf("partitionDN is required")
}
return c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
return am.ChangePassword(accountDN, partitionDN, oldPassword, newPassword)
})
}
// ADCAPTranslateName translates an array of names from one format to another.
// Valid formats: DistinguishedName, CanonicalName.
func (c *WSClient) ADCAPTranslateName(formatOffered, formatDesired string, names []string) ([]NameTranslateResult, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
return c.withAccountManagementClientResults(func(am *wscap.WSCapClient) ([]NameTranslateResult, error) {
return am.TranslateName(formatOffered, formatDesired, names)
})
}
// ADCAPGetADGroupMember returns the members of the specified group.
func (c *WSClient) ADCAPGetADGroupMember(groupDN, partitionDN string, recursive bool) ([]ADCAPActiveDirectoryPrincipal, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
groupDN = strings.TrimSpace(groupDN)
partitionDN = strings.TrimSpace(partitionDN)
if groupDN == "" {
return nil, fmt.Errorf("groupDN is required")
}
if partitionDN == "" {
return nil, fmt.Errorf("partitionDN is required")
}
var out []ADCAPActiveDirectoryPrincipal
err := c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
res, err := am.GetADGroupMember(groupDN, partitionDN, recursive)
if err != nil {
return err
}
out = res
return nil
})
return out, err
}
// ADCAPGetADPrincipalAuthorizationGroup returns the security-enabled groups used for authorization for a principal.
func (c *WSClient) ADCAPGetADPrincipalAuthorizationGroup(principalDN, partitionDN string) ([]ADCAPActiveDirectoryGroup, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
principalDN = strings.TrimSpace(principalDN)
partitionDN = strings.TrimSpace(partitionDN)
if principalDN == "" {
return nil, fmt.Errorf("principalDN is required")
}
if partitionDN == "" {
return nil, fmt.Errorf("partitionDN is required")
}
var out []ADCAPActiveDirectoryGroup
err := c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
res, err := am.GetADPrincipalAuthorizationGroup(partitionDN, principalDN)
if err != nil {
return err
}
out = res
return nil
})
return out, err
}
// ADCAPGetADPrincipalGroupMembership returns a set of groups associated with the specified principal.
//
// Note: per MS-ADCAP, this returns direct group membership only (no transitive expansion).
func (c *WSClient) ADCAPGetADPrincipalGroupMembership(principalDN, partitionDN, resourceContextPartition, resourceContextServer string) ([]ADCAPActiveDirectoryGroup, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
principalDN = strings.TrimSpace(principalDN)
partitionDN = strings.TrimSpace(partitionDN)
if principalDN == "" {
return nil, fmt.Errorf("principalDN is required")
}
if partitionDN == "" {
return nil, fmt.Errorf("partitionDN is required")
}
var out []ADCAPActiveDirectoryGroup
err := c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
res, err := am.GetADPrincipalGroupMembership(partitionDN, principalDN, resourceContextPartition, resourceContextServer)
if err != nil {
return err
}
out = res
return nil
})
return out, err
}
// PrincipalGroupMembership returns a set of groups associated with the specified principal,
// using the MS-ADCAP GetADPrincipalGroupMembership custom action.
//
// Note: per MS-ADCAP, no transitive group membership evaluation is performed.
func (c *WSClient) PrincipalGroupMembership(principalDN string) ([]ADWSItem, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
principalDN = strings.TrimSpace(principalDN)
if principalDN == "" {
return nil, fmt.Errorf("principalDN is required")
}
partitionDN := c.domainToBaseDN()
groups, err := c.ADCAPGetADPrincipalGroupMembership(principalDN, partitionDN, "", "")
if err != nil {
return nil, err
}
out := make([]ADWSItem, 0, len(groups))
for _, g := range groups {
dn := strings.TrimSpace(g.DistinguishedName)
if dn == "" {
dn = strings.TrimSpace(g.Name)
}
if dn == "" {
dn = strings.TrimSpace(g.SamAccountName)
}
out = append(out, ADWSItem{ObjectGUID: g.ObjectGuid, DistinguishedName: dn, Attributes: map[string][]ADWSValue{}})
}
return out, nil
}
// PrincipalAuthorizationGroups returns the security-enabled groups used for authorization decisions
// for the specified principal, using the MS-ADCAP GetADPrincipalAuthorizationGroup custom action.
func (c *WSClient) PrincipalAuthorizationGroups(principalDN string) ([]ADWSItem, error) {
if !c.connected {
return nil, fmt.Errorf("not connected")
}
principalDN = strings.TrimSpace(principalDN)
if principalDN == "" {
return nil, fmt.Errorf("principalDN is required")
}
partitionDN := c.domainToBaseDN()
groups, err := c.ADCAPGetADPrincipalAuthorizationGroup(principalDN, partitionDN)
if err != nil {
return nil, err
}
out := make([]ADWSItem, 0, len(groups))
for _, g := range groups {
dn := strings.TrimSpace(g.DistinguishedName)
if dn == "" {
dn = strings.TrimSpace(g.Name)
}
if dn == "" {
dn = strings.TrimSpace(g.SamAccountName)
}
out = append(out, ADWSItem{ObjectGUID: g.ObjectGuid, DistinguishedName: dn, Attributes: map[string][]ADWSValue{}})
}
return out, nil
}
func (c *WSClient) domainToBaseDN() string {
// baseDN derivation in CLI is also domain->DN; in the library we can reuse the domain.
parts := strings.Split(strings.TrimSpace(c.domain), ".")
var b strings.Builder
for i := 0; i < len(parts); i++ {
p := strings.TrimSpace(parts[i])
if p == "" {
continue
}
if b.Len() > 0 {
b.WriteString(",")
}
b.WriteString("DC=")
b.WriteString(p)
}
return b.String()
}
func (c *WSClient) withAccountManagementClient(fn func(am *wscap.WSCapClient) error) error {
if fn == nil {
return fmt.Errorf("fn is required")
}
ctx, cancel := context.WithTimeout(context.Background(), c.tcpTimeout)
defer cancel()
conn, err := transport.DialADWS(ctx, c.properDCAddr, c.port, c.resolverOpts)
if err != nil {
return err
}
targetSPN := c.buildTargetSPN(c.properDCAddr)
nnsConn := c.newNNSConnection(conn, targetSPN)
nmfConn := transport.NewNMFConnection(nnsConn, c.properDCAddr, c.port)
if err := nmfConn.Connect(wscap.EndpointAccountManagement); err != nil {
_ = nnsConn.Close()
return fmt.Errorf("NMF connection failed for endpoint %s: %w", wscap.EndpointAccountManagement, err)
}
defer nnsConn.Close()
am := wscap.NewWSCapClient(nmfConn, c.properDCAddr, c.port, wscap.EndpointAccountManagement, c.ldapPort, c.debugPrintXML)
return fn(am)
}
func (c *WSClient) withAccountManagementClientResults(fn func(am *wscap.WSCapClient) ([]NameTranslateResult, error)) ([]NameTranslateResult, error) {
if fn == nil {
return nil, fmt.Errorf("fn is required")
}
var out []NameTranslateResult
err := c.withAccountManagementClient(func(am *wscap.WSCapClient) error {
res, err := fn(am)
if err != nil {
return err
}
out = res
return nil
})
return out, err
}
// IMDAAttribute describes an attribute for an IMDA AddRequest.
//
// Name should be a fully qualified attribute type (e.g. "addata:cn", "addata:objectClass").
// XSIType should be an xsd:* type (e.g. "xsd:string", "xsd:int", "xsd:base64Binary").
// Values contains 1+ values for the attribute.
type IMDAAttribute struct {
Name string
XSIType string
Values []string
}
// WSTransferCreateCustom creates a custom object via WS-Transfer ResourceFactory using an IMDA AddRequest.
//
// parentDN is the container DN; rdn is the relative distinguished name (e.g. "CN=MyObject").
// The required IMDA attributes ad:relativeDistinguishedName and ad:container-hierarchy-parent are always injected.
func (c *WSClient) WSTransferCreateCustom(parentDN, rdn string, attrs []IMDAAttribute) (string, error) {
if !c.connected {
return "", fmt.Errorf("not connected")
}
parentDN = strings.TrimSpace(parentDN)
rdn = strings.TrimSpace(rdn)