
ADWSを介したActive DirectoryへのネイティブC++アクセス、.NET不要、WCF不要、HTTPスタック不要。
ネイティブC++によるActive DirectoryへのADWS経由のアクセス。.NET、WCF、HTTPスタック不要。
BridgeHeadは、完全な**Active Directory Web Services (ADWS)**プロトコルスタックをTCP上で直接実装するC++20静的ライブラリです。名前はADブリッジヘッドサーバーに由来しており、ディレクトリトラフィックが通過するゲートウェイであり、あなたのC++コードに、PowerShellのGet-ADUserやGet-ADComputerが内部で使用しているのと同じ低レベルなポート9389へのアクセスを提供します。
トランスポート層は、共通のbridgehead::transport::IByteStreamインターフェースを介して下位の層をラップします。NbfseCodecは、AdwsClientによって呼び出され、フレーミングの前後にSOAPメッセージをエンコード/デコードするコーデックユーティリティです。```
AdwsClient WS-Enumeration + WS-Transfer [MS-ADDM]
├── NbfseCodec .NET Binary Format for SOAP [MC-NBFSE] (encode/decode)
└── NmfFramer .NET Message Framing [MC-NMF] (send/receive frames)
└── NnsSession .NET NegotiateStream [MS-NNS]
└── TcpSocket raw TCP/IP
コンシューマーのエントリポイントは `bridgehead::adws::AdwsClient` です。
---
## クイックスタート
### すべてのユーザーをクエリ、列挙する```cpp
#include "bridgehead/adws/AdwsClient.hpp"
// NTLM (works on any host)
auto client = bridgehead::adws::AdwsClient::EnumerationClient(
"192.168.1.10", // DC IP or hostname
"DC01.corp.local", // DC FQDN, used in NMF Via header and Kerberos SPN
"CORP", // NetBIOS domain name
"Administrator", // username
"Passw0rd" // password
);
// Kerberos (username hidden on the wire; requires DC reachable on port 88)
auto client = bridgehead::adws::AdwsClient::EnumerationClient(
"192.168.1.10", "DC01.corp.local", "CORP",
"Administrator", "Passw0rd",
bridgehead::adws::AuthPackage::Kerberos
);
auto users = client.Query(
"(objectClass=user)",
{"sAMAccountName", "distinguishedName", "memberOf"}
);
for (auto& obj : users)
std::cout << obj.FirstValue("sAMAccountName") << '\n';
client.Enumerate( "(objectClass=computer)", {"dNSHostName", "operatingSystem"}, "", // empty = domain root base DN [](const bridgehead::adws::LdapObject& obj) { std::cout << obj.FirstValue("dNSHostName") << '\n'; return true; // return false to stop early (sends wsen:Release) } );
### スコープとページネーション```cpp
// OneLevel scope, 50 objects per Pull round-trip
client.Query(
"(objectClass=user)",
{"sAMAccountName"},
"OU=Admins,DC=corp,DC=local",
50,
bridgehead::adws::SearchScope::OneLevel
);
auto objs = client.Query("(objectClass=user)", {"objectGUID", "objectSid"}); for (auto& obj : objs) { if (auto* b = obj.FirstBytes("objectGUID")) std::cout << bridgehead::adws::ParseGuid(b) << '\n'; // {XXXXXXXX-...} if (auto b = obj.FirstBytes("objectSid")) std::cout << bridgehead::adws::ParseSid(*b) << '\n'; // S-1-5-... }
### セキュリティ記述子のデコード```cpp
#include "bridgehead/adws/SecurityDescriptor.hpp"
auto objs = client.Query("(objectClass=user)", {"nTSecurityDescriptor"});
if (auto* raw = objs[0].FirstBytes("nTSecurityDescriptor")) {
auto sd = bridgehead::adws::ParseSecurityDescriptor(*raw);
std::cout << "Owner: " << sd.ownerSid << '\n';
for (auto& ace : sd.dacl.aces)
std::cout << " type=" << (int)ace.type
<< " mask=0x" << std::hex << ace.mask
<< " sid=" << ace.sid << '\n';
}
auto rc = bridgehead::adws::AdwsClient::ResourceClient( "192.168.1.10", "DC01.corp.local", "CORP", "Administrator", "Passw0rd");
// Modify attributes rc.Put("CN=Alice,OU=Users,DC=corp,DC=local", { {"description", {"managed by bridgehead"}}, {"telephoneNumber", {"555-1234"}}, });
// Clear an attribute (both values and bytes empty = delete) rc.Put("CN=Alice,OU=Users,DC=corp,DC=local", { {"telephoneNumber", {}}, });
// Read back auto obj = rc.Get("CN=Alice,OU=Users,DC=corp,DC=local", {"description", "telephoneNumber"});
// Delete object rc.Delete("CN=TempUser,OU=Users,DC=corp,DC=local");
### LDAPの変更タイプ, Add / Replace / Delete
`Put` のデフォルトは `Replace` です(既存の値をすべて上書きします)。多値属性の詳細な制御には `ModifyOperation` を使用します:```cpp
using bridgehead::adws::LdapModification;
using bridgehead::adws::ModifyOperation;
rc.Put("CN=Alice,OU=Users,DC=corp,DC=local", {
// Append a value to an existing multi-valued attribute
LdapModification{"otherTelephone", {"555-9999"}, {}, ModifyOperation::Add},
// Remove one specific value (leave others intact)
LdapModification{"otherTelephone", {"555-0000"}, {}, ModifyOperation::Delete},
// Replace is the default, explicit here for clarity
LdapModification{"description", {"updated"}, {}, ModifyOperation::Replace},
});
// Move to a different OU rc.Move( "CN=Alice,OU=OldOU,DC=corp,DC=local", // current DN "CN=Alice,OU=NewOU,DC=corp,DC=local" // new DN );
// Rename in place (same parent, new CN) rc.Move( "CN=Alice,OU=Users,DC=corp,DC=local", "CN=AliceSmith,OU=Users,DC=corp,DC=local" );
### Write binary attributes
`LdapModification`の`bytes`フィールドにバイナリ値を指定します。それらはワイヤ上で自動的にbase64エンコードされます:```cpp
std::vector<uint8_t> thumbnail = loadFile("photo.jpg");
rc.Put("CN=Alice,OU=Users,DC=corp,DC=local", {
LdapModification{"thumbnailPhoto", {}, {thumbnail}},
});
auto rf = bridgehead::adws::AdwsClient::ResourceFactoryClient( "192.168.1.10", "DC01.corp.local", "CORP", "Administrator", "Passw0rd");
rf.Create( "CN=NewUser,OU=Users,DC=corp,DC=local", "user", {{"sAMAccountName", {"newuser"}}, {"userAccountControl", {"512"}}} );
### 非同期操作```cpp
#include "bridgehead/adws/AdwsClientAsync.hpp"
auto ac = bridgehead::adws::AdwsClientAsync::EnumerationClient(
"192.168.1.10", "DC01.corp.local", "CORP", "Administrator", "Passw0rd");
auto future = ac.QueryAsync("(objectClass=user)", {"sAMAccountName"});
// ... do other work while the query runs ...
auto users = future.get(); // blocks until complete; re-throws any exception
低速なDCでのタイムアウト:```cpp if (future.wait_for(std::chrono::seconds(5)) == std::future_status::timeout) { // query is still running }
すべての操作には非同期バリアントがあります: `QueryAsync`、`EnumerateAsync`、`GetAsync`、`PutAsync`、`DeleteAsync`、`CreateAsync`、`MoveAsync`。
### コネクションプール(高頻度/マルチスレッドワークロード)```cpp
#include "bridgehead/adws/AdwsClientPool.hpp"
// Enumeration pool, Query / Enumerate
bridgehead::adws::AdwsClientPool pool({
.host = "192.168.1.10", .fqdn = "DC01.corp.local",
.domain = "CORP", .username = "Administrator", .password = "Passw0rd",
.maxSize = 4, // up to 4 concurrent authenticated sessions
});
auto users = pool.Query("(objectClass=user)", {"sAMAccountName"});
// Resource pool, Get / Put / Delete
bridgehead::adws::AdwsClientPool resPool({
.host = "192.168.1.10", .fqdn = "DC01.corp.local",
.domain = "CORP", .username = "Administrator", .password = "Passw0rd",
.maxSize = 4,
.endpoint = bridgehead::adws::PoolEndpoint::Resource,
});
auto obj = resPool.Get("CN=Alice,OU=Users,DC=corp,DC=local", {"mail"});
resPool.Put("CN=Alice,OU=Users,DC=corp,DC=local", {{"mail", {"[email protected]"}}});
// ResourceFactory pool, Create
bridgehead::adws::AdwsClientPool rfPool({
.host = "192.168.1.10", .fqdn = "DC01.corp.local",
.domain = "CORP", .username = "Administrator", .password = "Passw0rd",
.endpoint = bridgehead::adws::PoolEndpoint::ResourceFactory,
});
rfPool.Create("CN=NewUser,OU=Users,DC=corp,DC=local", "user",
{{"sAMAccountName", {"newuser"}}});
すべての公開ヘッダーは include/bridgehead/ 以下にあります。完全なAPIドキュメントはDoxygenで生成できます(Build を参照)。
bridgehead::adws::AdwsClientbridgehead::adws::AdwsClientAsyncstd::future ベースの非同期ラッパーです。AdwsClient と同じファクトリメソッドを持ち、各操作は std::future<T> を返します。```cpp
std::future<std::vector> f = ac.QueryAsync(...);
std::future e = ac.EnumerateAsync(filter, attrs, baseDN, callback);
std::future g = ac.GetAsync(...);
std::future h = ac.PutAsync(...);
std::future i = ac.DeleteAsync(...);
std::future j = ac.CreateAsync(...);
std::future k = ac.MoveAsync(...);
複数の接続をまたいだ同時クエリには、`AdwsClientPool` を使用してください。
### `bridgehead::adws::AdwsClientPool`
事前認証済みセッションのスレッドセーフなプールです。コネクションは遅延作成され、呼び出し間で再利用されます。```cpp
pool.IdleCount(); // sessions currently idle
pool.TotalCount(); // idle + checked-out
pool.MaxSize(); // configured maximum pool size
pool.Move(dn, newDn); // Move/rename (Resource pool)
enum class SearchScope { Base, OneLevel, Subtree /default/ };
### `bridgehead::adws::LdapObject` / `LdapAttribute````cpp
struct LdapAttribute {
std::string name;
std::string syntax; // LdapSyntax OID, empty if absent
std::vector<std::string> values; // text values (raw base64 for binary)
std::vector<std::vector<uint8_t>> bytes; // decoded binary; parallel to values
};
struct LdapObject {
std::vector<LdapAttribute> attributes; // all returned attributes
const LdapAttribute* Find(const std::string& name) const; // case-insensitive
std::string FirstValue(const std::string& name) const;
const std::vector<uint8_t>* FirstBytes(const std::string& name) const;
};
std::string ParseGuid(const std::vector<uint8_t>& bytes); // → "{XXXXXXXX-XXXX-...}" std::string ParseSid (const std::vector<uint8_t>& bytes); // → "S-1-5-..."
### `FilterValue` とフィルタビルダーヘルパー
`FilterValue` は、構築時に RFC 4515 §3 のメタ文字(`\`, `*`, `(`, `)`, NUL)をエスケープする型安全なラッパーです。ビルダーヘルパーと併用することで、LDAPインジェクションを構造的に不可能にします:```cpp
// UNSAFE, raw string concatenation, easy to forget escaping
client.Query("(sAMAccountName=" + username + ")", ...);
// SAFE, FilterValue escapes on construction; FilterEq composes the assertion
FilterValue user = username;
client.Query(FilterEq("sAMAccountName", user), ...);
// Compose complex filters
client.Query(
FilterAnd({
FilterEq("objectClass", FilterValue::Raw("user")), // Raw() for safe literals
FilterOr({
FilterEq("sAMAccountName", user),
FilterEq("mail", FilterValue(email)),
}),
FilterNot(FilterPresent("userAccountControl")),
}), {"sAMAccountName", "mail"}
);
EscapeLdapFilter(str) は、フィルタ文字列を手動で構築する必要がある場合の低レベルプリミティブとして依然として利用可能です。
DnValue と DN ビルダーヘルパーFilterValue と同じパターンですが、識別名のRDN値(RFC 4514 §2.4)用です。エスケープするもの:,, +, ", \, <, >, ;, NUL、および先頭/末尾の # とスペース:```cpp
// UNSAFE, comma injection breaks the DN structure
rc.Get("CN=" + username + ",OU=Users,DC=corp,DC=local", attrs);
// SAFE DnValue cn = username; // auto-escaped auto dn = BuildDn({DnAttr("CN", cn), "OU=Users", "DC=corp", "DC=local"}); rc.Get(dn, attrs);
// DnValue::Raw() for values you control auto dn2 = BuildDn({DnAttr("CN", DnValue::Raw("Service Account")), "OU=SvcAccounts", "DC=corp", "DC=local"});
### `bridgehead::adws::SecurityDescriptor````cpp
SecurityDescriptor ParseSecurityDescriptor(const std::vector<uint8_t>& bytes);
struct SecurityDescriptor {
uint16_t control; // SdControl::* flags
std::string ownerSid;
std::string groupSid;
bool hasDacl; Acl dacl;
bool hasSacl; Acl sacl;
};
struct Acl { std::vector<Ace> aces; };
struct Ace {
uint8_t type; // AceType::*
uint8_t flags; // AceFlags::*
uint32_t mask;
std::string sid;
std::string objectType; // GUID string, object ACEs only
std::string inheritedObjectType; // GUID string, object ACEs only
};
定数名前空間: AceType::*, AceFlags::*, SdControl::*.
bridgehead::ConnectionError / AuthenticationError / ProtocolError定義場所: include/bridgehead/Exceptions.hpp (AdwsClient.hpp によって推移的にインクルードされます)。3つすべてが std::runtime_error を継承しています:
| 型 | スローされる状況 |
|---|---|
ConnectionError | TCPレベルの障害: 接続拒否、タイムアウト、I/Oエラー |
AuthenticationError | NTLM/Kerberos ネゴシエーションの失敗 |
ProtocolError | 任意のプロトコル層での不正なサーバーレスポンス |
| try { |
auto client = bridgehead::adws::AdwsClient::EnumerationClient(...);
auto users = client.Query(...);
} catch (const bridgehead::ConnectionError& e) { // unreachable DC, wrong port, timeout } catch (const bridgehead::AuthenticationError& e) { // bad credentials, KDC unreachable } catch (const bridgehead::ProtocolError& e) { // unexpected server response } catch (const bridgehead::adws::SoapFault& e) { // DC returned a SOAP fault (e.g. invalid filter) } // or coarse-grained: // } catch (const std::runtime_error& e) { ... }
### `bridgehead::adws::SoapFault`
DCからの任意の`s:Fault`応答に対して、通常の`std::runtime_error`の代わりにスローされます:```cpp
struct SoapFault : std::runtime_error {
std::string code; // e.g. "Sender"
std::string subcode; // e.g. "InvalidEnumerationContext", empty if absent
std::string reason; // human-readable text
};
bridgehead::adws::LdapModificationPut および Create で使用されます:```cpp
enum class ModifyOperation { Replace /default/, Add, Delete };
struct LdapModification { std::string name; std::vectorstd::string values; // text values std::vector<std::vector<uint8_t>> bytes; // binary values (base64-encoded on the wire) ModifyOperation operation = ModifyOperation::Replace; };
`values` と `bytes` の両方が空の場合、`operation` に関係なく属性はクリア/削除されます。
### `bridgehead::adws::ProtocolLimits`
すべてのファクトリメソッド、`AdwsClientAsync` ファクトリ、および `AdwsClientPool::Config::limits` のオプションの最後のパラメータです。すべてのフィールドには安全なデフォルト値が設定されています。特別な要件がある場合のみ変更してください。```cpp
struct ProtocolLimits {
uint32_t nmfMaxFrameBytes = 64 * 1024 * 1024; // max NMF frame (default 64 MiB)
uint32_t nnsMaxPayloadBytes = 16 * 1024 * 1024; // max NNS packet (default 16 MB)
int tcpKeepaliveIdleSec = 60; // idle seconds before first probe
int tcpKeepaliveIntervalSec = 10; // seconds between probes
int tcpKeepaliveProbeCount = 5; // probes before declaring dead (POSIX only)
};
非常に大きなバイナリ属性(多数のACEを持つ nTSecurityDescriptor や大きな thumbnailPhoto など)を持つオブジェクトを読み取る場合にのみ、nmfMaxFrameBytes / nnsMaxPayloadBytes を引き上げてください。クラウド/NAT環境でアイドル接続が積極的に切断される場合は、キープアライブフィールドを引き下げてください。
名前付きコンストラクターヘルパー(インライン静的ファクトリ):```cpp LdapModification::Replace(name, values) // Replace with text values (default) LdapModification::ReplaceBinary(name, bytes) // Replace with binary values LdapModification::Append(name, values) // Add to multi-valued attribute LdapModification::Remove(name, values={}) // Remove specific values (or all) LdapModification::Clear(name) // Delete the attribute entirely
---
## ビルド
**必要条件:** CMake 3.25+ および C++20対応コンパイラ (MSVC 2022+, GCC 12+, Clang 15+)。```bash
# Configure and build (unit tests only, no live AD needed)
cmake -B build -A x64
cmake --build build --config Release
# Run unit tests
ctest --test-dir build -C Release --output-on-failure
# With integration tests (requires a live Domain Controller)
cmake -B build -A x64 -DBRIDGEHEAD_INTEGRATION_TESTS=ON
cmake --build build --config Release
./build/tests/Release/bridgehead_integration_tests.exe
# With CLI tool (adws_list, browse AD objects from the command line)
cmake -B build -A x64 -DBRIDGEHEAD_BUILD_TOOLS=ON
cmake --build build --config Release --target adws_list
./build/tools/Release/adws_list.exe --host <dc-ip> --fqdn <dc-fqdn> --domain <domain> --user <user>
# Generate API reference docs (requires Doxygen)
cmake --build build --target docs
# or directly:
doxygen Doxyfile
# Output: docs/doxygen/html/index.html
add_subdirectory(bridgehead) target_link_libraries(my_target PRIVATE bridgehead::bridgehead)
### オプションB: インストール済みパッケージ (`find_package`)```bash
cmake --install build --prefix /usr/local # or any install prefix
リリースを作成する: publish.yml GitHubアクションを使用して新しいタグを作成し、プッシュします。このワークフローは手動でトリガーされ、release_type 入力を受け取ります。利用可能な値は次のとおりです:
patch (例: 1.0.10 -> 1.0.11)minor (例: 1.0.10 -> 1.1.0)major (例: 1.0.10 -> 2.0.0)バイナリをビルドする: タグが作成されると、release.yml GitHubアクションが自動的にトリガーされます。以下のバイナリをビルドします:
linux/amd64linux/arm64darwin/amd64darwin/arm64windows/amd64GitHubリリースを作成する: 新しいリリースはワークフローによって自動的に作成されます。完了後、編集して オプションを選択します。
`pugixml`、`ws2_32`、`secur32`(Windows)/ `gssapi_krb5`(Linux/macOS)はすべて推移的に取り込まれます。
---
## プラットフォームのサポート
| プラットフォーム | 認証バックエンド | 状態 |
|----------|-------------|--------|
| Windows | SSPI(`secur32.dll`)、NTLM および Kerberos | **動作確認済み** |
| Linux / macOS | GSSAPI(`libgssapi_krb5`)、SPNEGO / Kerberos | コンパイル済み;統合テスト未実施 |
`AuthPackage::Ntlm` と `AuthPackage::Kerberos` の両方が Windows で動作します。Kerberos はネットワーク上でユーザー名を隠し、本番環境では推奨されます。KDC(ポート 88)に到達できない場合のフォールバックとして NTLM が使用されます。
Linux/macOS では、GSSAPI バックエンドは SPNEGO と Kerberos を使用します。NTLM サポートのために `gss-ntlmssp` プラグインをインストールしてください:```bash
apt install libgss-ntlmssp # Debian / Ubuntu
dnf install gssntlmssp # Fedora / RHEL
プラグインがない場合、サーバーはKerberos認証をネゴシエートします。明示的なユーザー名/パスワードの認証情報は gss_acquire_cred_with_password(MIT Kerberos 1.9+)を使用します。空の文字列を渡すと、デフォルトの認証情報キャッシュ(kinit)が使用されます。GSSAPIパスはクリーンにコンパイルされ、設計上は正しいですが、まだライブのDCに対してエンドツーエンドで検証されていません。そのため、Linux/macOSのサポートはベータ版として扱ってください。
暗号化に関する注意: ポート9389のADWSはNNSレイヤー(NTLMセッションキーまたはKerberos AES-256)で暗号化されており、TLSではありません。これは設計上の仕様であり、DCはこのポートでTLSを提供しません。証明書ベースのサーバー認証が必要な場合は、代わりにLDAPS(ポート636)を利用してください。
cmake/Dependencies.cmakeで設定時に自動的に取得されるため、手動でのインストールは不要です。
OpenSSL、Asio、Boostは不要です。
Linux/macOS上のNTLM には、gss-ntlmssp GSSAPIプラグインが必要です(プラットフォームサポートを参照)。プラグインがない場合、サーバーは代わりにKerberosをネゴシエートします。Windows上のNTLMはSSPIを介してネイティブに動作します。
pugixml DOM では、各SOAP応答が結果を返す前に完全にメモリ内のXMLツリーに解析されます。これは、maxElementsページサイズ(Pullあたりのデフォルト256オブジェクト)によって制限されるため、結果セット全体が一度にメモリに保持されることはありません。大きなページサイズや、多数のACEを持つ大きなバイナリ属性(例:nTSecurityDescriptor)を持つオブジェクトの場合にのみ、メモリが問題になります。SAX/ストリーミングアプローチであればこれを排除できますが、現時点では計画されていません。
すべての仕様は MicrosoftのOpen Specificationsドキュメント から入手できます。
IBM X-ForceとSoaPyプロジェクトに、このプロジェクトに情報を提供するきっかけとなったインスピレーション、研究、および公開された作業について深く感謝します。また、IBM X-Force RedのSoaPyの作成者であるLogan Goins氏の尽力と洞察にも感謝します。
詳細は LICENSE をご覧ください。
| メソッド | エンドポイント | 説明 |
|---|
EnumerationClient(host, fqdn, domain, user, pass [, auth, timeoutMs, opTimeoutMs, limits]) | /Enumeration | ファクトリ、接続、認証 |
ResourceClient(...) | /Resource | Get / Put / Delete / Move のファクトリ |
ResourceFactoryClient(...) | /ResourceFactory | Create のファクトリ |
Query(filter, attrs [, baseDN, maxElems, scope]) | Enumeration | すべての結果を vector に収集 |
Enumerate(filter, attrs, baseDN, callback [, maxElems, scope]) | Enumeration | コールバック経由で結果をストリーム |
Get(dn, attrs) | Resource | 単一オブジェクトの属性を読み取り |
Put(dn, modifications) | Resource | 属性を変更 |
Delete(dn) | Resource | オブジェクトを削除 |
Create(dn, objectClass, attrs) | ResourceFactory | 新しいオブジェクトを作成 |
Move(dn, newDn) | Resource | 既存のオブジェクトを移動または名前変更 |
| オプション | デフォルト | 説明 |
|---|
BRIDGEHEAD_BUILD_TESTS | ON | 単体テストスイートをビルド |
BRIDGEHEAD_INTEGRATION_TESTS | OFF | 統合テストをビルド (ライブDCが必要) |
BRIDGEHEAD_BUILD_TOOLS | OFF | adws_list CLIツールをビルド |
Set as the latest releaseFormulaを更新する: リリースが作成されたら、Homebrew用のFormulaを更新します:
homebrew-tapリポジトリ内の cve-collector.rb ファイルを更新します。homebrew-tapリポジトリの README.md の指示に従ってください。```cmake
find_package(bridgehead REQUIRED)
target_link_libraries(my_target PRIVATE bridgehead::bridgehead)